Merge http-client-branch
authordfuchs
Tue, 19 Jun 2018 16:33:07 +0100
branchhttp-client-branch
changeset 56783 7add69e2fb68
parent 56781 4a32a40ce131 (current diff)
parent 50643 f2d94a0619a2 (diff)
child 56785 62937a37a291
Merge
make/common/Modules.gmk
src/java.base/share/classes/module-info.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/package.html
src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/package.html
src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java
test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ICC_B.jasm
test/jdk/ProblemList.txt
test/jdk/sanity/releaseFile/CheckSource.java
--- a/make/CompileJavaModules.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/CompileJavaModules.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -519,6 +519,7 @@
 # Exclude BreakIterator classes that are just used in compile process to generate
 # data files and shouldn't go in the product
 jdk.localedata_EXCLUDE_FILES += sun/text/resources/ext/BreakIteratorRules_th.java
+jdk.localedata_KEEP_ALL_TRANSLATIONS := true
 ################################################################################
 
 # There is an issue in sjavac that triggers a warning in jdk.jfr that isn't
--- a/make/ZipSource.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/ZipSource.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -68,6 +68,17 @@
 # Only evaluate the creation of src.zip in a sub make call when the symlinked
 # src directory structure has been generated.
 ifeq ($(SRC_GENERATED), true)
+
+  # Rewrite the EXCLUDE_TRANSLATIONS locales as exclude patters for java files
+  TRANSLATIONS_PATTERN := $(addprefix %_, $(addsuffix .java, $(EXCLUDE_TRANSLATIONS)))
+
+  # Add excludes for translations for all modules except jdk.localedata
+  $(foreach s, $(SRC_ZIP_SRCS), \
+    $(if $(filter $(notdir $s), jdk.localedata), , \
+      $(eval BUILD_SRC_ZIP_EXCLUDE_PATTERNS_$(dir $s) := $$(TRANSLATIONS_PATTERN)) \
+    ) \
+  )
+
   $(eval $(call SetupZipArchive, BUILD_SRC_ZIP, \
       SRC := $(dir $(SRC_ZIP_SRCS)), \
       INCLUDES := $(SRC_ZIP_INCLUDES), \
--- a/make/autoconf/configure.ac	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/autoconf/configure.ac	Tue Jun 19 16:33:07 2018 +0100
@@ -232,6 +232,7 @@
 JDKOPT_DETECT_INTREE_EC
 JDKOPT_ENABLE_DISABLE_FAILURE_HANDLER
 JDKOPT_ENABLE_DISABLE_GENERATE_CLASSLIST
+JDKOPT_EXCLUDE_TRANSLATIONS
 
 ###############################################################################
 #
--- a/make/autoconf/hotspot.m4	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/autoconf/hotspot.m4	Tue Jun 19 16:33:07 2018 +0100
@@ -241,10 +241,12 @@
 #
 AC_DEFUN_ONCE([HOTSPOT_ENABLE_DISABLE_CDS],
 [
-  AC_ARG_ENABLE([cds], [AS_HELP_STRING([--enable-cds@<:@=yes/no@:>@],
-      [enable class data sharing feature in non-minimal VM. Default is yes.])])
+  AC_ARG_ENABLE([cds], [AS_HELP_STRING([--enable-cds@<:@=yes/no/auto@:>@],
+      [enable class data sharing feature in non-minimal VM. Default is auto, where cds is enabled if supported on the platform.])])
 
-  if test "x$enable_cds" = "x" || test "x$enable_cds" = "xyes"; then
+  if test "x$enable_cds" = "x" || test "x$enable_cds" = "xauto"; then
+    ENABLE_CDS="true"
+  elif test "x$enable_cds" = "xyes"; then
     ENABLE_CDS="true"
   elif test "x$enable_cds" = "xno"; then
     ENABLE_CDS="false"
@@ -252,6 +254,14 @@
     AC_MSG_ERROR([Invalid value for --enable-cds: $enable_cds])
   fi
 
+  # Disable CDS on AIX.
+  if test "x$OPENJDK_TARGET_OS" = "xaix"; then
+    ENABLE_CDS="false"
+    if test "x$enable_cds" = "xyes"; then
+      AC_MSG_ERROR([CDS is currently not supported on AIX. Remove --enable-cds.])
+    fi
+  fi
+
   AC_SUBST(ENABLE_CDS)
 ])
 
@@ -424,8 +434,21 @@
 
   # All variants but minimal (and custom) get these features
   NON_MINIMAL_FEATURES="$NON_MINIMAL_FEATURES cmsgc g1gc parallelgc serialgc epsilongc jni-check jvmti management nmt services vm-structs"
+
+  AC_MSG_CHECKING([if cds should be enabled])
   if test "x$ENABLE_CDS" = "xtrue"; then
+    if test "x$enable_cds" = "xyes"; then
+      AC_MSG_RESULT([yes, forced])
+    else
+      AC_MSG_RESULT([yes])
+    fi
     NON_MINIMAL_FEATURES="$NON_MINIMAL_FEATURES cds"
+  else
+    if test "x$enable_cds" = "xno"; then
+      AC_MSG_RESULT([no, forced])
+    else
+      AC_MSG_RESULT([no])
+    fi
   fi
 
   # Enable features depending on variant.
--- a/make/autoconf/jdk-options.m4	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/autoconf/jdk-options.m4	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -582,3 +582,25 @@
 
   AC_SUBST(ENABLE_GENERATE_CLASSLIST)
 ])
+
+################################################################################
+#
+# Optionally filter resource translations
+#
+AC_DEFUN([JDKOPT_EXCLUDE_TRANSLATIONS],
+[
+  AC_ARG_WITH([exclude-translations], [AS_HELP_STRING([--with-exclude-translations],
+      [a comma separated list of locales to exclude translations for. Default is
+      to include all translations present in the source.])])
+
+  EXCLUDE_TRANSLATIONS=""
+  AC_MSG_CHECKING([if any translations should be excluded])
+  if test "x$with_exclude_translations" != "x"; then
+    EXCLUDE_TRANSLATIONS="${with_exclude_translations//,/ }"
+    AC_MSG_RESULT([yes: $EXCLUDE_TRANSLATIONS])
+  else
+    AC_MSG_RESULT([no])
+  fi
+
+  AC_SUBST(EXCLUDE_TRANSLATIONS)
+])
--- a/make/autoconf/spec.gmk.in	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/autoconf/spec.gmk.in	Tue Jun 19 16:33:07 2018 +0100
@@ -79,7 +79,7 @@
 OPENJDK_TARGET_CPU_LEGACY:=@OPENJDK_TARGET_CPU_LEGACY@
 OPENJDK_TARGET_CPU_LEGACY_LIB:=@OPENJDK_TARGET_CPU_LEGACY_LIB@
 OPENJDK_TARGET_CPU_OSARCH:=@OPENJDK_TARGET_CPU_OSARCH@
-OPENJDK_TARGET_OS_INCLUDE_SUBIDR:=@OPENJDK_TARGET_OS_INCLUDE_SUBDIR@
+OPENJDK_TARGET_OS_INCLUDE_SUBDIR:=@OPENJDK_TARGET_OS_INCLUDE_SUBDIR@
 
 HOTSPOT_TARGET_OS := @HOTSPOT_TARGET_OS@
 HOTSPOT_TARGET_OS_TYPE := @HOTSPOT_TARGET_OS_TYPE@
@@ -102,7 +102,7 @@
 OPENJDK_BUILD_CPU_BITS:=@OPENJDK_BUILD_CPU_BITS@
 OPENJDK_BUILD_CPU_ENDIAN:=@OPENJDK_BUILD_CPU_ENDIAN@
 
-OPENJDK_BUILD_OS_INCLUDE_SUBIDR:=@OPENJDK_TARGET_OS_INCLUDE_SUBDIR@
+OPENJDK_BUILD_OS_INCLUDE_SUBDIR:=@OPENJDK_TARGET_OS_INCLUDE_SUBDIR@
 
 # Target platform value in ModuleTarget class file attribute.
 OPENJDK_MODULE_TARGET_PLATFORM:=@OPENJDK_MODULE_TARGET_PLATFORM@
@@ -303,6 +303,8 @@
 
 ENABLE_GENERATE_CLASSLIST := @ENABLE_GENERATE_CLASSLIST@
 
+EXCLUDE_TRANSLATIONS := @EXCLUDE_TRANSLATIONS@
+
 # The boot jdk to use. This is overridden in bootcycle-spec.gmk. Make sure to keep
 # it in sync.
 BOOT_JDK:=@BOOT_JDK@
--- a/make/autoconf/toolchain_windows.m4	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/autoconf/toolchain_windows.m4	Tue Jun 19 16:33:07 2018 +0100
@@ -37,6 +37,7 @@
 VS_SDK_INSTALLDIR_2010="Microsoft SDKs/Windows/v7.1"
 VS_VS_PLATFORM_NAME_2010="v100"
 VS_SDK_PLATFORM_NAME_2010="Windows7.1SDK"
+VS_SUPPORTED_2010=false
 
 VS_DESCRIPTION_2012="Microsoft Visual Studio 2012"
 VS_VERSION_INTERNAL_2012=110
@@ -47,6 +48,7 @@
 VS_SDK_INSTALLDIR_2012=
 VS_VS_PLATFORM_NAME_2012="v110"
 VS_SDK_PLATFORM_NAME_2012=
+VS_SUPPORTED_2012=false
 
 VS_DESCRIPTION_2013="Microsoft Visual Studio 2013"
 VS_VERSION_INTERNAL_2013=120
@@ -57,6 +59,7 @@
 VS_SDK_INSTALLDIR_2013=
 VS_VS_PLATFORM_NAME_2013="v120"
 VS_SDK_PLATFORM_NAME_2013=
+VS_SUPPORTED_2013=false
 
 VS_DESCRIPTION_2015="Microsoft Visual Studio 2015"
 VS_VERSION_INTERNAL_2015=140
@@ -70,6 +73,7 @@
 # The vcvars of 2015 breaks if 2017 is also installed. Work around this by
 # explicitly specifying Windows Kit 8.1 to be used.
 VS_ENV_ARGS_2015="8.1"
+VS_SUPPORTED_2015=false
 
 VS_DESCRIPTION_2017="Microsoft Visual Studio 2017"
 VS_VERSION_INTERNAL_2017=141
@@ -82,6 +86,7 @@
 VS_SDK_INSTALLDIR_2017=
 VS_VS_PLATFORM_NAME_2017="v141"
 VS_SDK_PLATFORM_NAME_2017=
+VS_SUPPORTED_2017=true
 
 ################################################################################
 
@@ -266,6 +271,7 @@
     eval MSVCR_NAME="\${VS_MSVCR_${VS_VERSION}}"
     eval MSVCP_NAME="\${VS_MSVCP_${VS_VERSION}}"
     eval USE_UCRT="\${VS_USE_UCRT_${VS_VERSION}}"
+    eval VS_SUPPORTED="\${VS_SUPPORTED_${VS_VERSION}}"
     eval PLATFORM_TOOLSET="\${VS_VS_PLATFORM_NAME_${VS_VERSION}}"
     VS_PATH="$TOOLCHAIN_PATH:$PATH"
 
@@ -312,6 +318,7 @@
       eval MSVCR_NAME="\${VS_MSVCR_${VS_VERSION}}"
       eval MSVCP_NAME="\${VS_MSVCP_${VS_VERSION}}"
       eval USE_UCRT="\${VS_USE_UCRT_${VS_VERSION}}"
+      eval VS_SUPPORTED="\${VS_SUPPORTED_${VS_VERSION}}"
       # The rest of the variables are already evaled while probing
       AC_MSG_NOTICE([Found $VS_DESCRIPTION])
       break
@@ -319,7 +326,7 @@
   done
 
   TOOLCHAIN_DESCRIPTION="$VS_DESCRIPTION"
-  if test "$TOOLCHAIN_VERSION" -gt 2013; then
+  if test "x$VS_SUPPORTED" = "xfalse"; then
     UNSUPPORTED_TOOLCHAIN_VERSION=yes
   fi
 ])
--- a/make/common/JavaCompilation.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/common/JavaCompilation.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -180,6 +180,7 @@
 #   CREATE_API_DIGEST:=Set to true to use a javac plugin to generate a public API
 #        hash which can be used for down stream dependencies to only rebuild
 #        when the API changes. Implicitly used in sjavac.
+#   KEEP_ALL_TRANSLATIONS:=Set to true to skip translation filtering
 SetupJavaCompilation = $(NamedParamsMacroTemplate)
 define SetupJavaCompilationBody
 
@@ -266,6 +267,11 @@
           $$(eval $1_$$(relative_src) := 1) $$(s))))
   endif
 
+  # Filter out any excluded translations
+  ifneq ($$($1_KEEP_ALL_TRANSLATIONS), true)
+    $1_SRCS := $$(call FilterExcludedTranslations, $$($1_SRCS), .java)
+  endif
+
   ifeq ($$(strip $$($1_SRCS)), )
     ifneq ($$($1_FAIL_NO_SRC), false)
       $$(error No source files found for $1)
@@ -290,6 +296,10 @@
     ifneq (,$$($1_EXCLUDE_PATTERN))
       $1_ALL_COPIES := $$(filter-out $$($1_EXCLUDE_PATTERN),$$($1_ALL_COPIES))
     endif
+    # Filter out any excluded translations
+    ifneq ($$($1_KEEP_ALL_TRANSLATIONS), true)
+      $1_ALL_COPIES := $$(call FilterExcludedTranslations, $$($1_ALL_COPIES), .properties)
+    endif
     ifneq (,$$($1_ALL_COPIES))
       # Yep, there are files to be copied!
       $1_ALL_COPY_TARGETS:=
@@ -310,6 +320,10 @@
       ifneq (,$$($1_EXCLUDE_PATTERN))
         $1_ALL_CLEANS := $$(filter-out $$($1_EXCLUDE_PATTERN),$$($1_ALL_CLEANS))
       endif
+      # Filter out any excluded translations
+      ifneq ($$($1_KEEP_ALL_TRANSLATIONS), true)
+        $1_ALL_CLEANS := $$(call FilterExcludedTranslations, $$($1_ALL_CLEANS), .properties)
+      endif
       ifneq (,$$($1_ALL_CLEANS))
         # Yep, there are files to be copied and cleaned!
         $1_ALL_COPY_CLEAN_TARGETS:=
--- a/make/common/MakeBase.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/common/MakeBase.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -1075,6 +1075,22 @@
   )
 
 ################################################################################
+# Given a list of files, filters out locale specific files for translations
+# that should be excluded from this build.
+# $1 - The list of files to filter
+# $2 - The suffix of the files that should be considered (.java or .properties)
+FilterExcludedTranslations = \
+  $(strip $(if $(EXCLUDE_TRANSLATIONS), \
+    $(filter-out \
+        $(foreach suffix, $2, \
+          $(addprefix %_, $(addsuffix $(suffix), $(EXCLUDE_TRANSLATIONS))) \
+        ), \
+        $1 \
+    ), \
+    $1 \
+  ))
+
+################################################################################
 
 # Hook to include the corresponding custom file, if present.
 $(eval $(call IncludeCustomExtension, common/MakeBase.gmk))
--- a/make/common/Modules.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/common/Modules.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -77,6 +77,7 @@
 # should carefully be considered if it should be upgradeable or not.
 UPGRADEABLE_MODULES += \
     java.compiler \
+    jdk.aot \
     jdk.internal.vm.compiler \
     jdk.internal.vm.compiler.management \
     #
--- a/make/common/ZipArchive.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/common/ZipArchive.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -42,6 +42,10 @@
 #   INCLUDE_FILES
 #   EXCLUDES
 #   EXCLUDE_FILES
+#   EXCLUDE_PATTERNS - Patterns with at most one % wildcard matching filenames
+#                      and not directories.
+#   EXCLUDE_PATTERNS_$dir - Exclude patterns just like above but specific to one
+#                           src dir
 #   SUFFIXES
 #   EXTRA_DEPS
 #   ZIP_OPTIONS extra options to pass to zip
@@ -88,11 +92,26 @@
     $1_ALL_SRCS := $$(filter-out $$($1_SRC_EXCLUDES),$$($1_ALL_SRCS))
   endif
   ifneq ($$($1_EXCLUDE_FILES),)
-    # Cannot precompute ZIP_EXCLUDE_FILES as it is dependent on which src root is being
-    # zipped at the moment.
     $1_SRC_EXCLUDE_FILES := $$(addprefix %, $$($1_EXCLUDE_FILES)) $$($1_EXCLUDE_FILES)
     $1_ALL_SRCS := $$(filter-out $$($1_SRC_EXCLUDE_FILES), $$($1_ALL_SRCS))
+    $$(foreach s, $$($1_SRC), \
+      $$(eval $1_ZIP_EXCLUDES_$$s += \
+          $$(addprefix -x$$(SPACE), $$(patsubst $$s/%,%, $$($1_EXCLUDE_FILES))) \
+      ) \
+    )
   endif
+  ifneq ($$($1_EXCLUDE_PATTERNS), )
+    $1_ALL_SRCS := $$(filter-out $$($1_EXCLUDE_PATTERNS), $$($1_ALL_SRCS))
+    $1_ZIP_EXCLUDES += $$(addprefix -x$(SPACE), $$(subst %,\*,$$($1_EXCLUDE_PATTERNS)))
+  endif
+  # Rewrite src dir specific exclude patterns to zip excludes
+  $$(foreach s, $$($1_SRC), \
+    $$(if $$($1_EXCLUDE_PATTERNS_$$s), \
+      $$(eval $1_ZIP_EXCLUDES_$$s += \
+          $$(addprefix -x$$(SPACE), $$(subst %,\*,$$($1_EXCLUDE_PATTERNS_$$s))) \
+      ) \
+    ) \
+  )
 
   # Use a slightly shorter name for logging, but with enough path to identify this zip.
   $1_NAME:=$$(subst $$(OUTPUTDIR)/,,$$($1_ZIP))
@@ -107,9 +126,9 @@
   $$($1_ZIP) : $$($1_ALL_SRCS) $$($1_EXTRA_DEPS)
 	$(MKDIR) -p $$(@D)
 	$(ECHO) Updating $$($1_NAME)
-	$$(foreach i,$$($1_SRC),(cd $$i && $(ZIPEXE) -qru $$($1_ZIP_OPTIONS) $$@ . $$($1_ZIP_INCLUDES) \
-	    $$($1_ZIP_EXCLUDES) -x \*_the.\* \
-	    $$(addprefix -x$(SPACE), $$(patsubst $$i/%,%, $$($1_EXCLUDE_FILES))) \
+	$$(foreach s,$$($1_SRC),(cd $$s && $(ZIPEXE) -qru $$($1_ZIP_OPTIONS) $$@ . \
+	    $$($1_ZIP_INCLUDES) $$($1_ZIP_EXCLUDES) -x \*_the.\* \
+	    $$($1_ZIP_EXCLUDES_$$s) \
 	    || test "$$$$?" = "12" )$$(NEWLINE)) true
 	$(TOUCH) $$@
 
--- a/make/conf/jib-profiles.js	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/conf/jib-profiles.js	Tue Jun 19 16:33:07 2018 +0100
@@ -242,7 +242,8 @@
         dependencies: ["boot_jdk", "gnumake", "jtreg", "jib"],
         default_make_targets: ["product-bundles", "test-bundles"],
         configure_args: concat(["--enable-jtreg-failure-handler"],
-                               versionArgs(input, common))
+            "--with-exclude-translations=de,es,fr,it,ko,pt_BR,sv,ca,tr,cs,sk,ja_JP_A,ja_JP_HA,ja_JP_HI,ja_JP_I",
+            versionArgs(input, common))
     };
     // Extra settings for debug profiles
     common.debug_suffix = "-debug";
--- a/make/gensrc/Gensrc-jdk.localedata.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/gensrc/Gensrc-jdk.localedata.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -38,6 +38,7 @@
 $(eval $(call SetupCompileProperties, COMPILE_PROPERTIES, \
     SRC_DIRS := $(TOPDIR)/src/jdk.localedata/share/classes/sun/util/resources, \
     CLASS := sun.util.resources.LocaleNamesBundle, \
+    KEEP_ALL_TRANSLATIONS := true, \
 ))
 
 # Skip generating zh_HK from zh_TW for this module.
--- a/make/gensrc/GensrcCommonLangtools.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/gensrc/GensrcCommonLangtools.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -66,6 +66,9 @@
   PROPSOURCES := $2 \
       $$(shell $(FIND) $(TOPDIR)/src/$(MODULE)/share/classes -name "*.properties")
 
+  # Filter out any excluded translations
+  PROPSOURCES := $$(call FilterExcludedTranslations, $$(PROPSOURCES), .properties)
+
   # Convert .../src/<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN.properties
   # to .../langtools/gensrc/<module>/com/sun/tools/javac/resources/javac_zh_CN.java
   # Strip away prefix and suffix, leaving for example only:
@@ -105,6 +108,7 @@
 define SetupParseProperties
   # property files to process
   PARSEPROPSOURCES := $$(addprefix $(TOPDIR)/src/$(MODULE)/share/classes/, $2)
+  PARSEPROPSOURCES := $$(call FilterExcludedTranslations, $$(PARSEPROPSOURCES), .properties)
 
   PARSEPROPALLDIRS := $$(patsubst $(TOPDIR)/src/$(MODULE)/share/classes/%, \
       $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/%, \
--- a/make/gensrc/GensrcProperties.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/gensrc/GensrcProperties.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,7 @@
 # EXCLUDE   Exclude files matching this pattern.
 # CLASS   The super class for the generated classes.
 # MODULE_PATH_ROOT   Module path root, defaults to $(TOPDIR)/src.
+# KEEP_ALL_TRANSLATIONS Set to true to skip filtering of excluded translations.
 SetupCompileProperties = $(NamedParamsMacroTemplate)
 define SetupCompilePropertiesBody
   # Set default value unless overridden
@@ -73,10 +74,13 @@
     $1_SRC_FILES := $$(filter-out $$($1_EXCLUDE), $$($1_SRC_FILES))
   endif
 
+  # Filter out any excluded translations
+  ifneq ($$($1_KEEP_ALL_TRANSLATIONS), true)
+    $1_SRC_FILES := $$(call FilterExcludedTranslations, $$($1_SRC_FILES), .properties)
+  endif
+
   # Convert .../src/<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN.properties
   # to .../support/gensrc/<module>/com/sun/tools/javac/resources/javac_zh_CN.java
-  # Strip away prefix and suffix, leaving for example only:
-  # "<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN"
   $1_JAVAS := $$(patsubst $$($1_MODULE_PATH_ROOT)/%, \
       $(SUPPORT_OUTPUTDIR)/gensrc/%, \
       $$(patsubst %.properties, %.java, \
@@ -99,7 +103,7 @@
   $1_TARGET := $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.marker
   $1_CMDLINE_FILE := $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.cmdline
 
-# Now setup the rule for the generation of the resource bundles.
+  # Now setup the rule for the generation of the resource bundles.
   $$($1_TARGET): $$($1_SRC_FILES) $$($1_JAVAS) $(BUILD_TOOLS_JDK)
 	$(MKDIR) -p $$(@D) $$($1_DIRS)
 	$(ECHO) Compiling $$(words $$($1_SRC_FILES)) properties into resource bundles for $(MODULE)
--- a/make/lib/CoreLibraries.gmk	Tue Jun 19 16:08:39 2018 +0100
+++ b/make/lib/CoreLibraries.gmk	Tue Jun 19 16:33:07 2018 +0100
@@ -195,7 +195,6 @@
     OPTIMIZATION := LOW, \
     CFLAGS := $(CFLAGS_JDKLIB), \
     CXXFLAGS := $(CXXFLAGS_JDKLIB), \
-    DISABLED_WARNINGS_gcc := implicit-fallthrough, \
     CFLAGS_unix := -UDEBUG, \
     LDFLAGS := $(LDFLAGS_JDKLIB) $(LDFLAGS_CXX_JDK) \
         $(call SET_SHARED_LIBRARY_ORIGIN), \
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -58,6 +58,28 @@
 
 static float unpack(unsigned value);
 
+short Assembler::SIMD_Size_in_bytes[] = {
+  // T8B, T16B, T4H, T8H, T2S, T4S, T1D, T2D, T1Q
+       8,   16,   8,  16,   8,  16,   8,  16,  16
+};
+
+#ifdef ASSERT
+static void asm_check(const unsigned int *insns, const unsigned int *insns1, size_t len) {
+    bool ok = true;
+    for (unsigned int i = 0; i < len; i++) {
+      if (insns[i] != insns1[i]) {
+        ok = false;
+        printf("Ours:\n");
+        Disassembler::decode((address)&insns1[i], (address)&insns1[i+1]);
+        printf("Theirs:\n");
+        Disassembler::decode((address)&insns[i], (address)&insns[i+1]);
+        printf("\n");
+      }
+    }
+    assert(ok, "Assembler smoke test failed");
+  }
+#endif // ASSERT
+
 void entry(CodeBuffer *cb) {
 
   // {
@@ -1155,31 +1177,24 @@
   };
 // END  Generated code -- do not edit
 
+  asm_check((unsigned int *)entry, insns, sizeof insns / sizeof insns[0]);
+
   {
-    bool ok = true;
-    unsigned int *insns1 = (unsigned int *)entry;
-    for (unsigned int i = 0; i < sizeof insns / sizeof insns[0]; i++) {
-      if (insns[i] != insns1[i]) {
-        ok = false;
-        printf("Ours:\n");
-        Disassembler::decode((address)&insns1[i], (address)&insns1[i+1]);
-        printf("Theirs:\n");
-        Disassembler::decode((address)&insns[i], (address)&insns[i+1]);
-        printf("\n");
-      }
-    }
-    assert(ok, "Assembler smoke test failed");
+    address PC = __ pc();
+    __ ld1(v0, __ T16B, Address(r16));      // No offset
+    __ ld1(v0, __ T8H, __ post(r16, 16));   // Post-index
+    __ ld2(v0, v1, __ T8H, __ post(r24, 16 * 2));   // Post-index
+    __ ld1(v0, __ T16B, __ post(r16, r17)); // Register post-index
+    static const unsigned int vector_insns[] = {
+       0x4c407200, // ld1   {v0.16b}, [x16]
+       0x4cdf7600, // ld1   {v0.8h}, [x16], #16
+       0x4cdf8700, // ld2   {v0.8h, v1.8h}, [x24], #32
+       0x4cd17200, // ld1   {v0.16b}, [x16], x17
+      };
+    asm_check((unsigned int *)PC, vector_insns,
+              sizeof vector_insns / sizeof vector_insns[0]);
   }
 
-#ifndef PRODUCT
-
-  address PC = __ pc();
-  __ ld1(v0, __ T16B, Address(r16)); // No offset
-  __ ld1(v0, __ T16B, __ post(r16, 0)); // Post-index
-  __ ld1(v0, __ T16B, Address(r16, r17)); //
-
-
-#endif // PRODUCT
 #endif // ASSERT
 }
 
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -305,8 +305,11 @@
   Pre(Register reg, int o) : PrePost(reg, o) { }
 };
 class Post : public PrePost {
+  Register _idx;
 public:
-  Post(Register reg, int o) : PrePost(reg, o) { }
+  Post(Register reg, int o) : PrePost(reg, o) { _idx = NULL; }
+  Post(Register reg, Register idx) : PrePost(reg, 0) { _idx = idx; }
+  Register idx_reg() { return _idx; }
 };
 
 namespace ext
@@ -341,7 +344,7 @@
 class Address {
  public:
 
-  enum mode { no_mode, base_plus_offset, pre, post, pcrel,
+  enum mode { no_mode, base_plus_offset, pre, post, post_reg, pcrel,
               base_plus_offset_reg, literal };
 
   // Shift and extend for base reg + reg offset addressing
@@ -413,7 +416,8 @@
   Address(Pre p)
     : _mode(pre), _base(p.reg()), _offset(p.offset()) { }
   Address(Post p)
-    : _mode(post), _base(p.reg()), _offset(p.offset()), _target(0) { }
+    : _mode(p.idx_reg() == NULL ? post : post_reg), _base(p.reg()),
+      _offset(p.offset()), _target(0), _index(p.idx_reg()) { }
   Address(address target, RelocationHolder const& rspec)
     : _mode(literal),
       _rspec(rspec),
@@ -436,7 +440,7 @@
 
   Register base() const {
     guarantee((_mode == base_plus_offset | _mode == base_plus_offset_reg
-               | _mode == post),
+               | _mode == post | _mode == post_reg),
               "wrong mode");
     return _base;
   }
@@ -660,10 +664,14 @@
     return adjust(base, offset, true);
   }
 
-  Address post (Register base, int offset) {
+  Address post(Register base, int offset) {
     return adjust(base, offset, false);
   }
 
+  Address post(Register base, Register idx) {
+    return Address(Post(base, idx));
+  }
+
   Instruction_aarch64* current;
 
   void set_current(Instruction_aarch64* i) { current = i; }
@@ -2032,6 +2040,10 @@
        B, H, S, D, Q
   };
 
+private:
+  static short SIMD_Size_in_bytes[];
+
+public:
 #define INSN(NAME, op)                                            \
   void NAME(FloatRegister Rt, SIMD_RegVariant T, const Address &adr) {   \
     ld_st2((Register)Rt, adr, (int)T & 3, op + ((T==Q) ? 0b10:0b00), 1); \
@@ -2051,7 +2063,8 @@
     f((int)T >> 1, 11, 10), srf(Xn, 5), rf(Vt, 0);
   }
   void ld_st(FloatRegister Vt, SIMD_Arrangement T, Register Xn,
-             int imm, int op1, int op2) {
+             int imm, int op1, int op2, int regs) {
+    guarantee(T <= T1Q && imm == SIMD_Size_in_bytes[T] * regs, "bad offset");
     starti;
     f(0,31), f((int)T & 1, 30);
     f(op1 | 0b100, 29, 21), f(0b11111, 20, 16), f(op2, 15, 12);
@@ -2065,34 +2078,34 @@
     f((int)T >> 1, 11, 10), srf(Xn, 5), rf(Vt, 0);
   }
 
- void ld_st(FloatRegister Vt, SIMD_Arrangement T, Address a, int op1, int op2) {
-   switch (a.getMode()) {
-   case Address::base_plus_offset:
-     guarantee(a.offset() == 0, "no offset allowed here");
-     ld_st(Vt, T, a.base(), op1, op2);
-     break;
-   case Address::post:
-     ld_st(Vt, T, a.base(), a.offset(), op1, op2);
-     break;
-   case Address::base_plus_offset_reg:
-     ld_st(Vt, T, a.base(), a.index(), op1, op2);
-     break;
-   default:
-     ShouldNotReachHere();
-   }
- }
+  void ld_st(FloatRegister Vt, SIMD_Arrangement T, Address a, int op1, int op2, int regs) {
+    switch (a.getMode()) {
+    case Address::base_plus_offset:
+      guarantee(a.offset() == 0, "no offset allowed here");
+      ld_st(Vt, T, a.base(), op1, op2);
+      break;
+    case Address::post:
+      ld_st(Vt, T, a.base(), a.offset(), op1, op2, regs);
+      break;
+    case Address::post_reg:
+      ld_st(Vt, T, a.base(), a.index(), op1, op2);
+      break;
+    default:
+      ShouldNotReachHere();
+    }
+  }
 
  public:
 
-#define INSN1(NAME, op1, op2)                                   \
+#define INSN1(NAME, op1, op2)                                           \
   void NAME(FloatRegister Vt, SIMD_Arrangement T, const Address &a) {   \
-   ld_st(Vt, T, a, op1, op2);                                           \
+    ld_st(Vt, T, a, op1, op2, 1);                                       \
  }
 
 #define INSN2(NAME, op1, op2)                                           \
   void NAME(FloatRegister Vt, FloatRegister Vt2, SIMD_Arrangement T, const Address &a) { \
     assert(Vt->successor() == Vt2, "Registers must be ordered");        \
-    ld_st(Vt, T, a, op1, op2);                                          \
+    ld_st(Vt, T, a, op1, op2, 2);                                       \
   }
 
 #define INSN3(NAME, op1, op2)                                           \
@@ -2100,7 +2113,7 @@
             SIMD_Arrangement T, const Address &a) {                     \
     assert(Vt->successor() == Vt2 && Vt2->successor() == Vt3,           \
            "Registers must be ordered");                                \
-    ld_st(Vt, T, a, op1, op2);                                          \
+    ld_st(Vt, T, a, op1, op2, 3);                                       \
   }
 
 #define INSN4(NAME, op1, op2)                                           \
@@ -2108,7 +2121,7 @@
             FloatRegister Vt4, SIMD_Arrangement T, const Address &a) {  \
     assert(Vt->successor() == Vt2 && Vt2->successor() == Vt3 &&         \
            Vt3->successor() == Vt4, "Registers must be ordered");       \
-    ld_st(Vt, T, a, op1, op2);                                          \
+    ld_st(Vt, T, a, op1, op2, 4);                                       \
   }
 
   INSN1(ld1,  0b001100010, 0b0111);
--- a/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/aarch64/gc/shared/barrierSetAssembler_aarch64.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -33,13 +33,13 @@
 
   // LR is live.  It must be saved around calls.
 
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool oop_not_null = (decorators & OOP_NOT_NULL) != 0;
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
-    if (on_heap) {
+    if (in_heap) {
       if (UseCompressedOops) {
         __ ldrw(dst, src);
         if (oop_not_null) {
@@ -51,7 +51,7 @@
         __ ldr(dst, src);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ ldr(dst, src);
     }
     break;
@@ -71,13 +71,13 @@
 
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    Address dst, Register val, Register tmp1, Register tmp2) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
     val = val == noreg ? zr : val;
-    if (on_heap) {
+    if (in_heap) {
       if (UseCompressedOops) {
         assert(!dst.uses(val), "not enough registers");
         if (val != zr) {
@@ -88,7 +88,7 @@
         __ str(val, dst);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ str(val, dst);
     }
     break;
--- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -2120,7 +2120,7 @@
   tbz(r0, 0, not_weak);    // Test for jweak tag.
 
   // Resolve jweak.
-  access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF, value,
+  access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF, value,
                  Address(value, -JNIHandles::weak_tag_value), tmp, thread);
   verify_oop(value);
   b(done);
@@ -2570,54 +2570,47 @@
 #endif
 
 void MacroAssembler::push_call_clobbered_registers() {
+  int step = 4 * wordSize;
   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
-
+  sub(sp, sp, step);
+  mov(rscratch1, -step);
   // Push v0-v7, v16-v31.
-  for (int i = 30; i >= 0; i -= 2) {
-    if (i <= v7->encoding() || i >= v16->encoding()) {
-        stpd(as_FloatRegister(i), as_FloatRegister(i+1),
-             Address(pre(sp, -2 * wordSize)));
-    }
+  for (int i = 31; i>= 4; i -= 4) {
+    if (i <= v7->encoding() || i >= v16->encoding())
+      st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
+          as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
   }
+  st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
+      as_FloatRegister(3), T1D, Address(sp));
 }
 
 void MacroAssembler::pop_call_clobbered_registers() {
-
-  for (int i = 0; i < 32; i += 2) {
-    if (i <= v7->encoding() || i >= v16->encoding()) {
-      ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
-           Address(post(sp, 2 * wordSize)));
-    }
+  for (int i = 0; i < 32; i += 4) {
+    if (i <= v7->encoding() || i >= v16->encoding())
+      ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
+          as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
   }
 
   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
 }
 
 void MacroAssembler::push_CPU_state(bool save_vectors) {
+  int step = (save_vectors ? 8 : 4) * wordSize;
   push(0x3fffffff, sp);         // integer registers except lr & sp
-
-  if (!save_vectors) {
-    for (int i = 30; i >= 0; i -= 2)
-      stpd(as_FloatRegister(i), as_FloatRegister(i+1),
-           Address(pre(sp, -2 * wordSize)));
-  } else {
-    for (int i = 30; i >= 0; i -= 2)
-      stpq(as_FloatRegister(i), as_FloatRegister(i+1),
-           Address(pre(sp, -4 * wordSize)));
+  mov(rscratch1, -step);
+  sub(sp, sp, step);
+  for (int i = 28; i >= 4; i -= 4) {
+    st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
+        as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
   }
+  st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
 }
 
 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
-  if (!restore_vectors) {
-    for (int i = 0; i < 32; i += 2)
-      ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
-           Address(post(sp, 2 * wordSize)));
-  } else {
-    for (int i = 0; i < 32; i += 2)
-      ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
-           Address(post(sp, 4 * wordSize)));
-  }
-
+  int step = (restore_vectors ? 8 : 4) * wordSize;
+  for (int i = 0; i <= 28; i += 4)
+    ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
+        as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
   pop(0x3fffffff, sp);         // integer registers except lr & sp
 }
 
--- a/src/hotspot/cpu/arm/gc/shared/barrierSetAssembler_arm.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/arm/gc/shared/barrierSetAssembler_arm.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -29,12 +29,12 @@
 
 void BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                   Register dst, Address src, Register tmp1, Register tmp2, Register tmp3) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
-    if (on_heap) {
+    if (in_heap) {
 #ifdef AARCH64
       if (UseCompressedOops) {
         __ ldr_w(dst, src);
@@ -45,7 +45,7 @@
         __ ldr(dst, src);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ ldr(dst, src);
     }
     break;
@@ -57,12 +57,12 @@
 
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    Address obj, Register val, Register tmp1, Register tmp2, Register tmp3, bool is_null) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
-    if (on_heap) {
+    if (in_heap) {
 #ifdef AARCH64
       if (UseCompressedOops) {
         assert(!dst.uses(src), "not enough registers");
@@ -76,7 +76,7 @@
         __ str(val, obj);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ str(val, obj);
     }
     break;
--- a/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -2135,7 +2135,7 @@
   tbz(value, 0, not_weak);      // Test for jweak tag.
 
   // Resolve jweak.
-  access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
+  access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
                  Address(value, -JNIHandles::weak_tag_value), value, tmp1, tmp2, noreg);
   b(done);
   bind(not_weak);
--- a/src/hotspot/cpu/arm/vm_version_arm_32.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/arm/vm_version_arm_32.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,6 +104,18 @@
 extern "C" address check_vfp_fault_instr;
 extern "C" address check_simd_fault_instr;
 
+void VM_Version::early_initialize() {
+
+  // Make sure that _arm_arch is initialized so that any calls to OrderAccess will
+  // use proper dmb instruction
+  get_os_cpu_info();
+
+  _kuser_helper_version = *(int*)KUSER_HELPER_VERSION_ADDR;
+  // armv7 has the ldrexd instruction that can be used to implement cx8
+  // armv5 with linux >= 3.1 can use kernel helper routine
+  _supports_cx8 = (supports_ldrexd() || supports_kuser_cmpxchg64());
+}
+
 void VM_Version::initialize() {
   ResourceMark rm;
 
@@ -216,10 +228,6 @@
     FLAG_SET_DEFAULT(UseVectorizedMismatchIntrinsic, false);
   }
 
-  get_os_cpu_info();
-
-  _kuser_helper_version = *(int*)KUSER_HELPER_VERSION_ADDR;
-
 #ifdef COMPILER2
   // C2 is only supported on v7+ VFP at this time
   if (_arm_arch < 7 || !has_vfp()) {
@@ -227,9 +235,6 @@
   }
 #endif
 
-  // armv7 has the ldrexd instruction that can be used to implement cx8
-  // armv5 with linux >= 3.1 can use kernel helper routine
-  _supports_cx8 = (supports_ldrexd() || supports_kuser_cmpxchg64());
   // ARM doesn't have special instructions for these but ldrex/ldrexd
   // enable shorter instruction sequences that the ones based on cas.
   _supports_atomic_getset4 = supports_ldrex();
--- a/src/hotspot/cpu/ppc/gc/g1/g1BarrierSetAssembler_ppc.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/ppc/gc/g1/g1BarrierSetAssembler_ppc.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -335,7 +335,7 @@
 
   __ beq(CCR0, not_weak);     // Test for jweak tag.
   __ verify_oop(value);
-  g1_write_barrier_pre(masm, IN_ROOT | ON_PHANTOM_OOP_REF,
+  g1_write_barrier_pre(masm, IN_NATIVE | ON_PHANTOM_OOP_REF,
                        noreg, noreg, value,
                        tmp1, tmp2, needs_frame);
   __ bind(not_weak);
--- a/src/hotspot/cpu/ppc/gc/shared/barrierSetAssembler_ppc.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/ppc/gc/shared/barrierSetAssembler_ppc.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -33,16 +33,16 @@
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    Register base, RegisterOrConstant ind_or_offs, Register val,
                                    Register tmp1, Register tmp2, Register tmp3, bool needs_frame) {
-  bool on_heap  = (decorators & IN_HEAP) != 0;
-  bool on_root  = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool not_null = (decorators & OOP_NOT_NULL) != 0;
-  assert(on_heap || on_root, "where?");
+  assert(in_heap || in_native, "where?");
   assert_different_registers(base, val, tmp1, tmp2, R0);
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (UseCompressedOops && on_heap) {
+    if (UseCompressedOops && in_heap) {
       Register co = tmp1;
       if (val == noreg) {
         __ li(co, 0);
@@ -66,16 +66,16 @@
 void BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                   Register base, RegisterOrConstant ind_or_offs, Register dst,
                                   Register tmp1, Register tmp2, bool needs_frame, Label *L_handle_null) {
-  bool on_heap  = (decorators & IN_HEAP) != 0;
-  bool on_root  = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool not_null = (decorators & OOP_NOT_NULL) != 0;
-  assert(on_heap || on_root, "where?");
+  assert(in_heap || in_native, "where?");
   assert_different_registers(ind_or_offs.register_or_noreg(), dst, R0);
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (UseCompressedOops && on_heap) {
+    if (UseCompressedOops && in_heap) {
       if (L_handle_null != NULL) { // Label provided.
         __ lwz(dst, ind_or_offs, base);
         __ cmpwi(CCR0, dst, 0);
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -329,7 +329,7 @@
 inline void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
                                             Register base, RegisterOrConstant ind_or_offs, Register val,
                                             Register tmp1, Register tmp2, Register tmp3, bool needs_frame) {
-  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_ROOT | OOP_NOT_NULL |
+  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_NATIVE | OOP_NOT_NULL |
                          ON_UNKNOWN_OOP_REF)) == 0, "unsupported decorator");
   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
   bool as_raw = (decorators & AS_RAW) != 0;
@@ -348,7 +348,7 @@
 inline void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
                                            Register base, RegisterOrConstant ind_or_offs, Register dst,
                                            Register tmp1, Register tmp2, bool needs_frame, Label *L_handle_null) {
-  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_ROOT | OOP_NOT_NULL |
+  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_NATIVE | OOP_NOT_NULL |
                          ON_PHANTOM_OOP_REF | ON_WEAK_OOP_REF)) == 0, "unsupported decorator");
   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
   decorators = AccessInternal::decorator_fixup(decorators);
--- a/src/hotspot/cpu/s390/gc/g1/g1BarrierSetAssembler_s390.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/s390/gc/g1/g1BarrierSetAssembler_s390.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -403,7 +403,7 @@
   __ z_tmll(tmp1, JNIHandles::weak_tag_mask); // Test for jweak tag.
   __ z_braz(Lnot_weak);
   __ verify_oop(value);
-  DecoratorSet decorators = IN_ROOT | ON_PHANTOM_OOP_REF;
+  DecoratorSet decorators = IN_NATIVE | ON_PHANTOM_OOP_REF;
   g1_write_barrier_pre(masm, decorators, (const Address*)NULL, value, noreg, tmp1, tmp2, true);
   __ bind(Lnot_weak);
   __ verify_oop(value);
--- a/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -37,15 +37,15 @@
 
 void BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                   const Address& addr, Register dst, Register tmp1, Register tmp2, Label *L_handle_null) {
-  bool on_heap  = (decorators & IN_HEAP) != 0;
-  bool on_root  = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool not_null = (decorators & OOP_NOT_NULL) != 0;
-  assert(on_heap || on_root, "where?");
+  assert(in_heap || in_native, "where?");
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (UseCompressedOops && on_heap) {
+    if (UseCompressedOops && in_heap) {
       __ z_llgf(dst, addr);
       if (L_handle_null != NULL) { // Label provided.
         __ compareU32_and_branch(dst, (intptr_t)0, Assembler::bcondEqual, *L_handle_null);
@@ -67,16 +67,16 @@
 
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    const Address& addr, Register val, Register tmp1, Register tmp2, Register tmp3) {
-  bool on_heap  = (decorators & IN_HEAP) != 0;
-  bool on_root  = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool not_null = (decorators & OOP_NOT_NULL) != 0;
-  assert(on_heap || on_root, "where?");
+  assert(in_heap || in_native, "where?");
   assert_different_registers(val, tmp1, tmp2);
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (UseCompressedOops && on_heap) {
+    if (UseCompressedOops && in_heap) {
       if (val == noreg) {
         __ clear_mem(addr, 4);
       } else if (Universe::narrow_oop_mode() == Universe::UnscaledNarrowOop) {
--- a/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -4051,7 +4051,7 @@
 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
                                      const Address& addr, Register val,
                                      Register tmp1, Register tmp2, Register tmp3) {
-  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_ROOT | OOP_NOT_NULL |
+  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_NATIVE | OOP_NOT_NULL |
                          ON_UNKNOWN_OOP_REF)) == 0, "unsupported decorator");
   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
   decorators = AccessInternal::decorator_fixup(decorators);
@@ -4070,7 +4070,7 @@
 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
                                     const Address& addr, Register dst,
                                     Register tmp1, Register tmp2, Label *is_null) {
-  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_ROOT | OOP_NOT_NULL |
+  assert((decorators & ~(AS_RAW | IN_HEAP | IN_HEAP_ARRAY | IN_NATIVE | OOP_NOT_NULL |
                          ON_PHANTOM_OOP_REF | ON_WEAK_OOP_REF)) == 0, "unsupported decorator");
   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
   decorators = AccessInternal::decorator_fixup(decorators);
--- a/src/hotspot/cpu/sparc/gc/shared/barrierSetAssembler_sparc.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/sparc/gc/shared/barrierSetAssembler_sparc.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -32,14 +32,14 @@
 
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    Register val, Address dst, Register tmp) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool oop_not_null = (decorators & OOP_NOT_NULL) != 0;
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (on_heap) {
+    if (in_heap) {
       if (dst.has_disp() && !Assembler::is_simm13(dst.disp())) {
         assert(!dst.has_index(), "not supported yet");
         __ set(dst.disp(), tmp);
@@ -57,7 +57,7 @@
         __ st_ptr(val, dst);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ st_ptr(val, dst);
     }
     break;
@@ -68,14 +68,14 @@
 
 void BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                   Address src, Register dst, Register tmp) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool oop_not_null = (decorators & OOP_NOT_NULL) != 0;
 
   switch (type) {
   case T_ARRAY:
   case T_OBJECT: {
-    if (on_heap) {
+    if (in_heap) {
       if (src.has_disp() && !Assembler::is_simm13(src.disp())) {
         assert(!src.has_index(), "not supported yet");
         __ set(src.disp(), tmp);
@@ -92,7 +92,7 @@
         __ ld_ptr(src, dst);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ ld_ptr(src, dst);
     }
     break;
--- a/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -176,7 +176,7 @@
   delayed()->andcc(value, JNIHandles::weak_tag_mask, G0); // Test for jweak
   brx(Assembler::zero, true, Assembler::pt, not_weak);
   delayed()->nop();
-  access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
+  access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
                  Address(value, -JNIHandles::weak_tag_value), value, tmp);
   verify_oop(value);
   br (Assembler::always, true, Assembler::pt, done);
--- a/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/x86/gc/shared/barrierSetAssembler_x86.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -31,15 +31,15 @@
 
 void BarrierSetAssembler::load_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                   Register dst, Address src, Register tmp1, Register tmp_thread) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool oop_not_null = (decorators & OOP_NOT_NULL) != 0;
   bool atomic = (decorators & MO_RELAXED) != 0;
 
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
-    if (on_heap) {
+    if (in_heap) {
 #ifdef _LP64
       if (UseCompressedOops) {
         __ movl(dst, src);
@@ -54,7 +54,7 @@
         __ movptr(dst, src);
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       __ movptr(dst, src);
     }
     break;
@@ -96,15 +96,15 @@
 
 void BarrierSetAssembler::store_at(MacroAssembler* masm, DecoratorSet decorators, BasicType type,
                                    Address dst, Register val, Register tmp1, Register tmp2) {
-  bool on_heap = (decorators & IN_HEAP) != 0;
-  bool on_root = (decorators & IN_ROOT) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
+  bool in_native = (decorators & IN_NATIVE) != 0;
   bool oop_not_null = (decorators & OOP_NOT_NULL) != 0;
   bool atomic = (decorators & MO_RELAXED) != 0;
 
   switch (type) {
   case T_OBJECT:
   case T_ARRAY: {
-    if (on_heap) {
+    if (in_heap) {
       if (val == noreg) {
         assert(!oop_not_null, "inconsistent access");
 #ifdef _LP64
@@ -133,7 +133,7 @@
         }
       }
     } else {
-      assert(on_root, "why else?");
+      assert(in_native, "why else?");
       assert(val != noreg, "not supported");
       __ movptr(dst, val);
     }
--- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -5266,7 +5266,7 @@
   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
   jcc(Assembler::zero, not_weak);
   // Resolve jweak.
-  access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
+  access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
   verify_oop(value);
   jmp(done);
--- a/src/hotspot/cpu/x86/templateTable_x86.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/cpu/x86/templateTable_x86.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -4013,11 +4013,7 @@
 #endif // _LP64
 
   if (UseTLAB) {
-    __ movptr(rax, Address(thread, in_bytes(JavaThread::tlab_top_offset())));
-    __ lea(rbx, Address(rax, rdx, Address::times_1));
-    __ cmpptr(rbx, Address(thread, in_bytes(JavaThread::tlab_end_offset())));
-    __ jcc(Assembler::above, slow_case);
-    __ movptr(Address(thread, in_bytes(JavaThread::tlab_top_offset())), rbx);
+    __ tlab_allocate(rax, rdx, 0, rcx, rbx, slow_case);
     if (ZeroTLAB) {
       // the fields have been already cleared
       __ jmp(initialize_header);
@@ -4030,28 +4026,7 @@
     //
     // rdx: instance size in bytes
     if (allow_shared_alloc) {
-      ExternalAddress heap_top((address)Universe::heap()->top_addr());
-      ExternalAddress heap_end((address)Universe::heap()->end_addr());
-
-      Label retry;
-      __ bind(retry);
-      __ movptr(rax, heap_top);
-      __ lea(rbx, Address(rax, rdx, Address::times_1));
-      __ cmpptr(rbx, heap_end);
-      __ jcc(Assembler::above, slow_case);
-
-      // Compare rax, with the top addr, and if still equal, store the new
-      // top addr in rbx, at the address of the top addr pointer. Sets ZF if was
-      // equal, and clears it otherwise. Use lock prefix for atomicity on MPs.
-      //
-      // rax,: object begin
-      // rbx,: object end
-      // rdx: instance size in bytes
-      __ locked_cmpxchgptr(rbx, heap_top);
-
-      // if someone beat us on the allocation, try again, otherwise continue
-      __ jcc(Assembler::notEqual, retry);
-
+      __ eden_allocate(rax, rdx, 0, rbx, slow_case);
       __ incr_allocated_bytes(thread, rdx, 0);
     }
   }
--- a/src/hotspot/os_cpu/linux_arm/vm_version_linux_arm_32.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/os_cpu/linux_arm/vm_version_linux_arm_32.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,8 +46,3 @@
   }
 }
 
-// Make sure that _arm_arch is initialized so that any calls to OrderAccess will
-// use proper dmb instruction
-void VM_Version::early_initialize() {
-  get_os_cpu_info();
-}
--- a/src/hotspot/share/c1/c1_LIRGenerator.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/c1/c1_LIRGenerator.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -3245,7 +3245,7 @@
     int freq_log = Tier23InlineeNotifyFreqLog;
     double scale;
     if (_method->has_option_value("CompileThresholdScaling", scale)) {
-      freq_log = Arguments::scaled_freq_log(freq_log, scale);
+      freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
     }
     increment_event_counter_impl(info, x->inlinee(), LIR_OprFact::intConst(InvocationCounter::count_increment), right_n_bits(freq_log), InvocationEntryBci, false, true);
   }
@@ -3279,7 +3279,7 @@
   // Increment the appropriate invocation/backedge counter and notify the runtime.
   double scale;
   if (_method->has_option_value("CompileThresholdScaling", scale)) {
-    freq_log = Arguments::scaled_freq_log(freq_log, scale);
+    freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
   }
   increment_event_counter_impl(info, info->scope()->method(), step, right_n_bits(freq_log), bci, backedge, true);
 }
--- a/src/hotspot/share/classfile/classFileParser.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/classFileParser.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -955,7 +955,9 @@
 
       if (!interf->is_interface()) {
         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
-                   "Implementing class");
+                  err_msg("Class %s can not implement %s, because it is not an interface",
+                          _class_name->as_klass_external_name(),
+                          interf->class_loader_and_module_name()));
       }
 
       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
@@ -4509,7 +4511,7 @@
           vmSymbols::java_lang_IllegalAccessError(),
           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
           this_klass->external_name(),
-          this_klass->class_loader_data()->loader_name(),
+          this_klass->class_loader_data()->loader_name_and_id(),
           super->external_name());
         return;
       }
--- a/src/hotspot/share/classfile/classListParser.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/classListParser.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -274,8 +274,8 @@
 // This function is used for loading classes for customized class loaders
 // during archive dumping.
 InstanceKlass* ClassListParser::load_class_from_source(Symbol* class_name, TRAPS) {
-#if !(defined(_LP64) && (defined(LINUX)|| defined(SOLARIS) || defined(AIX)))
-  // The only supported platforms are: (1) Linux/64-bit; (2) Solaris/64-bit; (3) AIX/64-bit
+#if !(defined(_LP64) && (defined(LINUX)|| defined(SOLARIS)))
+  // The only supported platforms are: (1) Linux/64-bit and (2) Solaris/64-bit
   //
   // This #if condition should be in sync with the areCustomLoadersSupportedForCDS
   // method in test/lib/jdk/test/lib/Platform.java.
--- a/src/hotspot/share/classfile/classLoaderData.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -105,22 +105,41 @@
   }
 }
 
-// JFR and logging support so that the name and klass are available after the
-// class_loader oop is no longer alive, during unloading.
+// Obtain and set the class loader's name within the ClassLoaderData so
+// it will be available for error messages, logging, JFR, etc.  The name
+// and klass are available after the class_loader oop is no longer alive,
+// during unloading.
 void ClassLoaderData::initialize_name_and_klass(Handle class_loader) {
+  Thread* THREAD = Thread::current();
+  ResourceMark rm(THREAD);
   _class_loader_klass = class_loader->klass();
-  oop class_loader_name = java_lang_ClassLoader::name(class_loader());
-  if (class_loader_name != NULL) {
-    Thread* THREAD = Thread::current();
-    ResourceMark rm(THREAD);
-    const char* class_loader_instance_name =
-      java_lang_String::as_utf8_string(class_loader_name);
 
-    if (class_loader_instance_name != NULL && class_loader_instance_name[0] != '\0') {
+  // Obtain the class loader's name.  If the class loader's name was not
+  // explicitly set during construction, the CLD's _name field will be null.
+  oop cl_name = java_lang_ClassLoader::name(class_loader());
+  if (cl_name != NULL) {
+    const char* cl_instance_name = java_lang_String::as_utf8_string(cl_name);
+
+    if (cl_instance_name != NULL && cl_instance_name[0] != '\0') {
       // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
-      _class_loader_name = SymbolTable::new_symbol(class_loader_instance_name, CATCH);
+      _name = SymbolTable::new_symbol(cl_instance_name, CATCH);
     }
   }
+
+  // Obtain the class loader's name and identity hash.  If the class loader's
+  // name was not explicitly set during construction, the class loader's name and id
+  // will be set to the qualified class name of the class loader along with its
+  // identity hash.
+  // If for some reason the ClassLoader's constructor has not been run, instead of
+  // leaving the _name_and_id field null, fall back to the external qualified class
+  // name.  Thus CLD's _name_and_id field should never have a null value.
+  oop cl_name_and_id = java_lang_ClassLoader::nameAndId(class_loader());
+  const char* cl_instance_name_and_id =
+                  (cl_name_and_id == NULL) ? _class_loader_klass->external_name() :
+                                             java_lang_String::as_utf8_string(cl_name_and_id);
+  assert(cl_instance_name_and_id != NULL && cl_instance_name_and_id[0] != '\0', "class loader has no name and id");
+  // Can't throw InternalError and SymbolTable doesn't throw OOM anymore.
+  _name_and_id = SymbolTable::new_symbol(cl_instance_name_and_id, CATCH);
 }
 
 ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous) :
@@ -134,7 +153,7 @@
   _claimed(0), _modified_oops(true), _accumulated_modified_oops(false),
   _jmethod_ids(NULL), _handles(), _deallocate_list(NULL),
   _next(NULL),
-  _class_loader_klass(NULL), _class_loader_name(NULL),
+  _class_loader_klass(NULL), _name(NULL), _name_and_id(NULL),
   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true,
                             Monitor::_safepoint_check_never)) {
 
@@ -815,7 +834,7 @@
     assert(_handles.owner_of(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
     // This root is not walked in safepoints, and hence requires an appropriate
     // decorator that e.g. maintains the SATB invariant in SATB collectors.
-    RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
+    NativeAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
   }
 }
 
@@ -911,29 +930,40 @@
   return ClassLoaderDataGraph::add(loader, true);
 }
 
+// Caller needs ResourceMark
+// If the class loader's _name has not been explicitly set, the class loader's
+// qualified class name is returned.
 const char* ClassLoaderData::loader_name() const {
-  if (is_unloading()) {
-    if (_class_loader_klass == NULL) {
-      return "<bootloader>";
-    } else if (_class_loader_name != NULL) {
-      return _class_loader_name->as_C_string();
-    } else {
-      return _class_loader_klass->name()->as_C_string();
-    }
+   if (_class_loader_klass == NULL) {
+     return BOOTSTRAP_LOADER_NAME;
+   } else if (_name != NULL) {
+     return _name->as_C_string();
+   } else {
+     return _class_loader_klass->external_name();
+   }
+}
+
+// Caller needs ResourceMark
+// Format of the _name_and_id is as follows:
+//   If the defining loader has a name explicitly set then '<loader-name>' @<id>
+//   If the defining loader has no name then <qualified-class-name> @<id>
+//   If built-in loader, then omit '@<id>' as there is only one instance.
+const char* ClassLoaderData::loader_name_and_id() const {
+  if (_class_loader_klass == NULL) {
+    return "'" BOOTSTRAP_LOADER_NAME "'";
   } else {
-    // Handles null class loader
-    return SystemDictionary::loader_name(class_loader());
+    assert(_name_and_id != NULL, "encountered a class loader null name and id");
+    return _name_and_id->as_C_string();
   }
 }
 
-
 void ClassLoaderData::print_value_on(outputStream* out) const {
   if (!is_unloading() && class_loader() != NULL) {
     out->print("loader data: " INTPTR_FORMAT " for instance ", p2i(this));
-    class_loader()->print_value_on(out);  // includes loader_name() and address of class loader instance
+    class_loader()->print_value_on(out);  // includes loader_name_and_id() and address of class loader instance
   } else {
-    // loader data: 0xsomeaddr of <bootloader>
-    out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name());
+    // loader data: 0xsomeaddr of 'bootstrap'
+    out->print("loader data: " INTPTR_FORMAT " of %s", p2i(this), loader_name_and_id());
   }
   if (is_anonymous()) {
     out->print(" anonymous");
@@ -943,7 +973,7 @@
 #ifndef PRODUCT
 void ClassLoaderData::print_on(outputStream* out) const {
   out->print("ClassLoaderData CLD: " PTR_FORMAT ", loader: " PTR_FORMAT ", loader_klass: %s {",
-              p2i(this), p2i(_class_loader.ptr_raw()), loader_name());
+              p2i(this), p2i(_class_loader.ptr_raw()), loader_name_and_id());
   if (is_anonymous()) out->print(" anonymous");
   if (claimed()) out->print(" claimed");
   if (is_unloading()) out->print(" unloading");
@@ -1237,7 +1267,7 @@
   FOR_ALL_DICTIONARY(cld) {
     ResourceMark rm;
     stringStream tempst;
-    tempst.print("System Dictionary for %s", cld->loader_name());
+    tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
     cld->dictionary()->print_table_statistics(st, tempst.as_string());
   }
 }
--- a/src/hotspot/share/classfile/classLoaderData.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -37,6 +37,9 @@
 #include "jfr/support/jfrTraceIdExtension.hpp"
 #endif
 
+// external name (synthetic) for the primordial "bootstrap" class loader instance
+#define BOOTSTRAP_LOADER_NAME "bootstrap"
+#define BOOTSTRAP_LOADER_NAME_LEN 9
 
 //
 // A class loader represents a linkset. Conceptually, a linkset identifies
@@ -258,9 +261,9 @@
   // Support for walking class loader data objects
   ClassLoaderData* _next; /// Next loader_datas created
 
-  // JFR support
   Klass*  _class_loader_klass;
-  Symbol* _class_loader_name;
+  Symbol* _name;
+  Symbol* _name_and_id;
   JFR_ONLY(DEFINE_TRACE_ID_FIELD;)
 
   void set_next(ClassLoaderData* next) { _next = next; }
@@ -362,8 +365,6 @@
 
   void initialize_holder(Handle holder);
 
-  inline unsigned int identity_hash() const { return (unsigned int)(((intptr_t)this) >> 3); }
-
   void oops_do(OopClosure* f, bool must_claim, bool clear_modified_oops = false);
 
   void classes_do(KlassClosure* klass_closure);
@@ -377,7 +378,6 @@
   void print_value()                               { print_value_on(tty); }
   void print_value_on(outputStream* out) const;
   void verify();
-  const char* loader_name() const;
 
   OopHandle add_handle(Handle h);
   void remove_handle(OopHandle h);
@@ -400,15 +400,20 @@
   static ClassLoaderData* class_loader_data_or_null(oop loader);
   static ClassLoaderData* anonymous_class_loader_data(Handle loader);
 
-  // Returns Klass* of associated class loader, or NULL if associated loader is <bootstrap>.
+  // Returns Klass* of associated class loader, or NULL if associated loader is 'bootstrap'.
   // Also works if unloading.
   Klass* class_loader_klass() const { return _class_loader_klass; }
 
-  // Returns Name of associated class loader.
-  // Returns NULL if associated class loader is <bootstrap> or if no name has been set for
-  //   this loader.
-  // Also works if unloading.
-  Symbol* class_loader_name() const { return _class_loader_name; }
+  // Returns the class loader's explict name as specified during
+  // construction or the class loader's qualified class name.
+  // Works during unloading.
+  const char* loader_name() const;
+  // Returns the explicitly specified class loader name or NULL.
+  Symbol* name() const { return _name; }
+
+  // Obtain the class loader's _name_and_id, works during unloading.
+  const char* loader_name_and_id() const;
+  Symbol* name_and_id() const { return _name_and_id; }
 
   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
 };
--- a/src/hotspot/share/classfile/classLoaderHierarchyDCmd.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderHierarchyDCmd.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -157,7 +157,7 @@
 
     // Retrieve information.
     const Klass* const loader_klass = _cld->class_loader_klass();
-    const Symbol* const loader_name = _cld->class_loader_name();
+    const Symbol* const loader_name = _cld->name();
 
     branchtracker.print(st);
 
--- a/src/hotspot/share/classfile/dictionary.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/dictionary.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -641,6 +641,6 @@
 
   ResourceMark rm;
   stringStream tempst;
-  tempst.print("System Dictionary for %s", cld->loader_name());
+  tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
   verify_table<DictionaryEntry>(tempst.as_string());
 }
--- a/src/hotspot/share/classfile/javaClasses.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/javaClasses.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -3993,6 +3993,7 @@
 int  java_lang_ClassLoader::_loader_data_offset = -1;
 int  java_lang_ClassLoader::parallelCapable_offset = -1;
 int  java_lang_ClassLoader::name_offset = -1;
+int  java_lang_ClassLoader::nameAndId_offset = -1;
 int  java_lang_ClassLoader::unnamedModule_offset = -1;
 
 ClassLoaderData* java_lang_ClassLoader::loader_data(oop loader) {
@@ -4008,6 +4009,7 @@
 #define CLASSLOADER_FIELDS_DO(macro) \
   macro(parallelCapable_offset, k1, "parallelLockMap",      concurrenthashmap_signature, false); \
   macro(name_offset,            k1, vmSymbols::name_name(), string_signature, false); \
+  macro(nameAndId_offset,       k1, "nameAndId",            string_signature, false); \
   macro(unnamedModule_offset,   k1, "unnamedModule",        module_signature, false); \
   macro(parent_offset,          k1, "parent",               classloader_signature, false)
 
@@ -4033,11 +4035,24 @@
   return loader->obj_field(parent_offset);
 }
 
+// Returns the name field of this class loader.  If the name field has not
+// been set, null will be returned.
 oop java_lang_ClassLoader::name(oop loader) {
   assert(is_instance(loader), "loader must be oop");
   return loader->obj_field(name_offset);
 }
 
+// Returns the nameAndId field of this class loader. The format is
+// as follows:
+//   If the defining loader has a name explicitly set then '<loader-name>' @<id>
+//   If the defining loader has no name then <qualified-class-name> @<id>
+//   If built-in loader, then omit '@<id>' as there is only one instance.
+// Use ClassLoader::loader_name_id() to obtain this String as a char*.
+oop java_lang_ClassLoader::nameAndId(oop loader) {
+  assert(is_instance(loader), "loader must be oop");
+  return loader->obj_field(nameAndId_offset);
+}
+
 bool java_lang_ClassLoader::isAncestor(oop loader, oop cl) {
   assert(is_instance(loader), "loader must be oop");
   assert(cl == NULL || is_instance(cl), "cl argument must be oop");
@@ -4111,39 +4126,28 @@
 
 // Caller needs ResourceMark.
 const char* java_lang_ClassLoader::describe_external(const oop loader) {
+  ClassLoaderData *cld = ClassLoaderData::class_loader_data(loader);
+  const char* name = cld->loader_name_and_id();
+
+  // bootstrap loader
   if (loader == NULL) {
-    return "<bootstrap>";
+    return name;
   }
 
   bool well_known_loader = SystemDictionary::is_system_class_loader(loader) ||
                            SystemDictionary::is_platform_class_loader(loader);
 
-  const char* name = NULL;
-  oop nameOop = java_lang_ClassLoader::name(loader);
-  if (nameOop != NULL) {
-    name = java_lang_String::as_utf8_string(nameOop);
-  }
-  if (name == NULL) {
-    // Use placeholder for missing name to have fixed message format.
-    name = "<unnamed>";
-  }
-
   stringStream ss;
-  ss.print("\"%s\" (instance of %s", name, loader->klass()->external_name());
+  ss.print("%s (instance of %s", name, loader->klass()->external_name());
   if (!well_known_loader) {
-    const char* parentName = NULL;
     oop pl = java_lang_ClassLoader::parent(loader);
+    ClassLoaderData *pl_cld = ClassLoaderData::class_loader_data(pl);
+    const char* parentName = pl_cld->loader_name_and_id();
     if (pl != NULL) {
-      oop parentNameOop = java_lang_ClassLoader::name(pl);
-      if (parentNameOop != NULL) {
-        parentName = java_lang_String::as_utf8_string(parentNameOop);
-      }
-      if (parentName == NULL) {
-        parentName = "<unnamed>";
-      }
-      ss.print(", child of \"%s\" %s", parentName, pl->klass()->external_name());
+      ss.print(", child of %s %s", parentName, pl->klass()->external_name());
     } else {
-      ss.print(", child of <bootstrap>");
+      // bootstrap loader
+      ss.print(", child of %s", parentName);
     }
   }
   ss.print(")");
--- a/src/hotspot/share/classfile/javaClasses.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/javaClasses.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1272,6 +1272,7 @@
   static int parent_offset;
   static int parallelCapable_offset;
   static int name_offset;
+  static int nameAndId_offset;
   static int unnamedModule_offset;
 
  public:
@@ -1283,6 +1284,7 @@
 
   static oop parent(oop loader);
   static oop name(oop loader);
+  static oop nameAndId(oop loader);
   static bool isAncestor(oop loader, oop cl);
 
   // Support for parallelCapable field
--- a/src/hotspot/share/classfile/loaderConstraints.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/loaderConstraints.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -108,7 +108,7 @@
                      probe->name()->as_C_string());
           for (int i = 0; i < probe->num_loaders(); i++) {
             lt.print("    [%d]: %s", i,
-                          probe->loader_data(i)->loader_name());
+                          probe->loader_data(i)->loader_name_and_id());
           }
         }
       }
@@ -119,7 +119,7 @@
           if (lt.is_enabled()) {
             ResourceMark rm;
             lt.print("purging loader %s from constraint for name %s",
-                     probe->loader_data(n)->loader_name(),
+                     probe->loader_data(n)->loader_name_and_id(),
                      probe->name()->as_C_string()
                      );
           }
@@ -135,7 +135,7 @@
             lt.print("new loader list:");
             for (int i = 0; i < probe->num_loaders(); i++) {
               lt.print("    [%d]: %s", i,
-                            probe->loader_data(i)->loader_name());
+                            probe->loader_data(i)->loader_name_and_id());
             }
           }
 
@@ -177,8 +177,8 @@
     lt.print("Failed to add constraint for name: %s, loader[0]: %s,"
                 " loader[1]: %s, Reason: %s",
                   class_name->as_C_string(),
-                  SystemDictionary::loader_name(class_loader1()),
-                  SystemDictionary::loader_name(class_loader2()),
+                  ClassLoaderData::class_loader_data(class_loader1())->loader_name_and_id(),
+                  ClassLoaderData::class_loader_data(class_loader2())->loader_name_and_id(),
                   reason);
   }
 }
@@ -247,8 +247,8 @@
       lt.print("adding new constraint for name: %s, loader[0]: %s,"
                     " loader[1]: %s",
                     class_name->as_C_string(),
-                    SystemDictionary::loader_name(class_loader1()),
-                    SystemDictionary::loader_name(class_loader2())
+                    ClassLoaderData::class_loader_data(class_loader1())->loader_name_and_id(),
+                    ClassLoaderData::class_loader_data(class_loader2())->loader_name_and_id()
                     );
     }
   } else if (*pp1 == *pp2) {
@@ -260,7 +260,7 @@
         lt.print("setting class object in existing constraint for"
                       " name: %s and loader %s",
                       class_name->as_C_string(),
-                      SystemDictionary::loader_name(class_loader1())
+                      ClassLoaderData::class_loader_data(class_loader1())->loader_name_and_id()
                       );
       }
     } else {
@@ -291,7 +291,7 @@
       lt.print("constraint check failed for name %s, loader %s: "
                  "the presented class object differs from that stored",
                  name->as_C_string(),
-                 SystemDictionary::loader_name(loader()));
+                 ClassLoaderData::class_loader_data(loader())->loader_name_and_id());
     }
     return false;
   } else {
@@ -302,7 +302,7 @@
         lt.print("updating constraint for name %s, loader %s, "
                    "by setting class object",
                    name->as_C_string(),
-                   SystemDictionary::loader_name(loader()));
+                   ClassLoaderData::class_loader_data(loader())->loader_name_and_id());
       }
     }
     return true;
@@ -353,7 +353,7 @@
     lt.print("extending constraint for name %s by adding loader[%d]: %s %s",
                p->name()->as_C_string(),
                num,
-               SystemDictionary::loader_name(loader()),
+               ClassLoaderData::class_loader_data(loader())->loader_name_and_id(),
                (p->klass() == NULL ? " and setting class object" : "")
                );
   }
@@ -396,7 +396,7 @@
 
     for (int i = 0; i < p1->num_loaders(); i++) {
       lt.print("    [%d]: %s", i,
-                    p1->loader_data(i)->loader_name());
+                    p1->loader_data(i)->loader_name_and_id());
     }
     if (p1->klass() == NULL) {
       lt.print("... and setting class object");
--- a/src/hotspot/share/classfile/moduleEntry.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/moduleEntry.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -260,7 +260,7 @@
   ResourceMark rm;
   guarantee(java_lang_Module::is_instance(module),
             "The unnamed module for ClassLoader %s, is null or not an instance of java.lang.Module. The class loader has not been initialized correctly.",
-            cld->loader_name());
+            cld->loader_name_and_id());
 
   ModuleEntry* unnamed_module = new_unnamed_module_entry(Handle(Thread::current(), module), cld);
 
@@ -522,7 +522,7 @@
                p2i(this),
                name() == NULL ? UNNAMED_MODULE : name()->as_C_string(),
                p2i(module()),
-               loader_data()->loader_name(),
+               loader_data()->loader_name_and_id(),
                version() != NULL ? version()->as_C_string() : "NULL",
                location() != NULL ? location()->as_C_string() : "NULL",
                BOOL_TO_STR(!can_read_all_unnamed()), p2i(next()));
--- a/src/hotspot/share/classfile/modules.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/modules.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -312,6 +312,10 @@
               "Class loader is an invalid delegating class loader");
   }
   Handle h_loader = Handle(THREAD, loader);
+  // define_module can be called during start-up, before the class loader's ClassLoaderData
+  // has been created.  SystemDictionary::register_loader ensures creation, if needed.
+  ClassLoaderData* loader_data = SystemDictionary::register_loader(h_loader);
+  assert(loader_data != NULL, "class loader data shouldn't be null");
 
   // Check that the list of packages has no duplicates and that the
   // packages are syntactically ok.
@@ -329,7 +333,7 @@
         !SystemDictionary::is_platform_class_loader(h_loader()) &&
         (strncmp(package_name, JAVAPKG, JAVAPKG_LEN) == 0 &&
           (package_name[JAVAPKG_LEN] == '/' || package_name[JAVAPKG_LEN] == '\0'))) {
-      const char* class_loader_name = SystemDictionary::loader_name(h_loader());
+      const char* class_loader_name = loader_data->loader_name_and_id();
       size_t pkg_len = strlen(package_name);
       char* pkg_name = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, pkg_len);
       strncpy(pkg_name, package_name, pkg_len);
@@ -373,9 +377,6 @@
     }
   }
 
-  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(h_loader());
-  assert(loader_data != NULL, "class loader data shouldn't be null");
-
   PackageEntryTable* package_table = NULL;
   PackageEntry* existing_pkg = NULL;
   {
--- a/src/hotspot/share/classfile/stringTable.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/stringTable.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -456,7 +456,7 @@
   log_trace(stringtable)("Started to grow");
   {
     TraceTime timer("Grow", TRACETIME_LOG(Debug, stringtable, perf));
-    while (gt.doTask(jt)) {
+    while (gt.do_task(jt)) {
       gt.pause(jt);
       {
         ThreadBlockInVM tbivm(jt);
@@ -502,7 +502,7 @@
   bool interrupted = false;
   {
     TraceTime timer("Clean", TRACETIME_LOG(Debug, stringtable, perf));
-    while(bdt.doTask(jt, stdc, stdd)) {
+    while(bdt.do_task(jt, stdc, stdd)) {
       bdt.pause(jt);
       {
         ThreadBlockInVM tbivm(jt);
--- a/src/hotspot/share/classfile/systemDictionary.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/systemDictionary.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -3012,18 +3012,6 @@
   NOT_PRODUCT(SystemDictionary::verify());
 }
 
-// caller needs ResourceMark
-const char* SystemDictionary::loader_name(const oop loader) {
-  return ((loader) == NULL ? "<bootloader>" :
-          InstanceKlass::cast((loader)->klass())->name()->as_C_string());
-}
-
-// caller needs ResourceMark
-const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
-  return (loader_data->class_loader() == NULL ? "<bootloader>" :
-          SystemDictionary::loader_name(loader_data->class_loader()));
-}
-
 void SystemDictionary::initialize_oop_storage() {
   _vm_weak_oop_storage =
     new OopStorage("VM Weak Oop Handles",
--- a/src/hotspot/share/classfile/systemDictionary.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/classfile/systemDictionary.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -570,10 +570,6 @@
                                                      Handle *method_type_result,
                                                      TRAPS);
 
-  // Utility for printing loader "name" as part of tracing constraints
-  static const char* loader_name(const oop loader);
-  static const char* loader_name(const ClassLoaderData* loader_data);
-
   // Record the error when the first attempt to resolve a reference from a constant
   // pool entry to a class fails.
   static void add_resolution_error(const constantPoolHandle& pool, int which, Symbol* error,
--- a/src/hotspot/share/compiler/compilerDefinitions.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/compiler/compilerDefinitions.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
 #include "runtime/globals.hpp"
 #include "runtime/globals_extension.hpp"
 #include "compiler/compilerDefinitions.hpp"
+#include "gc/shared/gcConfig.hpp"
+#include "utilities/defaultStream.hpp"
 
 const char* compilertype2name_tab[compiler_number_of_types] = {
   "",
@@ -60,6 +62,55 @@
 CompMode  Compilation_mode             = CompMode_none;
 #endif
 
+// Returns threshold scaled with CompileThresholdScaling
+intx CompilerConfig::scaled_compile_threshold(intx threshold) {
+  return scaled_compile_threshold(threshold, CompileThresholdScaling);
+}
+
+// Returns freq_log scaled with CompileThresholdScaling
+intx CompilerConfig::scaled_freq_log(intx freq_log) {
+  return scaled_freq_log(freq_log, CompileThresholdScaling);
+}
+
+// Returns threshold scaled with the value of scale.
+// If scale < 0.0, threshold is returned without scaling.
+intx CompilerConfig::scaled_compile_threshold(intx threshold, double scale) {
+  if (scale == 1.0 || scale < 0.0) {
+    return threshold;
+  } else {
+    return (intx)(threshold * scale);
+  }
+}
+
+// Returns freq_log scaled with the value of scale.
+// Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
+// If scale < 0.0, freq_log is returned without scaling.
+intx CompilerConfig::scaled_freq_log(intx freq_log, double scale) {
+  // Check if scaling is necessary or if negative value was specified.
+  if (scale == 1.0 || scale < 0.0) {
+    return freq_log;
+  }
+  // Check values to avoid calculating log2 of 0.
+  if (scale == 0.0 || freq_log == 0) {
+    return 0;
+  }
+  // Determine the maximum notification frequency value currently supported.
+  // The largest mask value that the interpreter/C1 can handle is
+  // of length InvocationCounter::number_of_count_bits. Mask values are always
+  // one bit shorter then the value of the notification frequency. Set
+  // max_freq_bits accordingly.
+  intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
+  intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
+  if (scaled_freq == 0) {
+    // Return 0 right away to avoid calculating log2 of 0.
+    return 0;
+  } else if (scaled_freq > nth_bit(max_freq_bits)) {
+    return max_freq_bits;
+  } else {
+    return log2_intptr(scaled_freq);
+  }
+}
+
 #ifdef TIERED
 void set_client_compilation_mode() {
   Compilation_mode = CompMode_client;
@@ -113,4 +164,284 @@
     FLAG_SET_ERGO(intx, CICompilerCount, 1);
   }
 }
+
+bool compilation_mode_selected() {
+  return !FLAG_IS_DEFAULT(TieredCompilation) ||
+         !FLAG_IS_DEFAULT(TieredStopAtLevel) ||
+         !FLAG_IS_DEFAULT(UseAOT)
+         JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI)
+                    || !FLAG_IS_DEFAULT(UseJVMCICompiler));
+}
+
+void select_compilation_mode_ergonomically() {
+#if defined(_WINDOWS) && !defined(_LP64)
+  if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) {
+    FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true);
+  }
+#endif
+  if (NeverActAsServerClassMachine) {
+    set_client_compilation_mode();
+  }
+}
+
 #endif // TIERED
+
+void CompilerConfig::set_tiered_flags() {
+  // With tiered, set default policy to SimpleThresholdPolicy, which is 2.
+  if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
+    FLAG_SET_DEFAULT(CompilationPolicyChoice, 2);
+  }
+  if (CompilationPolicyChoice < 2) {
+    vm_exit_during_initialization(
+      "Incompatible compilation policy selected", NULL);
+  }
+  // Increase the code cache size - tiered compiles a lot more.
+  if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
+    FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
+                  MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
+  }
+  // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
+  if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
+    FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
+  }
+  if (!UseInterpreter) { // -Xcomp
+    Tier3InvokeNotifyFreqLog = 0;
+    Tier4InvocationThreshold = 0;
+  }
+
+  if (CompileThresholdScaling < 0) {
+    vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
+  }
+
+  // Scale tiered compilation thresholds.
+  // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
+  if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
+    FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
+    FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
+
+    FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
+    FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
+    FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
+    FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
+
+    // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
+    // once these thresholds become supported.
+
+    FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
+    FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
+
+    FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
+    FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
+
+    FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
+
+    FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
+    FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
+    FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
+    FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
+  }
+}
+
+#if INCLUDE_JVMCI
+void set_jvmci_specific_flags() {
+  if (UseJVMCICompiler) {
+    Compilation_mode = CompMode_server;
+
+    if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
+      FLAG_SET_DEFAULT(TypeProfileWidth, 8);
+    }
+    if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
+      FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
+    }
+    if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
+      FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
+    }
+    if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
+      FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
+    }
+    if (FLAG_IS_DEFAULT(MetaspaceSize)) {
+      FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
+    }
+    if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
+      FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
+    }
+    if (TieredStopAtLevel != CompLevel_full_optimization) {
+      // Currently JVMCI compiler can only work at the full optimization level
+      warning("forcing TieredStopAtLevel to full optimization because JVMCI is enabled");
+      FLAG_SET_ERGO(intx, TieredStopAtLevel, CompLevel_full_optimization);
+    }
+    if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
+      FLAG_SET_DEFAULT(TypeProfileLevel, 0);
+    }
+  }
+}
+#endif // INCLUDE_JVMCI
+
+bool CompilerConfig::check_args_consistency(bool status) {
+  // Check lower bounds of the code cache
+  // Template Interpreter code is approximately 3X larger in debug builds.
+  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
+  if (ReservedCodeCacheSize < InitialCodeCacheSize) {
+    jio_fprintf(defaultStream::error_stream(),
+                "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
+                ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
+    status = false;
+  } else if (ReservedCodeCacheSize < min_code_cache_size) {
+    jio_fprintf(defaultStream::error_stream(),
+                "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
+                min_code_cache_size/K);
+    status = false;
+  } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
+    // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
+    jio_fprintf(defaultStream::error_stream(),
+                "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
+                CODE_CACHE_SIZE_LIMIT/M);
+    status = false;
+  } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
+    jio_fprintf(defaultStream::error_stream(),
+                "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
+                min_code_cache_size/K);
+    status = false;
+  }
+
+#ifdef _LP64
+  if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
+    warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
+  }
+#endif
+
+  if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
+    if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
+      warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
+    }
+    FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
+  }
+
+#ifdef COMPILER2
+  if (PostLoopMultiversioning && !RangeCheckElimination) {
+    if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
+      warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
+    }
+    FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
+  }
+  if (UseCountedLoopSafepoints && LoopStripMiningIter == 0) {
+    if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
+      warning("When counted loop safepoints are enabled, LoopStripMiningIter must be at least 1 (a safepoint every 1 iteration): setting it to 1");
+    }
+    LoopStripMiningIter = 1;
+  } else if (!UseCountedLoopSafepoints && LoopStripMiningIter > 0) {
+    if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
+      warning("Disabling counted safepoints implies no loop strip mining: setting LoopStripMiningIter to 0");
+    }
+    LoopStripMiningIter = 0;
+  }
+#endif // COMPILER2
+
+  if (Arguments::is_interpreter_only()) {
+    if (UseCompiler) {
+      if (!FLAG_IS_DEFAULT(UseCompiler)) {
+        warning("UseCompiler disabled due to -Xint.");
+      }
+      FLAG_SET_CMDLINE(bool, UseCompiler, false);
+    }
+    if (ProfileInterpreter) {
+      if (!FLAG_IS_DEFAULT(ProfileInterpreter)) {
+        warning("ProfileInterpreter disabled due to -Xint.");
+      }
+      FLAG_SET_CMDLINE(bool, ProfileInterpreter, false);
+    }
+    if (TieredCompilation) {
+      if (!FLAG_IS_DEFAULT(TieredCompilation)) {
+        warning("TieredCompilation disabled due to -Xint.");
+      }
+      FLAG_SET_CMDLINE(bool, TieredCompilation, false);
+    }
+#if INCLUDE_JVMCI
+    if (EnableJVMCI) {
+      if (!FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler)) {
+        warning("JVMCI Compiler disabled due to -Xint.");
+      }
+      FLAG_SET_CMDLINE(bool, EnableJVMCI, false);
+      FLAG_SET_CMDLINE(bool, UseJVMCICompiler, false);
+    }
+#endif
+  } else {
+#if INCLUDE_JVMCI
+    status = status && JVMCIGlobals::check_jvmci_flags_are_consistent();
+#endif
+  }
+  return status;
+}
+
+void CompilerConfig::ergo_initialize() {
+  if (Arguments::is_interpreter_only()) {
+    return; // Nothing to do.
+  }
+
+#ifdef TIERED
+  if (!compilation_mode_selected()) {
+    select_compilation_mode_ergonomically();
+  }
+#endif
+
+#if INCLUDE_JVMCI
+  // Check that JVMCI compiler supports selested GC.
+  // Should be done after GCConfig::initialize() was called.
+  JVMCIGlobals::check_jvmci_supported_gc();
+  set_jvmci_specific_flags();
+#endif
+
+  if (TieredCompilation) {
+    set_tiered_flags();
+  } else {
+    int max_compilation_policy_choice = 1;
+#ifdef COMPILER2
+    if (is_server_compilation_mode_vm()) {
+      max_compilation_policy_choice = 2;
+    }
+#endif
+    // Check if the policy is valid.
+    if (CompilationPolicyChoice >= max_compilation_policy_choice) {
+      vm_exit_during_initialization(
+        "Incompatible compilation policy selected", NULL);
+    }
+    // Scale CompileThreshold
+    // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
+    if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
+      FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
+    }
+  }
+
+  if (UseOnStackReplacement && !UseLoopCounter) {
+    warning("On-stack-replacement requires loop counters; enabling loop counters");
+    FLAG_SET_DEFAULT(UseLoopCounter, true);
+  }
+
+#ifdef COMPILER2
+  if (!EliminateLocks) {
+    EliminateNestedLocks = false;
+  }
+  if (!Inline) {
+    IncrementalInline = false;
+  }
+#ifndef PRODUCT
+  if (!IncrementalInline) {
+    AlwaysIncrementalInline = false;
+  }
+  if (PrintIdealGraphLevel > 0) {
+    FLAG_SET_ERGO(bool, PrintIdealGraph, true);
+  }
+#endif
+  if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
+    // nothing to use the profiling, turn if off
+    FLAG_SET_DEFAULT(TypeProfileLevel, 0);
+  }
+  if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
+    FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
+  }
+  if (FLAG_IS_DEFAULT(LoopStripMiningIterShortLoop)) {
+    // blind guess
+    LoopStripMiningIterShortLoop = LoopStripMiningIter / 10;
+  }
+#endif // COMPILER2
+}
--- a/src/hotspot/share/compiler/compilerDefinitions.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/compiler/compilerDefinitions.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,7 @@
 #ifndef SHARE_VM_COMPILER_COMPILERDEFINITIONS_HPP
 #define SHARE_VM_COMPILER_COMPILERDEFINITIONS_HPP
 
-#include "utilities/globalDefinitions.hpp"
+#include "memory/allocation.hpp"
 
 // The (closed set) of concrete compiler classes.
 enum CompilerType {
@@ -75,8 +75,6 @@
   return Compilation_mode == CompMode_client;
 }
 
-extern void set_client_compilation_mode();
-
 inline bool is_c1_compile(int comp_level) {
   return comp_level > CompLevel_none && comp_level < CompLevel_full_optimization;
 }
@@ -109,4 +107,23 @@
 #define RTM_OPT_ONLY(code)
 #endif
 
+class CompilerConfig : public AllStatic {
+public:
+  // Scale compile thresholds
+  // Returns threshold scaled with CompileThresholdScaling
+  static intx scaled_compile_threshold(intx threshold, double scale);
+  static intx scaled_compile_threshold(intx threshold);
+
+  // Returns freq_log scaled with CompileThresholdScaling
+  static intx scaled_freq_log(intx freq_log, double scale);
+  static intx scaled_freq_log(intx freq_log);
+
+  static bool check_args_consistency(bool status);
+
+  static void ergo_initialize();
+
+private:
+  static void set_tiered_flags();
+};
+
 #endif // SHARE_VM_COMPILER_COMPILERDEFINITIONS_HPP
--- a/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -56,6 +56,7 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "gc/shared/oopStorageParState.hpp"
 #include "gc/shared/referencePolicy.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/space.inline.hpp"
 #include "gc/shared/strongRootsScope.hpp"
 #include "gc/shared/taskqueue.inline.hpp"
@@ -299,7 +300,8 @@
                              _cmsGen->refs_discovery_is_mt(),        // mt discovery
                              MAX2(ConcGCThreads, ParallelGCThreads), // mt discovery degree
                              _cmsGen->refs_discovery_is_atomic(),    // discovery is not atomic
-                             &_is_alive_closure);                    // closure for liveness info
+                             &_is_alive_closure,                     // closure for liveness info
+                             false);                                 // disable adjusting number of processing threads
     // Initialize the _ref_processor field of CMSGen
     _cmsGen->set_ref_processor(_ref_processor);
 
@@ -5125,16 +5127,18 @@
   log_develop_trace(gc, task)("\t(%d: stole %d oops)", i, num_steals);
 }
 
-void CMSRefProcTaskExecutor::execute(ProcessTask& task)
-{
+void CMSRefProcTaskExecutor::execute(ProcessTask& task, uint ergo_workers) {
   CMSHeap* heap = CMSHeap::heap();
   WorkGang* workers = heap->workers();
   assert(workers != NULL, "Need parallel worker threads.");
+  assert(workers->active_workers() == ergo_workers,
+         "Ergonomically chosen workers (%u) must be equal to active workers (%u)",
+         ergo_workers, workers->active_workers());
   CMSRefProcTaskProxy rp_task(task, &_collector,
                               _collector.ref_processor_span(),
                               _collector.markBitMap(),
                               workers, _collector.task_queues());
-  workers->run_task(&rp_task);
+  workers->run_task(&rp_task, workers->active_workers());
 }
 
 void CMSCollector::refProcessingWork() {
@@ -8084,6 +8088,7 @@
     case CMSCollector::InitialMarking:
       initialize(manager /* GC manager */ ,
                  cause   /* cause of the GC */,
+                 true    /* allMemoryPoolsAffected */,
                  true    /* recordGCBeginTime */,
                  true    /* recordPreGCUsage */,
                  false   /* recordPeakUsage */,
@@ -8096,6 +8101,7 @@
     case CMSCollector::FinalMarking:
       initialize(manager /* GC manager */ ,
                  cause   /* cause of the GC */,
+                 true    /* allMemoryPoolsAffected */,
                  false   /* recordGCBeginTime */,
                  false   /* recordPreGCUsage */,
                  false   /* recordPeakUsage */,
@@ -8108,6 +8114,7 @@
     case CMSCollector::Sweeping:
       initialize(manager /* GC manager */ ,
                  cause   /* cause of the GC */,
+                 true    /* allMemoryPoolsAffected */,
                  false   /* recordGCBeginTime */,
                  false   /* recordPreGCUsage */,
                  true    /* recordPeakUsage */,
--- a/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -486,7 +486,7 @@
   { }
 
   // Executes a task using worker threads.
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 private:
   CMSCollector& _collector;
 };
--- a/src/hotspot/share/gc/cms/parNewGeneration.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/cms/parNewGeneration.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -42,6 +42,7 @@
 #include "gc/shared/plab.inline.hpp"
 #include "gc/shared/preservedMarks.inline.hpp"
 #include "gc/shared/referencePolicy.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/space.hpp"
 #include "gc/shared/spaceDecorator.hpp"
 #include "gc/shared/strongRootsScope.hpp"
@@ -792,14 +793,17 @@
              par_scan_state.evacuate_followers_closure());
 }
 
-void ParNewRefProcTaskExecutor::execute(ProcessTask& task) {
+void ParNewRefProcTaskExecutor::execute(ProcessTask& task, uint ergo_workers) {
   CMSHeap* gch = CMSHeap::heap();
   WorkGang* workers = gch->workers();
   assert(workers != NULL, "Need parallel worker threads.");
+  assert(workers->active_workers() == ergo_workers,
+         "Ergonomically chosen workers (%u) must be equal to active workers (%u)",
+         ergo_workers, workers->active_workers());
   _state_set.reset(workers->active_workers(), _young_gen.promotion_failed());
   ParNewRefProcTaskProxy rp_task(task, _young_gen, _old_gen,
                                  _young_gen.reserved().end(), _state_set);
-  workers->run_task(&rp_task);
+  workers->run_task(&rp_task, workers->active_workers());
   _state_set.reset(0 /* bad value in debug if not reset */,
                    _young_gen.promotion_failed());
 }
@@ -812,7 +816,7 @@
 
 ScanClosureWithParBarrier::
 ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier) :
-  ScanClosure(g, gc_barrier)
+  OopsInClassLoaderDataOrGenClosure(g), _g(g), _boundary(g->reserved().end()), _gc_barrier(gc_barrier)
 { }
 
 template <typename OopClosureType1, typename OopClosureType2>
@@ -1449,7 +1453,8 @@
                              refs_discovery_is_mt(),     // mt discovery
                              ParallelGCThreads,          // mt discovery degree
                              refs_discovery_is_atomic(), // atomic_discovery
-                             NULL);                      // is_alive_non_header
+                             NULL,                       // is_alive_non_header
+                             false);                     // disable adjusting number of processing threads
   }
 }
 
--- a/src/hotspot/share/gc/cms/parNewGeneration.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/cms/parNewGeneration.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -275,9 +275,14 @@
 
 // Closure for scanning ParNewGeneration.
 // Same as ScanClosure, except does parallel GC barrier.
-class ScanClosureWithParBarrier: public ScanClosure {
- protected:
+class ScanClosureWithParBarrier: public OopsInClassLoaderDataOrGenClosure {
+ private:
+  ParNewGeneration* _g;
+  HeapWord*         _boundary;
+  bool              _gc_barrier;
+
   template <class T> void do_oop_work(T* p);
+
  public:
   ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier);
   virtual void do_oop(oop* p);
@@ -298,7 +303,7 @@
   { }
 
   // Executes a task using worker threads.
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
   // Switch to single threaded mode.
   virtual void set_single_threaded_mode();
 };
--- a/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/c2/g1BarrierSetC2.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -601,10 +601,10 @@
 
   bool mismatched = (decorators & C2_MISMATCHED) != 0;
   bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
-  bool on_heap = (decorators & IN_HEAP) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
   bool on_weak = (decorators & ON_WEAK_OOP_REF) != 0;
   bool is_unordered = (decorators & MO_UNORDERED) != 0;
-  bool need_cpu_mem_bar = !is_unordered || mismatched || !on_heap;
+  bool need_cpu_mem_bar = !is_unordered || mismatched || !in_heap;
 
   Node* offset = adr->is_AddP() ? adr->in(AddPNode::Offset) : kit->top();
   Node* load = CardTableBarrierSetC2::load_at_resolved(access, val_type);
@@ -615,7 +615,7 @@
   // SATB log buffer using the pre-barrier mechanism.
   // Also we need to add memory barrier to prevent commoning reads
   // from this field across safepoint since GC can change its value.
-  bool need_read_barrier = on_heap && (on_weak ||
+  bool need_read_barrier = in_heap && (on_weak ||
                                        (unknown && offset != kit->top() && obj != kit->top()));
 
   if (!access.is_oop() || !need_read_barrier) {
--- a/src/hotspot/share/gc/g1/g1Arguments.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1Arguments.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -122,6 +122,10 @@
     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
   }
 
+  if (FLAG_IS_DEFAULT(ParallelRefProcEnabled) && ParallelGCThreads > 1) {
+    FLAG_SET_DEFAULT(ParallelRefProcEnabled, true);
+  }
+
   log_trace(gc)("MarkStackSize: %uk  MarkStackSizeMax: %uk", (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
 
   // By default do not let the target stack size to be more than 1/4 of the entries
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1737,7 +1737,7 @@
 
   _memory_manager.add_pool(_eden_pool);
   _memory_manager.add_pool(_survivor_pool);
-
+  _memory_manager.add_pool(_old_pool, false /* always_affected_by_gc */);
 }
 
 void G1CollectedHeap::stop() {
@@ -1815,7 +1815,8 @@
                            (ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery
                            MAX2(ParallelGCThreads, ConcGCThreads),         // degree of mt discovery
                            false,                                          // Reference discovery is not atomic
-                           &_is_alive_closure_cm);                         // is alive closure
+                           &_is_alive_closure_cm,                          // is alive closure
+                           true);                                          // allow changes to number of processing threads
 
   // STW ref processor
   _ref_processor_stw =
@@ -1825,7 +1826,8 @@
                            (ParallelGCThreads > 1),              // mt discovery
                            ParallelGCThreads,                    // degree of mt discovery
                            true,                                 // Reference discovery is atomic
-                           &_is_alive_closure_stw);              // is alive closure
+                           &_is_alive_closure_stw,               // is alive closure
+                           true);                                // allow changes to number of processing threads
 }
 
 CollectorPolicy* G1CollectedHeap::collector_policy() const {
@@ -2831,7 +2833,8 @@
     log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
 
     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
-    TraceMemoryManagerStats tms(&_memory_manager, gc_cause());
+    TraceMemoryManagerStats tms(&_memory_manager, gc_cause(),
+                                collector_state()->yc_type() == Mixed /* allMemoryPoolsAffected */);
 
     G1HeapTransition heap_transition(this);
     size_t heap_used_bytes_before_gc = used();
@@ -3791,25 +3794,22 @@
   G1ParScanThreadStateSet*  _pss;
   RefToScanQueueSet*        _queues;
   WorkGang*                 _workers;
-  uint                      _active_workers;
 
 public:
   G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
                            G1ParScanThreadStateSet* per_thread_states,
                            WorkGang* workers,
-                           RefToScanQueueSet *task_queues,
-                           uint n_workers) :
+                           RefToScanQueueSet *task_queues) :
     _g1h(g1h),
     _pss(per_thread_states),
     _queues(task_queues),
-    _workers(workers),
-    _active_workers(n_workers)
+    _workers(workers)
   {
-    g1h->ref_processor_stw()->set_active_mt_degree(n_workers);
+    g1h->ref_processor_stw()->set_active_mt_degree(workers->active_workers());
   }
 
   // Executes the given task using concurrent marking worker threads.
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 };
 
 // Gang task for possibly parallel reference processing
@@ -3843,7 +3843,7 @@
 
     G1STWIsAliveClosure is_alive(_g1h);
 
-    G1ParScanThreadState*          pss = _pss->state_for_worker(worker_id);
+    G1ParScanThreadState* pss = _pss->state_for_worker(worker_id);
     pss->set_ref_discoverer(NULL);
 
     // Keep alive closure.
@@ -3865,13 +3865,16 @@
 // Driver routine for parallel reference processing.
 // Creates an instance of the ref processing gang
 // task and has the worker threads execute it.
-void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
+void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task, uint ergo_workers) {
   assert(_workers != NULL, "Need parallel worker threads.");
 
-  ParallelTaskTerminator terminator(_active_workers, _queues);
+  assert(_workers->active_workers() >= ergo_workers,
+         "Ergonomically chosen workers (%u) should be less than or equal to active workers (%u)",
+         ergo_workers, _workers->active_workers());
+  ParallelTaskTerminator terminator(ergo_workers, _queues);
   G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _pss, _queues, &terminator);
 
-  _workers->run_task(&proc_task_proxy);
+  _workers->run_task(&proc_task_proxy, ergo_workers);
 }
 
 // End of weak reference support closures
@@ -3922,7 +3925,7 @@
            "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",
            no_of_gc_workers,  rp->max_num_queues());
 
-    G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues, no_of_gc_workers);
+    G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues);
     stats = rp->process_discovered_references(&is_alive,
                                               &keep_alive,
                                               &drain_queue,
--- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1518,8 +1518,7 @@
     _g1h(g1h), _cm(cm),
     _workers(workers), _active_workers(n_workers) { }
 
-  // Executes the given task using concurrent marking worker threads.
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 };
 
 class G1CMRefProcTaskProxy : public AbstractGangTask {
@@ -1550,9 +1549,12 @@
   }
 };
 
-void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
+void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task, uint ergo_workers) {
   assert(_workers != NULL, "Need parallel worker threads.");
   assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
+  assert(_workers->active_workers() >= ergo_workers,
+         "Ergonomically chosen workers(%u) should be less than or equal to active workers(%u)",
+         ergo_workers, _workers->active_workers());
 
   G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm);
 
@@ -1560,8 +1562,8 @@
   // proxy task execution, so that the termination protocol
   // and overflow handling in G1CMTask::do_marking_step() knows
   // how many workers to wait for.
-  _cm->set_concurrency(_active_workers);
-  _workers->run_task(&proc_task_proxy);
+  _cm->set_concurrency(ergo_workers);
+  _workers->run_task(&proc_task_proxy, ergo_workers);
 }
 
 void G1ConcurrentMark::weak_refs_work(bool clear_all_soft_refs) {
--- a/src/hotspot/share/gc/g1/g1FullGCReferenceProcessorExecutor.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1FullGCReferenceProcessorExecutor.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -67,9 +67,13 @@
   G1CollectedHeap::heap()->workers()->run_task(task, _collector->workers());
 }
 
-void G1FullGCReferenceProcessingExecutor::execute(ProcessTask& proc_task) {
+void G1FullGCReferenceProcessingExecutor::run_task(AbstractGangTask* task, uint workers) {
+  G1CollectedHeap::heap()->workers()->run_task(task, workers);
+}
+
+void G1FullGCReferenceProcessingExecutor::execute(ProcessTask& proc_task, uint ergo_workers) {
   G1RefProcTaskProxy proc_task_proxy(proc_task, _collector);
-  run_task(&proc_task_proxy);
+  run_task(&proc_task_proxy, ergo_workers);
 }
 
 void G1FullGCReferenceProcessingExecutor::execute(STWGCTimer* timer, G1FullGCTracer* tracer) {
--- a/src/hotspot/share/gc/g1/g1FullGCReferenceProcessorExecutor.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1FullGCReferenceProcessorExecutor.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -50,10 +50,11 @@
   void execute(STWGCTimer* timer, G1FullGCTracer* tracer);
 
   // Executes the given task using concurrent marking worker threads.
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 
 private:
   void run_task(AbstractGangTask* task);
+  void run_task(AbstractGangTask* task, uint workers);
 
   class G1RefProcTaskProxy : public AbstractGangTask {
     typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
--- a/src/hotspot/share/gc/parallel/pcTasks.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/parallel/pcTasks.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -146,10 +146,13 @@
 // RefProcTaskExecutor
 //
 
-void RefProcTaskExecutor::execute(ProcessTask& task)
+void RefProcTaskExecutor::execute(ProcessTask& task, uint ergo_workers)
 {
   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
   uint active_gc_threads = heap->gc_task_manager()->active_workers();
+  assert(active_gc_threads == ergo_workers,
+         "Ergonomically chosen workers (%u) must be equal to active workers (%u)",
+         ergo_workers, active_gc_threads);
   OopTaskQueueSet* qset = ParCompactionManager::stack_array();
   ParallelTaskTerminator terminator(active_gc_threads, qset);
   GCTaskQueue* q = GCTaskQueue::create();
--- a/src/hotspot/share/gc/parallel/pcTasks.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/parallel/pcTasks.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -140,7 +140,7 @@
 //
 
 class RefProcTaskExecutor: public AbstractRefProcTaskExecutor {
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 };
 
 
--- a/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -46,6 +46,7 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "gc/shared/referencePolicy.hpp"
 #include "gc/shared/referenceProcessor.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/spaceDecorator.hpp"
 #include "gc/shared/weakProcessor.hpp"
 #include "logging/log.hpp"
--- a/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -49,6 +49,7 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "gc/shared/referencePolicy.hpp"
 #include "gc/shared/referenceProcessor.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/spaceDecorator.hpp"
 #include "gc/shared/weakProcessor.hpp"
 #include "logging/log.hpp"
@@ -851,7 +852,8 @@
                            true,                // mt discovery
                            ParallelGCThreads,   // mt discovery degree
                            true,                // atomic_discovery
-                           &_is_alive_closure); // non-header is alive closure
+                           &_is_alive_closure,  // non-header is alive closure
+                           false);              // disable adjusting number of processing threads
   _counters = new CollectorCounters("PSParallelCompact", 1);
 
   // Initialize static fields in ParCompactionManager.
--- a/src/hotspot/share/gc/parallel/psScavenge.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psScavenge.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -43,6 +43,7 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "gc/shared/referencePolicy.hpp"
 #include "gc/shared/referenceProcessor.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/spaceDecorator.hpp"
 #include "gc/shared/weakProcessor.hpp"
 #include "memory/resourceArea.hpp"
@@ -149,20 +150,26 @@
 }
 
 class PSRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
-  virtual void execute(ProcessTask& task);
+  virtual void execute(ProcessTask& task, uint ergo_workers);
 };
 
-void PSRefProcTaskExecutor::execute(ProcessTask& task)
+void PSRefProcTaskExecutor::execute(ProcessTask& task, uint ergo_workers)
 {
   GCTaskQueue* q = GCTaskQueue::create();
   GCTaskManager* manager = ParallelScavengeHeap::gc_task_manager();
-  for(uint i=0; i < manager->active_workers(); i++) {
+  uint active_workers = manager->active_workers();
+
+  assert(active_workers == ergo_workers,
+         "Ergonomically chosen workers (%u) must be equal to active workers (%u)",
+         ergo_workers, active_workers);
+
+  for(uint i=0; i < active_workers; i++) {
     q->enqueue(new PSRefProcTaskProxy(task, i));
   }
-  ParallelTaskTerminator terminator(manager->active_workers(),
-                 (TaskQueueSetSuper*) PSPromotionManager::stack_array_depth());
-  if (task.marks_oops_alive() && manager->active_workers() > 1) {
-    for (uint j = 0; j < manager->active_workers(); j++) {
+  ParallelTaskTerminator terminator(active_workers,
+                                    (TaskQueueSetSuper*) PSPromotionManager::stack_array_depth());
+  if (task.marks_oops_alive() && active_workers > 1) {
+    for (uint j = 0; j < active_workers; j++) {
       q->enqueue(new StealTask(&terminator));
     }
   }
@@ -747,7 +754,8 @@
                            true,                       // mt discovery
                            ParallelGCThreads,          // mt discovery degree
                            true,                       // atomic_discovery
-                           NULL);                      // header provides liveness info
+                           NULL,                       // header provides liveness info
+                           false);
 
   // Cache the cardtable
   _card_table = heap->card_table();
--- a/src/hotspot/share/gc/serial/defNewGeneration.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/serial/defNewGeneration.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -40,6 +40,7 @@
 #include "gc/shared/generationSpec.hpp"
 #include "gc/shared/preservedMarks.inline.hpp"
 #include "gc/shared/referencePolicy.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/space.inline.hpp"
 #include "gc/shared/spaceDecorator.hpp"
 #include "gc/shared/strongRootsScope.hpp"
@@ -127,7 +128,7 @@
   NOT_PRODUCT(ResourceMark rm);
   log_develop_trace(gc, scavenge)("CLDScanClosure::do_cld " PTR_FORMAT ", %s, dirty: %s",
                                   p2i(cld),
-                                  cld->loader_name(),
+                                  cld->loader_name_and_id(),
                                   cld->has_modified_oops() ? "true" : "false");
 
   // If the cld has not been dirtied we know that there's
--- a/src/hotspot/share/gc/serial/genMarkSweep.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/serial/genMarkSweep.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -41,6 +41,7 @@
 #include "gc/shared/genOopClosures.inline.hpp"
 #include "gc/shared/modRefBarrierSet.hpp"
 #include "gc/shared/referencePolicy.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/space.hpp"
 #include "gc/shared/strongRootsScope.hpp"
 #include "gc/shared/weakProcessor.hpp"
--- a/src/hotspot/share/gc/shared/barrierSet.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/barrierSet.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -270,7 +270,7 @@
     }
 
     // Off-heap oop accesses. These accessors get resolved when
-    // IN_HEAP is not set (e.g. when using the RootAccess API), it is
+    // IN_HEAP is not set (e.g. when using the NativeAccess API), it is
     // an oop* overload, and the barrier strength is AS_NORMAL.
     template <typename T>
     static oop oop_load_not_in_heap(T* addr) {
--- a/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/c2/barrierSetC2.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -41,7 +41,7 @@
   bool mismatched = (_decorators & C2_MISMATCHED) != 0;
   bool is_unordered = (_decorators & MO_UNORDERED) != 0;
   bool anonymous = (_decorators & C2_UNSAFE_ACCESS) != 0;
-  bool on_heap = (_decorators & IN_HEAP) != 0;
+  bool in_heap = (_decorators & IN_HEAP) != 0;
 
   bool is_write = (_decorators & C2_WRITE_ACCESS) != 0;
   bool is_read = (_decorators & C2_READ_ACCESS) != 0;
@@ -58,7 +58,7 @@
     // the barriers get omitted and the unsafe reference begins to "pollute"
     // the alias analysis of the rest of the graph, either Compile::can_alias
     // or Compile::must_alias will throw a diagnostic assert.)
-    if (!on_heap || !is_unordered || (mismatched && !_addr.type()->isa_aryptr())) {
+    if (!in_heap || !is_unordered || (mismatched && !_addr.type()->isa_aryptr())) {
       return true;
     }
   }
@@ -74,8 +74,8 @@
   bool unaligned = (decorators & C2_UNALIGNED) != 0;
   bool requires_atomic_access = (decorators & MO_UNORDERED) == 0;
 
-  bool in_root = (decorators & IN_ROOT) != 0;
-  assert(!in_root, "not supported yet");
+  bool in_native = (decorators & IN_NATIVE) != 0;
+  assert(!in_native, "not supported yet");
 
   if (access.type() == T_DOUBLE) {
     Node* new_val = kit->dstore_rounding(val.node());
@@ -103,8 +103,8 @@
   bool control_dependent = (decorators & C2_CONTROL_DEPENDENT_LOAD) != 0;
   bool pinned = (decorators & C2_PINNED_LOAD) != 0;
 
-  bool in_root = (decorators & IN_ROOT) != 0;
-  assert(!in_root, "not supported yet");
+  bool in_native = (decorators & IN_NATIVE) != 0;
+  assert(!in_native, "not supported yet");
 
   MemNode::MemOrd mo = access.mem_node_mo();
   LoadNode::ControlDependency dep = pinned ? LoadNode::Pinned : LoadNode::DependsOnlyOnTest;
--- a/src/hotspot/share/gc/shared/c2/modRefBarrierSetC2.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/c2/modRefBarrierSetC2.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -39,10 +39,10 @@
 
   bool on_array = (decorators & IN_HEAP_ARRAY) != 0;
   bool anonymous = (decorators & ON_UNKNOWN_OOP_REF) != 0;
-  bool on_heap = (decorators & IN_HEAP) != 0;
+  bool in_heap = (decorators & IN_HEAP) != 0;
   bool use_precise = on_array || anonymous;
 
-  if (!access.is_oop() || (!on_heap && !anonymous)) {
+  if (!access.is_oop() || (!in_heap && !anonymous)) {
     return BarrierSetC2::store_at_resolved(access, val);
   }
 
--- a/src/hotspot/share/gc/shared/gcConfig.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/gcConfig.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -76,12 +76,30 @@
          ZGC_ONLY_ARG(SupportedGC(UseZGC,             CollectedHeap::Z,        zArguments,        "z gc"))
 };
 
-#define FOR_EACH_SUPPORTED_GC(var) \
+#define FOR_EACH_SUPPORTED_GC(var)                                          \
   for (const SupportedGC* var = &SupportedGCs[0]; var < &SupportedGCs[ARRAY_SIZE(SupportedGCs)]; var++)
 
+#define FAIL_IF_SELECTED(option, enabled)                                   \
+  if (option == enabled && FLAG_IS_CMDLINE(option)) {                       \
+    vm_exit_during_initialization(enabled ?                                 \
+                                  "Option -XX:+" #option " not supported" : \
+                                  "Option -XX:-" #option " not supported"); \
+  }
+
 GCArguments* GCConfig::_arguments = NULL;
 bool GCConfig::_gc_selected_ergonomically = false;
 
+void GCConfig::fail_if_unsupported_gc_is_selected() {
+  NOT_CMSGC(     FAIL_IF_SELECTED(UseConcMarkSweepGC, true));
+  NOT_EPSILONGC( FAIL_IF_SELECTED(UseEpsilonGC,       true));
+  NOT_G1GC(      FAIL_IF_SELECTED(UseG1GC,            true));
+  NOT_PARALLELGC(FAIL_IF_SELECTED(UseParallelGC,      true));
+  NOT_PARALLELGC(FAIL_IF_SELECTED(UseParallelOldGC,   true));
+  NOT_SERIALGC(  FAIL_IF_SELECTED(UseSerialGC,        true));
+  NOT_SERIALGC(  FAIL_IF_SELECTED(UseParallelOldGC,   false));
+  NOT_ZGC(       FAIL_IF_SELECTED(UseZGC,             true));
+}
+
 void GCConfig::select_gc_ergonomically() {
   if (os::is_server_class_machine()) {
 #if INCLUDE_G1GC
@@ -96,14 +114,6 @@
     FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
 #endif
   }
-
-  NOT_CMSGC(     UNSUPPORTED_OPTION(UseConcMarkSweepGC));
-  NOT_EPSILONGC( UNSUPPORTED_OPTION(UseEpsilonGC);)
-  NOT_G1GC(      UNSUPPORTED_OPTION(UseG1GC);)
-  NOT_PARALLELGC(UNSUPPORTED_OPTION(UseParallelGC);)
-  NOT_PARALLELGC(UNSUPPORTED_OPTION(UseParallelOldGC));
-  NOT_SERIALGC(  UNSUPPORTED_OPTION(UseSerialGC);)
-  NOT_ZGC(       UNSUPPORTED_OPTION(UseZGC);)
 }
 
 bool GCConfig::is_no_gc_selected() {
@@ -135,6 +145,9 @@
 }
 
 GCArguments* GCConfig::select_gc() {
+  // Fail immediately if an unsupported GC is selected
+  fail_if_unsupported_gc_is_selected();
+
   if (is_no_gc_selected()) {
     // Try select GC ergonomically
     select_gc_ergonomically();
@@ -154,12 +167,6 @@
     vm_exit_during_initialization("Multiple garbage collectors selected", NULL);
   }
 
-#if INCLUDE_PARALLELGC && !INCLUDE_SERIALGC
-  if (FLAG_IS_CMDLINE(UseParallelOldGC) && !UseParallelOldGC) {
-    vm_exit_during_initialization("This JVM build only supports UseParallelOldGC as the full GC");
-  }
-#endif
-
   // Exactly one GC selected
   FOR_EACH_SUPPORTED_GC(gc) {
     if (gc->_flag) {
--- a/src/hotspot/share/gc/shared/gcConfig.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/gcConfig.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -35,6 +35,7 @@
   static GCArguments* _arguments;
   static bool         _gc_selected_ergonomically;
 
+  static void fail_if_unsupported_gc_is_selected();
   static bool is_no_gc_selected();
   static bool is_exactly_one_gc_selected();
 
--- a/src/hotspot/share/gc/shared/gc_globals.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/gc_globals.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -307,6 +307,12 @@
   product(bool, ParallelRefProcBalancingEnabled, true,                      \
           "Enable balancing of reference processing queues")                \
                                                                             \
+  experimental(size_t, ReferencesPerThread, 1000,                           \
+               "Ergonomically start one thread for this amount of "         \
+               "references for reference processing if "                    \
+               "ParallelRefProcEnabled is true. Specify 0 to disable and "  \
+               "use all threads.")                                          \
+                                                                            \
   product(uintx, InitiatingHeapOccupancyPercent, 45,                        \
           "The percent occupancy (IHOP) of the current old generation "     \
           "capacity above which a concurrent mark cycle will be initiated " \
--- a/src/hotspot/share/gc/shared/genOopClosures.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/genOopClosures.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -101,7 +101,7 @@
 // This closure will perform barrier store calls for ALL
 // pointers in scanned oops.
 class ScanClosure: public OopsInClassLoaderDataOrGenClosure {
- protected:
+ private:
   DefNewGeneration* _g;
   HeapWord*         _boundary;
   bool              _gc_barrier;
--- a/src/hotspot/share/gc/shared/referenceProcessor.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/referenceProcessor.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -31,6 +31,7 @@
 #include "gc/shared/gcTraceTime.inline.hpp"
 #include "gc/shared/referencePolicy.hpp"
 #include "gc/shared/referenceProcessor.inline.hpp"
+#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "logging/log.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/resourceArea.hpp"
@@ -98,13 +99,15 @@
                                        bool      mt_discovery,
                                        uint      mt_discovery_degree,
                                        bool      atomic_discovery,
-                                       BoolObjectClosure* is_alive_non_header)  :
+                                       BoolObjectClosure* is_alive_non_header,
+                                       bool      adjust_no_of_processing_threads)  :
   _is_subject_to_discovery(is_subject_to_discovery),
   _discovering_refs(false),
   _enqueuing_is_done(false),
   _is_alive_non_header(is_alive_non_header),
   _processing_is_mt(mt_processing),
-  _next_id(0)
+  _next_id(0),
+  _adjust_no_of_processing_threads(adjust_no_of_processing_threads)
 {
   assert(is_subject_to_discovery != NULL, "must be set");
 
@@ -125,8 +128,7 @@
 
   // Initialize all entries to NULL
   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
-    _discovered_refs[i].set_head(NULL);
-    _discovered_refs[i].set_length(0);
+    _discovered_refs[i].clear();
   }
 
   setup_policy(false /* default soft ref policy */);
@@ -189,6 +191,13 @@
   return total;
 }
 
+#ifdef ASSERT
+void ReferenceProcessor::verify_total_count_zero(DiscoveredList lists[], const char* type) {
+  size_t count = total_count(lists);
+  assert(count == 0, "%ss must be empty but has " SIZE_FORMAT " elements", type, count);
+}
+#endif
+
 ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   BoolObjectClosure*            is_alive,
   OopClosure*                   keep_alive,
@@ -217,34 +226,27 @@
                                 total_count(_discoveredFinalRefs),
                                 total_count(_discoveredPhantomRefs));
 
-  // Soft references
   {
-    RefProcPhaseTimesTracker tt(REF_SOFT, phase_times, this);
-    process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
-                               is_alive, keep_alive, complete_gc, task_executor, phase_times);
+    RefProcTotalPhaseTimesTracker tt(RefPhase1, phase_times, this);
+    process_soft_ref_reconsider(is_alive, keep_alive, complete_gc,
+                                task_executor, phase_times);
   }
 
   update_soft_ref_master_clock();
 
-  // Weak references
   {
-    RefProcPhaseTimesTracker tt(REF_WEAK, phase_times, this);
-    process_discovered_reflist(_discoveredWeakRefs, NULL, true,
-                               is_alive, keep_alive, complete_gc, task_executor, phase_times);
+    RefProcTotalPhaseTimesTracker tt(RefPhase2, phase_times, this);
+    process_soft_weak_final_refs(is_alive, keep_alive, complete_gc, task_executor, phase_times);
   }
 
-  // Final references
   {
-    RefProcPhaseTimesTracker tt(REF_FINAL, phase_times, this);
-    process_discovered_reflist(_discoveredFinalRefs, NULL, false,
-                               is_alive, keep_alive, complete_gc, task_executor, phase_times);
+    RefProcTotalPhaseTimesTracker tt(RefPhase3, phase_times, this);
+    process_final_keep_alive(keep_alive, complete_gc, task_executor, phase_times);
   }
 
-  // Phantom references
   {
-    RefProcPhaseTimesTracker tt(REF_PHANTOM, phase_times, this);
-    process_discovered_reflist(_discoveredPhantomRefs, NULL, true,
-                               is_alive, keep_alive, complete_gc, task_executor, phase_times);
+    RefProcTotalPhaseTimesTracker tt(RefPhase4, phase_times, this);
+    process_phantom_refs(is_alive, keep_alive, complete_gc, task_executor, phase_times);
   }
 
   if (task_executor != NULL) {
@@ -294,7 +296,7 @@
   // pre-barrier here because we know the Reference has already been found/marked,
   // that's how it ended up in the discovered list in the first place.
   RawAccess<>::oop_store(_prev_discovered_addr, new_next);
-  NOT_PRODUCT(_removed++);
+  _removed++;
   _refs_list.dec_length(1);
 }
 
@@ -318,24 +320,29 @@
   }
 }
 
-// NOTE: process_phase*() are largely similar, and at a high level
-// merely iterate over the extant list applying a predicate to
-// each of its elements and possibly removing that element from the
-// list and applying some further closures to that element.
-// We should consider the possibility of replacing these
-// process_phase*() methods by abstracting them into
-// a single general iterator invocation that receives appropriate
-// closures that accomplish this work.
+inline void log_dropped_ref(const DiscoveredListIterator& iter, const char* reason) {
+  if (log_develop_is_enabled(Trace, gc, ref)) {
+    ResourceMark rm;
+    log_develop_trace(gc, ref)("Dropping %s reference " PTR_FORMAT ": %s",
+                               reason, p2i(iter.obj()),
+                               iter.obj()->klass()->internal_name());
+  }
+}
 
-// (SoftReferences only) Traverse the list and remove any SoftReferences whose
-// referents are not alive, but that should be kept alive for policy reasons.
-// Keep alive the transitive closure of all such referents.
-void
-ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
-                                   ReferencePolicy*   policy,
-                                   BoolObjectClosure* is_alive,
-                                   OopClosure*        keep_alive,
-                                   VoidClosure*       complete_gc) {
+inline void log_enqueued_ref(const DiscoveredListIterator& iter, const char* reason) {
+  if (log_develop_is_enabled(Trace, gc, ref)) {
+    ResourceMark rm;
+    log_develop_trace(gc, ref)("Enqueue %s reference (" INTPTR_FORMAT ": %s)",
+                               reason, p2i(iter.obj()), iter.obj()->klass()->internal_name());
+  }
+  assert(oopDesc::is_oop(iter.obj(), UseConcMarkSweepGC), "Adding a bad reference");
+}
+
+size_t ReferenceProcessor::process_soft_ref_reconsider_work(DiscoveredList&    refs_list,
+                                                            ReferencePolicy*   policy,
+                                                            BoolObjectClosure* is_alive,
+                                                            OopClosure*        keep_alive,
+                                                            VoidClosure*       complete_gc) {
   assert(policy != NULL, "Must have a non-NULL policy");
   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   // Decide which softly reachable refs should be kept alive.
@@ -344,8 +351,7 @@
     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
     if (referent_is_dead &&
         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
-      log_develop_trace(gc, ref)("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
-                                 p2i(iter.obj()), iter.obj()->klass()->internal_name());
+      log_dropped_ref(iter, "by policy");
       // Remove Reference object from list
       iter.remove();
       // keep the referent around
@@ -357,23 +363,16 @@
   }
   // Close the reachable set
   complete_gc->do_void();
+
   log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
                              iter.removed(), iter.processed(), p2i(&refs_list));
+  return iter.removed();
 }
 
-inline void log_dropped_ref(const DiscoveredListIterator& iter, const char* reason) {
-  log_develop_trace(gc, ref)("Dropping %s reference " PTR_FORMAT ": %s",
-                             reason, p2i(iter.obj()),
-                             iter.obj()->klass()->internal_name());
-}
-
-// Traverse the list and remove any Refs whose referents are alive,
-// or NULL if discovery is not atomic.
-void ReferenceProcessor::process_phase2(DiscoveredList&    refs_list,
-                                        BoolObjectClosure* is_alive,
-                                        OopClosure*        keep_alive,
-                                        VoidClosure*       complete_gc) {
-  // complete_gc is unused.
+size_t ReferenceProcessor::process_soft_weak_final_refs_work(DiscoveredList&    refs_list,
+                                                             BoolObjectClosure* is_alive,
+                                                             OopClosure*        keep_alive,
+                                                             bool               do_enqueue_and_clear) {
   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   while (iter.has_next()) {
     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
@@ -395,50 +394,80 @@
       iter.make_referent_alive();
       iter.move_to_next();
     } else {
+      if (do_enqueue_and_clear) {
+        iter.clear_referent();
+        iter.enqueue();
+        log_enqueued_ref(iter, "cleared");
+      }
+      // Keep in discovered list
       iter.next();
     }
   }
-  NOT_PRODUCT(
-    if (iter.processed() > 0) {
-      log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
-        " Refs in discovered list " INTPTR_FORMAT,
-        iter.removed(), iter.processed(), p2i(&refs_list));
-    }
-  )
+  if (do_enqueue_and_clear) {
+    iter.complete_enqueue();
+    refs_list.clear();
+  }
+
+  log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
+                             " Refs in discovered list " INTPTR_FORMAT,
+                             iter.removed(), iter.processed(), p2i(&refs_list));
+  return iter.removed();
 }
 
-void ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
-                                        bool               clear_referent,
-                                        BoolObjectClosure* is_alive,
-                                        OopClosure*        keep_alive,
-                                        VoidClosure*       complete_gc) {
-  ResourceMark rm;
-  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
+size_t ReferenceProcessor::process_final_keep_alive_work(DiscoveredList& refs_list,
+                                                         OopClosure*     keep_alive,
+                                                         VoidClosure*    complete_gc) {
+  DiscoveredListIterator iter(refs_list, keep_alive, NULL);
   while (iter.has_next()) {
     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
-    if (clear_referent) {
-      // NULL out referent pointer
-      iter.clear_referent();
-    } else {
-      // Current reference is a FinalReference; that's the only kind we
-      // don't clear the referent, instead keeping it for calling finalize.
-      iter.make_referent_alive();
-      // Self-loop next, to mark it not active.
-      assert(java_lang_ref_Reference::next(iter.obj()) == NULL, "enqueued FinalReference");
-      java_lang_ref_Reference::set_next_raw(iter.obj(), iter.obj());
-    }
+    // keep the referent and followers around
+    iter.make_referent_alive();
+
+    // Self-loop next, to mark the FinalReference not active.
+    assert(java_lang_ref_Reference::next(iter.obj()) == NULL, "enqueued FinalReference");
+    java_lang_ref_Reference::set_next_raw(iter.obj(), iter.obj());
+
     iter.enqueue();
-    log_develop_trace(gc, ref)("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
-                               clear_referent ? "cleared " : "", p2i(iter.obj()), iter.obj()->klass()->internal_name());
-    assert(oopDesc::is_oop(iter.obj(), UseConcMarkSweepGC), "Adding a bad reference");
+    log_enqueued_ref(iter, "Final");
     iter.next();
   }
   iter.complete_enqueue();
   // Close the reachable set
   complete_gc->do_void();
-  // Clear the list.
-  refs_list.set_head(NULL);
-  refs_list.set_length(0);
+  refs_list.clear();
+
+  assert(iter.removed() == 0, "This phase does not remove anything.");
+  return iter.removed();
+}
+
+size_t ReferenceProcessor::process_phantom_refs_work(DiscoveredList&    refs_list,
+                                          BoolObjectClosure* is_alive,
+                                          OopClosure*        keep_alive,
+                                          VoidClosure*       complete_gc) {
+  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
+  while (iter.has_next()) {
+    iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
+
+    oop const referent = iter.referent();
+
+    if (referent == NULL || iter.is_referent_alive()) {
+      iter.make_referent_alive();
+      iter.remove();
+      iter.move_to_next();
+    } else {
+      iter.clear_referent();
+      iter.enqueue();
+      log_enqueued_ref(iter, "cleared Phantom");
+      iter.next();
+    }
+  }
+  iter.complete_enqueue();
+  // Close the reachable set; needed for collectors which keep_alive_closure do
+  // not immediately complete their work.
+  complete_gc->do_void();
+  refs_list.clear();
+
+  return iter.removed();
 }
 
 void
@@ -450,8 +479,7 @@
     next = java_lang_ref_Reference::discovered(obj);
     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
   }
-  refs_list.set_head(NULL);
-  refs_list.set_length(0);
+  refs_list.clear();
 }
 
 void ReferenceProcessor::abandon_partial_discovery() {
@@ -488,69 +516,107 @@
   return total_count(list);
 }
 
-class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
+class RefProcPhase1Task : public AbstractRefProcTaskExecutor::ProcessTask {
 public:
   RefProcPhase1Task(ReferenceProcessor&           ref_processor,
-                    DiscoveredList                refs_lists[],
-                    ReferencePolicy*              policy,
-                    bool                          marks_oops_alive,
-                    ReferenceProcessorPhaseTimes* phase_times)
-    : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
-      _policy(policy)
-  { }
-  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
+                    ReferenceProcessorPhaseTimes* phase_times,
+                    ReferencePolicy*              policy)
+    : ProcessTask(ref_processor, true /* marks_oops_alive */, phase_times),
+      _policy(policy) { }
+
+  virtual void work(uint worker_id,
+                    BoolObjectClosure& is_alive,
                     OopClosure& keep_alive,
                     VoidClosure& complete_gc)
   {
-    RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, _phase_times, i);
-
-    _ref_processor.process_phase1(_refs_lists[i], _policy,
-                                  &is_alive, &keep_alive, &complete_gc);
+    RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::SoftRefSubPhase1, _phase_times, worker_id);
+    size_t const removed = _ref_processor.process_soft_ref_reconsider_work(_ref_processor._discoveredSoftRefs[worker_id],
+                                                                           _policy,
+                                                                           &is_alive,
+                                                                           &keep_alive,
+                                                                           &complete_gc);
+    _phase_times->add_ref_cleared(REF_SOFT, removed);
   }
 private:
   ReferencePolicy* _policy;
 };
 
 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
+  void run_phase2(uint worker_id,
+                  DiscoveredList list[],
+                  BoolObjectClosure& is_alive,
+                  OopClosure& keep_alive,
+                  bool do_enqueue_and_clear,
+                  ReferenceType ref_type) {
+    size_t const removed = _ref_processor.process_soft_weak_final_refs_work(list[worker_id],
+                                                                            &is_alive,
+                                                                            &keep_alive,
+                                                                            do_enqueue_and_clear);
+    _phase_times->add_ref_cleared(ref_type, removed);
+  }
+
 public:
-  RefProcPhase2Task(ReferenceProcessor&           ref_processor,
-                    DiscoveredList                refs_lists[],
-                    bool                          marks_oops_alive,
+  RefProcPhase2Task(ReferenceProcessor& ref_processor,
                     ReferenceProcessorPhaseTimes* phase_times)
-    : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times)
-  { }
-  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
+    : ProcessTask(ref_processor, false /* marks_oops_alive */, phase_times) { }
+
+  virtual void work(uint worker_id,
+                    BoolObjectClosure& is_alive,
                     OopClosure& keep_alive,
-                    VoidClosure& complete_gc)
-  {
-    RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, _phase_times, i);
-
-    _ref_processor.process_phase2(_refs_lists[i],
-                                  &is_alive, &keep_alive, &complete_gc);
+                    VoidClosure& complete_gc) {
+    RefProcWorkerTimeTracker t(_phase_times->phase2_worker_time_sec(), worker_id);
+    {
+      RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::SoftRefSubPhase2, _phase_times, worker_id);
+      run_phase2(worker_id, _ref_processor._discoveredSoftRefs, is_alive, keep_alive, true /* do_enqueue_and_clear */, REF_SOFT);
+    }
+    {
+      RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::WeakRefSubPhase2, _phase_times, worker_id);
+      run_phase2(worker_id, _ref_processor._discoveredWeakRefs, is_alive, keep_alive, true /* do_enqueue_and_clear */, REF_WEAK);
+    }
+    {
+      RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::FinalRefSubPhase2, _phase_times, worker_id);
+      run_phase2(worker_id, _ref_processor._discoveredFinalRefs, is_alive, keep_alive, false /* do_enqueue_and_clear */, REF_FINAL);
+    }
+    // Close the reachable set; needed for collectors which keep_alive_closure do
+    // not immediately complete their work.
+    complete_gc.do_void();
   }
 };
 
 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 public:
   RefProcPhase3Task(ReferenceProcessor&           ref_processor,
-                    DiscoveredList                refs_lists[],
-                    bool                         clear_referent,
-                    bool                          marks_oops_alive,
                     ReferenceProcessorPhaseTimes* phase_times)
-    : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
-      _clear_referent(clear_referent)
-  { }
-  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
+    : ProcessTask(ref_processor, true /* marks_oops_alive */, phase_times) { }
+
+  virtual void work(uint worker_id,
+                    BoolObjectClosure& is_alive,
                     OopClosure& keep_alive,
                     VoidClosure& complete_gc)
   {
-    RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, _phase_times, i);
+    RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::FinalRefSubPhase3, _phase_times, worker_id);
+    _ref_processor.process_final_keep_alive_work(_ref_processor._discoveredFinalRefs[worker_id], &keep_alive, &complete_gc);
+  }
+};
+
+class RefProcPhase4Task: public AbstractRefProcTaskExecutor::ProcessTask {
+public:
+  RefProcPhase4Task(ReferenceProcessor&           ref_processor,
+                    ReferenceProcessorPhaseTimes* phase_times)
+    : ProcessTask(ref_processor, false /* marks_oops_alive */, phase_times) { }
 
-    _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
-                                  &is_alive, &keep_alive, &complete_gc);
+  virtual void work(uint worker_id,
+                    BoolObjectClosure& is_alive,
+                    OopClosure& keep_alive,
+                    VoidClosure& complete_gc)
+  {
+    RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::PhantomRefSubPhase4, _phase_times, worker_id);
+    size_t const removed = _ref_processor.process_phantom_refs_work(_ref_processor._discoveredPhantomRefs[worker_id],
+                                                                    &is_alive,
+                                                                    &keep_alive,
+                                                                    &complete_gc);
+    _phase_times->add_ref_cleared(REF_PHANTOM, removed);
   }
-private:
-  bool _clear_referent;
 };
 
 void ReferenceProcessor::log_reflist(const char* prefix, DiscoveredList list[], uint num_active_queues) {
@@ -614,6 +680,13 @@
   }
 }
 
+void ReferenceProcessor::maybe_balance_queues(DiscoveredList refs_lists[]) {
+  assert(_processing_is_mt, "Should not call this otherwise");
+  if (need_balance_queues(refs_lists)) {
+    balance_queues(refs_lists);
+  }
+}
+
 // Balances reference queues.
 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
 // queues[0, 1, ..., _num_q-1] because only the first _num_q
@@ -698,77 +771,211 @@
 #endif
 }
 
-void ReferenceProcessor::process_discovered_reflist(
-  DiscoveredList                refs_lists[],
-  ReferencePolicy*              policy,
-  bool                          clear_referent,
-  BoolObjectClosure*            is_alive,
-  OopClosure*                   keep_alive,
-  VoidClosure*                  complete_gc,
-  AbstractRefProcTaskExecutor*  task_executor,
-  ReferenceProcessorPhaseTimes* phase_times)
-{
-  bool mt_processing = task_executor != NULL && _processing_is_mt;
+bool ReferenceProcessor::is_mt_processing_set_up(AbstractRefProcTaskExecutor* task_executor) const {
+  return task_executor != NULL && _processing_is_mt;
+}
+
+void ReferenceProcessor::process_soft_ref_reconsider(BoolObjectClosure* is_alive,
+                                                     OopClosure* keep_alive,
+                                                     VoidClosure* complete_gc,
+                                                     AbstractRefProcTaskExecutor* task_executor,
+                                                     ReferenceProcessorPhaseTimes* phase_times) {
+  assert(!_processing_is_mt || task_executor != NULL, "Task executor must not be NULL when mt processing is set.");
+
+  size_t const num_soft_refs = total_count(_discoveredSoftRefs);
+  phase_times->set_ref_discovered(REF_SOFT, num_soft_refs);
+
+  phase_times->set_processing_is_mt(_processing_is_mt);
+
+  if (num_soft_refs == 0 || _current_soft_ref_policy == NULL) {
+    log_debug(gc, ref)("Skipped phase1 of Reference Processing due to unavailable references");
+    return;
+  }
+
+  RefProcMTDegreeAdjuster a(this, RefPhase1, num_soft_refs);
+
+  if (_processing_is_mt) {
+    RefProcBalanceQueuesTimeTracker tt(RefPhase1, phase_times);
+    maybe_balance_queues(_discoveredSoftRefs);
+  }
+
+  RefProcPhaseTimeTracker tt(RefPhase1, phase_times);
 
-  phase_times->set_processing_is_mt(mt_processing);
+  log_reflist("Phase1 Soft before", _discoveredSoftRefs, _max_num_queues);
+  if (_processing_is_mt) {
+    RefProcPhase1Task phase1(*this, phase_times, _current_soft_ref_policy);
+    task_executor->execute(phase1, num_queues());
+  } else {
+    size_t removed = 0;
+
+    RefProcSubPhasesWorkerTimeTracker tt2(SoftRefSubPhase1, phase_times, 0);
+    for (uint i = 0; i < _max_num_queues; i++) {
+      removed += process_soft_ref_reconsider_work(_discoveredSoftRefs[i], _current_soft_ref_policy,
+                                                  is_alive, keep_alive, complete_gc);
+    }
+
+    phase_times->add_ref_cleared(REF_SOFT, removed);
+  }
+  log_reflist("Phase1 Soft after", _discoveredSoftRefs, _max_num_queues);
+}
 
-  if (mt_processing && need_balance_queues(refs_lists)) {
-    RefProcBalanceQueuesTimeTracker tt(phase_times);
-    balance_queues(refs_lists);
+void ReferenceProcessor::process_soft_weak_final_refs(BoolObjectClosure* is_alive,
+                                                      OopClosure* keep_alive,
+                                                      VoidClosure* complete_gc,
+                                                      AbstractRefProcTaskExecutor*  task_executor,
+                                                      ReferenceProcessorPhaseTimes* phase_times) {
+  assert(!_processing_is_mt || task_executor != NULL, "Task executor must not be NULL when mt processing is set.");
+
+  size_t const num_soft_refs = total_count(_discoveredSoftRefs);
+  size_t const num_weak_refs = total_count(_discoveredWeakRefs);
+  size_t const num_final_refs = total_count(_discoveredFinalRefs);
+  size_t const num_total_refs = num_soft_refs + num_weak_refs + num_final_refs;
+  phase_times->set_ref_discovered(REF_WEAK, num_weak_refs);
+  phase_times->set_ref_discovered(REF_FINAL, num_final_refs);
+
+  phase_times->set_processing_is_mt(_processing_is_mt);
+
+  if (num_total_refs == 0) {
+    log_debug(gc, ref)("Skipped phase2 of Reference Processing due to unavailable references");
+    return;
   }
 
-  // Phase 1 (soft refs only):
-  // . Traverse the list and remove any SoftReferences whose
-  //   referents are not alive, but that should be kept alive for
-  //   policy reasons. Keep alive the transitive closure of all
-  //   such referents.
-  if (policy != NULL) {
-    RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, phase_times);
+  RefProcMTDegreeAdjuster a(this, RefPhase2, num_total_refs);
 
-    if (mt_processing) {
-      RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/, phase_times);
-      task_executor->execute(phase1);
-    } else {
-      for (uint i = 0; i < _max_num_queues; i++) {
-        process_phase1(refs_lists[i], policy,
-                       is_alive, keep_alive, complete_gc);
-      }
-    }
-  } else { // policy == NULL
-    assert(refs_lists != _discoveredSoftRefs,
-           "Policy must be specified for soft references.");
+  if (_processing_is_mt) {
+    RefProcBalanceQueuesTimeTracker tt(RefPhase2, phase_times);
+    maybe_balance_queues(_discoveredSoftRefs);
+    maybe_balance_queues(_discoveredWeakRefs);
+    maybe_balance_queues(_discoveredFinalRefs);
   }
 
-  // Phase 2:
-  // . Traverse the list and remove any refs whose referents are alive.
-  {
-    RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, phase_times);
+  RefProcPhaseTimeTracker tt(RefPhase2, phase_times);
+
+  log_reflist("Phase2 Soft before", _discoveredSoftRefs, _max_num_queues);
+  log_reflist("Phase2 Weak before", _discoveredWeakRefs, _max_num_queues);
+  log_reflist("Phase2 Final before", _discoveredFinalRefs, _max_num_queues);
+  if (_processing_is_mt) {
+    RefProcPhase2Task phase2(*this, phase_times);
+    task_executor->execute(phase2, num_queues());
+  } else {
+    RefProcWorkerTimeTracker t(phase_times->phase2_worker_time_sec(), 0);
+    {
+      size_t removed = 0;
+
+      RefProcSubPhasesWorkerTimeTracker tt2(SoftRefSubPhase2, phase_times, 0);
+      for (uint i = 0; i < _max_num_queues; i++) {
+        removed += process_soft_weak_final_refs_work(_discoveredSoftRefs[i], is_alive, keep_alive, true /* do_enqueue */);
+      }
+
+      phase_times->add_ref_cleared(REF_SOFT, removed);
+    }
+    {
+      size_t removed = 0;
+
+      RefProcSubPhasesWorkerTimeTracker tt2(WeakRefSubPhase2, phase_times, 0);
+      for (uint i = 0; i < _max_num_queues; i++) {
+        removed += process_soft_weak_final_refs_work(_discoveredWeakRefs[i], is_alive, keep_alive, true /* do_enqueue */);
+      }
+
+      phase_times->add_ref_cleared(REF_WEAK, removed);
+    }
+    {
+      size_t removed = 0;
 
-    if (mt_processing) {
-      RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/, phase_times);
-      task_executor->execute(phase2);
-    } else {
+      RefProcSubPhasesWorkerTimeTracker tt2(FinalRefSubPhase2, phase_times, 0);
       for (uint i = 0; i < _max_num_queues; i++) {
-        process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
+        removed += process_soft_weak_final_refs_work(_discoveredFinalRefs[i], is_alive, keep_alive, false /* do_enqueue */);
       }
+
+      phase_times->add_ref_cleared(REF_FINAL, removed);
     }
+    complete_gc->do_void();
+  }
+  verify_total_count_zero(_discoveredSoftRefs, "SoftReference");
+  verify_total_count_zero(_discoveredWeakRefs, "WeakReference");
+  log_reflist("Phase2 Final after", _discoveredFinalRefs, _max_num_queues);
+}
+
+void ReferenceProcessor::process_final_keep_alive(OopClosure* keep_alive,
+                                                  VoidClosure* complete_gc,
+                                                  AbstractRefProcTaskExecutor*  task_executor,
+                                                  ReferenceProcessorPhaseTimes* phase_times) {
+  assert(!_processing_is_mt || task_executor != NULL, "Task executor must not be NULL when mt processing is set.");
+
+  size_t const num_final_refs = total_count(_discoveredFinalRefs);
+
+  phase_times->set_processing_is_mt(_processing_is_mt);
+
+  if (num_final_refs == 0) {
+    log_debug(gc, ref)("Skipped phase3 of Reference Processing due to unavailable references");
+    return;
+  }
+
+  RefProcMTDegreeAdjuster a(this, RefPhase3, num_final_refs);
+
+  if (_processing_is_mt) {
+    RefProcBalanceQueuesTimeTracker tt(RefPhase3, phase_times);
+    maybe_balance_queues(_discoveredFinalRefs);
   }
 
   // Phase 3:
-  // . Traverse the list and process referents as appropriate.
-  {
-    RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, phase_times);
+  // . Traverse referents of final references and keep them and followers alive.
+  RefProcPhaseTimeTracker tt(RefPhase3, phase_times);
 
-    if (mt_processing) {
-      RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/, phase_times);
-      task_executor->execute(phase3);
-    } else {
-      for (uint i = 0; i < _max_num_queues; i++) {
-        process_phase3(refs_lists[i], clear_referent,
-                       is_alive, keep_alive, complete_gc);
-      }
+  if (_processing_is_mt) {
+    RefProcPhase3Task phase3(*this, phase_times);
+    task_executor->execute(phase3, num_queues());
+  } else {
+    RefProcSubPhasesWorkerTimeTracker tt2(FinalRefSubPhase3, phase_times, 0);
+    for (uint i = 0; i < _max_num_queues; i++) {
+      process_final_keep_alive_work(_discoveredFinalRefs[i], keep_alive, complete_gc);
     }
   }
+  verify_total_count_zero(_discoveredFinalRefs, "FinalReference");
+}
+
+void ReferenceProcessor::process_phantom_refs(BoolObjectClosure* is_alive,
+                                              OopClosure* keep_alive,
+                                              VoidClosure* complete_gc,
+                                              AbstractRefProcTaskExecutor* task_executor,
+                                              ReferenceProcessorPhaseTimes* phase_times) {
+  assert(!_processing_is_mt || task_executor != NULL, "Task executor must not be NULL when mt processing is set.");
+
+  size_t const num_phantom_refs = total_count(_discoveredPhantomRefs);
+  phase_times->set_ref_discovered(REF_PHANTOM, num_phantom_refs);
+
+  phase_times->set_processing_is_mt(_processing_is_mt);
+
+  if (num_phantom_refs == 0) {
+    log_debug(gc, ref)("Skipped phase4 of Reference Processing due to unavailable references");
+    return;
+  }
+
+  RefProcMTDegreeAdjuster a(this, RefPhase4, num_phantom_refs);
+
+  if (_processing_is_mt) {
+    RefProcBalanceQueuesTimeTracker tt(RefPhase4, phase_times);
+    maybe_balance_queues(_discoveredPhantomRefs);
+  }
+
+  // Phase 4: Walk phantom references appropriately.
+  RefProcPhaseTimeTracker tt(RefPhase4, phase_times);
+
+  log_reflist("Phase4 Phantom before", _discoveredPhantomRefs, _max_num_queues);
+  if (_processing_is_mt) {
+    RefProcPhase4Task phase4(*this, phase_times);
+    task_executor->execute(phase4, num_queues());
+  } else {
+    size_t removed = 0;
+
+    RefProcSubPhasesWorkerTimeTracker tt(PhantomRefSubPhase4, phase_times, 0);
+    for (uint i = 0; i < _max_num_queues; i++) {
+      removed += process_phantom_refs_work(_discoveredPhantomRefs[i], is_alive, keep_alive, complete_gc);
+    }
+
+    phase_times->add_ref_cleared(REF_PHANTOM, removed);
+  }
+  verify_total_count_zero(_discoveredPhantomRefs, "PhantomReference");
 }
 
 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
@@ -1119,12 +1326,10 @@
   // Close the reachable set
   complete_gc->do_void();
 
-  NOT_PRODUCT(
-    if (iter.processed() > 0) {
-      log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
-        iter.removed(), iter.processed(), p2i(&refs_list));
-    }
-  )
+  if (iter.processed() > 0) {
+    log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
+                               iter.removed(), iter.processed(), p2i(&refs_list));
+  }
   return false;
 }
 
@@ -1142,3 +1347,45 @@
    ShouldNotReachHere();
    return NULL;
 }
+
+uint RefProcMTDegreeAdjuster::ergo_proc_thread_count(size_t ref_count,
+                                                     uint max_threads,
+                                                     RefProcPhases phase) const {
+  assert(0 < max_threads, "must allow at least one thread");
+
+  if (use_max_threads(phase) || (ReferencesPerThread == 0)) {
+    return max_threads;
+  }
+
+  size_t thread_count = 1 + (ref_count / ReferencesPerThread);
+  return (uint)MIN3(thread_count,
+                    static_cast<size_t>(max_threads),
+                    (size_t)os::active_processor_count());
+}
+
+bool RefProcMTDegreeAdjuster::use_max_threads(RefProcPhases phase) const {
+  // Even a small number of references in either of those cases could produce large amounts of work.
+  return (phase == ReferenceProcessor::RefPhase1 || phase == ReferenceProcessor::RefPhase3);
+}
+
+RefProcMTDegreeAdjuster::RefProcMTDegreeAdjuster(ReferenceProcessor* rp,
+                                                 RefProcPhases phase,
+                                                 size_t ref_count):
+    _rp(rp),
+    _saved_mt_processing(_rp->processing_is_mt()),
+    _saved_num_queues(_rp->num_queues()) {
+  if (!_rp->processing_is_mt() || !_rp->adjust_no_of_processing_threads() || (ReferencesPerThread == 0)) {
+    return;
+  }
+
+  uint workers = ergo_proc_thread_count(ref_count, _rp->num_queues(), phase);
+
+  _rp->set_mt_processing(workers > 1);
+  _rp->set_active_mt_degree(workers);
+}
+
+RefProcMTDegreeAdjuster::~RefProcMTDegreeAdjuster() {
+  // Revert to previous status.
+  _rp->set_mt_processing(_saved_mt_processing);
+  _rp->set_active_mt_degree(_saved_num_queues);
+}
--- a/src/hotspot/share/gc/shared/referenceProcessor.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/referenceProcessor.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -27,28 +27,14 @@
 
 #include "gc/shared/referenceDiscoverer.hpp"
 #include "gc/shared/referencePolicy.hpp"
-#include "gc/shared/referenceProcessorPhaseTimes.hpp"
 #include "gc/shared/referenceProcessorStats.hpp"
 #include "memory/referenceType.hpp"
 #include "oops/instanceRefKlass.hpp"
 
+class AbstractRefProcTaskExecutor;
 class GCTimer;
-
-// ReferenceProcessor class encapsulates the per-"collector" processing
-// of java.lang.Reference objects for GC. The interface is useful for supporting
-// a generational abstraction, in particular when there are multiple
-// generations that are being independently collected -- possibly
-// concurrently and/or incrementally.
-// ReferenceProcessor class abstracts away from a generational setting
-// by using a closure that determines whether a given reference or referent are
-// subject to this ReferenceProcessor's discovery, thus allowing its use in a
-// straightforward manner in a general, non-generational, non-contiguous generation
-// (or heap) setting.
-//
-
-// forward references
 class ReferencePolicy;
-class AbstractRefProcTaskExecutor;
+class ReferenceProcessorPhaseTimes;
 
 // List of discovered references.
 class DiscoveredList {
@@ -65,6 +51,8 @@
   void   set_length(size_t len) { _len = len;  }
   void   inc_length(size_t inc) { _len += inc; assert(_len > 0, "Error"); }
   void   dec_length(size_t dec) { _len -= dec; }
+
+  inline void clear();
 private:
   // Set value depending on UseCompressedOops. This could be a template class
   // but then we have to fix all the instantiations and declarations that use this class.
@@ -93,10 +81,8 @@
   oop                _first_seen; // cyclic linked list check
   )
 
-  NOT_PRODUCT(
   size_t             _processed;
   size_t             _removed;
-  )
 
 public:
   inline DiscoveredListIterator(DiscoveredList&    refs_list,
@@ -153,10 +139,8 @@
   void clear_referent();
 
   // Statistics
-  NOT_PRODUCT(
   inline size_t processed() const { return _processed; }
-  inline size_t removed() const   { return _removed; }
-  )
+  inline size_t removed() const { return _removed; }
 
   inline void move_to_next() {
     if (_current_discovered == _next_discovered) {
@@ -166,12 +150,50 @@
       _current_discovered = _next_discovered;
     }
     assert(_current_discovered != _first_seen, "cyclic ref_list found");
-    NOT_PRODUCT(_processed++);
+    _processed++;
   }
 };
 
+// The ReferenceProcessor class encapsulates the per-"collector" processing
+// of java.lang.Reference objects for GC. The interface is useful for supporting
+// a generational abstraction, in particular when there are multiple
+// generations that are being independently collected -- possibly
+// concurrently and/or incrementally.
+// ReferenceProcessor class abstracts away from a generational setting
+// by using a closure that determines whether a given reference or referent are
+// subject to this ReferenceProcessor's discovery, thus allowing its use in a
+// straightforward manner in a general, non-generational, non-contiguous generation
+// (or heap) setting.
 class ReferenceProcessor : public ReferenceDiscoverer {
+  friend class RefProcPhase1Task;
+  friend class RefProcPhase2Task;
+  friend class RefProcPhase3Task;
+  friend class RefProcPhase4Task;
+public:
+  // Names of sub-phases of reference processing. Indicates the type of the reference
+  // processed and the associated phase number at the end.
+  enum RefProcSubPhases {
+    SoftRefSubPhase1,
+    SoftRefSubPhase2,
+    WeakRefSubPhase2,
+    FinalRefSubPhase2,
+    FinalRefSubPhase3,
+    PhantomRefSubPhase4,
+    RefSubPhaseMax
+  };
+
+  // Main phases of reference processing.
+  enum RefProcPhases {
+    RefPhase1,
+    RefPhase2,
+    RefPhase3,
+    RefPhase4,
+    RefPhaseMax
+  };
+
+private:
   size_t total_count(DiscoveredList lists[]) const;
+  void verify_total_count_zero(DiscoveredList lists[], const char* type) NOT_DEBUG_RETURN;
 
   // The SoftReference master timestamp clock
   static jlong _soft_ref_timestamp_clock;
@@ -191,6 +213,7 @@
   uint        _next_id;                 // round-robin mod _num_queues counter in
                                         // support of work distribution
 
+  bool        _adjust_no_of_processing_threads; // allow dynamic adjustment of processing threads
   // For collectors that do not keep GC liveness information
   // in the object header, this field holds a closure that
   // helps the reference processor determine the reachability
@@ -222,15 +245,72 @@
   DiscoveredList* _discoveredFinalRefs;
   DiscoveredList* _discoveredPhantomRefs;
 
- public:
+  // Phase 1: Re-evaluate soft ref policy.
+  void process_soft_ref_reconsider(BoolObjectClosure* is_alive,
+                                   OopClosure* keep_alive,
+                                   VoidClosure* complete_gc,
+                                   AbstractRefProcTaskExecutor*  task_executor,
+                                   ReferenceProcessorPhaseTimes* phase_times);
+
+  // Phase 2: Drop Soft/Weak/Final references with a NULL or live referent, and clear
+  // and enqueue non-Final references.
+  void process_soft_weak_final_refs(BoolObjectClosure* is_alive,
+                                    OopClosure* keep_alive,
+                                    VoidClosure* complete_gc,
+                                    AbstractRefProcTaskExecutor*  task_executor,
+                                    ReferenceProcessorPhaseTimes* phase_times);
+
+  // Phase 3: Keep alive followers of Final references, and enqueue.
+  void process_final_keep_alive(OopClosure* keep_alive,
+                                VoidClosure* complete_gc,
+                                AbstractRefProcTaskExecutor*  task_executor,
+                                ReferenceProcessorPhaseTimes* phase_times);
+
+  // Phase 4: Drop and keep alive live Phantom references, or clear and enqueue if dead.
+  void process_phantom_refs(BoolObjectClosure* is_alive,
+                            OopClosure* keep_alive,
+                            VoidClosure* complete_gc,
+                            AbstractRefProcTaskExecutor*  task_executor,
+                            ReferenceProcessorPhaseTimes* phase_times);
+
+  // Work methods used by the process_* methods. All methods return the number of
+  // removed elements.
+
+  // (SoftReferences only) Traverse the list and remove any SoftReferences whose
+  // referents are not alive, but that should be kept alive for policy reasons.
+  // Keep alive the transitive closure of all such referents.
+  size_t process_soft_ref_reconsider_work(DiscoveredList&     refs_list,
+                                          ReferencePolicy*    policy,
+                                          BoolObjectClosure*  is_alive,
+                                          OopClosure*         keep_alive,
+                                          VoidClosure*        complete_gc);
+
+  // Traverse the list and remove any Refs whose referents are alive,
+  // or NULL if discovery is not atomic. Enqueue and clear the reference for
+  // others if do_enqueue_and_clear is set.
+  size_t process_soft_weak_final_refs_work(DiscoveredList&    refs_list,
+                                           BoolObjectClosure* is_alive,
+                                           OopClosure*        keep_alive,
+                                           bool               do_enqueue_and_clear);
+
+  // Keep alive followers of referents for FinalReferences. Must only be called for
+  // those.
+  size_t process_final_keep_alive_work(DiscoveredList&    refs_list,
+                                       OopClosure*        keep_alive,
+                                       VoidClosure*       complete_gc);
+
+  size_t process_phantom_refs_work(DiscoveredList&    refs_list,
+                                   BoolObjectClosure* is_alive,
+                                   OopClosure*        keep_alive,
+                                   VoidClosure*       complete_gc);
+
+public:
   static int number_of_subclasses_of_ref() { return (REF_PHANTOM - REF_OTHER); }
 
   uint num_queues() const                  { return _num_queues; }
   uint max_num_queues() const              { return _max_num_queues; }
   void set_active_mt_degree(uint v);
 
-  DiscoveredList* discovered_refs()        { return _discovered_refs; }
-
   ReferencePolicy* setup_policy(bool always_clear) {
     _current_soft_ref_policy = always_clear ?
       _always_clear_soft_ref_policy : _default_soft_ref_policy;
@@ -238,38 +318,6 @@
     return _current_soft_ref_policy;
   }
 
-  // Process references with a certain reachability level.
-  void process_discovered_reflist(DiscoveredList                refs_lists[],
-                                  ReferencePolicy*              policy,
-                                  bool                          clear_referent,
-                                  BoolObjectClosure*            is_alive,
-                                  OopClosure*                   keep_alive,
-                                  VoidClosure*                  complete_gc,
-                                  AbstractRefProcTaskExecutor*  task_executor,
-                                  ReferenceProcessorPhaseTimes* phase_times);
-
-  // Work methods used by the method process_discovered_reflist
-  // Phase1: keep alive all those referents that are otherwise
-  // dead but which must be kept alive by policy (and their closure).
-  void process_phase1(DiscoveredList&     refs_list,
-                      ReferencePolicy*    policy,
-                      BoolObjectClosure*  is_alive,
-                      OopClosure*         keep_alive,
-                      VoidClosure*        complete_gc);
-  // Phase2: remove all those references whose referents are
-  // reachable.
-  void process_phase2(DiscoveredList&    refs_list,
-                      BoolObjectClosure* is_alive,
-                      OopClosure*        keep_alive,
-                      VoidClosure*       complete_gc);
-  // Phase3: process the referents by either clearing them
-  // or keeping them alive (and their closure), and enqueuing them.
-  void process_phase3(DiscoveredList&    refs_list,
-                      bool               clear_referent,
-                      BoolObjectClosure* is_alive,
-                      OopClosure*        keep_alive,
-                      VoidClosure*       complete_gc);
-
   // "Preclean" all the discovered reference lists by removing references that
   // are active (e.g. due to the mutator calling enqueue()) or with NULL or
   // strongly reachable referents.
@@ -285,11 +333,11 @@
                                       YieldClosure*      yield,
                                       GCTimer*           gc_timer);
 
+private:
   // Returns the name of the discovered reference list
   // occupying the i / _num_queues slot.
   const char* list_name(uint i);
 
-private:
   // "Preclean" the given discovered reference list by removing references with
   // the attributes mentioned in preclean_discovered_references().
   // Supports both normal and fine grain yielding.
@@ -323,18 +371,24 @@
   void balance_queues(DiscoveredList refs_lists[]);
   bool need_balance_queues(DiscoveredList refs_lists[]);
 
+  // If there is need to balance the given queue, do it.
+  void maybe_balance_queues(DiscoveredList refs_lists[]);
+
   // Update (advance) the soft ref master clock field.
   void update_soft_ref_master_clock();
 
   bool is_subject_to_discovery(oop const obj) const;
 
+  bool is_mt_processing_set_up(AbstractRefProcTaskExecutor* task_executor) const;
+
 public:
   // Default parameters give you a vanilla reference processor.
   ReferenceProcessor(BoolObjectClosure* is_subject_to_discovery,
                      bool mt_processing = false, uint mt_processing_degree = 1,
                      bool mt_discovery  = false, uint mt_discovery_degree  = 1,
                      bool atomic_discovery = true,
-                     BoolObjectClosure* is_alive_non_header = NULL);
+                     BoolObjectClosure* is_alive_non_header = NULL,
+                     bool adjust_no_of_processing_threads = false);
 
   // RefDiscoveryPolicy values
   enum DiscoveryPolicy {
@@ -346,7 +400,6 @@
 
   static void init_statics();
 
- public:
   // get and set "is_alive_non_header" field
   BoolObjectClosure* is_alive_non_header() {
     return _is_alive_non_header;
@@ -408,6 +461,8 @@
   // debugging
   void verify_no_references_recorded() PRODUCT_RETURN;
   void verify_referent(oop obj)        PRODUCT_RETURN;
+
+  bool adjust_no_of_processing_threads() const { return _adjust_no_of_processing_threads; }
 };
 
 // A subject-to-discovery closure that uses a single memory span to determine the area that
@@ -576,7 +631,6 @@
   }
 };
 
-
 // This class is an interface used to implement task execution for the
 // reference processing.
 class AbstractRefProcTaskExecutor {
@@ -586,7 +640,7 @@
   class ProcessTask;
 
   // Executes a task using worker threads.
-  virtual void execute(ProcessTask& task) = 0;
+  virtual void execute(ProcessTask& task, uint ergo_workers) = 0;
 
   // Switch to single threaded mode.
   virtual void set_single_threaded_mode() { };
@@ -595,30 +649,50 @@
 // Abstract reference processing task to execute.
 class AbstractRefProcTaskExecutor::ProcessTask {
 protected:
-  ProcessTask(ReferenceProcessor&           ref_processor,
-              DiscoveredList                refs_lists[],
-              bool                          marks_oops_alive,
+  ReferenceProcessor&           _ref_processor;
+  // Indicates whether the phase could generate work that should be balanced across
+  // threads after execution.
+  bool                          _marks_oops_alive;
+  ReferenceProcessorPhaseTimes* _phase_times;
+
+  ProcessTask(ReferenceProcessor& ref_processor,
+              bool marks_oops_alive,
               ReferenceProcessorPhaseTimes* phase_times)
     : _ref_processor(ref_processor),
-      _refs_lists(refs_lists),
-      _phase_times(phase_times),
-      _marks_oops_alive(marks_oops_alive)
+      _marks_oops_alive(marks_oops_alive),
+      _phase_times(phase_times)
   { }
 
 public:
-  virtual void work(unsigned int work_id, BoolObjectClosure& is_alive,
+  virtual void work(uint worker_id,
+                    BoolObjectClosure& is_alive,
                     OopClosure& keep_alive,
                     VoidClosure& complete_gc) = 0;
 
-  // Returns true if a task marks some oops as alive.
-  bool marks_oops_alive() const
-  { return _marks_oops_alive; }
+  bool marks_oops_alive() const { return _marks_oops_alive; }
+};
+
+// Temporarily change the number of workers based on given reference count.
+// This ergonomically decided worker count will be used to activate worker threads.
+class RefProcMTDegreeAdjuster : public StackObj {
+  typedef ReferenceProcessor::RefProcPhases RefProcPhases;
+
+  ReferenceProcessor* _rp;
+  bool                _saved_mt_processing;
+  uint                _saved_num_queues;
 
-protected:
-  ReferenceProcessor&           _ref_processor;
-  DiscoveredList*               _refs_lists;
-  ReferenceProcessorPhaseTimes* _phase_times;
-  const bool                    _marks_oops_alive;
+  // Calculate based on total of references.
+  uint ergo_proc_thread_count(size_t ref_count,
+                              uint max_threads,
+                              RefProcPhases phase) const;
+
+  bool use_max_threads(RefProcPhases phase) const;
+
+public:
+  RefProcMTDegreeAdjuster(ReferenceProcessor* rp,
+                          RefProcPhases phase,
+                          size_t ref_count);
+  ~RefProcMTDegreeAdjuster();
 };
 
 #endif // SHARE_VM_GC_SHARED_REFERENCEPROCESSOR_HPP
--- a/src/hotspot/share/gc/shared/referenceProcessor.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/referenceProcessor.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -47,6 +47,11 @@
  return head() == NULL;
 }
 
+void DiscoveredList::clear() {
+  set_head(NULL);
+  set_length(0);
+}
+
 DiscoveredListIterator::DiscoveredListIterator(DiscoveredList&    refs_list,
                                                OopClosure*        keep_alive,
                                                BoolObjectClosure* is_alive):
@@ -57,10 +62,8 @@
 #ifdef ASSERT
   _first_seen(refs_list.head()),
 #endif
-#ifndef PRODUCT
   _processed(0),
   _removed(0),
-#endif
   _next_discovered(NULL),
   _keep_alive(keep_alive),
   _is_alive(is_alive) {
--- a/src/hotspot/share/gc/shared/referenceProcessorPhaseTimes.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/referenceProcessorPhaseTimes.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -31,61 +31,96 @@
 #include "logging/logStream.hpp"
 #include "memory/allocation.inline.hpp"
 
-RefProcWorkerTimeTracker::RefProcWorkerTimeTracker(ReferenceProcessorPhaseTimes::RefProcPhaseNumbers number,
-                                                   ReferenceProcessorPhaseTimes* phase_times,
-                                                   uint worker_id) :
-  _worker_time(NULL), _start_time(os::elapsedTime()), _worker_id(worker_id) {
-  assert (phase_times != NULL, "Invariant");
+#define ASSERT_REF_TYPE(ref_type) assert((ref_type) >= REF_SOFT && (ref_type) <= REF_PHANTOM, \
+                                         "Invariant (%d)", (int)ref_type)
+
+#define ASSERT_PHASE(phase) assert((phase) >= ReferenceProcessor::RefPhase1 && \
+                                   (phase) < ReferenceProcessor::RefPhaseMax,  \
+                                   "Invariant (%d)", (int)phase);
+
+#define ASSERT_SUB_PHASE(phase) assert((phase) >= ReferenceProcessor::SoftRefSubPhase1 && \
+                                       (phase) < ReferenceProcessor::RefSubPhaseMax, \
+                                       "Invariant (%d)", (int)phase);
+
+static const char* SubPhasesParWorkTitle[ReferenceProcessor::RefSubPhaseMax] = {
+       "SoftRef (ms):",
+       "SoftRef (ms):",
+       "WeakRef (ms):",
+       "FinalRef (ms):",
+       "FinalRef (ms):",
+       "PhantomRef (ms):"
+       };
+
+static const char* Phase2ParWorkTitle = "Total (ms):";
 
-  _worker_time = phase_times->worker_time_sec(phase_times->par_phase(number));
+static const char* SubPhasesSerWorkTitle[ReferenceProcessor::RefSubPhaseMax] = {
+       "SoftRef:",
+       "SoftRef:",
+       "WeakRef:",
+       "FinalRef:",
+       "FinalRef:",
+       "PhantomRef:"
+       };
+
+static const char* Phase2SerWorkTitle = "Total:";
+
+static const char* Indents[6] = {"", "  ", "    ", "      ", "        ", "          "};
+
+static const char* PhaseNames[ReferenceProcessor::RefPhaseMax] = {
+       "Reconsider SoftReferences",
+       "Notify Soft/WeakReferences",
+       "Notify and keep alive finalizable",
+       "Notify PhantomReferences"
+       };
+
+static const char* ReferenceTypeNames[REF_PHANTOM + 1] = {
+       "None", "Other", "SoftReference", "WeakReference", "FinalReference", "PhantomReference"
+       };
+
+STATIC_ASSERT((REF_PHANTOM + 1) == ARRAY_SIZE(ReferenceTypeNames));
+
+static const char* phase_enum_2_phase_string(ReferenceProcessor::RefProcPhases phase) {
+  assert(phase >= ReferenceProcessor::RefPhase1 && phase <= ReferenceProcessor::RefPhaseMax,
+         "Invalid reference processing phase (%d)", phase);
+  return PhaseNames[phase];
 }
 
-RefProcWorkerTimeTracker::RefProcWorkerTimeTracker(ReferenceProcessorPhaseTimes::RefProcParPhases phase,
-                                                   ReferenceProcessorPhaseTimes* phase_times,
-                                                   uint worker_id) :
-  _worker_time(NULL), _start_time(os::elapsedTime()), _worker_id(worker_id) {
-  assert (phase_times != NULL, "Invariant");
+static const char* ref_type_2_string(ReferenceType ref_type) {
+  ASSERT_REF_TYPE(ref_type);
+  return ReferenceTypeNames[ref_type];
+}
 
-  _worker_time = phase_times->worker_time_sec(phase);
+RefProcWorkerTimeTracker::RefProcWorkerTimeTracker(WorkerDataArray<double>* worker_time, uint worker_id) :
+  _worker_time(worker_time), _start_time(os::elapsedTime()), _worker_id(worker_id) {
+  assert(worker_time != NULL, "Invariant");
 }
 
 RefProcWorkerTimeTracker::~RefProcWorkerTimeTracker() {
-  _worker_time->set(_worker_id, os::elapsedTime() - _start_time);
+  double result = os::elapsedTime() - _start_time;
+  _worker_time->set(_worker_id, result);
+}
+
+RefProcSubPhasesWorkerTimeTracker::RefProcSubPhasesWorkerTimeTracker(ReferenceProcessor::RefProcSubPhases phase,
+                                                                     ReferenceProcessorPhaseTimes* phase_times,
+                                                                     uint worker_id) :
+  RefProcWorkerTimeTracker(phase_times->sub_phase_worker_time_sec(phase), worker_id) {
+}
+
+RefProcSubPhasesWorkerTimeTracker::~RefProcSubPhasesWorkerTimeTracker() {
 }
 
 RefProcPhaseTimeBaseTracker::RefProcPhaseTimeBaseTracker(const char* title,
+                                                         ReferenceProcessor::RefProcPhases phase_number,
                                                          ReferenceProcessorPhaseTimes* phase_times) :
-  _title(title), _phase_times(phase_times), _start_ticks(), _end_ticks() {
+  _phase_times(phase_times), _start_ticks(), _end_ticks(), _phase_number(phase_number) {
   assert(_phase_times != NULL, "Invariant");
 
   _start_ticks.stamp();
   if (_phase_times->gc_timer() != NULL) {
-    _phase_times->gc_timer()->register_gc_phase_start(_title, _start_ticks);
+    _phase_times->gc_timer()->register_gc_phase_start(title, _start_ticks);
   }
 }
 
-static const char* phase_enum_2_phase_string(ReferenceProcessorPhaseTimes::RefProcParPhases phase) {
-  switch(phase) {
-    case ReferenceProcessorPhaseTimes::SoftRefPhase1:
-      return "Phase1";
-    case ReferenceProcessorPhaseTimes::SoftRefPhase2:
-    case ReferenceProcessorPhaseTimes::WeakRefPhase2:
-    case ReferenceProcessorPhaseTimes::FinalRefPhase2:
-    case ReferenceProcessorPhaseTimes::PhantomRefPhase2:
-      return "Phase2";
-    case ReferenceProcessorPhaseTimes::SoftRefPhase3:
-    case ReferenceProcessorPhaseTimes::WeakRefPhase3:
-    case ReferenceProcessorPhaseTimes::FinalRefPhase3:
-    case ReferenceProcessorPhaseTimes::PhantomRefPhase3:
-      return "Phase3";
-    default:
-      ShouldNotReachHere();
-      return NULL;
-  }
-}
-
-static const char* Indents[6] = {"", "  ", "    ", "      ", "        ", "          "};
-
 Ticks RefProcPhaseTimeBaseTracker::end_ticks() {
   // If ASSERT is defined, the default value of Ticks will be -2.
   if (_end_ticks.value() <= 0) {
@@ -108,140 +143,83 @@
   }
 }
 
-RefProcBalanceQueuesTimeTracker::RefProcBalanceQueuesTimeTracker(ReferenceProcessorPhaseTimes* phase_times) :
-  RefProcPhaseTimeBaseTracker("Balance queues", phase_times) {}
+RefProcBalanceQueuesTimeTracker::RefProcBalanceQueuesTimeTracker(ReferenceProcessor::RefProcPhases phase_number,
+                                                                 ReferenceProcessorPhaseTimes* phase_times) :
+  RefProcPhaseTimeBaseTracker("Balance queues", phase_number, phase_times) {}
 
 RefProcBalanceQueuesTimeTracker::~RefProcBalanceQueuesTimeTracker() {
   double elapsed = elapsed_time();
-  phase_times()->set_balance_queues_time_ms(phase_times()->processing_ref_type(), elapsed);
+  phase_times()->set_balance_queues_time_ms(_phase_number, elapsed);
 }
 
-#define ASSERT_REF_TYPE(ref_type) assert(ref_type >= REF_SOFT && ref_type <= REF_PHANTOM, \
-                                         "Invariant (%d)", (int)ref_type)
-
-#define ASSERT_PHASE_NUMBER(phase_number) assert(phase_number >= ReferenceProcessorPhaseTimes::RefPhase1 && \
-                                                 phase_number <= ReferenceProcessorPhaseTimes::RefPhaseMax, \
-                                                 "Invariant (%d)", phase_number);
-
-static const char* phase_number_2_string(ReferenceProcessorPhaseTimes::RefProcPhaseNumbers phase_number) {
-  ASSERT_PHASE_NUMBER(phase_number);
-
-  switch(phase_number) {
-    case ReferenceProcessorPhaseTimes::RefPhase1:
-      return "Phase1";
-    case ReferenceProcessorPhaseTimes::RefPhase2:
-      return "Phase2";
-    case ReferenceProcessorPhaseTimes::RefPhase3:
-      return "Phase3";
-    default:
-      ShouldNotReachHere();
-      return NULL;
-  }
-}
-
-RefProcParPhaseTimeTracker::RefProcParPhaseTimeTracker(ReferenceProcessorPhaseTimes::RefProcPhaseNumbers phase_number,
+RefProcPhaseTimeTracker::RefProcPhaseTimeTracker(ReferenceProcessor::RefProcPhases phase_number,
                                                        ReferenceProcessorPhaseTimes* phase_times) :
-  _phase_number(phase_number),
-  RefProcPhaseTimeBaseTracker(phase_number_2_string(phase_number), phase_times) {}
-
-RefProcParPhaseTimeTracker::~RefProcParPhaseTimeTracker() {
-  double elapsed = elapsed_time();
-  ReferenceProcessorPhaseTimes::RefProcParPhases phase = phase_times()->par_phase(_phase_number);
-  phase_times()->set_par_phase_time_ms(phase, elapsed);
+  RefProcPhaseTimeBaseTracker(phase_enum_2_phase_string(phase_number), phase_number, phase_times) {
 }
 
-static const char* ref_type_2_string(ReferenceType ref_type) {
-  ASSERT_REF_TYPE(ref_type);
-
-  switch(ref_type) {
-    case REF_SOFT:
-      return "SoftReference";
-    case REF_WEAK:
-      return "WeakReference";
-    case REF_FINAL:
-      return "FinalReference";
-    case REF_PHANTOM:
-      return "PhantomReference";
-    default:
-      ShouldNotReachHere();
-      return NULL;
-  }
+RefProcPhaseTimeTracker::~RefProcPhaseTimeTracker() {
+  double elapsed = elapsed_time();
+  phase_times()->set_phase_time_ms(_phase_number, elapsed);
 }
 
-RefProcPhaseTimesTracker::RefProcPhaseTimesTracker(ReferenceType ref_type,
-                                                   ReferenceProcessorPhaseTimes* phase_times,
-                                                   ReferenceProcessor* rp) :
-  _rp(rp), RefProcPhaseTimeBaseTracker(ref_type_2_string(ref_type), phase_times) {
-  phase_times->set_processing_ref_type(ref_type);
-
-  size_t discovered = rp->total_reference_count(ref_type);
-  phase_times->set_ref_discovered(ref_type, discovered);
+RefProcTotalPhaseTimesTracker::RefProcTotalPhaseTimesTracker(ReferenceProcessor::RefProcPhases phase_number,
+                                                             ReferenceProcessorPhaseTimes* phase_times,
+                                                             ReferenceProcessor* rp) :
+  _rp(rp), RefProcPhaseTimeBaseTracker(phase_enum_2_phase_string(phase_number), phase_number, phase_times) {
 }
 
-RefProcPhaseTimesTracker::~RefProcPhaseTimesTracker() {
+RefProcTotalPhaseTimesTracker::~RefProcTotalPhaseTimesTracker() {
   double elapsed = elapsed_time();
-  ReferenceProcessorPhaseTimes* times = phase_times();
-  ReferenceType ref_type = times->processing_ref_type();
-  times->set_ref_proc_time_ms(ref_type, elapsed);
-
-  size_t after_count = _rp->total_reference_count(ref_type);
-  size_t discovered = times->ref_discovered(ref_type);
-  times->set_ref_cleared(ref_type, discovered - after_count);
+  phase_times()->set_phase_time_ms(_phase_number, elapsed);
 }
 
 ReferenceProcessorPhaseTimes::ReferenceProcessorPhaseTimes(GCTimer* gc_timer, uint max_gc_threads) :
   _gc_timer(gc_timer), _processing_is_mt(false) {
 
-  for (int i = 0; i < RefParPhaseMax; i++) {
-    _worker_time_sec[i] = new WorkerDataArray<double>(max_gc_threads, "Process lists (ms)");
-    _par_phase_time_ms[i] = uninitialized();
+  for (uint i = 0; i < ReferenceProcessor::RefSubPhaseMax; i++) {
+    _sub_phases_worker_time_sec[i] = new WorkerDataArray<double>(max_gc_threads, SubPhasesParWorkTitle[i]);
   }
+  _phase2_worker_time_sec = new WorkerDataArray<double>(max_gc_threads, Phase2ParWorkTitle);
 
-  for (int i = 0; i < number_of_subclasses_of_ref; i++) {
-    _ref_proc_time_ms[i] = uninitialized();
-    _balance_queues_time_ms[i] = uninitialized();
-    _ref_cleared[i] = 0;
-    _ref_discovered[i] = 0;
-    _ref_enqueued[i] = 0;
-  }
+  reset();
 }
 
 inline int ref_type_2_index(ReferenceType ref_type) {
   return ref_type - REF_SOFT;
 }
 
-#define ASSERT_PAR_PHASE(phase) assert(phase >= ReferenceProcessorPhaseTimes::SoftRefPhase1 && \
-                                       phase < ReferenceProcessorPhaseTimes::RefParPhaseMax, \
-                                       "Invariant (%d)", (int)phase);
-
-WorkerDataArray<double>* ReferenceProcessorPhaseTimes::worker_time_sec(RefProcParPhases par_phase) const {
-  ASSERT_PAR_PHASE(par_phase);
-  return _worker_time_sec[par_phase];
+WorkerDataArray<double>* ReferenceProcessorPhaseTimes::sub_phase_worker_time_sec(ReferenceProcessor::RefProcSubPhases sub_phase) const {
+  ASSERT_SUB_PHASE(sub_phase);
+  return _sub_phases_worker_time_sec[sub_phase];
 }
 
-double ReferenceProcessorPhaseTimes::par_phase_time_ms(RefProcParPhases par_phase) const {
-  ASSERT_PAR_PHASE(par_phase);
-  return _par_phase_time_ms[par_phase];
+double ReferenceProcessorPhaseTimes::phase_time_ms(ReferenceProcessor::RefProcPhases phase) const {
+  ASSERT_PHASE(phase);
+  return _phases_time_ms[phase];
 }
 
-void ReferenceProcessorPhaseTimes::set_par_phase_time_ms(RefProcParPhases par_phase,
-                                                         double par_phase_time_ms) {
-  ASSERT_PAR_PHASE(par_phase);
-  _par_phase_time_ms[par_phase] = par_phase_time_ms;
+void ReferenceProcessorPhaseTimes::set_phase_time_ms(ReferenceProcessor::RefProcPhases phase,
+                                                     double phase_time_ms) {
+  ASSERT_PHASE(phase);
+  _phases_time_ms[phase] = phase_time_ms;
 }
 
 void ReferenceProcessorPhaseTimes::reset() {
-  for (int i = 0; i < RefParPhaseMax; i++) {
-    _worker_time_sec[i]->reset();
-    _par_phase_time_ms[i] = uninitialized();
+  for (int i = 0; i < ReferenceProcessor::RefSubPhaseMax; i++) {
+    _sub_phases_worker_time_sec[i]->reset();
+    _sub_phases_total_time_ms[i] = uninitialized();
   }
 
+  for (int i = 0; i < ReferenceProcessor::RefPhaseMax; i++) {
+    _phases_time_ms[i] = uninitialized();
+    _balance_queues_time_ms[i] = uninitialized();
+  }
+
+  _phase2_worker_time_sec->reset();
+
   for (int i = 0; i < number_of_subclasses_of_ref; i++) {
-    _ref_proc_time_ms[i] = uninitialized();
-    _balance_queues_time_ms[i] = uninitialized();
     _ref_cleared[i] = 0;
     _ref_discovered[i] = 0;
-    _ref_enqueued[i] = 0;
   }
 
   _total_time_ms = uninitialized();
@@ -250,35 +228,26 @@
 }
 
 ReferenceProcessorPhaseTimes::~ReferenceProcessorPhaseTimes() {
-  for (int i = 0; i < RefParPhaseMax; i++) {
-    delete _worker_time_sec[i];
+  for (int i = 0; i < ReferenceProcessor::RefSubPhaseMax; i++) {
+    delete _sub_phases_worker_time_sec[i];
   }
-}
-
-double ReferenceProcessorPhaseTimes::ref_proc_time_ms(ReferenceType ref_type) const {
-  ASSERT_REF_TYPE(ref_type);
-  return _ref_proc_time_ms[ref_type_2_index(ref_type)];
+  delete _phase2_worker_time_sec;
 }
 
-void ReferenceProcessorPhaseTimes::set_ref_proc_time_ms(ReferenceType ref_type,
-                                                        double ref_proc_time_ms) {
-  ASSERT_REF_TYPE(ref_type);
-  _ref_proc_time_ms[ref_type_2_index(ref_type)] = ref_proc_time_ms;
+double ReferenceProcessorPhaseTimes::sub_phase_total_time_ms(ReferenceProcessor::RefProcSubPhases sub_phase) const {
+  ASSERT_SUB_PHASE(sub_phase);
+  return _sub_phases_total_time_ms[sub_phase];
 }
 
-size_t ReferenceProcessorPhaseTimes::ref_cleared(ReferenceType ref_type) const {
-  ASSERT_REF_TYPE(ref_type);
-  return _ref_cleared[ref_type_2_index(ref_type)];
+void ReferenceProcessorPhaseTimes::set_sub_phase_total_phase_time_ms(ReferenceProcessor::RefProcSubPhases sub_phase,
+                                                                     double time_ms) {
+  ASSERT_SUB_PHASE(sub_phase);
+  _sub_phases_total_time_ms[sub_phase] = time_ms;
 }
 
-void ReferenceProcessorPhaseTimes::set_ref_cleared(ReferenceType ref_type, size_t count) {
+void ReferenceProcessorPhaseTimes::add_ref_cleared(ReferenceType ref_type, size_t count) {
   ASSERT_REF_TYPE(ref_type);
-  _ref_cleared[ref_type_2_index(ref_type)] = count;
-}
-
-size_t ReferenceProcessorPhaseTimes::ref_discovered(ReferenceType ref_type) const {
-  ASSERT_REF_TYPE(ref_type);
-  return _ref_discovered[ref_type_2_index(ref_type)];
+  Atomic::add(count, &_ref_cleared[ref_type_2_index(ref_type)]);
 }
 
 void ReferenceProcessorPhaseTimes::set_ref_discovered(ReferenceType ref_type, size_t count) {
@@ -286,70 +255,14 @@
   _ref_discovered[ref_type_2_index(ref_type)] = count;
 }
 
-size_t ReferenceProcessorPhaseTimes::ref_enqueued(ReferenceType ref_type) const {
-  ASSERT_REF_TYPE(ref_type);
-  return _ref_enqueued[ref_type_2_index(ref_type)];
-}
-
-void ReferenceProcessorPhaseTimes::set_ref_enqueued(ReferenceType ref_type, size_t count) {
-  ASSERT_REF_TYPE(ref_type);
-  _ref_enqueued[ref_type_2_index(ref_type)] = count;
-}
-
-double ReferenceProcessorPhaseTimes::balance_queues_time_ms(ReferenceType ref_type) const {
-  ASSERT_REF_TYPE(ref_type);
-  return _balance_queues_time_ms[ref_type_2_index(ref_type)];
-}
-
-void ReferenceProcessorPhaseTimes::set_balance_queues_time_ms(ReferenceType ref_type, double time_ms) {
-  ASSERT_REF_TYPE(ref_type);
-  _balance_queues_time_ms[ref_type_2_index(ref_type)] = time_ms;
+double ReferenceProcessorPhaseTimes::balance_queues_time_ms(ReferenceProcessor::RefProcPhases phase) const {
+  ASSERT_PHASE(phase);
+  return _balance_queues_time_ms[phase];
 }
 
-ReferenceProcessorPhaseTimes::RefProcParPhases
-ReferenceProcessorPhaseTimes::par_phase(RefProcPhaseNumbers phase_number) const {
-  ASSERT_PHASE_NUMBER(phase_number);
-  ASSERT_REF_TYPE(_processing_ref_type);
-
-  int result = SoftRefPhase1;
-
-  switch(_processing_ref_type) {
-    case REF_SOFT:
-      result = (int)SoftRefPhase1;
-      result += phase_number;
-
-      assert((RefProcParPhases)result >= SoftRefPhase1 &&
-             (RefProcParPhases)result <= SoftRefPhase3,
-             "Invariant (%d)", result);
-      break;
-    case REF_WEAK:
-      result = (int)WeakRefPhase2;
-      result += (phase_number - 1);
-      assert((RefProcParPhases)result >= WeakRefPhase2 &&
-             (RefProcParPhases)result <= WeakRefPhase3,
-             "Invariant (%d)", result);
-      break;
-    case REF_FINAL:
-      result = (int)FinalRefPhase2;
-      result += (phase_number - 1);
-      assert((RefProcParPhases)result >= FinalRefPhase2 &&
-             (RefProcParPhases)result <= FinalRefPhase3,
-             "Invariant (%d)", result);
-      break;
-    case REF_PHANTOM:
-      result = (int)PhantomRefPhase2;
-      result += (phase_number - 1);
-      assert((RefProcParPhases)result >= PhantomRefPhase2 &&
-             (RefProcParPhases)result <= PhantomRefPhase3,
-             "Invariant (%d)", result);
-      break;
-    default:
-      ShouldNotReachHere();
-  }
-
-  ASSERT_PAR_PHASE(result);
-
-  return (RefProcParPhases)result;
+void ReferenceProcessorPhaseTimes::set_balance_queues_time_ms(ReferenceProcessor::RefProcPhases phase, double time_ms) {
+  ASSERT_PHASE(phase);
+  _balance_queues_time_ms[phase] = time_ms;
 }
 
 #define TIME_FORMAT "%.1lfms"
@@ -366,10 +279,16 @@
   }
 
   uint next_indent = base_indent + 1;
+  print_phase(ReferenceProcessor::RefPhase1, next_indent);
+  print_phase(ReferenceProcessor::RefPhase2, next_indent);
+  print_phase(ReferenceProcessor::RefPhase3, next_indent);
+  print_phase(ReferenceProcessor::RefPhase4, next_indent);
+
   print_reference(REF_SOFT, next_indent);
   print_reference(REF_WEAK, next_indent);
   print_reference(REF_FINAL, next_indent);
   print_reference(REF_PHANTOM, next_indent);
+
 }
 
 void ReferenceProcessorPhaseTimes::print_reference(ReferenceType ref_type, uint base_indent) const {
@@ -377,73 +296,99 @@
 
   if (lt.is_enabled()) {
     LogStream ls(lt);
-    uint next_indent = base_indent + 1;
     ResourceMark rm;
 
-    ls.print_cr("%s%s: " TIME_FORMAT,
-                Indents[base_indent], ref_type_2_string(ref_type), ref_proc_time_ms(ref_type));
+    ls.print_cr("%s%s:", Indents[base_indent], ref_type_2_string(ref_type));
+
+    uint const next_indent = base_indent + 1;
+    int const ref_type_index = ref_type_2_index(ref_type);
+
+    ls.print_cr("%sDiscovered: " SIZE_FORMAT, Indents[next_indent], _ref_discovered[ref_type_index]);
+    ls.print_cr("%sCleared: " SIZE_FORMAT, Indents[next_indent], _ref_cleared[ref_type_index]);
+  }
+}
+
+void ReferenceProcessorPhaseTimes::print_phase(ReferenceProcessor::RefProcPhases phase, uint indent) const {
+  double phase_time = phase_time_ms(phase);
 
-    double balance_time = balance_queues_time_ms(ref_type);
-    if (balance_time != uninitialized()) {
-      ls.print_cr("%s%s " TIME_FORMAT, Indents[next_indent], "Balance queues:", balance_time);
+  if (phase_time == uninitialized()) {
+    return;
+  }
+
+  LogTarget(Debug, gc, phases, ref) lt;
+  LogStream ls(lt);
+
+  ls.print_cr("%s%s%s " TIME_FORMAT,
+              Indents[indent],
+              phase_enum_2_phase_string(phase),
+              indent == 0 ? "" : ":", /* 0 indent logs don't need colon. */
+              phase_time);
+
+  LogTarget(Debug, gc, phases, ref) lt2;
+  if (lt2.is_enabled()) {
+    LogStream ls(lt2);
+
+    if (_processing_is_mt) {
+      print_balance_time(&ls, phase, indent + 1);
     }
 
-    switch(ref_type) {
-      case REF_SOFT:
-        print_phase(SoftRefPhase1, next_indent);
-        print_phase(SoftRefPhase2, next_indent);
-        print_phase(SoftRefPhase3, next_indent);
-        break;
-
-      case REF_WEAK:
-        print_phase(WeakRefPhase2, next_indent);
-        print_phase(WeakRefPhase3, next_indent);
+    switch (phase) {
+      case ReferenceProcessor::RefPhase1:
+        print_sub_phase(&ls, ReferenceProcessor::SoftRefSubPhase1, indent + 1);
         break;
-
-      case REF_FINAL:
-        print_phase(FinalRefPhase2, next_indent);
-        print_phase(FinalRefPhase3, next_indent);
+      case ReferenceProcessor::RefPhase2:
+        print_sub_phase(&ls, ReferenceProcessor::SoftRefSubPhase2, indent + 1);
+        print_sub_phase(&ls, ReferenceProcessor::WeakRefSubPhase2, indent + 1);
+        print_sub_phase(&ls, ReferenceProcessor::FinalRefSubPhase2, indent + 1);
         break;
-
-      case REF_PHANTOM:
-        print_phase(PhantomRefPhase2, next_indent);
-        print_phase(PhantomRefPhase3, next_indent);
+      case ReferenceProcessor::RefPhase3:
+        print_sub_phase(&ls, ReferenceProcessor::FinalRefSubPhase3, indent + 1);
         break;
-
+      case ReferenceProcessor::RefPhase4:
+        print_sub_phase(&ls, ReferenceProcessor::PhantomRefSubPhase4, indent + 1);
+        break;
       default:
         ShouldNotReachHere();
     }
+    if (phase == ReferenceProcessor::RefPhase2) {
+      print_worker_time(&ls, _phase2_worker_time_sec, Phase2SerWorkTitle, indent + 1);
+    }
+  }
+}
 
-    ls.print_cr("%s%s " SIZE_FORMAT, Indents[next_indent], "Discovered:", ref_discovered(ref_type));
-    ls.print_cr("%s%s " SIZE_FORMAT, Indents[next_indent], "Cleared:", ref_cleared(ref_type));
+void ReferenceProcessorPhaseTimes::print_balance_time(LogStream* ls, ReferenceProcessor::RefProcPhases phase, uint indent) const {
+  double balance_time = balance_queues_time_ms(phase);
+  if (balance_time != uninitialized()) {
+    ls->print_cr("%s%s " TIME_FORMAT, Indents[indent], "Balance queues:", balance_time);
   }
 }
 
-void ReferenceProcessorPhaseTimes::print_phase(RefProcParPhases phase, uint indent) const {
-  double phase_time = par_phase_time_ms(phase);
-  if (phase_time != uninitialized()) {
-    LogTarget(Debug, gc, phases, ref) lt;
-
-    LogStream ls(lt);
+void ReferenceProcessorPhaseTimes::print_sub_phase(LogStream* ls, ReferenceProcessor::RefProcSubPhases sub_phase, uint indent) const {
+  print_worker_time(ls, _sub_phases_worker_time_sec[sub_phase], SubPhasesSerWorkTitle[sub_phase], indent);
+}
 
-    ls.print_cr("%s%s%s " TIME_FORMAT,
-                Indents[indent],
-                phase_enum_2_phase_string(phase),
-                indent == 0 ? "" : ":", /* 0 indent logs don't need colon. */
-                phase_time);
-
-    LogTarget(Trace, gc, phases, ref) lt2;
-    if (_processing_is_mt && lt2.is_enabled()) {
-      LogStream ls(lt2);
-
-      ls.print("%s", Indents[indent + 1]);
-      // worker_time_sec is recorded in seconds but it will be printed in milliseconds.
-      worker_time_sec(phase)->print_summary_on(&ls, true);
+void ReferenceProcessorPhaseTimes::print_worker_time(LogStream* ls, WorkerDataArray<double>* worker_time, const char* ser_title, uint indent) const {
+  ls->print("%s", Indents[indent]);
+  if (_processing_is_mt) {
+    worker_time->print_summary_on(ls, true);
+    LogTarget(Trace, gc, phases, task) lt;
+    if (lt.is_enabled()) {
+      LogStream ls2(lt);
+      ls2.print("%s", Indents[indent]);
+      worker_time->print_details_on(&ls2);
+    }
+  } else {
+    if (worker_time->get(0) != uninitialized()) {
+      ls->print_cr("%s " TIME_FORMAT,
+                   ser_title,
+                   worker_time->get(0) * MILLIUNITS);
+    } else {
+      ls->print_cr("%s skipped", ser_title);
     }
   }
 }
 
 #undef ASSERT_REF_TYPE
-#undef ASSERT_PHASE_NUMBER
-#undef ASSERT_PAR_PHASE
+#undef ASSERT_SUB_PHASE
+#undef ASSERT_PHASE
 #undef TIME_FORMAT
--- a/src/hotspot/share/gc/shared/referenceProcessorPhaseTimes.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/referenceProcessorPhaseTimes.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -25,108 +25,76 @@
 #ifndef SHARE_VM_GC_SHARED_REFERENCEPROCESSORPHASETIMES_HPP
 #define SHARE_VM_GC_SHARED_REFERENCEPROCESSORPHASETIMES_HPP
 
+#include "gc/shared/referenceProcessor.hpp"
 #include "gc/shared/referenceProcessorStats.hpp"
 #include "gc/shared/workerDataArray.hpp"
+#include "memory/allocation.hpp"
 #include "memory/referenceType.hpp"
 #include "utilities/ticks.hpp"
 
 class DiscoveredList;
 class GCTimer;
+class LogStream;
 
 class ReferenceProcessorPhaseTimes : public CHeapObj<mtGC> {
-public:
-  // Detailed phases that has parallel work.
-  enum RefProcParPhases {
-    SoftRefPhase1,
-    SoftRefPhase2,
-    SoftRefPhase3,
-    WeakRefPhase2,
-    WeakRefPhase3,
-    FinalRefPhase2,
-    FinalRefPhase3,
-    PhantomRefPhase2,
-    PhantomRefPhase3,
-    RefParPhaseMax
-  };
-
-  // Sub-phases that are used when processing each j.l.Reference types.
-  // Only SoftReference has RefPhase1.
-  enum RefProcPhaseNumbers {
-    RefPhase1,
-    RefPhase2,
-    RefPhase3,
-    RefPhaseMax
-  };
-
-private:
   static const int number_of_subclasses_of_ref = REF_PHANTOM - REF_OTHER; // 5 - 1 = 4
 
-  // Records per thread information of each phase.
-  WorkerDataArray<double>* _worker_time_sec[RefParPhaseMax];
-  // Records elapsed time of each phase.
-  double                   _par_phase_time_ms[RefParPhaseMax];
+  // Records per thread time information of each sub phase.
+  WorkerDataArray<double>* _sub_phases_worker_time_sec[ReferenceProcessor::RefSubPhaseMax];
+  // Total time of each sub phase.
+  double                   _sub_phases_total_time_ms[ReferenceProcessor::RefSubPhaseMax];
 
-  // Total spent time for references.
-  // e.g. _ref_proc_time_ms[0] = _par_phase_time_ms[SoftRefPhase1] +
-  //                             _par_phase_time_ms[SoftRefPhase2] +
-  //                             _par_phase_time_ms[SoftRefPhase3] + extra time.
-  double                   _ref_proc_time_ms[number_of_subclasses_of_ref];
+  // Records total elapsed time for each phase.
+  double                   _phases_time_ms[ReferenceProcessor::RefPhaseMax];
+  // Records total queue balancing for each phase.
+  double                   _balance_queues_time_ms[ReferenceProcessor::RefPhaseMax];
 
+  WorkerDataArray<double>* _phase2_worker_time_sec;
+
+  // Total spent time for reference processing.
   double                   _total_time_ms;
 
   size_t                   _ref_cleared[number_of_subclasses_of_ref];
   size_t                   _ref_discovered[number_of_subclasses_of_ref];
-  size_t                   _ref_enqueued[number_of_subclasses_of_ref];
-  double                   _balance_queues_time_ms[number_of_subclasses_of_ref];
 
   bool                     _processing_is_mt;
 
-  // Currently processing reference type.
-  ReferenceType            _processing_ref_type;
-
   GCTimer*                 _gc_timer;
 
-  double par_phase_time_ms(RefProcParPhases phase) const;
-  double ref_proc_time_ms(ReferenceType ref_type) const;
+  double phase_time_ms(ReferenceProcessor::RefProcPhases phase) const;
+  double sub_phase_total_time_ms(ReferenceProcessor::RefProcSubPhases sub_phase) const;
 
   double total_time_ms() const { return _total_time_ms; }
 
-  size_t ref_cleared(ReferenceType ref_type) const;
-  size_t ref_enqueued(ReferenceType ref_type) const;
-
-  double balance_queues_time_ms(ReferenceType ref_type) const;
+  double balance_queues_time_ms(ReferenceProcessor::RefProcPhases phase) const;
 
   void print_reference(ReferenceType ref_type, uint base_indent) const;
-  void print_phase(RefProcParPhases phase, uint indent) const;
 
+  void print_phase(ReferenceProcessor::RefProcPhases phase, uint indent) const;
+  void print_balance_time(LogStream* ls, ReferenceProcessor::RefProcPhases phase, uint indent) const;
+  void print_sub_phase(LogStream* ls, ReferenceProcessor::RefProcSubPhases sub_phase, uint indent) const;
+  void print_worker_time(LogStream* ls, WorkerDataArray<double>* worker_time, const char* ser_title, uint indent) const;
+
+  static double uninitialized() { return -1.0; }
 public:
   ReferenceProcessorPhaseTimes(GCTimer* gc_timer, uint max_gc_threads);
   ~ReferenceProcessorPhaseTimes();
 
-  static double uninitialized() { return -1.0; }
+  WorkerDataArray<double>* phase2_worker_time_sec() const { return _phase2_worker_time_sec; }
+  WorkerDataArray<double>* sub_phase_worker_time_sec(ReferenceProcessor::RefProcSubPhases phase) const;
+  void set_phase_time_ms(ReferenceProcessor::RefProcPhases phase, double par_phase_time_ms);
 
-  WorkerDataArray<double>* worker_time_sec(RefProcParPhases phase) const;
-  void set_par_phase_time_ms(RefProcParPhases phase, double par_phase_time_ms);
-
-  void set_ref_proc_time_ms(ReferenceType ref_type, double ref_proc_time_ms);
+  void set_sub_phase_total_phase_time_ms(ReferenceProcessor::RefProcSubPhases sub_phase, double ref_proc_time_ms);
 
   void set_total_time_ms(double total_time_ms) { _total_time_ms = total_time_ms; }
 
-  void set_ref_cleared(ReferenceType ref_type, size_t count);
-  size_t ref_discovered(ReferenceType ref_type) const;
+  void add_ref_cleared(ReferenceType ref_type, size_t count);
   void set_ref_discovered(ReferenceType ref_type, size_t count);
-  void set_ref_enqueued(ReferenceType ref_type, size_t count);
 
-  void set_balance_queues_time_ms(ReferenceType ref_type, double time_ms);
+  void set_balance_queues_time_ms(ReferenceProcessor::RefProcPhases phase, double time_ms);
 
   void set_processing_is_mt(bool processing_is_mt) { _processing_is_mt = processing_is_mt; }
 
-  ReferenceType processing_ref_type() const { return _processing_ref_type; }
-  void set_processing_ref_type(ReferenceType processing_ref_type) { _processing_ref_type = processing_ref_type; }
-
-  // Returns RefProcParPhases calculated from phase_number and _processing_ref_type.
-  RefProcParPhases par_phase(RefProcPhaseNumbers phase_number) const;
-
   GCTimer* gc_timer() const { return _gc_timer; }
 
   // Reset all fields. If not reset at next cycle, an assertion will fail.
@@ -135,38 +103,40 @@
   void print_all_references(uint base_indent = 0, bool print_total = true) const;
 };
 
-// Updates working time of each worker thread.
-class RefProcWorkerTimeTracker : public StackObj {
+class RefProcWorkerTimeTracker : public CHeapObj<mtGC> {
 protected:
   WorkerDataArray<double>* _worker_time;
   double                   _start_time;
   uint                     _worker_id;
-
 public:
-  RefProcWorkerTimeTracker(ReferenceProcessorPhaseTimes::RefProcPhaseNumbers number,
-                           ReferenceProcessorPhaseTimes* phase_times,
-                           uint worker_id);
-  RefProcWorkerTimeTracker(ReferenceProcessorPhaseTimes::RefProcParPhases phase,
-                           ReferenceProcessorPhaseTimes* phase_times,
-                           uint worker_id);
-  ~RefProcWorkerTimeTracker();
+  RefProcWorkerTimeTracker(WorkerDataArray<double>* worker_time, uint worker_id);
+  virtual ~RefProcWorkerTimeTracker();
+};
+
+// Updates working time of each worker thread for a given sub phase.
+class RefProcSubPhasesWorkerTimeTracker : public RefProcWorkerTimeTracker {
+public:
+  RefProcSubPhasesWorkerTimeTracker(ReferenceProcessor::RefProcSubPhases phase,
+                                    ReferenceProcessorPhaseTimes* phase_times,
+                                    uint worker_id);
+  ~RefProcSubPhasesWorkerTimeTracker();
 };
 
 class RefProcPhaseTimeBaseTracker : public StackObj {
 protected:
-  const char*                   _title;
   ReferenceProcessorPhaseTimes* _phase_times;
   Ticks                         _start_ticks;
   Ticks                         _end_ticks;
 
+  ReferenceProcessor::RefProcPhases _phase_number;
+
   Ticks end_ticks();
   double elapsed_time();
   ReferenceProcessorPhaseTimes* phase_times() const { return _phase_times; }
-  // Print phase elapsed time with each worker information if MT processed.
-  void print_phase(ReferenceProcessorPhaseTimes::RefProcParPhases phase, uint indent);
 
 public:
   RefProcPhaseTimeBaseTracker(const char* title,
+                              ReferenceProcessor::RefProcPhases _phase_number,
                               ReferenceProcessorPhaseTimes* phase_times);
   ~RefProcPhaseTimeBaseTracker();
 };
@@ -175,30 +145,27 @@
 // save it into GCTimer.
 class RefProcBalanceQueuesTimeTracker : public RefProcPhaseTimeBaseTracker {
 public:
-  RefProcBalanceQueuesTimeTracker(ReferenceProcessorPhaseTimes* phase_times);
+  RefProcBalanceQueuesTimeTracker(ReferenceProcessor::RefProcPhases phase_number,
+                                  ReferenceProcessorPhaseTimes* phase_times);
   ~RefProcBalanceQueuesTimeTracker();
 };
 
 // Updates phase time at ReferenceProcessorPhaseTimes and save it into GCTimer.
-class RefProcParPhaseTimeTracker : public RefProcPhaseTimeBaseTracker {
-  ReferenceProcessorPhaseTimes::RefProcPhaseNumbers _phase_number;
-
+class RefProcPhaseTimeTracker : public RefProcPhaseTimeBaseTracker {
 public:
-  RefProcParPhaseTimeTracker(ReferenceProcessorPhaseTimes::RefProcPhaseNumbers phase_number,
-                             ReferenceProcessorPhaseTimes* phase_times);
-  ~RefProcParPhaseTimeTracker();
+  RefProcPhaseTimeTracker(ReferenceProcessor::RefProcPhases phase_number,
+                          ReferenceProcessorPhaseTimes* phase_times);
+  ~RefProcPhaseTimeTracker();
 };
 
-// Updates phase time related information.
-// - Each phase processing time, cleared/discovered reference counts and stats for each working threads if MT processed.
-class RefProcPhaseTimesTracker : public RefProcPhaseTimeBaseTracker {
+// Highest level time tracker.
+class RefProcTotalPhaseTimesTracker : public RefProcPhaseTimeBaseTracker {
   ReferenceProcessor* _rp;
-
 public:
-  RefProcPhaseTimesTracker(ReferenceType ref_type,
-                           ReferenceProcessorPhaseTimes* phase_times,
-                           ReferenceProcessor* rp);
-  ~RefProcPhaseTimesTracker();
+  RefProcTotalPhaseTimesTracker(ReferenceProcessor::RefProcPhases phase_number,
+                                ReferenceProcessorPhaseTimes* phase_times,
+                                ReferenceProcessor* rp);
+  ~RefProcTotalPhaseTimesTracker();
 };
 
 #endif // SHARE_VM_GC_SHARED_REFERENCEPROCESSORPHASETIMES_HPP
--- a/src/hotspot/share/gc/shared/stringdedup/stringDedup.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/stringdedup/stringDedup.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -102,9 +102,9 @@
 
 protected:
   // Initialize string deduplication.
-  // QUEUE: String Dedup Queue implementation
-  // STAT:  String Dedup Stat implementation
-  template <typename QUEUE, typename STAT>
+  // Q: String Dedup Queue implementation
+  // S: String Dedup Stat implementation
+  template <typename Q, typename S>
   static void initialize_impl();
 };
 
--- a/src/hotspot/share/gc/shared/stringdedup/stringDedupTable.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/shared/stringdedup/stringDedupTable.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -286,7 +286,7 @@
         // Apply proper barrier to make sure it is kept alive. Concurrent mark might
         // otherwise declare it dead if there are no other strong references to this object.
         oop* obj_addr = (oop*)entry->obj_addr();
-        oop obj = RootAccess<IN_CONCURRENT_ROOT | ON_WEAK_OOP_REF>::oop_load(obj_addr);
+        oop obj = NativeAccess<IN_CONCURRENT_ROOT | ON_WEAK_OOP_REF>::oop_load(obj_addr);
         return typeArrayOop(obj);
       }
     }
--- a/src/hotspot/share/gc/z/c2/zBarrierSetC2.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/c2/zBarrierSetC2.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1181,8 +1181,14 @@
           if (is_strip_mined && (i == LoopNode::EntryControl)) {
             assert(region->in(i)->is_OuterStripMinedLoop(), "");
             igvn.replace_input_of(region->in(i), i, out_ctrl);
+            phase->set_idom(region->in(i), out_ctrl, phase->dom_depth(out_ctrl));
           } else if (ctrl == region->in(i)) {
             igvn.replace_input_of(region, i, out_ctrl);
+            // Only update the idom if is the loop entry we are updating
+            // - A loop backedge doesn't change the idom
+            if (region->is_Loop() && i == LoopNode::EntryControl) {
+              phase->set_idom(region, out_ctrl, phase->dom_depth(out_ctrl));
+            }
           } else {
             Node* iff = region->in(i)->in(0);
             igvn.replace_input_of(iff, 0, out_ctrl);
--- a/src/hotspot/share/gc/z/zArguments.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zArguments.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -94,11 +94,6 @@
   // Verification of stacks not (yet) supported, for the same reason
   // we need fixup_partial_loads
   DEBUG_ONLY(FLAG_SET_DEFAULT(VerifyStack, false));
-
-  // JVMCI not (yet) supported
-  if (EnableJVMCI) {
-    vm_exit_during_initialization("The flag -XX:+UseZGC can not be combined with -XX:+EnableJVMCI");
-  }
 }
 
 CollectedHeap* ZArguments::create_heap() {
--- a/src/hotspot/share/gc/z/zBarrier.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zBarrier.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -83,6 +83,7 @@
   static  oop load_barrier_on_phantom_oop_field_preloaded(volatile oop* p, oop o);
 
   // Weak load barrier
+  static oop weak_load_barrier_on_oop_field(volatile oop* p);
   static oop weak_load_barrier_on_oop_field_preloaded(volatile oop* p, oop o);
   static oop weak_load_barrier_on_weak_oop(oop o);
   static oop weak_load_barrier_on_weak_oop_field(volatile oop* p);
--- a/src/hotspot/share/gc/z/zBarrier.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zBarrier.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -191,6 +191,12 @@
 //
 // Weak load barrier
 //
+inline oop ZBarrier::weak_load_barrier_on_oop_field(volatile oop* p) {
+  assert(!ZResurrection::is_blocked(), "Should not be called during resurrection blocked phase");
+  const oop o = *p;
+  return weak_load_barrier_on_oop_field_preloaded(p, o);
+}
+
 inline oop ZBarrier::weak_load_barrier_on_oop_field_preloaded(volatile oop* p, oop o) {
   return weak_barrier<is_weak_good_or_null_fast_path, weak_load_barrier_on_oop_slow_path>(p, o);
 }
--- a/src/hotspot/share/gc/z/zOopClosures.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zOopClosures.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -57,7 +57,7 @@
 void ZVerifyRootOopClosure::do_oop(oop* p) {
   guarantee(!ZHeap::heap()->is_in((uintptr_t)p), "oop* " PTR_FORMAT " in heap", p2i(p));
 
-  const oop obj = RootAccess<>::oop_load(p);
+  const oop obj = NativeAccess<>::oop_load(p);
   z_verify_loaded_object(p, obj);
 }
 
--- a/src/hotspot/share/gc/z/zReferenceProcessor.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zReferenceProcessor.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -105,19 +105,21 @@
   return *reference_referent_addr(obj);
 }
 
-bool ZReferenceProcessor::is_referent_alive_or_null(oop obj, ReferenceType type) const {
-  volatile oop* const p = reference_referent_addr(obj);
+bool ZReferenceProcessor::is_referent_strongly_alive_or_null(oop obj, ReferenceType type) const {
+  // Check if the referent is strongly alive or null, in which case we don't want to
+  // discover the reference. It can only be null if the application called
+  // Reference.enqueue() or Reference.clear().
+  //
+  // PhantomReferences with finalizable marked referents should technically not have
+  // to be discovered. However, InstanceRefKlass::oop_oop_iterate_ref_processing()
+  // does not know about the finalizable mark concept, and will therefore mark
+  // referents in non-discovered PhantomReferences as strongly live. To prevent
+  // this, we always discover PhantomReferences with finalizable marked referents.
+  // They will automatically be dropped during the reference processing phase.
 
-  // Check if the referent is alive or null, in which case we don't want to discover
-  // the reference. It can only be null if the application called Reference.enqueue()
-  // or Reference.clear().
-  if (type == REF_PHANTOM) {
-    const oop o = ZBarrier::weak_load_barrier_on_phantom_oop_field(p);
-    return o == NULL || ZHeap::heap()->is_object_live(ZOop::to_address(o));
-  } else {
-    const oop o = ZBarrier::weak_load_barrier_on_weak_oop_field(p);
-    return o == NULL || ZHeap::heap()->is_object_strongly_live(ZOop::to_address(o));
-  }
+  volatile oop* const p = reference_referent_addr(obj);
+  const oop o = ZBarrier::weak_load_barrier_on_oop_field(p);
+  return o == NULL || ZHeap::heap()->is_object_strongly_live(ZOop::to_address(o));
 }
 
 bool ZReferenceProcessor::is_referent_softly_alive(oop obj, ReferenceType type) const {
@@ -191,7 +193,7 @@
   _encountered_count.get()[type]++;
 
   if (is_reference_inactive(obj) ||
-      is_referent_alive_or_null(obj, type) ||
+      is_referent_strongly_alive_or_null(obj, type) ||
       is_referent_softly_alive(obj, type)) {
     // Not discovered
     return false;
--- a/src/hotspot/share/gc/z/zReferenceProcessor.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/gc/z/zReferenceProcessor.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -53,7 +53,7 @@
   volatile oop* reference_referent_addr(oop obj) const;
   oop reference_referent(oop obj) const;
   bool is_reference_inactive(oop obj) const;
-  bool is_referent_alive_or_null(oop obj, ReferenceType type) const;
+  bool is_referent_strongly_alive_or_null(oop obj, ReferenceType type) const;
   bool is_referent_softly_alive(oop obj, ReferenceType type) const;
   bool should_drop_reference(oop obj, ReferenceType type) const;
   bool should_mark_referent(ReferenceType type) const;
--- a/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSet.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSet.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -238,9 +238,9 @@
     // (primordial) boot class loader
     writer->write(cld_id); // class loader instance id
     writer->write((traceid)0);  // class loader type id (absence of)
-    writer->write((traceid)CREATE_SYMBOL_ID(1)); // 1 maps to synthetic name -> "boot"
+    writer->write((traceid)CREATE_SYMBOL_ID(1)); // 1 maps to synthetic name -> "bootstrap"
   } else {
-    Symbol* symbol_name = cld->class_loader_name();
+    Symbol* symbol_name = cld->name();
     const traceid symbol_name_id = symbol_name != NULL ? artifacts->mark(symbol_name) : 0;
     writer->write(cld_id); // class loader instance id
     writer->write(TRACE_ID(class_loader_klass)); // class loader type id
@@ -441,13 +441,13 @@
     CStringEntryPtr entry = this->_artifacts->map_cstring(0);
     assert(entry != NULL, "invariant");
     assert(strncmp(entry->literal(),
-      boot_class_loader_name,
-      strlen(boot_class_loader_name)) == 0, "invariant");
+      BOOTSTRAP_LOADER_NAME,
+      BOOTSTRAP_LOADER_NAME_LEN) == 0, "invariant");
     if (_unique_predicate(entry->id())) {
       count += write__artifact__cstring__entry__(this->_writer, entry);
     }
   } else {
-    const Symbol* class_loader_name = cld->class_loader_name();
+    const Symbol* class_loader_name = cld->name();
     if (class_loader_name != NULL) {
       SymbolEntryPtr entry = this->_artifacts->map_symbol(class_loader_name);
       assert(entry != NULL, "invariant");
--- a/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSetUtils.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSetUtils.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -208,7 +208,7 @@
   assert(_symbol_id != NULL, "invariant");
   _symbol_id->initialize();
   assert(!_symbol_id->has_entries(), "invariant");
-  _symbol_id->mark(boot_class_loader_name, 0); // pre-load "boot"
+  _symbol_id->mark(BOOTSTRAP_LOADER_NAME, 0); // pre-load "bootstrap"
   _class_unload = class_unload;
   // resource allocation
   _klass_list = new GrowableArray<const Klass*>(initial_class_list_size, false, mtTracing);
--- a/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSetUtils.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSetUtils.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -295,9 +295,6 @@
   bool has_cstring_entries() const { return _cstring_table->has_entries(); }
 };
 
-// external name (synthetic) for the primordial "boot" class loader instance
-const char* const boot_class_loader_name = "boot";
-
 /**
  * When processing a set of artifacts, there will be a need
  * to track transitive dependencies originating with each artifact.
--- a/src/hotspot/share/jvmci/jvmci_globals.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/jvmci/jvmci_globals.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "jvm.h"
 #include "jvmci/jvmci_globals.hpp"
+#include "gc/shared/gcConfig.hpp"
 #include "utilities/defaultStream.hpp"
 #include "runtime/globals_extension.hpp"
 
@@ -113,3 +114,13 @@
 #undef CHECK_NOT_SET
   return true;
 }
+void JVMCIGlobals::check_jvmci_supported_gc() {
+  if (EnableJVMCI) {
+    // Check if selected GC is supported by JVMCI and Java compiler
+    if (!(UseSerialGC || UseParallelGC || UseParallelOldGC || UseG1GC)) {
+      vm_exit_during_initialization("JVMCI Compiler does not support selected GC", GCConfig::hs_err_name());
+      FLAG_SET_DEFAULT(EnableJVMCI, false);
+      FLAG_SET_DEFAULT(UseJVMCICompiler, false);
+    }
+  }
+}
--- a/src/hotspot/share/jvmci/jvmci_globals.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/jvmci/jvmci_globals.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -121,5 +121,8 @@
   // an error message describing the inconsistency is printed before
   // returning false.
   static bool check_jvmci_flags_are_consistent();
+
+  // Check and exit VM with error if selected GC is not supported by JVMCI.
+  static void check_jvmci_supported_gc();
 };
 #endif // SHARE_VM_JVMCI_JVMCIGLOBALS_HPP
--- a/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/memory/metaspace/printCLDMetaspaceInfoClosure.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -88,7 +88,7 @@
     Klass* k = cld->class_loader_klass();
     if (k != NULL) {
       class_name = k->external_name();
-      Symbol* s = cld->class_loader_name();
+      Symbol* s = cld->name();
       if (s != NULL) {
         name = s->as_C_string();
       }
--- a/src/hotspot/share/oops/access.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/access.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -121,7 +121,7 @@
   static void verify_heap_oop_decorators() {
     const DecoratorSet heap_oop_decorators = AS_DECORATOR_MASK | ON_DECORATOR_MASK |
                                              OOP_DECORATOR_MASK | (IN_DECORATOR_MASK ^
-                                                                   (IN_ROOT | IN_CONCURRENT_ROOT)); // no root accesses in the heap
+                                                                   (IN_NATIVE | IN_CONCURRENT_ROOT)); // no root accesses in the heap
     verify_decorators<expected_mo_decorators | heap_oop_decorators>();
   }
 
@@ -296,7 +296,7 @@
 // Helper for performing normal accesses in roots. These accesses
 // may resolve an accessor on a GC barrier set
 template <DecoratorSet decorators = INTERNAL_EMPTY>
-class RootAccess: public Access<IN_ROOT | decorators> {};
+class NativeAccess: public Access<IN_NATIVE | decorators> {};
 
 // Helper for array access.
 template <DecoratorSet decorators = INTERNAL_EMPTY>
@@ -376,10 +376,10 @@
   ));
   const DecoratorSet location_decorators = decorators & IN_DECORATOR_MASK;
   STATIC_ASSERT(location_decorators == 0 || ( // make sure location decorators are disjoint if set
-    (location_decorators ^ IN_ROOT) == 0 ||
+    (location_decorators ^ IN_NATIVE) == 0 ||
     (location_decorators ^ IN_HEAP) == 0 ||
     (location_decorators ^ (IN_HEAP | IN_HEAP_ARRAY)) == 0 ||
-    (location_decorators ^ (IN_ROOT | IN_CONCURRENT_ROOT)) == 0
+    (location_decorators ^ (IN_NATIVE | IN_CONCURRENT_ROOT)) == 0
   ));
 }
 
--- a/src/hotspot/share/oops/accessDecorators.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/accessDecorators.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -184,16 +184,16 @@
 //   be omitted if this decorator is not set.
 // * IN_HEAP_ARRAY: The access is performed on a heap allocated array. This is sometimes a special case
 //   for some GCs, and implies that it is an IN_HEAP.
-// * IN_ROOT: The access is performed in an off-heap data structure pointing into the Java heap.
+// * IN_NATIVE: The access is performed in an off-heap data structure pointing into the Java heap.
 // * IN_CONCURRENT_ROOT: The access is performed in an off-heap data structure pointing into the Java heap,
 //   but is notably not scanned during safepoints. This is sometimes a special case for some GCs and
-//   implies that it is also an IN_ROOT.
+//   implies that it is also an IN_NATIVE.
 const DecoratorSet IN_HEAP            = UCONST64(1) << 20;
 const DecoratorSet IN_HEAP_ARRAY      = UCONST64(1) << 21;
-const DecoratorSet IN_ROOT            = UCONST64(1) << 22;
+const DecoratorSet IN_NATIVE          = UCONST64(1) << 22;
 const DecoratorSet IN_CONCURRENT_ROOT = UCONST64(1) << 23;
 const DecoratorSet IN_DECORATOR_MASK  = IN_HEAP | IN_HEAP_ARRAY |
-                                        IN_ROOT | IN_CONCURRENT_ROOT;
+                                        IN_NATIVE | IN_CONCURRENT_ROOT;
 
 // == Value Decorators ==
 // * OOP_NOT_NULL: This property can make certain barriers faster such as compressing oops.
@@ -242,7 +242,7 @@
     static const DecoratorSet heap_array_is_in_heap = barrier_strength_default |
       ((IN_HEAP_ARRAY & barrier_strength_default) != 0 ? IN_HEAP : INTERNAL_EMPTY);
     static const DecoratorSet conc_root_is_root = heap_array_is_in_heap |
-      ((IN_CONCURRENT_ROOT & heap_array_is_in_heap) != 0 ? IN_ROOT : INTERNAL_EMPTY);
+      ((IN_CONCURRENT_ROOT & heap_array_is_in_heap) != 0 ? IN_NATIVE : INTERNAL_EMPTY);
     static const DecoratorSet value = conc_root_is_root | BT_BUILDTIME_DECORATORS;
   };
 
@@ -263,7 +263,7 @@
     DecoratorSet heap_array_is_in_heap = barrier_strength_default |
       ((IN_HEAP_ARRAY & barrier_strength_default) != 0 ? IN_HEAP : INTERNAL_EMPTY);
     DecoratorSet conc_root_is_root = heap_array_is_in_heap |
-      ((IN_CONCURRENT_ROOT & heap_array_is_in_heap) != 0 ? IN_ROOT : INTERNAL_EMPTY);
+      ((IN_CONCURRENT_ROOT & heap_array_is_in_heap) != 0 ? IN_NATIVE : INTERNAL_EMPTY);
     DecoratorSet value = conc_root_is_root | BT_BUILDTIME_DECORATORS;
     return value;
   }
--- a/src/hotspot/share/oops/instanceKlass.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -2328,8 +2328,7 @@
 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) {
 
   // ensure java/ packages only loaded by boot or platform builtin loaders
-  Handle class_loader(THREAD, loader_data->class_loader());
-  check_prohibited_package(name(), class_loader, CHECK);
+  check_prohibited_package(name(), loader_data, CHECK);
 
   TempNewSymbol pkg_name = package_from_name(name(), CHECK);
 
@@ -2359,7 +2358,7 @@
 
       // A package should have been successfully created
       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
-             name()->as_C_string(), loader_data->loader_name());
+             name()->as_C_string(), loader_data->loader_name_and_id());
     }
 
     if (log_is_enabled(Debug, module)) {
@@ -2368,14 +2367,14 @@
       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
                         external_name(),
                         pkg_name->as_C_string(),
-                        loader_data->loader_name(),
+                        loader_data->loader_name_and_id(),
                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
     }
   } else {
     ResourceMark rm;
     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
                       external_name(),
-                      (loader_data != NULL) ? loader_data->loader_name() : "NULL",
+                      (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
                       UNNAMED_MODULE);
   }
 }
@@ -2471,10 +2470,10 @@
 
 // Only boot and platform class loaders can define classes in "java/" packages.
 void InstanceKlass::check_prohibited_package(Symbol* class_name,
-                                             Handle class_loader,
+                                             ClassLoaderData* loader_data,
                                              TRAPS) {
-  if (!class_loader.is_null() &&
-      !SystemDictionary::is_platform_class_loader(class_loader()) &&
+  if (!loader_data->is_boot_class_loader_data() &&
+      !loader_data->is_platform_class_loader_data() &&
       class_name != NULL) {
     ResourceMark rm(THREAD);
     char* name = class_name->as_C_string();
@@ -2482,7 +2481,7 @@
       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK);
       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
       name = pkg_name->as_C_string();
-      const char* class_loader_name = SystemDictionary::loader_name(class_loader());
+      const char* class_loader_name = loader_data->loader_name_and_id();
       StringUtils::replace_no_expand(name, "/", ".");
       const char* msg_text1 = "Class loader (instance of): ";
       const char* msg_text2 = " tried to load prohibited package name: ";
@@ -2641,7 +2640,12 @@
     // If the interface isn't implemented by the receiver class,
     // the VM should throw IncompatibleClassChangeError.
     if (cnt >= nof_interfaces) {
-      THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
+      ResourceMark rm(THREAD);
+      stringStream ss;
+      ss.print("Receiver class %s does not implement "
+               "the interface %s defining the method to be called",
+               class_loader_and_module_name(), holder->class_loader_and_module_name());
+      THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
     }
 
     Klass* ik = ioe->interface_klass();
--- a/src/hotspot/share/oops/instanceKlass.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -471,7 +471,7 @@
  private:
   // Check prohibited package ("java/" only loadable by boot or platform loaders)
   static void check_prohibited_package(Symbol* class_name,
-                                       Handle class_loader,
+                                       ClassLoaderData* loader_data,
                                        TRAPS);
  public:
   // tell if two classes have the same enclosing class (at package level)
--- a/src/hotspot/share/oops/klass.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/klass.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -142,7 +142,10 @@
 
 
 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
-  THROW(vmSymbols::java_lang_ArrayStoreException());
+  ResourceMark rm(THREAD);
+  assert(s != NULL, "Throw NPE!");
+  THROW_MSG(vmSymbols::java_lang_ArrayStoreException(),
+            err_msg("arraycopy: source type %s is not an array", s->klass()->external_name()));
 }
 
 
--- a/src/hotspot/share/oops/methodCounters.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/methodCounters.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 #define SHARE_VM_OOPS_METHODCOUNTERS_HPP
 
 #include "oops/metadata.hpp"
+#include "compiler/compilerDefinitions.hpp"
 #include "compiler/compilerOracle.hpp"
 #include "interpreter/invocationCounter.hpp"
 #include "runtime/arguments.hpp"
@@ -96,7 +97,7 @@
     double scale = 1.0;
     CompilerOracle::has_option_value(mh, "CompileThresholdScaling", scale);
 
-    int compile_threshold = Arguments::scaled_compile_threshold(CompileThreshold, scale);
+    int compile_threshold = CompilerConfig::scaled_compile_threshold(CompileThreshold, scale);
     _interpreter_invocation_limit = compile_threshold << InvocationCounter::count_shift;
     if (ProfileInterpreter) {
       // If interpreter profiling is enabled, the backward branch limit
@@ -107,8 +108,8 @@
       _interpreter_backward_branch_limit = ((compile_threshold * OnStackReplacePercentage) / 100) << InvocationCounter::count_shift;
     }
     _interpreter_profile_limit = ((compile_threshold * InterpreterProfilePercentage) / 100) << InvocationCounter::count_shift;
-    _invoke_mask = right_n_bits(Arguments::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
-    _backedge_mask = right_n_bits(Arguments::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
+    _invoke_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
+    _backedge_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
   }
 
  public:
--- a/src/hotspot/share/oops/methodData.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/methodData.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1217,8 +1217,8 @@
   // Set per-method invoke- and backedge mask.
   double scale = 1.0;
   CompilerOracle::has_option_value(_method, "CompileThresholdScaling", scale);
-  _invoke_mask = right_n_bits(Arguments::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
-  _backedge_mask = right_n_bits(Arguments::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
+  _invoke_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
+  _backedge_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
 
   _tenure_traps = 0;
   _num_loops = 0;
--- a/src/hotspot/share/oops/methodData.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/methodData.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -139,7 +139,7 @@
     //
     // The trap_state is collected only if ProfileTraps is true.
     trap_bits = 1+31,  // 31: enough to distinguish [0..Reason_RECORDED_LIMIT].
-    trap_mask = right_n_bits(trap_bits),
+    trap_mask = -1,
     first_flag = 0
   };
 
@@ -1976,7 +1976,7 @@
 
   // Whole-method sticky bits and flags
   enum {
-    _trap_hist_limit    = 23 JVMCI_ONLY(+5),   // decoupled from Deoptimization::Reason_LIMIT
+    _trap_hist_limit    = 24 JVMCI_ONLY(+5),   // decoupled from Deoptimization::Reason_LIMIT
     _trap_hist_mask     = max_jubyte,
     _extra_data_count   = 4     // extra DataLayout headers, for trap history
   }; // Public flag values
--- a/src/hotspot/share/oops/objArrayKlass.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/objArrayKlass.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -235,7 +235,19 @@
       // slow case: need individual subtype checks
       // note: don't use obj_at_put below because it includes a redundant store check
       if (!ArrayAccess<ARRAYCOPY_DISJOINT | ARRAYCOPY_CHECKCAST>::oop_arraycopy(s, src_offset, d, dst_offset, length)) {
-        THROW(vmSymbols::java_lang_ArrayStoreException());
+        ResourceMark rm(THREAD);
+        stringStream ss;
+        if (!bound->is_subtype_of(stype)) {
+          ss.print("arraycopy: type mismatch: can not copy %s[] into %s[]",
+                   stype->external_name(), bound->external_name());
+        } else {
+          // oop_arraycopy should return the index in the source array that
+          // contains the problematic oop.
+          ss.print("arraycopy: element type mismatch: can not cast one of the elements"
+                   " of %s[] to the type of the destination array, %s",
+                   stype->external_name(), bound->external_name());
+        }
+        THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
       }
     }
   }
@@ -246,13 +258,21 @@
   assert(s->is_objArray(), "must be obj array");
 
   if (!d->is_objArray()) {
-    THROW(vmSymbols::java_lang_ArrayStoreException());
+    ResourceMark rm(THREAD);
+    stringStream ss;
+    if (d->is_typeArray()) {
+      ss.print("arraycopy: type mismatch: can not copy object array[] into %s[]",
+               type2name_tab[ArrayKlass::cast(d->klass())->element_type()]);
+    } else {
+      ss.print("arraycopy: destination type %s is not an array", d->klass()->external_name());
+    }
+    THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
   }
 
   // Check is all offsets and lengths are non negative
   if (src_pos < 0 || dst_pos < 0 || length < 0) {
     // Pass specific exception reason.
-    ResourceMark rm;
+    ResourceMark rm(THREAD);
     stringStream ss;
     if (src_pos < 0) {
       ss.print("arraycopy: source index %d out of bounds for object array[%d]",
@@ -269,7 +289,7 @@
   if ((((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) ||
       (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length())) {
     // Pass specific exception reason.
-    ResourceMark rm;
+    ResourceMark rm(THREAD);
     stringStream ss;
     if (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) {
       ss.print("arraycopy: last source index %u out of bounds for object array[%d]",
--- a/src/hotspot/share/oops/oopHandle.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/oopHandle.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -29,7 +29,7 @@
 #include "oops/oopHandle.hpp"
 
 inline oop OopHandle::resolve() const {
-  return (_obj == NULL) ? (oop)NULL : RootAccess<IN_CONCURRENT_ROOT>::oop_load(_obj);
+  return (_obj == NULL) ? (oop)NULL : NativeAccess<IN_CONCURRENT_ROOT>::oop_load(_obj);
 }
 
 #endif //  SHARE_VM_OOPS_OOPHANDLE_INLINE_HPP
--- a/src/hotspot/share/oops/typeArrayKlass.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/typeArrayKlass.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -131,15 +131,31 @@
 void TypeArrayKlass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
   assert(s->is_typeArray(), "must be type array");
 
-  // Check destination
-  if (!d->is_typeArray() || element_type() != TypeArrayKlass::cast(d->klass())->element_type()) {
-    THROW(vmSymbols::java_lang_ArrayStoreException());
+  // Check destination type.
+  if (!d->is_typeArray()) {
+    ResourceMark rm(THREAD);
+    stringStream ss;
+    if (d->is_objArray()) {
+      ss.print("arraycopy: type mismatch: can not copy %s[] into object array[]",
+               type2name_tab[ArrayKlass::cast(s->klass())->element_type()]);
+    } else {
+      ss.print("arraycopy: destination type %s is not an array", d->klass()->external_name());
+    }
+    THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
+  }
+  if (element_type() != TypeArrayKlass::cast(d->klass())->element_type()) {
+    ResourceMark rm(THREAD);
+    stringStream ss;
+    ss.print("arraycopy: type mismatch: can not copy %s[] into %s[]",
+             type2name_tab[ArrayKlass::cast(s->klass())->element_type()],
+             type2name_tab[ArrayKlass::cast(d->klass())->element_type()]);
+    THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
   }
 
-  // Check is all offsets and lengths are non negative
+  // Check if all offsets and lengths are non negative.
   if (src_pos < 0 || dst_pos < 0 || length < 0) {
     // Pass specific exception reason.
-    ResourceMark rm;
+    ResourceMark rm(THREAD);
     stringStream ss;
     if (src_pos < 0) {
       ss.print("arraycopy: source index %d out of bounds for %s[%d]",
@@ -156,7 +172,7 @@
   if ((((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) ||
       (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length())) {
     // Pass specific exception reason.
-    ResourceMark rm;
+    ResourceMark rm(THREAD);
     stringStream ss;
     if (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length()) {
       ss.print("arraycopy: last source index %u out of bounds for %s[%d]",
--- a/src/hotspot/share/oops/weakHandle.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/weakHandle.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -48,7 +48,7 @@
     vm_exit_out_of_memory(sizeof(oop*), OOM_MALLOC_ERROR, "Unable to create new weak oop handle in OopStorage");
   }
   // Create WeakHandle with address returned and store oop into it.
-  RootAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_addr, obj());
+  NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_addr, obj());
   return WeakHandle(oop_addr);
 }
 
@@ -58,7 +58,7 @@
   if (_obj != NULL) {
     // Clear the WeakHandle.  For race in creating ClassLoaderData, we can release this
     // WeakHandle before it is cleared by GC.
-    RootAccess<ON_PHANTOM_OOP_REF>::oop_store(_obj, (oop)NULL);
+    NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(_obj, (oop)NULL);
     get_storage()->release(_obj);
   }
 }
--- a/src/hotspot/share/oops/weakHandle.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/oops/weakHandle.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -31,18 +31,18 @@
 template <WeakHandleType T>
 oop WeakHandle<T>::resolve() const {
   assert(!is_null(), "Must be created");
-  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(_obj);
+  return NativeAccess<ON_PHANTOM_OOP_REF>::oop_load(_obj);
 }
 
 template <WeakHandleType T>
 oop WeakHandle<T>::peek() const {
   assert(!is_null(), "Must be created");
-  return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(_obj);
+  return NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(_obj);
 }
 
 template <WeakHandleType T>
 void WeakHandle<T>::replace(oop with_obj) {
-  RootAccess<ON_PHANTOM_OOP_REF>::oop_store(_obj, with_obj);
+  NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(_obj, with_obj);
 }
 
 #endif // SHARE_VM_OOPS_WEAKHANDLE_INLINE_HPP
--- a/src/hotspot/share/opto/c2_globals.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/c2_globals.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -754,6 +754,9 @@
   product(uintx, LoopStripMiningIterShortLoop, 0,                           \
           "Loop with fewer iterations are not strip mined")                 \
           range(0, max_juint)                                               \
+                                                                            \
+  product(bool, UseProfiledLoopPredicate, true,                             \
+          "move predicates out of loops based on profiling data")           \
 
 C2_FLAGS(DECLARE_DEVELOPER_FLAG, \
          DECLARE_PD_DEVELOPER_FLAG, \
--- a/src/hotspot/share/opto/graphKit.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/graphKit.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -3804,6 +3804,9 @@
   if (UseLoopPredicate) {
     add_predicate_impl(Deoptimization::Reason_predicate, nargs);
   }
+  if (UseProfiledLoopPredicate) {
+    add_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);
+  }
   // loop's limit check predicate should be near the loop.
   add_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
 }
--- a/src/hotspot/share/opto/loopPredicate.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/loopPredicate.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -34,6 +34,8 @@
 #include "opto/opaquenode.hpp"
 #include "opto/rootnode.hpp"
 #include "opto/subnode.hpp"
+#include <fenv.h>
+#include <math.h>
 
 /*
  * The general idea of Loop Predication is to insert a predicate on the entry
@@ -89,7 +91,7 @@
 //
 //
 // We will create a region to guard the uct call if there is no one there.
-// The true projecttion (if_cont) of the new_iff is returned.
+// The true projection (if_cont) of the new_iff is returned.
 // This code is also used to clone predicates to cloned loops.
 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
                                                       Deoptimization::DeoptReason reason,
@@ -318,18 +320,37 @@
   if (limit_check_proj != NULL) {
     entry = entry->in(0)->in(0);
   }
+  ProjNode* profile_predicate_proj = NULL;
+  ProjNode* predicate_proj = NULL;
+  if (UseProfiledLoopPredicate) {
+    profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+    if (profile_predicate_proj != NULL) {
+      entry = skip_loop_predicates(entry);
+    }
+  }
   if (UseLoopPredicate) {
-    ProjNode* predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
-    if (predicate_proj != NULL) { // right pattern that can be used by loop predication
-      // clone predicate
-      new_entry = clone_predicate(predicate_proj, new_entry,
-                                  Deoptimization::Reason_predicate,
-                                  loop_phase, igvn);
-      assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
-      if (TraceLoopPredicate) {
-        tty->print("Loop Predicate cloned: ");
-        debug_only( new_entry->in(0)->dump(); )
-      }
+    predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
+  }
+  if (predicate_proj != NULL) { // right pattern that can be used by loop predication
+    // clone predicate
+    new_entry = clone_predicate(predicate_proj, new_entry,
+                                Deoptimization::Reason_predicate,
+                                loop_phase, igvn);
+    assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
+    if (TraceLoopPredicate) {
+      tty->print("Loop Predicate cloned: ");
+      debug_only( new_entry->in(0)->dump(); );
+    }
+  }
+  if (profile_predicate_proj != NULL) { // right pattern that can be used by loop predication
+    // clone predicate
+    new_entry = clone_predicate(profile_predicate_proj, new_entry,
+                                Deoptimization::Reason_profile_predicate,
+                                loop_phase, igvn);
+    assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
+    if (TraceLoopPredicate) {
+      tty->print("Loop Predicate cloned: ");
+      debug_only( new_entry->in(0)->dump(); );
     }
   }
   if (limit_check_proj != NULL && clone_limit_check) {
@@ -351,25 +372,36 @@
 //--------------------------skip_loop_predicates------------------------------
 // Skip related predicates.
 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) {
+  IfNode* iff = entry->in(0)->as_If();
+  ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
+  Node* rgn = uncommon_proj->unique_ctrl_out();
+  assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
+  entry = entry->in(0)->in(0);
+  while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
+    uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
+    if (uncommon_proj->unique_ctrl_out() != rgn)
+      break;
+    entry = entry->in(0)->in(0);
+  }
+  return entry;
+}
+
+Node* PhaseIdealLoop::skip_all_loop_predicates(Node* entry) {
   Node* predicate = NULL;
   predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
   if (predicate != NULL) {
     entry = entry->in(0)->in(0);
   }
+  if (UseProfiledLoopPredicate) {
+    predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+    if (predicate != NULL) { // right pattern that can be used by loop predication
+      entry = skip_loop_predicates(entry);
+    }
+  }
   if (UseLoopPredicate) {
     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
     if (predicate != NULL) { // right pattern that can be used by loop predication
-      IfNode* iff = entry->in(0)->as_If();
-      ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
-      Node* rgn = uncommon_proj->unique_ctrl_out();
-      assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
-      entry = entry->in(0)->in(0);
-      while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
-        uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
-        if (uncommon_proj->unique_ctrl_out() != rgn)
-          break;
-        entry = entry->in(0)->in(0);
-      }
+      entry = skip_loop_predicates(entry);
     }
   }
   return entry;
@@ -400,6 +432,12 @@
       return entry;
     }
   }
+  if (UseProfiledLoopPredicate) {
+    predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+    if (predicate != NULL) { // right pattern that can be used by loop predication
+      return entry;
+    }
+  }
   return NULL;
 }
 
@@ -766,24 +804,432 @@
   return bol;
 }
 
+// Should loop predication look not only in the path from tail to head
+// but also in branches of the loop body?
+bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree *loop, ProjNode *predicate_proj, float& loop_trip_cnt) {
+  if (!UseProfiledLoopPredicate) {
+    return false;
+  }
+
+  if (predicate_proj == NULL) {
+    return false;
+  }
+
+  LoopNode* head = loop->_head->as_Loop();
+  bool follow_branches = true;
+  IdealLoopTree* l = loop->_child;
+  // For leaf loops and loops with a single inner loop
+  while (l != NULL && follow_branches) {
+    IdealLoopTree* child = l;
+    if (child->_child != NULL &&
+        child->_head->is_OuterStripMinedLoop()) {
+      assert(child->_child->_next == NULL, "only one inner loop for strip mined loop");
+      assert(child->_child->_head->is_CountedLoop() && child->_child->_head->as_CountedLoop()->is_strip_mined(), "inner loop should be strip mined");
+      child = child->_child;
+    }
+    if (child->_child != NULL || child->_irreducible) {
+      follow_branches = false;
+    }
+    l = l->_next;
+  }
+  if (follow_branches) {
+    loop->compute_profile_trip_cnt(this);
+    if (head->is_profile_trip_failed()) {
+      follow_branches = false;
+    } else {
+      loop_trip_cnt = head->profile_trip_cnt();
+      if (head->is_CountedLoop()) {
+        CountedLoopNode* cl = head->as_CountedLoop();
+        if (cl->phi() != NULL) {
+          const TypeInt* t = _igvn.type(cl->phi())->is_int();
+          float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS(cl->stride_con());
+          if (worst_case_trip_cnt < loop_trip_cnt) {
+            loop_trip_cnt = worst_case_trip_cnt;
+          }
+        }
+      }
+    }
+  }
+  return follow_branches;
+}
+
+// Compute probability of reaching some CFG node from a fixed
+// dominating CFG node
+class PathFrequency {
+private:
+  Node* _dom; // frequencies are computed relative to this node
+  Node_Stack _stack;
+  GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions
+  GrowableArray<float> _freqs; // cache frequencies
+  PhaseIdealLoop* _phase;
+
+public:
+  PathFrequency(Node* dom, PhaseIdealLoop* phase)
+    : _dom(dom), _stack(0), _phase(phase) {
+  }
+
+  float to(Node* n) {
+    // post order walk on the CFG graph from n to _dom
+    fesetround(FE_TOWARDZERO); // make sure rounding doesn't push frequency above 1
+    IdealLoopTree* loop = _phase->get_loop(_dom);
+    Node* c = n;
+    for (;;) {
+      assert(_phase->get_loop(c) == loop, "have to be in the same loop");
+      if (c == _dom || _freqs.at_grow(c->_idx, -1) >= 0) {
+        float f = c == _dom ? 1 : _freqs.at(c->_idx);
+        Node* prev = c;
+        while (_stack.size() > 0 && prev == c) {
+          Node* n = _stack.node();
+          if (!n->is_Region()) {
+            if (_phase->get_loop(n) != _phase->get_loop(n->in(0))) {
+              // Found an inner loop: compute frequency of reaching this
+              // exit from the loop head by looking at the number of
+              // times each loop exit was taken
+              IdealLoopTree* inner_loop = _phase->get_loop(n->in(0));
+              LoopNode* inner_head = inner_loop->_head->as_Loop();
+              assert(_phase->get_loop(n) == loop, "only 1 inner loop");
+              if (inner_head->is_OuterStripMinedLoop()) {
+                inner_head->verify_strip_mined(1);
+                if (n->in(0) == inner_head->in(LoopNode::LoopBackControl)->in(0)) {
+                  n = n->in(0)->in(0)->in(0);
+                }
+                inner_loop = inner_loop->_child;
+                inner_head = inner_loop->_head->as_Loop();
+                inner_head->verify_strip_mined(1);
+              }
+              fesetround(FE_UPWARD);  // make sure rounding doesn't push frequency above 1
+              float loop_exit_cnt = 0.0f;
+              for (uint i = 0; i < inner_loop->_body.size(); i++) {
+                Node *n = inner_loop->_body[i];
+                float c = inner_loop->compute_profile_trip_cnt_helper(n);
+                loop_exit_cnt += c;
+              }
+              fesetround(FE_TOWARDZERO);
+              float cnt = -1;
+              if (n->in(0)->is_If()) {
+                IfNode* iff = n->in(0)->as_If();
+                float p = n->in(0)->as_If()->_prob;
+                if (n->Opcode() == Op_IfFalse) {
+                  p = 1 - p;
+                }
+                if (p > PROB_MIN) {
+                  cnt = p * iff->_fcnt;
+                } else {
+                  cnt = 0;
+                }
+              } else {
+                assert(n->in(0)->is_Jump(), "unsupported node kind");
+                JumpNode* jmp = n->in(0)->as_Jump();
+                float p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
+                cnt = p * jmp->_fcnt;
+              }
+              float this_exit_f = cnt > 0 ? cnt / loop_exit_cnt : 0;
+              assert(this_exit_f <= 1 && this_exit_f >= 0, "Incorrect frequency");
+              f = f * this_exit_f;
+              assert(f <= 1 && f >= 0, "Incorrect frequency");
+            } else {
+              float p = -1;
+              if (n->in(0)->is_If()) {
+                p = n->in(0)->as_If()->_prob;
+                if (n->Opcode() == Op_IfFalse) {
+                  p = 1 - p;
+                }
+              } else {
+                assert(n->in(0)->is_Jump(), "unsupported node kind");
+                p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
+              }
+              f = f * p;
+              assert(f <= 1 && f >= 0, "Incorrect frequency");
+            }
+            _freqs.at_put_grow(n->_idx, (float)f, -1);
+            _stack.pop();
+          } else {
+            float prev_f = _freqs_stack.pop();
+            float new_f = f;
+            f = new_f + prev_f;
+            assert(f <= 1 && f >= 0, "Incorrect frequency");
+            uint i = _stack.index();
+            if (i < n->req()) {
+              c = n->in(i);
+              _stack.set_index(i+1);
+              _freqs_stack.push(f);
+            } else {
+              _freqs.at_put_grow(n->_idx, f, -1);
+              _stack.pop();
+            }
+          }
+        }
+        if (_stack.size() == 0) {
+          fesetround(FE_TONEAREST);
+          assert(f >= 0 && f <= 1, "should have been computed");
+          return f;
+        }
+      } else if (c->is_Loop()) {
+        ShouldNotReachHere();
+        c = c->in(LoopNode::EntryControl);
+      } else if (c->is_Region()) {
+        _freqs_stack.push(0);
+        _stack.push(c, 2);
+        c = c->in(1);
+      } else {
+        if (c->is_IfProj()) {
+          IfNode* iff = c->in(0)->as_If();
+          if (iff->_prob == PROB_UNKNOWN) {
+            // assume never taken
+            _freqs.at_put_grow(c->_idx, 0, -1);
+          } else if (_phase->get_loop(c) != _phase->get_loop(iff)) {
+            if (iff->_fcnt == COUNT_UNKNOWN) {
+              // assume never taken
+              _freqs.at_put_grow(c->_idx, 0, -1);
+            } else {
+              // skip over loop
+              _stack.push(c, 1);
+              c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
+            }
+          } else {
+            _stack.push(c, 1);
+            c = iff;
+          }
+        } else if (c->is_JumpProj()) {
+          JumpNode* jmp = c->in(0)->as_Jump();
+          if (_phase->get_loop(c) != _phase->get_loop(jmp)) {
+            if (jmp->_fcnt == COUNT_UNKNOWN) {
+              // assume never taken
+              _freqs.at_put_grow(c->_idx, 0, -1);
+            } else {
+              // skip over loop
+              _stack.push(c, 1);
+              c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
+            }
+          } else {
+            _stack.push(c, 1);
+            c = jmp;
+          }
+        } else if (c->Opcode() == Op_CatchProj &&
+                   c->in(0)->Opcode() == Op_Catch &&
+                   c->in(0)->in(0)->is_Proj() &&
+                   c->in(0)->in(0)->in(0)->is_Call()) {
+          // assume exceptions are never thrown
+          uint con = c->as_Proj()->_con;
+          if (con == CatchProjNode::fall_through_index) {
+            Node* call = c->in(0)->in(0)->in(0)->in(0);
+            if (_phase->get_loop(call) != _phase->get_loop(c)) {
+              _freqs.at_put_grow(c->_idx, 0, -1);
+            } else {
+              c = call;
+            }
+          } else {
+            assert(con >= CatchProjNode::catch_all_index, "what else?");
+            _freqs.at_put_grow(c->_idx, 0, -1);
+          }
+        } else if (c->unique_ctrl_out() == NULL && !c->is_If() && !c->is_Jump()) {
+          ShouldNotReachHere();
+        } else {
+          c = c->in(0);
+        }
+      }
+    }
+    ShouldNotReachHere();
+    return -1;
+  }
+};
+
+void PhaseIdealLoop::loop_predication_follow_branches(Node *n, IdealLoopTree *loop, float loop_trip_cnt,
+                                                      PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
+                                                      Node_List& if_proj_list) {
+  assert(n->is_Region(), "start from a region");
+  Node* tail = loop->tail();
+  stack.push(n, 1);
+  do {
+    Node* c = stack.node();
+    assert(c->is_Region() || c->is_IfProj(), "only region here");
+    uint i = stack.index();
+
+    if (i < c->req()) {
+      stack.set_index(i+1);
+      Node* in = c->in(i);
+      while (!is_dominator(in, tail) && !seen.test_set(in->_idx)) {
+        IdealLoopTree* in_loop = get_loop(in);
+        if (in_loop != loop) {
+          in = in_loop->_head->in(LoopNode::EntryControl);
+        } else if (in->is_Region()) {
+          stack.push(in, 1);
+          break;
+        } else if (in->is_IfProj() &&
+                   in->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
+          if (pf.to(in) * loop_trip_cnt >= 1) {
+            stack.push(in, 1);
+          }
+          in = in->in(0);
+        } else {
+          in = in->in(0);
+        }
+      }
+    } else {
+      if (c->is_IfProj()) {
+        if_proj_list.push(c);
+      }
+      stack.pop();
+    }
+
+  } while (stack.size() > 0);
+}
+
+
+bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree *loop, ProjNode* proj, ProjNode *predicate_proj,
+                                                  CountedLoopNode *cl, ConNode* zero, Invariance& invar,
+                                                  Deoptimization::DeoptReason reason) {
+  // Following are changed to nonnull when a predicate can be hoisted
+  ProjNode* new_predicate_proj = NULL;
+  IfNode*   iff  = proj->in(0)->as_If();
+  Node*     test = iff->in(1);
+  if (!test->is_Bool()){ //Conv2B, ...
+    return false;
+  }
+  BoolNode* bol = test->as_Bool();
+  if (invar.is_invariant(bol)) {
+    // Invariant test
+    new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
+                                                     reason,
+                                                     iff->Opcode());
+    Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
+    BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
+
+    // Negate test if necessary
+    bool negated = false;
+    if (proj->_con != predicate_proj->_con) {
+      new_predicate_bol = new BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
+      register_new_node(new_predicate_bol, ctrl);
+      negated = true;
+    }
+    IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
+    _igvn.hash_delete(new_predicate_iff);
+    new_predicate_iff->set_req(1, new_predicate_bol);
+#ifndef PRODUCT
+    if (TraceLoopPredicate) {
+      tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
+      loop->dump_head();
+    } else if (TraceLoopOpts) {
+      tty->print("Predicate IC ");
+      loop->dump_head();
+    }
+#endif
+  } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
+    // Range check for counted loops
+    const Node*    cmp    = bol->in(1)->as_Cmp();
+    Node*          idx    = cmp->in(1);
+    assert(!invar.is_invariant(idx), "index is variant");
+    Node* rng = cmp->in(2);
+    assert(rng->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(rng)->is_int()->_lo >= 0, "must be");
+    assert(invar.is_invariant(rng), "range must be invariant");
+    int scale    = 1;
+    Node* offset = zero;
+    bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
+    assert(ok, "must be index expression");
+
+    Node* init    = cl->init_trip();
+    // Limit is not exact.
+    // Calculate exact limit here.
+    // Note, counted loop's test is '<' or '>'.
+    Node* limit   = exact_limit(loop);
+    int  stride   = cl->stride()->get_int();
+
+    // Build if's for the upper and lower bound tests.  The
+    // lower_bound test will dominate the upper bound test and all
+    // cloned or created nodes will use the lower bound test as
+    // their declared control.
+
+    // Perform cloning to keep Invariance state correct since the
+    // late schedule will place invariant things in the loop.
+    Node *ctrl = predicate_proj->in(0)->as_If()->in(0);
+    rng = invar.clone(rng, ctrl);
+    if (offset && offset != zero) {
+      assert(invar.is_invariant(offset), "offset must be loop invariant");
+      offset = invar.clone(offset, ctrl);
+    }
+    // If predicate expressions may overflow in the integer range, longs are used.
+    bool overflow = false;
+
+    // Test the lower bound
+    BoolNode* lower_bound_bol = rc_predicate(loop, ctrl, scale, offset, init, limit, stride, rng, false, overflow);
+    // Negate test if necessary
+    bool negated = false;
+    if (proj->_con != predicate_proj->_con) {
+      lower_bound_bol = new BoolNode(lower_bound_bol->in(1), lower_bound_bol->_test.negate());
+      register_new_node(lower_bound_bol, ctrl);
+      negated = true;
+    }
+    ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
+    IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
+    _igvn.hash_delete(lower_bound_iff);
+    lower_bound_iff->set_req(1, lower_bound_bol);
+    if (TraceLoopPredicate) tty->print_cr("lower bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
+
+    // Test the upper bound
+    BoolNode* upper_bound_bol = rc_predicate(loop, lower_bound_proj, scale, offset, init, limit, stride, rng, true, overflow);
+    negated = false;
+    if (proj->_con != predicate_proj->_con) {
+      upper_bound_bol = new BoolNode(upper_bound_bol->in(1), upper_bound_bol->_test.negate());
+      register_new_node(upper_bound_bol, ctrl);
+      negated = true;
+    }
+    ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
+    assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
+    IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
+    _igvn.hash_delete(upper_bound_iff);
+    upper_bound_iff->set_req(1, upper_bound_bol);
+    if (TraceLoopPredicate) tty->print_cr("upper bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
+
+    // Fall through into rest of the clean up code which will move
+    // any dependent nodes onto the upper bound test.
+    new_predicate_proj = upper_bound_proj;
+
+    if (iff->is_RangeCheck()) {
+      new_predicate_proj = insert_skeleton_predicate(iff, loop, proj, predicate_proj, upper_bound_proj, scale, offset, init, limit, stride, rng, overflow, reason);
+    }
+
+#ifndef PRODUCT
+    if (TraceLoopOpts && !TraceLoopPredicate) {
+      tty->print("Predicate RC ");
+      loop->dump_head();
+    }
+#endif
+  } else {
+    // Loop variant check (for example, range check in non-counted loop)
+    // with uncommon trap.
+    return false;
+  }
+  assert(new_predicate_proj != NULL, "sanity");
+  // Success - attach condition (new_predicate_bol) to predicate if
+  invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
+
+  // Eliminate the old If in the loop body
+  dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
+
+  C->set_major_progress();
+  return true;
+}
+
+
 // After pre/main/post loops are created, we'll put a copy of some
-// range checks between the pre and main loop to validate the initial
-// value of the induction variable for the main loop. Make a copy of
-// the predicates here with an opaque node as a place holder for the
-// initial value.
+// range checks between the pre and main loop to validate the value
+// of the main loop induction variable. Make a copy of the predicates
+// here with an opaque node as a place holder for the value (will be
+// updated by PhaseIdealLoop::update_skeleton_predicate()).
 ProjNode* PhaseIdealLoop::insert_skeleton_predicate(IfNode* iff, IdealLoopTree *loop,
                                                     ProjNode* proj, ProjNode *predicate_proj,
                                                     ProjNode* upper_bound_proj,
                                                     int scale, Node* offset,
                                                     Node* init, Node* limit, jint stride,
-                                                    Node* rng, bool &overflow) {
+                                                    Node* rng, bool &overflow,
+                                                    Deoptimization::DeoptReason reason) {
   assert(proj->_con && predicate_proj->_con, "not a range check?");
   Node* opaque_init = new Opaque1Node(C, init);
   register_new_node(opaque_init, upper_bound_proj);
   BoolNode* bol = rc_predicate(loop, upper_bound_proj, scale, offset, opaque_init, limit, stride, rng, (stride > 0) != (scale > 0), overflow);
   Node* opaque_bol = new Opaque4Node(C, bol, _igvn.intcon(1)); // This will go away once loop opts are over
   register_new_node(opaque_bol, upper_bound_proj);
-  ProjNode* new_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate, overflow ? Op_If : iff->Opcode());
+  ProjNode* new_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
   _igvn.replace_input_of(new_proj->in(0), 1, opaque_bol);
   assert(opaque_init->outcnt() > 0, "should be used");
   return new_proj;
@@ -821,13 +1267,32 @@
   }
 
   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
+  ProjNode *loop_limit_proj = NULL;
   ProjNode *predicate_proj = NULL;
+  ProjNode *profile_predicate_proj = NULL;
   // Loop limit check predicate should be near the loop.
-  predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
-  if (predicate_proj != NULL)
-    entry = predicate_proj->in(0)->in(0);
+  loop_limit_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
+  if (loop_limit_proj != NULL) {
+    entry = loop_limit_proj->in(0)->in(0);
+  }
+  bool has_profile_predicates = false;
+  profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+  if (profile_predicate_proj != NULL) {
+    Node* n = skip_loop_predicates(entry);
+    // Check if predicates were already added to the profile predicate
+    // block
+    if (n != entry->in(0)->in(0)) {
+      has_profile_predicates = true;
+    }
+    entry = n;
+  }
   predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
-  if (!predicate_proj) {
+
+  float loop_trip_cnt = -1;
+  bool follow_branches = loop_predication_should_follow_branches(loop, profile_predicate_proj, loop_trip_cnt);
+  assert(!follow_branches || loop_trip_cnt >= 0, "negative trip count?");
+
+  if (predicate_proj == NULL && !follow_branches) {
 #ifndef PRODUCT
     if (TraceLoopPredicate) {
       tty->print("missing predicate:");
@@ -846,7 +1311,11 @@
   // Create list of if-projs such that a newer proj dominates all older
   // projs in the list, and they all dominate loop->tail()
   Node_List if_proj_list(area);
+  Node_List regions(area);
   Node *current_proj = loop->tail(); //start from tail
+
+
+  Node_List controls(area);
   while (current_proj != head) {
     if (loop == get_loop(current_proj) && // still in the loop ?
         current_proj->is_Proj()        && // is a projection  ?
@@ -854,161 +1323,79 @@
          current_proj->in(0)->Opcode() == Op_RangeCheck)) { // is a if projection ?
       if_proj_list.push(current_proj);
     }
+    if (follow_branches &&
+        current_proj->Opcode() == Op_Region &&
+        loop == get_loop(current_proj)) {
+      regions.push(current_proj);
+    }
     current_proj = idom(current_proj);
   }
 
   bool hoisted = false; // true if at least one proj is promoted
-  while (if_proj_list.size() > 0) {
-    // Following are changed to nonnull when a predicate can be hoisted
-    ProjNode* new_predicate_proj = NULL;
 
-    ProjNode* proj = if_proj_list.pop()->as_Proj();
-    IfNode*   iff  = proj->in(0)->as_If();
+  if (!has_profile_predicates) {
+    while (if_proj_list.size() > 0) {
+      Node* n = if_proj_list.pop();
+
+      ProjNode* proj = n->as_Proj();
+      IfNode*   iff  = proj->in(0)->as_If();
 
-    if (!proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
-      if (loop->is_loop_exit(iff)) {
-        // stop processing the remaining projs in the list because the execution of them
-        // depends on the condition of "iff" (iff->in(1)).
+      CallStaticJavaNode* call = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
+      if (call == NULL) {
+        if (loop->is_loop_exit(iff)) {
+          // stop processing the remaining projs in the list because the execution of them
+          // depends on the condition of "iff" (iff->in(1)).
+          break;
+        } else {
+          // Both arms are inside the loop. There are two cases:
+          // (1) there is one backward branch. In this case, any remaining proj
+          //     in the if_proj list post-dominates "iff". So, the condition of "iff"
+          //     does not determine the execution the remining projs directly, and we
+          //     can safely continue.
+          // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
+          //     does not dominate loop->tail(), so it can not be in the if_proj list.
+          continue;
+        }
+      }
+      Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(call->uncommon_trap_request());
+      if (reason == Deoptimization::Reason_predicate) {
         break;
-      } else {
-        // Both arms are inside the loop. There are two cases:
-        // (1) there is one backward branch. In this case, any remaining proj
-        //     in the if_proj list post-dominates "iff". So, the condition of "iff"
-        //     does not determine the execution the remining projs directly, and we
-        //     can safely continue.
-        // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
-        //     does not dominate loop->tail(), so it can not be in the if_proj list.
-        continue;
+      }
+
+      if (predicate_proj != NULL) {
+        hoisted = loop_predication_impl_helper(loop, proj, predicate_proj, cl, zero, invar, Deoptimization::Reason_predicate) | hoisted;
+      }
+    } // end while
+  }
+
+  Node_List if_proj_list_freq(area);
+  if (follow_branches) {
+    PathFrequency pf(loop->_head, this);
+
+    // Some projections were skipped by regular predicates because of
+    // an early loop exit. Try them with profile data.
+    while (if_proj_list.size() > 0) {
+      Node* proj = if_proj_list.pop();
+      float f = pf.to(proj);
+      if (proj->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
+          f * loop_trip_cnt >= 1) {
+        hoisted = loop_predication_impl_helper(loop, proj->as_Proj(), profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
       }
     }
 
-    Node*     test = iff->in(1);
-    if (!test->is_Bool()){ //Conv2B, ...
-      continue;
+    // And look into all branches
+    Node_Stack stack(0);
+    VectorSet seen(Thread::current()->resource_area());
+    while (regions.size() > 0) {
+      Node* c = regions.pop();
+      loop_predication_follow_branches(c, loop, loop_trip_cnt, pf, stack, seen, if_proj_list_freq);
     }
-    BoolNode* bol = test->as_Bool();
-    if (invar.is_invariant(bol)) {
-      // Invariant test
-      new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
-                                                       Deoptimization::Reason_predicate,
-                                                       iff->Opcode());
-      Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
-      BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
-
-      // Negate test if necessary
-      bool negated = false;
-      if (proj->_con != predicate_proj->_con) {
-        new_predicate_bol = new BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
-        register_new_node(new_predicate_bol, ctrl);
-        negated = true;
-      }
-      IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
-      _igvn.hash_delete(new_predicate_iff);
-      new_predicate_iff->set_req(1, new_predicate_bol);
-#ifndef PRODUCT
-      if (TraceLoopPredicate) {
-        tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
-        loop->dump_head();
-      } else if (TraceLoopOpts) {
-        tty->print("Predicate IC ");
-        loop->dump_head();
-      }
-#endif
-    } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
-      // Range check for counted loops
-      const Node*    cmp    = bol->in(1)->as_Cmp();
-      Node*          idx    = cmp->in(1);
-      assert(!invar.is_invariant(idx), "index is variant");
-      Node* rng = cmp->in(2);
-      assert(rng->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(rng)->is_int()->_lo >= 0, "must be");
-      assert(invar.is_invariant(rng), "range must be invariant");
-      int scale    = 1;
-      Node* offset = zero;
-      bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
-      assert(ok, "must be index expression");
-
-      Node* init    = cl->init_trip();
-      // Limit is not exact.
-      // Calculate exact limit here.
-      // Note, counted loop's test is '<' or '>'.
-      Node* limit   = exact_limit(loop);
-      int  stride   = cl->stride()->get_int();
-
-      // Build if's for the upper and lower bound tests.  The
-      // lower_bound test will dominate the upper bound test and all
-      // cloned or created nodes will use the lower bound test as
-      // their declared control.
 
-      // Perform cloning to keep Invariance state correct since the
-      // late schedule will place invariant things in the loop.
-      Node *ctrl = predicate_proj->in(0)->as_If()->in(0);
-      rng = invar.clone(rng, ctrl);
-      if (offset && offset != zero) {
-        assert(invar.is_invariant(offset), "offset must be loop invariant");
-        offset = invar.clone(offset, ctrl);
-      }
-      // If predicate expressions may overflow in the integer range, longs are used.
-      bool overflow = false;
-
-      // Test the lower bound
-      BoolNode* lower_bound_bol = rc_predicate(loop, ctrl, scale, offset, init, limit, stride, rng, false, overflow);
-      // Negate test if necessary
-      bool negated = false;
-      if (proj->_con != predicate_proj->_con) {
-        lower_bound_bol = new BoolNode(lower_bound_bol->in(1), lower_bound_bol->_test.negate());
-        register_new_node(lower_bound_bol, ctrl);
-        negated = true;
-      }
-      ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate, overflow ? Op_If : iff->Opcode());
-      IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
-      _igvn.hash_delete(lower_bound_iff);
-      lower_bound_iff->set_req(1, lower_bound_bol);
-      if (TraceLoopPredicate) tty->print_cr("lower bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
-
-      // Test the upper bound
-      BoolNode* upper_bound_bol = rc_predicate(loop, lower_bound_proj, scale, offset, init, limit, stride, rng, true, overflow);
-      negated = false;
-      if (proj->_con != predicate_proj->_con) {
-        upper_bound_bol = new BoolNode(upper_bound_bol->in(1), upper_bound_bol->_test.negate());
-        register_new_node(upper_bound_bol, ctrl);
-        negated = true;
-      }
-      ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate, overflow ? Op_If : iff->Opcode());
-      assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
-      IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
-      _igvn.hash_delete(upper_bound_iff);
-      upper_bound_iff->set_req(1, upper_bound_bol);
-      if (TraceLoopPredicate) tty->print_cr("upper bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
-
-      // Fall through into rest of the clean up code which will move
-      // any dependent nodes onto the upper bound test.
-      new_predicate_proj = upper_bound_proj;
-
-      if (iff->is_RangeCheck()) {
-        new_predicate_proj = insert_skeleton_predicate(iff, loop, proj, predicate_proj, upper_bound_proj, scale, offset, init, limit, stride, rng, overflow);
-      }
-
-#ifndef PRODUCT
-      if (TraceLoopOpts && !TraceLoopPredicate) {
-        tty->print("Predicate RC ");
-        loop->dump_head();
-      }
-#endif
-    } else {
-      // Loop variant check (for example, range check in non-counted loop)
-      // with uncommon trap.
-      continue;
+    for (uint i = 0; i < if_proj_list_freq.size(); i++) {
+      ProjNode* proj = if_proj_list_freq.at(i)->as_Proj();
+      hoisted = loop_predication_impl_helper(loop, proj, profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
     }
-    assert(new_predicate_proj != NULL, "sanity");
-    // Success - attach condition (new_predicate_bol) to predicate if
-    invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
-
-    // Eliminate the old If in the loop body
-    dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
-
-    hoisted = true;
-    C->set_major_progress();
-  } // end while
+  }
 
 #ifndef PRODUCT
   // report that the loop predication has been actually performed
--- a/src/hotspot/share/opto/loopTransform.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/loopTransform.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -137,11 +137,45 @@
 //------------------------------compute_profile_trip_cnt----------------------------
 // Compute loop trip count from profile data as
 //    (backedge_count + loop_exit_count) / loop_exit_count
-void IdealLoopTree::compute_profile_trip_cnt( PhaseIdealLoop *phase ) {
-  if (!_head->is_CountedLoop()) {
+
+float IdealLoopTree::compute_profile_trip_cnt_helper(Node* n) {
+  if (n->is_If()) {
+    IfNode *iff = n->as_If();
+    if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
+      Node *exit = is_loop_exit(iff);
+      if (exit) {
+        float exit_prob = iff->_prob;
+        if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
+        if (exit_prob > PROB_MIN) {
+          float exit_cnt = iff->_fcnt * exit_prob;
+          return exit_cnt;
+        }
+      }
+    }
+  }
+  if (n->is_Jump()) {
+    JumpNode *jmp = n->as_Jump();
+    if (jmp->_fcnt != COUNT_UNKNOWN) {
+      float* probs = jmp->_probs;
+      float exit_prob = 0;
+      PhaseIdealLoop *phase = _phase;
+      for (DUIterator_Fast imax, i = jmp->fast_outs(imax); i < imax; i++) {
+        JumpProjNode* u = jmp->fast_out(i)->as_JumpProj();
+        if (!is_member(_phase->get_loop(u))) {
+          exit_prob += probs[u->_con];
+        }
+      }
+      return exit_prob * jmp->_fcnt;
+    }
+  }
+  return 0;
+}
+
+void IdealLoopTree::compute_profile_trip_cnt(PhaseIdealLoop *phase) {
+  if (!_head->is_Loop()) {
     return;
   }
-  CountedLoopNode* head = _head->as_CountedLoop();
+  LoopNode* head = _head->as_Loop();
   if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
     return; // Already computed
   }
@@ -153,7 +187,8 @@
         back->in(0) &&
         back->in(0)->is_If() &&
         back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
-        back->in(0)->as_If()->_prob != PROB_UNKNOWN) {
+        back->in(0)->as_If()->_prob != PROB_UNKNOWN &&
+        (back->Opcode() == Op_IfTrue ? 1-back->in(0)->as_If()->_prob : back->in(0)->as_If()->_prob) > PROB_MIN) {
       break;
     }
     back = phase->idom(back);
@@ -162,26 +197,34 @@
     assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
            back->in(0), "if-projection exists");
     IfNode* back_if = back->in(0)->as_If();
-    float loop_back_cnt = back_if->_fcnt * back_if->_prob;
+    float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : (1 - back_if->_prob));
 
     // Now compute a loop exit count
     float loop_exit_cnt = 0.0f;
-    for( uint i = 0; i < _body.size(); i++ ) {
-      Node *n = _body[i];
-      if( n->is_If() ) {
-        IfNode *iff = n->as_If();
-        if( iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN ) {
-          Node *exit = is_loop_exit(iff);
-          if( exit ) {
-            float exit_prob = iff->_prob;
-            if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
-            if (exit_prob > PROB_MIN) {
-              float exit_cnt = iff->_fcnt * exit_prob;
-              loop_exit_cnt += exit_cnt;
+    if (_child == NULL) {
+      for( uint i = 0; i < _body.size(); i++ ) {
+        Node *n = _body[i];
+        loop_exit_cnt += compute_profile_trip_cnt_helper(n);
+      }
+    } else {
+      ResourceMark rm;
+      Unique_Node_List wq;
+      wq.push(back);
+      for (uint i = 0; i < wq.size(); i++) {
+        Node *n = wq.at(i);
+        assert(n->is_CFG(), "only control nodes");
+        if (n != head) {
+          if (n->is_Region()) {
+            for (uint j = 1; j < n->req(); j++) {
+              wq.push(n->in(j));
             }
+          } else {
+            loop_exit_cnt += compute_profile_trip_cnt_helper(n);
+            wq.push(n->in(0));
           }
         }
       }
+
     }
     if (loop_exit_cnt > 0.0f) {
       trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
@@ -189,6 +232,8 @@
       // No exit count so use
       trip_cnt = loop_back_cnt;
     }
+  } else {
+    head->mark_profile_trip_failed();
   }
 #ifndef PRODUCT
   if (TraceProfileTripCount) {
@@ -1014,11 +1059,139 @@
 // loop is never executed). When that happens, range check
 // CastII/ConvI2L nodes cause some data paths to die. For consistency,
 // the control paths must die too but the range checks were removed by
-// predication. The range checks that we add here guarantee that they
-// do.
-void PhaseIdealLoop::duplicate_predicates(CountedLoopNode* pre_head, Node* min_taken, Node* castii,
-                                          IdealLoopTree* outer_loop, LoopNode* outer_main_head,
-                                          uint dd_main_head) {
+// predication. The range checks that we add here guarantee that they do.
+void PhaseIdealLoop::duplicate_predicates_helper(Node* predicate, Node* castii, IdealLoopTree* outer_loop,
+                                                 LoopNode* outer_main_head, uint dd_main_head) {
+  if (predicate != NULL) {
+    IfNode* iff = predicate->in(0)->as_If();
+    ProjNode* uncommon_proj = iff->proj_out(1 - predicate->as_Proj()->_con);
+    Node* rgn = uncommon_proj->unique_ctrl_out();
+    assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
+    assert(iff->in(1)->in(1)->Opcode() == Op_Opaque1, "unexpected predicate shape");
+    predicate = iff->in(0);
+    Node* current_proj = outer_main_head->in(LoopNode::EntryControl);
+    Node* prev_proj = current_proj;
+    while (predicate != NULL && predicate->is_Proj() && predicate->in(0)->is_If()) {
+      iff = predicate->in(0)->as_If();
+      uncommon_proj = iff->proj_out(1 - predicate->as_Proj()->_con);
+      if (uncommon_proj->unique_ctrl_out() != rgn)
+        break;
+      if (iff->in(1)->Opcode() == Op_Opaque4) {
+        // Clone the predicate twice and initialize one with the initial
+        // value of the loop induction variable. Leave the other predicate
+        // to be initialized when increasing the stride during loop unrolling.
+        prev_proj = update_skeleton_predicate(iff, castii, predicate, uncommon_proj, current_proj, outer_loop, prev_proj);
+        Node* value = new Opaque1Node(C, castii);
+        register_new_node(value, current_proj);
+        prev_proj = update_skeleton_predicate(iff, value, predicate, uncommon_proj, current_proj, outer_loop, prev_proj);
+        // Remove the skeleton predicate from the pre-loop
+        _igvn.replace_input_of(iff, 1, _igvn.intcon(1));
+      }
+      predicate = predicate->in(0)->in(0);
+    }
+    _igvn.replace_input_of(outer_main_head, LoopNode::EntryControl, prev_proj);
+    set_idom(outer_main_head, prev_proj, dd_main_head);
+  }
+}
+
+Node* PhaseIdealLoop::update_skeleton_predicate(Node* iff, Node* value, Node* predicate, Node* uncommon_proj,
+                                                Node* current_proj, IdealLoopTree* outer_loop, Node* prev_proj) {
+  bool clone = (outer_loop != NULL); // Clone the predicate?
+  Node_Stack to_clone(2);
+  to_clone.push(iff->in(1), 1);
+  uint current = C->unique();
+  Node* result = NULL;
+  // Look for the opaque node to replace with the new value
+  // and clone everything in between. We keep the Opaque4 node
+  // so the duplicated predicates are eliminated once loop
+  // opts are over: they are here only to keep the IR graph
+  // consistent.
+  do {
+    Node* n = to_clone.node();
+    uint i = to_clone.index();
+    Node* m = n->in(i);
+    int op = m->Opcode();
+    if (m->is_Bool() ||
+        m->is_Cmp() ||
+        op == Op_AndL ||
+        op == Op_OrL ||
+        op == Op_RShiftL ||
+        op == Op_LShiftL ||
+        op == Op_AddL ||
+        op == Op_AddI ||
+        op == Op_MulL ||
+        op == Op_MulI ||
+        op == Op_SubL ||
+        op == Op_SubI ||
+        op == Op_ConvI2L) {
+        to_clone.push(m, 1);
+        continue;
+    }
+    if (op == Op_Opaque1) {
+      if (!clone) {
+        // Update the input of the Opaque1Node and exit
+        _igvn.replace_input_of(m, 1, value);
+        return prev_proj;
+      }
+      if (n->_idx < current) {
+        n = n->clone();
+      }
+      n->set_req(i, value);
+      register_new_node(n, current_proj);
+      to_clone.set_node(n);
+    }
+    for (;;) {
+      Node* cur = to_clone.node();
+      uint j = to_clone.index();
+      if (j+1 < cur->req()) {
+        to_clone.set_index(j+1);
+        break;
+      }
+      to_clone.pop();
+      if (to_clone.size() == 0) {
+        result = cur;
+        break;
+      }
+      Node* next = to_clone.node();
+      j = to_clone.index();
+      if (clone && cur->_idx >= current) {
+        if (next->_idx < current) {
+          next = next->clone();
+          register_new_node(next, current_proj);
+          to_clone.set_node(next);
+        }
+        assert(next->in(j) != cur, "input should have been cloned");
+        next->set_req(j, cur);
+      }
+    }
+  } while (result == NULL);
+  if (!clone) {
+    return NULL;
+  }
+  assert(result->_idx >= current, "new node expected");
+
+  Node* proj = predicate->clone();
+  Node* other_proj = uncommon_proj->clone();
+  Node* new_iff = iff->clone();
+  new_iff->set_req(1, result);
+  proj->set_req(0, new_iff);
+  other_proj->set_req(0, new_iff);
+  Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
+  register_new_node(frame, C->start());
+  // It's impossible for the predicate to fail at runtime. Use an Halt node.
+  Node* halt = new HaltNode(other_proj, frame);
+  C->root()->add_req(halt);
+  new_iff->set_req(0, prev_proj);
+
+  register_control(new_iff, outer_loop->_parent, prev_proj);
+  register_control(proj, outer_loop->_parent, new_iff);
+  register_control(other_proj, _ltree_root, new_iff);
+  register_control(halt, _ltree_root, other_proj);
+  return proj;
+}
+
+void PhaseIdealLoop::duplicate_predicates(CountedLoopNode* pre_head, Node* castii, IdealLoopTree* outer_loop,
+                                          LoopNode* outer_main_head, uint dd_main_head) {
   if (UseLoopPredicate) {
     Node* entry = pre_head->in(LoopNode::EntryControl);
     Node* predicate = NULL;
@@ -1026,112 +1199,16 @@
     if (predicate != NULL) {
       entry = entry->in(0)->in(0);
     }
+    Node* profile_predicate = NULL;
+    if (UseProfiledLoopPredicate) {
+      profile_predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+      if (profile_predicate != NULL) {
+        entry = skip_loop_predicates(entry);
+      }
+    }
     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
-    if (predicate != NULL) {
-      IfNode* iff = entry->in(0)->as_If();
-      ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
-      Node* rgn = uncommon_proj->unique_ctrl_out();
-      assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
-      assert(iff->in(1)->in(1)->Opcode() == Op_Opaque1, "unexpected predicate shape");
-      entry = entry->in(0)->in(0);
-      Node* prev_proj = min_taken;
-      while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
-        uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
-        if (uncommon_proj->unique_ctrl_out() != rgn)
-          break;
-        iff = entry->in(0)->as_If();
-        if (iff->in(1)->Opcode() == Op_Opaque4) {
-          Node_Stack to_clone(2);
-          to_clone.push(iff->in(1), 1);
-          uint current = C->unique();
-          Node* result = NULL;
-          // Look for the opaque node to replace with the init value
-          // and clone everything in between. We keep the Opaque4 node
-          // so the duplicated predicates are eliminated once loop
-          // opts are over: they are here only to keep the IR graph
-          // consistent.
-          do {
-            Node* n = to_clone.node();
-            uint i = to_clone.index();
-            Node* m = n->in(i);
-            int op = m->Opcode();
-            if (m->is_Bool() ||
-                m->is_Cmp() ||
-                op == Op_AndL ||
-                op == Op_OrL ||
-                op == Op_RShiftL ||
-                op == Op_LShiftL ||
-                op == Op_AddL ||
-                op == Op_AddI ||
-                op == Op_MulL ||
-                op == Op_MulI ||
-                op == Op_SubL ||
-                op == Op_SubI ||
-                op == Op_ConvI2L) {
-              to_clone.push(m, 1);
-              continue;
-            }
-            if (op == Op_Opaque1) {
-              if (n->_idx < current) {
-                n = n->clone();
-              }
-              n->set_req(i, castii);
-              register_new_node(n, min_taken);
-              to_clone.set_node(n);
-            }
-            for (;;) {
-              Node* cur = to_clone.node();
-              uint j = to_clone.index();
-              if (j+1 < cur->req()) {
-                to_clone.set_index(j+1);
-                break;
-              }
-              to_clone.pop();
-              if (to_clone.size() == 0) {
-                result = cur;
-                break;
-              }
-              Node* next = to_clone.node();
-              j = to_clone.index();
-              if (cur->_idx >= current) {
-                if (next->_idx < current) {
-                  next = next->clone();
-                  register_new_node(next, min_taken);
-                  to_clone.set_node(next);
-                }
-                assert(next->in(j) != cur, "input should have been cloned");
-                next->set_req(j, cur);
-              }
-            }
-          } while (result == NULL);
-          assert(result->_idx >= current, "new node expected");
-
-          Node* proj = entry->clone();
-          Node* other_proj = uncommon_proj->clone();
-          Node* new_iff = iff->clone();
-          new_iff->set_req(1, result);
-          proj->set_req(0, new_iff);
-          other_proj->set_req(0, new_iff);
-          Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
-          register_new_node(frame, C->start());
-          // It's impossible for the predicate to fail at runtime. Use
-          // an Halt node.
-          Node* halt = new HaltNode(other_proj, frame);
-          C->root()->add_req(halt);
-          new_iff->set_req(0, prev_proj);
-
-          register_control(new_iff, outer_loop->_parent, prev_proj);
-          register_control(proj, outer_loop->_parent, new_iff);
-          register_control(other_proj, _ltree_root, new_iff);
-          register_control(halt, _ltree_root, other_proj);
-
-          prev_proj = proj;
-        }
-        entry = entry->in(0)->in(0);
-      }
-      _igvn.replace_input_of(outer_main_head, LoopNode::EntryControl, prev_proj);
-      set_idom(outer_main_head, prev_proj, dd_main_head);
-    }
+    duplicate_predicates_helper(predicate, castii, outer_loop, outer_main_head, dd_main_head);
+    duplicate_predicates_helper(profile_predicate, castii, outer_loop, outer_main_head, dd_main_head);
   }
 }
 
@@ -1278,7 +1355,7 @@
   // CastII for the main loop:
   Node* castii = cast_incr_before_loop( pre_incr, min_taken, main_head );
   assert(castii != NULL, "no castII inserted");
-  duplicate_predicates(pre_head, min_taken, castii, outer_loop, outer_main_head, dd_main_head);
+  duplicate_predicates(pre_head, castii, outer_loop, outer_main_head, dd_main_head);
 
   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
   // RCE and alignment may change this later.
@@ -1622,6 +1699,30 @@
   assert(old_trip_count > 1 &&
       (!adjust_min_trip || stride_p <= (1<<3)*loop_head->unrolled_count()), "sanity");
 
+  if (UseLoopPredicate) {
+    // Search for skeleton predicates and update them according to the new stride
+    Node* entry = ctrl;
+    while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
+      IfNode* iff = entry->in(0)->as_If();
+      ProjNode* proj = iff->proj_out(1 - entry->as_Proj()->_con);
+      if (proj->unique_ctrl_out()->Opcode() != Op_Halt) {
+        break;
+      }
+      if (iff->in(1)->Opcode() == Op_Opaque4) {
+        // Compute the value of the loop induction variable at the end of the
+        // first iteration of the unrolled loop: init + new_stride_con - init_inc
+        int init_inc = stride_con/loop_head->unrolled_count();
+        assert(init_inc != 0, "invalid loop increment");
+        int new_stride_con = stride_con * 2;
+        Node* max_value = _igvn.intcon(new_stride_con - init_inc);
+        max_value = new AddINode(init, max_value);
+        register_new_node(max_value, get_ctrl(iff->in(1)));
+        update_skeleton_predicate(iff, max_value);
+      }
+      entry = entry->in(0)->in(0);
+    }
+  }
+
   // Adjust loop limit to keep valid iterations number after unroll.
   // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
   // which may overflow.
@@ -2815,7 +2916,7 @@
   }
   if (needs_guard) {
     // Check for an obvious zero trip guard.
-    Node* inctrl = PhaseIdealLoop::skip_loop_predicates(cl->skip_predicates());
+    Node* inctrl = PhaseIdealLoop::skip_all_loop_predicates(cl->skip_predicates());
     if (inctrl->Opcode() == Op_IfTrue || inctrl->Opcode() == Op_IfFalse) {
       bool maybe_swapped = (inctrl->Opcode() == Op_IfFalse);
       // The test should look like just the backedge of a CountedLoop
--- a/src/hotspot/share/opto/loopUnswitch.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/loopUnswitch.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -138,9 +138,19 @@
   Node* uniqc = proj_true->unique_ctrl_out();
   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
   Node* predicate = find_predicate(entry);
+  if (predicate != NULL) {
+    entry = skip_loop_predicates(entry);
+  }
   if (predicate != NULL && UseLoopPredicate) {
     // We may have two predicates, find first.
-    entry = find_predicate(entry->in(0)->in(0));
+    Node* n = find_predicate(entry);
+    if (n != NULL) {
+      predicate = n;
+      entry = skip_loop_predicates(entry);
+    }
+  }
+  if (predicate != NULL && UseProfiledLoopPredicate) {
+    entry = find_predicate(entry);
     if (entry != NULL) predicate = entry;
   }
   if (predicate != NULL) predicate = predicate->in(0);
--- a/src/hotspot/share/opto/loopnode.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/loopnode.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1281,9 +1281,7 @@
   return l->outer_safepoint();
 }
 
-Node* CountedLoopNode::skip_predicates() {
-  if (is_main_loop()) {
-    Node* ctrl = skip_strip_mined()->in(LoopNode::EntryControl);
+Node* CountedLoopNode::skip_predicates_from_entry(Node* ctrl) {
     while (ctrl != NULL && ctrl->is_Proj() && ctrl->in(0)->is_If() &&
            ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->outcnt() == 1 &&
            ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->unique_out()->Opcode() == Op_Halt) {
@@ -1292,6 +1290,13 @@
 
     return ctrl;
   }
+
+Node* CountedLoopNode::skip_predicates() {
+  if (is_main_loop()) {
+    Node* ctrl = skip_strip_mined()->in(LoopNode::EntryControl);
+
+    return skip_predicates_from_entry(ctrl);
+  }
   return in(LoopNode::EntryControl);
 }
 
@@ -2400,6 +2405,13 @@
     entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
     if (entry != NULL) {
       tty->print(" predicated");
+      entry = PhaseIdealLoop::skip_loop_predicates(entry);
+    }
+  }
+  if (UseProfiledLoopPredicate) {
+    entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
+    if (entry != NULL) {
+      tty->print(" profile_predicated");
     }
   }
   if (_head->is_CountedLoop()) {
@@ -2507,11 +2519,18 @@
     if (predicate_proj != NULL ) { // right pattern that can be used by loop predication
       assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be");
       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
-      entry = entry->in(0)->in(0);
+      entry = skip_loop_predicates(entry);
     }
     predicate_proj = find_predicate(entry); // Predicate
     if (predicate_proj != NULL ) {
       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
+      entry = skip_loop_predicates(entry);
+    }
+    if (UseProfiledLoopPredicate) {
+      predicate_proj = find_predicate(entry); // Predicate
+      if (predicate_proj != NULL ) {
+        useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
+      }
     }
   }
 
@@ -4205,12 +4224,33 @@
   // which can inhibit range check elimination.
   if (least != early) {
     Node* ctrl_out = least->unique_ctrl_out();
-    if (ctrl_out && ctrl_out->is_Loop() &&
-        least == ctrl_out->in(LoopNode::EntryControl) &&
-        (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) {
-      Node* least_dom = idom(least);
-      if (get_loop(least_dom)->is_member(get_loop(least))) {
-        least = least_dom;
+    if (ctrl_out && ctrl_out->is_CountedLoop() &&
+        least == ctrl_out->in(LoopNode::EntryControl)) {
+      Node* new_ctrl = least;
+      // Move the node above predicates so a following pass of loop
+      // predication doesn't hoist a predicate that depends on it
+      // above that node.
+      if (find_predicate_insertion_point(new_ctrl, Deoptimization::Reason_loop_limit_check) != NULL) {
+        new_ctrl = new_ctrl->in(0)->in(0);
+        assert(is_dominator(early, new_ctrl), "least != early so we can move up the dominator tree");
+      }
+      if (find_predicate_insertion_point(new_ctrl, Deoptimization::Reason_profile_predicate) != NULL) {
+        Node* c = new_ctrl->in(0)->in(0);
+        assert(is_dominator(early, c), "least != early so we can move up the dominator tree");
+        new_ctrl = c;
+      }
+      if (find_predicate_insertion_point(new_ctrl, Deoptimization::Reason_predicate) != NULL) {
+        Node* c = new_ctrl->in(0)->in(0);
+        assert(is_dominator(early, c), "least != early so we can move up the dominator tree");
+        new_ctrl = c;
+      }
+      if (new_ctrl != ctrl_out) {
+        least = new_ctrl;
+      } else if (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop()) {
+        Node* least_dom = idom(least);
+        if (get_loop(least_dom)->is_member(get_loop(least))) {
+          least = least_dom;
+        }
       }
     }
   }
--- a/src/hotspot/share/opto/loopnode.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/loopnode.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -38,6 +38,7 @@
 class LoopNode;
 class Node;
 class OuterStripMinedLoopEndNode;
+class PathFrequency;
 class PhaseIdealLoop;
 class CountedLoopReserveKit;
 class VectorSet;
@@ -57,7 +58,7 @@
   // the semantics so it does not appear in the hash & cmp functions.
   virtual uint size_of() const { return sizeof(*this); }
 protected:
-  short _loop_flags;
+  uint _loop_flags;
   // Names for flag bitfields
   enum { Normal=0, Pre=1, Main=2, Post=3, PreMainPostFlagsMask=3,
          MainHasNoPreLoop=4,
@@ -73,26 +74,31 @@
          HasAtomicPostLoop=4096,
          HasRangeChecks=8192,
          IsMultiversioned=16384,
-         StripMined=32768};
+         StripMined=32768,
+         ProfileTripFailed=65536};
   char _unswitch_count;
   enum { _unswitch_max=3 };
   char _postloop_flags;
   enum { LoopNotRCEChecked = 0, LoopRCEChecked = 1, RCEPostLoop = 2 };
 
+  // Expected trip count from profile data
+  float _profile_trip_cnt;
+
 public:
   // Names for edge indices
   enum { Self=0, EntryControl, LoopBackControl };
 
-  int is_inner_loop() const { return _loop_flags & InnerLoop; }
+  bool is_inner_loop() const { return _loop_flags & InnerLoop; }
   void set_inner_loop() { _loop_flags |= InnerLoop; }
 
-  int range_checks_present() const { return _loop_flags & HasRangeChecks; }
-  int is_multiversioned() const { return _loop_flags & IsMultiversioned; }
-  int is_vectorized_loop() const { return _loop_flags & VectorizedLoop; }
-  int is_partial_peel_loop() const { return _loop_flags & PartialPeelLoop; }
+  bool range_checks_present() const { return _loop_flags & HasRangeChecks; }
+  bool is_multiversioned() const { return _loop_flags & IsMultiversioned; }
+  bool is_vectorized_loop() const { return _loop_flags & VectorizedLoop; }
+  bool is_partial_peel_loop() const { return _loop_flags & PartialPeelLoop; }
   void set_partial_peel_loop() { _loop_flags |= PartialPeelLoop; }
-  int partial_peel_has_failed() const { return _loop_flags & PartialPeelFailed; }
-  int is_strip_mined() const { return _loop_flags & StripMined; }
+  bool partial_peel_has_failed() const { return _loop_flags & PartialPeelFailed; }
+  bool is_strip_mined() const { return _loop_flags & StripMined; }
+  bool is_profile_trip_failed() const { return _loop_flags & ProfileTripFailed; }
 
   void mark_partial_peel_failed() { _loop_flags |= PartialPeelFailed; }
   void mark_has_reductions() { _loop_flags |= HasReductions; }
@@ -105,6 +111,7 @@
   void mark_is_multiversioned() { _loop_flags |= IsMultiversioned; }
   void mark_strip_mined() { _loop_flags |= StripMined; }
   void clear_strip_mined() { _loop_flags &= ~StripMined; }
+  void mark_profile_trip_failed() { _loop_flags |= ProfileTripFailed; }
 
   int unswitch_max() { return _unswitch_max; }
   int unswitch_count() { return _unswitch_count; }
@@ -119,7 +126,12 @@
     _unswitch_count = val;
   }
 
-  LoopNode(Node *entry, Node *backedge) : RegionNode(3), _loop_flags(0), _unswitch_count(0), _postloop_flags(0) {
+  void set_profile_trip_cnt(float ptc) { _profile_trip_cnt = ptc; }
+  float profile_trip_cnt()             { return _profile_trip_cnt; }
+
+  LoopNode(Node *entry, Node *backedge)
+    : RegionNode(3), _loop_flags(0), _unswitch_count(0),
+      _postloop_flags(0), _profile_trip_cnt(COUNT_UNKNOWN)  {
     init_class_id(Class_Loop);
     init_req(EntryControl, entry);
     init_req(LoopBackControl, backedge);
@@ -186,9 +198,6 @@
   // Known trip count calculated by compute_exact_trip_count()
   uint  _trip_count;
 
-  // Expected trip count from profile data
-  float _profile_trip_cnt;
-
   // Log2 of original loop bodies in unrolled loop
   int _unrolled_count_log2;
 
@@ -203,8 +212,8 @@
 public:
   CountedLoopNode( Node *entry, Node *backedge )
     : LoopNode(entry, backedge), _main_idx(0), _trip_count(max_juint),
-      _profile_trip_cnt(COUNT_UNKNOWN), _unrolled_count_log2(0),
-      _node_count_before_unroll(0), _slp_maximum_unroll_factor(0) {
+      _unrolled_count_log2(0), _node_count_before_unroll(0),
+      _slp_maximum_unroll_factor(0) {
     init_class_id(Class_CountedLoop);
     // Initialize _trip_count to the largest possible value.
     // Will be reset (lower) if the loop's trip count is known.
@@ -245,16 +254,16 @@
 
   // A 'main' loop that is ONLY unrolled or peeled, never RCE'd or
   // Aligned, may be missing it's pre-loop.
-  int is_normal_loop   () const { return (_loop_flags&PreMainPostFlagsMask) == Normal; }
-  int is_pre_loop      () const { return (_loop_flags&PreMainPostFlagsMask) == Pre;    }
-  int is_main_loop     () const { return (_loop_flags&PreMainPostFlagsMask) == Main;   }
-  int is_post_loop     () const { return (_loop_flags&PreMainPostFlagsMask) == Post;   }
-  int is_reduction_loop() const { return (_loop_flags&HasReductions) == HasReductions; }
-  int was_slp_analyzed () const { return (_loop_flags&WasSlpAnalyzed) == WasSlpAnalyzed; }
-  int has_passed_slp   () const { return (_loop_flags&PassedSlpAnalysis) == PassedSlpAnalysis; }
-  int do_unroll_only      () const { return (_loop_flags&DoUnrollOnly) == DoUnrollOnly; }
-  int is_main_no_pre_loop() const { return _loop_flags & MainHasNoPreLoop; }
-  int has_atomic_post_loop  () const { return (_loop_flags & HasAtomicPostLoop) == HasAtomicPostLoop; }
+  bool is_normal_loop   () const { return (_loop_flags&PreMainPostFlagsMask) == Normal; }
+  bool is_pre_loop      () const { return (_loop_flags&PreMainPostFlagsMask) == Pre;    }
+  bool is_main_loop     () const { return (_loop_flags&PreMainPostFlagsMask) == Main;   }
+  bool is_post_loop     () const { return (_loop_flags&PreMainPostFlagsMask) == Post;   }
+  bool is_reduction_loop() const { return (_loop_flags&HasReductions) == HasReductions; }
+  bool was_slp_analyzed () const { return (_loop_flags&WasSlpAnalyzed) == WasSlpAnalyzed; }
+  bool has_passed_slp   () const { return (_loop_flags&PassedSlpAnalysis) == PassedSlpAnalysis; }
+  bool do_unroll_only      () const { return (_loop_flags&DoUnrollOnly) == DoUnrollOnly; }
+  bool is_main_no_pre_loop() const { return _loop_flags & MainHasNoPreLoop; }
+  bool has_atomic_post_loop  () const { return (_loop_flags & HasAtomicPostLoop) == HasAtomicPostLoop; }
   void set_main_no_pre_loop() { _loop_flags |= MainHasNoPreLoop; }
 
   int main_idx() const { return _main_idx; }
@@ -280,9 +289,6 @@
     _loop_flags &= ~PassedSlpAnalysis;
   }
 
-  void set_profile_trip_cnt(float ptc) { _profile_trip_cnt = ptc; }
-  float profile_trip_cnt()             { return _profile_trip_cnt; }
-
   void double_unrolled_count() { _unrolled_count_log2++; }
   int  unrolled_count()        { return 1 << MIN2(_unrolled_count_log2, BitsPerInt-3); }
 
@@ -301,6 +307,7 @@
   // If this is a main loop in a pre/main/post loop nest, walk over
   // the predicates that were inserted by
   // duplicate_predicates()/add_range_check_predicate()
+  static Node* skip_predicates_from_entry(Node* ctrl);
   Node* skip_predicates();
 
 #ifndef PRODUCT
@@ -588,6 +595,7 @@
   void compute_trip_count(PhaseIdealLoop* phase);
 
   // Compute loop trip count from profile data
+  float compute_profile_trip_cnt_helper(Node* n);
   void compute_profile_trip_cnt( PhaseIdealLoop *phase );
 
   // Reassociate invariant expressions.
@@ -732,9 +740,12 @@
   }
 
   Node* cast_incr_before_loop(Node* incr, Node* ctrl, Node* loop);
-  void duplicate_predicates(CountedLoopNode* pre_head, Node *min_taken, Node* castii,
-                            IdealLoopTree* outer_loop, LoopNode* outer_main_head,
-                            uint dd_main_head);
+  void duplicate_predicates_helper(Node* predicate, Node* castii, IdealLoopTree* outer_loop,
+                                   LoopNode* outer_main_head, uint dd_main_head);
+  void duplicate_predicates(CountedLoopNode* pre_head, Node* castii, IdealLoopTree* outer_loop,
+                            LoopNode* outer_main_head, uint dd_main_head);
+  Node* update_skeleton_predicate(Node* iff, Node* value, Node* predicate = NULL, Node* uncommon_proj = NULL,
+                                  Node* current_proj = NULL, IdealLoopTree* outer_loop = NULL, Node* prev_proj = NULL);
 
 public:
 
@@ -1073,6 +1084,7 @@
                                          PhaseIterGVN* igvn);
   Node* clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check);
 
+  static Node* skip_all_loop_predicates(Node* entry);
   static Node* skip_loop_predicates(Node* entry);
 
   // Find a good location to insert a predicate
@@ -1087,12 +1099,20 @@
 
   // Implementation of the loop predication to promote checks outside the loop
   bool loop_predication_impl(IdealLoopTree *loop);
+  bool loop_predication_impl_helper(IdealLoopTree *loop, ProjNode* proj, ProjNode *predicate_proj,
+                                    CountedLoopNode *cl, ConNode* zero, Invariance& invar,
+                                    Deoptimization::DeoptReason reason);
+  bool loop_predication_should_follow_branches(IdealLoopTree *loop, ProjNode *predicate_proj, float& loop_trip_cnt);
+  void loop_predication_follow_branches(Node *c, IdealLoopTree *loop, float loop_trip_cnt,
+                                        PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
+                                        Node_List& if_proj_list);
   ProjNode* insert_skeleton_predicate(IfNode* iff, IdealLoopTree *loop,
                                       ProjNode* proj, ProjNode *predicate_proj,
                                       ProjNode* upper_bound_proj,
                                       int scale, Node* offset,
                                       Node* init, Node* limit, jint stride,
-                                      Node* rng, bool& overflow);
+                                      Node* rng, bool& overflow,
+                                      Deoptimization::DeoptReason reason);
   Node* add_range_check_predicate(IdealLoopTree* loop, CountedLoopNode* cl,
                                   Node* predicate_proj, int scale_con, Node* offset,
                                   Node* limit, jint stride_con);
--- a/src/hotspot/share/opto/node.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/node.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -73,6 +73,7 @@
 class FastLockNode;
 class FastUnlockNode;
 class IfNode;
+class IfProjNode;
 class IfFalseNode;
 class IfTrueNode;
 class InitializeNode;
@@ -676,8 +677,9 @@
     DEFINE_CLASS_ID(Proj,  Node, 3)
       DEFINE_CLASS_ID(CatchProj, Proj, 0)
       DEFINE_CLASS_ID(JumpProj,  Proj, 1)
-      DEFINE_CLASS_ID(IfTrue,    Proj, 2)
-      DEFINE_CLASS_ID(IfFalse,   Proj, 3)
+      DEFINE_CLASS_ID(IfProj,    Proj, 2)
+        DEFINE_CLASS_ID(IfTrue,    IfProj, 0)
+        DEFINE_CLASS_ID(IfFalse,   IfProj, 1)
       DEFINE_CLASS_ID(Parm,      Proj, 4)
       DEFINE_CLASS_ID(MachProj,  Proj, 5)
 
@@ -818,6 +820,7 @@
   DEFINE_CLASS_QUERY(FastUnlock)
   DEFINE_CLASS_QUERY(If)
   DEFINE_CLASS_QUERY(RangeCheck)
+  DEFINE_CLASS_QUERY(IfProj)
   DEFINE_CLASS_QUERY(IfFalse)
   DEFINE_CLASS_QUERY(IfTrue)
   DEFINE_CLASS_QUERY(Initialize)
--- a/src/hotspot/share/opto/parse.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/parse.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -161,6 +161,7 @@
     bool               _has_merged_backedge; // does this block have merged backedge?
     SafePointNode*     _start_map;      // all values flowing into this block
     MethodLivenessResult _live_locals;  // lazily initialized liveness bitmap
+    bool               _has_predicates; // Were predicates added before parsing of the loop head?
 
     int                _num_successors; // Includes only normal control flow.
     int                _all_successors; // Include exception paths also.
@@ -203,6 +204,9 @@
     // True when all non-exception predecessors have been parsed.
     bool is_ready() const                  { return preds_parsed() == pred_count(); }
 
+    bool has_predicates() const            { return _has_predicates; }
+    void set_has_predicates()              { _has_predicates = true; }
+
     int num_successors() const             { return _num_successors; }
     int all_successors() const             { return _all_successors; }
     Block* successor_at(int i) const {
@@ -552,6 +556,7 @@
   void    sharpen_type_after_if(BoolTest::mask btest,
                                 Node* con, const Type* tcon,
                                 Node* val, const Type* tval);
+  void    maybe_add_predicate_after_if(Block* path);
   IfNode* jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt);
   Node*   jump_if_join(Node* iffalse, Node* iftrue);
   void    jump_if_true_fork(IfNode *ifNode, int dest_bci_if_true, int prof_table_index, bool unc);
--- a/src/hotspot/share/opto/parse1.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/parse1.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -666,10 +666,13 @@
         if (block->is_SEL_head()) {
           // Add predicate to single entry (not irreducible) loop head.
           assert(!block->has_merged_backedge(), "only entry paths should be merged for now");
-          // Need correct bci for predicate.
-          // It is fine to set it here since do_one_block() will set it anyway.
-          set_parse_bci(block->start());
-          add_predicate();
+          // Predicates may have been added after a dominating if
+          if (!block->has_predicates()) {
+            // Need correct bci for predicate.
+            // It is fine to set it here since do_one_block() will set it anyway.
+            set_parse_bci(block->start());
+            add_predicate();
+          }
           // Add new region for back branches.
           int edges = block->pred_count() - block->preds_parsed() + 1; // +1 for original region
           RegionNode *r = new RegionNode(edges+1);
@@ -1262,6 +1265,7 @@
   _is_handler = false;
   _has_merged_backedge = false;
   _start_map = NULL;
+  _has_predicates = false;
   _num_successors = 0;
   _all_successors = 0;
   _successors = NULL;
--- a/src/hotspot/share/opto/parse2.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/parse2.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1649,6 +1649,18 @@
   return (seems_never_taken(prob) && seems_stable_comparison());
 }
 
+void Parse::maybe_add_predicate_after_if(Block* path) {
+  if (path->is_SEL_head() && path->preds_parsed() == 0) {
+    // Add predicates at bci of if dominating the loop so traps can be
+    // recorded on the if's profile data
+    int bc_depth = repush_if_args();
+    add_predicate();
+    dec_sp(bc_depth);
+    path->set_has_predicates();
+  }
+}
+
+
 //----------------------------adjust_map_after_if------------------------------
 // Adjust the JVM state to reflect the result of taking this path.
 // Basically, it means inspecting the CmpNode controlling this
@@ -1657,8 +1669,14 @@
 // as graph nodes in the current abstract interpretation map.
 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
                                 Block* path, Block* other_path) {
-  if (stopped() || !c->is_Cmp() || btest == BoolTest::illegal)
+  if (!c->is_Cmp()) {
+    maybe_add_predicate_after_if(path);
+    return;
+  }
+
+  if (stopped() || btest == BoolTest::illegal) {
     return;                             // nothing to do
+  }
 
   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
 
@@ -1690,10 +1708,13 @@
       have_con = false;
     }
   }
-  if (!have_con)                        // remaining adjustments need a con
+  if (!have_con) {                        // remaining adjustments need a con
+    maybe_add_predicate_after_if(path);
     return;
+  }
 
   sharpen_type_after_if(btest, con, tcon, val, tval);
+  maybe_add_predicate_after_if(path);
 }
 
 
--- a/src/hotspot/share/opto/superword.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/opto/superword.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -887,7 +887,9 @@
   if (init_nd->is_Con() && p.invar() == NULL) {
     int init = init_nd->bottom_type()->is_int()->get_con();
     int init_offset = init * p.scale_in_bytes() + offset;
-    assert(init_offset >= 0, "positive offset from object start");
+    if (init_offset < 0) { // negative offset from object start?
+      return false;        // may happen in dead loop
+    }
     if (vw % span == 0) {
       // If vm is a multiple of span, we use formula (1).
       if (span > 0) {
--- a/src/hotspot/share/prims/jni.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/prims/jni.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -2630,7 +2630,17 @@
     if (v == NULL || v->is_a(ObjArrayKlass::cast(a->klass())->element_klass())) {
       a->obj_at_put(index, v);
     } else {
-      THROW(vmSymbols::java_lang_ArrayStoreException());
+      ResourceMark rm(THREAD);
+      stringStream ss;
+      Klass *bottom_kl = ObjArrayKlass::cast(a->klass())->bottom_klass();
+      ss.print("type mismatch: can not store %s to %s[%d]",
+               v->klass()->external_name(),
+               bottom_kl->is_typeArray_klass() ? type2name_tab[ArrayKlass::cast(bottom_kl)->element_type()] : bottom_kl->external_name(),
+               index);
+      for (int dims = ArrayKlass::cast(a->klass())->dimension(); dims > 1; --dims) {
+        ss.print("[]");
+      }
+      THROW_MSG(vmSymbols::java_lang_ArrayStoreException(), ss.as_string());
     }
   } else {
     char buf[jintAsStringSize];
--- a/src/hotspot/share/prims/jvmtiEnv.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiEnv.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -657,7 +657,11 @@
 
     // add the jar file to the bootclasspath
     log_info(class, load)("opened: %s", zip_entry->name());
+#if INCLUDE_CDS
     ClassLoaderExt::append_boot_classpath(zip_entry);
+#else
+    ClassLoader::add_to_boot_append_entries(zip_entry);
+#endif
     return JVMTI_ERROR_NONE;
   } else {
     return JVMTI_ERROR_WRONG_PHASE;
--- a/src/hotspot/share/prims/jvmtiTagMap.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiTagMap.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -90,11 +90,11 @@
 
   // accessor methods
   inline oop* object_addr() { return &_object; }
-  inline oop object()       { return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(object_addr()); }
+  inline oop object()       { return NativeAccess<ON_PHANTOM_OOP_REF>::oop_load(object_addr()); }
   // Peek at the object without keeping it alive. The returned object must be
   // kept alive using a normal access if it leaks out of a thread transition from VM.
   inline oop object_peek()  {
-    return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(object_addr());
+    return NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(object_addr());
   }
   inline jlong tag() const  { return _tag; }
 
--- a/src/hotspot/share/runtime/arguments.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/arguments.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1592,101 +1592,6 @@
   }
 }
 
-// Returns threshold scaled with the value of scale.
-// If scale < 0.0, threshold is returned without scaling.
-intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
-  if (scale == 1.0 || scale < 0.0) {
-    return threshold;
-  } else {
-    return (intx)(threshold * scale);
-  }
-}
-
-// Returns freq_log scaled with the value of scale.
-// Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
-// If scale < 0.0, freq_log is returned without scaling.
-intx Arguments::scaled_freq_log(intx freq_log, double scale) {
-  // Check if scaling is necessary or if negative value was specified.
-  if (scale == 1.0 || scale < 0.0) {
-    return freq_log;
-  }
-  // Check values to avoid calculating log2 of 0.
-  if (scale == 0.0 || freq_log == 0) {
-    return 0;
-  }
-  // Determine the maximum notification frequency value currently supported.
-  // The largest mask value that the interpreter/C1 can handle is
-  // of length InvocationCounter::number_of_count_bits. Mask values are always
-  // one bit shorter then the value of the notification frequency. Set
-  // max_freq_bits accordingly.
-  intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
-  intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
-  if (scaled_freq == 0) {
-    // Return 0 right away to avoid calculating log2 of 0.
-    return 0;
-  } else if (scaled_freq > nth_bit(max_freq_bits)) {
-    return max_freq_bits;
-  } else {
-    return log2_intptr(scaled_freq);
-  }
-}
-
-void Arguments::set_tiered_flags() {
-  // With tiered, set default policy to SimpleThresholdPolicy, which is 2.
-  if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
-    FLAG_SET_DEFAULT(CompilationPolicyChoice, 2);
-  }
-  if (CompilationPolicyChoice < 2) {
-    vm_exit_during_initialization(
-      "Incompatible compilation policy selected", NULL);
-  }
-  // Increase the code cache size - tiered compiles a lot more.
-  if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
-    FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
-                  MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
-  }
-  // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
-  if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
-    FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
-  }
-  if (!UseInterpreter) { // -Xcomp
-    Tier3InvokeNotifyFreqLog = 0;
-    Tier4InvocationThreshold = 0;
-  }
-
-  if (CompileThresholdScaling < 0) {
-    vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
-  }
-
-  // Scale tiered compilation thresholds.
-  // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
-  if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
-    FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
-    FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
-
-    FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
-    FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
-    FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
-    FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
-
-    // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
-    // once these thresholds become supported.
-
-    FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
-    FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
-
-    FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
-    FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
-
-    FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
-
-    FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
-    FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
-    FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
-    FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
-  }
-}
-
 void set_object_alignment() {
   // Object alignment.
   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
@@ -1787,74 +1692,9 @@
                                           CollectorPolicy::compute_heap_alignment());
 }
 
-#ifdef TIERED
-bool Arguments::compilation_mode_selected() {
- return !FLAG_IS_DEFAULT(TieredCompilation) || !FLAG_IS_DEFAULT(TieredStopAtLevel) ||
-        !FLAG_IS_DEFAULT(UseAOT) JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler));
-
-}
-
-void Arguments::select_compilation_mode_ergonomically() {
-#if defined(_WINDOWS) && !defined(_LP64)
-  if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) {
-    FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true);
-  }
-#endif
-  if (NeverActAsServerClassMachine) {
-    set_client_compilation_mode();
-  }
-}
-#endif //TIERED
-
-#if INCLUDE_JVMCI
-void Arguments::set_jvmci_specific_flags() {
-  if (UseJVMCICompiler) {
-    if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
-      FLAG_SET_DEFAULT(TypeProfileWidth, 8);
-    }
-    if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
-      FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
-    }
-    if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
-      FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
-    }
-    if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
-      FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
-    }
-    if (FLAG_IS_DEFAULT(MetaspaceSize)) {
-      FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
-    }
-    if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
-      FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
-    }
-    if (TieredStopAtLevel != CompLevel_full_optimization) {
-      // Currently JVMCI compiler can only work at the full optimization level
-      warning("forcing TieredStopAtLevel to full optimization because JVMCI is enabled");
-      TieredStopAtLevel = CompLevel_full_optimization;
-    }
-    if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
-      FLAG_SET_DEFAULT(TypeProfileLevel, 0);
-    }
-  }
-}
-#endif
-
 jint Arguments::set_ergonomics_flags() {
-#ifdef TIERED
-  if (!compilation_mode_selected()) {
-    select_compilation_mode_ergonomically();
-  }
-#endif
-
   GCConfig::initialize();
 
-#if defined(IA32)
-  // Only server compiler can optimize safepoints well enough.
-  if (!is_server_compilation_mode_vm()) {
-    FLAG_SET_ERGO_IF_DEFAULT(bool, ThreadLocalHandshakes, false);
-  }
-#endif
-
   set_conservative_max_heap_alignment();
 
 #ifndef ZERO
@@ -2185,12 +2025,11 @@
 //===========================================================================================================
 // Parsing of main arguments
 
-#if INCLUDE_JVMCI
-// Check consistency of jvmci vm argument settings.
-bool Arguments::check_jvmci_args_consistency() {
-   return JVMCIGlobals::check_jvmci_flags_are_consistent();
-}
-#endif //INCLUDE_JVMCI
+unsigned int addreads_count = 0;
+unsigned int addexports_count = 0;
+unsigned int addopens_count = 0;
+unsigned int addmods_count = 0;
+unsigned int patch_mod_count = 0;
 
 // Check the consistency of vm_init_args
 bool Arguments::check_vm_args_consistency() {
@@ -2219,52 +2058,17 @@
 #endif
   }
 
+  status = CompilerConfig::check_args_consistency(status);
 #if INCLUDE_JVMCI
-  status = status && check_jvmci_args_consistency();
-
-  if (EnableJVMCI) {
+  if (status && EnableJVMCI) {
     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
         AddProperty, UnwriteableProperty, InternalProperty);
-
-    if (!ScavengeRootsInCode) {
-      warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
-      ScavengeRootsInCode = 1;
+    if (!create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
+      return false;
     }
   }
 #endif
 
-  // Check lower bounds of the code cache
-  // Template Interpreter code is approximately 3X larger in debug builds.
-  uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
-  if (ReservedCodeCacheSize < InitialCodeCacheSize) {
-    jio_fprintf(defaultStream::error_stream(),
-                "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
-                ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
-    status = false;
-  } else if (ReservedCodeCacheSize < min_code_cache_size) {
-    jio_fprintf(defaultStream::error_stream(),
-                "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
-                min_code_cache_size/K);
-    status = false;
-  } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
-    // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
-    jio_fprintf(defaultStream::error_stream(),
-                "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
-                CODE_CACHE_SIZE_LIMIT/M);
-    status = false;
-  } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
-    jio_fprintf(defaultStream::error_stream(),
-                "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
-                min_code_cache_size/K);
-    status = false;
-  }
-
-#ifdef _LP64
-  if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
-    warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
-  }
-#endif
-
 #ifndef SUPPORT_RESERVED_STACK_AREA
   if (StackReservedPages != 0) {
     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
@@ -2272,37 +2076,6 @@
   }
 #endif
 
-  if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
-    if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
-      warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
-    }
-    FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
-  }
-  if (UseCompiler && is_interpreter_only()) {
-    if (!FLAG_IS_DEFAULT(UseCompiler)) {
-      warning("UseCompiler disabled due to -Xint.");
-    }
-    FLAG_SET_CMDLINE(bool, UseCompiler, false);
-  }
-#ifdef COMPILER2
-  if (PostLoopMultiversioning && !RangeCheckElimination) {
-    if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
-      warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
-    }
-    FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
-  }
-  if (UseCountedLoopSafepoints && LoopStripMiningIter == 0) {
-    if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
-      warning("When counted loop safepoints are enabled, LoopStripMiningIter must be at least 1 (a safepoint every 1 iteration): setting it to 1");
-    }
-    LoopStripMiningIter = 1;
-  } else if (!UseCountedLoopSafepoints && LoopStripMiningIter > 0) {
-    if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
-      warning("Disabling counted safepoints implies no loop strip mining: setting LoopStripMiningIter to 0");
-    }
-    LoopStripMiningIter = 0;
-  }
-#endif
   if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
     if ((UseNUMAInterleaving && !FLAG_IS_DEFAULT(UseNUMAInterleaving)) || (UseNUMA && !FLAG_IS_DEFAULT(UseNUMA))) {
       log_warning(arguments) ("NUMA support for Heap depends on the file system when AllocateHeapAt option is used.\n");
@@ -2364,12 +2137,6 @@
   return false;
 }
 
-unsigned int addreads_count = 0;
-unsigned int addexports_count = 0;
-unsigned int addopens_count = 0;
-unsigned int addmods_count = 0;
-unsigned int patch_mod_count = 0;
-
 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
   char* property = AllocateHeap(prop_len, mtArguments);
@@ -3358,13 +3125,6 @@
     FLAG_SET_DEFAULT(UseLargePages, false);
   }
 
-#elif defined(COMPILER2)
-  if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
-    FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
-  }
-#endif
-
-#if !COMPILER2_OR_JVMCI
   UNSUPPORTED_OPTION(ProfileInterpreter);
   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
 #endif
@@ -3378,19 +3138,6 @@
     return JNI_ERR;
   }
 
-#if INCLUDE_JVMCI
-  if (EnableJVMCI &&
-      !create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
-    return JNI_ENOMEM;
-  }
-#endif
-
-#if INCLUDE_JVMCI
-  if (UseJVMCICompiler) {
-    Compilation_mode = CompMode_server;
-  }
-#endif
-
 #if INCLUDE_CDS
   if (DumpSharedSpaces) {
     // Disable biased locking now as it interferes with the clean up of
@@ -4149,41 +3896,8 @@
   jint result = set_ergonomics_flags();
   if (result != JNI_OK) return result;
 
-#if INCLUDE_JVMCI
-  set_jvmci_specific_flags();
-#endif
-
   set_shared_spaces_flags();
 
-  if (TieredCompilation) {
-    set_tiered_flags();
-  } else {
-    int max_compilation_policy_choice = 1;
-#ifdef COMPILER2
-    if (is_server_compilation_mode_vm()) {
-      max_compilation_policy_choice = 2;
-    }
-#endif
-    // Check if the policy is valid.
-    if (CompilationPolicyChoice >= max_compilation_policy_choice) {
-      vm_exit_during_initialization(
-        "Incompatible compilation policy selected", NULL);
-    }
-    // Scale CompileThreshold
-    // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
-    if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
-      FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
-    }
-  }
-
-#ifdef COMPILER2
-#ifndef PRODUCT
-  if (PrintIdealGraphLevel > 0) {
-    FLAG_SET_ERGO(bool, PrintIdealGraph, true);
-  }
-#endif
-#endif
-
   // Set heap size based on available physical memory
   set_heap_size();
 
@@ -4192,6 +3906,10 @@
   // Initialize Metaspace flags and alignments
   Metaspace::ergo_initialize();
 
+  // Set compiler flags after GC is selected and GC specific
+  // flags (LoopStripMiningIter) are set.
+  CompilerConfig::ergo_initialize();
+
   // Set bytecode rewriting flags
   set_bytecode_flags();
 
@@ -4229,28 +3947,6 @@
   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
 #endif // CC_INTERP
 
-#ifdef COMPILER2
-  if (!EliminateLocks) {
-    EliminateNestedLocks = false;
-  }
-  if (!Inline) {
-    IncrementalInline = false;
-  }
-#ifndef PRODUCT
-  if (!IncrementalInline) {
-    AlwaysIncrementalInline = false;
-  }
-#endif
-  if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
-    // nothing to use the profiling, turn if off
-    FLAG_SET_DEFAULT(TypeProfileLevel, 0);
-  }
-  if (FLAG_IS_DEFAULT(LoopStripMiningIterShortLoop)) {
-    // blind guess
-    LoopStripMiningIterShortLoop = LoopStripMiningIter / 10;
-  }
-#endif
-
   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
     DebugNonSafepoints = true;
@@ -4260,11 +3956,6 @@
     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
   }
 
-  if (UseOnStackReplacement && !UseLoopCounter) {
-    warning("On-stack-replacement requires loop counters; enabling loop counters");
-    FLAG_SET_DEFAULT(UseLoopCounter, true);
-  }
-
 #ifndef PRODUCT
   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
     if (use_vm_log()) {
@@ -4290,6 +3981,13 @@
   }
 #endif
 
+#if defined(IA32)
+  // Only server compiler can optimize safepoints well enough.
+  if (!is_server_compilation_mode_vm()) {
+    FLAG_SET_ERGO_IF_DEFAULT(bool, ThreadLocalHandshakes, false);
+  }
+#endif
+
   // ThreadLocalHandshakesConstraintFunc handles the constraints.
   if (FLAG_IS_DEFAULT(ThreadLocalHandshakes) || !SafepointMechanism::supports_thread_local_poll()) {
     log_debug(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
--- a/src/hotspot/share/runtime/arguments.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/arguments.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -372,13 +372,6 @@
   static intx _Tier3InvokeNotifyFreqLog;
   static intx _Tier4InvocationThreshold;
 
-  // Compilation mode.
-  static bool compilation_mode_selected();
-  static void select_compilation_mode_ergonomically();
-
-  // Tiered
-  static void set_tiered_flags();
-
   // GC ergonomics
   static void set_conservative_max_heap_alignment();
   static void set_use_compressed_oops();
@@ -469,18 +462,6 @@
   static void add_string(char*** bldarray, int* count, const char* arg);
   static const char* build_resource_string(char** args, int count);
 
-  static bool methodExists(
-    char* className, char* methodName,
-    int classesNum, char** classes, bool* allMethods,
-    int methodsNum, char** methods, bool* allClasses
-  );
-
-  static void parseOnlyLine(
-    const char* line,
-    short* classesNum, short* classesMax, char*** classes, bool** allMethods,
-    short* methodsNum, short* methodsMax, char*** methods, bool** allClasses
-  );
-
   // Returns true if the flag is obsolete (and not yet expired).
   // In this case the 'version' buffer is filled in with
   // the version number when the flag became obsolete.
@@ -505,38 +486,10 @@
   static const char* handle_aliases_and_deprecation(const char* arg, bool warn);
   static bool lookup_logging_aliases(const char* arg, char* buffer);
   static AliasedLoggingFlag catch_logging_aliases(const char* name, bool on);
-  static short  CompileOnlyClassesNum;
-  static short  CompileOnlyClassesMax;
-  static char** CompileOnlyClasses;
-  static bool*  CompileOnlyAllMethods;
-
-  static short  CompileOnlyMethodsNum;
-  static short  CompileOnlyMethodsMax;
-  static char** CompileOnlyMethods;
-  static bool*  CompileOnlyAllClasses;
-
-  static short  InterpretOnlyClassesNum;
-  static short  InterpretOnlyClassesMax;
-  static char** InterpretOnlyClasses;
-  static bool*  InterpretOnlyAllMethods;
-
-  static bool   CheckCompileOnly;
 
   static char*  SharedArchivePath;
 
  public:
-  // Scale compile thresholds
-  // Returns threshold scaled with CompileThresholdScaling
-  static intx scaled_compile_threshold(intx threshold, double scale);
-  static intx scaled_compile_threshold(intx threshold) {
-    return scaled_compile_threshold(threshold, CompileThresholdScaling);
-  }
-  // Returns freq_log scaled with CompileThresholdScaling
-  static intx scaled_freq_log(intx freq_log, double scale);
-  static intx scaled_freq_log(intx freq_log) {
-    return scaled_freq_log(freq_log, CompileThresholdScaling);
-  }
-
   // Parses the arguments, first phase
   static jint parse(const JavaVMInitArgs* args);
   // Apply ergonomics
@@ -544,11 +497,6 @@
   // Adjusts the arguments after the OS have adjusted the arguments
   static jint adjust_after_os();
 
-#if INCLUDE_JVMCI
-  // Check consistency of jvmci vm argument settings.
-  static bool check_jvmci_args_consistency();
-  static void set_jvmci_specific_flags();
-#endif
   // Check for consistency in the selection of the garbage collector.
   static bool check_gc_consistency();        // Check user-selected gc
   // Check consistency or otherwise of VM argument settings
@@ -622,19 +570,8 @@
   static exit_hook_t     exit_hook()        { return _exit_hook; }
   static vfprintf_hook_t vfprintf_hook()    { return _vfprintf_hook; }
 
-  static bool GetCheckCompileOnly ()        { return CheckCompileOnly; }
-
   static const char* GetSharedArchivePath() { return SharedArchivePath; }
 
-  static bool CompileMethod(char* className, char* methodName) {
-    return
-      methodExists(
-        className, methodName,
-        CompileOnlyClassesNum, CompileOnlyClasses, CompileOnlyAllMethods,
-        CompileOnlyMethodsNum, CompileOnlyMethods, CompileOnlyAllClasses
-      );
-  }
-
   // Java launcher properties
   static void process_sun_java_launcher_properties(JavaVMInitArgs* args);
 
--- a/src/hotspot/share/runtime/deoptimization.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/deoptimization.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -2170,6 +2170,7 @@
   "array_check",
   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
+  "profile_predicate",
   "unloaded",
   "uninitialized",
   "unreached",
--- a/src/hotspot/share/runtime/deoptimization.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/deoptimization.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -41,7 +41,7 @@
   enum DeoptReason {
     Reason_many = -1,             // indicates presence of several reasons
     Reason_none = 0,              // indicates absence of a relevant deopt.
-    // Next 7 reasons are recorded per bytecode in DataLayout::trap_bits.
+    // Next 8 reasons are recorded per bytecode in DataLayout::trap_bits.
     // This is more complicated for JVMCI as JVMCI may deoptimize to *some* bytecode before the
     // bytecode that actually caused the deopt (with inlining, JVMCI may even deoptimize to a
     // bytecode in another method):
@@ -62,6 +62,8 @@
     Reason_optimized_type_check   = Reason_bimorphic,
 #endif
 
+    Reason_profile_predicate,     // compiler generated predicate moved from frequent branch in a loop failed
+
     // recorded per method
     Reason_unloaded,              // unloaded class or constant pool entry
     Reason_uninitialized,         // bad class state (uninitialized)
@@ -92,8 +94,8 @@
     Reason_LIMIT,
 
     // Note:  Keep this enum in sync. with _trap_reason_name.
-    Reason_RECORDED_LIMIT = Reason_bimorphic  // some are not recorded per bc
-    // Note:  Reason_RECORDED_LIMIT should be < 8 to fit into 3 bits of
+    Reason_RECORDED_LIMIT = Reason_profile_predicate  // some are not recorded per bc
+    // Note:  Reason_RECORDED_LIMIT should fit into 31 bits of
     // DataLayout::trap_bits.  This dependency is enforced indirectly
     // via asserts, to avoid excessive direct header-to-header dependencies.
     // See Deoptimization::trap_state_reason and class DataLayout.
--- a/src/hotspot/share/runtime/handshake.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/handshake.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -28,6 +28,7 @@
 #include "memory/resourceArea.hpp"
 #include "runtime/handshake.hpp"
 #include "runtime/interfaceSupport.inline.hpp"
+#include "runtime/orderAccess.hpp"
 #include "runtime/osThread.hpp"
 #include "runtime/semaphore.inline.hpp"
 #include "runtime/task.hpp"
@@ -44,19 +45,26 @@
 };
 
 class HandshakeThreadsOperation: public HandshakeOperation {
-  Semaphore _done;
+  static Semaphore _done;
   ThreadClosure* _thread_cl;
 
 public:
-  HandshakeThreadsOperation(ThreadClosure* cl) : _done(0), _thread_cl(cl) {}
+  HandshakeThreadsOperation(ThreadClosure* cl) : _thread_cl(cl) {}
   void do_handshake(JavaThread* thread);
   void cancel_handshake(JavaThread* thread) { _done.signal(); };
 
   bool thread_has_completed() { return _done.trywait(); }
+
+#ifdef ASSERT
+  void check_state() {
+    assert(!_done.trywait(), "Must be zero");
+  }
+#endif
 };
 
+Semaphore HandshakeThreadsOperation::_done(0);
+
 class VM_Handshake: public VM_Operation {
-  HandshakeThreadsOperation* const _op;
   const jlong _handshake_timeout;
  public:
   bool evaluate_at_safepoint() const { return false; }
@@ -64,6 +72,7 @@
   bool evaluate_concurrently() const { return false; }
 
  protected:
+  HandshakeThreadsOperation* const _op;
 
   VM_Handshake(HandshakeThreadsOperation* op) :
       _op(op),
@@ -102,7 +111,6 @@
   fatal("Handshake operation timed out");
 }
 
-
 class VM_HandshakeOneThread: public VM_Handshake {
   JavaThread* _target;
   bool _thread_alive;
@@ -111,6 +119,7 @@
     VM_Handshake(op), _target(target), _thread_alive(false) {}
 
   void doit() {
+    DEBUG_ONLY(_op->check_state();)
     TraceTime timer("Performing single-target operation (vmoperation doit)", TRACETIME_LOG(Info, handshake));
 
     {
@@ -155,6 +164,7 @@
         // then we hang here, which is good for debugging.
       }
     } while (!poll_for_completed_thread());
+    DEBUG_ONLY(_op->check_state();)
   }
 
   VMOp_Type type() const { return VMOp_HandshakeOneThread; }
@@ -167,6 +177,7 @@
   VM_HandshakeAllThreads(HandshakeThreadsOperation* op) : VM_Handshake(op) {}
 
   void doit() {
+    DEBUG_ONLY(_op->check_state();)
     TraceTime timer("Performing operation (vmoperation doit)", TRACETIME_LOG(Info, handshake));
 
     int number_of_threads_issued = 0;
@@ -213,7 +224,9 @@
         number_of_threads_completed++;
       }
 
-    } while (number_of_threads_issued != number_of_threads_completed);
+    } while (number_of_threads_issued > number_of_threads_completed);
+    assert(number_of_threads_issued == number_of_threads_completed, "Must be the same");
+    DEBUG_ONLY(_op->check_state();)
   }
 
   VMOp_Type type() const { return VMOp_HandshakeAllThreads; }
@@ -245,8 +258,6 @@
   bool thread_alive() const { return _thread_alive; }
 };
 
-#undef ALL_JAVA_THREADS
-
 void HandshakeThreadsOperation::do_handshake(JavaThread* thread) {
   ResourceMark rm;
   FormatBufferResource message("Operation for thread " PTR_FORMAT ", is_vm_thread: %s",
@@ -282,7 +293,7 @@
   }
 }
 
-HandshakeState::HandshakeState() : _operation(NULL), _semaphore(1), _vmthread_holds_semaphore(false), _thread_in_process_handshake(false) {}
+HandshakeState::HandshakeState() : _operation(NULL), _semaphore(1), _thread_in_process_handshake(false) {}
 
 void HandshakeState::set_operation(JavaThread* target, HandshakeOperation* op) {
   _operation = op;
@@ -296,17 +307,23 @@
 
 void HandshakeState::process_self_inner(JavaThread* thread) {
   assert(Thread::current() == thread, "should call from thread");
+
+  if (thread->is_terminated()) {
+    // If thread is not on threads list but armed, cancel.
+    thread->cancel_handshake();
+    return;
+  }
+
   CautiouslyPreserveExceptionMark pem(thread);
   ThreadInVMForHandshake tivm(thread);
   if (!_semaphore.trywait()) {
     _semaphore.wait_with_safepoint_check(thread);
   }
-  if (has_operation()) {
-    HandshakeOperation* op = _operation;
+  HandshakeOperation* op = OrderAccess::load_acquire(&_operation);
+  if (op != NULL) {
+    // Disarm before execute the operation
     clear_handshake(thread);
-    if (op != NULL) {
-      op->do_handshake(thread);
-    }
+    op->do_handshake(thread);
   }
   _semaphore.signal();
 }
@@ -314,12 +331,6 @@
 void HandshakeState::cancel_inner(JavaThread* thread) {
   assert(Thread::current() == thread, "should call from thread");
   assert(thread->thread_state() == _thread_in_vm, "must be in vm state");
-#ifdef DEBUG
-  {
-    ThreadsListHandle tlh;
-    assert(!tlh.includes(_target), "java thread must not be on threads list");
-  }
-#endif
   HandshakeOperation* op = _operation;
   clear_handshake(thread);
   if (op != NULL) {
@@ -332,14 +343,14 @@
 }
 
 bool HandshakeState::claim_handshake_for_vmthread() {
-  if (_semaphore.trywait()) {
-    if (has_operation()) {
-      _vmthread_holds_semaphore = true;
-    } else {
-      _semaphore.signal();
-    }
+  if (!_semaphore.trywait()) {
+    return false;
   }
-  return _vmthread_holds_semaphore;
+  if (has_operation()) {
+    return true;
+  }
+  _semaphore.signal();
+  return false;
 }
 
 void HandshakeState::process_by_vmthread(JavaThread* target) {
@@ -355,16 +366,22 @@
     return;
   }
 
+  // Claim the semaphore if there still an operation to be executed.
+  if (!claim_handshake_for_vmthread()) {
+    return;
+  }
+
   // If we own the semaphore at this point and while owning the semaphore
   // can observe a safe state the thread cannot possibly continue without
   // getting caught by the semaphore.
-  if (claim_handshake_for_vmthread() && vmthread_can_process_handshake(target)) {
+  if (vmthread_can_process_handshake(target)) {
     guarantee(!_semaphore.trywait(), "we should already own the semaphore");
 
     _operation->do_handshake(target);
+    // Disarm after VM thread have executed the operation.
     clear_handshake(target);
-    _vmthread_holds_semaphore = false;
     // Release the thread
-    _semaphore.signal();
   }
+
+  _semaphore.signal();
 }
--- a/src/hotspot/share/runtime/handshake.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/handshake.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -54,7 +54,6 @@
   HandshakeOperation* volatile _operation;
 
   Semaphore _semaphore;
-  bool _vmthread_holds_semaphore;
   bool _thread_in_process_handshake;
 
   bool claim_handshake_for_vmthread();
--- a/src/hotspot/share/runtime/jniHandles.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/jniHandles.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -109,7 +109,7 @@
     // Return NULL on allocation failure.
     if (ptr != NULL) {
       assert(*ptr == NULL, "invariant");
-      RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, obj());
+      NativeAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, obj());
       res = reinterpret_cast<jobject>(ptr);
     } else {
       report_handle_allocation_failure(alloc_failmode, "global");
@@ -133,7 +133,7 @@
     // Return NULL on allocation failure.
     if (ptr != NULL) {
       assert(*ptr == NULL, "invariant");
-      RootAccess<ON_PHANTOM_OOP_REF>::oop_store(ptr, obj());
+      NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(ptr, obj());
       char* tptr = reinterpret_cast<char*>(ptr) + weak_tag_value;
       res = reinterpret_cast<jobject>(tptr);
     } else {
@@ -160,14 +160,14 @@
 oop JNIHandles::resolve_jweak(jweak handle) {
   assert(handle != NULL, "precondition");
   assert(is_jweak(handle), "precondition");
-  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(jweak_ptr(handle));
+  return NativeAccess<ON_PHANTOM_OOP_REF>::oop_load(jweak_ptr(handle));
 }
 
 bool JNIHandles::is_global_weak_cleared(jweak handle) {
   assert(handle != NULL, "precondition");
   assert(is_jweak(handle), "not a weak handle");
   oop* oop_ptr = jweak_ptr(handle);
-  oop value = RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr);
+  oop value = NativeAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(oop_ptr);
   return value == NULL;
 }
 
@@ -175,7 +175,7 @@
   if (handle != NULL) {
     assert(!is_jweak(handle), "wrong method for detroying jweak");
     oop* oop_ptr = jobject_ptr(handle);
-    RootAccess<IN_CONCURRENT_ROOT>::oop_store(oop_ptr, (oop)NULL);
+    NativeAccess<IN_CONCURRENT_ROOT>::oop_store(oop_ptr, (oop)NULL);
     global_handles()->release(oop_ptr);
   }
 }
@@ -185,7 +185,7 @@
   if (handle != NULL) {
     assert(is_jweak(handle), "JNI handle not jweak");
     oop* oop_ptr = jweak_ptr(handle);
-    RootAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)NULL);
+    NativeAccess<ON_PHANTOM_OOP_REF>::oop_store(oop_ptr, (oop)NULL);
     weak_global_handles()->release(oop_ptr);
   }
 }
@@ -517,7 +517,7 @@
   // Try last block
   if (_last->_top < block_size_in_oops) {
     oop* handle = &(_last->_handles)[_last->_top++];
-    RootAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj);
+    NativeAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj);
     return (jobject) handle;
   }
 
@@ -525,7 +525,7 @@
   if (_free_list != NULL) {
     oop* handle = _free_list;
     _free_list = (oop*) *_free_list;
-    RootAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj);
+    NativeAccess<AS_DEST_NOT_INITIALIZED>::oop_store(handle, obj);
     return (jobject) handle;
   }
   // Check if unused block follow last
--- a/src/hotspot/share/runtime/jniHandles.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/jniHandles.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -57,7 +57,7 @@
   if (is_jweak(handle)) {       // Unlikely
     result = resolve_jweak(handle);
   } else {
-    result = RootAccess<IN_CONCURRENT_ROOT>::oop_load(jobject_ptr(handle));
+    result = NativeAccess<IN_CONCURRENT_ROOT>::oop_load(jobject_ptr(handle));
     // Construction of jobjects canonicalize a null value into a null
     // jobject, so for non-jweak the pointee should never be null.
     assert(external_guard || result != NULL, "Invalid JNI handle");
@@ -83,7 +83,7 @@
 inline void JNIHandles::destroy_local(jobject handle) {
   if (handle != NULL) {
     assert(!is_jweak(handle), "Invalid JNI local handle");
-    RootAccess<>::oop_store(jobject_ptr(handle), (oop)NULL);
+    NativeAccess<>::oop_store(jobject_ptr(handle), (oop)NULL);
   }
 }
 
--- a/src/hotspot/share/runtime/safepointMechanism.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/safepointMechanism.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -59,12 +59,11 @@
   bool armed = local_poll_armed(thread); // load acquire, polling page -> op / global state
   if(armed) {
     // We could be armed for either a handshake operation or a safepoint
+    if (global_poll()) {
+      SafepointSynchronize::block(thread);
+    }
     if (thread->has_handshake()) {
       thread->handshake_process_by_self();
-    } else {
-      if (global_poll()) {
-        SafepointSynchronize::block(thread);
-      }
     }
   }
 }
--- a/src/hotspot/share/runtime/thread.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/thread.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -4219,6 +4219,9 @@
   before_exit(thread);
 
   thread->exit(true);
+  // thread will never call smr_delete, instead of implicit cancel
+  // in wait_for_vm_thread_exit we do it explicit.
+  thread->cancel_handshake();
 
   // Stop VM thread.
   {
--- a/src/hotspot/share/runtime/threadHeapSampler.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/threadHeapSampler.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -47,7 +47,7 @@
   const uint64_t PrngMult = 0x5DEECE66DLL;
   const uint64_t PrngAdd = 0xB;
   const uint64_t PrngModPower = 48;
-  const uint64_t PrngModMask = right_n_bits(PrngModPower);
+  const uint64_t PrngModMask = ((uint64_t)1 << PrngModPower) - 1;
   //assert(IS_SAFE_SIZE_MUL(PrngMult, rnd), "Overflow on multiplication.");
   //assert(IS_SAFE_SIZE_ADD(PrngMult * rnd, PrngAdd), "Overflow on addition.");
   return (PrngMult * rnd + PrngAdd) & PrngModMask;
--- a/src/hotspot/share/runtime/vmStructs.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/runtime/vmStructs.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1117,11 +1117,11 @@
   /* FileMapInfo fields (CDS archive related) */                                                                                     \
   /********************************************/                                                                                     \
                                                                                                                                      \
-  nonstatic_field(FileMapInfo,                 _header,                                       FileMapInfo::FileMapHeader*)           \
-     static_field(FileMapInfo,                 _current_info,                                 FileMapInfo*)                          \
-  nonstatic_field(FileMapInfo::FileMapHeader,  _space[0],                                     FileMapInfo::FileMapHeader::space_info)\
-  nonstatic_field(FileMapInfo::FileMapHeader::space_info, _addr._base,                        char*)                                 \
-  nonstatic_field(FileMapInfo::FileMapHeader::space_info, _used,                              size_t)                                \
+  CDS_ONLY(nonstatic_field(FileMapInfo,                            _header,                   FileMapInfo::FileMapHeader*))          \
+  CDS_ONLY(   static_field(FileMapInfo,                            _current_info,             FileMapInfo*))                         \
+  CDS_ONLY(nonstatic_field(FileMapInfo::FileMapHeader,             _space[0],                 FileMapInfo::FileMapHeader::space_info))\
+  CDS_ONLY(nonstatic_field(FileMapInfo::FileMapHeader::space_info, _addr._base,               char*))                                \
+  CDS_ONLY(nonstatic_field(FileMapInfo::FileMapHeader::space_info, _used,                     size_t))                               \
                                                                                                                                      \
   /******************/                                                                                                               \
   /* VMError fields */                                                                                                               \
@@ -2381,6 +2381,7 @@
   declare_constant(Deoptimization::Reason_array_check)                    \
   declare_constant(Deoptimization::Reason_intrinsic)                      \
   declare_constant(Deoptimization::Reason_bimorphic)                      \
+  declare_constant(Deoptimization::Reason_profile_predicate)              \
   declare_constant(Deoptimization::Reason_unloaded)                       \
   declare_constant(Deoptimization::Reason_uninitialized)                  \
   declare_constant(Deoptimization::Reason_unreached)                      \
--- a/src/hotspot/share/services/diagnosticArgument.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/diagnosticArgument.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -68,27 +68,27 @@
   set_is_set(true);
 }
 
-void GenDCmdArgument::to_string(jlong l, char* buf, size_t len) {
+void GenDCmdArgument::to_string(jlong l, char* buf, size_t len) const {
   jio_snprintf(buf, len, INT64_FORMAT, l);
 }
 
-void GenDCmdArgument::to_string(bool b, char* buf, size_t len) {
+void GenDCmdArgument::to_string(bool b, char* buf, size_t len) const {
   jio_snprintf(buf, len, b ? "true" : "false");
 }
 
-void GenDCmdArgument::to_string(NanoTimeArgument n, char* buf, size_t len) {
+void GenDCmdArgument::to_string(NanoTimeArgument n, char* buf, size_t len) const {
   jio_snprintf(buf, len, INT64_FORMAT, n._nanotime);
 }
 
-void GenDCmdArgument::to_string(MemorySizeArgument m, char* buf, size_t len) {
+void GenDCmdArgument::to_string(MemorySizeArgument m, char* buf, size_t len) const {
   jio_snprintf(buf, len, INT64_FORMAT, m._size);
 }
 
-void GenDCmdArgument::to_string(char* c, char* buf, size_t len) {
+void GenDCmdArgument::to_string(char* c, char* buf, size_t len) const {
   jio_snprintf(buf, len, "%s", (c != NULL) ? c : "");
 }
 
-void GenDCmdArgument::to_string(StringArrayArgument* f, char* buf, size_t len) {
+void GenDCmdArgument::to_string(StringArrayArgument* f, char* buf, size_t len) const {
   int length = f->array()->length();
   size_t written = 0;
   buf[0] = 0;
--- a/src/hotspot/share/services/diagnosticArgument.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/diagnosticArgument.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -62,40 +62,35 @@
 class GenDCmdArgument : public ResourceObj {
 protected:
   GenDCmdArgument* _next;
-  const char*      _name;
-  const char*      _description;
-  const char*      _type;
-  const char*      _default_string;
-  bool             _is_set;
-  bool             _is_mandatory;
+  const char* const _name;
+  const char* const _description;
+  const char* const _type;
+  const char* const _default_string;
+  bool              _is_set;
+  const bool        _is_mandatory;
   bool             _allow_multiple;
   GenDCmdArgument(const char* name, const char* description, const char* type,
-                  const char* default_string, bool mandatory) {
-    _name = name;
-    _description = description;
-    _type = type;
-    _default_string = default_string;
-    _is_mandatory = mandatory;
-    _is_set = false;
-    _allow_multiple = false;
-  };
+                  const char* default_string, bool mandatory)
+    : _next(NULL), _name(name), _description(description), _type(type),
+      _default_string(default_string), _is_set(false), _is_mandatory(mandatory),
+      _allow_multiple(false) {}
 public:
-  const char* name() { return _name; }
-  const char* description() { return _description; }
-  const char* type() { return _type; }
-  const char* default_string() { return _default_string; }
-  bool is_set() { return _is_set; }
-  void set_is_set(bool b) { _is_set = b; }
-  bool allow_multiple() { return _allow_multiple; }
-  bool is_mandatory() { return _is_mandatory; }
-  bool has_value() { return _is_set || _default_string != NULL; }
-  bool has_default() { return _default_string != NULL; }
+  const char* name() const        { return _name; }
+  const char* description() const { return _description; }
+  const char* type() const        { return _type; }
+  const char* default_string() const { return _default_string; }
+  bool is_set() const             { return _is_set; }
+  void set_is_set(bool b)         { _is_set = b; }
+  bool allow_multiple() const     { return _allow_multiple; }
+  bool is_mandatory() const       { return _is_mandatory; }
+  bool has_value() const          { return _is_set || _default_string != NULL; }
+  bool has_default() const        { return _default_string != NULL; }
   void read_value(const char* str, size_t len, TRAPS);
   virtual void parse_value(const char* str, size_t len, TRAPS) = 0;
   virtual void init_value(TRAPS) = 0;
   virtual void reset(TRAPS) = 0;
   virtual void cleanup() = 0;
-  virtual void value_as_str(char* buf, size_t len) = 0;
+  virtual void value_as_str(char* buf, size_t len) const = 0;
   void set_next(GenDCmdArgument* arg) {
     _next = arg;
   }
@@ -103,12 +98,12 @@
     return _next;
   }
 
-  void to_string(jlong l, char* buf, size_t len);
-  void to_string(bool b, char* buf, size_t len);
-  void to_string(char* c, char* buf, size_t len);
-  void to_string(NanoTimeArgument n, char* buf, size_t len);
-  void to_string(MemorySizeArgument f, char* buf, size_t len);
-  void to_string(StringArrayArgument* s, char* buf, size_t len);
+  void to_string(jlong l, char* buf, size_t len) const;
+  void to_string(bool b, char* buf, size_t len) const;
+  void to_string(char* c, char* buf, size_t len) const;
+  void to_string(NanoTimeArgument n, char* buf, size_t len) const;
+  void to_string(MemorySizeArgument f, char* buf, size_t len) const;
+  void to_string(StringArrayArgument* s, char* buf, size_t len) const;
 };
 
 template <class ArgType> class DCmdArgument: public GenDCmdArgument {
@@ -123,7 +118,7 @@
                GenDCmdArgument(name, description, type, defaultvalue, mandatory)
                { }
   ~DCmdArgument() { destroy_value(); }
-  ArgType value() { return _value;}
+  ArgType value() const { return _value;}
   void set_value(ArgType v) { _value = v; }
   void reset(TRAPS) {
     destroy_value();
@@ -136,7 +131,7 @@
   void parse_value(const char* str, size_t len, TRAPS);
   void init_value(TRAPS);
   void destroy_value();
-  void value_as_str(char *buf, size_t len) { return to_string(_value, buf, len);}
+  void value_as_str(char *buf, size_t len) const { to_string(_value, buf, len);}
 };
 
 #endif  /* SHARE_VM_SERVICES_DIAGNOSTICARGUMENT_HPP */
--- a/src/hotspot/share/services/diagnosticFramework.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/diagnosticFramework.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -34,7 +34,9 @@
 #include "services/diagnosticFramework.hpp"
 #include "services/management.hpp"
 
-CmdLine::CmdLine(const char* line, size_t len, bool no_command_name) {
+CmdLine::CmdLine(const char* line, size_t len, bool no_command_name)
+  : _cmd(line), _cmd_len(0), _args(NULL), _args_len(0)
+{
   assert(line != NULL, "Command line string should not be NULL");
   const char* line_end;
   const char* cmd_end;
@@ -251,7 +253,7 @@
   }
 }
 
-void DCmdParser::print_help(outputStream* out, const char* cmd_name) {
+void DCmdParser::print_help(outputStream* out, const char* cmd_name) const {
   out->print("Syntax : %s %s", cmd_name, _options == NULL ? "" : "[options]");
   GenDCmdArgument* arg = _arguments_list;
   while (arg != NULL) {
@@ -323,7 +325,7 @@
   }
 }
 
-int DCmdParser::num_arguments() {
+int DCmdParser::num_arguments() const {
   GenDCmdArgument* arg = _arguments_list;
   int count = 0;
   while (arg != NULL) {
@@ -338,7 +340,7 @@
   return count;
 }
 
-GrowableArray<const char *>* DCmdParser::argument_name_array() {
+GrowableArray<const char *>* DCmdParser::argument_name_array() const {
   int count = num_arguments();
   GrowableArray<const char *>* array = new GrowableArray<const char *>(count);
   GenDCmdArgument* arg = _arguments_list;
@@ -354,7 +356,7 @@
   return array;
 }
 
-GrowableArray<DCmdArgumentInfo*>* DCmdParser::argument_info_array() {
+GrowableArray<DCmdArgumentInfo*>* DCmdParser::argument_info_array() const {
   int count = num_arguments();
   GrowableArray<DCmdArgumentInfo*>* array = new GrowableArray<DCmdArgumentInfo *>(count);
   int idx = 0;
@@ -399,6 +401,7 @@
       break;
     }
     if (line.is_executable()) {
+      ResourceMark rm;
       DCmd* command = DCmdFactory::create_local_DCmd(source, line, out, CHECK);
       assert(command != NULL, "command error must be handled before this line");
       DCmdMark mark(command);
@@ -413,7 +416,7 @@
   _dcmdparser.parse(line, delim, CHECK);
 }
 
-void DCmdWithParser::print_help(const char* name) {
+void DCmdWithParser::print_help(const char* name) const {
   _dcmdparser.print_help(output(), name);
 }
 
@@ -425,11 +428,11 @@
   _dcmdparser.cleanup();
 }
 
-GrowableArray<const char*>* DCmdWithParser::argument_name_array() {
+GrowableArray<const char*>* DCmdWithParser::argument_name_array() const {
   return _dcmdparser.argument_name_array();
 }
 
-GrowableArray<DCmdArgumentInfo*>* DCmdWithParser::argument_info_array() {
+GrowableArray<DCmdArgumentInfo*>* DCmdWithParser::argument_info_array() const {
   return _dcmdparser.argument_info_array();
 }
 
@@ -519,20 +522,6 @@
   return 0; // Actually, there's no checks for duplicates
 }
 
-DCmd* DCmdFactory::create_global_DCmd(DCmdSource source, CmdLine &line,
-                                      outputStream* out, TRAPS) {
-  DCmdFactory* f = factory(source, line.cmd_addr(), line.cmd_len());
-  if (f != NULL) {
-    if (f->is_enabled()) {
-      THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
-                     f->disabled_message());
-    }
-    return f->create_Cheap_instance(out);
-  }
-  THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
-             "Unknown diagnostic command");
-}
-
 DCmd* DCmdFactory::create_local_DCmd(DCmdSource source, CmdLine &line,
                                      outputStream* out, TRAPS) {
   DCmdFactory* f = factory(source, line.cmd_addr(), line.cmd_len());
--- a/src/hotspot/share/services/diagnosticFramework.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/diagnosticFramework.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,13 +61,13 @@
   size_t      _args_len;
 public:
   CmdLine(const char* line, size_t len, bool no_command_name);
-  const char* args_addr() const { return _args; }
-  size_t args_len() const { return _args_len; }
-  const char* cmd_addr() const { return _cmd; }
-  size_t cmd_len() const { return _cmd_len; }
-  bool is_empty() { return _cmd_len == 0; }
-  bool is_executable() { return is_empty() || _cmd[0] != '#'; }
-  bool is_stop() { return !is_empty() && strncmp("stop", _cmd, _cmd_len) == 0; }
+  const char* args_addr() const   { return _args; }
+  size_t args_len() const         { return _args_len; }
+  const char* cmd_addr() const    { return _cmd; }
+  size_t cmd_len() const          { return _cmd_len; }
+  bool is_empty() const           { return _cmd_len == 0; }
+  bool is_executable() const      { return is_empty() || _cmd[0] != '#'; }
+  bool is_stop() const            { return !is_empty() && strncmp("stop", _cmd, _cmd_len) == 0; }
 };
 
 // Iterator class taking a character string in input and returning a CmdLine
@@ -75,19 +75,16 @@
 class DCmdIter : public StackObj {
   friend class DCmd;
 private:
-  const char* _str;
-  char        _delim;
-  size_t      _len;
+  const char* const _str;
+  const char        _delim;
+  const size_t      _len;
   size_t      _cursor;
 public:
 
-  DCmdIter(const char* str, char delim) {
-    _str = str;
-    _delim = delim;
-    _len = strlen(str);
-    _cursor = 0;
-  }
-  bool has_next() { return _cursor < _len; }
+  DCmdIter(const char* str, char delim)
+   : _str(str), _delim(delim), _len(::strlen(str)),
+     _cursor(0) {}
+  bool has_next() const { return _cursor < _len; }
   CmdLine next() {
     assert(_cursor <= _len, "Cannot iterate more");
     size_t n = _cursor;
@@ -102,58 +99,51 @@
 
 // Iterator class to iterate over diagnostic command arguments
 class DCmdArgIter : public ResourceObj {
-  const char* _buffer;
-  size_t      _len;
+  const char* const _buffer;
+  const size_t      _len;
   size_t      _cursor;
   const char* _key_addr;
   size_t      _key_len;
   const char* _value_addr;
   size_t      _value_len;
-  char        _delim;
+  const char  _delim;
 public:
-  DCmdArgIter(const char* buf, size_t len, char delim) {
-    _buffer = buf;
-    _len = len;
-    _delim = delim;
-    _cursor = 0;
-  }
+  DCmdArgIter(const char* buf, size_t len, char delim)
+    : _buffer(buf), _len(len), _cursor(0), _key_addr(NULL),
+      _key_len(0), _value_addr(NULL), _value_len(0), _delim(delim) {}
+
   bool next(TRAPS);
-  const char* key_addr() { return _key_addr; }
-  size_t key_length() { return _key_len; }
-  const char* value_addr() { return _value_addr; }
-  size_t value_length() { return _value_len; }
+  const char* key_addr() const    { return _key_addr; }
+  size_t key_length() const       { return _key_len; }
+  const char* value_addr() const  { return _value_addr; }
+  size_t value_length() const     { return _value_len; }
 };
 
 // A DCmdInfo instance provides a description of a diagnostic command. It is
 // used to export the description to the JMX interface of the framework.
 class DCmdInfo : public ResourceObj {
 protected:
-  const char* _name;           /* Name of the diagnostic command */
-  const char* _description;    /* Short description */
-  const char* _impact;         /* Impact on the JVM */
-  JavaPermission _permission;  /* Java Permission required to execute this command if any */
-  int         _num_arguments;  /* Number of supported options or arguments */
-  bool        _is_enabled;     /* True if the diagnostic command can be invoked, false otherwise */
+  const char* const _name;           /* Name of the diagnostic command */
+  const char* const _description;    /* Short description */
+  const char* const _impact;         /* Impact on the JVM */
+  const JavaPermission _permission;  /* Java Permission required to execute this command if any */
+  const int         _num_arguments;  /* Number of supported options or arguments */
+  const bool        _is_enabled;     /* True if the diagnostic command can be invoked, false otherwise */
 public:
   DCmdInfo(const char* name,
           const char* description,
           const char* impact,
           JavaPermission permission,
           int num_arguments,
-          bool enabled) {
-    this->_name = name;
-    this->_description = description;
-    this->_impact = impact;
-    this->_permission = permission;
-    this->_num_arguments = num_arguments;
-    this->_is_enabled = enabled;
-  }
-  const char* name() const { return _name; }
-  const char* description() const { return _description; }
-  const char* impact() const { return _impact; }
-  JavaPermission permission() const { return _permission; }
-  int num_arguments() const { return _num_arguments; }
-  bool is_enabled() const { return _is_enabled; }
+          bool enabled)
+  : _name(name), _description(description), _impact(impact), _permission(permission),
+    _num_arguments(num_arguments), _is_enabled(enabled) {}
+  const char* name() const          { return _name; }
+  const char* description() const   { return _description; }
+  const char* impact() const        { return _impact; }
+  const JavaPermission& permission() const { return _permission; }
+  int num_arguments() const         { return _num_arguments; }
+  bool is_enabled() const           { return _is_enabled; }
 
   static bool by_name(void* name, DCmdInfo* info);
 };
@@ -163,51 +153,32 @@
 // framework.
 class DCmdArgumentInfo : public ResourceObj {
 protected:
-  const char* _name;            /* Option/Argument name*/
-  const char* _description;     /* Short description */
-  const char* _type;            /* Type: STRING, BOOLEAN, etc. */
-  const char* _default_string;  /* Default value in a parsable string */
-  bool        _mandatory;       /* True if the option/argument is mandatory */
-  bool        _option;          /* True if it is an option, false if it is an argument */
+  const char* const _name;            /* Option/Argument name*/
+  const char* const _description;     /* Short description */
+  const char* const _type;            /* Type: STRING, BOOLEAN, etc. */
+  const char* const _default_string;  /* Default value in a parsable string */
+  const bool        _mandatory;       /* True if the option/argument is mandatory */
+  const bool        _option;          /* True if it is an option, false if it is an argument */
                                 /* (see diagnosticFramework.hpp for option/argument definitions) */
-  bool        _multiple;        /* True is the option can be specified several time */
-  int         _position;        /* Expected position for this argument (this field is */
+  const bool        _multiple;        /* True is the option can be specified several time */
+  const int         _position;        /* Expected position for this argument (this field is */
                                 /* meaningless for options) */
 public:
   DCmdArgumentInfo(const char* name, const char* description, const char* type,
                    const char* default_string, bool mandatory, bool option,
-                   bool multiple) {
-    this->_name = name;
-    this->_description = description;
-    this->_type = type;
-    this->_default_string = default_string;
-    this->_option = option;
-    this->_mandatory = mandatory;
-    this->_option = option;
-    this->_multiple = multiple;
-    this->_position = -1;
-  }
-  DCmdArgumentInfo(const char* name, const char* description, const char* type,
-                   const char* default_string, bool mandatory, bool option,
-                   bool multiple, int position) {
-    this->_name = name;
-    this->_description = description;
-    this->_type = type;
-    this->_default_string = default_string;
-    this->_option = option;
-    this->_mandatory = mandatory;
-    this->_option = option;
-    this->_multiple = multiple;
-    this->_position = position;
-  }
-  const char* name() const { return _name; }
+                   bool multiple, int position = -1)
+    : _name(name), _description(description), _type(type),
+      _default_string(default_string), _mandatory(mandatory), _option(option),
+      _multiple(multiple), _position(position) {}
+
+  const char* name() const        { return _name; }
   const char* description() const { return _description; }
-  const char* type() const { return _type; }
+  const char* type() const        { return _type; }
   const char* default_string() const { return _default_string; }
-  bool is_mandatory() const { return _mandatory; }
-  bool is_option() const { return _option; }
-  bool is_multiple() const { return _multiple; }
-  int position() const { return _position; }
+  bool is_mandatory() const       { return _mandatory; }
+  bool is_option() const          { return _option; }
+  bool is_multiple() const        { return _multiple; }
+  int position() const            { return _position; }
 };
 
 // The DCmdParser class can be used to create an argument parser for a
@@ -233,25 +204,21 @@
 private:
   GenDCmdArgument* _options;
   GenDCmdArgument* _arguments_list;
-  char             _delim;
 public:
-  DCmdParser() {
-    _options = NULL;
-    _arguments_list = NULL;
-    _delim = ' ';
-  }
+  DCmdParser()
+    : _options(NULL), _arguments_list(NULL) {}
   void add_dcmd_option(GenDCmdArgument* arg);
   void add_dcmd_argument(GenDCmdArgument* arg);
   GenDCmdArgument* lookup_dcmd_option(const char* name, size_t len);
-  GenDCmdArgument* arguments_list() { return _arguments_list; };
+  GenDCmdArgument* arguments_list() const { return _arguments_list; };
   void check(TRAPS);
   void parse(CmdLine* line, char delim, TRAPS);
-  void print_help(outputStream* out, const char* cmd_name);
+  void print_help(outputStream* out, const char* cmd_name) const;
   void reset(TRAPS);
   void cleanup();
-  int num_arguments();
-  GrowableArray<const char*>* argument_name_array();
-  GrowableArray<DCmdArgumentInfo*>* argument_info_array();
+  int num_arguments() const;
+  GrowableArray<const char*>* argument_name_array() const;
+  GrowableArray<DCmdArgumentInfo*>* argument_info_array() const;
 };
 
 // The DCmd class is the parent class of all diagnostic commands
@@ -270,17 +237,18 @@
 // thread that will access the instance.
 class DCmd : public ResourceObj {
 protected:
-  outputStream* _output;
-  bool          _is_heap_allocated;
+  outputStream* const _output;
+  const bool          _is_heap_allocated;
 public:
-  DCmd(outputStream* output, bool heap_allocated) {
-    _output = output;
-    _is_heap_allocated = heap_allocated;
-  }
+  DCmd(outputStream* output, bool heap_allocated)
+   : _output(output), _is_heap_allocated(heap_allocated) {}
 
-  static const char* name() { return "No Name";}
-  static const char* description() { return "No Help";}
+  // Child classes: please always provide these methods:
+  //  static const char* name()             { return "<command name>";}
+  //  static const char* description()      { return "<command help>";}
+
   static const char* disabled_message() { return "Diagnostic command currently disabled"; }
+
   // The impact() method returns a description of the intrusiveness of the diagnostic
   // command on the Java Virtual Machine behavior. The rational for this method is that some
   // diagnostic commands can seriously disrupt the behavior of the Java Virtual Machine
@@ -291,7 +259,8 @@
   // where the impact level is selected among this list: {Low, Medium, High}. The optional
   // longer description can provide more specific details like the fact that Thread Dump
   // impact depends on the heap size.
-  static const char* impact() { return "Low: No impact"; }
+  static const char* impact()       { return "Low: No impact"; }
+
   // The permission() method returns the description of Java Permission. This
   // permission is required when the diagnostic command is invoked via the
   // DiagnosticCommandMBean. The rationale for this permission check is that
@@ -305,10 +274,10 @@
     JavaPermission p = {NULL, NULL, NULL};
     return p;
   }
-  static int num_arguments() { return 0; }
-  outputStream* output() { return _output; }
-  bool is_heap_allocated()  { return _is_heap_allocated; }
-  virtual void print_help(const char* name) {
+  static int num_arguments()        { return 0; }
+  outputStream* output() const      { return _output; }
+  bool is_heap_allocated() const    { return _is_heap_allocated; }
+  virtual void print_help(const char* name) const {
     output()->print_cr("Syntax: %s", name);
   }
   virtual void parse(CmdLine* line, char delim, TRAPS) {
@@ -324,11 +293,11 @@
   virtual void cleanup() { }
 
   // support for the JMX interface
-  virtual GrowableArray<const char*>* argument_name_array() {
+  virtual GrowableArray<const char*>* argument_name_array() const {
     GrowableArray<const char*>* array = new GrowableArray<const char*>(0);
     return array;
   }
-  virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array() {
+  virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array() const {
     GrowableArray<DCmdArgumentInfo*>* array = new GrowableArray<DCmdArgumentInfo*>(0);
     return array;
   }
@@ -343,25 +312,21 @@
   DCmdParser _dcmdparser;
 public:
   DCmdWithParser (outputStream *output, bool heap=false) : DCmd(output, heap) { }
-  static const char* name() { return "No Name";}
-  static const char* description() { return "No Help";}
   static const char* disabled_message() { return "Diagnostic command currently disabled"; }
-  static const char* impact() { return "Low: No impact"; }
-  static const JavaPermission permission() {JavaPermission p = {NULL, NULL, NULL}; return p; }
-  static int num_arguments() { return 0; }
+  static const char* impact()         { return "Low: No impact"; }
   virtual void parse(CmdLine *line, char delim, TRAPS);
   virtual void execute(DCmdSource source, TRAPS) { }
   virtual void reset(TRAPS);
   virtual void cleanup();
-  virtual void print_help(const char* name);
-  virtual GrowableArray<const char*>* argument_name_array();
-  virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array();
+  virtual void print_help(const char* name) const;
+  virtual GrowableArray<const char*>* argument_name_array() const;
+  virtual GrowableArray<DCmdArgumentInfo*>* argument_info_array() const;
 };
 
 class DCmdMark : public StackObj {
-  DCmd* _ref;
+  DCmd* const _ref;
 public:
-  DCmdMark(DCmd* cmd) { _ref = cmd; }
+  DCmdMark(DCmd* cmd) : _ref(cmd) {}
   ~DCmdMark() {
     if (_ref != NULL) {
       _ref->cleanup();
@@ -382,37 +347,31 @@
   static Mutex*       _dcmdFactory_lock;
   static bool         _send_jmx_notification;
   static bool         _has_pending_jmx_notification;
+  static DCmdFactory* _DCmdFactoryList;
+
   // Pointer to the next factory in the singly-linked list of registered
   // diagnostic commands
   DCmdFactory*        _next;
   // When disabled, a diagnostic command cannot be executed. Any attempt to
   // execute it will result in the printing of the disabled message without
   // instantiating the command.
-  bool                _enabled;
+  const bool          _enabled;
   // When hidden, a diagnostic command doesn't appear in the list of commands
   // provided by the 'help' command.
-  bool                _hidden;
-  uint32_t            _export_flags;
-  int                 _num_arguments;
-  static DCmdFactory* _DCmdFactoryList;
+  const bool          _hidden;
+  const uint32_t      _export_flags;
+  const int           _num_arguments;
+
 public:
-  DCmdFactory(int num_arguments, uint32_t flags, bool enabled, bool hidden) {
-    _next = NULL;
-    _enabled = enabled;
-    _hidden = hidden;
-    _export_flags = flags;
-    _num_arguments = num_arguments;
-  }
-  bool is_enabled() const { return _enabled; }
-  void set_enabled(bool b) { _enabled = b; }
-  bool is_hidden() const { return _hidden; }
-  void set_hidden(bool b) { _hidden = b; }
-  uint32_t export_flags() { return _export_flags; }
-  void set_export_flags(uint32_t f) { _export_flags = f; }
-  int num_arguments() { return _num_arguments; }
-  DCmdFactory* next() { return _next; }
-  virtual DCmd* create_Cheap_instance(outputStream* output) = 0;
-  virtual DCmd* create_resource_instance(outputStream* output) = 0;
+  DCmdFactory(int num_arguments, uint32_t flags, bool enabled, bool hidden)
+    : _next(NULL), _enabled(enabled), _hidden(hidden),
+      _export_flags(flags), _num_arguments(num_arguments) {}
+  bool is_enabled() const       { return _enabled; }
+  bool is_hidden() const        { return _hidden; }
+  uint32_t export_flags() const { return _export_flags; }
+  int num_arguments() const     { return _num_arguments; }
+  DCmdFactory* next() const     { return _next; }
+  virtual DCmd* create_resource_instance(outputStream* output) const = 0;
   virtual const char* name() const = 0;
   virtual const char* description() const = 0;
   virtual const char* impact() const = 0;
@@ -424,8 +383,6 @@
   // enabled flag to false.
   static int register_DCmdFactory(DCmdFactory* factory);
   static DCmdFactory* factory(DCmdSource source, const char* cmd, size_t len);
-  // Returns a C-heap allocated diagnostic command for the given command line
-  static DCmd* create_global_DCmd(DCmdSource source, CmdLine &line, outputStream* out, TRAPS);
   // Returns a resourceArea allocated diagnostic command for the given command line
   static DCmd* create_local_DCmd(DCmdSource source, CmdLine &line, outputStream* out, TRAPS);
   static GrowableArray<const char*>* DCmd_list(DCmdSource source);
@@ -449,27 +406,23 @@
 public:
   DCmdFactoryImpl(uint32_t flags, bool enabled, bool hidden) :
     DCmdFactory(DCmdClass::num_arguments(), flags, enabled, hidden) { }
-  // Returns a C-heap allocated instance
-  virtual DCmd* create_Cheap_instance(outputStream* output) {
-    return new (ResourceObj::C_HEAP, mtInternal) DCmdClass(output, true);
-  }
   // Returns a resourceArea allocated instance
-  virtual DCmd* create_resource_instance(outputStream* output) {
+  DCmd* create_resource_instance(outputStream* output) const {
     return new DCmdClass(output, false);
   }
-  virtual const char* name() const {
+  const char* name() const {
     return DCmdClass::name();
   }
-  virtual const char* description() const {
+  const char* description() const {
     return DCmdClass::description();
   }
-  virtual const char* impact() const {
+  const char* impact() const {
     return DCmdClass::impact();
   }
-  virtual const JavaPermission permission() const {
+  const JavaPermission permission() const {
     return DCmdClass::permission();
   }
-  virtual const char* disabled_message() const {
+  const char* disabled_message() const {
      return DCmdClass::disabled_message();
   }
 };
--- a/src/hotspot/share/services/memoryManager.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/memoryManager.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -43,13 +43,15 @@
   (void)const_cast<instanceOop&>(_memory_mgr_obj = instanceOop(NULL));
 }
 
-void MemoryManager::add_pool(MemoryPool* pool) {
-  assert(_num_pools < MemoryManager::max_num_pools, "_num_pools exceeds the max");
-  if (_num_pools < MemoryManager::max_num_pools) {
-    _pools[_num_pools] = pool;
+int MemoryManager::add_pool(MemoryPool* pool) {
+  int index = _num_pools;
+  assert(index < MemoryManager::max_num_pools, "_num_pools exceeds the max");
+  if (index < MemoryManager::max_num_pools) {
+    _pools[index] = pool;
     _num_pools++;
   }
   pool->add_manager(this);
+  return index;
 }
 
 MemoryManager* MemoryManager::get_code_cache_memory_manager() {
@@ -189,6 +191,15 @@
   delete _current_gc_stat;
 }
 
+void GCMemoryManager::add_pool(MemoryPool* pool) {
+  add_pool(pool, true);
+}
+
+void GCMemoryManager::add_pool(MemoryPool* pool, bool always_affected_by_gc) {
+  int index = MemoryManager::add_pool(pool);
+  _pool_always_affected_by_gc[index] = always_affected_by_gc;
+}
+
 void GCMemoryManager::initialize_gc_stat_info() {
   assert(MemoryService::num_memory_pools() > 0, "should have one or more memory pools");
   _last_gc_stat = new(ResourceObj::C_HEAP, mtGC) GCStatInfo(MemoryService::num_memory_pools());
@@ -230,7 +241,8 @@
 void GCMemoryManager::gc_end(bool recordPostGCUsage,
                              bool recordAccumulatedGCTime,
                              bool recordGCEndTime, bool countCollection,
-                             GCCause::Cause cause) {
+                             GCCause::Cause cause,
+                             bool allMemoryPoolsAffected) {
   if (recordAccumulatedGCTime) {
     _accumulated_timer.stop();
   }
@@ -259,9 +271,11 @@
       MemoryPool* pool = get_memory_pool(i);
       MemoryUsage usage = pool->get_memory_usage();
 
-      // Compare with GC usage threshold
-      pool->set_last_collection_usage(usage);
-      LowMemoryDetector::detect_after_gc_memory(pool);
+      if (allMemoryPoolsAffected || pool_always_affected_by_gc(i)) {
+        // Compare with GC usage threshold
+        pool->set_last_collection_usage(usage);
+        LowMemoryDetector::detect_after_gc_memory(pool);
+      }
     }
   }
 
--- a/src/hotspot/share/services/memoryManager.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/memoryManager.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -45,11 +45,12 @@
 class OopClosure;
 
 class MemoryManager : public CHeapObj<mtInternal> {
-private:
+protected:
   enum {
     max_num_pools = 10
   };
 
+private:
   MemoryPool* _pools[max_num_pools];
   int         _num_pools;
 
@@ -67,7 +68,7 @@
     return _pools[index];
   }
 
-  void add_pool(MemoryPool* pool);
+  int add_pool(MemoryPool* pool);
 
   bool is_manager(instanceHandle mh)     { return oopDesc::equals(mh(), _memory_mgr_obj); }
 
@@ -142,11 +143,21 @@
   GCStatInfo*  _current_gc_stat;
   int          _num_gc_threads;
   volatile bool _notification_enabled;
-  const char* _gc_end_message;
+  const char*  _gc_end_message;
+  bool         _pool_always_affected_by_gc[MemoryManager::max_num_pools];
+
 public:
   GCMemoryManager(const char* name, const char* gc_end_message);
   ~GCMemoryManager();
 
+  void add_pool(MemoryPool* pool);
+  void add_pool(MemoryPool* pool, bool always_affected_by_gc);
+
+  bool pool_always_affected_by_gc(int index) {
+    assert(index >= 0 && index < num_memory_pools(), "Invalid index");
+    return _pool_always_affected_by_gc[index];
+  }
+
   void   initialize_gc_stat_info();
 
   bool   is_gc_memory_manager()         { return true; }
@@ -158,7 +169,8 @@
   void   gc_begin(bool recordGCBeginTime, bool recordPreGCUsage,
                   bool recordAccumulatedGCTime);
   void   gc_end(bool recordPostGCUsage, bool recordAccumulatedGCTime,
-                bool recordGCEndTime, bool countCollection, GCCause::Cause cause);
+                bool recordGCEndTime, bool countCollection, GCCause::Cause cause,
+                bool allMemoryPoolsAffected);
 
   void        reset_gc_stat()   { _num_collections = 0; _accumulated_timer.reset(); }
 
--- a/src/hotspot/share/services/memoryService.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/memoryService.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -182,10 +182,11 @@
 void MemoryService::gc_end(GCMemoryManager* manager, bool recordPostGCUsage,
                            bool recordAccumulatedGCTime,
                            bool recordGCEndTime, bool countCollection,
-                           GCCause::Cause cause) {
+                           GCCause::Cause cause,
+                           bool allMemoryPoolsAffected) {
   // register the GC end statistics and memory usage
   manager->gc_end(recordPostGCUsage, recordAccumulatedGCTime, recordGCEndTime,
-                  countCollection, cause);
+                  countCollection, cause, allMemoryPoolsAffected);
 }
 
 void MemoryService::oops_do(OopClosure* f) {
@@ -232,6 +233,7 @@
 
 TraceMemoryManagerStats::TraceMemoryManagerStats(GCMemoryManager* gc_memory_manager,
                                                  GCCause::Cause cause,
+                                                 bool allMemoryPoolsAffected,
                                                  bool recordGCBeginTime,
                                                  bool recordPreGCUsage,
                                                  bool recordPeakUsage,
@@ -239,7 +241,8 @@
                                                  bool recordAccumulatedGCTime,
                                                  bool recordGCEndTime,
                                                  bool countCollection) {
-  initialize(gc_memory_manager, cause, recordGCBeginTime, recordPreGCUsage, recordPeakUsage,
+  initialize(gc_memory_manager, cause, allMemoryPoolsAffected,
+             recordGCBeginTime, recordPreGCUsage, recordPeakUsage,
              recordPostGCUsage, recordAccumulatedGCTime, recordGCEndTime,
              countCollection);
 }
@@ -248,6 +251,7 @@
 // the MemoryService
 void TraceMemoryManagerStats::initialize(GCMemoryManager* gc_memory_manager,
                                          GCCause::Cause cause,
+                                         bool allMemoryPoolsAffected,
                                          bool recordGCBeginTime,
                                          bool recordPreGCUsage,
                                          bool recordPeakUsage,
@@ -256,6 +260,7 @@
                                          bool recordGCEndTime,
                                          bool countCollection) {
   _gc_memory_manager = gc_memory_manager;
+  _allMemoryPoolsAffected = allMemoryPoolsAffected;
   _recordGCBeginTime = recordGCBeginTime;
   _recordPreGCUsage = recordPreGCUsage;
   _recordPeakUsage = recordPeakUsage;
@@ -271,5 +276,5 @@
 
 TraceMemoryManagerStats::~TraceMemoryManagerStats() {
   MemoryService::gc_end(_gc_memory_manager, _recordPostGCUsage, _recordAccumulatedGCTime,
-                        _recordGCEndTime, _countCollection, _cause);
+                        _recordGCEndTime, _countCollection, _cause, _allMemoryPoolsAffected);
 }
--- a/src/hotspot/share/services/memoryService.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/services/memoryService.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -102,7 +102,8 @@
   static void gc_end(GCMemoryManager* manager, bool recordPostGCUsage,
                      bool recordAccumulatedGCTime,
                      bool recordGCEndTime, bool countCollection,
-                     GCCause::Cause cause);
+                     GCCause::Cause cause,
+                     bool allMemoryPoolsAffected);
 
   static void oops_do(OopClosure* f);
 
@@ -116,6 +117,7 @@
 class TraceMemoryManagerStats : public StackObj {
 private:
   GCMemoryManager* _gc_memory_manager;
+  bool         _allMemoryPoolsAffected;
   bool         _recordGCBeginTime;
   bool         _recordPreGCUsage;
   bool         _recordPeakUsage;
@@ -128,6 +130,7 @@
   TraceMemoryManagerStats() {}
   TraceMemoryManagerStats(GCMemoryManager* gc_memory_manager,
                           GCCause::Cause cause,
+                          bool allMemoryPoolsAffected = true,
                           bool recordGCBeginTime = true,
                           bool recordPreGCUsage = true,
                           bool recordPeakUsage = true,
@@ -138,6 +141,7 @@
 
   void initialize(GCMemoryManager* gc_memory_manager,
                   GCCause::Cause cause,
+                  bool allMemoryPoolsAffected,
                   bool recordGCBeginTime,
                   bool recordPreGCUsage,
                   bool recordPeakUsage,
--- a/src/hotspot/share/utilities/concurrentHashTable.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/utilities/concurrentHashTable.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -361,7 +361,7 @@
   template <typename EVALUATE_FUNC, typename DELETE_FUNC>
   void do_bulk_delete_locked_for(Thread* thread, size_t start_idx,
                                  size_t stop_idx, EVALUATE_FUNC& eval_f,
-                                 DELETE_FUNC& del_f);
+                                 DELETE_FUNC& del_f, bool is_mt = false);
 
   // Method to delete one items.
   template <typename LOOKUP_FUNC>
--- a/src/hotspot/share/utilities/concurrentHashTable.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/utilities/concurrentHashTable.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -484,11 +484,12 @@
 template <typename EVALUATE_FUNC, typename DELETE_FUNC>
 inline void ConcurrentHashTable<VALUE, CONFIG, F>::
   do_bulk_delete_locked_for(Thread* thread, size_t start_idx, size_t stop_idx,
-                            EVALUATE_FUNC& eval_f, DELETE_FUNC& del_f)
+                            EVALUATE_FUNC& eval_f, DELETE_FUNC& del_f, bool is_mt)
 {
   // Here we have resize lock so table is SMR safe, and there is no new
   // table. Can do this in parallel if we want.
-  assert(_resize_lock_owner == thread, "Re-size lock not held");
+  assert((is_mt && _resize_lock_owner != NULL) ||
+         (!is_mt && _resize_lock_owner == thread), "Re-size lock not held");
   Node* ndel[BULK_DELETE_LIMIT];
   InternalTable* table = get_table();
   assert(start_idx < stop_idx, "Must be");
@@ -516,7 +517,11 @@
     bucket->lock();
     size_t nd = delete_check_nodes(bucket, eval_f, BULK_DELETE_LIMIT, ndel);
     bucket->unlock();
-    write_synchonize_on_visible_epoch(thread);
+    if (is_mt) {
+      GlobalCounter::write_synchronize();
+    } else {
+      write_synchonize_on_visible_epoch(thread);
+    }
     for (size_t node_it = 0; node_it < nd; node_it++) {
       del_f(ndel[node_it]->value());
       Node::destroy_node(ndel[node_it]);
@@ -1198,7 +1203,7 @@
   if (!try_resize_lock(thread)) {
     return false;
   }
-  assert(_new_table == NULL, "Must be NULL");
+  assert(_new_table == NULL || _new_table == POISON_PTR, "Must be NULL");
   for (size_t bucket_it = 0; bucket_it < _table->_size; bucket_it++) {
     Bucket* bucket = _table->get_bucket(bucket_it);
     assert(!bucket->have_redirect() && !bucket->is_locked(), "Table must be uncontended");
--- a/src/hotspot/share/utilities/concurrentHashTableTasks.inline.hpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/hotspot/share/utilities/concurrentHashTableTasks.inline.hpp	Tue Jun 19 16:33:07 2018 +0100
@@ -45,9 +45,10 @@
   size_t _task_size_log2; // Number of buckets.
   size_t _stop_task;      // Last task
   size_t _size_log2;      // Table size.
+  bool   _is_mt;
 
-  BucketsOperation(ConcurrentHashTable<VALUE, CONFIG, F>* cht)
-    : _cht(cht), _next_to_claim(0), _task_size_log2(DEFAULT_TASK_SIZE_LOG2),
+  BucketsOperation(ConcurrentHashTable<VALUE, CONFIG, F>* cht, bool is_mt = false)
+    : _cht(cht), _is_mt(is_mt), _next_to_claim(0), _task_size_log2(DEFAULT_TASK_SIZE_LOG2),
     _stop_task(0), _size_log2(0) {}
 
   // Returns true if you succeeded to claim the range start -> (stop-1).
@@ -107,8 +108,8 @@
   public BucketsOperation
 {
  public:
-  BulkDeleteTask(ConcurrentHashTable<VALUE, CONFIG, F>* cht)
-    : BucketsOperation(cht) {
+  BulkDeleteTask(ConcurrentHashTable<VALUE, CONFIG, F>* cht, bool is_mt = false)
+    : BucketsOperation(cht, is_mt) {
   }
   // Before start prepare must be called.
   bool prepare(Thread* thread) {
@@ -124,7 +125,7 @@
   // Does one range destroying all matching EVALUATE_FUNC and
   // DELETE_FUNC is called be destruction. Returns true if there is more work.
   template <typename EVALUATE_FUNC, typename DELETE_FUNC>
-  bool doTask(Thread* thread, EVALUATE_FUNC& eval_f, DELETE_FUNC& del_f) {
+  bool do_task(Thread* thread, EVALUATE_FUNC& eval_f, DELETE_FUNC& del_f) {
     size_t start, stop;
     assert(BucketsOperation::_cht->_resize_lock_owner != NULL,
            "Should be locked");
@@ -132,7 +133,8 @@
       return false;
     }
     BucketsOperation::_cht->do_bulk_delete_locked_for(thread, start, stop,
-                                                      eval_f, del_f);
+                                                      eval_f, del_f,
+                                                      BucketsOperation::_is_mt);
     return true;
   }
 
@@ -187,7 +189,7 @@
   }
 
   // Re-sizes a portion of the table. Returns true if there is more work.
-  bool doTask(Thread* thread) {
+  bool do_task(Thread* thread) {
     size_t start, stop;
     assert(BucketsOperation::_cht->_resize_lock_owner != NULL,
            "Should be locked");
@@ -217,7 +219,7 @@
     this->thread_owns_resize_lock(thread);
   }
 
-  // Must be called after doTask returns false.
+  // Must be called after do_task returns false.
   void done(Thread* thread) {
     this->thread_owns_resize_lock(thread);
     BucketsOperation::_cht->internal_grow_epilog(thread);
--- a/src/java.base/linux/classes/sun/nio/ch/EPollSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/linux/classes/sun/nio/ch/EPollSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,6 +27,7 @@
 
 import java.io.IOException;
 import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.ArrayDeque;
@@ -34,6 +35,7 @@
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 
 import static sun.nio.ch.EPoll.EPOLLIN;
 import static sun.nio.ch.EPoll.EPOLL_CTL_ADD;
@@ -97,7 +99,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
 
         // epoll_wait timeout is int
@@ -130,7 +134,7 @@
             end(blocking);
         }
         processDeregisterQueue();
-        return updateSelectedKeys(numEntries);
+        return processEvents(numEntries, action);
     }
 
     /**
@@ -171,13 +175,13 @@
     }
 
     /**
-     * Update the keys of file descriptors that were polled and add them to
-     * the selected-key set.
+     * Process the polled events.
      * If the interrupt fd has been selected, drain it and clear the interrupt.
      */
-    private int updateSelectedKeys(int numEntries) throws IOException {
+    private int processEvents(int numEntries, Consumer<SelectionKey> action)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
-        assert Thread.holdsLock(nioSelectedKeys());
 
         boolean interrupted = false;
         int numKeysUpdated = 0;
@@ -190,17 +194,7 @@
                 SelectionKeyImpl ski = fdToKey.get(fd);
                 if (ski != null) {
                     int rOps = EPoll.getEvents(event);
-                    if (selectedKeys.contains(ski)) {
-                        if (ski.translateAndUpdateReadyOps(rOps)) {
-                            numKeysUpdated++;
-                        }
-                    } else {
-                        ski.translateAndSetReadyOps(rOps);
-                        if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
-                            selectedKeys.add(ski);
-                            numKeysUpdated++;
-                        }
-                    }
+                    numKeysUpdated += processReadyEvents(rOps, ski, action);
                 }
             }
         }
--- a/src/java.base/macosx/classes/sun/nio/ch/KQueueSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/macosx/classes/sun/nio/ch/KQueueSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,6 +27,7 @@
 
 import java.io.IOException;
 import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.ArrayDeque;
@@ -34,6 +35,7 @@
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 
 import static sun.nio.ch.KQueue.EVFILT_READ;
 import static sun.nio.ch.KQueue.EVFILT_WRITE;
@@ -100,7 +102,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
 
         long to = Math.min(timeout, Integer.MAX_VALUE);  // max kqueue timeout
@@ -132,7 +136,7 @@
             end(blocking);
         }
         processDeregisterQueue();
-        return updateSelectedKeys(numEntries);
+        return processEvents(numEntries, action);
     }
 
     /**
@@ -180,13 +184,13 @@
     }
 
     /**
-     * Update the keys of file descriptors that were polled and add them to
-     * the selected-key set.
+     * Process the polled events.
      * If the interrupt fd has been selected, drain it and clear the interrupt.
      */
-    private int updateSelectedKeys(int numEntries) throws IOException {
+    private int processEvents(int numEntries, Consumer<SelectionKey> action)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
-        assert Thread.holdsLock(nioSelectedKeys());
 
         int numKeysUpdated = 0;
         boolean interrupted = false;
@@ -214,22 +218,10 @@
                     } else if (filter == EVFILT_WRITE) {
                         rOps |= Net.POLLOUT;
                     }
-
-                    if (selectedKeys.contains(ski)) {
-                        if (ski.translateAndUpdateReadyOps(rOps)) {
-                            // file descriptor may be polled more than once per poll
-                            if (ski.lastPolled != pollCount) {
-                                numKeysUpdated++;
-                                ski.lastPolled = pollCount;
-                            }
-                        }
-                    } else {
-                        ski.translateAndSetReadyOps(rOps);
-                        if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
-                            selectedKeys.add(ski);
-                            numKeysUpdated++;
-                            ski.lastPolled = pollCount;
-                        }
+                    int updated = processReadyEvents(rOps, ski, action);
+                    if (updated > 0 && ski.lastPolled != pollCount) {
+                        numKeysUpdated++;
+                        ski.lastPolled = pollCount;
                     }
                 }
             }
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/BandStructure.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/BandStructure.java	Tue Jun 19 16:33:07 2018 +0100
@@ -54,6 +54,7 @@
  * Define the structure and ordering of "bands" in a packed file.
  * @author John Rose
  */
+@SuppressWarnings({"removal"})
 abstract
 class BandStructure {
     static final int MAX_EFFORT = 9;
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -56,9 +56,12 @@
 
 /** Command line interface for Pack200.
  */
+
+@SuppressWarnings({"removal"})
 class Driver {
-        private static final ResourceBundle RESOURCE =
-                ResourceBundle.getBundle("com.sun.java.util.jar.pack.DriverResource");
+    private static final ResourceBundle RESOURCE =
+        ResourceBundle.getBundle("com.sun.java.util.jar.pack.DriverResource");
+    private static boolean suppressDeprecateMsg = false;
 
     public static void main(String[] ava) throws IOException {
         List<String> av = new ArrayList<>(Arrays.asList(ava));
@@ -67,6 +70,7 @@
         boolean doUnpack = false;
         boolean doRepack = false;
         boolean doZip = true;
+        suppressDeprecateMsg = av.remove("-XDsuppress-tool-removal-message");
         String logFile = null;
         String verboseProp = Utils.DEBUG_VERBOSE;
 
@@ -85,6 +89,10 @@
             }
         }
 
+        if (!suppressDeprecateMsg) {
+            printDeprecateWarning(doPack, System.out);
+        }
+
         // Collect engine properties here:
         Map<String,String> engProps = new HashMap<>();
         engProps.put(verboseProp, System.getProperty(verboseProp));
@@ -395,6 +403,12 @@
     }
 
     private static
+    void printDeprecateWarning(boolean doPack, PrintStream out) {
+        String prog = doPack ? "pack200" : "unpack200";
+        out.println(MessageFormat.format(RESOURCE.getString(DriverResource.DEPRECATED), prog));
+    }
+
+    private static
     void printUsage(boolean doPack, boolean full, PrintStream out) {
         String prog = doPack ? "pack200" : "unpack200";
         String[] packUsage = (String[])RESOURCE.getObject(DriverResource.PACK_HELP);
@@ -407,6 +421,11 @@
                 break;
             }
         }
+        // Print a warning at the end
+        // The full help page is long, the beginning warning could be out of sight
+        if (full && !suppressDeprecateMsg) {
+            printDeprecateWarning(doPack, out);
+        }
     }
 
     private static
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/DriverResource.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/DriverResource.java	Tue Jun 19 16:33:07 2018 +0100
@@ -42,6 +42,7 @@
     public static final String MORE_INFO = "MORE_INFO";
     public static final String DUPLICATE_OPTION = "DUPLICATE_OPTION";
     public static final String BAD_SPEC = "BAD_SPEC";
+    public static final String DEPRECATED = "DEPRECATED";
 
     /*
      * The following are the output of 'pack200' and 'unpack200' commands.
@@ -126,6 +127,7 @@
         {MORE_INFO, "(For more information, run {0} --help .)"}, // parameter 0:command name
         {DUPLICATE_OPTION, "duplicate option: {0}"}, // parameter 0:option
         {BAD_SPEC, "bad spec for {0}: {1}"}, // parameter 0:option;parameter 1:specifier
+        {DEPRECATED, "\nWarning: The {0} tool is deprecated, and is planned for removal in a future JDK release.\n"} // parameter 0:command name
     };
 
     protected Object[][] getContents() {
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,6 +39,7 @@
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
+@SuppressWarnings({"removal"})
 class NativeUnpack {
     // Pointer to the native unpacker obj
     private long unpackerPtr;
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -55,7 +55,7 @@
  * @author Kumar Srinivasan
  */
 
-
+@SuppressWarnings({"removal"})
 public class PackerImpl  extends TLGlobals implements Pack200.Packer {
 
     /**
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/PropMap.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/PropMap.java	Tue Jun 19 16:33:07 2018 +0100
@@ -47,6 +47,7 @@
  * Control block for publishing Pack200 options to the other classes.
  */
 
+@SuppressWarnings({"removal"})
 final class PropMap implements SortedMap<String, String>  {
     private final TreeMap<String, String> theMap = new TreeMap<>();;
 
--- a/src/java.base/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -53,6 +53,7 @@
  */
 
 
+@SuppressWarnings({"removal"})
 public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
 
     public UnpackerImpl() {}
--- a/src/java.base/share/classes/java/lang/ClassLoader.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/lang/ClassLoader.java	Tue Jun 19 16:33:07 2018 +0100
@@ -59,6 +59,7 @@
 import java.util.stream.Stream;
 import java.util.stream.StreamSupport;
 
+import jdk.internal.loader.BuiltinClassLoader;
 import jdk.internal.perf.PerfCounter;
 import jdk.internal.loader.BootLoader;
 import jdk.internal.loader.ClassLoaders;
@@ -246,6 +247,9 @@
     // the unnamed module for this ClassLoader
     private final Module unnamedModule;
 
+    // a string for exception message printing
+    private final String nameAndId;
+
     /**
      * Encapsulates the set of parallel capable loader types.
      */
@@ -381,6 +385,24 @@
             package2certs = new Hashtable<>();
             assertionLock = this;
         }
+        this.nameAndId = nameAndId(this);
+    }
+
+    /**
+     * If the defining loader has a name explicitly set then
+     *       '<loader-name>' @<id>
+     * If the defining loader has no name then
+     *       <qualified-class-name> @<id>
+     * If it's built-in loader then omit `@<id>` as there is only one instance.
+     */
+    private static String nameAndId(ClassLoader ld) {
+        String nid = ld.getName() != null ? "\'" + ld.getName() + "\'"
+                                          : ld.getClass().getName();
+        if (!(ld instanceof BuiltinClassLoader)) {
+            String id = Integer.toHexString(System.identityHashCode(ld));
+            nid = nid + " @" + id;
+        }
+        return nid;
     }
 
     /**
--- a/src/java.base/share/classes/java/nio/X-Buffer.java.template	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/nio/X-Buffer.java.template	Tue Jun 19 16:33:07 2018 +0100
@@ -1353,6 +1353,38 @@
 #end[floatingPointType]
     }
 
+    /**
+     * Finds and returns the relative index of the first mismatch between this
+     * buffer and a given buffer.  The index is relative to the
+     * {@link #position() position} of each buffer and will be in the range of
+     * 0 (inclusive) up to the smaller of the {@link #remaining() remaining}
+     * elements in each buffer (exclusive).
+     *
+     * <p> If the two buffers share a common prefix then the returned index is
+     * the length of the common prefix and it follows that there is a mismatch
+     * between the two buffers at that index within the respective buffers.
+     * If one buffer is a proper prefix of the other then the returned index is
+     * the smaller of the remaining elements in each buffer, and it follows that
+     * the index is only valid for the buffer with the larger number of
+     * remaining elements.
+     * Otherwise, there is no mismatch.
+     *
+     * @param  that
+     *         The byte buffer to be tested for a mismatch with this buffer
+     *
+     * @return  The relative index of the first mismatch between this and the
+     *          given buffer, otherwise -1 if no mismatch.
+     *
+     * @since 11
+     */
+    public int mismatch($Type$Buffer that) {
+        int length = Math.min(this.remaining(), that.remaining());
+        int r = BufferMismatch.mismatch(this, this.position(),
+                                        that, that.position(),
+                                        length);
+        return (r == -1 && this.remaining() != that.remaining()) ? length : r;
+    }
+
     // -- Other char stuff --
 
 #if[char]
--- a/src/java.base/share/classes/java/nio/channels/SelectionKey.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/nio/channels/SelectionKey.java	Tue Jun 19 16:33:07 2018 +0100
@@ -291,7 +291,7 @@
      * detects that the corresponding channel is ready for reading, has reached
      * end-of-stream, has been remotely shut down for further reading, or has
      * an error pending, then it will add {@code OP_READ} to the key's
-     * ready-operation set and add the key to its selected-key&nbsp;set.  </p>
+     * ready-operation set.  </p>
      */
     public static final int OP_READ = 1 << 0;
 
@@ -303,8 +303,7 @@
      * href="Selector.html#selop">selection operation</a>.  If the selector
      * detects that the corresponding channel is ready for writing, has been
      * remotely shut down for further writing, or has an error pending, then it
-     * will add {@code OP_WRITE} to the key's ready set and add the key to its
-     * selected-key&nbsp;set.  </p>
+     * will add {@code OP_WRITE} to the key's ready set.  </p>
      */
     public static final int OP_WRITE = 1 << 2;
 
@@ -316,8 +315,7 @@
      * href="Selector.html#selop">selection operation</a>.  If the selector
      * detects that the corresponding socket channel is ready to complete its
      * connection sequence, or has an error pending, then it will add
-     * {@code OP_CONNECT} to the key's ready set and add the key to its
-     * selected-key&nbsp;set.  </p>
+     * {@code OP_CONNECT} to the key's ready set.  </p>
      */
     public static final int OP_CONNECT = 1 << 3;
 
@@ -329,8 +327,7 @@
      * href="Selector.html#selop">selection operation</a>.  If the selector
      * detects that the corresponding server-socket channel is ready to accept
      * another connection, or has an error pending, then it will add
-     * {@code OP_ACCEPT} to the key's ready set and add the key to its
-     * selected-key&nbsp;set.  </p>
+     * {@code OP_ACCEPT} to the key's ready set.  </p>
      */
     public static final int OP_ACCEPT = 1 << 4;
 
--- a/src/java.base/share/classes/java/nio/channels/Selector.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/nio/channels/Selector.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,7 +28,9 @@
 import java.io.Closeable;
 import java.io.IOException;
 import java.nio.channels.spi.SelectorProvider;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Consumer;
 
 
 /**
@@ -56,7 +58,8 @@
  *
  *   <li><p> The <i>selected-key set</i> is the set of keys such that each
  *   key's channel was detected to be ready for at least one of the operations
- *   identified in the key's interest set during a prior selection operation.
+ *   identified in the key's interest set during a prior selection operation
+ *   that adds keys or updates keys in the set.
  *   This set is returned by the {@link #selectedKeys() selectedKeys} method.
  *   The selected-key set is always a subset of the key set. </p></li>
  *
@@ -92,6 +95,27 @@
  * <a id="selop"></a>
  * <h2>Selection</h2>
  *
+ * <p> A selection operation queries the underlying operating system for an
+ * update as to the readiness of each registered channel to perform any of the
+ * operations identified by its key's interest set.  There are two forms of
+ * selection operation:
+ *
+ * <ol>
+ *
+ *   <li><p> The {@link #select()}, {@link #select(long)}, and {@link #selectNow()}
+ *   methods add the keys of channels ready to perform an operation to the
+ *   selected-key set, or update the ready-operation set of keys already in the
+ *   selected-key set. </p></li>
+ *
+ *   <li><p> The {@link #select(Consumer)}, {@link #select(Consumer, long)}, and
+ *   {@link #selectNow(Consumer)} methods perform an <i>action</i> on the key
+ *   of each channel that is ready to perform an operation.  These methods do
+ *   not add to the selected-key set. </p></li>
+ *
+ * </ol>
+ *
+ * <h3>Selection operations that add to the selected-key set</h3>
+ *
  * <p> During each selection operation, keys may be added to and removed from a
  * selector's selected-key set and may be removed from its key and
  * cancelled-key sets.  Selection is performed by the {@link #select()}, {@link
@@ -141,6 +165,45 @@
  * difference between the three selection methods. </p>
  *
  *
+ * <h3>Selection operations that perform an action on selected keys</h3>
+ *
+ * <p> During each selection operation, keys may be removed from the selector's
+ * key, selected-key, and cancelled-key sets.  Selection is performed by the
+ * {@link #select(Consumer)}, {@link #select(Consumer,long)}, and {@link
+ * #selectNow(Consumer)} methods, and involves three steps:  </p>
+ *
+ * <ol>
+ *
+ *   <li><p> Each key in the cancelled-key set is removed from each key set of
+ *   which it is a member, and its channel is deregistered.  This step leaves
+ *   the cancelled-key set empty. </p></li>
+ *
+ *   <li><p> The underlying operating system is queried for an update as to the
+ *   readiness of each remaining channel to perform any of the operations
+ *   identified by its key's interest set as of the moment that the selection
+ *   operation began.
+ *
+ *   <p> For a channel that is ready for at least one such operation, the
+ *   ready-operation set of the channel's key is set to identify exactly the
+ *   operations for which the channel is ready and the <i>action</i> specified
+ *   to the {@code select} method is invoked to consume the channel's key.  Any
+ *   readiness information previously recorded in the ready set is discarded
+ *   prior to invoking the <i>action</i>.
+ *
+ *   <p> Alternatively, where a channel is ready for more than one operation,
+ *   the <i>action</i> may be invoked more than once with the channel's key and
+ *   ready-operation set modified to a subset of the operations for which the
+ *   channel is ready.  Where the <i>action</i> is invoked more than once for
+ *   the same key then its ready-operation set never contains operation bits
+ *   that were contained in the set at previous calls to the <i>action</i>
+ *   in the same selection operation.  </p></li>
+ *
+ *   <li><p> If any keys were added to the cancelled-key set while step (2) was
+ *   in progress then they are processed as in step (1). </p></li>
+ *
+ * </ol>
+ *
+ *
  * <h2>Concurrency</h2>
  *
  * <p> A Selector and its key set are safe for use by multiple concurrent
@@ -156,13 +219,12 @@
  *
  * <p> Keys may be cancelled and channels may be closed at any time.  Hence the
  * presence of a key in one or more of a selector's key sets does not imply
- * that the key is valid or that its channel is open.  Application code should
+ * that the key is valid or that its channel is open. Application code should
  * be careful to synchronize and check these conditions as necessary if there
  * is any possibility that another thread will cancel a key or close a channel.
  *
- * <p> A thread blocked in one of the {@link #select()} or {@link
- * #select(long)} methods may be interrupted by some other thread in one of
- * three ways:
+ * <p> A thread blocked in a selection operation may be interrupted by some
+ * other thread in one of three ways:
  *
  * <ul>
  *
@@ -356,18 +418,188 @@
     public abstract int select() throws IOException;
 
     /**
+     * Selects and performs an action on the keys whose corresponding channels
+     * are ready for I/O operations.
+     *
+     * <p> This method performs a blocking <a href="#selop">selection
+     * operation</a>.  It wakes up from querying the operating system only when
+     * at least one channel is selected, this selector's {@link #wakeup wakeup}
+     * method is invoked, the current thread is interrupted, or the given
+     * timeout period expires, whichever comes first.
+     *
+     * <p> The specified <i>action</i>'s {@link Consumer#accept(Object) accept}
+     * method is invoked with the key for each channel that is ready to perform
+     * an operation identified by its key's interest set.  The {@code accept}
+     * method may be invoked more than once for the same key but with the
+     * ready-operation set containing a subset of the operations for which the
+     * channel is ready (as described above).  The {@code accept} method is
+     * invoked while synchronized on the selector and its selected-key set.
+     * Great care must be taken to avoid deadlocking with other threads that
+     * also synchronize on these objects.  Selection operations are not reentrant
+     * in general and consequently the <i>action</i> should take great care not
+     * to attempt a selection operation on the same selector.  The behavior when
+     * attempting a reentrant selection operation is implementation specific and
+     * therefore not specified.  If the <i>action</i> closes the selector then
+     * {@code ClosedSelectorException} is thrown when the action completes.
+     * The <i>action</i> is not prohibited from closing channels registered with
+     * the selector, nor prohibited from cancelling keys or changing a key's
+     * interest set.  If a channel is selected but its key is cancelled or its
+     * interest set changed before the <i>action</i> is performed on the key
+     * then it is implementation specific as to whether the <i>action</i> is
+     * invoked (it may be invoked with an {@link SelectionKey#isValid() invalid}
+     * key).  Exceptions thrown by the action are relayed to the caller.
+     *
+     * <p> This method does not offer real-time guarantees: It schedules the
+     * timeout as if by invoking the {@link Object#wait(long)} method.
+     *
+     * @implSpec The default implementation removes all keys from the
+     * selected-key set, invokes {@link #select(long) select(long)} with the
+     * given timeout and then performs the action for each key added to the
+     * selected-key set.  The default implementation does not detect the action
+     * performing a reentrant selection operation.  The selected-key set may
+     * or may not be empty on completion of the default implementation.
+     *
+     * @param  action   The action to perform
+     *
+     * @param  timeout  If positive, block for up to {@code timeout}
+     *                  milliseconds, more or less, while waiting for a
+     *                  channel to become ready; if zero, block indefinitely;
+     *                  must not be negative
+     *
+     * @return  The number of unique keys consumed, possibly zero
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
+     *
+     * @throws  ClosedSelectorException
+     *          If this selector is closed or is closed by the action
+     *
+     * @throws  IllegalArgumentException
+     *          If the value of the timeout argument is negative
+     *
+     * @since 11
+     */
+    public int select(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
+        if (timeout < 0)
+            throw new IllegalArgumentException("Negative timeout");
+        return doSelect(Objects.requireNonNull(action), timeout);
+    }
+
+    /**
+     * Selects and performs an action on the keys whose corresponding channels
+     * are ready for I/O operations.
+     *
+     * <p> This method performs a blocking <a href="#selop">selection
+     * operation</a>.  It wakes up from querying the operating system only when
+     * at least one channel is selected, this selector's {@link #wakeup wakeup}
+     * method is invoked, or the current thread is interrupted, whichever comes
+     * first.
+     *
+     * <p> This method is equivalent to invoking the 2-arg
+     * {@link #select(Consumer, long) select} method with a timeout of {@code 0}
+     * to block indefinitely.  </p>
+     *
+     * @implSpec The default implementation invokes the 2-arg {@code select}
+     * method with a timeout of {@code 0}.
+     *
+     * @param  action   The action to perform
+     *
+     * @return  The number of unique keys consumed, possibly zero
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
+     *
+     * @throws  ClosedSelectorException
+     *          If this selector is closed or is closed by the action
+     *
+     * @since 11
+     */
+    public int select(Consumer<SelectionKey> action) throws IOException {
+        return select(action, 0);
+    }
+
+    /**
+     * Selects and performs an action on the keys whose corresponding channels
+     * are ready for I/O operations.
+     *
+     * <p> This method performs a non-blocking <a href="#selop">selection
+     * operation</a>.
+     *
+     * <p> Invoking this method clears the effect of any previous invocations
+     * of the {@link #wakeup wakeup} method.  </p>
+     *
+     * @implSpec The default implementation removes all keys from the
+     * selected-key set, invokes {@link #selectNow() selectNow()} and then
+     * performs the action for each key added to the selected-key set.  The
+     * default implementation does not detect the action performing a reentrant
+     * selection operation.  The selected-key set may or may not be empty on
+     * completion of the default implementation.
+     *
+     * @param  action   The action to perform
+     *
+     * @return  The number of unique keys consumed, possibly zero
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
+     *
+     * @throws  ClosedSelectorException
+     *          If this selector is closed or is closed by the action
+     *
+     * @since 11
+     */
+    public int selectNow(Consumer<SelectionKey> action) throws IOException {
+        return doSelect(Objects.requireNonNull(action), -1);
+    }
+
+    /**
+     * Default implementation of select(Consumer) and selectNow(Consumer).
+     */
+    private int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
+        synchronized (this) {
+            Set<SelectionKey> selectedKeys = selectedKeys();
+            synchronized (selectedKeys) {
+                selectedKeys.clear();
+                int numKeySelected;
+                if (timeout < 0) {
+                    numKeySelected = selectNow();
+                } else {
+                    numKeySelected = select(timeout);
+                }
+
+                // copy selected-key set as action may remove keys
+                Set<SelectionKey> keysToConsume = Set.copyOf(selectedKeys);
+                assert keysToConsume.size() == numKeySelected;
+                selectedKeys.clear();
+
+                // invoke action for each selected key
+                keysToConsume.forEach(k -> {
+                    action.accept(k);
+                    if (!isOpen())
+                        throw new ClosedSelectorException();
+                });
+
+                return numKeySelected;
+            }
+        }
+    }
+
+
+    /**
      * Causes the first selection operation that has not yet returned to return
      * immediately.
      *
-     * <p> If another thread is currently blocked in an invocation of the
-     * {@link #select()} or {@link #select(long)} methods then that invocation
-     * will return immediately.  If no selection operation is currently in
-     * progress then the next invocation of one of these methods will return
-     * immediately unless the {@link #selectNow()} method is invoked in the
-     * meantime.  In any case the value returned by that invocation may be
-     * non-zero.  Subsequent invocations of the {@link #select()} or {@link
-     * #select(long)} methods will block as usual unless this method is invoked
-     * again in the meantime.
+     * <p> If another thread is currently blocked in a selection operation then
+     * that invocation will return immediately.  If no selection operation is
+     * currently in progress then the next invocation of a selection operation
+     * will return immediately unless {@link #selectNow()} or {@link
+     * #selectNow(Consumer)} is invoked in the meantime.  In any case the value
+     * returned by that invocation may be non-zero.  Subsequent selection
+     * operations will block as usual unless this method is invoked again in the
+     * meantime.
      *
      * <p> Invoking this method more than once between two successive selection
      * operations has the same effect as invoking it just once.  </p>
@@ -398,5 +630,4 @@
      *          If an I/O error occurs
      */
     public abstract void close() throws IOException;
-
 }
--- a/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java	Tue Jun 19 16:33:07 2018 +0100
@@ -793,6 +793,11 @@
         final LocaleStore store = new LocaleStore(map);
         DateTimeTextProvider provider = new DateTimeTextProvider() {
             @Override
+            public String getText(Chronology chrono, TemporalField field,
+                                  long value, TextStyle style, Locale locale) {
+                return store.getText(value, style);
+            }
+            @Override
             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
                 return store.getText(value, style);
             }
--- a/src/java.base/share/classes/java/util/BitSet.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/util/BitSet.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1277,12 +1277,33 @@
 
                 int hi = getFence();
                 int i = index;
-                int v = wordIndex(hi - 1);
                 index = -1;
-                while (i >= 0 && i < hi) {
-                    action.accept(i);
-                    i = nextSetBit(i + 1, v);
+
+                if (i >= 0 && i < hi) {
+                    action.accept(i++);
+
+                    int u = wordIndex(i);      // next lower word bound
+                    int v = wordIndex(hi - 1); // upper word bound
+
+                    words_loop:
+                    for (; u <= v && i <= hi; u++, i = u << ADDRESS_BITS_PER_WORD) {
+                        long word = words[u] & (WORD_MASK << i);
+                        while (word != 0) {
+                            i = (u << ADDRESS_BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
+                            if (i >= hi) {
+                                // Break out of outer loop to ensure check of
+                                // Integer.MAX_VALUE bit set
+                                break words_loop;
+                            }
+
+                            // Flip the set bit
+                            word &= ~(1L << i);
+
+                            action.accept(i);
+                        }
+                    }
                 }
+
                 // Check if there is a final bit set for Integer.MAX_VALUE
                 if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) {
                     action.accept(Integer.MAX_VALUE);
--- a/src/java.base/share/classes/java/util/jar/Pack200.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/java/util/jar/Pack200.java	Tue Jun 19 16:33:07 2018 +0100
@@ -101,7 +101,10 @@
  * @author John Rose
  * @author Kumar Srinivasan
  * @since 1.5
+ * @deprecated This class is deprecated, and is planned for removal in a future
+ *             release.
  */
+@Deprecated(since="11", forRemoval=true)
 public abstract class Pack200 {
     private Pack200() {} //prevent instantiation
 
@@ -225,7 +228,10 @@
      * to be thrown.
      *
      * @since 1.5
+     * @deprecated This interface is deprecated, and is planned for removal in a
+     *             future release.
      */
+    @Deprecated(since="11", forRemoval=true)
     public interface Packer {
         /**
          * This property is a numeral giving the estimated target size N
@@ -584,7 +590,10 @@
      * <p>
      * This version of the unpacker is compatible with all previous versions.
      * @since 1.5
+     * @deprecated This interface is deprecated, and is planned for removal in a
+     *             future release.
      */
+    @Deprecated(since="11", forRemoval=true)
     public interface Unpacker {
 
         /** The string "keep", a possible value for certain properties.
--- a/src/java.base/share/classes/module-info.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/module-info.java	Tue Jun 19 16:33:07 2018 +0100
@@ -152,8 +152,7 @@
         jdk.jartool,
         jdk.jfr,
         jdk.jlink,
-        jdk.scripting.nashorn,
-        jdk.internal.vm.ci;
+        jdk.scripting.nashorn;
     exports jdk.internal.org.objectweb.asm.tree to
         jdk.jfr,
         jdk.jlink;
@@ -182,7 +181,6 @@
         jdk.charsets,
         jdk.compiler,
         java.net.http,
-        jdk.jdeps,
         jdk.jfr,
         jdk.jlink,
         jdk.jshell,
@@ -212,11 +210,11 @@
         jdk.scripting.nashorn,
         jdk.unsupported;
     exports jdk.internal.vm to
-        jdk.management.agent,
-        jdk.internal.jvmstat;
+        jdk.internal.jvmstat,
+        jdk.management.agent;
     exports jdk.internal.vm.annotation to
-        jdk.unsupported,
-        jdk.internal.vm.ci;
+        jdk.internal.vm.ci,
+        jdk.unsupported;
     exports jdk.internal.util.jar to
         jdk.jartool;
     exports jdk.internal.util.xml to
@@ -260,8 +258,7 @@
         java.management,
         java.management.rmi,
         java.rmi,
-        java.sql.rowset,
-        java.xml;
+        java.sql.rowset;
     exports sun.security.action to
         java.desktop,
         java.security.jgss;
@@ -312,12 +309,9 @@
     exports sun.security.x509 to
         jdk.crypto.ec,
         jdk.crypto.cryptoki,
-        jdk.jartool,
-        jdk.security.auth;
+        jdk.jartool;
     exports sun.security.validator to
         jdk.jartool;
-    exports sun.text.resources to
-        jdk.localedata;
     exports sun.util.cldr to
         jdk.jlink;
     exports sun.util.locale.provider to
--- a/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,8 +36,10 @@
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
 
 
 /**
@@ -51,12 +53,15 @@
     private final Set<SelectionKey> keys;
 
     // The set of keys with data ready for an operation
-    protected final Set<SelectionKey> selectedKeys;
+    private final Set<SelectionKey> selectedKeys;
 
     // Public views of the key sets
     private final Set<SelectionKey> publicKeys;             // Immutable
     private final Set<SelectionKey> publicSelectedKeys;     // Removal allowed, but not addition
 
+    // used to check for reentrancy
+    private boolean inSelect;
+
     protected SelectorImpl(SelectorProvider sp) {
         super(sp);
         keys = ConcurrentHashMap.newKeySet();
@@ -83,13 +88,6 @@
     }
 
     /**
-     * Returns the public view of the selected-key set
-     */
-    protected final Set<SelectionKey> nioSelectedKeys() {
-        return publicSelectedKeys;
-    }
-
-    /**
      * Marks the beginning of a select operation that might block
      */
     protected final void begin(boolean blocking) {
@@ -106,16 +104,27 @@
     /**
      * Selects the keys for channels that are ready for I/O operations.
      *
+     * @param action  the action to perform, can be null
      * @param timeout timeout in milliseconds to wait, 0 to not wait, -1 to
      *                wait indefinitely
      */
-    protected abstract int doSelect(long timeout) throws IOException;
+    protected abstract int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException;
 
-    private int lockAndDoSelect(long timeout) throws IOException {
+    private int lockAndDoSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         synchronized (this) {
             ensureOpen();
-            synchronized (publicSelectedKeys) {
-                return doSelect(timeout);
+            if (inSelect)
+                throw new IllegalStateException("select in progress");
+            inSelect = true;
+            try {
+                synchronized (publicSelectedKeys) {
+                    return doSelect(action, timeout);
+                }
+            } finally {
+                inSelect = false;
             }
         }
     }
@@ -124,17 +133,39 @@
     public final int select(long timeout) throws IOException {
         if (timeout < 0)
             throw new IllegalArgumentException("Negative timeout");
-        return lockAndDoSelect((timeout == 0) ? -1 : timeout);
+        return lockAndDoSelect(null, (timeout == 0) ? -1 : timeout);
     }
 
     @Override
     public final int select() throws IOException {
-        return lockAndDoSelect(-1);
+        return lockAndDoSelect(null, -1);
     }
 
     @Override
     public final int selectNow() throws IOException {
-        return lockAndDoSelect(0);
+        return lockAndDoSelect(null, 0);
+    }
+
+    @Override
+    public final int select(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
+        Objects.requireNonNull(action);
+        if (timeout < 0)
+            throw new IllegalArgumentException("Negative timeout");
+        return lockAndDoSelect(action, (timeout == 0) ? -1 : timeout);
+    }
+
+    @Override
+    public final int select(Consumer<SelectionKey> action) throws IOException {
+        Objects.requireNonNull(action);
+        return lockAndDoSelect(action, -1);
+    }
+
+    @Override
+    public final int selectNow(Consumer<SelectionKey> action) throws IOException {
+        Objects.requireNonNull(action);
+        return lockAndDoSelect(action, 0);
     }
 
     /**
@@ -240,6 +271,39 @@
     }
 
     /**
+     * Invoked by selection operations to handle ready events. If an action
+     * is specified then it is invoked to handle the key, otherwise the key
+     * is added to the selected-key set (or updated when it is already in the
+     * set).
+     */
+    protected final int processReadyEvents(int rOps,
+                                           SelectionKeyImpl ski,
+                                           Consumer<SelectionKey> action) {
+        if (action != null) {
+            ski.translateAndSetReadyOps(rOps);
+            if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
+                action.accept(ski);
+                ensureOpen();
+                return 1;
+            }
+        } else {
+            assert Thread.holdsLock(publicSelectedKeys);
+            if (selectedKeys.contains(ski)) {
+                if (ski.translateAndUpdateReadyOps(rOps)) {
+                    return 1;
+                }
+            } else {
+                ski.translateAndSetReadyOps(rOps);
+                if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
+                    selectedKeys.add(ski);
+                    return 1;
+                }
+            }
+        }
+        return 0;
+    }
+
+    /**
      * Invoked by interestOps to ensure the interest ops are updated at the
      * next selection operation.
      */
--- a/src/java.base/share/classes/sun/reflect/annotation/AnnotationParser.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/classes/sun/reflect/annotation/AnnotationParser.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,10 +26,11 @@
 package sun.reflect.annotation;
 
 import java.lang.annotation.*;
-import java.util.*;
+import java.lang.reflect.*;
+import java.nio.BufferUnderflowException;
 import java.nio.ByteBuffer;
-import java.nio.BufferUnderflowException;
-import java.lang.reflect.*;
+import java.util.*;
+import java.util.function.Supplier;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import jdk.internal.reflect.ConstantPool;
@@ -714,40 +715,16 @@
                                           ByteBuffer buf,
                                           ConstantPool constPool,
                                           Class<?> container) {
-        Object[] result = new Class<?>[length];
-        boolean typeMismatch = false;
-        int tag = 0;
-
-        for (int i = 0; i < length; i++) {
-            tag = buf.get();
-            if (tag == 'c') {
-                result[i] = parseClassValue(buf, constPool, container);
-            } else {
-                skipMemberValue(tag, buf);
-                typeMismatch = true;
-            }
-        }
-        return typeMismatch ? exceptionProxy(tag) : result;
+        return parseArrayElements(new Class<?>[length],
+                buf, 'c', () -> parseClassValue(buf, constPool, container));
     }
 
     private static Object parseEnumArray(int length, Class<? extends Enum<?>> enumType,
                                          ByteBuffer buf,
                                          ConstantPool constPool,
                                          Class<?> container) {
-        Object[] result = (Object[]) Array.newInstance(enumType, length);
-        boolean typeMismatch = false;
-        int tag = 0;
-
-        for (int i = 0; i < length; i++) {
-            tag = buf.get();
-            if (tag == 'e') {
-                result[i] = parseEnumValue(enumType, buf, constPool, container);
-            } else {
-                skipMemberValue(tag, buf);
-                typeMismatch = true;
-            }
-        }
-        return typeMismatch ? exceptionProxy(tag) : result;
+        return parseArrayElements((Object[]) Array.newInstance(enumType, length),
+                buf, 'e', () -> parseEnumValue(enumType, buf, constPool, container));
     }
 
     private static Object parseAnnotationArray(int length,
@@ -755,20 +732,30 @@
                                                ByteBuffer buf,
                                                ConstantPool constPool,
                                                Class<?> container) {
-        Object[] result = (Object[]) Array.newInstance(annotationType, length);
-        boolean typeMismatch = false;
-        int tag = 0;
+        return parseArrayElements((Object[]) Array.newInstance(annotationType, length),
+                buf, '@', () -> parseAnnotation(buf, constPool, container, true));
+    }
 
-        for (int i = 0; i < length; i++) {
-            tag = buf.get();
-            if (tag == '@') {
-                result[i] = parseAnnotation(buf, constPool, container, true);
+    private static Object parseArrayElements(Object[] result,
+                                             ByteBuffer buf,
+                                             int expectedTag,
+                                             Supplier<Object> parseElement) {
+        Object exceptionProxy = null;
+        for (int i = 0; i < result.length; i++) {
+            int tag = buf.get();
+            if (tag == expectedTag) {
+                Object value = parseElement.get();
+                if (value instanceof ExceptionProxy) {
+                    if (exceptionProxy == null) exceptionProxy = (ExceptionProxy) value;
+                } else {
+                    result[i] = value;
+                }
             } else {
                 skipMemberValue(tag, buf);
-                typeMismatch = true;
+                if (exceptionProxy == null) exceptionProxy = exceptionProxy(tag);
             }
         }
-        return typeMismatch ? exceptionProxy(tag) : result;
+        return (exceptionProxy != null) ? exceptionProxy : result;
     }
 
     /**
--- a/src/java.base/share/native/libjimage/imageDecompressor.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/share/native/libjimage/imageDecompressor.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -322,6 +322,7 @@
             {
                 i++;
             }
+            /* fall through */
             default:
             {
                 *uncompressed_resource = tag;
--- a/src/java.base/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,6 +27,7 @@
 
 import java.io.IOException;
 import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.ArrayDeque;
@@ -34,6 +35,7 @@
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 
 import static sun.nio.ch.DevPollArrayWrapper.NUM_POLLFDS;
 import static sun.nio.ch.DevPollArrayWrapper.POLLREMOVE;
@@ -85,7 +87,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
 
         long to = timeout;
@@ -117,7 +121,7 @@
             end(blocking);
         }
         processDeregisterQueue();
-        return updateSelectedKeys(numEntries);
+        return processEvents(numEntries, action);
     }
 
     /**
@@ -165,13 +169,13 @@
     }
 
     /**
-     * Update the keys of file descriptors that were polled and add them to
-     * the selected-key set.
+     * Process the polled events.
      * If the interrupt fd has been selected, drain it and clear the interrupt.
      */
-    private int updateSelectedKeys(int numEntries) throws IOException {
+    private int processEvents(int numEntries, Consumer<SelectionKey> action)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
-        assert Thread.holdsLock(nioSelectedKeys());
 
         boolean interrupted = false;
         int numKeysUpdated = 0;
@@ -183,17 +187,7 @@
                 SelectionKeyImpl ski = fdToKey.get(fd);
                 if (ski != null) {
                     int rOps = pollWrapper.getReventOps(i);
-                    if (selectedKeys.contains(ski)) {
-                        if (ski.translateAndUpdateReadyOps(rOps)) {
-                            numKeysUpdated++;
-                        }
-                    } else {
-                        ski.translateAndSetReadyOps(rOps);
-                        if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
-                            selectedKeys.add(ski);
-                            numKeysUpdated++;
-                        }
-                    }
+                    numKeysUpdated += processReadyEvents(rOps, ski, action);
                 }
             }
         }
--- a/src/java.base/solaris/classes/sun/nio/ch/EventPortSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/solaris/classes/sun/nio/ch/EventPortSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,6 +35,7 @@
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 
 import static sun.nio.ch.SolarisEventPort.PORT_SOURCE_FD;
 import static sun.nio.ch.SolarisEventPort.PORT_SOURCE_USER;
@@ -97,7 +98,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
 
         long to = timeout;
@@ -129,7 +132,7 @@
             end(blocking);
         }
         processDeregisterQueue();
-        return processPortEvents(numEvents);
+        return processPortEvents(numEvents, action);
     }
 
     /**
@@ -166,19 +169,21 @@
     }
 
     /**
-     * Process the port events. This method updates the keys of file descriptors
-     * that were polled. It also re-queues the key so that the file descriptor
-     * is re-associated at the next select operation.
-     *
-     * @return the number of selection keys updated.
+     * Process the polled events and re-queue the selected keys so the file
+     * descriptors are re-associated at the next select operation.
      */
-    private int processPortEvents(int numEvents) throws IOException {
+    private int processPortEvents(int numEvents, Consumer<SelectionKey> action)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
-        assert Thread.holdsLock(nioSelectedKeys());
 
         int numKeysUpdated = 0;
         boolean interrupted = false;
 
+        // Process the polled events while holding the update lock. This allows
+        // keys to be queued for ready file descriptors so they can be
+        // re-associated at the next select. The selected-key can be updated
+        // in this pass.
         synchronized (updateLock) {
             for (int i = 0; i < numEvents; i++) {
                 short source = getSource(i);
@@ -186,27 +191,36 @@
                     int fd = getDescriptor(i);
                     SelectionKeyImpl ski = fdToKey.get(fd);
                     if (ski != null) {
+                        ski.registeredEvents(0);
+                        updateKeys.addLast(ski);
+
+                        // update selected-key set if no action specified
+                        if (action == null) {
+                            int rOps = getEventOps(i);
+                            numKeysUpdated += processReadyEvents(rOps, ski, null);
+                        }
+
+                    }
+                } else if (source == PORT_SOURCE_USER) {
+                    interrupted = true;
+                } else {
+                    assert false;
+                }
+            }
+        }
+
+        // if an action specified then iterate over the polled events again so
+        // that the action is performed without holding the update lock.
+        if (action != null) {
+            for (int i = 0; i < numEvents; i++) {
+                short source = getSource(i);
+                if (source == PORT_SOURCE_FD) {
+                    int fd = getDescriptor(i);
+                    SelectionKeyImpl ski = fdToKey.get(fd);
+                    if (ski != null) {
                         int rOps = getEventOps(i);
-                        if (selectedKeys.contains(ski)) {
-                            if (ski.translateAndUpdateReadyOps(rOps)) {
-                                numKeysUpdated++;
-                            }
-                        } else {
-                            ski.translateAndSetReadyOps(rOps);
-                            if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
-                                selectedKeys.add(ski);
-                                numKeysUpdated++;
-                            }
-                        }
-
-                        // re-queue key so it re-associated at next select
-                        ski.registeredEvents(0);
-                        updateKeys.addLast(ski);
+                        numKeysUpdated += processReadyEvents(rOps, ski, action);
                     }
-                } else if (source == PORT_SOURCE_USER) {
-                    interrupted = true;
-                } else {
-                    assert false;
                 }
             }
         }
--- a/src/java.base/unix/classes/sun/nio/ch/PollSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/unix/classes/sun/nio/ch/PollSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,6 +26,7 @@
 
 import java.io.IOException;
 import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.ArrayDeque;
@@ -33,6 +34,7 @@
 import java.util.Deque;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 
 import jdk.internal.misc.Unsafe;
 
@@ -92,7 +94,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
 
         int to = (int) Math.min(timeout, Integer.MAX_VALUE); // max poll timeout
@@ -125,7 +129,7 @@
         }
 
         processDeregisterQueue();
-        return updateSelectedKeys();
+        return processEvents(action);
     }
 
     /**
@@ -157,13 +161,13 @@
     }
 
     /**
-     * Update the keys of file descriptors that were polled and add them to
-     * the selected-key set.
+     * Process the polled events.
      * If the interrupt fd has been selected, drain it and clear the interrupt.
      */
-    private int updateSelectedKeys() throws IOException {
+    private int processEvents(Consumer<SelectionKey> action)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
-        assert Thread.holdsLock(nioSelectedKeys());
         assert pollArraySize > 0 && pollArraySize == pollKeys.size();
 
         int numKeysUpdated = 0;
@@ -173,17 +177,7 @@
                 SelectionKeyImpl ski = pollKeys.get(i);
                 assert ski.getFDVal() == getDescriptor(i);
                 if (ski.isValid()) {
-                    if (selectedKeys.contains(ski)) {
-                        if (ski.translateAndUpdateReadyOps(rOps)) {
-                            numKeysUpdated++;
-                        }
-                    } else {
-                        ski.translateAndSetReadyOps(rOps);
-                        if ((ski.nioReadyOps() & ski.nioInterestOps()) != 0) {
-                            selectedKeys.add(ski);
-                            numKeysUpdated++;
-                        }
-                    }
+                    numKeysUpdated += processReadyEvents(rOps, ski, action);
                 }
             }
         }
--- a/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,6 +28,7 @@
 import java.io.IOException;
 import java.nio.channels.ClosedSelectorException;
 import java.nio.channels.Pipe;
+import java.nio.channels.SelectionKey;
 import java.nio.channels.Selector;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.ArrayDeque;
@@ -36,6 +37,7 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Consumer;
 
 /**
  * A multi-threaded implementation of Selector for Windows.
@@ -139,7 +141,9 @@
     }
 
     @Override
-    protected int doSelect(long timeout) throws IOException {
+    protected int doSelect(Consumer<SelectionKey> action, long timeout)
+        throws IOException
+    {
         assert Thread.holdsLock(this);
         this.timeout = timeout; // set selector timeout
         processUpdateQueue();
@@ -173,7 +177,7 @@
         // Done with poll(). Set wakeupSocket to nonsignaled  for the next run.
         finishLock.checkForException();
         processDeregisterQueue();
-        int updated = updateSelectedKeys();
+        int updated = updateSelectedKeys(action);
         // Done with poll(). Set wakeupSocket to nonsignaled  for the next run.
         resetWakeupSocket();
         return updated;
@@ -349,16 +353,16 @@
         private native int poll0(long pollAddress, int numfds,
              int[] readFds, int[] writeFds, int[] exceptFds, long timeout);
 
-        private int processSelectedKeys(long updateCount) {
+        private int processSelectedKeys(long updateCount, Consumer<SelectionKey> action) {
             int numKeysUpdated = 0;
-            numKeysUpdated += processFDSet(updateCount, readFds,
+            numKeysUpdated += processFDSet(updateCount, action, readFds,
                                            Net.POLLIN,
                                            false);
-            numKeysUpdated += processFDSet(updateCount, writeFds,
+            numKeysUpdated += processFDSet(updateCount, action, writeFds,
                                            Net.POLLCONN |
                                            Net.POLLOUT,
                                            false);
-            numKeysUpdated += processFDSet(updateCount, exceptFds,
+            numKeysUpdated += processFDSet(updateCount, action, exceptFds,
                                            Net.POLLIN |
                                            Net.POLLCONN |
                                            Net.POLLOUT,
@@ -372,7 +376,9 @@
          *
          * me.updateCount <= updateCount
          */
-        private int processFDSet(long updateCount, int[] fds, int rOps,
+        private int processFDSet(long updateCount,
+                                 Consumer<SelectionKey> action,
+                                 int[] fds, int rOps,
                                  boolean isExceptFds)
         {
             int numKeysUpdated = 0;
@@ -401,20 +407,10 @@
                     continue;
                 }
 
-                if (selectedKeys.contains(sk)) { // Key in selected set
-                    if (sk.translateAndUpdateReadyOps(rOps)) {
-                        if (me.updateCount != updateCount) {
-                            me.updateCount = updateCount;
-                            numKeysUpdated++;
-                        }
-                    }
-                } else { // Key is not in selected set yet
-                    sk.translateAndSetReadyOps(rOps);
-                    if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) {
-                        selectedKeys.add(sk);
-                        me.updateCount = updateCount;
-                        numKeysUpdated++;
-                    }
+                int updated = processReadyEvents(rOps, sk, action);
+                if (updated > 0 && me.updateCount != updateCount) {
+                    me.updateCount = updateCount;
+                    numKeysUpdated++;
                 }
             }
             return numKeysUpdated;
@@ -509,12 +505,12 @@
 
     // Update ops of the corresponding Channels. Add the ready keys to the
     // ready queue.
-    private int updateSelectedKeys() {
+    private int updateSelectedKeys(Consumer<SelectionKey> action) {
         updateCount++;
         int numKeysUpdated = 0;
-        numKeysUpdated += subSelector.processSelectedKeys(updateCount);
+        numKeysUpdated += subSelector.processSelectedKeys(updateCount, action);
         for (SelectThread t: threads) {
-            numKeysUpdated += t.subSelector.processSelectedKeys(updateCount);
+            numKeysUpdated += t.subSelector.processSelectedKeys(updateCount, action);
         }
         return numKeysUpdated;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Tue Jun 19 16:33:07 2018 +0100
@@ -30,9 +30,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
@@ -61,9 +59,8 @@
     /** The namespace for CONF file **/
     public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration";
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Init.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(Init.class);
 
     /** Field alreadyInitialized */
     private static boolean alreadyInitialized = false;
@@ -72,7 +69,7 @@
      * Method isInitialized
      * @return true if the library is already initialized.
      */
-    public static synchronized final boolean isInitialized() {
+    public static final synchronized boolean isInitialized() {
         return Init.alreadyInitialized;
     }
 
@@ -87,16 +84,16 @@
 
         InputStream is =
             AccessController.doPrivileged(
-                new PrivilegedAction<InputStream>() {
-                    public InputStream run() {
+                (PrivilegedAction<InputStream>)
+                    () -> {
                         String cfile =
                             System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
                         if (cfile == null) {
                             return null;
                         }
-                        return getClass().getResourceAsStream(cfile);
+                        return Init.class.getResourceAsStream(cfile);
                     }
-                });
+                );
         if (is == null) {
             dynamicInit();
         } else {
@@ -117,9 +114,8 @@
         //
         I18n.init("en", "US");
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Registering default algorithms");
-        }
+        LOG.debug("Registering default algorithms");
+
         try {
             AccessController.doPrivileged(new PrivilegedExceptionAction<Void>(){
                 @Override public Void run() throws XMLSecurityException {
@@ -160,10 +156,10 @@
 
                     return null;
                 }
-           });
+            });
         } catch (PrivilegedActionException ex) {
             XMLSecurityException xse = (XMLSecurityException)ex.getException();
-            log.log(java.util.logging.Level.SEVERE, xse.getMessage(), xse);
+            LOG.error(xse.getMessage(), xse);
             xse.printStackTrace();
         }
     }
@@ -174,13 +170,7 @@
     private static void fileInit(InputStream is) {
         try {
             /* read library configuration file */
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-
-            dbf.setNamespaceAware(true);
-            dbf.setValidating(false);
-
-            DocumentBuilder db = dbf.newDocumentBuilder();
+            DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
             Document doc = db.parse(is);
             Node config = doc.getFirstChild();
             for (; config != null; config = config.getNextSibling()) {
@@ -189,7 +179,7 @@
                 }
             }
             if (config == null) {
-                log.log(java.util.logging.Level.SEVERE, "Error in reading configuration file - Configuration element not found");
+                LOG.error("Error in reading configuration file - Configuration element not found");
                 return;
             }
             for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
@@ -197,11 +187,11 @@
                     continue;
                 }
                 String tag = el.getLocalName();
-                if (tag.equals("ResourceBundles")) {
+                if ("ResourceBundles".equals(tag)) {
                     Element resource = (Element)el;
                     /* configure internationalization */
-                    Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
-                    Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
+                    Attr langAttr = resource.getAttributeNodeNS(null, "defaultLanguageCode");
+                    Attr countryAttr = resource.getAttributeNodeNS(null, "defaultCountryCode");
                     String languageCode =
                         (langAttr == null) ? null : langAttr.getNodeValue();
                     String countryCode =
@@ -209,45 +199,41 @@
                     I18n.init(languageCode, countryCode);
                 }
 
-                if (tag.equals("CanonicalizationMethods")) {
+                if ("CanonicalizationMethods".equals(tag)) {
                     Element[] list =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");
 
-                    for (int i = 0; i < list.length; i++) {
-                        String uri = list[i].getAttributeNS(null, "URI");
+                    for (Element element : list) {
+                        String uri = element.getAttributeNS(null, "URI");
                         String javaClass =
-                            list[i].getAttributeNS(null, "JAVACLASS");
+                            element.getAttributeNS(null, "JAVACLASS");
                         try {
                             Canonicalizer.register(uri, javaClass);
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + uri + ", " + javaClass + ")");
-                            }
+                            LOG.debug("Canonicalizer.register({}, {})", uri, javaClass);
                         } catch (ClassNotFoundException e) {
                             Object exArgs[] = { uri, javaClass };
-                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                            LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                         }
                     }
                 }
 
-                if (tag.equals("TransformAlgorithms")) {
+                if ("TransformAlgorithms".equals(tag)) {
                     Element[] tranElem =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");
 
-                    for (int i = 0; i < tranElem.length; i++) {
-                        String uri = tranElem[i].getAttributeNS(null, "URI");
+                    for (Element element : tranElem) {
+                        String uri = element.getAttributeNS(null, "URI");
                         String javaClass =
-                            tranElem[i].getAttributeNS(null, "JAVACLASS");
+                            element.getAttributeNS(null, "JAVACLASS");
                         try {
                             Transform.register(uri, javaClass);
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Transform.register(" + uri + ", " + javaClass + ")");
-                            }
+                            LOG.debug("Transform.register({}, {})", uri, javaClass);
                         } catch (ClassNotFoundException e) {
                             Object exArgs[] = { uri, javaClass };
 
-                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                            LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                         } catch (NoClassDefFoundError ex) {
-                            log.log(java.util.logging.Level.WARNING, "Not able to found dependencies for algorithm, I'll keep working.");
+                            LOG.warn("Not able to found dependencies for algorithm, I'll keep working.");
                         }
                     }
                 }
@@ -257,64 +243,54 @@
                     if (algorithmsNode != null) {
                         Element[] algorithms =
                             XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm");
-                        for (int i = 0; i < algorithms.length; i++) {
-                            Element element = algorithms[i];
-                            String id = element.getAttribute("URI");
+                        for (Element element : algorithms) {
+                            String id = element.getAttributeNS(null, "URI");
                             JCEMapper.register(id, new JCEMapper.Algorithm(element));
                         }
                     }
                 }
 
-                if (tag.equals("SignatureAlgorithms")) {
+                if ("SignatureAlgorithms".equals(tag)) {
                     Element[] sigElems =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");
 
-                    for (int i = 0; i < sigElems.length; i++) {
-                        String uri = sigElems[i].getAttributeNS(null, "URI");
+                    for (Element sigElem : sigElems) {
+                        String uri = sigElem.getAttributeNS(null, "URI");
                         String javaClass =
-                            sigElems[i].getAttributeNS(null, "JAVACLASS");
+                            sigElem.getAttributeNS(null, "JAVACLASS");
 
                         /** $todo$ handle registering */
 
                         try {
                             SignatureAlgorithm.register(uri, javaClass);
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + uri + ", "
-                                          + javaClass + ")");
-                            }
+                            LOG.debug("SignatureAlgorithm.register({}, {})", uri, javaClass);
                         } catch (ClassNotFoundException e) {
                             Object exArgs[] = { uri, javaClass };
 
-                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                            LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
                         }
                     }
                 }
 
-                if (tag.equals("ResourceResolvers")) {
-                    Element[]resolverElem =
+                if ("ResourceResolvers".equals(tag)) {
+                    Element[] resolverElem =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
 
-                    for (int i = 0; i < resolverElem.length; i++) {
+                    for (Element element : resolverElem) {
                         String javaClass =
-                            resolverElem[i].getAttributeNS(null, "JAVACLASS");
+                            element.getAttributeNS(null, "JAVACLASS");
                         String description =
-                            resolverElem[i].getAttributeNS(null, "DESCRIPTION");
+                            element.getAttributeNS(null, "DESCRIPTION");
 
-                        if ((description != null) && (description.length() > 0)) {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
-                                          + description);
-                            }
+                        if (description != null && description.length() > 0) {
+                            LOG.debug("Register Resolver: {}: {}", javaClass, description);
                         } else {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
-                                          + ": For unknown purposes");
-                            }
+                            LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
                         }
                         try {
                             ResourceResolver.register(javaClass);
                         } catch (Throwable e) {
-                            log.log(java.util.logging.Level.WARNING,
+                            LOG.warn(
                                  "Cannot register:" + javaClass
                                  + " perhaps some needed jars are not installed",
                                  e
@@ -323,26 +299,20 @@
                     }
                 }
 
-                if (tag.equals("KeyResolver")){
+                if ("KeyResolver".equals(tag)){
                     Element[] resolverElem =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
-                    List<String> classNames = new ArrayList<String>(resolverElem.length);
-                    for (int i = 0; i < resolverElem.length; i++) {
+                    List<String> classNames = new ArrayList<>(resolverElem.length);
+                    for (Element element : resolverElem) {
                         String javaClass =
-                            resolverElem[i].getAttributeNS(null, "JAVACLASS");
+                            element.getAttributeNS(null, "JAVACLASS");
                         String description =
-                            resolverElem[i].getAttributeNS(null, "DESCRIPTION");
+                            element.getAttributeNS(null, "DESCRIPTION");
 
-                        if ((description != null) && (description.length() > 0)) {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
-                                          + description);
-                            }
+                        if (description != null && description.length() > 0) {
+                            LOG.debug("Register Resolver: {}: {}", javaClass, description);
                         } else {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
-                                          + ": For unknown purposes");
-                            }
+                            LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
                         }
                         classNames.add(javaClass);
                     }
@@ -350,27 +320,22 @@
                 }
 
 
-                if (tag.equals("PrefixMappings")){
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
-                    }
+                if ("PrefixMappings".equals(tag)){
+                    LOG.debug("Now I try to bind prefixes:");
 
                     Element[] nl =
                         XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");
 
-                    for (int i = 0; i < nl.length; i++) {
-                        String namespace = nl[i].getAttributeNS(null, "namespace");
-                        String prefix = nl[i].getAttributeNS(null, "prefix");
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
-                        }
+                    for (Element element : nl) {
+                        String namespace = element.getAttributeNS(null, "namespace");
+                        String prefix = element.getAttributeNS(null, "prefix");
+                        LOG.debug("Now I try to bind {} to {}", prefix, namespace);
                         ElementProxy.setDefaultPrefix(namespace, prefix);
                     }
                 }
             }
         } catch (Exception e) {
-            log.log(java.util.logging.Level.SEVERE, "Bad: ", e);
-            e.printStackTrace();
+            LOG.error("Bad: ", e);
         }
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java	Tue Jun 19 16:33:07 2018 +0100
@@ -40,7 +40,6 @@
      */
     public Algorithm(Document doc, String algorithmURI) {
         super(doc);
-
         this.setAlgorithmURI(algorithmURI);
     }
 
@@ -48,11 +47,11 @@
      * Constructor Algorithm
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public Algorithm(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public Algorithm(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -61,7 +60,7 @@
      * @return The URI of the algorithm
      */
     public String getAlgorithmURI() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        return getLocalAttribute(Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -71,9 +70,7 @@
      */
     protected void setAlgorithmURI(String algorithmURI) {
         if (algorithmURI != null) {
-            this.constructionElement.setAttributeNS(
-                null, Constants._ATT_ALGORITHM, algorithmURI
-            );
+            setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/ClassLoaderUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,211 +23,19 @@
 
 package com.sun.org.apache.xml.internal.security.algorithms;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-/**
- * This class is extremely useful for loading resources and classes in a fault
- * tolerant manner that works across different applications servers. Do not
- * touch this unless you're a grizzled classloading guru veteran who is going to
- * verify any change on 6 different application servers.
- */
 // NOTE! This is a duplicate of utils.ClassLoaderUtils with public
 // modifiers changed to package-private. Make sure to integrate any future
 // changes to utils.ClassLoaderUtils to this file.
 final class ClassLoaderUtils {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
 
     private ClassLoaderUtils() {
     }
 
     /**
-     * Load a given resource. <p/> This method will try to load the resource
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static URL getResource(String resourceName, Class<?> callingClass) {
-        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url =
-                Thread.currentThread().getContextClassLoader().getResource(
-                    resourceName.substring(1)
-                );
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (url == null) {
-            url = cluClassloader.getResource(resourceName);
-        }
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url = cluClassloader.getResource(resourceName.substring(1));
-        }
-
-        if (url == null) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                url = cl.getResource(resourceName);
-            }
-        }
-
-        if (url == null) {
-            url = callingClass.getResource(resourceName);
-        }
-
-        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResource('/' + resourceName, callingClass);
-        }
-
-        return url;
-    }
-
-    /**
-     * Load a given resources. <p/> This method will try to load the resources
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static List<URL> getResources(String resourceName, Class<?> callingClass) {
-        List<URL> ret = new ArrayList<URL>();
-        Enumeration<URL> urls = new Enumeration<URL>() {
-            public boolean hasMoreElements() {
-                return false;
-            }
-            public URL nextElement() {
-                return null;
-            }
-
-        };
-        try {
-            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            //ignore
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls =
-                    Thread.currentThread().getContextClassLoader().getResources(
-                        resourceName.substring(1)
-                    );
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (!urls.hasMoreElements()) {
-            try {
-                urls = cluClassloader.getResources(resourceName);
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls = cluClassloader.getResources(resourceName.substring(1));
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                try {
-                    urls = cl.getResources(resourceName);
-                } catch (IOException e) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                    }
-                    // ignore
-                }
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            URL url = callingClass.getResource(resourceName);
-            if (url != null) {
-                ret.add(url);
-            }
-        }
-        while (urls.hasMoreElements()) {
-            ret.add(urls.nextElement());
-        }
-
-
-        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResources('/' + resourceName, callingClass);
-        }
-        return ret;
-    }
-
-
-    /**
-     * This is a convenience method to load a resource as a stream. <p/> The
-     * algorithm used to find the resource is given in getResource()
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
-        URL url = getResource(resourceName, callingClass);
-
-        try {
-            return (url != null) ? url.openStream() : null;
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            return null;
-        }
-    }
-
-    /**
-     * Load a class with a given name. <p/> It will try to load the class in the
+     * Load a class with a given name. <p></p> It will try to load the class in the
      * following order:
      * <ul>
      * <li>From Thread.currentThread().getContextClassLoader()
@@ -249,9 +57,7 @@
                 return cl.loadClass(className);
             }
         } catch (ClassNotFoundException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
             //ignore
         }
         return loadClass2(className, callingClass);
@@ -271,9 +77,7 @@
                     return callingClass.getClassLoader().loadClass(className);
                 }
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             throw ex;
         }
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
-import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import org.w3c.dom.Element;
@@ -36,14 +35,13 @@
  */
 public class JCEMapper {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(JCEMapper.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(JCEMapper.class);
 
     private static Map<String, Algorithm> algorithmsMap =
         new ConcurrentHashMap<String, Algorithm>();
 
-    private static String providerName = null;
+    private static String providerName;
 
     /**
      * Method register
@@ -62,6 +60,7 @@
      * This method registers the default algorithms.
      */
     public static void registerDefaultAlgorithms() {
+        // Digest algorithms
         algorithmsMap.put(
             MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5,
             new Algorithm("", "MD5", "MessageDigest")
@@ -75,6 +74,10 @@
             new Algorithm("", "SHA-1", "MessageDigest")
         );
         algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA224,
+            new Algorithm("", "SHA-224", "MessageDigest")
+        );
+        algorithmsMap.put(
             MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256,
             new Algorithm("", "SHA-256", "MessageDigest")
         );
@@ -87,136 +90,149 @@
             new Algorithm("", "SHA-512", "MessageDigest")
         );
         algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_WHIRLPOOL,
+            new Algorithm("", "WHIRLPOOL", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_224,
+            new Algorithm("", "SHA3-224", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_256,
+            new Algorithm("", "SHA3-256", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_384,
+            new Algorithm("", "SHA3-384", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_512,
+            new Algorithm("", "SHA3-512", "MessageDigest")
+        );
+        // Signature algorithms
+        algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_DSA,
-            new Algorithm("", "SHA1withDSA", "Signature")
+            new Algorithm("DSA", "SHA1withDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256,
-            new Algorithm("", "SHA256withDSA", "Signature")
+            new Algorithm("DSA", "SHA256withDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
-            new Algorithm("", "MD5withRSA", "Signature")
+            new Algorithm("RSA", "MD5withRSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
-            new Algorithm("", "RIPEMD160withRSA", "Signature")
+            new Algorithm("RSA", "RIPEMD160withRSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
-            new Algorithm("", "SHA1withRSA", "Signature")
+            new Algorithm("RSA", "SHA1withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224,
+            new Algorithm("RSA", "SHA224withRSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
-            new Algorithm("", "SHA256withRSA", "Signature")
+            new Algorithm("RSA", "SHA256withRSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
-            new Algorithm("", "SHA384withRSA", "Signature")
+            new Algorithm("RSA", "SHA384withRSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
-            new Algorithm("", "SHA512withRSA", "Signature")
+            new Algorithm("RSA", "SHA512withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1,
+            new Algorithm("RSA", "SHA1withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1,
+            new Algorithm("RSA", "SHA224withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1,
+            new Algorithm("RSA", "SHA256withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1,
+            new Algorithm("RSA", "SHA384withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1,
+            new Algorithm("RSA", "SHA512withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1,
+             new Algorithm("RSA", "SHA3-224withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1,
+             new Algorithm("RSA", "SHA3-256withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1,
+             new Algorithm("RSA", "SHA3-384withRSAandMGF1", "Signature")
+        );
+        algorithmsMap.put(
+             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1,
+             new Algorithm("RSA", "SHA3-512withRSAandMGF1", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1,
-            new Algorithm("", "SHA1withECDSA", "Signature")
+            new Algorithm("EC", "SHA1withECDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224,
+            new Algorithm("EC", "SHA224withECDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256,
-            new Algorithm("", "SHA256withECDSA", "Signature")
+            new Algorithm("EC", "SHA256withECDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384,
-            new Algorithm("", "SHA384withECDSA", "Signature")
+            new Algorithm("EC", "SHA384withECDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512,
-            new Algorithm("", "SHA512withECDSA", "Signature")
+            new Algorithm("EC", "SHA512withECDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160,
+            new Algorithm("EC", "RIPEMD160withECDSA", "Signature")
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
-            new Algorithm("", "HmacMD5", "Mac")
+            new Algorithm("", "HmacMD5", "Mac", 0, 0)
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
-            new Algorithm("", "HMACRIPEMD160", "Mac")
+            new Algorithm("", "HMACRIPEMD160", "Mac", 0, 0)
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
-            new Algorithm("", "HmacSHA1", "Mac")
+            new Algorithm("", "HmacSHA1", "Mac", 0, 0)
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA224,
+            new Algorithm("", "HmacSHA224", "Mac", 0, 0)
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
-            new Algorithm("", "HmacSHA256", "Mac")
+            new Algorithm("", "HmacSHA256", "Mac", 0, 0)
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
-            new Algorithm("", "HmacSHA384", "Mac")
+            new Algorithm("", "HmacSHA384", "Mac", 0, 0)
         );
         algorithmsMap.put(
             XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
-            new Algorithm("", "HmacSHA512", "Mac")
-        );
-        algorithmsMap.put(
-            XMLCipher.TRIPLEDES,
-            new Algorithm("DESede", "DESede/CBC/ISO10126Padding", "BlockEncryption", 192)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_128,
-            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 128)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_192,
-            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 192)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_256,
-            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_128_GCM,
-            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 128)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_192_GCM,
-            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 192)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_256_GCM,
-            new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 256)
-        );
-        algorithmsMap.put(
-            XMLCipher.RSA_v1dot5,
-            new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
-        );
-        algorithmsMap.put(
-            XMLCipher.RSA_OAEP,
-            new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
-        );
-        algorithmsMap.put(
-            XMLCipher.RSA_OAEP_11,
-            new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
-        );
-        algorithmsMap.put(
-            XMLCipher.DIFFIE_HELLMAN,
-            new Algorithm("", "", "KeyAgreement")
-        );
-        algorithmsMap.put(
-            XMLCipher.TRIPLEDES_KeyWrap,
-            new Algorithm("DESede", "DESedeWrap", "SymmetricKeyWrap", 192)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_128_KeyWrap,
-            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 128)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_192_KeyWrap,
-            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 192)
-        );
-        algorithmsMap.put(
-            XMLCipher.AES_256_KeyWrap,
-            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 256)
+            new Algorithm("", "HmacSHA512", "Mac", 0, 0)
         );
     }
 
@@ -227,11 +243,7 @@
      * @return the JCE standard name corresponding to the given URI
      */
     public static String translateURItoJCEID(String algorithmURI) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
-        }
-
-        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        Algorithm algorithm = getAlgorithm(algorithmURI);
         if (algorithm != null) {
             return algorithm.jceName;
         }
@@ -244,11 +256,7 @@
      * @return the class name that implements this algorithm
      */
     public static String getAlgorithmClassFromURI(String algorithmURI) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
-        }
-
-        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        Algorithm algorithm = getAlgorithm(algorithmURI);
         if (algorithm != null) {
             return algorithm.algorithmClass;
         }
@@ -262,16 +270,21 @@
      * @return The length of the key used in the algorithm
      */
     public static int getKeyLengthFromURI(String algorithmURI) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
-        }
-        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        Algorithm algorithm = getAlgorithm(algorithmURI);
         if (algorithm != null) {
             return algorithm.keyLength;
         }
         return 0;
     }
 
+    public static int getIVLengthFromURI(String algorithmURI) {
+        Algorithm algorithm = getAlgorithm(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.ivLength;
+        }
+        return 0;
+    }
+
     /**
      * Method getJCEKeyAlgorithmFromURI
      *
@@ -279,12 +292,38 @@
      * @return The KeyAlgorithm for the given URI.
      */
     public static String getJCEKeyAlgorithmFromURI(String algorithmURI) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
+        Algorithm algorithm = getAlgorithm(algorithmURI);
+         if (algorithm != null) {
+             return algorithm.requiredKey;
+         }
+        return null;
+    }
+
+    /**
+     * Method getJCEProviderFromURI
+     *
+     * @param algorithmURI
+     * @return The JCEProvider for the given URI.
+     */
+    public static String getJCEProviderFromURI(String algorithmURI) {
+        Algorithm algorithm = getAlgorithm(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.jceProvider;
         }
-        Algorithm algorithm = algorithmsMap.get(algorithmURI);
-        if (algorithm != null) {
-            return algorithm.requiredKey;
+        return null;
+    }
+
+    /**
+     * Method getAlgorithm
+     *
+     * @param algorithmURI
+     * @return The Algorithm object for the given URI.
+     */
+    private static Algorithm getAlgorithm(String algorithmURI) {
+        LOG.debug("Request for URI {}", algorithmURI);
+
+        if (algorithmURI != null) {
+            return algorithmsMap.get(algorithmURI);
         }
         return null;
     }
@@ -301,7 +340,7 @@
      * Sets the default Provider for obtaining the security algorithms
      * @param provider the default providerId.
      * @throws SecurityException if a security manager is installed and the
-     *    caller does not have permission to set the JCE provider
+     *    caller does not have permission to register the JCE algorithm
      */
     public static void setProviderId(String provider) {
         JavaUtils.checkRegisterPermission();
@@ -317,40 +356,54 @@
         final String jceName;
         final String algorithmClass;
         final int keyLength;
+        final int ivLength;
+        final String jceProvider;
 
         /**
          * Gets data from element
          * @param el
          */
         public Algorithm(Element el) {
-            requiredKey = el.getAttribute("RequiredKey");
-            jceName = el.getAttribute("JCEName");
-            algorithmClass = el.getAttribute("AlgorithmClass");
+            requiredKey = el.getAttributeNS(null, "RequiredKey");
+            jceName = el.getAttributeNS(null, "JCEName");
+            algorithmClass = el.getAttributeNS(null, "AlgorithmClass");
+            jceProvider = el.getAttributeNS(null, "JCEProvider");
             if (el.hasAttribute("KeyLength")) {
-                keyLength = Integer.parseInt(el.getAttribute("KeyLength"));
+                keyLength = Integer.parseInt(el.getAttributeNS(null, "KeyLength"));
             } else {
                 keyLength = 0;
             }
+            if (el.hasAttribute("IVLength")) {
+                ivLength = Integer.parseInt(el.getAttributeNS(null, "IVLength"));
+            } else {
+                ivLength = 0;
+            }
         }
 
         public Algorithm(String requiredKey, String jceName) {
-            this(requiredKey, jceName, null, 0);
+            this(requiredKey, jceName, null, 0, 0);
         }
 
         public Algorithm(String requiredKey, String jceName, String algorithmClass) {
-            this(requiredKey, jceName, algorithmClass, 0);
+            this(requiredKey, jceName, algorithmClass, 0, 0);
         }
 
         public Algorithm(String requiredKey, String jceName, int keyLength) {
-            this(requiredKey, jceName, null, keyLength);
+            this(requiredKey, jceName, null, keyLength, 0);
         }
 
-        public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength) {
+        public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength, int ivLength) {
+            this(requiredKey, jceName, algorithmClass, keyLength, ivLength, null);
+        }
+
+        public Algorithm(String requiredKey, String jceName,
+                         String algorithmClass, int keyLength, int ivLength, String jceProvider) {
             this.requiredKey = requiredKey;
             this.jceName = jceName;
             this.algorithmClass = algorithmClass;
             this.keyLength = keyLength;
+            this.ivLength = ivLength;
+            this.jceProvider = jceProvider;
         }
     }
-
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,7 +31,7 @@
 import org.w3c.dom.Document;
 
 /**
- * Digest Message wrapper & selector class.
+ * Digest Message wrapper and selector class.
  *
  * <pre>
  * MessageDigestAlgorithm.getInstance()
@@ -44,6 +44,9 @@
         Constants.MoreAlgorithmsSpecNS + "md5";
     /** Digest - Required SHA1*/
     public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
+    /** Message Digest - OPTIONAL SHA224*/
+    public static final String ALGO_ID_DIGEST_SHA224 =
+        Constants.MoreAlgorithmsSpecNS + "sha224";
     /** Message Digest - RECOMMENDED SHA256*/
     public static final String ALGO_ID_DIGEST_SHA256 =
         EncryptionConstants.EncryptionSpecNS + "sha256";
@@ -57,6 +60,18 @@
     public static final String ALGO_ID_DIGEST_RIPEMD160 =
         EncryptionConstants.EncryptionSpecNS + "ripemd160";
 
+    // Newer digest algorithms...all optional
+    public static final String ALGO_ID_DIGEST_WHIRLPOOL =
+        Constants.XML_DSIG_NS_MORE_07_05 + "whirlpool";
+    public static final String ALGO_ID_DIGEST_SHA3_224 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-224";
+    public static final String ALGO_ID_DIGEST_SHA3_256 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-256";
+    public static final String ALGO_ID_DIGEST_SHA3_384 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-384";
+    public static final String ALGO_ID_DIGEST_SHA3_512 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-512";
+
     /** Field algorithm stores the actual {@link java.security.MessageDigest} */
     private final MessageDigest algorithm;
 
@@ -121,7 +136,7 @@
      *
      * @return the actual {@link java.security.MessageDigest} algorithm object
      */
-    public java.security.MessageDigest getAlgorithm() {
+    public MessageDigest getAlgorithm() {
         return algorithm;
     }
 
@@ -134,7 +149,7 @@
      * @return the result of the {@link java.security.MessageDigest#isEqual} method
      */
     public static boolean isEqual(byte[] digesta, byte[] digestb) {
-        return java.security.MessageDigest.isEqual(digesta, digestb);
+        return MessageDigest.isEqual(digesta, digestb);
     }
 
     /**
@@ -243,12 +258,12 @@
         algorithm.update(buf, offset, len);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseNamespace() {
         return Constants.SignatureSpecNS;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_DIGESTMETHOD;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Tue Jun 19 16:33:07 2018 +0100
@@ -46,13 +46,11 @@
  * Allows selection of digital signature's algorithm, private keys, other
  * security parameters, and algorithm's ID.
  *
- * @author Christian Geuer-Pollmann
  */
 public class SignatureAlgorithm extends Algorithm {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureAlgorithm.class);
 
     /** All available algorithm classes are registered here */
     private static Map<String, Class<? extends SignatureAlgorithmSpi>> algorithmHash =
@@ -75,7 +73,7 @@
         this.algorithmURI = algorithmURI;
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(getElement());
     }
 
     /**
@@ -93,10 +91,10 @@
         this.algorithmURI = algorithmURI;
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(getElement());
 
         signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
-        ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement);
+        ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(getElement());
     }
 
     /**
@@ -107,7 +105,7 @@
      * @throws XMLSecurityException
      */
     public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException {
-        this(element, baseURI, false);
+        this(element, baseURI, true);
     }
 
     /**
@@ -137,7 +135,7 @@
         }
 
         signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
-        signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
+        signatureAlgorithm.engineGetContextFromElement(getElement());
     }
 
     /**
@@ -148,22 +146,17 @@
         try {
             Class<? extends SignatureAlgorithmSpi> implementingClass =
                 algorithmHash.get(algorithmURI);
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
-                   + implementingClass + "\"");
+            LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, implementingClass);
+            if (implementingClass == null) {
+                Object exArgs[] = { algorithmURI };
+                throw new XMLSignatureException("algorithms.NoSuchAlgorithmNoEx", exArgs);
             }
             @SuppressWarnings("deprecation")
-            SignatureAlgorithmSpi result = implementingClass.newInstance();
-            return result;
-        }  catch (IllegalAccessException ex) {
+            SignatureAlgorithmSpi tmp = implementingClass.newInstance();
+            return tmp;
+        }  catch (IllegalAccessException | InstantiationException | NullPointerException ex) {
             Object exArgs[] = { algorithmURI, ex.getMessage() };
-            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
-        } catch (InstantiationException ex) {
-            Object exArgs[] = { algorithmURI, ex.getMessage() };
-            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
-        } catch (NullPointerException ex) {
-            Object exArgs[] = { algorithmURI, ex.getMessage() };
-            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+            throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs);
         }
     }
 
@@ -313,14 +306,14 @@
      * @return the URI representation of Transformation algorithm
      */
     public final String getURI() {
-        return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        return getLocalAttribute(Constants._ATT_ALGORITHM);
     }
 
     /**
      * Registers implementing class of the SignatureAlgorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
-     * @param implementingClass <code>implementingClass</code> the implementing class of
+     * @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}.
+     * @param implementingClass {@code implementingClass} the implementing class of
      * {@link SignatureAlgorithmSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
      * @throws XMLSignatureException
@@ -332,9 +325,7 @@
        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
            XMLSignatureException {
         JavaUtils.checkRegisterPermission();
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
-        }
+        LOG.debug("Try to register {} {}", algorithmURI, implementingClass);
 
         // are we already registered?
         Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
@@ -351,15 +342,15 @@
             algorithmHash.put(algorithmURI, clazz);
         } catch (NullPointerException ex) {
             Object exArgs[] = { algorithmURI, ex.getMessage() };
-            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+            throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs);
         }
     }
 
     /**
-     * Registers implementing class of the Transform algorithm with algorithmURI
+     * Registers implementing class of the SignatureAlgorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
-     * @param implementingClass <code>implementingClass</code> the implementing class of
+     * @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}.
+     * @param implementingClass {@code implementingClass} the implementing class of
      * {@link SignatureAlgorithmSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
      * @throws XMLSignatureException
@@ -370,9 +361,7 @@
        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
            XMLSignatureException {
         JavaUtils.checkRegisterPermission();
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
-        }
+        LOG.debug("Try to register {} {}", algorithmURI, implementingClass);
 
         // are we already registered?
         Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
@@ -410,6 +399,9 @@
             SignatureBaseRSA.SignatureRSARIPEMD160.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224, SignatureBaseRSA.SignatureRSASHA224.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, SignatureBaseRSA.SignatureRSASHA256.class
         );
         algorithmHash.put(
@@ -419,9 +411,39 @@
             XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, SignatureBaseRSA.SignatureRSASHA512.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1, SignatureBaseRSA.SignatureRSASHA1MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1, SignatureBaseRSA.SignatureRSASHA224MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1, SignatureBaseRSA.SignatureRSASHA256MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1, SignatureBaseRSA.SignatureRSASHA384MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1, SignatureBaseRSA.SignatureRSASHA512MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1, SignatureBaseRSA.SignatureRSASHA3_224MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1, SignatureBaseRSA.SignatureRSASHA3_256MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1, SignatureBaseRSA.SignatureRSASHA3_384MGF1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1, SignatureBaseRSA.SignatureRSASHA3_512MGF1.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224, SignatureECDSA.SignatureECDSASHA224.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class
         );
         algorithmHash.put(
@@ -431,12 +453,18 @@
             XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160, SignatureECDSA.SignatureECDSARIPEMD160.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
         );
         algorithmHash.put(
             XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, IntegrityHmac.IntegrityHmacRIPEMD160.class
         );
         algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA224, IntegrityHmac.IntegrityHmacSHA224.class
+        );
+        algorithmHash.put(
             XMLSignature.ALGO_ID_MAC_HMAC_SHA256, IntegrityHmac.IntegrityHmacSHA256.class
         );
         algorithmHash.put(
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,9 +32,9 @@
 public abstract class SignatureAlgorithmSpi {
 
     /**
-     * Returns the URI representation of <code>Transformation algorithm</code>
+     * Returns the URI representation of {@code Transformation algorithm}
      *
-     * @return the URI representation of <code>Transformation algorithm</code>
+     * @return the URI representation of {@code Transformation algorithm}
      */
     protected abstract String engineGetURI();
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,918 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.algorithms.implementations;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public final class ECDSAUtils {
+
+    private ECDSAUtils() {
+        // complete
+    }
+
+    /**
+     * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
+     * <p></p>
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param asn1Bytes
+     * @return the decode bytes
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+     */
+    public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
+
+        if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
+        int offset;
+        if (asn1Bytes[1] > 0) {
+            offset = 2;
+        } else if (asn1Bytes[1] == (byte) 0x81) {
+            offset = 3;
+        } else {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
+
+        byte rLength = asn1Bytes[offset + 1];
+        int i;
+
+        for (i = rLength; i > 0 && asn1Bytes[offset + 2 + rLength - i] == 0; i--); //NOPMD
+
+        byte sLength = asn1Bytes[offset + 2 + rLength + 1];
+        int j;
+
+        for (j = sLength; j > 0 && asn1Bytes[offset + 2 + rLength + 2 + sLength - j] == 0; j--); //NOPMD
+
+        int rawLen = Math.max(i, j);
+
+        if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset
+                || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
+                || asn1Bytes[offset] != 2
+                || asn1Bytes[offset + 2 + rLength] != 2) {
+            throw new IOException("Invalid ASN.1 format of ECDSA signature");
+        }
+        byte xmldsigBytes[] = new byte[2 * rawLen];
+
+        System.arraycopy(asn1Bytes, offset + 2 + rLength - i, xmldsigBytes, rawLen - i, i);
+        System.arraycopy(asn1Bytes, offset + 2 + rLength + 2 + sLength - j, xmldsigBytes,
+                2 * rawLen - j, j);
+
+        return xmldsigBytes;
+    }
+
+    /**
+     * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
+     * <p></p>
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
+     * pairs; the XML Signature requires the core BigInteger values.
+     *
+     * @param xmldsigBytes
+     * @return the encoded ASN.1 bytes
+     * @throws IOException
+     * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+     * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+     */
+    public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
+
+        int rawLen = xmldsigBytes.length / 2;
+
+        int i;
+
+        for (i = rawLen; i > 0 && xmldsigBytes[rawLen - i] == 0; i--); //NOPMD
+
+        int j = i;
+
+        if (xmldsigBytes[rawLen - i] < 0) {
+            j += 1;
+        }
+
+        int k;
+
+        for (k = rawLen; k > 0 && xmldsigBytes[2 * rawLen - k] == 0; k--); //NOPMD
+
+        int l = k;
+
+        if (xmldsigBytes[2 * rawLen - k] < 0) {
+            l += 1;
+        }
+
+        int len = 2 + j + 2 + l;
+        if (len > 255) {
+            throw new IOException("Invalid XMLDSIG format of ECDSA signature");
+        }
+        int offset;
+        byte asn1Bytes[];
+        if (len < 128) {
+            asn1Bytes = new byte[2 + 2 + j + 2 + l];
+            offset = 1;
+        } else {
+            asn1Bytes = new byte[3 + 2 + j + 2 + l];
+            asn1Bytes[1] = (byte) 0x81;
+            offset = 2;
+        }
+        asn1Bytes[0] = 48;
+        asn1Bytes[offset++] = (byte) len;
+        asn1Bytes[offset++] = 2;
+        asn1Bytes[offset++] = (byte) j;
+
+        System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, offset + j - i, i);
+
+        offset += j;
+
+        asn1Bytes[offset++] = 2;
+        asn1Bytes[offset++] = (byte) l;
+
+        System.arraycopy(xmldsigBytes, 2 * rawLen - k, asn1Bytes, offset + l - k, k);
+
+        return asn1Bytes;
+    }
+
+    private static final List<ECCurveDefinition> ecCurveDefinitions = new ArrayList<>();
+
+    static {
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp112r1",
+                        "1.3.132.0.6",
+                        "db7c2abf62e35e668076bead208b",
+                        "db7c2abf62e35e668076bead2088",
+                        "659ef8ba043916eede8911702b22",
+                        "09487239995a5ee76b55f9c2f098",
+                        "a89ce5af8724c0a23e0e0ff77500",
+                        "db7c2abf62e35e7628dfac6561c5",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp112r2",
+                        "1.3.132.0.7",
+                        "db7c2abf62e35e668076bead208b",
+                        "6127c24c05f38a0aaaf65c0ef02c",
+                        "51def1815db5ed74fcc34c85d709",
+                        "4ba30ab5e892b4e1649dd0928643",
+                        "adcd46f5882e3747def36e956e97",
+                        "36df0aafd8b8d7597ca10520d04b",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp128r1",
+                        "1.3.132.0.28",
+                        "fffffffdffffffffffffffffffffffff",
+                        "fffffffdfffffffffffffffffffffffc",
+                        "e87579c11079f43dd824993c2cee5ed3",
+                        "161ff7528b899b2d0c28607ca52c5b86",
+                        "cf5ac8395bafeb13c02da292dded7a83",
+                        "fffffffe0000000075a30d1b9038a115",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp128r2",
+                        "1.3.132.0.29",
+                        "fffffffdffffffffffffffffffffffff",
+                        "d6031998d1b3bbfebf59cc9bbff9aee1",
+                        "5eeefca380d02919dc2c6558bb6d8a5d",
+                        "7b6aa5d85e572983e6fb32a7cdebc140",
+                        "27b6916a894d3aee7106fe805fc34b44",
+                        "3fffffff7fffffffbe0024720613b5a3",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp160k1",
+                        "1.3.132.0.9",
+                        "fffffffffffffffffffffffffffffffeffffac73",
+                        "0000000000000000000000000000000000000000",
+                        "0000000000000000000000000000000000000007",
+                        "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
+                        "938cf935318fdced6bc28286531733c3f03c4fee",
+                        "0100000000000000000001b8fa16dfab9aca16b6b3",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp160r1",
+                        "1.3.132.0.8",
+                        "ffffffffffffffffffffffffffffffff7fffffff",
+                        "ffffffffffffffffffffffffffffffff7ffffffc",
+                        "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
+                        "4a96b5688ef573284664698968c38bb913cbfc82",
+                        "23a628553168947d59dcc912042351377ac5fb32",
+                        "0100000000000000000001f4c8f927aed3ca752257",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp160r2",
+                        "1.3.132.0.30",
+                        "fffffffffffffffffffffffffffffffeffffac73",
+                        "fffffffffffffffffffffffffffffffeffffac70",
+                        "b4e134d3fb59eb8bab57274904664d5af50388ba",
+                        "52dcb034293a117e1f4ff11b30f7199d3144ce6d",
+                        "feaffef2e331f296e071fa0df9982cfea7d43f2e",
+                        "0100000000000000000000351ee786a818f3a1a16b",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp192k1",
+                        "1.3.132.0.31",
+                        "fffffffffffffffffffffffffffffffffffffffeffffee37",
+                        "000000000000000000000000000000000000000000000000",
+                        "000000000000000000000000000000000000000000000003",
+                        "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
+                        "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d",
+                        "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp192r1 [NIST P-192, X9.62 prime192v1]",
+                        "1.2.840.10045.3.1.1",
+                        "fffffffffffffffffffffffffffffffeffffffffffffffff",
+                        "fffffffffffffffffffffffffffffffefffffffffffffffc",
+                        "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
+                        "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
+                        "07192b95ffc8da78631011ed6b24cdd573f977a11e794811",
+                        "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp224k1",
+                        "1.3.132.0.32",
+                        "fffffffffffffffffffffffffffffffffffffffffffffffeffffe56d",
+                        "00000000000000000000000000000000000000000000000000000000",
+                        "00000000000000000000000000000000000000000000000000000005",
+                        "a1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c",
+                        "7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5",
+                        "010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp224r1 [NIST P-224]",
+                        "1.3.132.0.33",
+                        "ffffffffffffffffffffffffffffffff000000000000000000000001",
+                        "fffffffffffffffffffffffffffffffefffffffffffffffffffffffe",
+                        "b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4",
+                        "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21",
+                        "bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34",
+                        "ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp256k1",
+                        "1.3.132.0.10",
+                        "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
+                        "0000000000000000000000000000000000000000000000000000000000000000",
+                        "0000000000000000000000000000000000000000000000000000000000000007",
+                        "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
+                        "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
+                        "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp256r1 [NIST P-256, X9.62 prime256v1]",
+                        "1.2.840.10045.3.1.7",
+                        "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
+                        "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
+                        "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
+                        "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
+                        "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5",
+                        "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp384r1 [NIST P-384]",
+                        "1.3.132.0.34",
+                        "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
+                        "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc",
+                        "b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef",
+                        "aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
+                        "3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",
+                        "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "secp521r1 [NIST P-521]",
+                        "1.3.132.0.35",
+                        "01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+                        "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc",
+                        "0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00",
+                        "00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66",
+                        "011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",
+                        "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 prime192v2",
+                        "1.2.840.10045.3.1.2",
+                        "fffffffffffffffffffffffffffffffeffffffffffffffff",
+                        "fffffffffffffffffffffffffffffffefffffffffffffffc",
+                        "cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953",
+                        "eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a",
+                        "6574d11d69b6ec7a672bb82a083df2f2b0847de970b2de15",
+                        "fffffffffffffffffffffffe5fb1a724dc80418648d8dd31",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 prime192v3",
+                        "1.2.840.10045.3.1.3",
+                        "fffffffffffffffffffffffffffffffeffffffffffffffff",
+                        "fffffffffffffffffffffffffffffffefffffffffffffffc",
+                        "22123dc2395a05caa7423daeccc94760a7d462256bd56916",
+                        "7d29778100c65a1da1783716588dce2b8b4aee8e228f1896",
+                        "38a90f22637337334b49dcb66a6dc8f9978aca7648a943b0",
+                        "ffffffffffffffffffffffff7a62d031c83f4294f640ec13",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 prime239v1",
+                        "1.2.840.10045.3.1.4",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
+                        "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a",
+                        "0ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf",
+                        "7debe8e4e90a5dae6e4054ca530ba04654b36818ce226b39fccb7b02f1ae",
+                        "7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 prime239v2",
+                        "1.2.840.10045.3.1.5",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
+                        "617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c",
+                        "38af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7",
+                        "5b0125e4dbea0ec7206da0fc01d9b081329fb555de6ef460237dff8be4ba",
+                        "7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 prime239v3",
+                        "1.2.840.10045.3.1.6",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
+                        "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
+                        "255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e",
+                        "6768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a",
+                        "1607e6898f390c06bc1d552bad226f3b6fcfe48b6e818499af18e3ed6cf3",
+                        "7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551",
+                        1)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect113r1",
+                        "1.3.132.0.4",
+                        "020000000000000000000000000201",
+                        "003088250ca6e7c7fe649ce85820f7",
+                        "00e8bee4d3e2260744188be0e9c723",
+                        "009d73616f35f4ab1407d73562c10f",
+                        "00a52830277958ee84d1315ed31886",
+                        "0100000000000000d9ccec8a39e56f",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect113r2",
+                        "1.3.132.0.5",
+                        "020000000000000000000000000201",
+                        "00689918dbec7e5a0dd6dfc0aa55c7",
+                        "0095e9a9ec9b297bd4bf36e059184f",
+                        "01a57a6a7b26ca5ef52fcdb8164797",
+                        "00b3adc94ed1fe674c06e695baba1d",
+                        "010000000000000108789b2496af93",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect131r1",
+                        "1.3.132.0.22",
+                        "080000000000000000000000000000010d",
+                        "07a11b09a76b562144418ff3ff8c2570b8",
+                        "0217c05610884b63b9c6c7291678f9d341",
+                        "0081baf91fdf9833c40f9c181343638399",
+                        "078c6e7ea38c001f73c8134b1b4ef9e150",
+                        "0400000000000000023123953a9464b54d",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect131r2",
+                        "1.3.132.0.23",
+                        "080000000000000000000000000000010d",
+                        "03e5a88919d7cafcbf415f07c2176573b2",
+                        "04b8266a46c55657ac734ce38f018f2192",
+                        "0356dcd8f2f95031ad652d23951bb366a8",
+                        "0648f06d867940a5366d9e265de9eb240f",
+                        "0400000000000000016954a233049ba98f",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect163k1 [NIST K-163]",
+                        "1.3.132.0.1",
+                        "0800000000000000000000000000000000000000c9",
+                        "000000000000000000000000000000000000000001",
+                        "000000000000000000000000000000000000000001",
+                        "02fe13c0537bbc11acaa07d793de4e6d5e5c94eee8",
+                        "0289070fb05d38ff58321f2e800536d538ccdaa3d9",
+                        "04000000000000000000020108a2e0cc0d99f8a5ef",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect163r1",
+                        "1.3.132.0.2",
+                        "0800000000000000000000000000000000000000c9",
+                        "07b6882caaefa84f9554ff8428bd88e246d2782ae2",
+                        "0713612dcddcb40aab946bda29ca91f73af958afd9",
+                        "0369979697ab43897789566789567f787a7876a654",
+                        "00435edb42efafb2989d51fefce3c80988f41ff883",
+                        "03ffffffffffffffffffff48aab689c29ca710279b",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect163r2 [NIST B-163]",
+                        "1.3.132.0.15",
+                        "0800000000000000000000000000000000000000c9",
+                        "000000000000000000000000000000000000000001",
+                        "020a601907b8c953ca1481eb10512f78744a3205fd",
+                        "03f0eba16286a2d57ea0991168d4994637e8343e36",
+                        "00d51fbc6c71a0094fa2cdd545b11c5c0c797324f1",
+                        "040000000000000000000292fe77e70c12a4234c33",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect193r1",
+                        "1.3.132.0.24",
+                        "02000000000000000000000000000000000000000000008001",
+                        "0017858feb7a98975169e171f77b4087de098ac8a911df7b01",
+                        "00fdfb49bfe6c3a89facadaa7a1e5bbc7cc1c2e5d831478814",
+                        "01f481bc5f0ff84a74ad6cdf6fdef4bf6179625372d8c0c5e1",
+                        "0025e399f2903712ccf3ea9e3a1ad17fb0b3201b6af7ce1b05",
+                        "01000000000000000000000000c7f34a778f443acc920eba49",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect193r2",
+                        "1.3.132.0.25",
+                        "02000000000000000000000000000000000000000000008001",
+                        "0163f35a5137c2ce3ea6ed8667190b0bc43ecd69977702709b",
+                        "00c9bb9e8927d4d64c377e2ab2856a5b16e3efb7f61d4316ae",
+                        "00d9b67d192e0367c803f39e1a7e82ca14a651350aae617e8f",
+                        "01ce94335607c304ac29e7defbd9ca01f596f927224cdecf6c",
+                        "010000000000000000000000015aab561b005413ccd4ee99d5",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect233k1 [NIST K-233]",
+                        "1.3.132.0.26",
+                        "020000000000000000000000000000000000000004000000000000000001",
+                        "000000000000000000000000000000000000000000000000000000000000",
+                        "000000000000000000000000000000000000000000000000000000000001",
+                        "017232ba853a7e731af129f22ff4149563a419c26bf50a4c9d6eefad6126",
+                        "01db537dece819b7f70f555a67c427a8cd9bf18aeb9b56e0c11056fae6a3",
+                        "008000000000000000000000000000069d5bb915bcd46efb1ad5f173abdf",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect233r1 [NIST B-233]",
+                        "1.3.132.0.27",
+                        "020000000000000000000000000000000000000004000000000000000001",
+                        "000000000000000000000000000000000000000000000000000000000001",
+                        "0066647ede6c332c7f8c0923bb58213b333b20e9ce4281fe115f7d8f90ad",
+                        "00fac9dfcbac8313bb2139f1bb755fef65bc391f8b36f8f8eb7371fd558b",
+                        "01006a08a41903350678e58528bebf8a0beff867a7ca36716f7e01f81052",
+                        "01000000000000000000000000000013e974e72f8a6922031d2603cfe0d7",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect239k1",
+                        "1.3.132.0.3",
+                        "800000000000000000004000000000000000000000000000000000000001",
+                        "000000000000000000000000000000000000000000000000000000000000",
+                        "000000000000000000000000000000000000000000000000000000000001",
+                        "29a0b6a887a983e9730988a68727a8b2d126c44cc2cc7b2a6555193035dc",
+                        "76310804f12e549bdb011c103089e73510acb275fc312a5dc6b76553f0ca",
+                        "2000000000000000000000000000005a79fec67cb6e91f1c1da800e478a5",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect283k1 [NIST K-283]",
+                        "1.3.132.0.16",
+                        "0800000000000000000000000000000000000000000000000000000000000000000010a1",
+                        "000000000000000000000000000000000000000000000000000000000000000000000000",
+                        "000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "0503213f78ca44883f1a3b8162f188e553cd265f23c1567a16876913b0c2ac2458492836",
+                        "01ccda380f1c9e318d90f95d07e5426fe87e45c0e8184698e45962364e34116177dd2259",
+                        "01ffffffffffffffffffffffffffffffffffe9ae2ed07577265dff7f94451e061e163c61",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect283r1 [NIST B-283]",
+                        "1.3.132.0.17",
+                        "0800000000000000000000000000000000000000000000000000000000000000000010a1",
+                        "000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "027b680ac8b8596da5a4af8a19a0303fca97fd7645309fa2a581485af6263e313b79a2f5",
+                        "05f939258db7dd90e1934f8c70b0dfec2eed25b8557eac9c80e2e198f8cdbecd86b12053",
+                        "03676854fe24141cb98fe6d4b20d02b4516ff702350eddb0826779c813f0df45be8112f4",
+                        "03ffffffffffffffffffffffffffffffffffef90399660fc938a90165b042a7cefadb307",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect409k1 [NIST K-409]",
+                        "1.3.132.0.36",
+                        "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
+                        "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+                        "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "0060f05f658f49c1ad3ab1890f7184210efd0987e307c84c27accfb8f9f67cc2c460189eb5aaaa62ee222eb1b35540cfe9023746",
+                        "01e369050b7c4e42acba1dacbf04299c3460782f918ea427e6325165e9ea10e3da5f6c42e9c55215aa9ca27a5863ec48d8e0286b",
+                        "007ffffffffffffffffffffffffffffffffffffffffffffffffffe5f83b2d4ea20400ec4557d5ed3e3e7ca5b4b5c83b8e01e5fcf",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect409r1 [NIST B-409]",
+                        "1.3.132.0.37",
+                        "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
+                        "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "0021a5c2c8ee9feb5c4b9a753b7b476b7fd6422ef1f3dd674761fa99d6ac27c8a9a197b272822f6cd57a55aa4f50ae317b13545f",
+                        "015d4860d088ddb3496b0c6064756260441cde4af1771d4db01ffe5b34e59703dc255a868a1180515603aeab60794e54bb7996a7",
+                        "0061b1cfab6be5f32bbfa78324ed106a7636b9c5a7bd198d0158aa4f5488d08f38514f1fdf4b4f40d2181b3681c364ba0273c706",
+                        "010000000000000000000000000000000000000000000000000001e2aad6a612f33307be5fa47c3c9e052f838164cd37d9a21173",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect571k1 [NIST K-571]",
+                        "1.3.132.0.38",
+                        "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
+                        "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+                        "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "026eb7a859923fbc82189631f8103fe4ac9ca2970012d5d46024804801841ca44370958493b205e647da304db4ceb08cbbd1ba39494776fb988b47174dca88c7e2945283a01c8972",
+                        "0349dc807f4fbf374f4aeade3bca95314dd58cec9f307a54ffc61efc006d8a2c9d4979c0ac44aea74fbebbb9f772aedcb620b01a7ba7af1b320430c8591984f601cd4c143ef1c7a3",
+                        "020000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "sect571r1 [NIST B-571]",
+                        "1.3.132.0.39",
+                        "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
+                        "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
+                        "02f40e7e2221f295de297117b7f3d62f5c6a97ffcb8ceff1cd6ba8ce4a9a18ad84ffabbd8efa59332be7ad6756a66e294afd185a78ff12aa520e4de739baca0c7ffeff7f2955727a",
+                        "0303001d34b856296c16c0d40d3cd7750a93d1d2955fa80aa5f40fc8db7b2abdbde53950f4c0d293cdd711a35b67fb1499ae60038614f1394abfa3b4c850d927e1e7769c8eec2d19",
+                        "037bf27342da639b6dccfffeb73d69d78c6c27a6009cbbca1980f8533921e8a684423e43bab08a576291af8f461bb2a8b3531d2f0485c19b16e2f1516e23dd3c1a4827af1b8ac15b",
+                        "03ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe661ce18ff55987308059b186823851ec7dd9ca1161de93d5174d66e8382e9bb2fe84e47",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb191v1",
+                        "1.2.840.10045.3.0.5",
+                        "800000000000000000000000000000000000000000000201",
+                        "2866537b676752636a68f56554e12640276b649ef7526267",
+                        "2e45ef571f00786f67b0081b9495a3d95462f5de0aa185ec",
+                        "36b3daf8a23206f9c4f299d7b21a9c369137f2c84ae1aa0d",
+                        "765be73433b3f95e332932e70ea245ca2418ea0ef98018fb",
+                        "40000000000000000000000004a20e90c39067c893bbb9a5",
+                        2)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb191v2",
+                        "1.2.840.10045.3.0.6",
+                        "800000000000000000000000000000000000000000000201",
+                        "401028774d7777c7b7666d1366ea432071274f89ff01e718",
+                        "0620048d28bcbd03b6249c99182b7c8cd19700c362c46a01",
+                        "3809b2b7cc1b28cc5a87926aad83fd28789e81e2c9e3bf10",
+                        "17434386626d14f3dbf01760d9213a3e1cf37aec437d668a",
+                        "20000000000000000000000050508cb89f652824e06b8173",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb191v3",
+                        "1.2.840.10045.3.0.7",
+                        "800000000000000000000000000000000000000000000201",
+                        "6c01074756099122221056911c77d77e77a777e7e7e77fcb",
+                        "71fe1af926cf847989efef8db459f66394d90f32ad3f15e8",
+                        "375d4ce24fde434489de8746e71786015009e66e38a926dd",
+                        "545a39176196575d985999366e6ad34ce0a77cd7127b06be",
+                        "155555555555555555555555610c0b196812bfb6288a3ea3",
+                        6)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb239v1",
+                        "1.2.840.10045.3.0.11",
+                        "800000000000000000000000000000000000000000000000001000000001",
+                        "32010857077c5431123a46b808906756f543423e8d27877578125778ac76",
+                        "790408f2eedaf392b012edefb3392f30f4327c0ca3f31fc383c422aa8c16",
+                        "57927098fa932e7c0a96d3fd5b706ef7e5f5c156e16b7e7c86038552e91d",
+                        "61d8ee5077c33fecf6f1a16b268de469c3c7744ea9a971649fc7a9616305",
+                        "2000000000000000000000000000000f4d42ffe1492a4993f1cad666e447",
+                        4)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb239v2",
+                        "1.2.840.10045.3.0.12",
+                        "800000000000000000000000000000000000000000000000001000000001",
+                        "4230017757a767fae42398569b746325d45313af0766266479b75654e65f",
+                        "5037ea654196cff0cd82b2c14a2fcf2e3ff8775285b545722f03eacdb74b",
+                        "28f9d04e900069c8dc47a08534fe76d2b900b7d7ef31f5709f200c4ca205",
+                        "5667334c45aff3b5a03bad9dd75e2c71a99362567d5453f7fa6e227ec833",
+                        "1555555555555555555555555555553c6f2885259c31e3fcdf154624522d",
+                        6)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb239v3",
+                        "1.2.840.10045.3.0.13",
+                        "800000000000000000000000000000000000000000000000001000000001",
+                        "01238774666a67766d6676f778e676b66999176666e687666d8766c66a9f",
+                        "6a941977ba9f6a435199acfc51067ed587f519c5ecb541b8e44111de1d40",
+                        "70f6e9d04d289c4e89913ce3530bfde903977d42b146d539bf1bde4e9c92",
+                        "2e5a0eaf6e5e1305b9004dce5c0ed7fe59a35608f33837c816d80b79f461",
+                        "0cccccccccccccccccccccccccccccac4912d2d9df903ef9888b8a0e4cff",
+                        0xA)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb359v1",
+                        "1.2.840.10045.3.0.18",
+                        "800000000000000000000000000000000000000000000000000000000000000000000000100000000000000001",
+                        "5667676a654b20754f356ea92017d946567c46675556f19556a04616b567d223a5e05656fb549016a96656a557",
+                        "2472e2d0197c49363f1fe7f5b6db075d52b6947d135d8ca445805d39bc345626089687742b6329e70680231988",
+                        "3c258ef3047767e7ede0f1fdaa79daee3841366a132e163aced4ed2401df9c6bdcde98e8e707c07a2239b1b097",
+                        "53d7e08529547048121e9c95f3791dd804963948f34fae7bf44ea82365dc7868fe57e4ae2de211305a407104bd",
+                        "01af286bca1af286bca1af286bca1af286bca1af286bc9fb8f6b85c556892c20a7eb964fe7719e74f490758d3b",
+                        0x4C)
+        );
+
+        ecCurveDefinitions.add(
+                new ECCurveDefinition(
+                        "X9.62 c2tnb431r1",
+                        "1.2.840.10045.3.0.20",
+                        "800000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000001",
+                        "1a827ef00dd6fc0e234caf046c6a5d8a85395b236cc4ad2cf32a0cadbdc9ddf620b0eb9906d0957f6c6feacd615468df104de296cd8f",
+                        "10d9b4a3d9047d8b154359abfb1b7f5485b04ceb868237ddc9deda982a679a5a919b626d4e50a8dd731b107a9962381fb5d807bf2618",
+                        "120fc05d3c67a99de161d2f4092622feca701be4f50f4758714e8a87bbf2a658ef8c21e7c5efe965361f6c2999c0c247b0dbd70ce6b7",
+                        "20d0af8903a96f8d5fa2c255745d3c451b302c9346d9b7e485e7bce41f6b591f3e8f6addcbb0bc4c2f947a7de1a89b625d6a598b3760",
+                        "0340340340340340340340340340340340340340340340340340340323c313fab50589703b5ec68d3587fec60d161cc149c1ad4a91",
+                        0x2760)
+        );
+    }
+
+    public static String getOIDFromPublicKey(ECPublicKey ecPublicKey) {
+        ECParameterSpec ecParameterSpec = ecPublicKey.getParams();
+        BigInteger order = ecParameterSpec.getOrder();
+        BigInteger affineX = ecParameterSpec.getGenerator().getAffineX();
+        BigInteger affineY = ecParameterSpec.getGenerator().getAffineY();
+        BigInteger a = ecParameterSpec.getCurve().getA();
+        BigInteger b = ecParameterSpec.getCurve().getB();
+        int h = ecParameterSpec.getCofactor();
+        ECField ecField = ecParameterSpec.getCurve().getField();
+        BigInteger field;
+        if (ecField instanceof ECFieldFp) {
+            ECFieldFp ecFieldFp = (ECFieldFp) ecField;
+            field = ecFieldFp.getP();
+        } else {
+            ECFieldF2m ecFieldF2m = (ECFieldF2m) ecField;
+            field = ecFieldF2m.getReductionPolynomial();
+        }
+
+        Iterator<ECCurveDefinition> ecCurveDefinitionIterator = ecCurveDefinitions.iterator();
+        while (ecCurveDefinitionIterator.hasNext()) {
+            ECCurveDefinition ecCurveDefinition = ecCurveDefinitionIterator.next();
+            String oid = ecCurveDefinition.equals(field, a, b, affineX, affineY, order, h);
+            if (oid != null) {
+                return oid;
+            }
+        }
+        return null;
+    }
+
+    public static ECCurveDefinition getECCurveDefinition(String oid) {
+        Iterator<ECCurveDefinition> ecCurveDefinitionIterator = ecCurveDefinitions.iterator();
+        while (ecCurveDefinitionIterator.hasNext()) {
+            ECCurveDefinition ecCurveDefinition = ecCurveDefinitionIterator.next();
+            if (ecCurveDefinition.getOid().equals(oid)) {
+                return ecCurveDefinition;
+            }
+        }
+        return null;
+    }
+
+    public static class ECCurveDefinition {
+
+        private final String name;
+        private final String oid;
+        private final String field;
+        private final String a;
+        private final String b;
+        private final String x;
+        private final String y;
+        private final String n;
+        private final int h;
+
+        public ECCurveDefinition(String name, String oid, String field, String a, String b, String x, String y, String n, int h) {
+            this.name = name;
+            this.oid = oid;
+            this.field = field;
+            this.a = a;
+            this.b = b;
+            this.x = x;
+            this.y = y;
+            this.n = n;
+            this.h = h;
+        }
+
+        /**
+         * returns the ec oid if parameter are equal to this definition
+         */
+        public String equals(BigInteger field, BigInteger a, BigInteger b, BigInteger x, BigInteger y, BigInteger n, int h) {
+            if (this.field.equals(field.toString(16))
+                    && this.a.equals(a.toString(16))
+                    && this.b.equals(b.toString(16))
+                    && this.x.equals(x.toString(16))
+                    && this.y.equals(y.toString(16))
+                    && this.n.equals(n.toString(16))
+                    && this.h == h) {
+                return this.oid;
+            }
+            return null;
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public String getOid() {
+            return oid;
+        }
+
+        public String getField() {
+            return field;
+        }
+
+        public String getA() {
+            return a;
+        }
+
+        public String getB() {
+            return b;
+        }
+
+        public String getX() {
+            return x;
+        }
+
+        public String getY() {
+            return y;
+        }
+
+        public String getN() {
+            return n;
+        }
+
+        public int getH() {
+            return h;
+        }
+    }
+
+    public static byte[] encodePoint(ECPoint ecPoint, EllipticCurve ellipticCurve) {
+        int size = (ellipticCurve.getField().getFieldSize() + 7) / 8;
+        byte affineXBytes[] = stripLeadingZeros(ecPoint.getAffineX().toByteArray());
+        byte affineYBytes[] = stripLeadingZeros(ecPoint.getAffineY().toByteArray());
+        byte encodedBytes[] = new byte[size * 2 + 1];
+        encodedBytes[0] = 0x04; //uncompressed
+        System.arraycopy(affineXBytes, 0, encodedBytes, size - affineXBytes.length + 1, affineXBytes.length);
+        System.arraycopy(affineYBytes, 0, encodedBytes, encodedBytes.length - affineYBytes.length, affineYBytes.length);
+        return encodedBytes;
+    }
+
+    public static ECPoint decodePoint(byte[] encodedBytes, EllipticCurve elliptiCcurve) {
+        if (encodedBytes[0] != 0x04) {
+            throw new IllegalArgumentException("Only uncompressed format is supported");
+        }
+
+        int size = (elliptiCcurve.getField().getFieldSize() + 7) / 8;
+        byte affineXBytes[] = new byte[size];
+        byte affineYBytes[] = new byte[size];
+        System.arraycopy(encodedBytes, 1, affineXBytes, 0, size);
+        System.arraycopy(encodedBytes, size + 1, affineYBytes, 0, size);
+        return new ECPoint(new BigInteger(1, affineXBytes), new BigInteger(1, affineYBytes));
+    }
+
+    public static byte[] stripLeadingZeros(byte[] bytes) {
+        int i;
+        for (i = 0; i < bytes.length - 1; i++) {
+            if (bytes[i] != 0) {
+                break;
+            }
+        }
+
+        if (i == 0) {
+            return bytes;
+        } else {
+            byte stripped[] = new byte[bytes.length - i];
+            System.arraycopy(bytes, i, stripped, 0, stripped.length);
+            return stripped;
+        }
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Tue Jun 19 16:33:07 2018 +0100
@@ -44,21 +44,20 @@
 
 public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(IntegrityHmac.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(IntegrityHmac.class);
 
     /** Field macAlgorithm */
-    private Mac macAlgorithm = null;
+    private Mac macAlgorithm;
 
     /** Field HMACOutputLength */
-    private int HMACOutputLength = 0;
+    private int HMACOutputLength;
     private boolean HMACOutputLengthSet = false;
 
     /**
      * Method engineGetURI
      *
-     *@inheritDoc
+     *{@inheritDoc}
      */
     public abstract String engineGetURI();
 
@@ -74,9 +73,7 @@
      */
     public IntegrityHmac() throws XMLSignatureException {
         String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
-        }
+        LOG.debug("Created IntegrityHmacSHA1 using {}", algorithmID);
 
         try {
             this.macAlgorithm = Mac.getInstance(algorithmID);
@@ -96,7 +93,7 @@
      * @throws XMLSignatureException
      */
     protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
-        throw new XMLSignatureException("empty");
+        throw new XMLSignatureException("empty", new Object[]{"Incorrect method call"});
     }
 
     public void reset() {
@@ -116,9 +113,7 @@
     protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
         try {
             if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
-                }
+                LOG.debug("HMACOutputLength must not be less than {}", getDigestLength());
                 Object[] exArgs = { String.valueOf(getDigestLength()) };
                 throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
             } else {
@@ -126,7 +121,7 @@
                 return MessageDigestAlgorithm.isEqual(completeResult, signature);
             }
         } catch (IllegalStateException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -139,7 +134,10 @@
      */
     protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
         if (!(secretKey instanceof SecretKey)) {
-            String supplied = secretKey.getClass().getName();
+            String supplied = null;
+            if (secretKey != null) {
+                supplied = secretKey.getClass().getName();
+            }
             String needed = SecretKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -156,12 +154,10 @@
                 this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous Mac
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
-                }
+                LOG.debug("Exception when reinstantiating Mac: {}", e);
                 this.macAlgorithm = mac;
             }
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -175,16 +171,14 @@
     protected byte[] engineSign() throws XMLSignatureException {
         try {
             if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
-                }
+                LOG.debug("HMACOutputLength must not be less than {}", getDigestLength());
                 Object[] exArgs = { String.valueOf(getDigestLength()) };
                 throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
             } else {
                 return this.macAlgorithm.doFinal();
             }
         } catch (IllegalStateException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -195,19 +189,7 @@
      * @throws XMLSignatureException
      */
     protected void engineInitSign(Key secretKey) throws XMLSignatureException {
-        if (!(secretKey instanceof SecretKey)) {
-            String supplied = secretKey.getClass().getName();
-            String needed = SecretKey.class.getName();
-            Object exArgs[] = { supplied, needed };
-
-            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
-        }
-
-        try {
-            this.macAlgorithm.init(secretKey);
-        } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
-        }
+        engineInitSign(secretKey, (AlgorithmParameterSpec)null);
     }
 
     /**
@@ -221,7 +203,10 @@
         Key secretKey, AlgorithmParameterSpec algorithmParameterSpec
     ) throws XMLSignatureException {
         if (!(secretKey instanceof SecretKey)) {
-            String supplied = secretKey.getClass().getName();
+            String supplied = null;
+            if (secretKey != null) {
+                supplied = secretKey.getClass().getName();
+            }
             String needed = SecretKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -229,11 +214,15 @@
         }
 
         try {
-            this.macAlgorithm.init(secretKey, algorithmParameterSpec);
+            if (algorithmParameterSpec == null) {
+                this.macAlgorithm.init(secretKey);
+            } else {
+                this.macAlgorithm.init(secretKey, algorithmParameterSpec);
+            }
         } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidAlgorithmParameterException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -260,7 +249,7 @@
         try {
             this.macAlgorithm.update(input);
         } catch (IllegalStateException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -275,7 +264,7 @@
         try {
             this.macAlgorithm.update(input);
         } catch (IllegalStateException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -292,13 +281,13 @@
         try {
             this.macAlgorithm.update(buf, offset, len);
         } catch (IllegalStateException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
      * Method engineGetJCEAlgorithmString
-     * @inheritDoc
+     * {@inheritDoc}
      *
      */
     protected String engineGetJCEAlgorithmString() {
@@ -308,7 +297,7 @@
     /**
      * Method engineGetJCEAlgorithmString
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetJCEProviderName() {
         return this.macAlgorithm.getProvider().getName();
@@ -360,7 +349,7 @@
             Element HMElem =
                 XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
             Text HMText =
-                doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());
+                doc.createTextNode("" + this.HMACOutputLength);
 
             HMElem.appendChild(HMText);
             XMLUtils.addReturnToElement(element);
@@ -385,7 +374,7 @@
 
         /**
          * Method engineGetURI
-         * @inheritDoc
+         * {@inheritDoc}
          *
          */
         public String engineGetURI() {
@@ -398,6 +387,34 @@
     }
 
     /**
+     * Class IntegrityHmacSHA224
+     */
+    public static class IntegrityHmacSHA224 extends IntegrityHmac {
+
+        /**
+         * Constructor IntegrityHmacSHA224
+         *
+         * @throws XMLSignatureException
+         */
+        public IntegrityHmacSHA224() throws XMLSignatureException {
+            super();
+        }
+
+        /**
+         * Method engineGetURI
+         *
+         * {@inheritDoc}
+         */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_MAC_HMAC_SHA224;
+        }
+
+        int getDigestLength() {
+            return 224;
+        }
+    }
+
+    /**
      * Class IntegrityHmacSHA256
      */
     public static class IntegrityHmacSHA256 extends IntegrityHmac {
@@ -414,7 +431,7 @@
         /**
          * Method engineGetURI
          *
-         * @inheritDoc
+         * {@inheritDoc}
          */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
@@ -441,7 +458,7 @@
 
         /**
          * Method engineGetURI
-         * @inheritDoc
+         * {@inheritDoc}
          *
          */
         public String engineGetURI() {
@@ -469,7 +486,7 @@
 
         /**
          * Method engineGetURI
-         * @inheritDoc
+         * {@inheritDoc}
          *
          */
         public String engineGetURI() {
@@ -498,7 +515,7 @@
         /**
          * Method engineGetURI
          *
-         * @inheritDoc
+         * {@inheritDoc}
          */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
@@ -526,7 +543,7 @@
         /**
          * Method engineGetURI
          *
-         * @inheritDoc
+         * {@inheritDoc}
          */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Tue Jun 19 16:33:07 2018 +0100
@@ -40,15 +40,14 @@
 
 public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureBaseRSA.class);
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public abstract String engineGetURI();
 
     /** Field algorithm */
-    private java.security.Signature signatureAlgorithm = null;
+    private Signature signatureAlgorithm;
 
     /**
      * Constructor SignatureRSA
@@ -58,15 +57,13 @@
     public SignatureBaseRSA() throws XMLSignatureException {
         String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID);
-        }
+        LOG.debug("Created SignatureRSA using {}", algorithmID);
         String provider = JCEMapper.getProviderId();
         try {
             if (provider == null) {
                 this.signatureAlgorithm = Signature.getInstance(algorithmID);
             } else {
-                this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+                this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
             }
         } catch (java.security.NoSuchAlgorithmException ex) {
             Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
@@ -79,29 +76,32 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineSetParameter(AlgorithmParameterSpec params)
         throws XMLSignatureException {
         try {
             this.signatureAlgorithm.setParameter(params);
         } catch (InvalidAlgorithmParameterException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
         try {
             return this.signatureAlgorithm.verify(signature);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
         if (!(publicKey instanceof PublicKey)) {
-            String supplied = publicKey.getClass().getName();
+            String supplied = null;
+            if (publicKey != null) {
+                supplied = publicKey.getClass().getName();
+            }
             String needed = PublicKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -119,46 +119,30 @@
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
-                }
+                LOG.debug("Exception when reinstantiating Signature: {}", e);
                 this.signatureAlgorithm = sig;
             }
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected byte[] engineSign() throws XMLSignatureException {
         try {
             return this.signatureAlgorithm.sign();
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
         throws XMLSignatureException {
         if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
-            String needed = PrivateKey.class.getName();
-            Object exArgs[] = { supplied, needed };
-
-            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
-        }
-
-        try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
-        } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
-        }
-    }
-
-    /** @inheritDoc */
-    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-        if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
+            String supplied = null;
+            if (privateKey != null) {
+                supplied = privateKey.getClass().getName();
+            }
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -166,56 +150,65 @@
         }
 
         try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+            if (secureRandom == null) {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+            } else {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+            }
         } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+        engineInitSign(privateKey, (SecureRandom)null);
+    }
+
+    /** {@inheritDoc} */
     protected void engineUpdate(byte[] input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineUpdate(byte input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(buf, offset, len);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetJCEAlgorithmString() {
         return this.signatureAlgorithm.getAlgorithm();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetJCEProviderName() {
         return this.signatureAlgorithm.getProvider().getName();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineSetHMACOutputLength(int HMACOutputLength)
         throws XMLSignatureException {
         throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitSign(
         Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
     ) throws XMLSignatureException {
@@ -236,13 +229,33 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
         }
     }
 
     /**
+     * Class SignatureRSASHA224
+     */
+    public static class SignatureRSASHA224 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA224
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA224() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224;
+        }
+    }
+
+    /**
      * Class SignatureRSASHA256
      */
     public static class SignatureRSASHA256 extends SignatureBaseRSA {
@@ -256,7 +269,7 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
         }
@@ -276,7 +289,7 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384;
         }
@@ -296,7 +309,7 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512;
         }
@@ -316,7 +329,7 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160;
         }
@@ -336,9 +349,189 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5;
         }
     }
+
+    /**
+     * Class SignatureRSASHA1MGF1
+     */
+    public static class SignatureRSASHA1MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA1MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA1MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA224MGF1
+     */
+    public static class SignatureRSASHA224MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA224MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA224MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA256MGF1
+     */
+    public static class SignatureRSASHA256MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA256MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA256MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA384MGF1
+     */
+    public static class SignatureRSASHA384MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA384MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA384MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA512MGF1
+     */
+    public static class SignatureRSASHA512MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA512MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA512MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSA3_SHA224MGF1
+     */
+    public static class SignatureRSASHA3_224MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA3_224MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA3_224MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSA3_SHA256MGF1
+     */
+    public static class SignatureRSASHA3_256MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA3_256MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA3_256MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSA3_SHA384MGF1
+     */
+    public static class SignatureRSASHA3_384MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA3_384MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA3_384MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1;
+        }
+    }
+
+    /**
+     * Class SignatureRSASHA3_512MGF1
+     */
+    public static class SignatureRSASHA3_512MGF1 extends SignatureBaseRSA {
+
+        /**
+         * Constructor SignatureRSASHA3_512MGF1
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureRSASHA3_512MGF1() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1;
+        }
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,22 +33,24 @@
 import java.security.SignatureException;
 import java.security.interfaces.DSAKey;
 import java.security.spec.AlgorithmParameterSpec;
+import java.util.Base64;
 
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 
 public class SignatureDSA extends SignatureAlgorithmSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
+    public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureDSA.class);
 
     /** Field algorithm */
-    private java.security.Signature signatureAlgorithm = null;
+    private Signature signatureAlgorithm;
 
     /** size of Q */
     private int size;
@@ -56,7 +58,7 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return XMLSignature.ALGO_ID_SIGNATURE_DSA;
@@ -69,9 +71,7 @@
      */
     public SignatureDSA() throws XMLSignatureException {
         String algorithmID = JCEMapper.translateURItoJCEID(engineGetURI());
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
-        }
+        LOG.debug("Created SignatureDSA using {}", algorithmID);
 
         String provider = JCEMapper.getProviderId();
         try {
@@ -91,25 +91,25 @@
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected void engineSetParameter(AlgorithmParameterSpec params)
         throws XMLSignatureException {
         try {
             this.signatureAlgorithm.setParameter(params);
         } catch (InvalidAlgorithmParameterException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected boolean engineVerify(byte[] signature)
         throws XMLSignatureException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Called DSA.verify() on " + Base64.getMimeEncoder().encodeToString(signature));
             }
 
             byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature,
@@ -117,18 +117,21 @@
 
             return this.signatureAlgorithm.verify(jcebytes);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
         if (!(publicKey instanceof PublicKey)) {
-            String supplied = publicKey.getClass().getName();
+            String supplied = null;
+            if (publicKey != null) {
+                supplied = publicKey.getClass().getName();
+            }
             String needed = PublicKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -146,18 +149,16 @@
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
-                }
+                LOG.debug("Exception when reinstantiating Signature: {}", e);
                 this.signatureAlgorithm = sig;
             }
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
         size = ((DSAKey)publicKey).getParams().getQ().bitLength();
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected byte[] engineSign() throws XMLSignatureException {
         try {
@@ -165,19 +166,22 @@
 
             return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size/8);
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
         throws XMLSignatureException {
         if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
+            String supplied = null;
+            if (privateKey != null) {
+                supplied = privateKey.getClass().getName();
+            }
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -185,70 +189,61 @@
         }
 
         try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+            if (secureRandom == null) {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+            } else {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+            }
         } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
-        }
-        size = ((DSAKey)privateKey).getParams().getQ().bitLength();
-    }
-
-    /**
-     * @inheritDoc
-     */
-    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-        if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
-            String needed = PrivateKey.class.getName();
-            Object exArgs[] = { supplied, needed };
-
-            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
-        }
-
-        try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
-        } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
         size = ((DSAKey)privateKey).getParams().getQ().bitLength();
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
+     */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+        engineInitSign(privateKey, (SecureRandom)null);
+    }
+
+    /**
+     * {@inheritDoc}
      */
     protected void engineUpdate(byte[] input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected void engineUpdate(byte input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(buf, offset, len);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
      * Method engineGetJCEAlgorithmString
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetJCEAlgorithmString() {
         return this.signatureAlgorithm.getAlgorithm();
@@ -257,7 +252,7 @@
     /**
      * Method engineGetJCEProviderName
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetJCEProviderName() {
         return this.signatureAlgorithm.getProvider().getName();
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,34 +33,31 @@
 import java.security.Signature;
 import java.security.SignatureException;
 import java.security.spec.AlgorithmParameterSpec;
+import java.util.Base64;
 
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 
 /**
  *
- * @author $Author: raul $
- * @author Alex Dupre
  */
 public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureECDSA.class);
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public abstract String engineGetURI();
 
     /** Field algorithm */
-    private java.security.Signature signatureAlgorithm = null;
+    private Signature signatureAlgorithm;
 
     /**
      * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
      *
-     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
      * pairs; the XML Signature requires the core BigInteger values.
      *
      * @param asn1Bytes
@@ -71,51 +68,13 @@
      * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
      */
     public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
-
-        if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) {
-            throw new IOException("Invalid ASN.1 format of ECDSA signature");
-        }
-        int offset;
-        if (asn1Bytes[1] > 0) {
-            offset = 2;
-        } else if (asn1Bytes[1] == (byte) 0x81) {
-            offset = 3;
-        } else {
-            throw new IOException("Invalid ASN.1 format of ECDSA signature");
-        }
-
-        byte rLength = asn1Bytes[offset + 1];
-        int i;
-
-        for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--);
-
-        byte sLength = asn1Bytes[offset + 2 + rLength + 1];
-        int j;
-
-        for (j = sLength;
-            (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--);
-
-        int rawLen = Math.max(i, j);
-
-        if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset
-            || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
-            || asn1Bytes[offset] != 2
-            || asn1Bytes[offset + 2 + rLength] != 2) {
-            throw new IOException("Invalid ASN.1 format of ECDSA signature");
-        }
-        byte xmldsigBytes[] = new byte[2*rawLen];
-
-        System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i);
-        System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes,
-                         2*rawLen - j, j);
-
-        return xmldsigBytes;
+        return ECDSAUtils.convertASN1toXMLDSIG(asn1Bytes);
     }
 
     /**
      * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
      *
-     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
      * pairs; the XML Signature requires the core BigInteger values.
      *
      * @param xmldsigBytes
@@ -126,58 +85,7 @@
      * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
      */
     public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
-
-        int rawLen = xmldsigBytes.length/2;
-
-        int i;
-
-        for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--);
-
-        int j = i;
-
-        if (xmldsigBytes[rawLen - i] < 0) {
-            j += 1;
-        }
-
-        int k;
-
-        for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--);
-
-        int l = k;
-
-        if (xmldsigBytes[2*rawLen - k] < 0) {
-            l += 1;
-        }
-
-        int len = 2 + j + 2 + l;
-        if (len > 255) {
-            throw new IOException("Invalid XMLDSIG format of ECDSA signature");
-        }
-        int offset;
-        byte asn1Bytes[];
-        if (len < 128) {
-            asn1Bytes = new byte[2 + 2 + j + 2 + l];
-            offset = 1;
-        } else {
-            asn1Bytes = new byte[3 + 2 + j + 2 + l];
-            asn1Bytes[1] = (byte) 0x81;
-            offset = 2;
-        }
-        asn1Bytes[0] = 48;
-        asn1Bytes[offset++] = (byte) len;
-        asn1Bytes[offset++] = 2;
-        asn1Bytes[offset++] = (byte) j;
-
-        System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i);
-
-        offset += j;
-
-        asn1Bytes[offset++] = 2;
-        asn1Bytes[offset++] = (byte) l;
-
-        System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k);
-
-        return asn1Bytes;
+        return ECDSAUtils.convertXMLDSIGtoASN1(xmldsigBytes);
     }
 
     /**
@@ -189,15 +97,13 @@
 
         String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
-        }
+        LOG.debug("Created SignatureECDSA using {}", algorithmID);
         String provider = JCEMapper.getProviderId();
         try {
             if (provider == null) {
                 this.signatureAlgorithm = Signature.getInstance(algorithmID);
             } else {
-                this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+                this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
             }
         } catch (java.security.NoSuchAlgorithmException ex) {
             Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
@@ -210,38 +116,41 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineSetParameter(AlgorithmParameterSpec params)
         throws XMLSignatureException {
         try {
             this.signatureAlgorithm.setParameter(params);
         } catch (InvalidAlgorithmParameterException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
         try {
             byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
 
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Called ECDSA.verify() on " + Base64.getMimeEncoder().encodeToString(signature));
             }
 
             return this.signatureAlgorithm.verify(jcebytes);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
 
         if (!(publicKey instanceof PublicKey)) {
-            String supplied = publicKey.getClass().getName();
+            String supplied = null;
+            if (publicKey != null) {
+                supplied = publicKey.getClass().getName();
+            }
             String needed = PublicKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -259,50 +168,34 @@
             } catch (Exception e) {
                 // this shouldn't occur, but if it does, restore previous
                 // Signature
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
-                }
+                LOG.debug("Exception when reinstantiating Signature: {}", e);
                 this.signatureAlgorithm = sig;
             }
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected byte[] engineSign() throws XMLSignatureException {
         try {
             byte jcebytes[] = this.signatureAlgorithm.sign();
 
             return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
         throws XMLSignatureException {
         if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
-            String needed = PrivateKey.class.getName();
-            Object exArgs[] = { supplied, needed };
-
-            throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
-        }
-
-        try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
-        } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
-        }
-    }
-
-    /** @inheritDoc */
-    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-        if (!(privateKey instanceof PrivateKey)) {
-            String supplied = privateKey.getClass().getName();
+            String supplied = null;
+            if (privateKey != null) {
+                supplied = privateKey.getClass().getName();
+            }
             String needed = PrivateKey.class.getName();
             Object exArgs[] = { supplied, needed };
 
@@ -310,56 +203,65 @@
         }
 
         try {
-            this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+            if (secureRandom == null) {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+            } else {
+                this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+            }
         } catch (InvalidKeyException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
+    protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+        engineInitSign(privateKey, (SecureRandom)null);
+    }
+
+    /** {@inheritDoc} */
     protected void engineUpdate(byte[] input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineUpdate(byte input) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(input);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
         try {
             this.signatureAlgorithm.update(buf, offset, len);
         } catch (SignatureException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetJCEAlgorithmString() {
         return this.signatureAlgorithm.getAlgorithm();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetJCEProviderName() {
         return this.signatureAlgorithm.getProvider().getName();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineSetHMACOutputLength(int HMACOutputLength)
         throws XMLSignatureException {
         throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected void engineInitSign(
         Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
     ) throws XMLSignatureException {
@@ -367,13 +269,12 @@
     }
 
     /**
-     * Class SignatureRSASHA1
+     * Class SignatureECDSASHA1
      *
-     * @author $Author: marcx $
      */
     public static class SignatureECDSASHA1 extends SignatureECDSA {
         /**
-         * Constructor SignatureRSASHA1
+         * Constructor SignatureECDSASHA1
          *
          * @throws XMLSignatureException
          */
@@ -381,21 +282,40 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
         }
     }
 
     /**
-     * Class SignatureRSASHA256
+     * Class SignatureECDSASHA224
+     */
+    public static class SignatureECDSASHA224 extends SignatureECDSA {
+
+        /**
+         * Constructor SignatureECDSASHA224
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSASHA224() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224;
+        }
+    }
+
+    /**
+     * Class SignatureECDSASHA256
      *
-     * @author Alex Dupre
      */
     public static class SignatureECDSASHA256 extends SignatureECDSA {
 
         /**
-         * Constructor SignatureRSASHA256
+         * Constructor SignatureECDSASHA256
          *
          * @throws XMLSignatureException
          */
@@ -403,21 +323,20 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256;
         }
     }
 
     /**
-     * Class SignatureRSASHA384
+     * Class SignatureECDSASHA384
      *
-     * @author Alex Dupre
      */
     public static class SignatureECDSASHA384 extends SignatureECDSA {
 
         /**
-         * Constructor SignatureRSASHA384
+         * Constructor SignatureECDSASHA384
          *
          * @throws XMLSignatureException
          */
@@ -425,21 +344,20 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384;
         }
     }
 
     /**
-     * Class SignatureRSASHA512
+     * Class SignatureECDSASHA512
      *
-     * @author Alex Dupre
      */
     public static class SignatureECDSASHA512 extends SignatureECDSA {
 
         /**
-         * Constructor SignatureRSASHA512
+         * Constructor SignatureECDSASHA512
          *
          * @throws XMLSignatureException
          */
@@ -447,10 +365,30 @@
             super();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public String engineGetURI() {
             return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512;
         }
     }
 
+    /**
+     * Class SignatureECDSARIPEMD160
+     */
+    public static class SignatureECDSARIPEMD160 extends SignatureECDSA {
+
+        /**
+         * Constructor SignatureECDSARIPEMD160
+         *
+         * @throws XMLSignatureException
+         */
+        public SignatureECDSARIPEMD160() throws XMLSignatureException {
+            super();
+        }
+
+        /** {@inheritDoc} */
+        public String engineGetURI() {
+            return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160;
+        }
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML> <HEAD> </HEAD> <BODY> <P>
-implementations of {@link com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi}.
-</P></BODY> </HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-algorithm factories.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,7 +27,6 @@
 /**
  * Class CanonicalizationException
  *
- * @author Christian Geuer-Pollmann
  */
 public class CanonicalizationException extends XMLSecurityException {
 
@@ -44,6 +43,10 @@
         super();
     }
 
+    public CanonicalizationException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor CanonicalizationException
      *
@@ -66,23 +69,33 @@
     /**
      * Constructor CanonicalizationException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public CanonicalizationException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public CanonicalizationException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor CanonicalizationException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
     public CanonicalizationException(
-        String msgID, Object exArgs[], Exception originalException
+        Exception originalException, String msgID, Object exArgs[]
     ) {
-        super(msgID, exArgs, originalException);
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public CanonicalizationException(String msgID, Object exArgs[], Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,13 +25,12 @@
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
-import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments;
@@ -42,6 +41,7 @@
 import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
 import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
@@ -49,12 +49,11 @@
 
 /**
  *
- * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer {
 
     /** The output encoding of canonicalized data */
-    public static final String ENCODING = "UTF8";
+    public static final String ENCODING = StandardCharsets.UTF_8.name();
 
     /**
      * XPath Expression for selecting every node and continuous comments joined
@@ -103,6 +102,7 @@
         new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
 
     private final CanonicalizerSpi canonicalizerSpi;
+    private boolean secureValidation;
 
     /**
      * Constructor Canonicalizer
@@ -122,7 +122,7 @@
         } catch (Exception e) {
             Object exArgs[] = { algorithmURI };
             throw new InvalidCanonicalizerException(
-                "signature.Canonicalizer.UnknownCanonicalizer", exArgs, e
+                e, "signature.Canonicalizer.UnknownCanonicalizer", exArgs
             );
         }
     }
@@ -162,7 +162,8 @@
         }
 
         canonicalizerHash.put(
-            algorithmURI, (Class<? extends CanonicalizerSpi>)Class.forName(implementingClass)
+            algorithmURI, (Class<? extends CanonicalizerSpi>)
+            ClassLoaderUtils.loadClass(implementingClass, Canonicalizer.class)
         );
     }
 
@@ -244,7 +245,7 @@
     /**
      * This method tries to canonicalize the given bytes. It's possible to even
      * canonicalize non-wellformed sequences if they are well-formed after being
-     * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
+     * wrapped with a {@code &gt;a&lt;...&gt;/a&lt;}.
      *
      * @param inputBytes
      * @return the result of the canonicalization.
@@ -256,47 +257,43 @@
     public byte[] canonicalize(byte[] inputBytes)
         throws javax.xml.parsers.ParserConfigurationException,
         java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
-        InputStream bais = new ByteArrayInputStream(inputBytes);
-        InputSource in = new InputSource(bais);
-        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
-        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+        Document document = null;
+        try (InputStream bais = new ByteArrayInputStream(inputBytes)) {
+            InputSource in = new InputSource(bais);
 
-        dfactory.setNamespaceAware(true);
-
-        // needs to validate for ID attribute normalization
-        dfactory.setValidating(true);
-
-        DocumentBuilder db = dfactory.newDocumentBuilder();
+            // needs to validate for ID attribute normalization
+            DocumentBuilder db = XMLUtils.createDocumentBuilder(true, secureValidation);
 
-        /*
-         * for some of the test vectors from the specification,
-         * there has to be a validating parser for ID attributes, default
-         * attribute values, NMTOKENS, etc.
-         * Unfortunately, the test vectors do use different DTDs or
-         * even no DTD. So Xerces 1.3.1 fires many warnings about using
-         * ErrorHandlers.
-         *
-         * Text from the spec:
-         *
-         * The input octet stream MUST contain a well-formed XML document,
-         * but the input need not be validated. However, the attribute
-         * value normalization and entity reference resolution MUST be
-         * performed in accordance with the behaviors of a validating
-         * XML processor. As well, nodes for default attributes (declared
-         * in the ATTLIST with an AttValue but not specified) are created
-         * in each element. Thus, the declarations in the document type
-         * declaration are used to help create the canonical form, even
-         * though the document type declaration is not retained in the
-         * canonical form.
-         */
-        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
+            /*
+             * for some of the test vectors from the specification,
+             * there has to be a validating parser for ID attributes, default
+             * attribute values, NMTOKENS, etc.
+             * Unfortunately, the test vectors do use different DTDs or
+             * even no DTD. So Xerces 1.3.1 fires many warnings about using
+             * ErrorHandlers.
+             *
+             * Text from the spec:
+             *
+             * The input octet stream MUST contain a well-formed XML document,
+             * but the input need not be validated. However, the attribute
+             * value normalization and entity reference resolution MUST be
+             * performed in accordance with the behaviors of a validating
+             * XML processor. As well, nodes for default attributes (declared
+             * in the ATTLIST with an AttValue but not specified) are created
+             * in each element. Thus, the declarations in the document type
+             * declaration are used to help create the canonical form, even
+             * though the document type declaration is not retained in the
+             * canonical form.
+             */
+            db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
 
-        Document document = db.parse(in);
+            document = db.parse(in);
+        }
         return this.canonicalizeSubtree(document);
     }
 
     /**
-     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
+     * Canonicalizes the subtree rooted by {@code node}.
      *
      * @param node The node to canonicalize
      * @return the result of the c14n.
@@ -304,11 +301,12 @@
      * @throws CanonicalizationException
      */
     public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return canonicalizerSpi.engineCanonicalizeSubTree(node);
     }
 
     /**
-     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
+     * Canonicalizes the subtree rooted by {@code node}.
      *
      * @param node
      * @param inclusiveNamespaces
@@ -317,11 +315,26 @@
      */
     public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces)
         throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces);
     }
 
     /**
-     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
+     * Canonicalizes the subtree rooted by {@code node}.
+     *
+     * @param node
+     * @param inclusiveNamespaces
+     * @return the result of the c14n.
+     * @throws CanonicalizationException
+     */
+    public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces, boolean propagateDefaultNamespace)
+            throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
+        return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, propagateDefaultNamespace);
+    }
+
+    /**
+     * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated
      * as a list of XPath nodes, not as a list of subtrees.
      *
      * @param xpathNodeSet
@@ -330,11 +343,12 @@
      */
     public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet)
         throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
     }
 
     /**
-     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
+     * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated
      * as a list of XPath nodes, not as a list of subtrees.
      *
      * @param xpathNodeSet
@@ -345,6 +359,7 @@
     public byte[] canonicalizeXPathNodeSet(
         NodeList xpathNodeSet, String inclusiveNamespaces
     ) throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return
             canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
     }
@@ -358,6 +373,7 @@
      */
     public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
         throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
     }
 
@@ -372,6 +388,7 @@
     public byte[] canonicalizeXPathNodeSet(
         Set<Node> xpathNodeSet, String inclusiveNamespaces
     ) throws CanonicalizationException {
+        canonicalizerSpi.secureValidation = secureValidation;
         return
             canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
     }
@@ -401,4 +418,12 @@
         canonicalizerSpi.reset = false;
     }
 
+    public boolean isSecureValidation() {
+        return secureValidation;
+    }
+
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,9 +26,7 @@
 import java.io.OutputStream;
 import java.util.Set;
 
-import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
@@ -39,12 +37,12 @@
 /**
  * Base class which all Canonicalization algorithms extend.
  *
- * @author Christian Geuer-Pollmann
  */
 public abstract class CanonicalizerSpi {
 
     /** Reset the writer after a c14n */
     protected boolean reset = false;
+    protected boolean secureValidation;
 
     /**
      * Method canonicalize
@@ -61,17 +59,14 @@
         throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
         org.xml.sax.SAXException, CanonicalizationException {
 
-        java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
-        InputSource in = new InputSource(bais);
-        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
-        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+        Document document = null;
+        try (java.io.InputStream bais = new ByteArrayInputStream(inputBytes)) {
+            InputSource in = new InputSource(bais);
 
-        // needs to validate for ID attribute normalization
-        dfactory.setNamespaceAware(true);
+            DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation);
 
-        DocumentBuilder db = dfactory.newDocumentBuilder();
-
-        Document document = db.parse(in);
+            document = db.parse(in);
+        }
         return this.engineCanonicalizeSubTree(document);
     }
 
@@ -160,10 +155,31 @@
         throws CanonicalizationException;
 
     /**
+     * C14n a node tree.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element
+     * @return the c14n bytes
+     * @throws CanonicalizationException
+     */
+    public abstract byte[] engineCanonicalizeSubTree(
+            Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace)
+            throws CanonicalizationException;
+
+    /**
      * Sets the writer where the canonicalization ends. ByteArrayOutputStream if
      * none is set.
      * @param os
      */
     public abstract void setWriter(OutputStream os);
 
+    public boolean isSecureValidation() {
+        return secureValidation;
+    }
+
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,84 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.c14n;
+
+// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
+// modifiers changed to package-private. Make sure to integrate any future
+// changes to utils.ClassLoaderUtils to this file.
+final class ClassLoaderUtils {
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a class with a given name. <p></p> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            LOG.debug(e.getMessage(), e);
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            LOG.debug(ex.getMessage(), ex);
+            throw ex;
+        }
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -61,23 +61,33 @@
     /**
      * Constructor InvalidCanonicalizerException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public InvalidCanonicalizerException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public InvalidCanonicalizerException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor InvalidCanonicalizerException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
     public InvalidCanonicalizerException(
-        String msgID, Object exArgs[], Exception originalException
+        Exception originalException, String msgID, Object exArgs[]
     ) {
-        super(msgID, exArgs, originalException);
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public InvalidCanonicalizerException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,7 +41,6 @@
  *   key (an empty namespace URI is lexicographically least).
  * </UL>
  *
- * @author Christian Geuer-Pollmann
  */
 public class AttrCompare implements Comparator<Attr>, Serializable {
 
@@ -117,6 +116,6 @@
             return a;
         }
 
-        return (attr0.getLocalName()).compareTo(attr1.getLocalName());
+        return attr0.getLocalName().compareTo(attr1.getLocalName());
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,9 +31,8 @@
 /**
  * Temporary swapped static functions from the normalizer Section
  *
- * @author Christian Geuer-Pollmann
  */
-public class C14nHelper {
+public final class C14nHelper {
 
     /**
      * Constructor C14nHelper
@@ -100,7 +99,7 @@
         }
 
         String nodeAttrName = attr.getNodeName();
-        boolean definesDefaultNS = nodeAttrName.equals("xmlns");
+        boolean definesDefaultNS = "xmlns".equals(nodeAttrName);
         boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");
 
         if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
@@ -145,7 +144,8 @@
         if (ctxNode != null) {
             NamedNodeMap attributes = ctxNode.getAttributes();
 
-            for (int i = 0; i < attributes.getLength(); i++) {
+            int length = attributes.getLength();
+            for (int i = 0; i < length; i++) {
                 C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
             }
         } else {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML> <HEAD> </HEAD> <BODY> <P>
-helper classes for canonicalization.
-</P></BODY> </HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,687 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.c14n.implementations;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import javax.xml.parsers.ParserConfigurationException;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
-
-import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
-import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-
-/**
- * Implements <A HREF="http://www.w3.org/TR/2008/PR-xml-c14n11-20080129/">
- * Canonical XML Version 1.1</A>, a W3C Proposed Recommendation from 29
- * January 2008.
- *
- * @author Sean Mullan
- * @author Raul Benito
- */
-public abstract class Canonicalizer11 extends CanonicalizerBase {
-
-    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
-    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Canonicalizer11.class.getName());
-    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
-
-    private boolean firstCall = true;
-
-    private static class XmlAttrStack {
-        static class XmlsStackElement {
-            int level;
-            boolean rendered = false;
-            List<Attr> nodes = new ArrayList<Attr>();
-        };
-
-        int currentLevel = 0;
-        int lastlevel = 0;
-        XmlsStackElement cur;
-        List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
-
-        void push(int level) {
-            currentLevel = level;
-            if (currentLevel == -1) {
-                return;
-            }
-            cur = null;
-            while (lastlevel >= currentLevel) {
-                levels.remove(levels.size() - 1);
-                int newSize = levels.size();
-                if (newSize == 0) {
-                    lastlevel = 0;
-                    return;
-                }
-                lastlevel = (levels.get(newSize - 1)).level;
-            }
-        }
-
-        void addXmlnsAttr(Attr n) {
-            if (cur == null) {
-                cur = new XmlsStackElement();
-                cur.level = currentLevel;
-                levels.add(cur);
-                lastlevel = currentLevel;
-            }
-            cur.nodes.add(n);
-        }
-
-        void getXmlnsAttr(Collection<Attr> col) {
-            int size = levels.size() - 1;
-            if (cur == null) {
-                cur = new XmlsStackElement();
-                cur.level = currentLevel;
-                lastlevel = currentLevel;
-                levels.add(cur);
-            }
-            boolean parentRendered = false;
-            XmlsStackElement e = null;
-            if (size == -1) {
-                parentRendered = true;
-            } else {
-                e = levels.get(size);
-                if (e.rendered && e.level + 1 == currentLevel) {
-                    parentRendered = true;
-                }
-            }
-            if (parentRendered) {
-                col.addAll(cur.nodes);
-                cur.rendered = true;
-                return;
-            }
-
-            Map<String, Attr> loa = new HashMap<String, Attr>();
-            List<Attr> baseAttrs = new ArrayList<Attr>();
-            boolean successiveOmitted = true;
-            for (; size >= 0; size--) {
-                e = levels.get(size);
-                if (e.rendered) {
-                    successiveOmitted = false;
-                }
-                Iterator<Attr> it = e.nodes.iterator();
-                while (it.hasNext() && successiveOmitted) {
-                    Attr n = it.next();
-                    if (n.getLocalName().equals("base") && !e.rendered) {
-                        baseAttrs.add(n);
-                    } else if (!loa.containsKey(n.getName())) {
-                        loa.put(n.getName(), n);
-                    }
-                }
-            }
-            if (!baseAttrs.isEmpty()) {
-                Iterator<Attr> it = col.iterator();
-                String base = null;
-                Attr baseAttr = null;
-                while (it.hasNext()) {
-                    Attr n = it.next();
-                    if (n.getLocalName().equals("base")) {
-                        base = n.getValue();
-                        baseAttr = n;
-                        break;
-                    }
-                }
-                it = baseAttrs.iterator();
-                while (it.hasNext()) {
-                    Attr n = it.next();
-                    if (base == null) {
-                        base = n.getValue();
-                        baseAttr = n;
-                    } else {
-                        try {
-                            base = joinURI(n.getValue(), base);
-                        } catch (URISyntaxException ue) {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, ue.getMessage(), ue);
-                            }
-                        }
-                    }
-                }
-                if (base != null && base.length() != 0) {
-                    baseAttr.setValue(base);
-                    col.add(baseAttr);
-                }
-            }
-
-            cur.rendered = true;
-            col.addAll(loa.values());
-        }
-    };
-
-    private XmlAttrStack xmlattrStack = new XmlAttrStack();
-
-    /**
-     * Constructor Canonicalizer11
-     *
-     * @param includeComments
-     */
-    public Canonicalizer11(boolean includeComments) {
-        super(includeComments);
-    }
-
-    /**
-     * Always throws a CanonicalizationException because this is inclusive c14n.
-     *
-     * @param xpathNodeSet
-     * @param inclusiveNamespaces
-     * @return none it always fails
-     * @throws CanonicalizationException always
-     */
-    public byte[] engineCanonicalizeXPathNodeSet(
-        Set<Node> xpathNodeSet, String inclusiveNamespaces
-    ) throws CanonicalizationException {
-        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
-    }
-
-    /**
-     * Always throws a CanonicalizationException because this is inclusive c14n.
-     *
-     * @param rootNode
-     * @param inclusiveNamespaces
-     * @return none it always fails
-     * @throws CanonicalizationException
-     */
-    public byte[] engineCanonicalizeSubTree(
-        Node rootNode, String inclusiveNamespaces
-    ) throws CanonicalizationException {
-        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
-    }
-
-    /**
-     * Returns the Attr[]s to be output for the given element.
-     * <br>
-     * The code of this method is a copy of {@link #handleAttributes(Element,
-     * NameSpaceSymbTable)},
-     * whereas it takes into account that subtree-c14n is -- well --
-     * subtree-based.
-     * So if the element in question isRoot of c14n, it's parent is not in the
-     * node set, as well as all other ancestors.
-     *
-     * @param element
-     * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
-     */
-    @Override
-    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
-        if (!element.hasAttributes() && !firstCall) {
-            return null;
-        }
-        // result will contain the attrs which have to be output
-        final SortedSet<Attr> result = this.result;
-        result.clear();
-
-        if (element.hasAttributes()) {
-            NamedNodeMap attrs = element.getAttributes();
-            int attrsLength = attrs.getLength();
-
-            for (int i = 0; i < attrsLength; i++) {
-                Attr attribute = (Attr) attrs.item(i);
-                String NUri = attribute.getNamespaceURI();
-                String NName = attribute.getLocalName();
-                String NValue = attribute.getValue();
-
-                if (!XMLNS_URI.equals(NUri)) {
-                    // It's not a namespace attr node. Add to the result and continue.
-                    result.add(attribute);
-                } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
-                    // The default mapping for xml must not be output.
-                    Node n = ns.addMappingAndRender(NName, NValue, attribute);
-
-                    if (n != null) {
-                        // Render the ns definition
-                        result.add((Attr)n);
-                        if (C14nHelper.namespaceIsRelative(attribute)) {
-                            Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
-                            throw new CanonicalizationException(
-                                "c14n.Canonicalizer.RelativeNamespace", exArgs
-                            );
-                        }
-                    }
-                }
-            }
-        }
-
-        if (firstCall) {
-            // It is the first node of the subtree
-            // Obtain all the namespaces defined in the parents, and added to the output.
-            ns.getUnrenderedNodes(result);
-            // output the attributes in the xml namespace.
-            xmlattrStack.getXmlnsAttr(result);
-            firstCall = false;
-        }
-
-        return result.iterator();
-    }
-
-    /**
-     * Returns the Attr[]s to be output for the given element.
-     * <br>
-     * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
-     * DOM which has been prepared using
-     * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
-     * org.w3c.dom.Document)}.
-     *
-     * @param element
-     * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
-     */
-    @Override
-    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
-        // result will contain the attrs which have to be output
-        xmlattrStack.push(ns.getLevel());
-        boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
-        final SortedSet<Attr> result = this.result;
-        result.clear();
-
-        if (element.hasAttributes()) {
-            NamedNodeMap attrs = element.getAttributes();
-            int attrsLength = attrs.getLength();
-
-            for (int i = 0; i < attrsLength; i++) {
-                Attr attribute = (Attr) attrs.item(i);
-                String NUri = attribute.getNamespaceURI();
-                String NName = attribute.getLocalName();
-                String NValue = attribute.getValue();
-
-                if (!XMLNS_URI.equals(NUri)) {
-                    //A non namespace definition node.
-                    if (XML_LANG_URI.equals(NUri)) {
-                        if (NName.equals("id")) {
-                            if (isRealVisible) {
-                                // treat xml:id like any other attribute
-                                // (emit it, but don't inherit it)
-                                result.add(attribute);
-                            }
-                        } else {
-                            xmlattrStack.addXmlnsAttr(attribute);
-                        }
-                    } else if (isRealVisible) {
-                        //The node is visible add the attribute to the list of output attributes.
-                        result.add(attribute);
-                    }
-                } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
-                    /* except omit namespace node with local name xml, which defines
-                     * the xml prefix, if its string value is
-                     * http://www.w3.org/XML/1998/namespace.
-                     */
-                    // add the prefix binding to the ns symb table.
-                    if (isVisible(attribute))  {
-                        if (isRealVisible || !ns.removeMappingIfRender(NName)) {
-                            // The xpath select this node output it if needed.
-                            Node n = ns.addMappingAndRender(NName, NValue, attribute);
-                            if (n != null) {
-                                result.add((Attr)n);
-                                if (C14nHelper.namespaceIsRelative(attribute)) {
-                                    Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
-                                    throw new CanonicalizationException(
-                                        "c14n.Canonicalizer.RelativeNamespace", exArgs
-                                    );
-                                }
-                            }
-                        }
-                    } else {
-                        if (isRealVisible && !XMLNS.equals(NName)) {
-                            ns.removeMapping(NName);
-                        } else {
-                            ns.addMapping(NName, NValue, attribute);
-                        }
-                    }
-                }
-            }
-        }
-
-        if (isRealVisible) {
-            //The element is visible, handle the xmlns definition
-            Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
-            Node n = null;
-            if (xmlns == null) {
-                //No xmlns def just get the already defined.
-                n = ns.getMapping(XMLNS);
-            } else if (!isVisible(xmlns)) {
-                //There is a definition but the xmlns is not selected by the xpath.
-                //then xmlns=""
-                n = ns.addMappingAndRender(
-                        XMLNS, "", getNullNode(xmlns.getOwnerDocument()));
-            }
-            //output the xmlns def if needed.
-            if (n != null) {
-                result.add((Attr)n);
-            }
-            //Float all xml:* attributes of the unselected parent elements to this one.
-            xmlattrStack.getXmlnsAttr(result);
-            ns.getUnrenderedNodes(result);
-        }
-
-        return result.iterator();
-    }
-
-    protected void circumventBugIfNeeded(XMLSignatureInput input)
-        throws CanonicalizationException, ParserConfigurationException,
-        IOException, SAXException {
-        if (!input.isNeedsToBeExpanded()) {
-            return;
-        }
-        Document doc = null;
-        if (input.getSubNode() != null) {
-            doc = XMLUtils.getOwnerDocument(input.getSubNode());
-        } else {
-            doc = XMLUtils.getOwnerDocument(input.getNodeSet());
-        }
-        XMLUtils.circumventBug2650(doc);
-    }
-
-    protected void handleParent(Element e, NameSpaceSymbTable ns) {
-        if (!e.hasAttributes() && e.getNamespaceURI() == null) {
-            return;
-        }
-        xmlattrStack.push(-1);
-        NamedNodeMap attrs = e.getAttributes();
-        int attrsLength = attrs.getLength();
-        for (int i = 0; i < attrsLength; i++) {
-            Attr attribute = (Attr) attrs.item(i);
-            String NName = attribute.getLocalName();
-            String NValue = attribute.getNodeValue();
-
-            if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
-                if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
-                    ns.addMapping(NName, NValue, attribute);
-                }
-            } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
-                xmlattrStack.addXmlnsAttr(attribute);
-            }
-        }
-        if (e.getNamespaceURI() != null) {
-            String NName = e.getPrefix();
-            String NValue = e.getNamespaceURI();
-            String Name;
-            if (NName == null || NName.equals("")) {
-                NName = "xmlns";
-                Name = "xmlns";
-            } else {
-                Name = "xmlns:" + NName;
-            }
-            Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
-            n.setValue(NValue);
-            ns.addMapping(NName, NValue, n);
-        }
-    }
-
-    private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
-        String bscheme = null;
-        String bauthority = null;
-        String bpath = "";
-        String bquery = null;
-
-        // pre-parse the baseURI
-        if (baseURI != null) {
-            if (baseURI.endsWith("..")) {
-                baseURI = baseURI + "/";
-            }
-            URI base = new URI(baseURI);
-            bscheme = base.getScheme();
-            bauthority = base.getAuthority();
-            bpath = base.getPath();
-            bquery = base.getQuery();
-        }
-
-        URI r = new URI(relativeURI);
-        String rscheme = r.getScheme();
-        String rauthority = r.getAuthority();
-        String rpath = r.getPath();
-        String rquery = r.getQuery();
-
-        String tscheme, tauthority, tpath, tquery;
-        if (rscheme != null && rscheme.equals(bscheme)) {
-            rscheme = null;
-        }
-        if (rscheme != null) {
-            tscheme = rscheme;
-            tauthority = rauthority;
-            tpath = removeDotSegments(rpath);
-            tquery = rquery;
-        } else {
-            if (rauthority != null) {
-                tauthority = rauthority;
-                tpath = removeDotSegments(rpath);
-                tquery = rquery;
-            } else {
-                if (rpath.length() == 0) {
-                    tpath = bpath;
-                    if (rquery != null) {
-                        tquery = rquery;
-                    } else {
-                        tquery = bquery;
-                    }
-                } else {
-                    if (rpath.startsWith("/")) {
-                        tpath = removeDotSegments(rpath);
-                    } else {
-                        if (bauthority != null && bpath.length() == 0) {
-                            tpath = "/" + rpath;
-                        } else {
-                            int last = bpath.lastIndexOf('/');
-                            if (last == -1) {
-                                tpath = rpath;
-                            } else {
-                                tpath = bpath.substring(0, last+1) + rpath;
-                            }
-                        }
-                        tpath = removeDotSegments(tpath);
-                    }
-                    tquery = rquery;
-                }
-                tauthority = bauthority;
-            }
-            tscheme = bscheme;
-        }
-        return new URI(tscheme, tauthority, tpath, tquery, null).toString();
-    }
-
-    private static String removeDotSegments(String path) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "STEP   OUTPUT BUFFER\t\tINPUT BUFFER");
-        }
-
-        // 1. The input buffer is initialized with the now-appended path
-        // components then replace occurrences of "//" in the input buffer
-        // with "/" until no more occurrences of "//" are in the input buffer.
-        String input = path;
-        while (input.indexOf("//") > -1) {
-            input = input.replaceAll("//", "/");
-        }
-
-        // Initialize the output buffer with the empty string.
-        StringBuilder output = new StringBuilder();
-
-        // If the input buffer starts with a root slash "/" then move this
-        // character to the output buffer.
-        if (input.charAt(0) == '/') {
-            output.append("/");
-            input = input.substring(1);
-        }
-
-        printStep("1 ", output.toString(), input);
-
-        // While the input buffer is not empty, loop as follows
-        while (input.length() != 0) {
-            // 2A. If the input buffer begins with a prefix of "./",
-            // then remove that prefix from the input buffer
-            // else if the input buffer begins with a prefix of "../", then
-            // if also the output does not contain the root slash "/" only,
-            // then move this prefix to the end of the output buffer else
-            // remove that prefix
-            if (input.startsWith("./")) {
-                input = input.substring(2);
-                printStep("2A", output.toString(), input);
-            } else if (input.startsWith("../")) {
-                input = input.substring(3);
-                if (!output.toString().equals("/")) {
-                    output.append("../");
-                }
-                printStep("2A", output.toString(), input);
-                // 2B. if the input buffer begins with a prefix of "/./" or "/.",
-                // where "." is a complete path segment, then replace that prefix
-                // with "/" in the input buffer; otherwise,
-            } else if (input.startsWith("/./")) {
-                input = input.substring(2);
-                printStep("2B", output.toString(), input);
-            } else if (input.equals("/.")) {
-                // FIXME: what is complete path segment?
-                input = input.replaceFirst("/.", "/");
-                printStep("2B", output.toString(), input);
-                // 2C. if the input buffer begins with a prefix of "/../" or "/..",
-                // where ".." is a complete path segment, then replace that prefix
-                // with "/" in the input buffer and if also the output buffer is
-                // empty, last segment in the output buffer equals "../" or "..",
-                // where ".." is a complete path segment, then append ".." or "/.."
-                // for the latter case respectively to the output buffer else
-                // remove the last segment and its preceding "/" (if any) from the
-                // output buffer and if hereby the first character in the output
-                // buffer was removed and it was not the root slash then delete a
-                // leading slash from the input buffer; otherwise,
-            } else if (input.startsWith("/../")) {
-                input = input.substring(3);
-                if (output.length() == 0) {
-                    output.append("/");
-                } else if (output.toString().endsWith("../")) {
-                    output.append("..");
-                } else if (output.toString().endsWith("..")) {
-                    output.append("/..");
-                } else {
-                    int index = output.lastIndexOf("/");
-                    if (index == -1) {
-                        output = new StringBuilder();
-                        if (input.charAt(0) == '/') {
-                            input = input.substring(1);
-                        }
-                    } else {
-                        output = output.delete(index, output.length());
-                    }
-                }
-                printStep("2C", output.toString(), input);
-            } else if (input.equals("/..")) {
-                // FIXME: what is complete path segment?
-                input = input.replaceFirst("/..", "/");
-                if (output.length() == 0) {
-                    output.append("/");
-                } else if (output.toString().endsWith("../")) {
-                    output.append("..");
-                } else if (output.toString().endsWith("..")) {
-                    output.append("/..");
-                } else {
-                    int index = output.lastIndexOf("/");
-                    if (index == -1) {
-                        output = new StringBuilder();
-                        if (input.charAt(0) == '/') {
-                            input = input.substring(1);
-                        }
-                    } else {
-                        output = output.delete(index, output.length());
-                    }
-                }
-                printStep("2C", output.toString(), input);
-                // 2D. if the input buffer consists only of ".", then remove
-                // that from the input buffer else if the input buffer consists
-                // only of ".." and if the output buffer does not contain only
-                // the root slash "/", then move the ".." to the output buffer
-                // else delte it.; otherwise,
-            } else if (input.equals(".")) {
-                input = "";
-                printStep("2D", output.toString(), input);
-            } else if (input.equals("..")) {
-                if (!output.toString().equals("/")) {
-                    output.append("..");
-                }
-                input = "";
-                printStep("2D", output.toString(), input);
-                // 2E. move the first path segment (if any) in the input buffer
-                // to the end of the output buffer, including the initial "/"
-                // character (if any) and any subsequent characters up to, but not
-                // including, the next "/" character or the end of the input buffer.
-            } else {
-                int end = -1;
-                int begin = input.indexOf('/');
-                if (begin == 0) {
-                    end = input.indexOf('/', 1);
-                } else {
-                    end = begin;
-                    begin = 0;
-                }
-                String segment;
-                if (end == -1) {
-                    segment = input.substring(begin);
-                    input = "";
-                } else {
-                    segment = input.substring(begin, end);
-                    input = input.substring(end);
-                }
-                output.append(segment);
-                printStep("2E", output.toString(), input);
-            }
-        }
-
-        // 3. Finally, if the only or last segment of the output buffer is
-        // "..", where ".." is a complete path segment not followed by a slash
-        // then append a slash "/". The output buffer is returned as the result
-        // of remove_dot_segments
-        if (output.toString().endsWith("..")) {
-            output.append("/");
-            printStep("3 ", output.toString(), input);
-        }
-
-        return output.toString();
-    }
-
-    private static void printStep(String step, String output, String input) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, " " + step + ":   " + output);
-            if (output.length() == 0) {
-                log.log(java.util.logging.Level.FINE, "\t\t\t\t" + input);
-            } else {
-                log.log(java.util.logging.Level.FINE, "\t\t\t" + input);
-            }
-        }
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,12 +25,11 @@
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
 /**
- * @author Sean Mullan
  */
-public class Canonicalizer11_OmitComments extends Canonicalizer11 {
+public class Canonicalizer11_OmitComments extends Canonicalizer20010315 {
 
     public Canonicalizer11_OmitComments() {
-        super(false);
+        super(false, true);
     }
 
     public final String engineGetURI() {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,12 +25,11 @@
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
 /**
- * @author Sean Mullan
  */
-public class Canonicalizer11_WithComments extends Canonicalizer11 {
+public class Canonicalizer11_WithComments extends Canonicalizer20010315 {
 
     public Canonicalizer11_WithComments() {
-        super(true);
+        super(true, true);
     }
 
     public final String engineGetURI() {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,11 +23,7 @@
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
+import java.io.OutputStream;
 import java.util.Map;
 import java.util.Set;
 import java.util.SortedSet;
@@ -38,9 +34,9 @@
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
+import org.w3c.dom.DOMException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
@@ -51,97 +47,13 @@
  * Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
  * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
  *
- * @author Christian Geuer-Pollmann <geuerp@apache.org>
  */
 public abstract class Canonicalizer20010315 extends CanonicalizerBase {
-    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
-    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
 
     private boolean firstCall = true;
-    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
-    private static class XmlAttrStack {
-        static class XmlsStackElement {
-            int level;
-            boolean rendered = false;
-            List<Attr> nodes = new ArrayList<Attr>();
-        };
-
-        int currentLevel = 0;
-        int lastlevel = 0;
-        XmlsStackElement cur;
-        List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
-
-        void push(int level) {
-            currentLevel = level;
-            if (currentLevel == -1) {
-                return;
-            }
-            cur = null;
-            while (lastlevel >= currentLevel) {
-                levels.remove(levels.size() - 1);
-                int newSize = levels.size();
-                if (newSize == 0) {
-                    lastlevel = 0;
-                    return;
-                }
-                lastlevel = (levels.get(newSize - 1)).level;
-            }
-        }
-
-        void addXmlnsAttr(Attr n) {
-            if (cur == null) {
-                cur = new XmlsStackElement();
-                cur.level = currentLevel;
-                levels.add(cur);
-                lastlevel = currentLevel;
-            }
-            cur.nodes.add(n);
-        }
-
-        void getXmlnsAttr(Collection<Attr> col) {
-            int size = levels.size() - 1;
-            if (cur == null) {
-                cur = new XmlsStackElement();
-                cur.level = currentLevel;
-                lastlevel = currentLevel;
-                levels.add(cur);
-            }
-            boolean parentRendered = false;
-            XmlsStackElement e = null;
-            if (size == -1) {
-                parentRendered = true;
-            } else {
-                e = levels.get(size);
-                if (e.rendered && e.level + 1 == currentLevel) {
-                    parentRendered = true;
-                }
-            }
-            if (parentRendered) {
-                col.addAll(cur.nodes);
-                cur.rendered = true;
-                return;
-            }
-
-            Map<String, Attr> loa = new HashMap<String, Attr>();
-            for (; size >= 0; size--) {
-                e = levels.get(size);
-                Iterator<Attr> it = e.nodes.iterator();
-                while (it.hasNext()) {
-                    Attr n = it.next();
-                    if (!loa.containsKey(n.getName())) {
-                        loa.put(n.getName(), n);
-                    }
-                }
-            }
-
-            cur.rendered = true;
-            col.addAll(loa.values());
-        }
-
-    }
-
-    private XmlAttrStack xmlattrStack = new XmlAttrStack();
+    private final XmlAttrStack xmlattrStack;
+    private final boolean c14n11;
 
     /**
      * Constructor Canonicalizer20010315
@@ -149,9 +61,22 @@
      * @param includeComments
      */
     public Canonicalizer20010315(boolean includeComments) {
+        this(includeComments, false);
+    }
+
+    /**
+     * Constructor Canonicalizer20010315
+     *
+     * @param includeComments
+     * @param c14n11 Whether this is a Canonical XML 1.1 implementation or not
+     */
+    public Canonicalizer20010315(boolean includeComments, boolean c14n11) {
         super(includeComments);
+        xmlattrStack = new XmlAttrStack(c14n11);
+        this.c14n11 = c14n11;
     }
 
+
     /**
      * Always throws a CanonicalizationException because this is inclusive c14n.
      *
@@ -183,28 +108,44 @@
     }
 
     /**
-     * Returns the Attr[]s to be output for the given element.
+     * Always throws a CanonicalizationException because this is inclusive c14n.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(
+            Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace)
+            throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Output the Attr[]s for the given element.
      * <br>
-     * The code of this method is a copy of {@link #handleAttributes(Element,
-     * NameSpaceSymbTable)},
+     * The code of this method is a copy of {@link #outputAttributes(Element,
+     * NameSpaceSymbTable, Map<String, byte[]>)},
      * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
      * So if the element in question isRoot of c14n, it's parent is not in the
      * node set, as well as all other ancestors.
      *
      * @param element
      * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
+     * @param cache
+     * @throws CanonicalizationException, DOMException, IOException
      */
     @Override
-    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
+    protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
+                                           Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
         if (!element.hasAttributes() && !firstCall) {
-            return null;
+            return;
         }
         // result will contain the attrs which have to be output
-        final SortedSet<Attr> result = this.result;
-        result.clear();
+        SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
         if (element.hasAttributes()) {
             NamedNodeMap attrs = element.getAttributes();
@@ -246,11 +187,15 @@
             firstCall = false;
         }
 
-        return result.iterator();
+        OutputStream writer = getWriter();
+        //we output all Attrs which are available
+        for (Attr attr : result) {
+            outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+        }
     }
 
     /**
-     * Returns the Attr[]s to be output for the given element.
+     * Output the Attr[]s for the given element.
      * <br>
      * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
      * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
@@ -258,17 +203,17 @@
      *
      * @param element
      * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
+     * @param cache
+     * @throws CanonicalizationException, DOMException, IOException
      */
     @Override
-    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
+    protected void outputAttributes(Element element, NameSpaceSymbTable ns,
+                                    Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
         // result will contain the attrs which have to be output
         xmlattrStack.push(ns.getLevel());
         boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
-        final SortedSet<Attr> result = this.result;
-        result.clear();
+        SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
         if (element.hasAttributes()) {
             NamedNodeMap attrs = element.getAttributes();
@@ -283,7 +228,15 @@
                 if (!XMLNS_URI.equals(NUri)) {
                     //A non namespace definition node.
                     if (XML_LANG_URI.equals(NUri)) {
-                        xmlattrStack.addXmlnsAttr(attribute);
+                        if (c14n11 && "id".equals(NName)) {
+                            if (isRealVisible) {
+                                // treat xml:id like any other attribute
+                                // (emit it, but don't inherit it)
+                                result.add(attribute);
+                            }
+                        } else {
+                            xmlattrStack.addXmlnsAttr(attribute);
+                        }
                     } else if (isRealVisible) {
                         //The node is visible add the attribute to the list of output attributes.
                         result.add(attribute);
@@ -339,7 +292,11 @@
             ns.getUnrenderedNodes(result);
         }
 
-        return result.iterator();
+        OutputStream writer = getWriter();
+        //we output all Attrs which are available
+        for (Attr attr : result) {
+            outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+        }
     }
 
     protected void circumventBugIfNeeded(XMLSignatureInput input)
@@ -369,11 +326,12 @@
             String NName = attribute.getLocalName();
             String NValue = attribute.getNodeValue();
 
-            if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
-                if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
+            if (XMLNS_URI.equals(attribute.getNamespaceURI())) {
+                if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
                     ns.addMapping(NName, NValue, attribute);
                 }
-            } else if (XML_LANG_URI.equals(attribute.getNamespaceURI())) {
+            } else if (XML_LANG_URI.equals(attribute.getNamespaceURI())
+                && (!c14n11 || c14n11 && !"id".equals(NName))) {
                 xmlattrStack.addXmlnsAttr(attribute);
             }
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,7 +23,8 @@
 package com.sun.org.apache.xml.internal.security.c14n.implementations;
 
 import java.io.IOException;
-import java.util.Iterator;
+import java.io.OutputStream;
+import java.util.Map;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
@@ -33,9 +34,9 @@
 import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
+import org.w3c.dom.DOMException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
@@ -45,31 +46,25 @@
 /**
  * Implements &quot; <A
  * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
- * Canonicalization, Version 1.0 </A>&quot; <BR />
+ * Canonicalization, Version 1.0 </A>&quot; <p></p>
  * Credits: During restructuring of the Canonicalizer framework, Ren??
  * Kollmorgen from Software AG submitted an implementation of ExclC14n which
  * fitted into the old architecture and which based heavily on my old (and slow)
  * implementation of "Canonical XML". A big "thank you" to Ren?? for this.
- * <BR />
+ * <p></p>
  * <i>THIS </i> implementation is a complete rewrite of the algorithm.
  *
- * @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1147448 $
- * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
- *          XML Canonicalization, Version 1.0</a>
+ * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">
+ *          Exclusive XML Canonicalization, Version 1.0</a>
  */
 public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
 
-    private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
-    private static final String XMLNS_URI = Constants.NamespaceSpecNS;
-
     /**
-      * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
-      * the inclusive namespaces.
-      */
+     * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
+     * the inclusive namespaces.
+     */
     private SortedSet<String> inclusiveNSSet;
-
-    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+    private boolean propagateDefaultNamespace = false;
 
     /**
      * Constructor Canonicalizer20010315Excl
@@ -82,7 +77,7 @@
 
     /**
      * Method engineCanonicalizeSubTree
-     * @inheritDoc
+     * {@inheritDoc}
      * @param rootNode
      *
      * @throws CanonicalizationException
@@ -94,7 +89,7 @@
 
     /**
      * Method engineCanonicalizeSubTree
-     *  @inheritDoc
+     *  {@inheritDoc}
      * @param rootNode
      * @param inclusiveNamespaces
      *
@@ -108,6 +103,22 @@
 
     /**
      * Method engineCanonicalizeSubTree
+     *  {@inheritDoc}
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element
+     *
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(
+            Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace
+    ) throws CanonicalizationException {
+        this.propagateDefaultNamespace = propagateDefaultNamespace;
+        return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null);
+    }
+
+    /**
+     * Method engineCanonicalizeSubTree
      * @param rootNode
      * @param inclusiveNamespaces
      * @param excl A element to exclude from the c14n process.
@@ -137,7 +148,7 @@
 
     /**
      * Method engineCanonicalizeXPathNodeSet
-     * @inheritDoc
+     * {@inheritDoc}
      * @param xpathNodeSet
      * @param inclusiveNamespaces
      * @throws CanonicalizationException
@@ -150,11 +161,11 @@
     }
 
     @Override
-    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
+    protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
+                                           Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
         // result will contain the attrs which have to be output
-        final SortedSet<Attr> result = this.result;
-        result.clear();
+        SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
         // The prefix visibly utilized (in the attribute or in the name) in
         // the element
@@ -193,6 +204,13 @@
                 }
             }
         }
+        if (propagateDefaultNamespace && ns.getLevel() == 1 &&
+                inclusiveNSSet.contains(XMLNS) &&
+                ns.getMappingWithoutRendered(XMLNS) == null) {
+                ns.removeMapping(XMLNS);
+                ns.addMapping(
+                    XMLNS, "", getNullNode(element.getOwnerDocument()));
+        }
         String prefix = null;
         if (element.getNamespaceURI() != null
             && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
@@ -209,20 +227,22 @@
             }
         }
 
-        return result.iterator();
+        OutputStream writer = getWriter();
+        //we output all Attrs which are available
+        for (Attr attr : result) {
+            outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+        }
     }
 
     /**
-     * @inheritDoc
-     * @param element
-     * @throws CanonicalizationException
+     * {@inheritDoc}
      */
     @Override
-    protected final Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
+    protected void outputAttributes(Element element, NameSpaceSymbTable ns,
+                                    Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
         // result will contain the attrs which have to be output
-        final SortedSet<Attr> result = this.result;
-        result.clear();
+        SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
         // The prefix visibly utilized (in the attribute or in the name) in
         // the element
@@ -312,7 +332,11 @@
             }
         }
 
-        return result.iterator();
+        OutputStream writer = getWriter();
+        //we output all Attrs which are available
+        for (Attr attr : result) {
+            outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+        }
     }
 
     protected void circumventBugIfNeeded(XMLSignatureInput input)
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,12 +33,12 @@
         super(false);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String engineGetURI() {
         return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final boolean engineGetIncludeComments() {
         return false;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -37,12 +37,12 @@
         super(true);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String engineGetURI() {
         return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final boolean engineGetIncludeComments() {
         return true;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
 /**
- * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 {
 
@@ -37,12 +36,12 @@
         super(false);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String engineGetURI() {
         return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final boolean engineGetIncludeComments() {
         return false;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 
 /**
- * @author Christian Geuer-Pollmann
  */
 public class Canonicalizer20010315WithComments extends Canonicalizer20010315 {
 
@@ -36,12 +35,12 @@
         super(true);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String engineGetURI() {
         return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final boolean engineGetIncludeComments() {
         return true;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java	Tue Jun 19 16:33:07 2018 +0100
@@ -46,8 +46,9 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Comment;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Document;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.w3c.dom.ProcessingInstruction;
@@ -55,12 +56,14 @@
 
 /**
  * Abstract base class for canonicalization algorithms.
- *
- * @author Christian Geuer-Pollmann <geuerp@apache.org>
+ * Please note that these implementations are NOT thread safe - please see the following JIRA for more information:
+ * https://issues.apache.org/jira/browse/SANTUARIO-463
  */
 public abstract class CanonicalizerBase extends CanonicalizerSpi {
     public static final String XML = "xml";
     public static final String XMLNS = "xmlns";
+    public static final String XMLNS_URI = Constants.NamespaceSpecNS;
+    public static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
 
     protected static final AttrCompare COMPARE = new AttrCompare();
 
@@ -96,9 +99,9 @@
     private Node excludeNode;
     private OutputStream writer = new ByteArrayOutputStream();
 
-    /**
-     * The null xmlns definition.
-     */
+   /**
+    * The null xmlns definition.
+    */
     private Attr nullNode;
 
     /**
@@ -112,7 +115,7 @@
 
     /**
      * Method engineCanonicalizeSubTree
-     * @inheritDoc
+     * {@inheritDoc}
      * @param rootNode
      * @throws CanonicalizationException
      */
@@ -123,7 +126,7 @@
 
     /**
      * Method engineCanonicalizeXPathNodeSet
-     * @inheritDoc
+     * {@inheritDoc}
      * @param xpathNodeSet
      * @throws CanonicalizationException
      */
@@ -161,14 +164,12 @@
                 }
             }
             return null;
-        } catch (CanonicalizationException ex) {
-            throw new CanonicalizationException("empty", ex);
         } catch (ParserConfigurationException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         } catch (IOException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         } catch (SAXException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         }
     }
 
@@ -179,6 +180,10 @@
         this.writer = writer;
     }
 
+    protected OutputStream getWriter() {
+        return writer;
+    }
+
     /**
      * Canonicalizes a Subtree node.
      *
@@ -224,9 +229,9 @@
             return null;
 
         } catch (UnsupportedEncodingException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         } catch (IOException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         }
     }
 
@@ -243,7 +248,7 @@
     protected final void canonicalizeSubTree(
         Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel
     ) throws CanonicalizationException, IOException {
-        if (isVisibleInt(currentNode) == -1) {
+        if (currentNode == null || isVisibleInt(currentNode) == -1) {
             return;
         }
         Node sibling = null;
@@ -251,7 +256,7 @@
         final OutputStream writer = this.writer;
         final Node excludeNode = this.excludeNode;
         final boolean includeComments = this.includeComments;
-        Map<String, byte[]> cache = new HashMap<String, byte[]>();
+        Map<String, byte[]> cache = new HashMap<>();
         do {
             switch (currentNode.getNodeType()) {
 
@@ -259,7 +264,8 @@
             case Node.NOTATION_NODE :
             case Node.ATTRIBUTE_NODE :
                 // illegal node type during traversal
-                throw new CanonicalizationException("empty");
+                throw new CanonicalizationException("empty",
+                                                    new Object[]{"illegal node type during traversal"});
 
             case Node.DOCUMENT_FRAGMENT_NODE :
             case Node.DOCUMENT_NODE :
@@ -294,14 +300,8 @@
                 String name = currentElement.getTagName();
                 UtfHelpper.writeByte(name, writer, cache);
 
-                Iterator<Attr> attrs = this.handleAttributesSubtree(currentElement, ns);
-                if (attrs != null) {
-                    //we output all Attrs which are available
-                    while (attrs.hasNext()) {
-                        Attr attr = attrs.next();
-                        outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
-                    }
-                }
+                outputAttributesSubtree(currentElement, ns, cache);
+
                 writer.write('>');
                 sibling = currentNode.getFirstChild();
                 if (sibling == null) {
@@ -373,9 +373,9 @@
             }
             return null;
         } catch (UnsupportedEncodingException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         } catch (IOException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         }
     }
 
@@ -403,9 +403,8 @@
         }
         Node sibling = null;
         Node parentNode = null;
-        OutputStream writer = this.writer;
         int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
-        Map<String, byte[]> cache = new HashMap<String, byte[]>();
+        Map<String, byte[]> cache = new HashMap<>();
         do {
             switch (currentNode.getNodeType()) {
 
@@ -413,7 +412,8 @@
             case Node.NOTATION_NODE :
             case Node.ATTRIBUTE_NODE :
                 // illegal node type during traversal
-                throw new CanonicalizationException("empty");
+                throw new CanonicalizationException("empty",
+                                                    new Object[]{"illegal node type during traversal"});
 
             case Node.DOCUMENT_FRAGMENT_NODE :
             case Node.DOCUMENT_NODE :
@@ -422,7 +422,7 @@
                 break;
 
             case Node.COMMENT_NODE :
-                if (this.includeComments && (isVisibleDO(currentNode, ns.getLevel()) == 1)) {
+                if (this.includeComments && isVisibleDO(currentNode, ns.getLevel()) == 1) {
                     outputCommentToWriter((Comment) currentNode, writer, documentLevel);
                 }
                 break;
@@ -438,8 +438,8 @@
                 if (isVisible(currentNode)) {
                     outputTextToWriter(currentNode.getNodeValue(), writer);
                     for (Node nextSibling = currentNode.getNextSibling();
-                        (nextSibling != null) && ((nextSibling.getNodeType() == Node.TEXT_NODE)
-                            || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE));
+                        nextSibling != null && (nextSibling.getNodeType() == Node.TEXT_NODE
+                            || nextSibling.getNodeType() == Node.CDATA_SECTION_NODE);
                         nextSibling = nextSibling.getNextSibling()) {
                         outputTextToWriter(nextSibling.getNodeValue(), writer);
                         currentNode = nextSibling;
@@ -458,7 +458,7 @@
                     sibling = currentNode.getNextSibling();
                     break;
                 }
-                currentNodeIsVisible = (i == 1);
+                currentNodeIsVisible = i == 1;
                 if (currentNodeIsVisible) {
                     ns.outputNodePush();
                     writer.write('<');
@@ -468,14 +468,8 @@
                     ns.push();
                 }
 
-                Iterator<Attr> attrs = handleAttributes(currentElement,ns);
-                if (attrs != null) {
-                    //we output all Attrs which are available
-                    while (attrs.hasNext()) {
-                        Attr attr = attrs.next();
-                        outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
-                    }
-                }
+                outputAttributes(currentElement, ns, cache);
+
                 if (currentNodeIsVisible) {
                     writer.write('>');
                 }
@@ -535,13 +529,13 @@
         if (nodeFilter != null) {
             Iterator<NodeFilter> it = nodeFilter.iterator();
             while (it.hasNext()) {
-                int i = (it.next()).isNodeIncludeDO(currentNode, level);
+                int i = it.next().isNodeIncludeDO(currentNode, level);
                 if (i != 1) {
                     return i;
                 }
             }
         }
-        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+        if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) {
             return 0;
         }
         return 1;
@@ -551,13 +545,13 @@
         if (nodeFilter != null) {
             Iterator<NodeFilter> it = nodeFilter.iterator();
             while (it.hasNext()) {
-                int i = (it.next()).isNodeInclude(currentNode);
+                int i = it.next().isNodeInclude(currentNode);
                 if (i != 1) {
                     return i;
                 }
             }
         }
-        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+        if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) {
             return 0;
         }
         return 1;
@@ -572,7 +566,7 @@
                 }
             }
         }
-        if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+        if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) {
             return false;
         }
         return true;
@@ -621,7 +615,7 @@
             return;
         }
         //Obtain all the parents of the element
-        List<Element> parents = new ArrayList<Element>();
+        List<Element> parents = new ArrayList<>();
         Node parent = n1;
         while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
             parents.add((Element)parent);
@@ -634,35 +628,34 @@
             handleParent(ele, ns);
         }
         parents.clear();
-        Attr nsprefix;
-        if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
-                && "".equals(nsprefix.getValue())) {
+        Attr nsprefix = ns.getMappingWithoutRendered(XMLNS);
+        if (nsprefix != null && "".equals(nsprefix.getValue())) {
             ns.addMappingAndRender(
                     XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
         }
     }
 
     /**
-     * Obtain the attributes to output for this node in XPathNodeSet c14n.
+     * Output the attributes for this node in XPathNodeSet c14n.
      *
      * @param element
      * @param ns
-     * @return the attributes nodes to output.
-     * @throws CanonicalizationException
+     * @param cache
+     * @throws CanonicalizationException, DOMException, IOException
      */
-    abstract Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException;
+    abstract void outputAttributes(Element element, NameSpaceSymbTable ns, Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException;
 
     /**
-     * Obtain the attributes to output for this node in a Subtree c14n.
+     * Output the attributes for this node in a Subtree c14n.
      *
      * @param element
      * @param ns
-     * @return the attributes nodes to output.
-     * @throws CanonicalizationException
+     * @param cache
+     * @throws CanonicalizationException, DOMException, IOException
      */
-    abstract Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException;
+    abstract void outputAttributesSubtree(Element element, NameSpaceSymbTable ns, Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException;
 
     abstract void circumventBugIfNeeded(XMLSignatureInput input)
         throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
@@ -672,13 +665,13 @@
      *
      * The string value of the node is modified by replacing
      * <UL>
-     * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
-     * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
-     * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
-     * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
+     * <LI>all ampersands with {@code &amp;amp;}</LI>
+     * <LI>all open angle brackets with {@code &amp;lt;}</LI>
+     * <LI>all quotation mark characters with {@code &amp;quot;}</LI>
+     * <LI>and the whitespace characters {@code #x9}, #xA, and #xD, with character
      * references. The character references are written in uppercase
-     * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
-     * by the character reference <CODE>&amp;#xD;</CODE>)</LI>
+     * hexadecimal with no leading zeroes (for example, {@code #xD} is represented
+     * by the character reference {@code &amp;#xD;})</LI>
      * </UL>
      *
      * @param name
@@ -697,7 +690,8 @@
         final int length = value.length();
         int i = 0;
         while (i < length) {
-            char c = value.charAt(i++);
+            int c = value.codePointAt(i);
+            i += Character.charCount(c);
 
             switch (c) {
 
@@ -729,7 +723,7 @@
                 if (c < 0x80) {
                     writer.write(c);
                 } else {
-                    UtfHelpper.writeCharToUtf8(c, writer);
+                    UtfHelpper.writeCodePointToUtf8(c, writer);
                 }
                 continue;
             }
@@ -757,15 +751,16 @@
         final String target = currentPI.getTarget();
         int length = target.length();
 
-        for (int i = 0; i < length; i++) {
-            char c = target.charAt(i);
+        for (int i = 0; i < length; ) {
+            int c = target.codePointAt(i);
+            i += Character.charCount(c);
             if (c == 0x0D) {
                 writer.write(XD.clone());
             } else {
                 if (c < 0x80) {
                     writer.write(c);
                 } else {
-                    UtfHelpper.writeCharToUtf8(c, writer);
+                    UtfHelpper.writeCodePointToUtf8(c, writer);
                 }
             }
         }
@@ -777,12 +772,13 @@
         if (length > 0) {
             writer.write(' ');
 
-            for (int i = 0; i < length; i++) {
-                char c = data.charAt(i);
+            for (int i = 0; i < length; ) {
+                int c = data.codePointAt(i);
+                i += Character.charCount(c);
                 if (c == 0x0D) {
                     writer.write(XD.clone());
                 } else {
-                    UtfHelpper.writeCharToUtf8(c, writer);
+                    UtfHelpper.writeCodePointToUtf8(c, writer);
                 }
             }
         }
@@ -811,15 +807,16 @@
         final String data = currentComment.getData();
         final int length = data.length();
 
-        for (int i = 0; i < length; i++) {
-            char c = data.charAt(i);
+        for (int i = 0; i < length; ) {
+            int c = data.codePointAt(i);
+            i += Character.charCount(c);
             if (c == 0x0D) {
                 writer.write(XD.clone());
             } else {
                 if (c < 0x80) {
                     writer.write(c);
                 } else {
-                    UtfHelpper.writeCharToUtf8(c, writer);
+                    UtfHelpper.writeCodePointToUtf8(c, writer);
                 }
             }
         }
@@ -842,8 +839,9 @@
     ) throws IOException {
         final int length = text.length();
         byte[] toWrite;
-        for (int i = 0; i < length; i++) {
-            char c = text.charAt(i);
+        for (int i = 0; i < length; ) {
+            int c = text.codePointAt(i);
+            i += Character.charCount(c);
 
             switch (c) {
 
@@ -867,7 +865,7 @@
                 if (c < 0x80) {
                     writer.write(c);
                 } else {
-                    UtfHelpper.writeCharToUtf8(c, writer);
+                    UtfHelpper.writeCodePointToUtf8(c, writer);
                 }
                 continue;
             }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,7 +24,7 @@
 
 import java.io.IOException;
 import java.io.OutputStream;
-import java.util.Iterator;
+import java.util.Map;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
@@ -36,6 +36,7 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Comment;
+import org.w3c.dom.DOMException;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
@@ -54,8 +55,6 @@
  */
 public class CanonicalizerPhysical extends CanonicalizerBase {
 
-    private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
-
     /**
      * Constructor Canonicalizer20010315
      */
@@ -94,31 +93,43 @@
     }
 
     /**
-     * Returns the Attr[]s to be output for the given element.
+     * Always throws a CanonicalizationException.
+     *
+     * @param rootNode
+     * @param inclusiveNamespaces
+     * @return none it always fails
+     * @throws CanonicalizationException
+     */
+    public byte[] engineCanonicalizeSubTree(
+            Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace)
+            throws CanonicalizationException {
+
+        /** $todo$ well, should we throw UnsupportedOperationException ? */
+        throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+    }
+
+    /**
+     * Output the Attr[]s for the given element.
      * <br>
-     * The code of this method is a copy of {@link #handleAttributes(Element,
-     * NameSpaceSymbTable)},
+     * The code of this method is a copy of {@link #outputAttributes(Element,
+     * NameSpaceSymbTable, Map<String, byte[]>)},
      * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
      * So if the element in question isRoot of c14n, it's parent is not in the
      * node set, as well as all other ancestors.
      *
      * @param element
      * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
+     * @param cache
+     * @throws CanonicalizationException, DOMException, IOException
      */
     @Override
-    protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
-        if (!element.hasAttributes()) {
-            return null;
-        }
+    protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
+                                           Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
+        if (element.hasAttributes()) {
+            // result will contain all the attrs declared directly on that element
+            SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
 
-        // result will contain all the attrs declared directly on that element
-        final SortedSet<Attr> result = this.result;
-        result.clear();
-
-        if (element.hasAttributes()) {
             NamedNodeMap attrs = element.getAttributes();
             int attrsLength = attrs.getLength();
 
@@ -126,22 +137,19 @@
                 Attr attribute = (Attr) attrs.item(i);
                 result.add(attribute);
             }
+
+            OutputStream writer = getWriter();
+            //we output all Attrs which are available
+            for (Attr attr : result) {
+                outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+            }
         }
-
-        return result.iterator();
     }
 
-    /**
-     * Returns the Attr[]s to be output for the given element.
-     *
-     * @param element
-     * @param ns
-     * @return the Attr[]s to be output
-     * @throws CanonicalizationException
-     */
     @Override
-    protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
-        throws CanonicalizationException {
+    protected void outputAttributes(Element element, NameSpaceSymbTable ns,
+                                    Map<String, byte[]> cache)
+        throws CanonicalizationException, DOMException, IOException {
 
         /** $todo$ well, should we throw UnsupportedOperationException ? */
         throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
@@ -157,12 +165,12 @@
         // nothing to do
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String engineGetURI() {
         return Canonicalizer.ALGO_ID_C14N_PHYSICAL;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final boolean engineGetIncludeComments() {
         return true;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,7 +35,6 @@
  * A stack based Symbol Table.
  *<br>For speed reasons all the symbols are introduced in the same map,
  * and at the same time in a list so it can be removed when the frame is pop back.
- * @author Raul Benito
  */
 public class NameSpaceSymbTable {
 
@@ -59,7 +58,7 @@
      * Default constractor
      **/
     public NameSpaceSymbTable() {
-        level = new ArrayList<SymbMap>();
+        level = new ArrayList<>();
         //Insert the default binding for xmlns.
         symb = (SymbMap) initialMap.clone();
     }
@@ -74,7 +73,7 @@
         while (it.hasNext()) {
             NameSpaceSymbEntry n = it.next();
             //put them rendered?
-            if ((!n.rendered) && (n.n != null)) {
+            if (!n.rendered && n.n != null) {
                 n = (NameSpaceSymbEntry) n.clone();
                 needsClone();
                 symb.put(n.prefix, n);
@@ -123,7 +122,7 @@
             if (size == 0) {
                 cloned = false;
             } else {
-                cloned = (level.get(size - 1) != symb);
+                cloned = level.get(size - 1) != symb;
             }
         } else {
             cloned = false;
@@ -191,7 +190,7 @@
      **/
     public boolean addMapping(String prefix, String uri, Attr n) {
         NameSpaceSymbEntry ob = symb.get(prefix);
-        if ((ob != null) && uri.equals(ob.uri)) {
+        if (ob != null && uri.equals(ob.uri)) {
             //If we have it previously defined. Don't keep working.
             return false;
         }
@@ -203,7 +202,7 @@
             //We have a previous definition store it for the pop.
             //Check if a previous definition(not the inmidiatly one) has been rendered.
             ne.lastrendered = ob.lastrendered;
-            if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
+            if (ob.lastrendered != null && ob.lastrendered.equals(uri)) {
                 //Yes it is. Mark as rendered.
                 ne.rendered = true;
             }
@@ -222,7 +221,7 @@
     public Node addMappingAndRender(String prefix, String uri, Attr n) {
         NameSpaceSymbEntry ob = symb.get(prefix);
 
-        if ((ob != null) && uri.equals(ob.uri)) {
+        if (ob != null && uri.equals(ob.uri)) {
             if (!ob.rendered) {
                 ob = (NameSpaceSymbEntry) ob.clone();
                 needsClone();
@@ -234,11 +233,11 @@
             return null;
         }
 
-        NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix);
+        NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, true, prefix);
         ne.lastrendered = uri;
         needsClone();
         symb.put(prefix, ne);
-        if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
+        if (ob != null && ob.lastrendered != null && ob.lastrendered.equals(uri)) {
             ne.rendered = true;
             return null;
         }
@@ -304,7 +303,7 @@
         this.prefix = prefix;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public Object clone() {
         try {
             return super.clone();
@@ -312,7 +311,7 @@
             return null;
         }
     }
-};
+}
 
 class SymbMap implements Cloneable {
     int free = 23;
@@ -329,7 +328,7 @@
         Object oldKey = keys[index];
         keys[index] = key;
         entries[index] = value;
-        if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) {
+        if ((oldKey == null || !oldKey.equals(key)) && --free == 0) {
             free = entries.length;
             int newCapacity = free << 2;
             rehash(newCapacity);
@@ -337,9 +336,9 @@
     }
 
     List<NameSpaceSymbEntry> entrySet() {
-        List<NameSpaceSymbEntry> a = new ArrayList<NameSpaceSymbEntry>();
+        List<NameSpaceSymbEntry> a = new ArrayList<>();
         for (int i = 0;i < entries.length;i++) {
-            if ((entries[i] != null) && !("".equals(entries[i].uri))) {
+            if (entries[i] != null && !"".equals(entries[i].uri)) {
                 a.add(entries[i]);
             }
         }
@@ -353,21 +352,21 @@
         int index = (obj.hashCode() & 0x7fffffff) % length;
         Object cur = set[index];
 
-        if (cur == null || (cur.equals(obj))) {
+        if (cur == null || cur.equals(obj)) {
             return index;
         }
         length--;
         do {
             index = index == length ? 0 : ++index;
             cur = set[index];
-        } while (cur != null && (!cur.equals(obj)));
+        } while (cur != null && !cur.equals(obj));
         return index;
     }
 
     /**
      * rehashes the map to the new capacity.
      *
-     * @param newCapacity an <code>int</code> value
+     * @param newCapacity an {@code int} value
      */
     protected void rehash(int newCapacity) {
         int oldCapacity = keys.length;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,11 +24,27 @@
 
 import java.io.IOException;
 import java.io.OutputStream;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.Map;
 
-public class UtfHelpper {
+public final class UtfHelpper {
 
-    static final void writeByte(
+    /**
+     * Revert to the old behavior (version 2 or before), i.e. surrogate pairs characters becomes
+     * '??' in output. Set system property com.sun.org.apache.xml.internal.security.c14n.oldUtf8=true if you want
+     * to verify signatures generated by version 2 or before that contains 32 bit chars in the
+     * XML document.
+     */
+    private static final boolean OLD_UTF8 =
+        AccessController.doPrivileged((PrivilegedAction<Boolean>)
+            () -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.c14n.oldUtf8"));
+
+    private UtfHelpper() {
+        // complete
+    }
+
+    public static void writeByte(
         final String str,
         final OutputStream out,
         Map<String, byte[]> cache
@@ -42,12 +58,73 @@
         out.write(result);
     }
 
-    static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException {
+    public static void writeCodePointToUtf8(final int c, final OutputStream out) throws IOException {
+        if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
+            // valid code point: c >= 0x0000 && c <= 0x10FFFF
+            out.write(0x3f);
+            return;
+        }
+        if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
+            // version 2 or before output 2 question mark characters for 32 bit chars
+            out.write(0x3f);
+            out.write(0x3f);
+            return;
+        }
+
+        if (c < 0x80) {
+            // 0x00000000 - 0x0000007F
+            // 0xxxxxxx
+            out.write(c);
+            return;
+        }
+        byte extraByte = 0;
+        if (c < 0x800) {
+            // 0x00000080 - 0x000007FF
+            // 110xxxxx 10xxxxxx
+            extraByte = 1;
+        } else if (c < 0x10000) {
+            // 0x00000800 - 0x0000FFFF
+            // 1110xxxx 10xxxxxx 10xxxxxx
+            extraByte = 2;
+        } else if (c < 0x200000) {
+            // 0x00010000 - 0x001FFFFF
+            // 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
+            extraByte = 3;
+        } else if (c < 0x4000000) {
+            // 0x00200000 - 0x03FFFFFF
+            // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+            // already outside valid Character range, just for completeness
+            extraByte = 4;
+        } else if (c <= 0x7FFFFFFF) {
+            // 0x04000000 - 0x7FFFFFFF
+            // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+            // already outside valid Character range, just for completeness
+            extraByte = 5;
+        } else {
+            // 0x80000000 - 0xFFFFFFFF
+            // case not possible as java has no unsigned int
+            out.write(0x3f);
+            return;
+        }
+
+        byte write;
+        int shift = 6 * extraByte;
+        write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
+        out.write(write);
+        for (int i = extraByte - 1; i >= 0; i--) {
+            shift -= 6;
+            write = (byte)(0x80 | ((c >>> shift) & 0x3F));
+            out.write(write);
+        }
+    }
+
+    @Deprecated
+    public static void writeCharToUtf8(final char c, final OutputStream out) throws IOException {
         if (c < 0x80) {
             out.write(c);
             return;
         }
-        if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
+        if (c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
             //No Surrogates in sun java
             out.write(0x3f);
             return;
@@ -59,7 +136,7 @@
             ch = (char)(c>>>12);
             write = 0xE0;
             if (ch > 0) {
-                write |= (ch & 0x0F);
+                write |= ch & 0x0F;
             }
             out.write(write);
             write = 0x80;
@@ -70,104 +147,149 @@
         }
         ch = (char)(c>>>6);
         if (ch > 0) {
-            write |= (ch & bias);
+            write |= ch & bias;
         }
         out.write(write);
         out.write(0x80 | ((c) & 0x3F));
 
     }
 
-    static final void writeStringToUtf8(
-        final String str,
-        final OutputStream out
-    ) throws IOException{
+    public static void writeStringToUtf8(
+        final String str, final OutputStream out
+    ) throws IOException {
         final int length = str.length();
         int i = 0;
-        char c;
+        int c;
         while (i < length) {
-            c = str.charAt(i++);
+            c = str.codePointAt(i);
+            i += Character.charCount(c);
+            if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
+                // valid code point: c >= 0x0000 && c <= 0x10FFFF
+                out.write(0x3f);
+                continue;
+            }
+            if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
+                // version 2 or before output 2 question mark characters for 32 bit chars
+                out.write(0x3f);
+                out.write(0x3f);
+                continue;
+            }
             if (c < 0x80)  {
                 out.write(c);
                 continue;
             }
-            if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
-                //No Surrogates in sun java
+            byte extraByte = 0;
+            if (c < 0x800) {
+                // 0x00000080 - 0x000007FF
+                // 110xxxxx 10xxxxxx
+                extraByte = 1;
+            } else if (c < 0x10000) {
+                // 0x00000800 - 0x0000FFFF
+                // 1110xxxx 10xxxxxx 10xxxxxx
+                extraByte = 2;
+            } else if (c < 0x200000) {
+                // 0x00010000 - 0x001FFFFF
+                // 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
+                extraByte = 3;
+            } else if (c < 0x4000000) {
+                // 0x00200000 - 0x03FFFFFF
+                // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+                // already outside valid Character range, just for completeness
+                extraByte = 4;
+            } else if (c <= 0x7FFFFFFF) {
+                // 0x04000000 - 0x7FFFFFFF
+                // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+                // already outside valid Character range, just for completeness
+                extraByte = 5;
+            } else {
+                // 0x80000000 - 0xFFFFFFFF
+                // case not possible as java has no unsigned int
                 out.write(0x3f);
                 continue;
             }
-            char ch;
-            int bias;
-            int write;
-            if (c > 0x07FF) {
-                ch = (char)(c>>>12);
-                write = 0xE0;
-                if (ch > 0) {
-                    write |= (ch & 0x0F);
-                }
+            byte write;
+            int shift = 6 * extraByte;
+            write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
+            out.write(write);
+            for (int j = extraByte - 1; j >= 0; j--) {
+                shift -= 6;
+                write = (byte)(0x80 | ((c >>> shift) & 0x3F));
                 out.write(write);
-                write = 0x80;
-                bias = 0x3F;
-            } else {
-                write = 0xC0;
-                bias = 0x1F;
             }
-            ch = (char)(c>>>6);
-            if (ch > 0) {
-                write |= (ch & bias);
-            }
-            out.write(write);
-            out.write(0x80 | ((c) & 0x3F));
 
         }
 
     }
 
-    public static final byte[] getStringInUtf8(final String str) {
+    public static byte[] getStringInUtf8(final String str) {
         final int length = str.length();
         boolean expanded = false;
         byte[] result = new byte[length];
         int i = 0;
         int out = 0;
-        char c;
+        int c;
         while (i < length) {
-            c = str.charAt(i++);
+            c = str.codePointAt(i);
+            i += Character.charCount(c);
+            if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
+                // valid code point: c >= 0x0000 && c <= 0x10FFFF
+                result[out++] = (byte)0x3f;
+                continue;
+            }
+            if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
+                // version 2 or before output 2 question mark characters for 32 bit chars
+                result[out++] = (byte)0x3f;
+                result[out++] = (byte)0x3f;
+                continue;
+            }
             if (c < 0x80) {
                 result[out++] = (byte)c;
                 continue;
             }
-            if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
-                //No Surrogates in sun java
-                result[out++] = 0x3f;
-                continue;
-            }
             if (!expanded) {
-                byte newResult[] = new byte[3*length];
+                byte newResult[] = new byte[6*length];
                 System.arraycopy(result, 0, newResult, 0, out);
                 result = newResult;
                 expanded = true;
             }
-            char ch;
-            int bias;
+            byte extraByte = 0;
+            if (c < 0x800) {
+                // 0x00000080 - 0x000007FF
+                // 110xxxxx 10xxxxxx
+                extraByte = 1;
+            } else if (c < 0x10000) {
+                // 0x00000800 - 0x0000FFFF
+                // 1110xxxx 10xxxxxx 10xxxxxx
+                extraByte = 2;
+            } else if (c < 0x200000) {
+                // 0x00010000 - 0x001FFFFF
+                // 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
+                extraByte = 3;
+            } else if (c < 0x4000000) {
+                // 0x00200000 - 0x03FFFFFF
+                // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+                // already outside valid Character range, just for completeness
+                extraByte = 4;
+            } else if (c <= 0x7FFFFFFF) {
+                // 0x04000000 - 0x7FFFFFFF
+                // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+                // already outside valid Character range, just for completeness
+                extraByte = 5;
+            } else {
+                // 0x80000000 - 0xFFFFFFFF
+                // case not possible as java has no unsigned int
+                result[out++] = 0x3f;
+                continue;
+            }
             byte write;
-            if (c > 0x07FF) {
-                ch = (char)(c>>>12);
-                write = (byte)0xE0;
-                if (ch > 0) {
-                    write |= (ch & 0x0F);
-                }
+            int shift = 6 * extraByte;
+            write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
+            result[out++] = write;
+            for (int j = extraByte - 1; j >= 0; j--) {
+                shift -= 6;
+                write = (byte)(0x80 | ((c >>> shift) & 0x3F));
                 result[out++] = write;
-                write = (byte)0x80;
-                bias = 0x3F;
-            } else {
-                write = (byte)0xC0;
-                bias = 0x1F;
             }
-            ch = (char)(c>>>6);
-            if (ch > 0) {
-                write |= (ch & bias);
-            }
-            result[out++] = write;
-            result[out++] = (byte)(0x80 | ((c) & 0x3F));
         }
         if (expanded) {
             byte newResult[] = new byte[out];
@@ -176,5 +298,4 @@
         }
         return result;
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/XmlAttrStack.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,412 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.c14n.implementations;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.w3c.dom.Attr;
+
+/**
+ * An XmlAttrStack that is shared between the Canonical XML 1.0 and 1.1 implementations.
+ */
+class XmlAttrStack {
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XmlAttrStack.class);
+
+    static class XmlsStackElement {
+        int level;
+        boolean rendered = false;
+        List<Attr> nodes = new ArrayList<>();
+    }
+
+    private int currentLevel = 0;
+    private int lastlevel = 0;
+    private XmlsStackElement cur;
+    private List<XmlsStackElement> levels = new ArrayList<>();
+    private boolean c14n11;
+
+    public XmlAttrStack(boolean c14n11) {
+        this.c14n11 = c14n11;
+    }
+
+    void push(int level) {
+        currentLevel = level;
+        if (currentLevel == -1) {
+            return;
+        }
+        cur = null;
+        while (lastlevel >= currentLevel) {
+            levels.remove(levels.size() - 1);
+            int newSize = levels.size();
+            if (newSize == 0) {
+                lastlevel = 0;
+                return;
+            }
+            lastlevel = levels.get(newSize - 1).level;
+        }
+    }
+
+    void addXmlnsAttr(Attr n) {
+        if (cur == null) {
+            cur = new XmlsStackElement();
+            cur.level = currentLevel;
+            levels.add(cur);
+            lastlevel = currentLevel;
+        }
+        cur.nodes.add(n);
+    }
+
+    void getXmlnsAttr(Collection<Attr> col) {
+        int size = levels.size() - 1;
+        if (cur == null) {
+            cur = new XmlsStackElement();
+            cur.level = currentLevel;
+            lastlevel = currentLevel;
+            levels.add(cur);
+        }
+        boolean parentRendered = false;
+        XmlsStackElement e = null;
+        if (size == -1) {
+            parentRendered = true;
+        } else {
+            e = levels.get(size);
+            if (e.rendered && e.level + 1 == currentLevel) {
+                parentRendered = true;
+            }
+        }
+        if (parentRendered) {
+            col.addAll(cur.nodes);
+            cur.rendered = true;
+            return;
+        }
+
+        Map<String, Attr> loa = new HashMap<>();
+        if (c14n11) {
+            List<Attr> baseAttrs = new ArrayList<>();
+            boolean successiveOmitted = true;
+            for (; size >= 0; size--) {
+                e = levels.get(size);
+                if (e.rendered) {
+                    successiveOmitted = false;
+                }
+                Iterator<Attr> it = e.nodes.iterator();
+                while (it.hasNext() && successiveOmitted) {
+                    Attr n = it.next();
+                    if (n.getLocalName().equals("base") && !e.rendered) {
+                        baseAttrs.add(n);
+                    } else if (!loa.containsKey(n.getName())) {
+                        loa.put(n.getName(), n);
+                    }
+                }
+            }
+            if (!baseAttrs.isEmpty()) {
+                Iterator<Attr> it = col.iterator();
+                String base = null;
+                Attr baseAttr = null;
+                while (it.hasNext()) {
+                    Attr n = it.next();
+                    if (n.getLocalName().equals("base")) {
+                        base = n.getValue();
+                        baseAttr = n;
+                        break;
+                    }
+                }
+                it = baseAttrs.iterator();
+                while (it.hasNext()) {
+                    Attr n = it.next();
+                    if (base == null) {
+                        base = n.getValue();
+                        baseAttr = n;
+                    } else {
+                        try {
+                            base = joinURI(n.getValue(), base);
+                        } catch (URISyntaxException ue) {
+                            LOG.debug(ue.getMessage(), ue);
+                        }
+                    }
+                }
+                if (base != null && base.length() != 0) {
+                    baseAttr.setValue(base);
+                    col.add(baseAttr);
+                }
+            }
+        } else {
+            for (; size >= 0; size--) {
+                e = levels.get(size);
+                Iterator<Attr> it = e.nodes.iterator();
+                while (it.hasNext()) {
+                    Attr n = it.next();
+                    if (!loa.containsKey(n.getName())) {
+                        loa.put(n.getName(), n);
+                    }
+                }
+            }
+        }
+
+        cur.rendered = true;
+        col.addAll(loa.values());
+    }
+
+    private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
+        String bscheme = null;
+        String bauthority = null;
+        String bpath = "";
+        String bquery = null;
+
+        // pre-parse the baseURI
+        if (baseURI != null) {
+            if (baseURI.endsWith("..")) {
+                baseURI = baseURI + "/";
+            }
+            URI base = new URI(baseURI);
+            bscheme = base.getScheme();
+            bauthority = base.getAuthority();
+            bpath = base.getPath();
+            bquery = base.getQuery();
+        }
+
+        URI r = new URI(relativeURI);
+        String rscheme = r.getScheme();
+        String rauthority = r.getAuthority();
+        String rpath = r.getPath();
+        String rquery = r.getQuery();
+
+        String tscheme, tauthority, tpath, tquery;
+        if (rscheme != null && rscheme.equals(bscheme)) {
+            rscheme = null;
+        }
+        if (rscheme != null) {
+            tscheme = rscheme;
+            tauthority = rauthority;
+            tpath = removeDotSegments(rpath);
+            tquery = rquery;
+        } else {
+            if (rauthority != null) {
+                tauthority = rauthority;
+                tpath = removeDotSegments(rpath);
+                tquery = rquery;
+            } else {
+                if (rpath.length() == 0) {
+                    tpath = bpath;
+                    if (rquery != null) {
+                        tquery = rquery;
+                    } else {
+                        tquery = bquery;
+                    }
+                } else {
+                    if (rpath.startsWith("/")) {
+                        tpath = removeDotSegments(rpath);
+                    } else {
+                        if (bauthority != null && bpath.length() == 0) {
+                            tpath = "/" + rpath;
+                        } else {
+                            int last = bpath.lastIndexOf('/');
+                            if (last == -1) {
+                                tpath = rpath;
+                            } else {
+                                tpath = bpath.substring(0, last+1) + rpath;
+                            }
+                        }
+                        tpath = removeDotSegments(tpath);
+                    }
+                    tquery = rquery;
+                }
+                tauthority = bauthority;
+            }
+            tscheme = bscheme;
+        }
+        return new URI(tscheme, tauthority, tpath, tquery, null).toString();
+    }
+
+    private static String removeDotSegments(String path) {
+        LOG.debug("STEP OUTPUT BUFFER\t\tINPUT BUFFER");
+
+        // 1. The input buffer is initialized with the now-appended path
+        // components then replace occurrences of "//" in the input buffer
+        // with "/" until no more occurrences of "//" are in the input buffer.
+        String input = path;
+        while (input.indexOf("//") > -1) {
+            input = input.replaceAll("//", "/");
+        }
+
+        // Initialize the output buffer with the empty string.
+        StringBuilder output = new StringBuilder();
+
+        // If the input buffer starts with a root slash "/" then move this
+        // character to the output buffer.
+        if (input.charAt(0) == '/') {
+            output.append("/");
+            input = input.substring(1);
+        }
+
+        printStep("1 ", output.toString(), input);
+
+        // While the input buffer is not empty, loop as follows
+        while (input.length() != 0) {
+            // 2A. If the input buffer begins with a prefix of "./",
+            // then remove that prefix from the input buffer
+            // else if the input buffer begins with a prefix of "../", then
+            // if also the output does not contain the root slash "/" only,
+            // then move this prefix to the end of the output buffer else
+            // remove that prefix
+            if (input.startsWith("./")) {
+                input = input.substring(2);
+                printStep("2A", output.toString(), input);
+            } else if (input.startsWith("../")) {
+                input = input.substring(3);
+                if (!output.toString().equals("/")) {
+                    output.append("../");
+                }
+                printStep("2A", output.toString(), input);
+                // 2B. if the input buffer begins with a prefix of "/./" or "/.",
+                // where "." is a complete path segment, then replace that prefix
+                // with "/" in the input buffer; otherwise,
+            } else if (input.startsWith("/./")) {
+                input = input.substring(2);
+                printStep("2B", output.toString(), input);
+            } else if (input.equals("/.")) {
+                // FIXME: what is complete path segment?
+                input = input.replaceFirst("/.", "/");
+                printStep("2B", output.toString(), input);
+                // 2C. if the input buffer begins with a prefix of "/../" or "/..",
+                // where ".." is a complete path segment, then replace that prefix
+                // with "/" in the input buffer and if also the output buffer is
+                // empty, last segment in the output buffer equals "../" or "..",
+                // where ".." is a complete path segment, then append ".." or "/.."
+                // for the latter case respectively to the output buffer else
+                // remove the last segment and its preceding "/" (if any) from the
+                // output buffer and if hereby the first character in the output
+                // buffer was removed and it was not the root slash then delete a
+                // leading slash from the input buffer; otherwise,
+            } else if (input.startsWith("/../")) {
+                input = input.substring(3);
+                if (output.length() == 0) {
+                    output.append("/");
+                } else if (output.toString().endsWith("../")) {
+                    output.append("..");
+                } else if (output.toString().endsWith("..")) {
+                    output.append("/..");
+                } else {
+                    int index = output.lastIndexOf("/");
+                    if (index == -1) {
+                        output = new StringBuilder();
+                        if (input.charAt(0) == '/') {
+                            input = input.substring(1);
+                        }
+                    } else {
+                        output = output.delete(index, output.length());
+                    }
+                }
+                printStep("2C", output.toString(), input);
+            } else if (input.equals("/..")) {
+                // FIXME: what is complete path segment?
+                input = input.replaceFirst("/..", "/");
+                if (output.length() == 0) {
+                    output.append("/");
+                } else if (output.toString().endsWith("../")) {
+                    output.append("..");
+                } else if (output.toString().endsWith("..")) {
+                    output.append("/..");
+                } else {
+                    int index = output.lastIndexOf("/");
+                    if (index == -1) {
+                        output = new StringBuilder();
+                        if (input.charAt(0) == '/') {
+                            input = input.substring(1);
+                        }
+                    } else {
+                        output = output.delete(index, output.length());
+                    }
+                }
+                printStep("2C", output.toString(), input);
+                // 2D. if the input buffer consists only of ".", then remove
+                // that from the input buffer else if the input buffer consists
+                // only of ".." and if the output buffer does not contain only
+                // the root slash "/", then move the ".." to the output buffer
+                // else delte it.; otherwise,
+            } else if (input.equals(".")) {
+                input = "";
+                printStep("2D", output.toString(), input);
+            } else if (input.equals("..")) {
+                if (!output.toString().equals("/")) {
+                    output.append("..");
+                }
+                input = "";
+                printStep("2D", output.toString(), input);
+                // 2E. move the first path segment (if any) in the input buffer
+                // to the end of the output buffer, including the initial "/"
+                // character (if any) and any subsequent characters up to, but not
+                // including, the next "/" character or the end of the input buffer.
+            } else {
+                int end = -1;
+                int begin = input.indexOf('/');
+                if (begin == 0) {
+                    end = input.indexOf('/', 1);
+                } else {
+                    end = begin;
+                    begin = 0;
+                }
+                String segment;
+                if (end == -1) {
+                    segment = input.substring(begin);
+                    input = "";
+                } else {
+                    segment = input.substring(begin, end);
+                    input = input.substring(end);
+                }
+                output.append(segment);
+                printStep("2E", output.toString(), input);
+            }
+        }
+
+        // 3. Finally, if the only or last segment of the output buffer is
+        // "..", where ".." is a complete path segment not followed by a slash
+        // then append a slash "/". The output buffer is returned as the result
+        // of remove_dot_segments
+        if (output.toString().endsWith("..")) {
+            output.append("/");
+            printStep("3 ", output.toString(), input);
+        }
+
+        return output.toString();
+    }
+
+    private static void printStep(String step, String output, String input) {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(" " + step + ":   " + output);
+            if (output.length() == 0) {
+                LOG.debug("\t\t\t\t" + input);
+            } else {
+                LOG.debug("\t\t\t" + input);
+            }
+        }
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML> <HEAD> </HEAD> <BODY> <P>
-canonicalization implementations.
-</P></BODY> </HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-Canonicalization related material and algorithms.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,250 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.HashMap;
-import java.util.Map;
-
-import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * Converts <code>String</code>s into <code>Node</code>s and visa versa.
- *
- * An abstract class for common Serializer functionality
- */
-public abstract class AbstractSerializer implements Serializer {
-
-    protected Canonicalizer canon;
-
-    public void setCanonicalizer(Canonicalizer canon) {
-        this.canon = canon;
-    }
-
-    /**
-     * Returns a <code>String</code> representation of the specified
-     * <code>Element</code>.
-     * <p/>
-     * Refer also to comments about setup of format.
-     *
-     * @param element the <code>Element</code> to serialize.
-     * @return the <code>String</code> representation of the serilaized
-     *   <code>Element</code>.
-     * @throws Exception
-     */
-    public String serialize(Element element) throws Exception {
-        return canonSerialize(element);
-    }
-
-    /**
-     * Returns a <code>byte[]</code> representation of the specified
-     * <code>Element</code>.
-     *
-     * @param element the <code>Element</code> to serialize.
-     * @return the <code>byte[]</code> representation of the serilaized
-     *   <code>Element</code>.
-     * @throws Exception
-     */
-    public byte[] serializeToByteArray(Element element) throws Exception {
-        return canonSerializeToByteArray(element);
-    }
-
-    /**
-     * Returns a <code>String</code> representation of the specified
-     * <code>NodeList</code>.
-     * <p/>
-     * This is a special case because the NodeList may represent a
-     * <code>DocumentFragment</code>. A document fragment may be a
-     * non-valid XML document (refer to appropriate description of
-     * W3C) because it my start with a non-element node, e.g. a text
-     * node.
-     * <p/>
-     * The methods first converts the node list into a document fragment.
-     * Special care is taken to not destroy the current document, thus
-     * the method clones the nodes (deep cloning) before it appends
-     * them to the document fragment.
-     * <p/>
-     * Refer also to comments about setup of format.
-     *
-     * @param content the <code>NodeList</code> to serialize.
-     * @return the <code>String</code> representation of the serialized
-     *   <code>NodeList</code>.
-     * @throws Exception
-     */
-    public String serialize(NodeList content) throws Exception {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        canon.setWriter(baos);
-        canon.notReset();
-        for (int i = 0; i < content.getLength(); i++) {
-            canon.canonicalizeSubtree(content.item(i));
-        }
-        String ret = baos.toString("UTF-8");
-        baos.reset();
-        return ret;
-    }
-
-    /**
-     * Returns a <code>byte[]</code> representation of the specified
-     * <code>NodeList</code>.
-     *
-     * @param content the <code>NodeList</code> to serialize.
-     * @return the <code>byte[]</code> representation of the serialized
-     *   <code>NodeList</code>.
-     * @throws Exception
-     */
-    public byte[] serializeToByteArray(NodeList content) throws Exception {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        canon.setWriter(baos);
-        canon.notReset();
-        for (int i = 0; i < content.getLength(); i++) {
-            canon.canonicalizeSubtree(content.item(i));
-        }
-        return baos.toByteArray();
-    }
-
-    /**
-     * Use the Canonicalizer to serialize the node
-     * @param node
-     * @return the canonicalization of the node
-     * @throws Exception
-     */
-    public String canonSerialize(Node node) throws Exception {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        canon.setWriter(baos);
-        canon.notReset();
-        canon.canonicalizeSubtree(node);
-        String ret = baos.toString("UTF-8");
-        baos.reset();
-        return ret;
-    }
-
-    /**
-     * Use the Canonicalizer to serialize the node
-     * @param node
-     * @return the (byte[]) canonicalization of the node
-     * @throws Exception
-     */
-    public byte[] canonSerializeToByteArray(Node node) throws Exception {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        canon.setWriter(baos);
-        canon.notReset();
-        canon.canonicalizeSubtree(node);
-        return baos.toByteArray();
-    }
-
-    /**
-     * @param source
-     * @param ctx
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException;
-
-    /**
-     * @param source
-     * @param ctx
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
-
-    protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException {
-        // Create the context to parse the document against
-        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-        try {
-            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
-            outputStreamWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
-
-            // Run through each node up to the document node and find any xmlns: nodes
-            Map<String, String> storedNamespaces = new HashMap<String, String>();
-            Node wk = ctx;
-            while (wk != null) {
-                NamedNodeMap atts = wk.getAttributes();
-                if (atts != null) {
-                    for (int i = 0; i < atts.getLength(); ++i) {
-                        Node att = atts.item(i);
-                        String nodeName = att.getNodeName();
-                        if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
-                                && !storedNamespaces.containsKey(att.getNodeName())) {
-                            outputStreamWriter.write(" ");
-                            outputStreamWriter.write(nodeName);
-                            outputStreamWriter.write("=\"");
-                            outputStreamWriter.write(att.getNodeValue());
-                            outputStreamWriter.write("\"");
-                            storedNamespaces.put(nodeName, att.getNodeValue());
-                        }
-                    }
-                }
-                wk = wk.getParentNode();
-            }
-            outputStreamWriter.write(">");
-            outputStreamWriter.flush();
-            byteArrayOutputStream.write(source);
-
-            outputStreamWriter.write("</dummy>");
-            outputStreamWriter.close();
-
-            return byteArrayOutputStream.toByteArray();
-        } catch (UnsupportedEncodingException e) {
-            throw new XMLEncryptionException("empty", e);
-        } catch (IOException e) {
-            throw new XMLEncryptionException("empty", e);
-        }
-    }
-
-    protected static String createContext(String source, Node ctx) {
-        // Create the context to parse the document against
-        StringBuilder sb = new StringBuilder();
-        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
-
-        // Run through each node up to the document node and find any xmlns: nodes
-        Map<String, String> storedNamespaces = new HashMap<String, String>();
-        Node wk = ctx;
-        while (wk != null) {
-            NamedNodeMap atts = wk.getAttributes();
-            if (atts != null) {
-                for (int i = 0; i < atts.getLength(); ++i) {
-                    Node att = atts.item(i);
-                    String nodeName = att.getNodeName();
-                    if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
-                        && !storedNamespaces.containsKey(att.getNodeName())) {
-                        sb.append(' ').append(nodeName).append("=\"")
-                                .append(att.getNodeValue()).append('"');
-                        storedNamespaces.put(nodeName, att.getNodeValue());
-                    }
-                }
-            }
-            wk = wk.getParentNode();
-        }
-        sb.append('>').append(source).append("</dummy>");
-        return sb.toString();
-    }
-
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,157 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
-import org.w3c.dom.Element;
-
-/**
- * A Key Agreement algorithm provides for the derivation of a shared secret key
- * based on a shared secret computed from certain types of compatible public
- * keys from both the sender and the recipient. Information from the originator
- * to determine the secret is indicated by an optional OriginatorKeyInfo
- * parameter child of an {@code AgreementMethod} element while that
- * associated with the recipient is indicated by an optional RecipientKeyInfo. A
- * shared key is derived from this shared secret by a method determined by the
- * Key Agreement algorithm.
- * <p>
- * <b>Note:</b> XML Encryption does not provide an on-line key agreement
- * negotiation protocol. The {@code AgreementMethod} element can be used by
- * the originator to identify the keys and computational procedure that were
- * used to obtain a shared encryption key. The method used to obtain or select
- * the keys or algorithm used for the agreement computation is beyond the scope
- * of this specification.
- * <p>
- * The {@code AgreementMethod} element appears as the content of a
- * {@code ds:KeyInfo} since, like other {@code ds:KeyInfo} children,
- * it yields a key. This {@code ds:KeyInfo} is in turn a child of an
- * {@code EncryptedData} or {@code EncryptedKey} element. The
- * Algorithm attribute and KeySize child of the {@code EncryptionMethod}
- * element under this {@code EncryptedData} or {@code EncryptedKey}
- * element are implicit parameters to the key agreement computation. In cases
- * where this {@code EncryptionMethod} algorithm {@code URI} is
- * insufficient to determine the key length, a KeySize MUST have been included.
- * In addition, the sender may place a KA-Nonce element under
- * {@code AgreementMethod} to assure that different keying material is
- * generated even for repeated agreements using the same sender and recipient
- * public keys.
- * <p>
- * If the agreed key is being used to wrap a key, then
- * {@code AgreementMethod} would appear inside a {@code ds:KeyInfo}
- * inside an {@code EncryptedKey} element.
- * <p>
- * The Schema for AgreementMethod is as follows:
- * <pre>{@code
- * <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
- * <complexType name="AgreementMethodType" mixed="true">
- *     <sequence>
- *         <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
- *         <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
- *         <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
- *         <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- *         <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- *     </sequence>
- *     <attribute name="Algorithm" type="anyURI" use="required"/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface AgreementMethod {
-
-    /**
-     * Returns a {@code byte} array.
-     * @return a {@code byte} array.
-     */
-    byte[] getKANonce();
-
-    /**
-     * Sets the KANonce.jj
-     * @param kanonce
-     */
-    void setKANonce(byte[] kanonce);
-
-    /**
-     * Returns additional information regarding the {@code AgreementMethod}.
-     * @return additional information regarding the {@code AgreementMethod}.
-     */
-    Iterator<Element> getAgreementMethodInformation();
-
-    /**
-     * Adds additional {@code AgreementMethod} information.
-     *
-     * @param info an {@code Element} that represents additional information
-     * specified by
-     *   <pre>{@code
-     *     <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-     *   }</pre>
-     */
-    void addAgreementMethodInformation(Element info);
-
-    /**
-     * Removes additional {@code AgreementMethod} information.
-     *
-     * @param info an {@code Element} that represents additional information
-     * specified by
-     *   <pre>{@code
-     *     <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-     *   }</pre>
-     */
-    void revoveAgreementMethodInformation(Element info);
-
-    /**
-     * Returns information relating to the originator's shared secret.
-     *
-     * @return information relating to the originator's shared secret.
-     */
-    KeyInfo getOriginatorKeyInfo();
-
-    /**
-     * Sets the information relating to the originator's shared secret.
-     *
-     * @param keyInfo information relating to the originator's shared secret.
-     */
-    void setOriginatorKeyInfo(KeyInfo keyInfo);
-
-    /**
-     * Returns information relating to the recipient's shared secret.
-     *
-     * @return information relating to the recipient's shared secret.
-     */
-    KeyInfo getRecipientKeyInfo();
-
-    /**
-     * Sets the information relating to the recipient's shared secret.
-     *
-     * @param keyInfo information relating to the recipient's shared secret.
-     */
-    void setRecipientKeyInfo(KeyInfo keyInfo);
-
-    /**
-     * Returns the algorithm URI of this {@code CryptographicMethod}.
-     *
-     * @return the algorithm URI of this {@code CryptographicMethod}
-     */
-    String getAlgorithm();
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,95 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * {@code CipherData} provides encrypted data. It must either contain the
- * encrypted octet sequence as base64 encoded text of the
- * {@code CipherValue} element, or provide a reference to an external
- * location containing the encrypted octet sequence via the
- * {@code CipherReference} element.
- * <p>
- * The schema definition is as follows:
- * <pre>{@code
- * <element name='CipherData' type='xenc:CipherDataType'/>
- * <complexType name='CipherDataType'>
- *     <choice>
- *         <element name='CipherValue' type='base64Binary'/>
- *         <element ref='xenc:CipherReference'/>
- *     </choice>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface CipherData {
-
-    /** VALUE_TYPE ASN */
-    int VALUE_TYPE = 0x00000001;
-
-    /** REFERENCE_TYPE ASN */
-    int REFERENCE_TYPE = 0x00000002;
-
-    /**
-     * Returns the type of encrypted data contained in the
-     * {@code CipherData}.
-     *
-     * @return {@code VALUE_TYPE} if the encrypted data is contained as
-     *   {@code CipherValue} or {@code REFERENCE_TYPE} if the
-     *   encrypted data is contained as {@code CipherReference}.
-     */
-    int getDataType();
-
-    /**
-     * Returns the cipher value as a base64 encoded {@code byte} array.
-     *
-     * @return the {@code CipherData}'s value.
-     */
-    CipherValue getCipherValue();
-
-    /**
-     * Sets the {@code CipherData}'s value.
-     *
-     * @param value the value of the {@code CipherData}.
-     * @throws XMLEncryptionException
-     */
-    void setCipherValue(CipherValue value) throws XMLEncryptionException;
-
-    /**
-     * Returns a reference to an external location containing the encrypted
-     * octet sequence ({@code byte} array).
-     *
-     * @return the reference to an external location containing the encrypted
-     * octet sequence.
-     */
-    CipherReference getCipherReference();
-
-    /**
-     * Sets the {@code CipherData}'s reference.
-     *
-     * @param reference an external location containing the encrypted octet sequence.
-     * @throws XMLEncryptionException
-     */
-    void setCipherReference(CipherReference reference) throws XMLEncryptionException;
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,95 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import org.w3c.dom.Attr;
-
-/**
- * {@code CipherReference} identifies a source which, when processed,
- * yields the encrypted octet sequence.
- * <p>
- * The actual value is obtained as follows. The {@code CipherReference URI}
- * contains an identifier that is dereferenced. Should the
- * Transforms, the data resulting from dereferencing the {@code URI} is
- * transformed as specified so as to yield the intended cipher value. For
- * example, if the value is base64 encoded within an XML document; the
- * transforms could specify an XPath expression followed by a base64 decoding so
- * as to extract the octets.
- * <p>
- * The syntax of the {@code URI} and Transforms is similar to that of
- * [XML-DSIG]. However, there is a difference between signature and encryption
- * processing. In [XML-DSIG] both generation and validation processing start
- * with the same source data and perform that transform in the same order. In
- * encryption, the decryptor has only the cipher data and the specified
- * transforms are enumerated for the decryptor, in the order necessary to obtain
- * the octets. Consequently, because it has different semantics Transforms is in
- * the &xenc; namespace.
- * <p>
- * The schema definition is as follows:
- * <pre>{@code
- * <element name='CipherReference' type='xenc:CipherReferenceType'/>
- * <complexType name='CipherReferenceType'>
- *     <sequence>
- *         <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
- *     </sequence>
- *     <attribute name='URI' type='anyURI' use='required'/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface CipherReference {
-    /**
-     * Returns an {@code URI} that contains an identifier that should be
-     * dereferenced.
-     * @return an {@code URI} that contains an identifier that should be
-     * dereferenced.
-     */
-    String getURI();
-
-    /**
-     * Gets the URI as an Attribute node.  Used to meld the CipherReference
-     * with the XMLSignature ResourceResolvers
-     * @return the URI as an Attribute node
-     */
-    Attr getURIAsAttr();
-
-    /**
-     * Returns the {@code Transforms} that specifies how to transform the
-     * {@code URI} to yield the appropriate cipher value.
-     *
-     * @return the transform that specifies how to transform the reference to
-     *   yield the intended cipher value.
-     */
-    Transforms getTransforms();
-
-    /**
-     * Sets the {@code Transforms} that specifies how to transform the
-     * {@code URI} to yield the appropriate cipher value.
-     *
-     * @param transforms the set of {@code Transforms} that specifies how
-     *   to transform the reference to yield the intended cipher value.
-     */
-    void setTransforms(Transforms transforms);
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * <code>CipherValue</code> is the wrapper for cipher text.
- *
- * @author Axl Mattheus
- */
-public interface CipherValue {
-    /**
-     * Returns the Base 64 encoded, encrypted octets that is the
-     * <code>CipherValue</code>.
-     *
-     * @return cipher value.
-     */
-    String getValue();
-
-    /**
-     * Sets the Base 64 encoded, encrypted octets that is the
-     * <code>CipherValue</code>.
-     *
-     * @param value the cipher value.
-     */
-    void setValue(String value);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,114 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringReader;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.DocumentFragment;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * Converts <code>String</code>s into <code>Node</code>s and visa versa.
- */
-public class DocumentSerializer extends AbstractSerializer {
-
-    protected DocumentBuilderFactory dbf;
-
-    /**
-     * @param source
-     * @param ctx
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException {
-        byte[] fragment = createContext(source, ctx);
-        return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment)));
-    }
-
-    /**
-     * @param source
-     * @param ctx
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    public Node deserialize(String source, Node ctx) throws XMLEncryptionException {
-        String fragment = createContext(source, ctx);
-        return deserialize(ctx, new InputSource(new StringReader(fragment)));
-    }
-
-    /**
-     * @param ctx
-     * @param inputSource
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException {
-        try {
-            if (dbf == null) {
-                dbf = DocumentBuilderFactory.newInstance();
-                dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-                dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
-                dbf.setValidating(false);
-            }
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            Document d = db.parse(inputSource);
-
-            Document contextDocument = null;
-            if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
-                contextDocument = (Document)ctx;
-            } else {
-                contextDocument = ctx.getOwnerDocument();
-            }
-
-            Element fragElt =
-                    (Element) contextDocument.importNode(d.getDocumentElement(), true);
-            DocumentFragment result = contextDocument.createDocumentFragment();
-            Node child = fragElt.getFirstChild();
-            while (child != null) {
-                fragElt.removeChild(child);
-                result.appendChild(child);
-                child = fragElt.getFirstChild();
-            }
-            return result;
-        } catch (SAXException se) {
-            throw new XMLEncryptionException("empty", se);
-        } catch (ParserConfigurationException pce) {
-            throw new XMLEncryptionException("empty", pce);
-        } catch (IOException ioe) {
-            throw new XMLEncryptionException("empty", ioe);
-        }
-    }
-
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * The {@code EncryptedData} element is the core element in the syntax. Not
- * only does its {@code CipherData} child contain the encrypted data, but
- * it's also the element that replaces the encrypted element, or serves as the
- * new document root.
- * <p>
- * It's schema definition is as follows:
- * <p>
- * <pre>{@code
- * <element name='EncryptedData' type='xenc:EncryptedDataType'/>
- * <complexType name='EncryptedDataType'>
- *     <complexContent>
- *         <extension base='xenc:EncryptedType'/>
- *     </complexContent>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptedData extends EncryptedType {
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,113 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * The {@code EncryptedKey} element is used to transport encryption keys
- * from the originator to a known recipient(s). It may be used as a stand-alone
- * XML document, be placed within an application document, or appear inside an
- * {@code EncryptedData} element as a child of a {@code ds:KeyInfo}
- * element. The key value is always encrypted to the recipient(s). When
- * {@code EncryptedKey} is decrypted the resulting octets are made
- * available to the {@code EncryptionMethod} algorithm without any
- * additional processing.
- * <p>
- * Its schema definition is as follows:
- * <pre>{@code
- * <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
- * <complexType name='EncryptedKeyType'>
- *     <complexContent>
- *         <extension base='xenc:EncryptedType'>
- *             <sequence>
- *                 <element ref='xenc:ReferenceList' minOccurs='0'/>
- *                 <element name='CarriedKeyName' type='string' minOccurs='0'/>
- *             </sequence>
- *             <attribute name='Recipient' type='string' use='optional'/>
- *         </extension>
- *     </complexContent>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptedKey extends EncryptedType {
-
-    /**
-     * Returns a hint as to which recipient this encrypted key value is intended for.
-     *
-     * @return the recipient of the {@code EncryptedKey}.
-     */
-    String getRecipient();
-
-    /**
-     * Sets the recipient for this {@code EncryptedKey}.
-     *
-     * @param recipient the recipient for this {@code EncryptedKey}.
-     */
-    void setRecipient(String recipient);
-
-    /**
-     * Returns pointers to data and keys encrypted using this key. The reference
-     * list may contain multiple references to {@code EncryptedKey} and
-     * {@code EncryptedData} elements. This is done using
-     * {@code KeyReference} and {@code DataReference} elements
-     * respectively.
-     *
-     * @return an {@code Iterator} over all the {@code ReferenceList}s
-     *   contained in this {@code EncryptedKey}.
-     */
-    ReferenceList getReferenceList();
-
-    /**
-     * Sets the {@code ReferenceList} to the {@code EncryptedKey}.
-     *
-     * @param list a list of pointers to data elements encrypted using this key.
-     */
-    void setReferenceList(ReferenceList list);
-
-    /**
-     * Returns a user readable name with the key value. This may then be used to
-     * reference the key using the {@code ds:KeyName} element within
-     * {@code ds:KeyInfo}. The same {@code CarriedKeyName} label,
-     * unlike an ID type, may occur multiple times within a single document. The
-     * value of the key is to be the same in all {@code EncryptedKey}
-     * elements identified with the same {@code CarriedKeyName} label
-     * within a single XML document.
-     * <br>
-     * <b>Note</b> that because whitespace is significant in the value of
-     * the {@code ds:KeyName} element, whitespace is also significant in
-     * the value of the {@code CarriedKeyName} element.
-     *
-     * @return over all the carried names contained in
-     *   this {@code EncryptedKey}.
-     */
-    String getCarriedName();
-
-    /**
-     * Sets the carried name.
-     *
-     * @param name the carried name.
-     */
-    void setCarriedName(String name);
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,197 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
-
-/**
- * EncryptedType is the abstract type from which {@code EncryptedData} and
- * {@code EncryptedKey} are derived. While these two latter element types
- * are very similar with respect to their content models, a syntactical
- * distinction is useful to processing.
- * <p>
- * Its schema definition is as follows:
- * <pre>{@code
- * <complexType name='EncryptedType' abstract='true'>
- *     <sequence>
- *         <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- *             minOccurs='0'/>
- *         <element ref='ds:KeyInfo' minOccurs='0'/>
- *         <element ref='xenc:CipherData'/>
- *         <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- *     </sequence>
- *     <attribute name='Id' type='ID' use='optional'/>
- *     <attribute name='Type' type='anyURI' use='optional'/>
- *     <attribute name='MimeType' type='string' use='optional'/>
- *     <attribute name='Encoding' type='anyURI' use='optional'/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptedType {
-
-    /**
-     * Returns a {@code String} providing for the standard method of
-     * assigning an id to the element within the document context.
-     *
-     * @return the id for the {@code EncryptedType}.
-     */
-    String getId();
-
-    /**
-     * Sets the id.
-     *
-     * @param id
-     */
-    void setId(String id);
-
-    /**
-     * Returns an {@code URI} identifying type information about the
-     * plaintext form of the encrypted content. While optional, this
-     * specification takes advantage of it for mandatory processing described in
-     * Processing Rules: Decryption (section 4.2). If the
-     * {@code EncryptedData} element contains data of Type 'element' or
-     * element 'content', and replaces that data in an XML document context, it
-     * is strongly recommended the Type attribute be provided. Without this
-     * information, the decryptor will be unable to automatically restore the
-     * XML document to its original cleartext form.
-     *
-     * @return the identifier for the type of information in plaintext form of
-     *   encrypted content.
-     */
-    String getType();
-
-    /**
-     * Sets the type.
-     *
-     * @param type an {@code URI} identifying type information about the
-     *   plaintext form of the encrypted content.
-     */
-    void setType(String type);
-
-    /**
-     * Returns a {@code String} which describes the media type of the data
-     * which has been encrypted. The value of this attribute has values defined
-     * by [MIME]. For example, if the data that is encrypted is a base64 encoded
-     * PNG, the transfer Encoding may be specified as
-     * 'http://www.w3.org/2000/09/xmldsig#base64' and the MimeType as
-     * 'image/png'.
-     * <br>
-     * This attribute is purely advisory; no validation of the MimeType
-     * information is required and it does not indicate the encryption
-     * application must do any additional processing. Note, this information may
-     * not be necessary if it is already bound to the identifier in the Type
-     * attribute. For example, the Element and Content types defined in this
-     * specification are always UTF-8 encoded text.
-     *
-     * @return the media type of the data which was encrypted.
-     */
-    String getMimeType();
-
-    /**
-     * Sets the mime type.
-     *
-     * @param type a {@code String} which describes the media type of the
-     *   data which has been encrypted.
-     */
-    void setMimeType(String type);
-
-    /**
-     * Return an {@code URI} representing the encoding of the
-     * {@code EncryptedType}.
-     *
-     * @return the encoding of this {@code EncryptedType}.
-     */
-    String getEncoding();
-
-    /**
-     * Sets the {@code URI} representing the encoding of the
-     * {@code EncryptedType}.
-     *
-     * @param encoding
-     */
-    void setEncoding(String encoding);
-
-    /**
-     * Returns an {@code EncryptionMethod} that describes the encryption
-     * algorithm applied to the cipher data. If the element is absent, the
-     * encryption algorithm must be known by the recipient or the decryption
-     * will fail.
-     *
-     * @return the method used to encrypt the cipher data.
-     */
-    EncryptionMethod getEncryptionMethod();
-
-    /**
-     * Sets the {@code EncryptionMethod} used to encrypt the cipher data.
-     *
-     * @param method the {@code EncryptionMethod}.
-     */
-    void setEncryptionMethod(EncryptionMethod method);
-
-    /**
-     * Returns the {@code ds:KeyInfo}, that carries information about the
-     * key used to encrypt the data. Subsequent sections of this specification
-     * define new elements that may appear as children of
-     * {@code ds:KeyInfo}.
-     *
-     * @return information about the key that encrypted the cipher data.
-     */
-    KeyInfo getKeyInfo();
-
-    /**
-     * Sets the encryption key information.
-     *
-     * @param info the {@code ds:KeyInfo}, that carries information about
-     *   the key used to encrypt the data.
-     */
-    void setKeyInfo(KeyInfo info);
-
-    /**
-     * Returns the {@code CipherReference} that contains the
-     * {@code CipherValue} or {@code CipherReference} with the
-     * encrypted data.
-     *
-     * @return the cipher data for the encrypted type.
-     */
-    CipherData getCipherData();
-
-    /**
-     * Returns additional information concerning the generation of the
-     * {@code EncryptedType}.
-     *
-     * @return information relating to the generation of the
-     *   {@code EncryptedType}.
-     */
-    EncryptionProperties getEncryptionProperties();
-
-    /**
-     * Sets the {@code EncryptionProperties} that supplies additional
-     * information about the generation of the {@code EncryptedType}.
-     *
-     * @param properties
-     */
-    void setEncryptionProperties(EncryptionProperties properties);
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,132 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-import org.w3c.dom.Element;
-
-/**
- * {@code EncryptionMethod} describes the encryption algorithm applied to
- * the cipher data. If the element is absent, the encryption algorithm must be
- * known by the recipient or the decryption will fail.
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <complexType name='EncryptionMethodType' mixed='true'>
- *     <sequence>
- *         <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
- *         <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
- *         <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- *     </sequence>
- *     <attribute name='Algorithm' type='anyURI' use='required'/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptionMethod {
-    /**
-     * Returns the algorithm applied to the cipher data.
-     *
-     * @return the encryption algorithm.
-     */
-    String getAlgorithm();
-
-    /**
-     * Returns the key size of the key of the algorithm applied to the cipher
-     * data.
-     *
-     * @return the key size.
-     */
-    int getKeySize();
-
-    /**
-     * Sets the size of the key of the algorithm applied to the cipher data.
-     *
-     * @param size the key size.
-     */
-    void setKeySize(int size);
-
-    /**
-     * Returns the OAEP parameters of the algorithm applied to the
-     * cipher data.
-     *
-     * @return the OAEP parameters.
-     */
-    byte[] getOAEPparams();
-
-    /**
-     * Sets the OAEP parameters.
-     *
-     * @param parameters the OAEP parameters.
-     */
-    void setOAEPparams(byte[] parameters);
-
-    /**
-     * Set the Digest Algorithm to use
-     * @param digestAlgorithm the Digest Algorithm to use
-     */
-    void setDigestAlgorithm(String digestAlgorithm);
-
-    /**
-     * Get the Digest Algorithm to use
-     * @return the Digest Algorithm to use
-     */
-    String getDigestAlgorithm();
-
-    /**
-     * Set the MGF Algorithm to use
-     * @param mgfAlgorithm the MGF Algorithm to use
-     */
-    void setMGFAlgorithm(String mgfAlgorithm);
-
-    /**
-     * Get the MGF Algorithm to use
-     * @return the MGF Algorithm to use
-     */
-    String getMGFAlgorithm();
-
-    /**
-     * Returns an iterator over all the additional elements contained in the
-     * {@code EncryptionMethod}.
-     *
-     * @return an {@code Iterator} over all the additional information
-     *   about the {@code EncryptionMethod}.
-     */
-    Iterator<Element> getEncryptionMethodInformation();
-
-    /**
-     * Adds encryption method information.
-     *
-     * @param information additional encryption method information.
-     */
-    void addEncryptionMethodInformation(Element information);
-
-    /**
-     * Removes encryption method information.
-     *
-     * @param information the information to remove from the
-     *   {@code EncryptionMethod}.
-     */
-    void removeEncryptionMethodInformation(Element information);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,87 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-
-/**
- * {@code EncryptionProperties} can hold additional information concerning
- * the generation of the {@code EncryptedData} or
- * {@code EncryptedKey}. This information is wraped int an
- * {@code EncryptionProperty} element. Examples of additional information
- * is e.g., a date/time stamp or the serial number of cryptographic hardware
- * used during encryption).
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
- * <complexType name='EncryptionPropertiesType'>
- *     <sequence>
- *         <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
- *     </sequence>
- *     <attribute name='Id' type='ID' use='optional'/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptionProperties {
-
-    /**
-     * Returns the {@code EncryptionProperties}' id.
-     *
-     * @return the id.
-     */
-    String getId();
-
-    /**
-     * Sets the id.
-     *
-     * @param id the id.
-     */
-    void setId(String id);
-
-    /**
-     * Returns an {@code Iterator} over all the
-     * {@code EncryptionPropterty} elements contained in this
-     * {@code EncryptionProperties}.
-     *
-     * @return an {@code Iterator} over all the encryption properties.
-     */
-    Iterator<EncryptionProperty> getEncryptionProperties();
-
-    /**
-     * Adds an {@code EncryptionProperty}.
-     *
-     * @param property
-     */
-    void addEncryptionProperty(EncryptionProperty property);
-
-    /**
-     * Removes the specified {@code EncryptionProperty}.
-     *
-     * @param property
-     */
-    void removeEncryptionProperty(EncryptionProperty property);
-}
-
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,121 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-import org.w3c.dom.Element;
-
-/**
- * Additional information items concerning the generation of the
- * {@code EncryptedData} or {@code EncryptedKey} can be placed in an
- * {@code EncryptionProperty} element (e.g., date/time stamp or the serial
- * number of cryptographic hardware used during encryption). The Target
- * attribute identifies the {@code EncryptedType} structure being
- * described. anyAttribute permits the inclusion of attributes from the XML
- * namespace to be included (i.e., {@code xml:space},
- * {@code xml:lang}, and {@code xml:base}).
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
- * <complexType name='EncryptionPropertyType' mixed='true'>
- *     <choice maxOccurs='unbounded'>
- *         <any namespace='##other' processContents='lax'/>
- *     </choice>
- *     <attribute name='Target' type='anyURI' use='optional'/>
- *     <attribute name='Id' type='ID' use='optional'/>
- *     <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- */
-public interface EncryptionProperty {
-
-    /**
-     * Returns the {@code EncryptedType} being described.
-     *
-     * @return the {@code EncryptedType} being described by this
-     *   {@code EncryptionProperty}.
-     */
-    String getTarget();
-
-    /**
-     * Sets the target.
-     *
-     * @param target
-     */
-    void setTarget(String target);
-
-    /**
-     * Returns the id of the {@code EncryptionProperty}.
-     *
-     * @return the id.
-     */
-    String getId();
-
-    /**
-     * Sets the id.
-     *
-     * @param id
-     */
-    void setId(String id);
-
-    /**
-     * Returns the attribute's value in the {@code xml} namespace.
-     *
-     * @param attribute
-     * @return the attribute's value.
-     */
-    String getAttribute(String attribute);
-
-    /**
-     * Set the attribute value.
-     *
-     * @param attribute the attribute's name.
-     * @param value the attribute's value.
-     */
-    void setAttribute(String attribute, String value);
-
-    /**
-     * Returns the properties of the {@code EncryptionProperty}.
-     *
-     * @return an {@code Iterator} over all the additional encryption
-     *   information contained in this class.
-     */
-    Iterator<Element> getEncryptionInformation();
-
-    /**
-     * Adds encryption information.
-     *
-     * @param information the additional encryption information.
-     */
-    void addEncryptionInformation(Element information);
-
-    /**
-     * Removes encryption information.
-     *
-     * @param information the information to remove.
-     */
-    void removeEncryptionInformation(Element information);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,99 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-import org.w3c.dom.Element;
-
-/**
- * A wrapper for a pointer from a key value of an {@code EncryptedKey} to
- * items encrypted by that key value ({@code EncryptedData} or
- * {@code EncryptedKey} elements).
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <complexType name='ReferenceType'>
- *     <sequence>
- *         <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- *     </sequence>
- *     <attribute name='URI' type='anyURI' use='required'/>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- * @see ReferenceList
- */
-public interface Reference {
-    /**
-     * Returns the {@code Element} tag name for this {@code Reference}.
-     *
-     * @return the tag name of this {@code Reference}.
-     */
-    String getType();
-
-    /**
-     * Returns a {@code URI} that points to an {@code Element} that
-     * were encrypted using the key defined in the enclosing
-     * {@code EncryptedKey} element.
-     *
-     * @return an Uniform Resource Identifier that qualifies an
-     *   {@code EncryptedType}.
-     */
-    String getURI();
-
-    /**
-     * Sets a {@code URI} that points to an {@code Element} that
-     * were encrypted using the key defined in the enclosing
-     * {@code EncryptedKey} element.
-     *
-     * @param uri the Uniform Resource Identifier that qualifies an
-     *   {@code EncryptedType}.
-     */
-    void setURI(String uri);
-
-    /**
-     * Returns an {@code Iterator} over all the child elements contained in
-     * this {@code Reference} that will aid the recipient in retrieving the
-     * {@code EncryptedKey} and/or {@code EncryptedData} elements.
-     * These could include information such as XPath transforms, decompression
-     * transforms, or information on how to retrieve the elements from a
-     * document storage facility.
-     *
-     * @return child elements.
-     */
-    Iterator<Element> getElementRetrievalInformation();
-
-    /**
-     * Adds retrieval information.
-     *
-     * @param info
-     */
-    void addElementRetrievalInformation(Element info);
-
-    /**
-     * Removes the specified retrieval information.
-     *
-     * @param info
-     */
-    void removeElementRetrievalInformation(Element info);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,109 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.util.Iterator;
-
-/**
- * {@code ReferenceList} is an element that contains pointers from a key
- * value of an {@code EncryptedKey} to items encrypted by that key value
- * ({@code EncryptedData} or {@code EncryptedKey} elements).
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <element name='ReferenceList'>
- *     <complexType>
- *         <choice minOccurs='1' maxOccurs='unbounded'>
- *             <element name='DataReference' type='xenc:ReferenceType'/>
- *             <element name='KeyReference' type='xenc:ReferenceType'/>
- *         </choice>
- *     </complexType>
- * </element>
- * }</pre>
- *
- * @author Axl Mattheus
- * @see Reference
- */
-public interface ReferenceList {
-
-    /** DATA TAG */
-    int DATA_REFERENCE = 0x00000001;
-
-    /** KEY TAG */
-    int KEY_REFERENCE  = 0x00000002;
-
-    /**
-     * Adds a reference to this reference list.
-     *
-     * @param reference the reference to add.
-     * @throws IllegalAccessException if the {@code Reference} is not an
-     *   instance of {@code DataReference} or {@code KeyReference}.
-     */
-    void add(Reference reference);
-
-    /**
-     * Removes a reference from the {@code ReferenceList}.
-     *
-     * @param reference the reference to remove.
-     */
-    void remove(Reference reference);
-
-    /**
-     * Returns the size of the {@code ReferenceList}.
-     *
-     * @return the size of the {@code ReferenceList}.
-     */
-    int size();
-
-    /**
-     * Indicates if the {@code ReferenceList} is empty.
-     *
-     * @return <b>{@code true}</b> if the {@code ReferenceList} is
-     *     empty, else <b>{@code false}</b>.
-     */
-    boolean isEmpty();
-
-    /**
-     * Returns an {@code Iterator} over all the {@code Reference}s
-     * contained in this {@code ReferenceList}.
-     *
-     * @return Iterator.
-     */
-    Iterator<Reference> getReferences();
-
-    /**
-     * {@code DataReference} factory method. Returns a
-     * {@code DataReference}.
-     * @param uri
-     * @return a {@code DataReference}.
-     */
-    Reference newDataReference(String uri);
-
-    /**
-     * {@code KeyReference} factory method. Returns a
-     * {@code KeyReference}.
-     * @param uri
-     * @return a {@code KeyReference}.
-     */
-    Reference newKeyReference(String uri);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * Converts <code>String</code>s into <code>Node</code>s and visa versa.
- */
-public interface Serializer {
-
-    /**
-     * Set the Canonicalizer object to use.
-     */
-    void setCanonicalizer(Canonicalizer canon);
-
-    /**
-     * Returns a <code>byte[]</code> representation of the specified
-     * <code>Element</code>.
-     *
-     * @param element the <code>Element</code> to serialize.
-     * @return the <code>byte[]</code> representation of the serilaized
-     *   <code>Element</code>.
-     * @throws Exception
-     */
-    byte[] serializeToByteArray(Element element) throws Exception;
-
-    /**
-     * Returns a <code>byte[]</code> representation of the specified
-     * <code>NodeList</code>.
-     *
-     * @param content the <code>NodeList</code> to serialize.
-     * @return the <code>byte[]</code> representation of the serialized
-     *   <code>NodeList</code>.
-     * @throws Exception
-     */
-    byte[] serializeToByteArray(NodeList content) throws Exception;
-
-    /**
-     * Use the Canonicalizer to serialize the node
-     * @param node
-     * @return the (byte[]) canonicalization of the node
-     * @throws Exception
-     */
-    byte[] canonSerializeToByteArray(Node node) throws Exception;
-
-    /**
-     * @param source
-     * @param ctx
-     * @return the Node resulting from the parse of the source
-     * @throws XMLEncryptionException
-     */
-    Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * A container for {@code ds:Transform}s.
- * <p>
- * It is defined as follows:
- * <pre>{@code
- * <complexType name='TransformsType'>
- *     <sequence>
- *         <element ref='ds:Transform' maxOccurs='unbounded'/>
- *     </sequence>
- * </complexType>
- * }</pre>
- *
- * @author Axl Mattheus
- * @see com.sun.org.apache.xml.internal.security.encryption.CipherReference
- */
-public interface Transforms {
-    /**
-     * Temporary method to turn the XMLEncryption Transforms class
-     * into a DS class.  The main logic is currently implemented in the
-     * DS class, so we need to get to get the base class.
-     * <p>
-     * <b>Note</b> This will be removed in future versions
-     */
-    com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms();
-
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3539 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.Key;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SecureRandom;
-import java.security.spec.MGF1ParameterSpec;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.OAEPParameterSpec;
-import javax.crypto.spec.PSource;
-
-import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
-import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
-import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
-import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
-import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
-import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.EncryptedKeyResolver;
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
-import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
-import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * <code>XMLCipher</code> encrypts and decrypts the contents of
- * <code>Document</code>s, <code>Element</code>s and <code>Element</code>
- * contents. It was designed to resemble <code>javax.crypto.Cipher</code> in
- * order to facilitate understanding of its functioning.
- *
- * @author Axl Mattheus (Sun Microsystems)
- * @author Christian Geuer-Pollmann
- */
-public class XMLCipher {
-
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XMLCipher.class.getName());
-
-    /** Triple DES EDE (192 bit key) in CBC mode */
-    public static final String TRIPLEDES =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES;
-
-    /** AES 128 Cipher */
-    public static final String AES_128 =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128;
-
-    /** AES 256 Cipher */
-    public static final String AES_256 =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256;
-
-    /** AES 192 Cipher */
-    public static final String AES_192 =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192;
-
-    /** AES 128 GCM Cipher */
-    public static final String AES_128_GCM =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM;
-
-    /** AES 192 GCM Cipher */
-    public static final String AES_192_GCM =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM;
-
-    /** AES 256 GCM Cipher */
-    public static final String AES_256_GCM =
-        EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM;
-
-    /** RSA 1.5 Cipher */
-    public static final String RSA_v1dot5 =
-        EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15;
-
-    /** RSA OAEP Cipher */
-    public static final String RSA_OAEP =
-        EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP;
-
-    /** RSA OAEP Cipher */
-    public static final String RSA_OAEP_11 =
-        EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP_11;
-
-    /** DIFFIE_HELLMAN Cipher */
-    public static final String DIFFIE_HELLMAN =
-        EncryptionConstants.ALGO_ID_KEYAGREEMENT_DH;
-
-    /** Triple DES EDE (192 bit key) in CBC mode KEYWRAP*/
-    public static final String TRIPLEDES_KeyWrap =
-        EncryptionConstants.ALGO_ID_KEYWRAP_TRIPLEDES;
-
-    /** AES 128 Cipher KeyWrap */
-    public static final String AES_128_KeyWrap =
-        EncryptionConstants.ALGO_ID_KEYWRAP_AES128;
-
-    /** AES 256 Cipher KeyWrap */
-    public static final String AES_256_KeyWrap =
-        EncryptionConstants.ALGO_ID_KEYWRAP_AES256;
-
-    /** AES 192 Cipher KeyWrap */
-    public static final String AES_192_KeyWrap =
-        EncryptionConstants.ALGO_ID_KEYWRAP_AES192;
-
-    /** SHA1 Cipher */
-    public static final String SHA1 =
-        Constants.ALGO_ID_DIGEST_SHA1;
-
-    /** SHA256 Cipher */
-    public static final String SHA256 =
-        MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256;
-
-    /** SHA512 Cipher */
-    public static final String SHA512 =
-        MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512;
-
-    /** RIPEMD Cipher */
-    public static final String RIPEMD_160 =
-        MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160;
-
-    /** XML Signature NS */
-    public static final String XML_DSIG =
-        Constants.SignatureSpecNS;
-
-    /** N14C_XML */
-    public static final String N14C_XML =
-        Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
-
-    /** N14C_XML with comments*/
-    public static final String N14C_XML_WITH_COMMENTS =
-        Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
-
-    /** N14C_XML exclusive */
-    public static final String EXCL_XML_N14C =
-        Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
-
-    /** N14C_XML exclusive with comments*/
-    public static final String EXCL_XML_N14C_WITH_COMMENTS =
-        Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
-
-    /** N14C_PHYSICAL preserve the physical representation*/
-    public static final String PHYSICAL_XML_N14C =
-        Canonicalizer.ALGO_ID_C14N_PHYSICAL;
-
-    /** Base64 encoding */
-    public static final String BASE64_ENCODING =
-        com.sun.org.apache.xml.internal.security.transforms.Transforms.TRANSFORM_BASE64_DECODE;
-
-    /** ENCRYPT Mode */
-    public static final int ENCRYPT_MODE = Cipher.ENCRYPT_MODE;
-
-    /** DECRYPT Mode */
-    public static final int DECRYPT_MODE = Cipher.DECRYPT_MODE;
-
-    /** UNWRAP Mode */
-    public static final int UNWRAP_MODE  = Cipher.UNWRAP_MODE;
-
-    /** WRAP Mode */
-    public static final int WRAP_MODE    = Cipher.WRAP_MODE;
-
-    private static final String ENC_ALGORITHMS = TRIPLEDES + "\n" +
-    AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" +
-    RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" +
-    AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" +
-    AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n";
-
-    /** Cipher created during initialisation that is used for encryption */
-    private Cipher contextCipher;
-
-    /** Mode that the XMLCipher object is operating in */
-    private int cipherMode = Integer.MIN_VALUE;
-
-    /** URI of algorithm that is being used for cryptographic operation */
-    private String algorithm = null;
-
-    /** Cryptographic provider requested by caller */
-    private String requestedJCEProvider = null;
-
-    /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */
-    private Canonicalizer canon;
-
-    /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
-    private Document contextDocument;
-
-    /** Instance of factory used to create XML Encryption objects */
-    private Factory factory;
-
-    /** Serializer class for going to/from UTF-8 */
-    private Serializer serializer;
-
-    /** Local copy of user's key */
-    private Key key;
-
-    /** Local copy of the kek (used to decrypt EncryptedKeys during a
-     *  DECRYPT_MODE operation */
-    private Key kek;
-
-    // The EncryptedKey being built (part of a WRAP operation) or read
-    // (part of an UNWRAP operation)
-    private EncryptedKey ek;
-
-    // The EncryptedData being built (part of a WRAP operation) or read
-    // (part of an UNWRAP operation)
-    private EncryptedData ed;
-
-    private SecureRandom random;
-
-    private boolean secureValidation;
-
-    private String digestAlg;
-
-    /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */
-    private List<KeyResolverSpi> internalKeyResolvers;
-
-    /**
-     * Set the Serializer algorithm to use
-     */
-    public void setSerializer(Serializer serializer) {
-        this.serializer = serializer;
-        serializer.setCanonicalizer(this.canon);
-    }
-
-    /**
-     * Get the Serializer algorithm to use
-     */
-    public Serializer getSerializer() {
-        return serializer;
-    }
-
-    /**
-     * Creates a new <code>XMLCipher</code>.
-     *
-     * @param transformation    the name of the transformation, e.g.,
-     *                          <code>XMLCipher.TRIPLEDES</code>. If null the XMLCipher can only
-     *                          be used for decrypt or unwrap operations where the encryption method
-     *                          is defined in the <code>EncryptionMethod</code> element.
-     * @param provider          the JCE provider that supplies the transformation,
-     *                          if null use the default provider.
-     * @param canon             the name of the c14n algorithm, if
-     *                          <code>null</code> use standard serializer
-     * @param digestMethod      An optional digestMethod to use.
-     */
-    private XMLCipher(
-        String transformation,
-        String provider,
-        String canonAlg,
-        String digestMethod
-    ) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
-        }
-
-        factory = new Factory();
-
-        algorithm = transformation;
-        requestedJCEProvider = provider;
-        digestAlg = digestMethod;
-
-        // Create a canonicalizer - used when serializing DOM to octets
-        // prior to encryption (and for the reverse)
-
-        try {
-            if (canonAlg == null) {
-                // The default is to preserve the physical representation.
-                this.canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_PHYSICAL);
-            } else {
-                this.canon = Canonicalizer.getInstance(canonAlg);
-            }
-        } catch (InvalidCanonicalizerException ice) {
-            throw new XMLEncryptionException("empty", ice);
-        }
-
-        if (serializer == null) {
-            serializer = new DocumentSerializer();
-        }
-        serializer.setCanonicalizer(this.canon);
-
-        if (transformation != null) {
-            contextCipher = constructCipher(transformation, digestMethod);
-        }
-    }
-
-    /**
-     * Checks to ensure that the supplied algorithm is valid.
-     *
-     * @param algorithm the algorithm to check.
-     * @return true if the algorithm is valid, otherwise false.
-     * @since 1.0.
-     */
-    private static boolean isValidEncryptionAlgorithm(String algorithm) {
-        return (
-            algorithm.equals(TRIPLEDES) ||
-            algorithm.equals(AES_128) ||
-            algorithm.equals(AES_256) ||
-            algorithm.equals(AES_192) ||
-            algorithm.equals(AES_128_GCM) ||
-            algorithm.equals(AES_192_GCM) ||
-            algorithm.equals(AES_256_GCM) ||
-            algorithm.equals(RSA_v1dot5) ||
-            algorithm.equals(RSA_OAEP) ||
-            algorithm.equals(RSA_OAEP_11) ||
-            algorithm.equals(TRIPLEDES_KeyWrap) ||
-            algorithm.equals(AES_128_KeyWrap) ||
-            algorithm.equals(AES_256_KeyWrap) ||
-            algorithm.equals(AES_192_KeyWrap)
-        );
-    }
-
-    /**
-     * Validate the transformation argument of getInstance or getProviderInstance
-     *
-     * @param transformation the name of the transformation, e.g.,
-     *   <code>XMLCipher.TRIPLEDES</code> which is shorthand for
-     *   &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
-     */
-    private static void validateTransformation(String transformation) {
-        if (null == transformation) {
-            throw new NullPointerException("Transformation unexpectedly null...");
-        }
-        if (!isValidEncryptionAlgorithm(transformation)) {
-            log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
-        }
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation and operates on the specified context document.
-     * <p>
-     * If the default provider package supplies an implementation of the
-     * requested transformation, an instance of Cipher containing that
-     * implementation is returned. If the transformation is not available in
-     * the default provider package, other provider packages are searched.
-     * <p>
-     * <b>NOTE<sub>1</sub>:</b> The transformation name does not follow the same
-     * pattern as that outlined in the Java Cryptography Extension Reference
-     * Guide but rather that specified by the XML Encryption Syntax and
-     * Processing document. The rational behind this is to make it easier for a
-     * novice at writing Java Encryption software to use the library.
-     * <p>
-     * <b>NOTE<sub>2</sub>:</b> <code>getInstance()</code> does not follow the
-     * same pattern regarding exceptional conditions as that used in
-     * <code>javax.crypto.Cipher</code>. Instead, it only throws an
-     * <code>XMLEncryptionException</code> which wraps an underlying exception.
-     * The stack trace from the exception should be self explanatory.
-     *
-     * @param transformation the name of the transformation, e.g.,
-     *   <code>XMLCipher.TRIPLEDES</code> which is shorthand for
-     *   &quot;http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot;
-     * @throws XMLEncryptionException
-     * @return the XMLCipher
-     * @see javax.crypto.Cipher#getInstance(java.lang.String)
-     */
-    public static XMLCipher getInstance(String transformation) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, null, null, null);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation, operates on the specified context document and serializes
-     * the document with the specified canonicalization algorithm before it
-     * encrypts the document.
-     * <p>
-     *
-     * @param transformation    the name of the transformation
-     * @param canon             the name of the c14n algorithm, if <code>null</code> use
-     *                          standard serializer
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getInstance(String transformation, String canon)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, null, canon, null);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation, operates on the specified context document and serializes
-     * the document with the specified canonicalization algorithm before it
-     * encrypts the document.
-     * <p>
-     *
-     * @param transformation    the name of the transformation
-     * @param canon             the name of the c14n algorithm, if <code>null</code> use
-     *                          standard serializer
-     * @param digestMethod      An optional digestMethod to use
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getInstance(String transformation, String canon, String digestMethod)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, null, canon, digestMethod);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation and operates on the specified context document.
-     *
-     * @param transformation    the name of the transformation
-     * @param provider          the JCE provider that supplies the transformation
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getProviderInstance(String transformation, String provider)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and provider");
-        }
-        if (null == provider) {
-            throw new NullPointerException("Provider unexpectedly null..");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, provider, null, null);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation, operates on the specified context document and serializes
-     * the document with the specified canonicalization algorithm before it
-     * encrypts the document.
-     * <p>
-     *
-     * @param transformation    the name of the transformation
-     * @param provider          the JCE provider that supplies the transformation
-     * @param canon             the name of the c14n algorithm, if <code>null</code> use standard
-     *                          serializer
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getProviderInstance(
-        String transformation, String provider, String canon
-    ) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm");
-        }
-        if (null == provider) {
-            throw new NullPointerException("Provider unexpectedly null..");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, provider, canon, null);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements the specified
-     * transformation, operates on the specified context document and serializes
-     * the document with the specified canonicalization algorithm before it
-     * encrypts the document.
-     * <p>
-     *
-     * @param transformation    the name of the transformation
-     * @param provider          the JCE provider that supplies the transformation
-     * @param canon             the name of the c14n algorithm, if <code>null</code> use standard
-     *                          serializer
-     * @param digestMethod      An optional digestMethod to use
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getProviderInstance(
-        String transformation, String provider, String canon, String digestMethod
-    ) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm");
-        }
-        if (null == provider) {
-            throw new NullPointerException("Provider unexpectedly null..");
-        }
-        validateTransformation(transformation);
-        return new XMLCipher(transformation, provider, canon, digestMethod);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements no specific
-     * transformation, and can therefore only be used for decrypt or
-     * unwrap operations where the encryption method is defined in the
-     * <code>EncryptionMethod</code> element.
-     *
-     * @return The XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getInstance() throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with no arguments");
-        }
-        return new XMLCipher(null, null, null, null);
-    }
-
-    /**
-     * Returns an <code>XMLCipher</code> that implements no specific
-     * transformation, and can therefore only be used for decrypt or
-     * unwrap operations where the encryption method is defined in the
-     * <code>EncryptionMethod</code> element.
-     *
-     * Allows the caller to specify a provider that will be used for
-     * cryptographic operations.
-     *
-     * @param provider          the JCE provider that supplies the transformation
-     * @return the XMLCipher
-     * @throws XMLEncryptionException
-     */
-    public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Getting XMLCipher with provider");
-        }
-        return new XMLCipher(null, provider, null, null);
-    }
-
-    /**
-     * Initializes this cipher with a key.
-     * <p>
-     * The cipher is initialized for one of the following four operations:
-     * encryption, decryption, key wrapping or key unwrapping, depending on the
-     * value of opmode.
-     *
-     * For WRAP and ENCRYPT modes, this also initialises the internal
-     * EncryptedKey or EncryptedData (with a CipherValue)
-     * structure that will be used during the ensuing operations.  This
-     * can be obtained (in order to modify KeyInfo elements etc. prior to
-     * finalising the encryption) by calling
-     * {@link #getEncryptedData} or {@link #getEncryptedKey}.
-     *
-     * @param opmode the operation mode of this cipher (this is one of the
-     *   following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE)
-     * @param key
-     * @see javax.crypto.Cipher#init(int, java.security.Key)
-     * @throws XMLEncryptionException
-     */
-    public void init(int opmode, Key key) throws XMLEncryptionException {
-        // sanity checks
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
-        }
-
-        ek = null;
-        ed = null;
-
-        switch (opmode) {
-
-        case ENCRYPT_MODE :
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
-            }
-            ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
-            break;
-        case DECRYPT_MODE :
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
-            }
-            break;
-        case WRAP_MODE :
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
-            }
-            ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
-            break;
-        case UNWRAP_MODE :
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
-            }
-            break;
-        default :
-            log.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
-            throw new XMLEncryptionException("Invalid mode in init");
-        }
-
-        cipherMode = opmode;
-        this.key = key;
-    }
-
-    /**
-     * Set whether secure validation is enabled or not. The default is false.
-     */
-    public void setSecureValidation(boolean secureValidation) {
-        this.secureValidation = secureValidation;
-    }
-
-    /**
-     * This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher.
-     * These KeyResolvers are used in KeyInfo objects in DECRYPT and
-     * UNWRAP modes.
-     *
-     * @param keyResolver
-     */
-    public void registerInternalKeyResolver(KeyResolverSpi keyResolver) {
-        if (internalKeyResolvers == null) {
-            internalKeyResolvers = new ArrayList<KeyResolverSpi>();
-        }
-        internalKeyResolvers.add(keyResolver);
-    }
-
-    /**
-     * Get the EncryptedData being built
-     * <p>
-     * Returns the EncryptedData being built during an ENCRYPT operation.
-     * This can then be used by applications to add KeyInfo elements and
-     * set other parameters.
-     *
-     * @return The EncryptedData being built
-     */
-    public EncryptedData getEncryptedData() {
-        // Sanity checks
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Returning EncryptedData");
-        }
-        return ed;
-    }
-
-    /**
-     * Get the EncryptedData being build
-     *
-     * Returns the EncryptedData being built during an ENCRYPT operation.
-     * This can then be used by applications to add KeyInfo elements and
-     * set other parameters.
-     *
-     * @return The EncryptedData being built
-     */
-    public EncryptedKey getEncryptedKey() {
-        // Sanity checks
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Returning EncryptedKey");
-        }
-        return ek;
-    }
-
-    /**
-     * Set a Key Encryption Key.
-     * <p>
-     * The Key Encryption Key (KEK) is used for encrypting/decrypting
-     * EncryptedKey elements.  By setting this separately, the XMLCipher
-     * class can know whether a key applies to the data part or wrapped key
-     * part of an encrypted object.
-     *
-     * @param kek The key to use for de/encrypting key data
-     */
-
-    public void setKEK(Key kek) {
-        this.kek = kek;
-    }
-
-    /**
-     * Martial an EncryptedData
-     *
-     * Takes an EncryptedData object and returns a DOM Element that
-     * represents the appropriate <code>EncryptedData</code>
-     * <p>
-     * <b>Note:</b> This should only be used in cases where the context
-     * document has been passed in via a call to doFinal.
-     *
-     * @param encryptedData EncryptedData object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(EncryptedData encryptedData) {
-        return factory.toElement(encryptedData);
-    }
-
-    /**
-     * Martial an EncryptedData
-     *
-     * Takes an EncryptedData object and returns a DOM Element that
-     * represents the appropriate <code>EncryptedData</code>
-     *
-     * @param context The document that will own the returned nodes
-     * @param encryptedData EncryptedData object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(Document context, EncryptedData encryptedData) {
-        contextDocument = context;
-        return factory.toElement(encryptedData);
-    }
-
-    /**
-     * Martial an EncryptedKey
-     *
-     * Takes an EncryptedKey object and returns a DOM Element that
-     * represents the appropriate <code>EncryptedKey</code>
-     *
-     * <p>
-     * <b>Note:</b> This should only be used in cases where the context
-     * document has been passed in via a call to doFinal.
-     *
-     * @param encryptedKey EncryptedKey object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(EncryptedKey encryptedKey) {
-        return factory.toElement(encryptedKey);
-    }
-
-    /**
-     * Martial an EncryptedKey
-     *
-     * Takes an EncryptedKey object and returns a DOM Element that
-     * represents the appropriate <code>EncryptedKey</code>
-     *
-     * @param context The document that will own the created nodes
-     * @param encryptedKey EncryptedKey object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(Document context, EncryptedKey encryptedKey) {
-        contextDocument = context;
-        return factory.toElement(encryptedKey);
-    }
-
-    /**
-     * Martial a ReferenceList
-     *
-     * Takes a ReferenceList object and returns a DOM Element that
-     * represents the appropriate <code>ReferenceList</code>
-     *
-     * <p>
-     * <b>Note:</b> This should only be used in cases where the context
-     * document has been passed in via a call to doFinal.
-     *
-     * @param referenceList ReferenceList object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(ReferenceList referenceList) {
-        return factory.toElement(referenceList);
-    }
-
-    /**
-     * Martial a ReferenceList
-     *
-     * Takes a ReferenceList object and returns a DOM Element that
-     * represents the appropriate <code>ReferenceList</code>
-     *
-     * @param context The document that will own the created nodes
-     * @param referenceList ReferenceList object to martial
-     * @return the DOM <code>Element</code> representing the passed in
-     * object
-     */
-    public Element martial(Document context, ReferenceList referenceList) {
-        contextDocument = context;
-        return factory.toElement(referenceList);
-    }
-
-    /**
-     * Encrypts an <code>Element</code> and replaces it with its encrypted
-     * counterpart in the context <code>Document</code>, that is, the
-     * <code>Document</code> specified when one calls
-     * {@link #getInstance(String) getInstance}.
-     *
-     * @param element the <code>Element</code> to encrypt.
-     * @return the context <code>Document</code> with the encrypted
-     *   <code>Element</code> having replaced the source <code>Element</code>.
-     *  @throws Exception
-     */
-    private Document encryptElement(Element element) throws Exception{
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypting element...");
-        }
-        if (null == element) {
-            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        }
-        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-        }
-
-        if (algorithm == null) {
-            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-        }
-        encryptData(contextDocument, element, false);
-
-        Element encryptedElement = factory.toElement(ed);
-
-        Node sourceParent = element.getParentNode();
-        sourceParent.replaceChild(encryptedElement, element);
-
-        return contextDocument;
-    }
-
-    /**
-     * Encrypts a <code>NodeList</code> (the contents of an
-     * <code>Element</code>) and replaces its parent <code>Element</code>'s
-     * content with this the resulting <code>EncryptedType</code> within the
-     * context <code>Document</code>, that is, the <code>Document</code>
-     * specified when one calls
-     * {@link #getInstance(String) getInstance}.
-     *
-     * @param element the <code>NodeList</code> to encrypt.
-     * @return the context <code>Document</code> with the encrypted
-     *   <code>NodeList</code> having replaced the content of the source
-     *   <code>Element</code>.
-     * @throws Exception
-     */
-    private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypting element content...");
-        }
-        if (null == element) {
-            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        }
-        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-        }
-
-        if (algorithm == null) {
-            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-        }
-        encryptData(contextDocument, element, true);
-
-        Element encryptedElement = factory.toElement(ed);
-
-        removeContent(element);
-        element.appendChild(encryptedElement);
-
-        return contextDocument;
-    }
-
-    /**
-     * Process a DOM <code>Document</code> node. The processing depends on the
-     * initialization parameters of {@link #init(int, Key) init()}.
-     *
-     * @param context the context <code>Document</code>.
-     * @param source the <code>Document</code> to be encrypted or decrypted.
-     * @return the processed <code>Document</code>.
-     * @throws Exception to indicate any exceptional conditions.
-     */
-    public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Processing source document...");
-        }
-        if (null == context) {
-            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        }
-        if (null == source) {
-            log.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null...");
-        }
-
-        contextDocument = context;
-
-        Document result = null;
-
-        switch (cipherMode) {
-        case DECRYPT_MODE:
-            result = decryptElement(source.getDocumentElement());
-            break;
-        case ENCRYPT_MODE:
-            result = encryptElement(source.getDocumentElement());
-            break;
-        case UNWRAP_MODE:
-        case WRAP_MODE:
-            break;
-        default:
-            throw new XMLEncryptionException("empty", new IllegalStateException());
-        }
-
-        return result;
-    }
-
-    /**
-     * Process a DOM <code>Element</code> node. The processing depends on the
-     * initialization parameters of {@link #init(int, Key) init()}.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> to be encrypted.
-     * @return the processed <code>Document</code>.
-     * @throws Exception to indicate any exceptional conditions.
-     */
-    public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Processing source element...");
-        }
-        if (null == context) {
-            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        }
-        if (null == element) {
-            log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
-        }
-
-        contextDocument = context;
-
-        Document result = null;
-
-        switch (cipherMode) {
-        case DECRYPT_MODE:
-            result = decryptElement(element);
-            break;
-        case ENCRYPT_MODE:
-            result = encryptElement(element);
-            break;
-        case UNWRAP_MODE:
-        case WRAP_MODE:
-            break;
-        default:
-            throw new XMLEncryptionException("empty", new IllegalStateException());
-        }
-
-        return result;
-    }
-
-    /**
-     * Process the contents of a DOM <code>Element</code> node. The processing
-     * depends on the initialization parameters of
-     * {@link #init(int, Key) init()}.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> which contents is to be
-     *   encrypted.
-     * @param content
-     * @return the processed <code>Document</code>.
-     * @throws Exception to indicate any exceptional conditions.
-     */
-    public Document doFinal(Document context, Element element, boolean content)
-        throws /* XMLEncryption*/ Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Processing source element...");
-        }
-        if (null == context) {
-            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        }
-        if (null == element) {
-            log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
-        }
-
-        contextDocument = context;
-
-        Document result = null;
-
-        switch (cipherMode) {
-        case DECRYPT_MODE:
-            if (content) {
-                result = decryptElementContent(element);
-            } else {
-                result = decryptElement(element);
-            }
-            break;
-        case ENCRYPT_MODE:
-            if (content) {
-                result = encryptElementContent(element);
-            } else {
-                result = encryptElement(element);
-            }
-            break;
-        case UNWRAP_MODE:
-        case WRAP_MODE:
-            break;
-        default:
-            throw new XMLEncryptionException("empty", new IllegalStateException());
-        }
-
-        return result;
-    }
-
-    /**
-     * Returns an <code>EncryptedData</code> interface. Use this operation if
-     * you want to have full control over the contents of the
-     * <code>EncryptedData</code> structure.
-     *
-     * This does not change the source document in any way.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> that will be encrypted.
-     * @return the <code>EncryptedData</code>
-     * @throws Exception
-     */
-    public EncryptedData encryptData(Document context, Element element) throws
-        /* XMLEncryption */Exception {
-        return encryptData(context, element, false);
-    }
-
-    /**
-     * Returns an <code>EncryptedData</code> interface. Use this operation if
-     * you want to have full control over the serialization of the element
-     * or element content.
-     *
-     * This does not change the source document in any way.
-     *
-     * @param context the context <code>Document</code>.
-     * @param type a URI identifying type information about the plaintext form
-     *    of the encrypted content (may be <code>null</code>)
-     * @param serializedData the serialized data
-     * @return the <code>EncryptedData</code>
-     * @throws Exception
-     */
-    public EncryptedData encryptData(
-        Document context, String type, InputStream serializedData
-    ) throws Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypting element...");
-        }
-        if (null == context) {
-            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        }
-        if (null == serializedData) {
-            log.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
-        }
-        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-        }
-
-        return encryptData(context, null, type, serializedData);
-    }
-
-    /**
-     * Returns an <code>EncryptedData</code> interface. Use this operation if
-     * you want to have full control over the contents of the
-     * <code>EncryptedData</code> structure.
-     *
-     * This does not change the source document in any way.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> that will be encrypted.
-     * @param contentMode <code>true</code> to encrypt element's content only,
-     *    <code>false</code> otherwise
-     * @return the <code>EncryptedData</code>
-     * @throws Exception
-     */
-    public EncryptedData encryptData(
-        Document context, Element element, boolean contentMode
-    ) throws /* XMLEncryption */ Exception {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypting element...");
-        }
-        if (null == context) {
-            log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
-        }
-        if (null == element) {
-            log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
-        }
-        if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
-        }
-
-        if (contentMode) {
-            return encryptData(context, element, EncryptionConstants.TYPE_CONTENT, null);
-        } else {
-            return encryptData(context, element, EncryptionConstants.TYPE_ELEMENT, null);
-        }
-    }
-
-    private EncryptedData encryptData(
-        Document context, Element element, String type, InputStream serializedData
-    ) throws /* XMLEncryption */ Exception {
-        contextDocument = context;
-
-        if (algorithm == null) {
-            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-        }
-
-        byte[] serializedOctets = null;
-        if (serializedData == null) {
-            if (type.equals(EncryptionConstants.TYPE_CONTENT)) {
-                NodeList children = element.getChildNodes();
-                if (null != children) {
-                    serializedOctets = serializer.serializeToByteArray(children);
-                } else {
-                    Object exArgs[] = { "Element has no content." };
-                    throw new XMLEncryptionException("empty", exArgs);
-                }
-            } else {
-                serializedOctets = serializer.serializeToByteArray(element);
-            }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8"));
-            }
-        }
-
-        byte[] encryptedBytes = null;
-
-        // Now create the working cipher if none was created already
-        Cipher c;
-        if (contextCipher == null) {
-            c = constructCipher(algorithm, null);
-        } else {
-            c = contextCipher;
-        }
-        // Now perform the encryption
-
-        try {
-            // The Spec mandates a 96-bit IV for GCM algorithms
-            if (AES_128_GCM.equals(algorithm) || AES_192_GCM.equals(algorithm)
-                || AES_256_GCM.equals(algorithm)) {
-                if (random == null) {
-                    random = SecureRandom.getInstance("SHA1PRNG");
-                }
-                byte[] temp = new byte[12];
-                random.nextBytes(temp);
-                IvParameterSpec paramSpec = new IvParameterSpec(temp);
-                c.init(cipherMode, key, paramSpec);
-            } else {
-                c.init(cipherMode, key);
-            }
-        } catch (InvalidKeyException ike) {
-            throw new XMLEncryptionException("empty", ike);
-        } catch (NoSuchAlgorithmException ex) {
-            throw new XMLEncryptionException("empty", ex);
-        }
-
-        try {
-            if (serializedData != null) {
-                int numBytes;
-                byte[] buf = new byte[8192];
-                ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                while ((numBytes = serializedData.read(buf)) != -1) {
-                    byte[] data = c.update(buf, 0, numBytes);
-                    baos.write(data);
-                }
-                baos.write(c.doFinal());
-                encryptedBytes = baos.toByteArray();
-            } else {
-                encryptedBytes = c.doFinal(serializedOctets);
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
-                        Integer.toString(c.getOutputSize(serializedOctets.length)));
-                }
-            }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = "
-                             + Integer.toString(encryptedBytes.length));
-            }
-        } catch (IllegalStateException ise) {
-            throw new XMLEncryptionException("empty", ise);
-        } catch (IllegalBlockSizeException ibse) {
-            throw new XMLEncryptionException("empty", ibse);
-        } catch (BadPaddingException bpe) {
-            throw new XMLEncryptionException("empty", bpe);
-        } catch (UnsupportedEncodingException uee) {
-            throw new XMLEncryptionException("empty", uee);
-        }
-
-        // Now build up to a properly XML Encryption encoded octet stream
-        // IvParameterSpec iv;
-        byte[] iv = c.getIV();
-        byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
-        System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
-        System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);
-        String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);
-
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
-            log.log(java.util.logging.Level.FINE, "Encrypted octets length = " + base64EncodedEncryptedOctets.length());
-        }
-
-        try {
-            CipherData cd = ed.getCipherData();
-            CipherValue cv = cd.getCipherValue();
-            // cv.setValue(base64EncodedEncryptedOctets.getBytes());
-            cv.setValue(base64EncodedEncryptedOctets);
-
-            if (type != null) {
-                ed.setType(new URI(type).toString());
-            }
-            EncryptionMethod method =
-                factory.newEncryptionMethod(new URI(algorithm).toString());
-            method.setDigestAlgorithm(digestAlg);
-            ed.setEncryptionMethod(method);
-        } catch (URISyntaxException ex) {
-            throw new XMLEncryptionException("empty", ex);
-        }
-        return ed;
-    }
-
-    /**
-     * Returns an <code>EncryptedData</code> interface. Use this operation if
-     * you want to load an <code>EncryptedData</code> structure from a DOM
-     * structure and manipulate the contents.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> that will be loaded
-     * @throws XMLEncryptionException
-     * @return the <code>EncryptedData</code>
-     */
-    public EncryptedData loadEncryptedData(Document context, Element element)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Loading encrypted element...");
-        }
-        if (null == context) {
-            throw new NullPointerException("Context document unexpectedly null...");
-        }
-        if (null == element) {
-            throw new NullPointerException("Element unexpectedly null...");
-        }
-        if (cipherMode != DECRYPT_MODE) {
-            throw new XMLEncryptionException("XMLCipher unexpectedly not in DECRYPT_MODE...");
-        }
-
-        contextDocument = context;
-        ed = factory.newEncryptedData(element);
-
-        return ed;
-    }
-
-    /**
-     * Returns an <code>EncryptedKey</code> interface. Use this operation if
-     * you want to load an <code>EncryptedKey</code> structure from a DOM
-     * structure and manipulate the contents.
-     *
-     * @param context the context <code>Document</code>.
-     * @param element the <code>Element</code> that will be loaded
-     * @return the <code>EncryptedKey</code>
-     * @throws XMLEncryptionException
-     */
-    public EncryptedKey loadEncryptedKey(Document context, Element element)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Loading encrypted key...");
-        }
-        if (null == context) {
-            throw new NullPointerException("Context document unexpectedly null...");
-        }
-        if (null == element) {
-            throw new NullPointerException("Element unexpectedly null...");
-        }
-        if (cipherMode != UNWRAP_MODE && cipherMode != DECRYPT_MODE) {
-            throw new XMLEncryptionException(
-                "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."
-            );
-        }
-
-        contextDocument = context;
-        ek = factory.newEncryptedKey(element);
-        return ek;
-    }
-
-    /**
-     * Returns an <code>EncryptedKey</code> interface. Use this operation if
-     * you want to load an <code>EncryptedKey</code> structure from a DOM
-     * structure and manipulate the contents.
-     *
-     * Assumes that the context document is the document that owns the element
-     *
-     * @param element the <code>Element</code> that will be loaded
-     * @return the <code>EncryptedKey</code>
-     * @throws XMLEncryptionException
-     */
-    public EncryptedKey loadEncryptedKey(Element element) throws XMLEncryptionException {
-        return loadEncryptedKey(element.getOwnerDocument(), element);
-    }
-
-    /**
-     * Encrypts a key to an EncryptedKey structure
-     *
-     * @param doc the Context document that will be used to general DOM
-     * @param key Key to encrypt (will use previously set KEK to
-     * perform encryption
-     * @return the <code>EncryptedKey</code>
-     * @throws XMLEncryptionException
-     */
-    public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException {
-        return encryptKey(doc, key, null, null);
-    }
-
-    /**
-     * Encrypts a key to an EncryptedKey structure
-     *
-     * @param doc the Context document that will be used to general DOM
-     * @param key Key to encrypt (will use previously set KEK to
-     * perform encryption
-     * @param mgfAlgorithm The xenc11 MGF Algorithm to use
-     * @param oaepParams The OAEPParams to use
-     * @return the <code>EncryptedKey</code>
-     * @throws XMLEncryptionException
-     */
-    public EncryptedKey encryptKey(
-        Document doc,
-        Key key,
-        String mgfAlgorithm,
-        byte[] oaepParams
-    ) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypting key ...");
-        }
-
-        if (null == key) {
-            log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
-        }
-        if (cipherMode != WRAP_MODE) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
-        }
-        if (algorithm == null) {
-            throw new XMLEncryptionException("XMLCipher instance without transformation specified");
-        }
-
-        contextDocument = doc;
-
-        byte[] encryptedBytes = null;
-        Cipher c;
-
-        if (contextCipher == null) {
-            // Now create the working cipher
-            c = constructCipher(algorithm, null);
-        } else {
-            c = contextCipher;
-        }
-        // Now perform the encryption
-
-        try {
-            // Should internally generate an IV
-            // todo - allow user to set an IV
-            OAEPParameterSpec oaepParameters =
-                constructOAEPParameters(
-                    algorithm, digestAlg, mgfAlgorithm, oaepParams
-                );
-            if (oaepParameters == null) {
-                c.init(Cipher.WRAP_MODE, this.key);
-            } else {
-                c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
-            }
-            encryptedBytes = c.wrap(key);
-        } catch (InvalidKeyException ike) {
-            throw new XMLEncryptionException("empty", ike);
-        } catch (IllegalBlockSizeException ibse) {
-            throw new XMLEncryptionException("empty", ibse);
-        } catch (InvalidAlgorithmParameterException e) {
-            throw new XMLEncryptionException("empty", e);
-        }
-
-        String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
-            log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
-        }
-
-        CipherValue cv = ek.getCipherData().getCipherValue();
-        cv.setValue(base64EncodedEncryptedOctets);
-
-        try {
-            EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
-            method.setDigestAlgorithm(digestAlg);
-            method.setMGFAlgorithm(mgfAlgorithm);
-            method.setOAEPparams(oaepParams);
-            ek.setEncryptionMethod(method);
-        } catch (URISyntaxException ex) {
-            throw new XMLEncryptionException("empty", ex);
-        }
-        return ek;
-    }
-
-    /**
-     * Decrypt a key from a passed in EncryptedKey structure
-     *
-     * @param encryptedKey Previously loaded EncryptedKey that needs
-     * to be decrypted.
-     * @param algorithm Algorithm for the decryption
-     * @return a key corresponding to the given type
-     * @throws XMLEncryptionException
-     */
-    public Key decryptKey(EncryptedKey encryptedKey, String algorithm)
-        throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
-        }
-
-        if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE...");
-        }
-
-        if (algorithm == null) {
-            throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm");
-        }
-
-        if (key == null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers");
-            }
-
-            KeyInfo ki = encryptedKey.getKeyInfo();
-            if (ki != null) {
-                ki.setSecureValidation(secureValidation);
-                try {
-                    String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
-                    String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
-                    if ("RSA".equals(keyType)) {
-                        key = ki.getPrivateKey();
-                    } else {
-                        key = ki.getSecretKey();
-                    }
-                }
-                catch (Exception e) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                    }
-                }
-            }
-            if (key == null) {
-                log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve");
-                throw new XMLEncryptionException("Unable to decrypt without a KEK");
-            }
-        }
-
-        // Obtain the encrypted octets
-        XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
-        cipherInput.setSecureValidation(secureValidation);
-        byte[] encryptedBytes = cipherInput.getBytes();
-
-        String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "JCE Key Algorithm: " + jceKeyAlgorithm);
-        }
-
-        Cipher c;
-        if (contextCipher == null) {
-            // Now create the working cipher
-            c =
-                constructCipher(
-                    encryptedKey.getEncryptionMethod().getAlgorithm(),
-                    encryptedKey.getEncryptionMethod().getDigestAlgorithm()
-                );
-        } else {
-            c = contextCipher;
-        }
-
-        Key ret;
-
-        try {
-            EncryptionMethod encMethod = encryptedKey.getEncryptionMethod();
-            OAEPParameterSpec oaepParameters =
-                constructOAEPParameters(
-                    encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(),
-                    encMethod.getMGFAlgorithm(), encMethod.getOAEPparams()
-                );
-            if (oaepParameters == null) {
-                c.init(Cipher.UNWRAP_MODE, key);
-            } else {
-                c.init(Cipher.UNWRAP_MODE, key, oaepParameters);
-            }
-            ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
-        } catch (InvalidKeyException ike) {
-            throw new XMLEncryptionException("empty", ike);
-        } catch (NoSuchAlgorithmException nsae) {
-            throw new XMLEncryptionException("empty", nsae);
-        } catch (InvalidAlgorithmParameterException e) {
-            throw new XMLEncryptionException("empty", e);
-        }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
-        }
-
-        return ret;
-    }
-
-    /**
-     * Construct an OAEPParameterSpec object from the given parameters
-     */
-    private OAEPParameterSpec constructOAEPParameters(
-        String encryptionAlgorithm,
-        String digestAlgorithm,
-        String mgfAlgorithm,
-        byte[] oaepParams
-    ) {
-        if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm)
-            || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
-
-            String jceDigestAlgorithm = "SHA-1";
-            if (digestAlgorithm != null) {
-                jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm);
-            }
-
-            PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
-            if (oaepParams != null) {
-                pSource = new PSource.PSpecified(oaepParams);
-            }
-
-            MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
-            if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
-                if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) {
-                    mgfParameterSpec = new MGF1ParameterSpec("SHA-256");
-                } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) {
-                    mgfParameterSpec = new MGF1ParameterSpec("SHA-384");
-                } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) {
-                    mgfParameterSpec = new MGF1ParameterSpec("SHA-512");
-                }
-            }
-            return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
-        }
-
-        return null;
-    }
-
-    /**
-     * Construct a Cipher object
-     */
-    private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException {
-        String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
-        }
-
-        Cipher c;
-        try {
-            if (requestedJCEProvider == null) {
-                c = Cipher.getInstance(jceAlgorithm);
-            } else {
-                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
-            }
-        } catch (NoSuchAlgorithmException nsae) {
-            // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested
-            // Some JDKs don't support RSA/ECB/OAEPPadding
-            if (XMLCipher.RSA_OAEP.equals(algorithm)
-                && (digestAlgorithm == null
-                    || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) {
-                try {
-                    if (requestedJCEProvider == null) {
-                        c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
-                    } else {
-                        c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider);
-                    }
-                } catch (Exception ex) {
-                    throw new XMLEncryptionException("empty", ex);
-                }
-            } else {
-                throw new XMLEncryptionException("empty", nsae);
-            }
-        } catch (NoSuchProviderException nspre) {
-            throw new XMLEncryptionException("empty", nspre);
-        } catch (NoSuchPaddingException nspae) {
-            throw new XMLEncryptionException("empty", nspae);
-        }
-
-        return c;
-    }
-
-    /**
-     * Decrypt a key from a passed in EncryptedKey structure.  This version
-     * is used mainly internally, when  the cipher already has an
-     * EncryptedData loaded.  The algorithm URI will be read from the
-     * EncryptedData
-     *
-     * @param encryptedKey Previously loaded EncryptedKey that needs
-     * to be decrypted.
-     * @return a key corresponding to the given type
-     * @throws XMLEncryptionException
-     */
-    public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException {
-        return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm());
-    }
-
-    /**
-     * Removes the contents of a <code>Node</code>.
-     *
-     * @param node the <code>Node</code> to clear.
-     */
-    private static void removeContent(Node node) {
-        while (node.hasChildNodes()) {
-            node.removeChild(node.getFirstChild());
-        }
-    }
-
-    /**
-     * Decrypts <code>EncryptedData</code> in a single-part operation.
-     *
-     * @param element the <code>EncryptedData</code> to decrypt.
-     * @return the <code>Node</code> as a result of the decrypt operation.
-     * @throws XMLEncryptionException
-     */
-    private Document decryptElement(Element element) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Decrypting element...");
-        }
-
-        if (cipherMode != DECRYPT_MODE) {
-            log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-        }
-
-        byte[] octets = decryptToByteArray(element);
-
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
-        }
-
-        Node sourceParent = element.getParentNode();
-        Node decryptedNode = serializer.deserialize(octets, sourceParent);
-
-        // The de-serialiser returns a node whose children we need to take on.
-        if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
-            // If this is a content decryption, this may have problems
-            contextDocument.removeChild(contextDocument.getDocumentElement());
-            contextDocument.appendChild(decryptedNode);
-        } else if (sourceParent != null) {
-            sourceParent.replaceChild(decryptedNode, element);
-        }
-
-        return contextDocument;
-    }
-
-    /**
-     *
-     * @param element
-     * @return the <code>Node</code> as a result of the decrypt operation.
-     * @throws XMLEncryptionException
-     */
-    private Document decryptElementContent(Element element) throws XMLEncryptionException {
-        Element e =
-            (Element) element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_ENCRYPTEDDATA
-            ).item(0);
-
-        if (null == e) {
-            throw new XMLEncryptionException("No EncryptedData child element.");
-        }
-
-        return decryptElement(e);
-    }
-
-    /**
-     * Decrypt an EncryptedData element to a byte array.
-     *
-     * When passed in an EncryptedData node, returns the decryption
-     * as a byte array.
-     *
-     * Does not modify the source document.
-     * @param element
-     * @return the bytes resulting from the decryption
-     * @throws XMLEncryptionException
-     */
-    public byte[] decryptToByteArray(Element element) throws XMLEncryptionException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
-        }
-
-        if (cipherMode != DECRYPT_MODE) {
-            log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-        }
-
-        EncryptedData encryptedData = factory.newEncryptedData(element);
-
-        if (key == null) {
-            KeyInfo ki = encryptedData.getKeyInfo();
-            if (ki != null) {
-                try {
-                    // Add an EncryptedKey resolver
-                    String encMethodAlgorithm = encryptedData.getEncryptionMethod().getAlgorithm();
-                    EncryptedKeyResolver resolver = new EncryptedKeyResolver(encMethodAlgorithm, kek);
-                    if (internalKeyResolvers != null) {
-                        int size = internalKeyResolvers.size();
-                        for (int i = 0; i < size; i++) {
-                            resolver.registerInternalKeyResolver(internalKeyResolvers.get(i));
-                        }
-                    }
-                    ki.registerInternalKeyResolver(resolver);
-                    ki.setSecureValidation(secureValidation);
-                    key = ki.getSecretKey();
-                } catch (KeyResolverException kre) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, kre.getMessage(), kre);
-                    }
-                }
-            }
-
-            if (key == null) {
-                log.log(java.util.logging.Level.SEVERE,
-                    "XMLCipher::decryptElement called without a key and unable to resolve"
-                );
-                throw new XMLEncryptionException("encryption.nokey");
-            }
-        }
-
-        // Obtain the encrypted octets
-        XMLCipherInput cipherInput = new XMLCipherInput(encryptedData);
-        cipherInput.setSecureValidation(secureValidation);
-        byte[] encryptedBytes = cipherInput.getBytes();
-
-        // Now create the working cipher
-        String jceAlgorithm =
-            JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm());
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
-        }
-
-        Cipher c;
-        try {
-            if (requestedJCEProvider == null) {
-                c = Cipher.getInstance(jceAlgorithm);
-            } else {
-                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
-            }
-        } catch (NoSuchAlgorithmException nsae) {
-            throw new XMLEncryptionException("empty", nsae);
-        } catch (NoSuchProviderException nspre) {
-            throw new XMLEncryptionException("empty", nspre);
-        } catch (NoSuchPaddingException nspae) {
-            throw new XMLEncryptionException("empty", nspae);
-        }
-
-        // Calculate the IV length and copy out
-
-        // For now, we only work with Block ciphers, so this will work.
-        // This should probably be put into the JCE mapper.
-
-        int ivLen = c.getBlockSize();
-        String alg = encryptedData.getEncryptionMethod().getAlgorithm();
-        if (AES_128_GCM.equals(alg) || AES_192_GCM.equals(alg) || AES_256_GCM.equals(alg)) {
-            ivLen = 12;
-        }
-        byte[] ivBytes = new byte[ivLen];
-
-        // You may be able to pass the entire piece in to IvParameterSpec
-        // and it will only take the first x bytes, but no way to be certain
-        // that this will work for every JCE provider, so lets copy the
-        // necessary bytes into a dedicated array.
-
-        System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen);
-        IvParameterSpec iv = new IvParameterSpec(ivBytes);
-
-        try {
-            c.init(cipherMode, key, iv);
-        } catch (InvalidKeyException ike) {
-            throw new XMLEncryptionException("empty", ike);
-        } catch (InvalidAlgorithmParameterException iape) {
-            throw new XMLEncryptionException("empty", iape);
-        }
-
-        try {
-            return c.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen);
-        } catch (IllegalBlockSizeException ibse) {
-            throw new XMLEncryptionException("empty", ibse);
-        } catch (BadPaddingException bpe) {
-            throw new XMLEncryptionException("empty", bpe);
-        }
-    }
-
-    /*
-     * Expose the interface for creating XML Encryption objects
-     */
-
-    /**
-     * Creates an <code>EncryptedData</code> <code>Element</code>.
-     *
-     * The newEncryptedData and newEncryptedKey methods create fairly complete
-     * elements that are immediately useable.  All the other create* methods
-     * return bare elements that still need to be built upon.
-     *<p>
-     * An EncryptionMethod will still need to be added however
-     *
-     * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
-     * CipherData this EncryptedData will contain.
-     * @param value the Base 64 encoded, encrypted text to wrap in the
-     *   <code>EncryptedData</code> or the URI to set in the CipherReference
-     * (usage will depend on the <code>type</code>
-     * @return the <code>EncryptedData</code> <code>Element</code>.
-     *
-     * <!--
-     * <EncryptedData Id[OPT] Type[OPT] MimeType[OPT] Encoding[OPT]>
-     *     <EncryptionMethod/>[OPT]
-     *     <ds:KeyInfo>[OPT]
-     *         <EncryptedKey/>[OPT]
-     *         <AgreementMethod/>[OPT]
-     *         <ds:KeyName/>[OPT]
-     *         <ds:RetrievalMethod/>[OPT]
-     *         <ds:[MUL]/>[OPT]
-     *     </ds:KeyInfo>
-     *     <CipherData>[MAN]
-     *         <CipherValue/> XOR <CipherReference/>
-     *     </CipherData>
-     *     <EncryptionProperties/>[OPT]
-     * </EncryptedData>
-     * -->
-     * @throws XMLEncryptionException
-     */
-    public EncryptedData createEncryptedData(int type, String value) throws XMLEncryptionException {
-        EncryptedData result = null;
-        CipherData data = null;
-
-        switch (type) {
-        case CipherData.REFERENCE_TYPE:
-            CipherReference cipherReference = factory.newCipherReference(value);
-            data = factory.newCipherData(type);
-            data.setCipherReference(cipherReference);
-            result = factory.newEncryptedData(data);
-            break;
-        case CipherData.VALUE_TYPE:
-            CipherValue cipherValue = factory.newCipherValue(value);
-            data = factory.newCipherData(type);
-            data.setCipherValue(cipherValue);
-            result = factory.newEncryptedData(data);
-        }
-
-        return result;
-    }
-
-    /**
-     * Creates an <code>EncryptedKey</code> <code>Element</code>.
-     *
-     * The newEncryptedData and newEncryptedKey methods create fairly complete
-     * elements that are immediately useable.  All the other create* methods
-     * return bare elements that still need to be built upon.
-     *<p>
-     * An EncryptionMethod will still need to be added however
-     *
-     * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of
-     * CipherData this EncryptedData will contain.
-     * @param value the Base 64 encoded, encrypted text to wrap in the
-     *   <code>EncryptedKey</code> or the URI to set in the CipherReference
-     * (usage will depend on the <code>type</code>
-     * @return the <code>EncryptedKey</code> <code>Element</code>.
-     *
-     * <!--
-     * <EncryptedKey Id[OPT] Type[OPT] MimeType[OPT] Encoding[OPT]>
-     *     <EncryptionMethod/>[OPT]
-     *     <ds:KeyInfo>[OPT]
-     *         <EncryptedKey/>[OPT]
-     *         <AgreementMethod/>[OPT]
-     *         <ds:KeyName/>[OPT]
-     *         <ds:RetrievalMethod/>[OPT]
-     *         <ds:[MUL]/>[OPT]
-     *     </ds:KeyInfo>
-     *     <CipherData>[MAN]
-     *         <CipherValue/> XOR <CipherReference/>
-     *     </CipherData>
-     *     <EncryptionProperties/>[OPT]
-     * </EncryptedData>
-     * -->
-     * @throws XMLEncryptionException
-     */
-    public EncryptedKey createEncryptedKey(int type, String value) throws XMLEncryptionException {
-        EncryptedKey result = null;
-        CipherData data = null;
-
-        switch (type) {
-        case CipherData.REFERENCE_TYPE:
-            CipherReference cipherReference = factory.newCipherReference(value);
-            data = factory.newCipherData(type);
-            data.setCipherReference(cipherReference);
-            result = factory.newEncryptedKey(data);
-            break;
-        case CipherData.VALUE_TYPE:
-            CipherValue cipherValue = factory.newCipherValue(value);
-            data = factory.newCipherData(type);
-            data.setCipherValue(cipherValue);
-            result = factory.newEncryptedKey(data);
-        }
-
-        return result;
-    }
-
-    /**
-     * Create an AgreementMethod object
-     *
-     * @param algorithm Algorithm of the agreement method
-     * @return a new <code>AgreementMethod</code>
-     */
-    public AgreementMethod createAgreementMethod(String algorithm) {
-        return factory.newAgreementMethod(algorithm);
-    }
-
-    /**
-     * Create a CipherData object
-     *
-     * @param type Type of this CipherData (either VALUE_TUPE or
-     * REFERENCE_TYPE)
-     * @return a new <code>CipherData</code>
-     */
-    public CipherData createCipherData(int type) {
-        return factory.newCipherData(type);
-    }
-
-    /**
-     * Create a CipherReference object
-     *
-     * @param uri The URI that the reference will refer
-     * @return a new <code>CipherReference</code>
-     */
-    public CipherReference createCipherReference(String uri) {
-        return factory.newCipherReference(uri);
-    }
-
-    /**
-     * Create a CipherValue element
-     *
-     * @param value The value to set the ciphertext to
-     * @return a new <code>CipherValue</code>
-     */
-    public CipherValue createCipherValue(String value) {
-        return factory.newCipherValue(value);
-    }
-
-    /**
-     * Create an EncryptionMethod object
-     *
-     * @param algorithm Algorithm for the encryption
-     * @return a new <code>EncryptionMethod</code>
-     */
-    public EncryptionMethod createEncryptionMethod(String algorithm) {
-        return factory.newEncryptionMethod(algorithm);
-    }
-
-    /**
-     * Create an EncryptionProperties element
-     * @return a new <code>EncryptionProperties</code>
-     */
-    public EncryptionProperties createEncryptionProperties() {
-        return factory.newEncryptionProperties();
-    }
-
-    /**
-     * Create a new EncryptionProperty element
-     * @return a new <code>EncryptionProperty</code>
-     */
-    public EncryptionProperty createEncryptionProperty() {
-        return factory.newEncryptionProperty();
-    }
-
-    /**
-     * Create a new ReferenceList object
-     * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
-     * @return a new <code>ReferenceList</code>
-     */
-    public ReferenceList createReferenceList(int type) {
-        return factory.newReferenceList(type);
-    }
-
-    /**
-     * Create a new Transforms object
-     * <p>
-     * <b>Note</b>: A context document <i>must</i> have been set
-     * elsewhere (possibly via a call to doFinal).  If not, use the
-     * createTransforms(Document) method.
-     * @return a new <code>Transforms</code>
-     */
-    public Transforms createTransforms() {
-        return factory.newTransforms();
-    }
-
-    /**
-     * Create a new Transforms object
-     *
-     * Because the handling of Transforms is currently done in the signature
-     * code, the creation of a Transforms object <b>requires</b> a
-     * context document.
-     *
-     * @param doc Document that will own the created Transforms node
-     * @return a new <code>Transforms</code>
-     */
-    public Transforms createTransforms(Document doc) {
-        return factory.newTransforms(doc);
-    }
-
-    /**
-     *
-     * @author Axl Mattheus
-     */
-    private class Factory {
-        /**
-         * @param algorithm
-         * @return a new AgreementMethod
-         */
-        AgreementMethod newAgreementMethod(String algorithm)  {
-            return new AgreementMethodImpl(algorithm);
-        }
-
-        /**
-         * @param type
-         * @return a new CipherData
-         *
-         */
-        CipherData newCipherData(int type) {
-            return new CipherDataImpl(type);
-        }
-
-        /**
-         * @param uri
-         * @return a new CipherReference
-         */
-        CipherReference newCipherReference(String uri)  {
-            return new CipherReferenceImpl(uri);
-        }
-
-        /**
-         * @param value
-         * @return a new CipherValue
-         */
-        CipherValue newCipherValue(String value) {
-            return new CipherValueImpl(value);
-        }
-
-        /*
-        CipherValue newCipherValue(byte[] value) {
-            return new CipherValueImpl(value);
-        }
-         */
-
-        /**
-         * @param data
-         * @return a new EncryptedData
-         */
-        EncryptedData newEncryptedData(CipherData data) {
-            return new EncryptedDataImpl(data);
-        }
-
-        /**
-         * @param data
-         * @return a new EncryptedKey
-         */
-        EncryptedKey newEncryptedKey(CipherData data) {
-            return new EncryptedKeyImpl(data);
-        }
-
-        /**
-         * @param algorithm
-         * @return a new EncryptionMethod
-         */
-        EncryptionMethod newEncryptionMethod(String algorithm) {
-            return new EncryptionMethodImpl(algorithm);
-        }
-
-        /**
-         * @return a new EncryptionProperties
-         */
-        EncryptionProperties newEncryptionProperties() {
-            return new EncryptionPropertiesImpl();
-        }
-
-        /**
-         * @return a new EncryptionProperty
-         */
-        EncryptionProperty newEncryptionProperty() {
-            return new EncryptionPropertyImpl();
-        }
-
-        /**
-         * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
-         * @return a new ReferenceList
-         */
-        ReferenceList newReferenceList(int type) {
-            return new ReferenceListImpl(type);
-        }
-
-        /**
-         * @return a new Transforms
-         */
-        Transforms newTransforms() {
-            return new TransformsImpl();
-        }
-
-        /**
-         * @param doc
-         * @return a new Transforms
-         */
-        Transforms newTransforms(Document doc) {
-            return new TransformsImpl(doc);
-        }
-
-        /**
-         * @param element
-         * @return a new CipherData
-         * @throws XMLEncryptionException
-         */
-        CipherData newCipherData(Element element) throws XMLEncryptionException {
-            if (null == element) {
-                throw new NullPointerException("element is null");
-            }
-
-            int type = 0;
-            Element e = null;
-            if (element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0
-            ) {
-                type = CipherData.VALUE_TYPE;
-                e = (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CIPHERVALUE).item(0);
-            } else if (element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_CIPHERREFERENCE).getLength() > 0) {
-                type = CipherData.REFERENCE_TYPE;
-                e = (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CIPHERREFERENCE).item(0);
-            }
-
-            CipherData result = newCipherData(type);
-            if (type == CipherData.VALUE_TYPE) {
-                result.setCipherValue(newCipherValue(e));
-            } else if (type == CipherData.REFERENCE_TYPE) {
-                result.setCipherReference(newCipherReference(e));
-            }
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new CipherReference
-         * @throws XMLEncryptionException
-         *
-         */
-        CipherReference newCipherReference(Element element) throws XMLEncryptionException {
-
-            Attr uriAttr =
-                element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI);
-            CipherReference result = new CipherReferenceImpl(uriAttr);
-
-            // Find any Transforms
-            NodeList transformsElements =
-                element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS);
-            Element transformsElement = (Element) transformsElements.item(0);
-
-            if (transformsElement != null) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
-                }
-                try {
-                    result.setTransforms(new TransformsImpl(transformsElement));
-                } catch (XMLSignatureException xse) {
-                    throw new XMLEncryptionException("empty", xse);
-                } catch (InvalidTransformException ite) {
-                    throw new XMLEncryptionException("empty", ite);
-                } catch (XMLSecurityException xse) {
-                    throw new XMLEncryptionException("empty", xse);
-                }
-            }
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new CipherValue
-         */
-        CipherValue newCipherValue(Element element) {
-            String value = XMLUtils.getFullTextChildrenFromElement(element);
-
-            return newCipherValue(value);
-        }
-
-        /**
-         * @param element
-         * @return a new EncryptedData
-         * @throws XMLEncryptionException
-         *
-         */
-        EncryptedData newEncryptedData(Element element) throws XMLEncryptionException {
-            EncryptedData result = null;
-
-            NodeList dataElements =
-                element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
-
-            // Need to get the last CipherData found, as earlier ones will
-            // be for elements in the KeyInfo lists
-
-            Element dataElement =
-                (Element) dataElements.item(dataElements.getLength() - 1);
-
-            CipherData data = newCipherData(dataElement);
-
-            result = newEncryptedData(data);
-
-            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
-            result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
-            result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE));
-            result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING));
-
-            Element encryptionMethodElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0);
-            if (null != encryptionMethodElement) {
-                result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement));
-            }
-
-            // BFL 16/7/03 - simple implementation
-            // TODO: Work out how to handle relative URI
-
-            Element keyInfoElement =
-                (Element) element.getElementsByTagNameNS(
-                    Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0);
-            if (null != keyInfoElement) {
-                KeyInfo ki = newKeyInfo(keyInfoElement);
-                result.setKeyInfo(ki);
-            }
-
-            // TODO: Implement
-            Element encryptionPropertiesElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
-            if (null != encryptionPropertiesElement) {
-                result.setEncryptionProperties(
-                    newEncryptionProperties(encryptionPropertiesElement)
-                );
-            }
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new EncryptedKey
-         * @throws XMLEncryptionException
-         */
-        EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException {
-            EncryptedKey result = null;
-            NodeList dataElements =
-                element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
-            Element dataElement =
-                (Element) dataElements.item(dataElements.getLength() - 1);
-
-            CipherData data = newCipherData(dataElement);
-            result = newEncryptedKey(data);
-
-            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
-            result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
-            result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE));
-            result.setEncoding(element.getAttributeNS(null, Constants._ATT_ENCODING));
-            result.setRecipient(element.getAttributeNS(null, EncryptionConstants._ATT_RECIPIENT));
-
-            Element encryptionMethodElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0);
-            if (null != encryptionMethodElement) {
-                result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement));
-            }
-
-            Element keyInfoElement =
-                (Element) element.getElementsByTagNameNS(
-                    Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0);
-            if (null != keyInfoElement) {
-                KeyInfo ki = newKeyInfo(keyInfoElement);
-                result.setKeyInfo(ki);
-            }
-
-            // TODO: Implement
-            Element encryptionPropertiesElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
-            if (null != encryptionPropertiesElement) {
-                result.setEncryptionProperties(
-                    newEncryptionProperties(encryptionPropertiesElement)
-                );
-            }
-
-            Element referenceListElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_REFERENCELIST).item(0);
-            if (null != referenceListElement) {
-                result.setReferenceList(newReferenceList(referenceListElement));
-            }
-
-            Element carriedNameElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_CARRIEDKEYNAME).item(0);
-            if (null != carriedNameElement) {
-                result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue());
-            }
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new KeyInfo
-         * @throws XMLEncryptionException
-         */
-        KeyInfo newKeyInfo(Element element) throws XMLEncryptionException {
-            try {
-                KeyInfo ki = new KeyInfo(element, null);
-                ki.setSecureValidation(secureValidation);
-                if (internalKeyResolvers != null) {
-                    int size = internalKeyResolvers.size();
-                    for (int i = 0; i < size; i++) {
-                        ki.registerInternalKeyResolver(internalKeyResolvers.get(i));
-                    }
-                }
-                return ki;
-            } catch (XMLSecurityException xse) {
-                throw new XMLEncryptionException("Error loading Key Info", xse);
-            }
-        }
-
-        /**
-         * @param element
-         * @return a new EncryptionMethod
-         */
-        EncryptionMethod newEncryptionMethod(Element element) {
-            String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM);
-            EncryptionMethod result = newEncryptionMethod(encAlgorithm);
-
-            Element keySizeElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_KEYSIZE).item(0);
-            if (null != keySizeElement) {
-                result.setKeySize(
-                    Integer.valueOf(
-                        keySizeElement.getFirstChild().getNodeValue()).intValue());
-            }
-
-            Element oaepParamsElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_OAEPPARAMS).item(0);
-            if (null != oaepParamsElement) {
-                try {
-                    String oaepParams = oaepParamsElement.getFirstChild().getNodeValue();
-                    result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8")));
-                } catch(UnsupportedEncodingException e) {
-                    throw new RuntimeException("UTF-8 not supported", e);
-                } catch (Base64DecodingException e) {
-                    throw new RuntimeException("BASE-64 decoding error", e);
-                }
-            }
-
-            Element digestElement =
-                (Element) element.getElementsByTagNameNS(
-                    Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0);
-            if (digestElement != null) {
-                String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm");
-                result.setDigestAlgorithm(digestAlgorithm);
-            }
-
-            Element mgfElement =
-                (Element) element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0);
-            if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) {
-                String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm");
-                result.setMGFAlgorithm(mgfAlgorithm);
-            }
-
-            // TODO: Make this mess work
-            // <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new EncryptionProperties
-         */
-        EncryptionProperties newEncryptionProperties(Element element) {
-            EncryptionProperties result = newEncryptionProperties();
-
-            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
-
-            NodeList encryptionPropertyList =
-                element.getElementsByTagNameNS(
-                    EncryptionConstants.EncryptionSpecNS,
-                    EncryptionConstants._TAG_ENCRYPTIONPROPERTY);
-            for (int i = 0; i < encryptionPropertyList.getLength(); i++) {
-                Node n = encryptionPropertyList.item(i);
-                if (null != n) {
-                    result.addEncryptionProperty(newEncryptionProperty((Element) n));
-                }
-            }
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new EncryptionProperty
-         */
-        EncryptionProperty newEncryptionProperty(Element element) {
-            EncryptionProperty result = newEncryptionProperty();
-
-            result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET));
-            result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
-            // TODO: Make this lot work...
-            // <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
-
-            // TODO: Make this work...
-            // <any namespace='##other' processContents='lax'/>
-
-            return result;
-        }
-
-        /**
-         * @param element
-         * @return a new ReferenceList
-         */
-        ReferenceList newReferenceList(Element element) {
-            int type = 0;
-            if (null != element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_DATAREFERENCE).item(0)) {
-                type = ReferenceList.DATA_REFERENCE;
-            } else if (null != element.getElementsByTagNameNS(
-                EncryptionConstants.EncryptionSpecNS,
-                EncryptionConstants._TAG_KEYREFERENCE).item(0)) {
-                type = ReferenceList.KEY_REFERENCE;
-            }
-
-            ReferenceList result = new ReferenceListImpl(type);
-            NodeList list = null;
-            switch (type) {
-            case ReferenceList.DATA_REFERENCE:
-                list =
-                    element.getElementsByTagNameNS(
-                        EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_DATAREFERENCE);
-                for (int i = 0; i < list.getLength() ; i++) {
-                    String uri = ((Element) list.item(i)).getAttribute("URI");
-                    result.add(result.newDataReference(uri));
-                }
-                break;
-            case ReferenceList.KEY_REFERENCE:
-                list =
-                    element.getElementsByTagNameNS(
-                        EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_KEYREFERENCE);
-                for (int i = 0; i < list.getLength() ; i++) {
-                    String uri = ((Element) list.item(i)).getAttribute("URI");
-                    result.add(result.newKeyReference(uri));
-                }
-            }
-
-            return result;
-        }
-
-        /**
-         * @param encryptedData
-         * @return the XML Element form of that EncryptedData
-         */
-        Element toElement(EncryptedData encryptedData) {
-            return ((EncryptedDataImpl) encryptedData).toElement();
-        }
-
-        /**
-         * @param encryptedKey
-         * @return the XML Element form of that EncryptedKey
-         */
-        Element toElement(EncryptedKey encryptedKey) {
-            return ((EncryptedKeyImpl) encryptedKey).toElement();
-        }
-
-        /**
-         * @param referenceList
-         * @return the XML Element form of that ReferenceList
-         */
-        Element toElement(ReferenceList referenceList) {
-            return ((ReferenceListImpl) referenceList).toElement();
-        }
-
-        private class AgreementMethodImpl implements AgreementMethod {
-            private byte[] kaNonce = null;
-            private List<Element> agreementMethodInformation = null;
-            private KeyInfo originatorKeyInfo = null;
-            private KeyInfo recipientKeyInfo = null;
-            private String algorithmURI = null;
-
-            /**
-             * @param algorithm
-             */
-            public AgreementMethodImpl(String algorithm) {
-                agreementMethodInformation = new LinkedList<Element>();
-                URI tmpAlgorithm = null;
-                try {
-                    tmpAlgorithm = new URI(algorithm);
-                } catch (URISyntaxException ex) {
-                    throw (IllegalArgumentException)
-                    new IllegalArgumentException().initCause(ex);
-                }
-                algorithmURI = tmpAlgorithm.toString();
-            }
-
-            /** @inheritDoc */
-            public byte[] getKANonce() {
-                return kaNonce;
-            }
-
-            /** @inheritDoc */
-            public void setKANonce(byte[] kanonce) {
-                kaNonce = kanonce;
-            }
-
-            /** @inheritDoc */
-            public Iterator<Element> getAgreementMethodInformation() {
-                return agreementMethodInformation.iterator();
-            }
-
-            /** @inheritDoc */
-            public void addAgreementMethodInformation(Element info) {
-                agreementMethodInformation.add(info);
-            }
-
-            /** @inheritDoc */
-            public void revoveAgreementMethodInformation(Element info) {
-                agreementMethodInformation.remove(info);
-            }
-
-            /** @inheritDoc */
-            public KeyInfo getOriginatorKeyInfo() {
-                return originatorKeyInfo;
-            }
-
-            /** @inheritDoc */
-            public void setOriginatorKeyInfo(KeyInfo keyInfo) {
-                originatorKeyInfo = keyInfo;
-            }
-
-            /** @inheritDoc */
-            public KeyInfo getRecipientKeyInfo() {
-                return recipientKeyInfo;
-            }
-
-            /** @inheritDoc */
-            public void setRecipientKeyInfo(KeyInfo keyInfo) {
-                recipientKeyInfo = keyInfo;
-            }
-
-            /** @inheritDoc */
-            public String getAlgorithm() {
-                return algorithmURI;
-            }
-        }
-
-        private class CipherDataImpl implements CipherData {
-            private static final String valueMessage =
-                "Data type is reference type.";
-            private static final String referenceMessage =
-                "Data type is value type.";
-            private CipherValue cipherValue = null;
-            private CipherReference cipherReference = null;
-            private int cipherType = Integer.MIN_VALUE;
-
-            /**
-             * @param type
-             */
-            public CipherDataImpl(int type) {
-                cipherType = type;
-            }
-
-            /** @inheritDoc */
-            public CipherValue getCipherValue() {
-                return cipherValue;
-            }
-
-            /** @inheritDoc */
-            public void setCipherValue(CipherValue value) throws XMLEncryptionException {
-
-                if (cipherType == REFERENCE_TYPE) {
-                    throw new XMLEncryptionException(
-                        "empty", new UnsupportedOperationException(valueMessage)
-                    );
-                }
-
-                cipherValue = value;
-            }
-
-            /** @inheritDoc */
-            public CipherReference getCipherReference() {
-                return cipherReference;
-            }
-
-            /** @inheritDoc */
-            public void setCipherReference(CipherReference reference) throws
-            XMLEncryptionException {
-                if (cipherType == VALUE_TYPE) {
-                    throw new XMLEncryptionException(
-                        "empty", new UnsupportedOperationException(referenceMessage)
-                    );
-                }
-
-                cipherReference = reference;
-            }
-
-            /** @inheritDoc */
-            public int getDataType() {
-                return cipherType;
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_CIPHERDATA
-                    );
-                if (cipherType == VALUE_TYPE) {
-                    result.appendChild(((CipherValueImpl) cipherValue).toElement());
-                } else if (cipherType == REFERENCE_TYPE) {
-                    result.appendChild(((CipherReferenceImpl) cipherReference).toElement());
-                }
-
-                return result;
-            }
-        }
-
-        private class CipherReferenceImpl implements CipherReference {
-            private String referenceURI = null;
-            private Transforms referenceTransforms = null;
-            private Attr referenceNode = null;
-
-            /**
-             * @param uri
-             */
-            public CipherReferenceImpl(String uri) {
-                /* Don't check validity of URI as may be "" */
-                referenceURI = uri;
-                referenceNode = null;
-            }
-
-            /**
-             * @param uri
-             */
-            public CipherReferenceImpl(Attr uri) {
-                referenceURI = uri.getNodeValue();
-                referenceNode = uri;
-            }
-
-            /** @inheritDoc */
-            public String getURI() {
-                return referenceURI;
-            }
-
-            /** @inheritDoc */
-            public Attr getURIAsAttr() {
-                return referenceNode;
-            }
-
-            /** @inheritDoc */
-            public Transforms getTransforms() {
-                return referenceTransforms;
-            }
-
-            /** @inheritDoc */
-            public void setTransforms(Transforms transforms) {
-                referenceTransforms = transforms;
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE
-                    );
-                result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI);
-                if (null != referenceTransforms) {
-                    result.appendChild(((TransformsImpl) referenceTransforms).toElement());
-                }
-
-                return result;
-            }
-        }
-
-        private class CipherValueImpl implements CipherValue {
-            private String cipherValue = null;
-
-            /**
-             * @param value
-             */
-            public CipherValueImpl(String value) {
-                cipherValue = value;
-            }
-
-            /** @inheritDoc */
-            public String getValue() {
-                return cipherValue;
-            }
-
-            /** @inheritDoc */
-            public void setValue(String value) {
-                cipherValue = value;
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_CIPHERVALUE
-                    );
-                result.appendChild(contextDocument.createTextNode(cipherValue));
-
-                return result;
-            }
-        }
-
-        private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData {
-
-            /**
-             * @param data
-             */
-            public EncryptedDataImpl(CipherData data) {
-                super(data);
-            }
-
-            Element toElement() {
-                Element result =
-                    ElementProxy.createElementForFamily(
-                        contextDocument, EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_ENCRYPTEDDATA
-                    );
-
-                if (null != super.getId()) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
-                }
-                if (null != super.getType()) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
-                }
-                if (null != super.getMimeType()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
-                    );
-                }
-                if (null != super.getEncoding()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_ENCODING, super.getEncoding()
-                    );
-                }
-                if (null != super.getEncryptionMethod()) {
-                    result.appendChild(
-                        ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement()
-                    );
-                }
-                if (null != super.getKeyInfo()) {
-                    result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
-                }
-
-                result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
-                if (null != super.getEncryptionProperties()) {
-                    result.appendChild(((EncryptionPropertiesImpl)
-                        super.getEncryptionProperties()).toElement());
-                }
-
-                return result;
-            }
-        }
-
-        private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey {
-            private String keyRecipient = null;
-            private ReferenceList referenceList = null;
-            private String carriedName = null;
-
-            /**
-             * @param data
-             */
-            public EncryptedKeyImpl(CipherData data) {
-                super(data);
-            }
-
-            /** @inheritDoc */
-            public String getRecipient() {
-                return keyRecipient;
-            }
-
-            /** @inheritDoc */
-            public void setRecipient(String recipient) {
-                keyRecipient = recipient;
-            }
-
-            /** @inheritDoc */
-            public ReferenceList getReferenceList() {
-                return referenceList;
-            }
-
-            /** @inheritDoc */
-            public void setReferenceList(ReferenceList list) {
-                referenceList = list;
-            }
-
-            /** @inheritDoc */
-            public String getCarriedName() {
-                return carriedName;
-            }
-
-            /** @inheritDoc */
-            public void setCarriedName(String name) {
-                carriedName = name;
-            }
-
-            Element toElement() {
-                Element result =
-                    ElementProxy.createElementForFamily(
-                        contextDocument, EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_ENCRYPTEDKEY
-                    );
-
-                if (null != super.getId()) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId());
-                }
-                if (null != super.getType()) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType());
-                }
-                if (null != super.getMimeType()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType()
-                    );
-                }
-                if (null != super.getEncoding()) {
-                    result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding());
-                }
-                if (null != getRecipient()) {
-                    result.setAttributeNS(
-                        null, EncryptionConstants._ATT_RECIPIENT, getRecipient()
-                    );
-                }
-                if (null != super.getEncryptionMethod()) {
-                    result.appendChild(((EncryptionMethodImpl)
-                        super.getEncryptionMethod()).toElement());
-                }
-                if (null != super.getKeyInfo()) {
-                    result.appendChild(super.getKeyInfo().getElement().cloneNode(true));
-                }
-                result.appendChild(((CipherDataImpl) super.getCipherData()).toElement());
-                if (null != super.getEncryptionProperties()) {
-                    result.appendChild(((EncryptionPropertiesImpl)
-                        super.getEncryptionProperties()).toElement());
-                }
-                if (referenceList != null && !referenceList.isEmpty()) {
-                    result.appendChild(((ReferenceListImpl)getReferenceList()).toElement());
-                }
-                if (null != carriedName) {
-                    Element element =
-                        ElementProxy.createElementForFamily(
-                            contextDocument,
-                            EncryptionConstants.EncryptionSpecNS,
-                            EncryptionConstants._TAG_CARRIEDKEYNAME
-                        );
-                    Node node = contextDocument.createTextNode(carriedName);
-                    element.appendChild(node);
-                    result.appendChild(element);
-                }
-
-                return result;
-            }
-        }
-
-        private abstract class EncryptedTypeImpl {
-            private String id =  null;
-            private String type = null;
-            private String mimeType = null;
-            private String encoding = null;
-            private EncryptionMethod encryptionMethod = null;
-            private KeyInfo keyInfo = null;
-            private CipherData cipherData = null;
-            private EncryptionProperties encryptionProperties = null;
-
-            /**
-             * Constructor.
-             * @param data
-             */
-            protected EncryptedTypeImpl(CipherData data) {
-                cipherData = data;
-            }
-
-            /**
-             *
-             * @return the Id
-             */
-            public String getId() {
-                return id;
-            }
-
-            /**
-             *
-             * @param id
-             */
-            public void setId(String id) {
-                this.id = id;
-            }
-
-            /**
-             *
-             * @return the type
-             */
-            public String getType() {
-                return type;
-            }
-
-            /**
-             *
-             * @param type
-             */
-            public void setType(String type) {
-                if (type == null || type.length() == 0) {
-                    this.type = null;
-                } else {
-                    URI tmpType = null;
-                    try {
-                        tmpType = new URI(type);
-                    } catch (URISyntaxException ex) {
-                        throw (IllegalArgumentException)
-                        new IllegalArgumentException().initCause(ex);
-                    }
-                    this.type = tmpType.toString();
-                }
-            }
-
-            /**
-             *
-             * @return the MimeType
-             */
-            public String getMimeType() {
-                return mimeType;
-            }
-            /**
-             *
-             * @param type
-             */
-            public void setMimeType(String type) {
-                mimeType = type;
-            }
-
-            /**
-             *
-             * @return the encoding
-             */
-            public String getEncoding() {
-                return encoding;
-            }
-
-            /**
-             *
-             * @param encoding
-             */
-            public void setEncoding(String encoding) {
-                if (encoding == null || encoding.length() == 0) {
-                    this.encoding = null;
-                } else {
-                    URI tmpEncoding = null;
-                    try {
-                        tmpEncoding = new URI(encoding);
-                    } catch (URISyntaxException ex) {
-                        throw (IllegalArgumentException)
-                        new IllegalArgumentException().initCause(ex);
-                    }
-                    this.encoding = tmpEncoding.toString();
-                }
-            }
-
-            /**
-             *
-             * @return the EncryptionMethod
-             */
-            public EncryptionMethod getEncryptionMethod() {
-                return encryptionMethod;
-            }
-
-            /**
-             *
-             * @param method
-             */
-            public void setEncryptionMethod(EncryptionMethod method) {
-                encryptionMethod = method;
-            }
-
-            /**
-             *
-             * @return the KeyInfo
-             */
-            public KeyInfo getKeyInfo() {
-                return keyInfo;
-            }
-
-            /**
-             *
-             * @param info
-             */
-            public void setKeyInfo(KeyInfo info) {
-                keyInfo = info;
-            }
-
-            /**
-             *
-             * @return the CipherData
-             */
-            public CipherData getCipherData() {
-                return cipherData;
-            }
-
-            /**
-             *
-             * @return the EncryptionProperties
-             */
-            public EncryptionProperties getEncryptionProperties() {
-                return encryptionProperties;
-            }
-
-            /**
-             *
-             * @param properties
-             */
-            public void setEncryptionProperties(EncryptionProperties properties) {
-                encryptionProperties = properties;
-            }
-        }
-
-        private class EncryptionMethodImpl implements EncryptionMethod {
-            private String algorithm = null;
-            private int keySize = Integer.MIN_VALUE;
-            private byte[] oaepParams = null;
-            private List<Element> encryptionMethodInformation = null;
-            private String digestAlgorithm = null;
-            private String mgfAlgorithm = null;
-
-            /**
-             * Constructor.
-             * @param algorithm
-             */
-            public EncryptionMethodImpl(String algorithm) {
-                URI tmpAlgorithm = null;
-                try {
-                    tmpAlgorithm = new URI(algorithm);
-                } catch (URISyntaxException ex) {
-                    throw (IllegalArgumentException)
-                    new IllegalArgumentException().initCause(ex);
-                }
-                this.algorithm = tmpAlgorithm.toString();
-                encryptionMethodInformation = new LinkedList<Element>();
-            }
-
-            /** @inheritDoc */
-            public String getAlgorithm() {
-                return algorithm;
-            }
-
-            /** @inheritDoc */
-            public int getKeySize() {
-                return keySize;
-            }
-
-            /** @inheritDoc */
-            public void setKeySize(int size) {
-                keySize = size;
-            }
-
-            /** @inheritDoc */
-            public byte[] getOAEPparams() {
-                return oaepParams;
-            }
-
-            /** @inheritDoc */
-            public void setOAEPparams(byte[] params) {
-                oaepParams = params;
-            }
-
-            /** @inheritDoc */
-            public void setDigestAlgorithm(String digestAlgorithm) {
-                this.digestAlgorithm = digestAlgorithm;
-            }
-
-            /** @inheritDoc */
-            public String getDigestAlgorithm() {
-                return digestAlgorithm;
-            }
-
-            /** @inheritDoc */
-            public void setMGFAlgorithm(String mgfAlgorithm) {
-                this.mgfAlgorithm = mgfAlgorithm;
-            }
-
-            /** @inheritDoc */
-            public String getMGFAlgorithm() {
-                return mgfAlgorithm;
-            }
-
-            /** @inheritDoc */
-            public Iterator<Element> getEncryptionMethodInformation() {
-                return encryptionMethodInformation.iterator();
-            }
-
-            /** @inheritDoc */
-            public void addEncryptionMethodInformation(Element info) {
-                encryptionMethodInformation.add(info);
-            }
-
-            /** @inheritDoc */
-            public void removeEncryptionMethodInformation(Element info) {
-                encryptionMethodInformation.remove(info);
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD
-                    );
-                result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm);
-                if (keySize > 0) {
-                    result.appendChild(
-                        XMLUtils.createElementInEncryptionSpace(
-                            contextDocument, EncryptionConstants._TAG_KEYSIZE
-                    ).appendChild(contextDocument.createTextNode(String.valueOf(keySize))));
-                }
-                if (null != oaepParams) {
-                    Element oaepElement =
-                        XMLUtils.createElementInEncryptionSpace(
-                            contextDocument, EncryptionConstants._TAG_OAEPPARAMS
-                        );
-                    oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams)));
-                    result.appendChild(oaepElement);
-                }
-                if (digestAlgorithm != null) {
-                    Element digestElement =
-                        XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD);
-                    digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm);
-                    result.appendChild(digestElement);
-                }
-                if (mgfAlgorithm != null) {
-                    Element mgfElement =
-                        XMLUtils.createElementInEncryption11Space(
-                            contextDocument, EncryptionConstants._TAG_MGF
-                        );
-                    mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm);
-                    mgfElement.setAttributeNS(
-                        Constants.NamespaceSpecNS,
-                        "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS),
-                        EncryptionConstants.EncryptionSpec11NS
-                    );
-                    result.appendChild(mgfElement);
-                }
-                Iterator<Element> itr = encryptionMethodInformation.iterator();
-                while (itr.hasNext()) {
-                    result.appendChild(itr.next());
-                }
-
-                return result;
-            }
-        }
-
-        private class EncryptionPropertiesImpl implements EncryptionProperties {
-            private String id = null;
-            private List<EncryptionProperty> encryptionProperties = null;
-
-            /**
-             * Constructor.
-             */
-            public EncryptionPropertiesImpl() {
-                encryptionProperties = new LinkedList<EncryptionProperty>();
-            }
-
-            /** @inheritDoc */
-            public String getId() {
-                return id;
-            }
-
-            /** @inheritDoc */
-            public void setId(String id) {
-                this.id = id;
-            }
-
-            /** @inheritDoc */
-            public Iterator<EncryptionProperty> getEncryptionProperties() {
-                return encryptionProperties.iterator();
-            }
-
-            /** @inheritDoc */
-            public void addEncryptionProperty(EncryptionProperty property) {
-                encryptionProperties.add(property);
-            }
-
-            /** @inheritDoc */
-            public void removeEncryptionProperty(EncryptionProperty property) {
-                encryptionProperties.remove(property);
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES
-                    );
-                if (null != id) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, id);
-                }
-                Iterator<EncryptionProperty> itr = getEncryptionProperties();
-                while (itr.hasNext()) {
-                    result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement());
-                }
-
-                return result;
-            }
-        }
-
-        private class EncryptionPropertyImpl implements EncryptionProperty {
-            private String target = null;
-            private String id = null;
-            private Map<String, String> attributeMap = new HashMap<String, String>();
-            private List<Element> encryptionInformation = null;
-
-            /**
-             * Constructor.
-             */
-            public EncryptionPropertyImpl() {
-                encryptionInformation = new LinkedList<Element>();
-            }
-
-            /** @inheritDoc */
-            public String getTarget() {
-                return target;
-            }
-
-            /** @inheritDoc */
-            public void setTarget(String target) {
-                if (target == null || target.length() == 0) {
-                    this.target = null;
-                } else if (target.startsWith("#")) {
-                    /*
-                     * This is a same document URI reference. Do not parse,
-                     * because it has no scheme.
-                     */
-                    this.target = target;
-                } else {
-                    URI tmpTarget = null;
-                    try {
-                        tmpTarget = new URI(target);
-                    } catch (URISyntaxException ex) {
-                        throw (IllegalArgumentException)
-                        new IllegalArgumentException().initCause(ex);
-                    }
-                    this.target = tmpTarget.toString();
-                }
-            }
-
-            /** @inheritDoc */
-            public String getId() {
-                return id;
-            }
-
-            /** @inheritDoc */
-            public void setId(String id) {
-                this.id = id;
-            }
-
-            /** @inheritDoc */
-            public String getAttribute(String attribute) {
-                return attributeMap.get(attribute);
-            }
-
-            /** @inheritDoc */
-            public void setAttribute(String attribute, String value) {
-                attributeMap.put(attribute, value);
-            }
-
-            /** @inheritDoc */
-            public Iterator<Element> getEncryptionInformation() {
-                return encryptionInformation.iterator();
-            }
-
-            /** @inheritDoc */
-            public void addEncryptionInformation(Element info) {
-                encryptionInformation.add(info);
-            }
-
-            /** @inheritDoc */
-            public void removeEncryptionInformation(Element info) {
-                encryptionInformation.remove(info);
-            }
-
-            Element toElement() {
-                Element result =
-                    XMLUtils.createElementInEncryptionSpace(
-                        contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY
-                    );
-                if (null != target) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target);
-                }
-                if (null != id) {
-                    result.setAttributeNS(null, EncryptionConstants._ATT_ID, id);
-                }
-                // TODO: figure out the anyAttribyte stuff...
-                // TODO: figure out the any stuff...
-
-                return result;
-            }
-        }
-
-        private class TransformsImpl extends com.sun.org.apache.xml.internal.security.transforms.Transforms
-            implements Transforms {
-
-            /**
-             * Construct Transforms
-             */
-            public TransformsImpl() {
-                super(contextDocument);
-            }
-
-            /**
-             *
-             * @param doc
-             */
-            public TransformsImpl(Document doc) {
-                if (doc == null) {
-                    throw new RuntimeException("Document is null");
-                }
-
-                this.doc = doc;
-                this.constructionElement =
-                    createElementForFamilyLocal(
-                        this.doc, this.getBaseNamespace(), this.getBaseLocalName()
-                    );
-            }
-
-            /**
-             *
-             * @param element
-             * @throws XMLSignatureException
-             * @throws InvalidTransformException
-             * @throws XMLSecurityException
-             * @throws TransformationException
-             */
-            public TransformsImpl(Element element)
-                throws XMLSignatureException, InvalidTransformException,
-                    XMLSecurityException, TransformationException {
-                super(element, "");
-            }
-
-            /**
-             *
-             * @return the XML Element form of that Transforms
-             */
-            public Element toElement() {
-                if (doc == null) {
-                    doc = contextDocument;
-                }
-
-                return getElement();
-            }
-
-            /** @inheritDoc */
-            public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() {
-                return this;
-            }
-
-            // Over-ride the namespace
-            /** @inheritDoc */
-            public String getBaseNamespace() {
-                return EncryptionConstants.EncryptionSpecNS;
-            }
-        }
-
-        private class ReferenceListImpl implements ReferenceList {
-            private Class<?> sentry;
-            private List<Reference> references;
-
-            /**
-             * Constructor.
-             * @param type
-             */
-            public ReferenceListImpl(int type) {
-                if (type == ReferenceList.DATA_REFERENCE) {
-                    sentry = DataReference.class;
-                } else if (type == ReferenceList.KEY_REFERENCE) {
-                    sentry = KeyReference.class;
-                } else {
-                    throw new IllegalArgumentException();
-                }
-                references = new LinkedList<Reference>();
-            }
-
-            /** @inheritDoc */
-            public void add(Reference reference) {
-                if (!reference.getClass().equals(sentry)) {
-                    throw new IllegalArgumentException();
-                }
-                references.add(reference);
-            }
-
-            /** @inheritDoc */
-            public void remove(Reference reference) {
-                if (!reference.getClass().equals(sentry)) {
-                    throw new IllegalArgumentException();
-                }
-                references.remove(reference);
-            }
-
-            /** @inheritDoc */
-            public int size() {
-                return references.size();
-            }
-
-            /** @inheritDoc */
-            public boolean isEmpty() {
-                return references.isEmpty();
-            }
-
-            /** @inheritDoc */
-            public Iterator<Reference> getReferences() {
-                return references.iterator();
-            }
-
-            Element toElement() {
-                Element result =
-                    ElementProxy.createElementForFamily(
-                        contextDocument,
-                        EncryptionConstants.EncryptionSpecNS,
-                        EncryptionConstants._TAG_REFERENCELIST
-                    );
-                Iterator<Reference> eachReference = references.iterator();
-                while (eachReference.hasNext()) {
-                    Reference reference = eachReference.next();
-                    result.appendChild(((ReferenceImpl) reference).toElement());
-                }
-                return result;
-            }
-
-            /** @inheritDoc */
-            public Reference newDataReference(String uri) {
-                return new DataReference(uri);
-            }
-
-            /** @inheritDoc */
-            public Reference newKeyReference(String uri) {
-                return new KeyReference(uri);
-            }
-
-            /**
-             * <code>ReferenceImpl</code> is an implementation of
-             * <code>Reference</code>.
-             *
-             * @see Reference
-             */
-            private abstract class ReferenceImpl implements Reference {
-                private String uri;
-                private List<Element> referenceInformation;
-
-                ReferenceImpl(String uri) {
-                    this.uri = uri;
-                    referenceInformation = new LinkedList<Element>();
-                }
-
-                /** @inheritDoc */
-                public abstract String getType();
-
-                /** @inheritDoc */
-                public String getURI() {
-                    return uri;
-                }
-
-                /** @inheritDoc */
-                public Iterator<Element> getElementRetrievalInformation() {
-                    return referenceInformation.iterator();
-                }
-
-                /** @inheritDoc */
-                public void setURI(String uri) {
-                    this.uri = uri;
-                }
-
-                /** @inheritDoc */
-                public void removeElementRetrievalInformation(Element node) {
-                    referenceInformation.remove(node);
-                }
-
-                /** @inheritDoc */
-                public void addElementRetrievalInformation(Element node) {
-                    referenceInformation.add(node);
-                }
-
-                /**
-                 * @return the XML Element form of that Reference
-                 */
-                public Element toElement() {
-                    String tagName = getType();
-                    Element result =
-                        ElementProxy.createElementForFamily(
-                            contextDocument,
-                            EncryptionConstants.EncryptionSpecNS,
-                            tagName
-                        );
-                    result.setAttribute(EncryptionConstants._ATT_URI, uri);
-
-                    // TODO: Need to martial referenceInformation
-                    // Figure out how to make this work..
-                    // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-
-                    return result;
-                }
-            }
-
-            private class DataReference extends ReferenceImpl {
-
-                DataReference(String uri) {
-                    super(uri);
-                }
-
-                /** @inheritDoc */
-                public String getType() {
-                    return EncryptionConstants._TAG_DATAREFERENCE;
-                }
-            }
-
-            private class KeyReference extends ReferenceImpl {
-
-                KeyReference(String uri) {
-                    super(uri);
-                }
-
-                /** @inheritDoc */
-                public String getType() {
-                    return EncryptionConstants._TAG_KEYREFERENCE;
-                }
-            }
-        }
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,192 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import java.io.IOException;
-
-import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
-import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
-import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
-import org.w3c.dom.Attr;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
-
-/**
- * <code>XMLCipherInput</code> is used to wrap input passed into the
- * XMLCipher encryption operations.
- *
- * In decryption mode, it takes a <code>CipherData</code> object and allows
- * callers to dereference the CipherData into the encrypted bytes that it
- * actually represents.  This takes care of all base64 encoding etc.
- *
- * While primarily an internal class, this can be used by applications to
- * quickly and easily retrieve the encrypted bytes from an EncryptedType
- * object
- *
- * @author Berin Lautenbach
- */
-public class XMLCipherInput {
-
-    private static java.util.logging.Logger logger =
-        java.util.logging.Logger.getLogger(XMLCipherInput.class.getName());
-
-    /** The data we are working with */
-    private CipherData cipherData;
-
-    /** MODES */
-    private int mode;
-
-    private boolean secureValidation;
-
-    /**
-     * Constructor for processing encrypted octets
-     *
-     * @param data The <code>CipherData</code> object to read the bytes from
-     * @throws XMLEncryptionException {@link XMLEncryptionException}
-     */
-    public XMLCipherInput(CipherData data) throws XMLEncryptionException {
-        cipherData = data;
-        mode = XMLCipher.DECRYPT_MODE;
-        if (cipherData == null) {
-            throw new XMLEncryptionException("CipherData is null");
-        }
-    }
-
-    /**
-     * Constructor for processing encrypted octets
-     *
-     * @param input The <code>EncryptedType</code> object to read
-     * the bytes from.
-     * @throws XMLEncryptionException {@link XMLEncryptionException}
-     */
-    public XMLCipherInput(EncryptedType input) throws XMLEncryptionException {
-        cipherData = ((input == null) ? null : input.getCipherData());
-        mode = XMLCipher.DECRYPT_MODE;
-        if (cipherData == null) {
-            throw new XMLEncryptionException("CipherData is null");
-        }
-    }
-
-    /**
-     * Set whether secure validation is enabled or not. The default is false.
-     */
-    public void setSecureValidation(boolean secureValidation) {
-        this.secureValidation = secureValidation;
-    }
-
-    /**
-     * Dereferences the input and returns it as a single byte array.
-     *
-     * @throws XMLEncryptionException
-     * @return The decripted bytes.
-     */
-    public byte[] getBytes() throws XMLEncryptionException {
-        if (mode == XMLCipher.DECRYPT_MODE) {
-            return getDecryptBytes();
-        }
-        return null;
-    }
-
-    /**
-     * Internal method to get bytes in decryption mode
-     * @return the decrypted bytes
-     * @throws XMLEncryptionException
-     */
-    private byte[] getDecryptBytes() throws XMLEncryptionException {
-        String base64EncodedEncryptedOctets = null;
-
-        if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
-            // Fun time!
-            if (logger.isLoggable(java.util.logging.Level.FINE)) {
-                logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
-            }
-            CipherReference cr = cipherData.getCipherReference();
-
-            // Need to wrap the uri in an Attribute node so that we can
-            // Pass to the resource resolvers
-
-            Attr uriAttr = cr.getURIAsAttr();
-            XMLSignatureInput input = null;
-
-            try {
-                ResourceResolver resolver =
-                    ResourceResolver.getInstance(uriAttr, null, secureValidation);
-                input = resolver.resolve(uriAttr, null, secureValidation);
-            } catch (ResourceResolverException ex) {
-                throw new XMLEncryptionException("empty", ex);
-            }
-
-            if (input != null) {
-                if (logger.isLoggable(java.util.logging.Level.FINE)) {
-                    logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\"");
-                }
-            } else {
-                if (logger.isLoggable(java.util.logging.Level.FINE)) {
-                    logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\"");
-                }
-            }
-
-            // Lets see if there are any transforms
-            Transforms transforms = cr.getTransforms();
-            if (transforms != null) {
-                if (logger.isLoggable(java.util.logging.Level.FINE)) {
-                    logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference");
-                }
-                try {
-                    com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms =
-                        transforms.getDSTransforms();
-                    dsTransforms.setSecureValidation(secureValidation);
-                    input = dsTransforms.performTransforms(input);
-                } catch (TransformationException ex) {
-                    throw new XMLEncryptionException("empty", ex);
-                }
-            }
-
-            try {
-                return input.getBytes();
-            } catch (IOException ex) {
-                throw new XMLEncryptionException("empty", ex);
-            } catch (CanonicalizationException ex) {
-                throw new XMLEncryptionException("empty", ex);
-            }
-
-            // retrieve the cipher text
-        } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) {
-            base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue();
-        } else {
-            throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
-        }
-
-        if (logger.isLoggable(java.util.logging.Level.FINE)) {
-            logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
-        }
-
-        try {
-            return Base64.decode(base64EncodedEncryptedOctets);
-        } catch (Base64DecodingException bde) {
-            throw new XMLEncryptionException("empty", bde);
-        }
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-/**
- * Constants
- */
-public interface XMLCipherParameters {
-
-    String AES_128 =
-        "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
-
-    String AES_256 =
-        "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
-
-    String AES_192 =
-        "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
-
-    String RSA_1_5 =
-        "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
-
-    String RSA_OAEP =
-        "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
-
-    String DIFFIE_HELLMAN =
-        "http://www.w3.org/2001/04/xmlenc#dh";
-
-    String TRIPLEDES_KEYWRAP =
-        "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
-
-    String AES_128_KEYWRAP =
-        "http://www.w3.org/2001/04/xmlenc#kw-aes128";
-
-    String AES_256_KEYWRAP =
-        "http://www.w3.org/2001/04/xmlenc#kw-aes256";
-
-    String AES_192_KEYWRAP =
-        "http://www.w3.org/2001/04/xmlenc#kw-aes192";
-
-    String SHA1 =
-        "http://www.w3.org/2000/09/xmldsig#sha1";
-
-    String SHA256 =
-        "http://www.w3.org/2001/04/xmlenc#sha256";
-
-    String SHA512 =
-        "http://www.w3.org/2001/04/xmlenc#sha512";
-
-    String RIPEMD_160 =
-        "http://www.w3.org/2001/04/xmlenc#ripemd160";
-
-    String XML_DSIG =
-        "http://www.w3.org/2000/09/xmldsig#";
-
-    String N14C_XML =
-        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
-
-    String N14C_XML_CMMNTS =
-        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
-
-    String EXCL_XML_N14C =
-        "http://www.w3.org/2001/10/xml-exc-c14n#";
-
-    String EXCL_XML_N14C_CMMNTS =
-        "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.encryption;
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
-/**
- *
- */
-public class XMLEncryptionException extends XMLSecurityException {
-    /**
-     *
-     */
-    private static final long serialVersionUID = 1L;
-
-    /**
-     *
-     *
-     */
-    public XMLEncryptionException() {
-        super();
-    }
-
-    /**
-     *
-     * @param msgID
-     */
-    public XMLEncryptionException(String msgID) {
-        super(msgID);
-    }
-
-    /**
-     *
-     * @param msgID
-     * @param exArgs
-     */
-    public XMLEncryptionException(String msgID, Object exArgs[]) {
-        super(msgID, exArgs);
-    }
-
-    /**
-     *
-     * @param msgID
-     * @param originalException
-     */
-    public XMLEncryptionException(String msgID, Exception originalException) {
-        super(msgID, originalException);
-
-    }
-
-    /**
-     *
-     * @param msgID
-     * @param exArgs
-     * @param originalException
-     */
-    public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/encryption/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
-  <title></title>
-</head>
-<body>
-Provides classes for implementing XML Encryption applications. There are two
-main families of classes in this package. The first group of classes is an
-XML Schema to Java mapping of &nbsp;the complex types and elements of the
-XML Encryption Schema as outllined at <a
- href="http://www.w3.org/Encryption/2001/Drafts/xmlenc-core/">XML Encrtypyion
-Specification</a>. The second group of classes are used to perform encryption
-operations, and to manipulate the first group of classes. The most important
-classes in this second group is <code><a
- href="file://./com/sun/org/apache/xml/internal/security/encryption/XMLCipher.html">XMLCipher</a></code>,
-<code><a
- href="file://./com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionFactory.html">XMLEncryptionFactory</a></code>
-and <code>XMLSerializer</code>. <code>XMLCipher</code> was designed to resemble
-<code>javax.crypto.Cipher</code>. The aforementioned classes were desinged
-with ease-of-use and configurability in mind. Becuase of this, the programmer
-may at times be exposed to lower level programming tasks. This library strives
-to be as simple as possible to use, but no simpler.<br>
-<br>
-</body>
-</html>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -58,24 +58,34 @@
     /**
      * Constructor AlgorithmAlreadyRegisteredException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public AlgorithmAlreadyRegisteredException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor AlgorithmAlreadyRegisteredException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
     public AlgorithmAlreadyRegisteredException(
-        String msgID, Object exArgs[], Exception originalException
+        Exception originalException, String msgID, Object exArgs[]
     ) {
-        super(msgID, exArgs, originalException);
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public AlgorithmAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 /**
  * This Exception is thrown if decoding of Base64 data fails.
  *
- * @author Christian Geuer-Pollmann
  */
 public class Base64DecodingException extends XMLSecurityException {
 
@@ -61,22 +60,32 @@
     /**
      * Constructor Base64DecodingException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public Base64DecodingException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public Base64DecodingException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor Base64DecodingException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public Base64DecodingException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public Base64DecodingException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,18 +22,15 @@
  */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
-import java.io.PrintStream;
-import java.io.PrintWriter;
 import java.text.MessageFormat;
 
-import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
 
 /**
  * The mother of all Exceptions in this bundle. It allows exceptions to have
  * their messages translated to the different locales.
  *
- * The <code>xmlsecurity_en.properties</code> file contains this line:
+ * The {@code xmlsecurity_en.properties} file contains this line:
  * <pre>
  * xml.WrongElement = Can't create a {0} from a {1} element
  * </pre>
@@ -47,7 +44,7 @@
  * }
  * </pre>
  *
- * Additionally, if another Exception has been caught, we can supply it, too>
+ * Additionally, if another Exception has been caught, we can supply it, too
  * <pre>
  * try {
  *    ...
@@ -59,7 +56,6 @@
  * </pre>
  *
  *
- * @author Christian Geuer-Pollmann
  */
 public class XMLSecurityException extends Exception {
 
@@ -98,7 +94,7 @@
      * @param msgID
      * @param exArgs
      */
-    public XMLSecurityException(String msgID, Object exArgs[]) {
+    public XMLSecurityException(String msgID, Object[] exArgs) {
 
         super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
 
@@ -112,11 +108,7 @@
      */
     public XMLSecurityException(Exception originalException) {
 
-        super("Missing message ID to locate message string in resource bundle \""
-              + Constants.exceptionMessagesResourceBundleBase
-              + "\". Original Exception was a "
-              + originalException.getClass().getName() + " and message "
-              + originalException.getMessage(), originalException);
+        super(originalException.getMessage(), originalException);
     }
 
     /**
@@ -125,12 +117,17 @@
      * @param msgID
      * @param originalException
      */
-    public XMLSecurityException(String msgID, Exception originalException) {
+    public XMLSecurityException(Exception originalException, String msgID) {
         super(I18n.getExceptionMessage(msgID, originalException), originalException);
 
         this.msgID = msgID;
     }
 
+    @Deprecated
+    public XMLSecurityException(String msgID, Exception originalException) {
+        this(originalException, msgID);
+    }
+
     /**
      * Constructor XMLSecurityException
      *
@@ -138,12 +135,18 @@
      * @param exArgs
      * @param originalException
      */
-    public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) {
+    public XMLSecurityException(Exception originalException, String msgID, Object[] exArgs) {
         super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
 
         this.msgID = msgID;
     }
 
+    @Deprecated
+    public XMLSecurityException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
+    }
+
+
     /**
      * Method getMsgID
      *
@@ -156,7 +159,7 @@
         return msgID;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String toString() {
         String s = this.getClass().getName();
         String message = super.getLocalizedMessage();
@@ -185,24 +188,6 @@
     }
 
     /**
-     * Method printStackTrace
-     *
-     * @param printwriter
-     */
-    public void printStackTrace(PrintWriter printwriter) {
-        super.printStackTrace(printwriter);
-    }
-
-    /**
-     * Method printStackTrace
-     *
-     * @param printstream
-     */
-    public void printStackTrace(PrintStream printstream) {
-        super.printStackTrace(printstream);
-    }
-
-    /**
      * Method getOriginalException
      *
      * @return the original exception
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,8 +22,6 @@
  */
 package com.sun.org.apache.xml.internal.security.exceptions;
 
-import java.io.PrintStream;
-import java.io.PrintWriter;
 import java.text.MessageFormat;
 
 import com.sun.org.apache.xml.internal.security.utils.Constants;
@@ -33,7 +31,7 @@
  * The mother of all runtime Exceptions in this bundle. It allows exceptions to have
  * their messages translated to the different locales.
  *
- * The <code>xmlsecurity_en.properties</code> file contains this line:
+ * The {@code xmlsecurity_en.properties} file contains this line:
  * <pre>
  * xml.WrongElement = Can't create a {0} from a {1} element
  * </pre>
@@ -47,7 +45,7 @@
  * }
  * </pre>
  *
- * Additionally, if another Exception has been caught, we can supply it, too>
+ * Additionally, if another Exception has been caught, we can supply it, too
  * <pre>
  * try {
  *    ...
@@ -59,7 +57,6 @@
  * </pre>
  *
  *
- * @author Christian Geuer-Pollmann
  */
 public class XMLSecurityRuntimeException extends RuntimeException {
 
@@ -134,7 +131,7 @@
      * @param originalException
      */
     public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) {
-        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
+        super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
 
         this.msgID = msgID;
     }
@@ -151,7 +148,7 @@
         return msgID;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String toString() {
         String s = this.getClass().getName();
         String message = super.getLocalizedMessage();
@@ -170,34 +167,6 @@
     }
 
     /**
-     * Method printStackTrace
-     *
-     */
-    public void printStackTrace() {
-        synchronized (System.err) {
-            super.printStackTrace(System.err);
-        }
-    }
-
-    /**
-     * Method printStackTrace
-     *
-     * @param printwriter
-     */
-    public void printStackTrace(PrintWriter printwriter) {
-        super.printStackTrace(printwriter);
-    }
-
-    /**
-     * Method printStackTrace
-     *
-     * @param printstream
-     */
-    public void printStackTrace(PrintStream printstream) {
-        super.printStackTrace(printstream);
-    }
-
-    /**
      * Method getOriginalException
      *
      * @return the original exception
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-general exceptions used by this library.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -61,24 +61,34 @@
     /**
      * Constructor ContentHandlerAlreadyRegisteredException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public ContentHandlerAlreadyRegisteredException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor ContentHandlerAlreadyRegisteredException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
     public ContentHandlerAlreadyRegisteredException(
-        String msgID, Object exArgs[], Exception originalException
+        Exception originalException, String msgID, Object exArgs[]
     ) {
-        super(msgID, exArgs, originalException);
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public ContentHandlerAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,9 +31,6 @@
 
 import javax.crypto.SecretKey;
 
-import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey;
-import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
-import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue;
 import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference;
@@ -52,6 +49,7 @@
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
@@ -59,55 +57,52 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * This class stand for KeyInfo Element that may contain keys, names,
  * certificates and other public key management information,
  * such as in-band key distribution or key agreement data.
- * <BR />
+ * <p></p>
  * KeyInfo Element has two basic functions:
  * One is KeyResolve for getting the public key in signature validation processing.
  * the other one is toElement for getting the element in signature generation processing.
- * <BR />
- * The <CODE>lengthXXX()</CODE> methods provide access to the internal Key
+ * <p></p>
+ * The {@code lengthXXX()} methods provide access to the internal Key
  * objects:
  * <UL>
- * <LI>If the <CODE>KeyInfo</CODE> was constructed from an Element
- * (Signature verification), the <CODE>lengthXXX()</CODE> methods searches
- * for child elements of <CODE>ds:KeyInfo</CODE> for known types. </LI>
- * <LI>If the <CODE>KeyInfo</CODE> was constructed from scratch (during
- * Signature generation), the <CODE>lengthXXX()</CODE> methods return the number
- * of <CODE>XXXs</CODE> objects already passed to the KeyInfo</LI>
+ * <LI>If the {@code KeyInfo} was constructed from an Element
+ * (Signature verification), the {@code lengthXXX()} methods searches
+ * for child elements of {@code ds:KeyInfo} for known types. </LI>
+ * <LI>If the {@code KeyInfo} was constructed from scratch (during
+ * Signature generation), the {@code lengthXXX()} methods return the number
+ * of {@code XXXs} objects already passed to the KeyInfo</LI>
  * </UL>
- * <BR />
- * The <CODE>addXXX()</CODE> methods are used for adding Objects of the
- * appropriate type to the <CODE>KeyInfo</CODE>. This is used during signature
+ * <p></p>
+ * The {@code addXXX()} methods are used for adding Objects of the
+ * appropriate type to the {@code KeyInfo}. This is used during signature
  * generation.
- * <BR />
- * The <CODE>itemXXX(int i)</CODE> methods return the i'th object of the
+ * <p></p>
+ * The {@code itemXXX(int i)} methods return the i'th object of the
  * corresponding type.
- * <BR />
- * The <CODE>containsXXX()</CODE> methods return <I>whether</I> the KeyInfo
+ * <p></p>
+ * The {@code containsXXX()} methods return <I>whether</I> the KeyInfo
  * contains the corresponding type.
  *
  */
 public class KeyInfo extends SignatureElementProxy {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(KeyInfo.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyInfo.class);
 
     // We need at least one StorageResolver otherwise
     // the KeyResolvers would not be called.
     // The default StorageResolver is null.
 
-    private List<X509Data> x509Datas = null;
-    private List<EncryptedKey> encryptedKeys = null;
+    private List<X509Data> x509Datas;
 
     private static final List<StorageResolver> nullList;
     static {
-        List<StorageResolver> list = new ArrayList<StorageResolver>(1);
+        List<StorageResolver> list = new ArrayList<>(1);
         list.add(null);
         nullList = java.util.Collections.unmodifiableList(list);
     }
@@ -118,7 +113,7 @@
     /**
      * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s
      */
-    private List<KeyResolverSpi> internalKeyResolvers = new ArrayList<KeyResolverSpi>();
+    private List<KeyResolverSpi> internalKeyResolvers = new ArrayList<>();
 
     private boolean secureValidation;
 
@@ -128,8 +123,14 @@
      */
     public KeyInfo(Document doc) {
         super(doc);
+        addReturnToSelf();
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        String prefix = ElementProxy.getDefaultPrefix(this.getBaseNamespace());
+        if (prefix != null && prefix.length() > 0) {
+            getElement().setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix,
+                                        this.getBaseNamespace());
+        }
+
     }
 
     /**
@@ -156,24 +157,23 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id ID
+     * @param id ID
      */
     public void setId(String id) {
         if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
@@ -182,7 +182,7 @@
      * @param keynameString
      */
     public void addKeyName(String keynameString) {
-        this.add(new KeyName(this.doc, keynameString));
+        this.add(new KeyName(getDocument(), keynameString));
     }
 
     /**
@@ -191,8 +191,8 @@
      * @param keyname
      */
     public void add(KeyName keyname) {
-        this.constructionElement.appendChild(keyname.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(keyname);
+        addReturnToSelf();
     }
 
     /**
@@ -201,7 +201,7 @@
      * @param pk
      */
     public void addKeyValue(PublicKey pk) {
-        this.add(new KeyValue(this.doc, pk));
+        this.add(new KeyValue(getDocument(), pk));
     }
 
     /**
@@ -210,7 +210,7 @@
      * @param unknownKeyValueElement
      */
     public void addKeyValue(Element unknownKeyValueElement) {
-        this.add(new KeyValue(this.doc, unknownKeyValueElement));
+        this.add(new KeyValue(getDocument(), unknownKeyValueElement));
     }
 
     /**
@@ -219,7 +219,7 @@
      * @param dsakeyvalue
      */
     public void add(DSAKeyValue dsakeyvalue) {
-        this.add(new KeyValue(this.doc, dsakeyvalue));
+        this.add(new KeyValue(getDocument(), dsakeyvalue));
     }
 
     /**
@@ -228,7 +228,7 @@
      * @param rsakeyvalue
      */
     public void add(RSAKeyValue rsakeyvalue) {
-        this.add(new KeyValue(this.doc, rsakeyvalue));
+        this.add(new KeyValue(getDocument(), rsakeyvalue));
     }
 
     /**
@@ -237,7 +237,7 @@
      * @param pk
      */
     public void add(PublicKey pk) {
-        this.add(new KeyValue(this.doc, pk));
+        this.add(new KeyValue(getDocument(), pk));
     }
 
     /**
@@ -246,8 +246,8 @@
      * @param keyvalue
      */
     public void add(KeyValue keyvalue) {
-        this.constructionElement.appendChild(keyvalue.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(keyvalue);
+        addReturnToSelf();
     }
 
     /**
@@ -256,7 +256,7 @@
      * @param mgmtdata
      */
     public void addMgmtData(String mgmtdata) {
-        this.add(new MgmtData(this.doc, mgmtdata));
+        this.add(new MgmtData(getDocument(), mgmtdata));
     }
 
     /**
@@ -265,8 +265,8 @@
      * @param mgmtdata
      */
     public void add(MgmtData mgmtdata) {
-        this.constructionElement.appendChild(mgmtdata.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(mgmtdata);
+        addReturnToSelf();
     }
 
     /**
@@ -275,8 +275,8 @@
      * @param pgpdata
      */
     public void add(PGPData pgpdata) {
-        this.constructionElement.appendChild(pgpdata.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(pgpdata);
+        addReturnToSelf();
     }
 
     /**
@@ -287,7 +287,7 @@
      * @param Type
      */
     public void addRetrievalMethod(String uri, Transforms transforms, String Type) {
-        this.add(new RetrievalMethod(this.doc, uri, transforms, Type));
+        this.add(new RetrievalMethod(getDocument(), uri, transforms, Type));
     }
 
     /**
@@ -296,8 +296,8 @@
      * @param retrievalmethod
      */
     public void add(RetrievalMethod retrievalmethod) {
-        this.constructionElement.appendChild(retrievalmethod.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(retrievalmethod);
+        addReturnToSelf();
     }
 
     /**
@@ -306,8 +306,8 @@
      * @param spkidata
      */
     public void add(SPKIData spkidata) {
-        this.constructionElement.appendChild(spkidata.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(spkidata);
+        addReturnToSelf();
     }
 
     /**
@@ -317,27 +317,11 @@
      */
     public void add(X509Data x509data) {
         if (x509Datas == null) {
-            x509Datas = new ArrayList<X509Data>();
+            x509Datas = new ArrayList<>();
         }
         x509Datas.add(x509data);
-        this.constructionElement.appendChild(x509data.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
-    }
-
-    /**
-     * Method addEncryptedKey
-     *
-     * @param encryptedKey
-     * @throws XMLEncryptionException
-     */
-
-    public void add(EncryptedKey encryptedKey) throws XMLEncryptionException {
-        if (encryptedKeys == null) {
-            encryptedKeys = new ArrayList<EncryptedKey>();
-        }
-        encryptedKeys.add(encryptedKey);
-        XMLCipher cipher = XMLCipher.getInstance();
-        this.constructionElement.appendChild(cipher.martial(encryptedKey));
+        appendSelf(x509data);
+        addReturnToSelf();
     }
 
     /**
@@ -347,7 +331,7 @@
      * @throws XMLSecurityException
      */
     public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException {
-        this.add(new DEREncodedKeyValue(this.doc, pk));
+        this.add(new DEREncodedKeyValue(getDocument(), pk));
     }
 
     /**
@@ -356,8 +340,8 @@
      * @param derEncodedKeyValue
      */
     public void add(DEREncodedKeyValue derEncodedKeyValue) {
-        this.constructionElement.appendChild(derEncodedKeyValue.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(derEncodedKeyValue);
+        addReturnToSelf();
     }
 
     /**
@@ -367,7 +351,7 @@
      * @throws XMLSecurityException
      */
     public void addKeyInfoReference(String URI) throws XMLSecurityException {
-        this.add(new KeyInfoReference(this.doc, URI));
+        this.add(new KeyInfoReference(getDocument(), URI));
     }
 
     /**
@@ -376,8 +360,8 @@
      * @param keyInfoReference
      */
     public void add(KeyInfoReference keyInfoReference) {
-        this.constructionElement.appendChild(keyInfoReference.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(keyInfoReference);
+        addReturnToSelf();
     }
 
     /**
@@ -386,8 +370,8 @@
      * @param element
      */
     public void addUnknownElement(Element element) {
-        this.constructionElement.appendChild(element);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(element);
+        addReturnToSelf();
     }
 
     /**
@@ -481,19 +465,17 @@
      */
     public int lengthUnknownElement() {
         int res = 0;
-        NodeList nl = this.constructionElement.getChildNodes();
-
-        for (int i = 0; i < nl.getLength(); i++) {
-            Node current = nl.item(i);
-
+        Node childNode = getElement().getFirstChild();
+        while (childNode != null) {
             /**
              * $todo$ using this method, we don't see unknown Elements
              *  from Signature NS; revisit
              */
-            if ((current.getNodeType() == Node.ELEMENT_NODE)
-                && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+            if (childNode.getNodeType() == Node.ELEMENT_NODE
+                && childNode.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
                 res++;
             }
+            childNode = childNode.getNextSibling();
         }
 
         return res;
@@ -509,7 +491,7 @@
     public KeyName itemKeyName(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_KEYNAME, i);
+                getFirstChild(), Constants._TAG_KEYNAME, i);
 
         if (e != null) {
             return new KeyName(e, this.baseURI);
@@ -527,7 +509,7 @@
     public KeyValue itemKeyValue(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_KEYVALUE, i);
+                getFirstChild(), Constants._TAG_KEYVALUE, i);
 
         if (e != null) {
             return new KeyValue(e, this.baseURI);
@@ -545,7 +527,7 @@
     public MgmtData itemMgmtData(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_MGMTDATA, i);
+                getFirstChild(), Constants._TAG_MGMTDATA, i);
 
         if (e != null) {
             return new MgmtData(e, this.baseURI);
@@ -563,7 +545,7 @@
     public PGPData itemPGPData(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i);
+                getFirstChild(), Constants._TAG_PGPDATA, i);
 
         if (e != null) {
             return new PGPData(e, this.baseURI);
@@ -581,7 +563,7 @@
     public RetrievalMethod itemRetrievalMethod(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i);
+                getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i);
 
         if (e != null) {
             return new RetrievalMethod(e, this.baseURI);
@@ -599,7 +581,7 @@
     public SPKIData itemSPKIData(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_SPKIDATA, i);
+                getFirstChild(), Constants._TAG_SPKIDATA, i);
 
         if (e != null) {
             return new SPKIData(e, this.baseURI);
@@ -620,7 +602,7 @@
         }
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509DATA, i);
+                getFirstChild(), Constants._TAG_X509DATA, i);
 
         if (e != null) {
             return new X509Data(e, this.baseURI);
@@ -629,29 +611,6 @@
     }
 
     /**
-     * Method itemEncryptedKey
-     *
-     * @param i
-     * @return the asked EncryptedKey element, null if the index is too big
-     * @throws XMLSecurityException
-     */
-    public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException {
-        if (encryptedKeys != null) {
-            return encryptedKeys.get(i);
-        }
-        Element e =
-            XMLUtils.selectXencNode(
-                this.constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY, i);
-
-        if (e != null) {
-            XMLCipher cipher = XMLCipher.getInstance();
-            cipher.init(XMLCipher.UNWRAP_MODE, null);
-            return cipher.loadEncryptedKey(e);
-        }
-        return null;
-    }
-
-    /**
      * Method itemDEREncodedKeyValue
      *
      * @param i
@@ -661,7 +620,7 @@
     public DEREncodedKeyValue itemDEREncodedKeyValue(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDs11Node(
-                this.constructionElement.getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i);
+                getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i);
 
         if (e != null) {
             return new DEREncodedKeyValue(e, this.baseURI);
@@ -679,7 +638,7 @@
     public KeyInfoReference itemKeyInfoReference(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDs11Node(
-                this.constructionElement.getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i);
+                getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i);
 
         if (e != null) {
             return new KeyInfoReference(e, this.baseURI);
@@ -694,24 +653,22 @@
      * @return the element number of the unknown elements
      */
     public Element itemUnknownElement(int i) {
-        NodeList nl = this.constructionElement.getChildNodes();
         int res = 0;
-
-        for (int j = 0; j < nl.getLength(); j++) {
-            Node current = nl.item(j);
-
+        Node childNode = getElement().getFirstChild();
+        while (childNode != null) {
             /**
              * $todo$ using this method, we don't see unknown Elements
              *  from Signature NS; revisit
              */
-            if ((current.getNodeType() == Node.ELEMENT_NODE)
-                && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+            if (childNode.getNodeType() == Node.ELEMENT_NODE
+                && childNode.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
                 res++;
 
                 if (res == i) {
-                    return (Element) current;
+                    return (Element) childNode;
                 }
             }
+            childNode = childNode.getNextSibling();
         }
 
         return null;
@@ -723,7 +680,7 @@
      * @return true if the element has no descendants.
      */
     public boolean isEmpty() {
-        return this.constructionElement.getFirstChild() == null;
+        return getFirstChild() == null;
     }
 
     /**
@@ -826,28 +783,20 @@
         PublicKey pk = this.getPublicKeyFromInternalResolvers();
 
         if (pk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers");
-            }
+            LOG.debug("I could find a key using the per-KeyInfo key resolvers");
 
             return pk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers");
-        }
+        LOG.debug("I couldn't find a key using the per-KeyInfo key resolvers");
 
         pk = this.getPublicKeyFromStaticResolvers();
 
         if (pk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers");
-            }
+            LOG.debug("I could find a key using the system-wide key resolvers");
 
             return pk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers");
-        }
+        LOG.debug("I couldn't find a key using the system-wide key resolvers");
 
         return null;
     }
@@ -863,7 +812,7 @@
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
             keyResolver.setSecureValidation(secureValidation);
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null) {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -892,11 +841,9 @@
      */
     PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-            }
+            LOG.debug("Try {}", keyResolver.getClass().getName());
             keyResolver.setSecureValidation(secureValidation);
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -929,29 +876,21 @@
         X509Certificate cert = this.getX509CertificateFromInternalResolvers();
 
         if (cert != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers");
-            }
+            LOG.debug("I could find a X509Certificate using the per-KeyInfo key resolvers");
 
             return cert;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers");
-        }
+        LOG.debug("I couldn't find a X509Certificate using the per-KeyInfo key resolvers");
 
         // Then use the system-wide Resolvers
         cert = this.getX509CertificateFromStaticResolvers();
 
         if (cert != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers");
-            }
+            LOG.debug("I could find a X509Certificate using the system-wide key resolvers");
 
             return cert;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers");
-        }
+        LOG.debug("I couldn't find a X509Certificate using the system-wide key resolvers");
 
         return null;
     }
@@ -966,12 +905,9 @@
      */
     X509Certificate getX509CertificateFromStaticResolvers()
         throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE,
-                "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length()
-                + " resolvers"
-            );
-        }
+        LOG.debug(
+            "Start getX509CertificateFromStaticResolvers() with {} resolvers", KeyResolver.length()
+        );
         String uri = this.getBaseURI();
         Iterator<KeyResolverSpi> it = KeyResolver.iterator();
         while (it.hasNext()) {
@@ -988,7 +924,7 @@
     private X509Certificate applyCurrentResolver(
         String uri, KeyResolverSpi keyResolver
     ) throws KeyResolverException {
-        Node currentChild = this.constructionElement.getFirstChild();
+        Node currentChild = getFirstChild();
         while (currentChild != null)      {
             if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
                 for (StorageResolver storage : storageResolvers) {
@@ -1015,17 +951,13 @@
      */
     X509Certificate getX509CertificateFromInternalResolvers()
         throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE,
-                "Start getX509CertificateFromInternalResolvers() with "
-                + this.lengthInternalKeyResolver() + " resolvers"
-            );
-        }
+        LOG.debug(
+            "Start getX509CertificateFromInternalResolvers() with {} resolvers",
+            + this.lengthInternalKeyResolver()
+        );
         String uri = this.getBaseURI();
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-            }
+            LOG.debug("Try {}", keyResolver.getClass().getName());
             keyResolver.setSecureValidation(secureValidation);
             X509Certificate cert = applyCurrentResolver(uri, keyResolver);
             if (cert != null) {
@@ -1045,28 +977,20 @@
         SecretKey sk = this.getSecretKeyFromInternalResolvers();
 
         if (sk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers");
-            }
+            LOG.debug("I could find a secret key using the per-KeyInfo key resolvers");
 
             return sk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
-        }
+        LOG.debug("I couldn't find a secret key using the per-KeyInfo key resolvers");
 
         sk = this.getSecretKeyFromStaticResolvers();
 
         if (sk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers");
-            }
+            LOG.debug("I could find a secret key using the system-wide key resolvers");
 
             return sk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers");
-        }
+        LOG.debug("I couldn't find a secret key using the system-wide key resolvers");
 
         return null;
     }
@@ -1083,7 +1007,7 @@
             KeyResolverSpi keyResolver = it.next();
             keyResolver.setSecureValidation(secureValidation);
 
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -1113,11 +1037,9 @@
 
     SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-            }
+            LOG.debug("Try {}", keyResolver.getClass().getName());
             keyResolver.setSecureValidation(secureValidation);
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -1148,25 +1070,17 @@
         PrivateKey pk = this.getPrivateKeyFromInternalResolvers();
 
         if (pk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers");
-            }
+            LOG.debug("I could find a private key using the per-KeyInfo key resolvers");
             return pk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
-        }
+        LOG.debug("I couldn't find a secret key using the per-KeyInfo key resolvers");
 
         pk = this.getPrivateKeyFromStaticResolvers();
         if (pk != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers");
-            }
+            LOG.debug("I could find a private key using the system-wide key resolvers");
             return pk;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers");
-        }
+        LOG.debug("I couldn't find a private key using the system-wide key resolvers");
 
         return null;
     }
@@ -1183,7 +1097,7 @@
             KeyResolverSpi keyResolver = it.next();
             keyResolver.setSecureValidation(secureValidation);
 
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -1212,11 +1126,9 @@
      */
     PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-            }
+            LOG.debug("Try {}", keyResolver.getClass().getName());
             keyResolver.setSecureValidation(secureValidation);
-            Node currentChild = this.constructionElement.getFirstChild();
+            Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null) {
                 if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
@@ -1274,13 +1186,13 @@
     public void addStorageResolver(StorageResolver storageResolver) {
         if (storageResolvers == nullList) {
             // Replace the default null StorageResolver
-            storageResolvers = new ArrayList<StorageResolver>();
+            storageResolvers = new ArrayList<>();
         }
         this.storageResolvers.add(storageResolver);
     }
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_KEYINFO;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,11 +32,10 @@
 import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
 
 /**
- * Utility class for the <CODE>com.sun.org.apache.xml.internal.security.keys</CODE> package.
+ * Utility class for {@code com.sun.org.apache.xml.internal.security.keys} package.
  *
- * @author $Author: coheigea $
  */
-public class KeyUtils {
+public final class KeyUtils {
 
     private KeyUtils() {
         // no instantiation
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,9 +35,8 @@
 import org.w3c.dom.Element;
 
 /**
- * Provides content model support for the <code>dsig11:DEREncodedKeyvalue</code> element.
+ * Provides content model support for the {@code dsig11:DEREncodedKeyvalue} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent {
 
@@ -48,11 +47,11 @@
      * Constructor DEREncodedKeyValue
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public DEREncodedKeyValue(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -72,7 +71,7 @@
      * Constructor DEREncodedKeyValue
      *
      * @param doc
-     * @param base64EncodedKey
+     * @param encodedKey
      */
     public DEREncodedKeyValue(Document doc, byte[] encodedKey) {
         super(doc);
@@ -81,29 +80,24 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id ID
+     * @param id ID
      */
     public void setId(String id) {
-        if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
-        } else {
-            this.constructionElement.removeAttributeNS(null, Constants._ATT_ID);
-        }
+        setLocalIdAttribute(Constants._ATT_ID, id);
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_DERENCODEDKEYVALUE;
     }
@@ -126,9 +120,9 @@
                 if (publicKey != null) {
                     return publicKey;
                 }
-            } catch (NoSuchAlgorithmException e) {
+            } catch (NoSuchAlgorithmException e) { //NOPMD
                 // Do nothing, try the next type
-            } catch (InvalidKeySpecException e) {
+            } catch (InvalidKeySpecException e) { //NOPMD
                 // Do nothing, try the next type
             }
         }
@@ -148,10 +142,10 @@
             return keySpec.getEncoded();
         } catch (NoSuchAlgorithmException e) {
             Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
-            throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+            throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
         } catch (InvalidKeySpecException e) {
             Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
-            throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+            throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
         }
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 /**
  * Empty interface just to identify Elements that can be children of ds:KeyInfo.
  *
- * @author $Author: coheigea $
  */
 public interface KeyInfoContent {
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java	Tue Jun 19 16:33:07 2018 +0100
@@ -30,9 +30,8 @@
 import org.w3c.dom.Element;
 
 /**
- * Provides content model support for the <code>dsig11:KeyInfoReference</code> element.
+ * Provides content model support for the {@code dsig11:KeyInfoReference} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent {
 
@@ -40,7 +39,7 @@
      * Constructor RetrievalMethod
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
     public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException {
@@ -51,12 +50,12 @@
      * Constructor RetrievalMethod
      *
      * @param doc
-     * @param URI
+     * @param uri
      */
-    public KeyInfoReference(Document doc, String URI) {
+    public KeyInfoReference(Document doc, String uri) {
         super(doc);
 
-        this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+        setLocalAttribute(Constants._ATT_URI, uri);
     }
 
     /**
@@ -65,7 +64,7 @@
      * @return the URI attribute
      */
     public Attr getURIAttr() {
-        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+        return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
     }
 
     /**
@@ -78,29 +77,24 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id ID
+     * @param id ID
      */
     public void setId(String id) {
-        if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
-        } else {
-            this.constructionElement.removeAttributeNS(null, Constants._ATT_ID);
-        }
+        setLocalIdAttribute(Constants._ATT_ID, id);
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_KEYINFOREFERENCE;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,7 +29,6 @@
 import org.w3c.dom.Element;
 
 /**
- * @author $Author: coheigea $
  */
 public class KeyName extends SignatureElementProxy implements KeyInfoContent {
 
@@ -37,11 +36,11 @@
      * Constructor KeyName
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public KeyName(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public KeyName(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -65,7 +64,7 @@
         return this.getTextFromTextChild();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_KEYNAME;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,7 +41,6 @@
  * keys values represented as PCDATA or element types from an external
  * namespace.
  *
- * @author $Author: coheigea $
  */
 public class KeyValue extends SignatureElementProxy implements KeyInfoContent {
 
@@ -54,9 +53,9 @@
     public KeyValue(Document doc, DSAKeyValue dsaKeyValue) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
-        this.constructionElement.appendChild(dsaKeyValue.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
+        appendSelf(dsaKeyValue);
+        addReturnToSelf();
     }
 
     /**
@@ -68,9 +67,9 @@
     public KeyValue(Document doc, RSAKeyValue rsaKeyValue) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
-        this.constructionElement.appendChild(rsaKeyValue.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
+        appendSelf(rsaKeyValue);
+        addReturnToSelf();
     }
 
     /**
@@ -82,9 +81,9 @@
     public KeyValue(Document doc, Element unknownKeyValue) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
-        this.constructionElement.appendChild(unknownKeyValue);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
+        appendSelf(unknownKeyValue);
+        addReturnToSelf();
     }
 
     /**
@@ -96,18 +95,22 @@
     public KeyValue(Document doc, PublicKey pk) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
         if (pk instanceof java.security.interfaces.DSAPublicKey) {
-            DSAKeyValue dsa = new DSAKeyValue(this.doc, pk);
+            DSAKeyValue dsa = new DSAKeyValue(getDocument(), pk);
 
-            this.constructionElement.appendChild(dsa.getElement());
-            XMLUtils.addReturnToElement(this.constructionElement);
+            appendSelf(dsa);
+            addReturnToSelf();
         } else if (pk instanceof java.security.interfaces.RSAPublicKey) {
-            RSAKeyValue rsa = new RSAKeyValue(this.doc, pk);
+            RSAKeyValue rsa = new RSAKeyValue(getDocument(), pk);
 
-            this.constructionElement.appendChild(rsa.getElement());
-            XMLUtils.addReturnToElement(this.constructionElement);
+            appendSelf(rsa);
+            addReturnToSelf();
+        } else {
+            String error = "The given PublicKey type " + pk + " is not supported. Only DSAPublicKey and "
+                + "RSAPublicKey types are currently supported";
+            throw new IllegalArgumentException(error);
         }
     }
 
@@ -115,11 +118,11 @@
      * Constructor KeyValue
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public KeyValue(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public KeyValue(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -131,7 +134,7 @@
     public PublicKey getPublicKey() throws XMLSecurityException {
         Element rsa =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
+                getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
 
         if (rsa != null) {
             RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI);
@@ -140,7 +143,7 @@
 
         Element dsa =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
+                getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
 
         if (dsa != null) {
             DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI);
@@ -150,7 +153,7 @@
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_KEYVALUE;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,7 +29,6 @@
 import org.w3c.dom.Element;
 
 /**
- * @author $Author: coheigea $
  */
 public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
 
@@ -37,12 +36,12 @@
      * Constructor MgmtData
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public MgmtData(Element element, String BaseURI)
+    public MgmtData(Element element, String baseURI)
         throws XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
     }
 
     /**
@@ -66,7 +65,7 @@
         return this.getTextFromTextChild();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_MGMTDATA;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,7 +28,6 @@
 import org.w3c.dom.Element;
 
 /**
- * @author $Author: coheigea $
  * $todo$ Implement
  */
 public class PGPData extends SignatureElementProxy implements KeyInfoContent {
@@ -37,14 +36,14 @@
      * Constructor PGPData
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public PGPData(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public PGPData(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_PGPDATA;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,17 +35,17 @@
 public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent {
 
     /** DSA retrieval */
-    public static final String TYPE_DSA     = Constants.SignatureSpecNS + "DSAKeyValue";
+    public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue";
     /** RSA retrieval */
-    public static final String TYPE_RSA     = Constants.SignatureSpecNS + "RSAKeyValue";
+    public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue";
     /** PGP retrieval */
-    public static final String TYPE_PGP     = Constants.SignatureSpecNS + "PGPData";
+    public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData";
     /** SPKI retrieval */
-    public static final String TYPE_SPKI    = Constants.SignatureSpecNS + "SPKIData";
+    public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData";
     /** MGMT retrieval */
-    public static final String TYPE_MGMT    = Constants.SignatureSpecNS + "MgmtData";
+    public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData";
     /** X509 retrieval */
-    public static final String TYPE_X509    = Constants.SignatureSpecNS + "X509Data";
+    public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data";
     /** RAWX509 retrieval */
     public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
 
@@ -53,11 +53,11 @@
      * Constructor RetrievalMethod
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public RetrievalMethod(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -71,15 +71,15 @@
     public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) {
         super(doc);
 
-        this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+        setLocalAttribute(Constants._ATT_URI, URI);
 
         if (Type != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type);
+            setLocalAttribute(Constants._ATT_TYPE, Type);
         }
 
         if (transforms != null) {
-            this.constructionElement.appendChild(transforms.getElement());
-            XMLUtils.addReturnToElement(this.constructionElement);
+            appendSelf(transforms);
+            addReturnToSelf();
         }
     }
 
@@ -89,7 +89,7 @@
      * @return the URI attribute
      */
     public Attr getURIAttr() {
-        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+        return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
     }
 
     /**
@@ -98,12 +98,12 @@
      * @return URI string
      */
     public String getURI() {
-        return this.getURIAttr().getNodeValue();
+        return getLocalAttribute(Constants._ATT_URI);
     }
 
     /** @return the type*/
     public String getType() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+        return getLocalAttribute(Constants._ATT_TYPE);
     }
 
     /**
@@ -116,7 +116,7 @@
         try {
             Element transformsElem =
                 XMLUtils.selectDsNode(
-                    this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0);
+                    getFirstChild(), Constants._TAG_TRANSFORMS, 0);
 
             if (transformsElem != null) {
                 return new Transforms(transformsElem, this.baseURI);
@@ -124,11 +124,11 @@
 
             return null;
         } catch (XMLSignatureException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_RETRIEVALMETHOD;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,7 +28,6 @@
 import org.w3c.dom.Element;
 
 /**
- * @author $Author: coheigea $
  * $todo$ implement
  */
 public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
@@ -37,15 +36,15 @@
      * Constructor SPKIData
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public SPKIData(Element element, String BaseURI)
+    public SPKIData(Element element, String baseURI)
         throws XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_SPKIDATA;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,9 +41,8 @@
 
 public class X509Data extends SignatureElementProxy implements KeyInfoContent {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509Data.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509Data.class);
 
     /**
      * Constructor X509Data
@@ -53,7 +52,7 @@
     public X509Data(Document doc) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
     }
 
     /**
@@ -66,17 +65,15 @@
     public X509Data(Element element, String baseURI) throws XMLSecurityException {
         super(element, baseURI);
 
-        Node sibling = this.constructionElement.getFirstChild();
-        while (sibling != null) {
-            if (sibling.getNodeType() != Node.ELEMENT_NODE) {
-                sibling = sibling.getNextSibling();
-                continue;
-            }
-            return;
+        Node sibling = getFirstChild();
+        while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
+            sibling = sibling.getNextSibling();
         }
-        /* No Elements found */
-        Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
-        throw new XMLSecurityException("xml.WrongContent", exArgs);
+        if (sibling == null || sibling.getNodeType() != Node.ELEMENT_NODE) {
+            /* No Elements found */
+            Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
+            throw new XMLSecurityException("xml.WrongContent", exArgs);
+        }
     }
 
     /**
@@ -86,7 +83,7 @@
      * @param X509SerialNumber
      */
     public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) {
-        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+        this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
     }
 
     /**
@@ -96,7 +93,7 @@
      * @param X509SerialNumber
      */
     public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) {
-        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+        this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
     }
 
     /**
@@ -106,7 +103,7 @@
      * @param X509SerialNumber
      */
     public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) {
-        this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+        this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
     }
 
     /**
@@ -116,8 +113,8 @@
      */
     public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
 
-        this.constructionElement.appendChild(xmlX509IssuerSerial.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509IssuerSerial);
+        addReturnToSelf();
     }
 
     /**
@@ -126,7 +123,7 @@
      * @param skiBytes
      */
     public void addSKI(byte[] skiBytes) {
-        this.add(new XMLX509SKI(this.doc, skiBytes));
+        this.add(new XMLX509SKI(getDocument(), skiBytes));
     }
 
     /**
@@ -137,7 +134,7 @@
      */
     public void addSKI(X509Certificate x509certificate)
         throws XMLSecurityException {
-        this.add(new XMLX509SKI(this.doc, x509certificate));
+        this.add(new XMLX509SKI(getDocument(), x509certificate));
     }
 
     /**
@@ -146,8 +143,8 @@
      * @param xmlX509SKI
      */
     public void add(XMLX509SKI xmlX509SKI) {
-        this.constructionElement.appendChild(xmlX509SKI.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509SKI);
+        addReturnToSelf();
     }
 
     /**
@@ -156,7 +153,7 @@
      * @param subjectName
      */
     public void addSubjectName(String subjectName) {
-        this.add(new XMLX509SubjectName(this.doc, subjectName));
+        this.add(new XMLX509SubjectName(getDocument(), subjectName));
     }
 
     /**
@@ -165,7 +162,7 @@
      * @param x509certificate
      */
     public void addSubjectName(X509Certificate x509certificate) {
-        this.add(new XMLX509SubjectName(this.doc, x509certificate));
+        this.add(new XMLX509SubjectName(getDocument(), x509certificate));
     }
 
     /**
@@ -174,8 +171,8 @@
      * @param xmlX509SubjectName
      */
     public void add(XMLX509SubjectName xmlX509SubjectName) {
-        this.constructionElement.appendChild(xmlX509SubjectName.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509SubjectName);
+        addReturnToSelf();
     }
 
     /**
@@ -186,7 +183,7 @@
      */
     public void addCertificate(X509Certificate x509certificate)
         throws XMLSecurityException {
-        this.add(new XMLX509Certificate(this.doc, x509certificate));
+        this.add(new XMLX509Certificate(getDocument(), x509certificate));
     }
 
     /**
@@ -195,7 +192,7 @@
      * @param x509certificateBytes
      */
     public void addCertificate(byte[] x509certificateBytes) {
-        this.add(new XMLX509Certificate(this.doc, x509certificateBytes));
+        this.add(new XMLX509Certificate(getDocument(), x509certificateBytes));
     }
 
     /**
@@ -204,8 +201,8 @@
      * @param xmlX509Certificate
      */
     public void add(XMLX509Certificate xmlX509Certificate) {
-        this.constructionElement.appendChild(xmlX509Certificate.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509Certificate);
+        addReturnToSelf();
     }
 
     /**
@@ -214,7 +211,7 @@
      * @param crlBytes
      */
     public void addCRL(byte[] crlBytes) {
-        this.add(new XMLX509CRL(this.doc, crlBytes));
+        this.add(new XMLX509CRL(getDocument(), crlBytes));
     }
 
     /**
@@ -223,8 +220,8 @@
      * @param xmlX509CRL
      */
     public void add(XMLX509CRL xmlX509CRL) {
-        this.constructionElement.appendChild(xmlX509CRL.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509CRL);
+        addReturnToSelf();
     }
 
     /**
@@ -236,27 +233,27 @@
      */
     public void addDigest(X509Certificate x509certificate, String algorithmURI)
         throws XMLSecurityException {
-        this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI));
+        this.add(new XMLX509Digest(getDocument(), x509certificate, algorithmURI));
     }
 
     /**
      * Method addDigest
      *
-     * @param x509CertificateDigestByes
+     * @param x509CertificateDigestBytes
      * @param algorithmURI
      */
-    public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) {
-        this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI));
+    public void addDigest(byte[] x509CertificateDigestBytes, String algorithmURI) {
+        this.add(new XMLX509Digest(getDocument(), x509CertificateDigestBytes, algorithmURI));
     }
 
     /**
      * Method add
      *
-     * @param XMLX509Digest
+     * @param xmlX509Digest
      */
     public void add(XMLX509Digest xmlX509Digest) {
-        this.constructionElement.appendChild(xmlX509Digest.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(xmlX509Digest);
+        addReturnToSelf();
     }
 
     /**
@@ -265,8 +262,8 @@
      * @param element
      */
     public void addUnknownElement(Element element) {
-        this.constructionElement.appendChild(element);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(element);
+        addReturnToSelf();
     }
 
     /**
@@ -330,9 +327,9 @@
      */
     public int lengthUnknownElement() {
         int result = 0;
-        Node n = this.constructionElement.getFirstChild();
-        while (n != null){
-            if ((n.getNodeType() == Node.ELEMENT_NODE)
+        Node n = getFirstChild();
+        while (n != null) {
+            if (n.getNodeType() == Node.ELEMENT_NODE
                 && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
                 result++;
             }
@@ -352,7 +349,7 @@
     public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException {
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
+                getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
 
         if (e != null) {
             return new XMLX509IssuerSerial(e, this.baseURI);
@@ -371,7 +368,7 @@
 
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i);
+                getFirstChild(), Constants._TAG_X509SKI, i);
 
         if (e != null) {
             return new XMLX509SKI(e, this.baseURI);
@@ -390,7 +387,7 @@
 
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
+                getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
 
         if (e != null) {
             return new XMLX509SubjectName(e, this.baseURI);
@@ -402,14 +399,14 @@
      * Method itemCertificate
      *
      * @param i
-     * @return the X509Certifacte, null if not present
+     * @return the X509Certificate, null if not present
      * @throws XMLSecurityException
      */
     public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException {
 
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
+                getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
 
         if (e != null) {
             return new XMLX509Certificate(e, this.baseURI);
@@ -428,7 +425,7 @@
 
         Element e =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i);
+                getFirstChild(), Constants._TAG_X509CRL, i);
 
         if (e != null) {
             return new XMLX509CRL(e, this.baseURI);
@@ -447,7 +444,7 @@
 
         Element e =
             XMLUtils.selectDs11Node(
-                this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i);
+                getFirstChild(), Constants._TAG_X509DIGEST, i);
 
         if (e != null) {
             return new XMLX509Digest(e, this.baseURI);
@@ -463,9 +460,7 @@
      * TODO implement
      **/
     public Element itemUnknownElement(int i) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i);
-        }
+        LOG.debug("itemUnknownElement not implemented: {}", i);
         return null;
     }
 
@@ -532,7 +527,7 @@
         return this.lengthUnknownElement() > 0;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509DATA;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,6 +27,7 @@
 import java.security.KeyFactory;
 import java.security.NoSuchAlgorithmException;
 import java.security.PublicKey;
+import java.security.interfaces.DSAParams;
 import java.security.interfaces.DSAPublicKey;
 import java.security.spec.DSAPublicKeySpec;
 import java.security.spec.InvalidKeySpecException;
@@ -35,7 +36,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -64,7 +64,7 @@
     public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
         this.addBigIntegerElement(P, Constants._TAG_P);
         this.addBigIntegerElement(Q, Constants._TAG_Q);
         this.addBigIntegerElement(G, Constants._TAG_G);
@@ -81,12 +81,13 @@
     public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
-        if (key instanceof java.security.interfaces.DSAPublicKey) {
-            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P);
-            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q);
-            this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G);
+        if (key instanceof DSAPublicKey) {
+            DSAParams params = ((DSAPublicKey) key).getParams();
+            this.addBigIntegerElement(params.getP(), Constants._TAG_P);
+            this.addBigIntegerElement(params.getQ(), Constants._TAG_Q);
+            this.addBigIntegerElement(params.getG(), Constants._TAG_G);
             this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
         } else {
             Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
@@ -95,7 +96,7 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public PublicKey getPublicKey() throws XMLSecurityException {
         try {
             DSAPublicKeySpec pkspec =
@@ -118,13 +119,13 @@
 
             return pk;
         } catch (NoSuchAlgorithmException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         } catch (InvalidKeySpecException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_DSAKEYVALUE;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,7 +35,6 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -45,11 +44,11 @@
      * Constructor RSAKeyValue
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public RSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -62,7 +61,7 @@
     public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
         this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
         this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
     }
@@ -77,9 +76,9 @@
     public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
-        if (key instanceof java.security.interfaces.RSAPublicKey ) {
+        if (key instanceof RSAPublicKey ) {
             this.addBigIntegerElement(
                 ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS
             );
@@ -93,7 +92,7 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public PublicKey getPublicKey() throws XMLSecurityException {
         try {
             KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
@@ -111,13 +110,13 @@
 
             return pk;
         } catch (NoSuchAlgorithmException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         } catch (InvalidKeySpecException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_RSAKEYVALUE;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-basic handlers for elements that can occur inside <CODE>ds:KeyValue</CODE>.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-basic handlers for elements that can occur inside <CODE>ds:KeyInfo</CODE>.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,11 +34,11 @@
      * Constructor XMLX509CRL
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509CRL(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public XMLX509CRL(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -63,7 +63,7 @@
         return this.getBytesFromTextChild();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509CRL;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,6 +23,8 @@
 package com.sun.org.apache.xml.internal.security.keys.content.x509;
 
 import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.security.PublicKey;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
@@ -44,11 +46,11 @@
      * Constructor X509Certificate
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509Certificate(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public XMLX509Certificate(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -77,7 +79,7 @@
         try {
             this.addBase64Text(x509certificate.getEncoded());
         } catch (java.security.cert.CertificateEncodingException ex) {
-            throw new XMLSecurityException("empty", ex);
+            throw new XMLSecurityException(ex);
         }
     }
 
@@ -98,22 +100,20 @@
      * @throws XMLSecurityException
      */
     public X509Certificate getX509Certificate() throws XMLSecurityException {
-        try {
-            byte certbytes[] = this.getCertificateBytes();
+        byte certbytes[] = this.getCertificateBytes();
+        try (InputStream is = new ByteArrayInputStream(certbytes)) {
             CertificateFactory certFact =
                 CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
             X509Certificate cert =
-                (X509Certificate) certFact.generateCertificate(
-                    new ByteArrayInputStream(certbytes)
-                );
+                (X509Certificate) certFact.generateCertificate(is);
 
             if (cert != null) {
                 return cert;
             }
 
             return null;
-        } catch (CertificateException ex) {
-            throw new XMLSecurityException("empty", ex);
+        } catch (CertificateException | IOException ex) {
+            throw new XMLSecurityException(ex);
         }
     }
 
@@ -123,7 +123,7 @@
      * @return the publickey
      * @throws XMLSecurityException
      */
-    public PublicKey getPublicKey() throws XMLSecurityException {
+    public PublicKey getPublicKey() throws XMLSecurityException, IOException {
         X509Certificate cert = this.getX509Certificate();
 
         if (cert != null) {
@@ -133,7 +133,7 @@
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public boolean equals(Object obj) {
         if (!(obj instanceof XMLX509Certificate)) {
             return false;
@@ -154,14 +154,12 @@
                 result = 31 * result + bytes[i];
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
         }
         return result;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509CERTIFICATE;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,6 @@
 /**
  * Just used for tagging contents that are allowed inside a ds:X509Data Element.
  *
- * @author $Author: coheigea $
  */
 public interface XMLX509DataContent {
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,9 +34,8 @@
 import org.w3c.dom.Element;
 
 /**
- * Provides content model support for the <code>dsig11:X509Digest</code> element.
+ * Provides content model support for the {@code dsig11:X509Digest} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent {
 
@@ -44,11 +43,11 @@
      * Constructor XMLX509Digest
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public XMLX509Digest(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -61,7 +60,7 @@
     public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) {
         super(doc);
         this.addBase64Text(digestBytes);
-        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+        setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
     }
 
     /**
@@ -75,7 +74,7 @@
     public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException {
         super(doc);
         this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI));
-        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+        setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
     }
 
     /**
@@ -84,7 +83,7 @@
      * @return the Algorithm attribute
      */
     public Attr getAlgorithmAttr() {
-        return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
+        return getElement().getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -118,21 +117,21 @@
     public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException {
         String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI);
         if (jcaDigestAlgorithm == null) {
-            Object exArgs[] = { algorithmURI };
-            throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
+                Object exArgs[] = { algorithmURI };
+                throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
         }
 
         try {
-            MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
-            return md.digest(cert.getEncoded());
-        } catch (Exception e) {
-            Object exArgs[] = { jcaDigestAlgorithm };
-            throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
-        }
+                        MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
+                        return md.digest(cert.getEncoded());
+                } catch (Exception e) {
+                Object exArgs[] = { jcaDigestAlgorithm };
+                        throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
+                }
 
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509DIGEST;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,15 +29,13 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509IssuerSerial.class);
 
     /**
      * Constructor XMLX509IssuerSerial
@@ -59,7 +57,7 @@
      */
     public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) {
         super(doc);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
         addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME);
         addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER);
     }
@@ -108,9 +106,7 @@
     public BigInteger getSerialNumber() {
         String text =
             this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text);
-        }
+        LOG.debug("X509SerialNumber text: {}", text);
 
         return new BigInteger(text);
     }
@@ -135,7 +131,7 @@
         );
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public boolean equals(Object obj) {
         if (!(obj instanceof XMLX509IssuerSerial)) {
             return false;
@@ -154,7 +150,7 @@
         return result;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509ISSUERSERIAL;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,9 +24,9 @@
 
 import java.security.cert.X509Certificate;
 import java.util.Arrays;
+import java.util.Base64;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
@@ -40,20 +40,19 @@
  */
 public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XMLX509SKI.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509SKI.class);
 
     /**
-     * <CODE>SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14)</CODE>:
+     * {@code SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14)}:
      * This extension identifies the public key being certified. It enables
      * distinct keys used by the same subject to be differentiated
      * (e.g., as key updating occurs).
-     * <BR />
+     * <p></p>
      * A key identifier shall be unique with respect to all key identifiers
      * for the subject with which it is used. This extension is always non-critical.
      */
-    public static final String SKI_OID = "2.5.29.14";
+    public static final String SKI_OID = "2.5.29.14"; //NOPMD
 
     /**
      * Constructor X509SKI
@@ -83,11 +82,11 @@
      * Constructor XMLX509SKI
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public XMLX509SKI(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
@@ -113,7 +112,7 @@
         throws XMLSecurityException {
 
         if (cert.getVersion() < 3) {
-            Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
+            Object exArgs[] = { cert.getVersion() };
             throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
         }
 
@@ -138,14 +137,14 @@
 
         System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Base64 of SKI is " + Base64.getMimeEncoder().encodeToString(skidValue));
         }
 
         return skidValue;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public boolean equals(Object obj) {
         if (!(obj instanceof XMLX509SKI)) {
             return false;
@@ -168,15 +167,13 @@
                 result = 31 * result + bytes[i];
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
         }
         return result;
 
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509SKI;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,7 +32,6 @@
 import org.w3c.dom.Element;
 
 /**
- * @author $Author: coheigea $
  */
 public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent {
 
@@ -40,12 +39,12 @@
      * Constructor X509SubjectName
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public XMLX509SubjectName(Element element, String BaseURI)
+    public XMLX509SubjectName(Element element, String baseURI)
         throws XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
     }
 
     /**
@@ -80,7 +79,7 @@
         return RFC2253Parser.normalize(this.getTextFromTextChild());
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public boolean equals(Object obj) {
         if (!(obj instanceof XMLX509SubjectName)) {
             return false;
@@ -99,7 +98,7 @@
         return result;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_X509SUBJECTNAME;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-basic handlers for elements that can occur inside <CODE>ds:X509Data</CODE>.
-</P></BODY></HTML>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,84 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.keys.keyresolver;
+
+// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
+// modifiers changed to package-private. Make sure to integrate any future
+// changes to utils.ClassLoaderUtils to this file.
+final class ClassLoaderUtils {
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a class with a given name. <p></p> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            LOG.debug(e.getMessage(), e);
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            LOG.debug(ex.getMessage(), ex);
+            throw ex;
+        }
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -61,21 +61,31 @@
     /**
      * Constructor InvalidKeyResolverException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public InvalidKeyResolverException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public InvalidKeyResolverException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor InvalidKeyResolverException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public InvalidKeyResolverException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public InvalidKeyResolverException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public InvalidKeyResolverException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -52,9 +52,8 @@
  */
 public class KeyResolver {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(KeyResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyResolver.class);
 
     /** Field resolverVector */
     private static List<KeyResolver> resolverVector = new CopyOnWriteArrayList<KeyResolver>();
@@ -96,16 +95,14 @@
         for (KeyResolver resolver : resolverVector) {
             if (resolver == null) {
                 Object exArgs[] = {
-                                   (((element != null)
-                                       && (element.getNodeType() == Node.ELEMENT_NODE))
-                                       ? element.getTagName() : "null")
+                                   element != null
+                                       && element.getNodeType() == Node.ELEMENT_NODE
+                                       ? element.getTagName() : "null"
                 };
 
                 throw new KeyResolverException("utils.resolver.noClass", exArgs);
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
-            }
+            LOG.debug("check resolvability by class {}", resolver.getClass());
 
             X509Certificate cert = resolver.resolveX509Certificate(element, baseURI, storage);
             if (cert != null) {
@@ -114,8 +111,8 @@
         }
 
         Object exArgs[] = {
-                           (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
-                           ? element.getTagName() : "null")
+                           element != null && element.getNodeType() == Node.ELEMENT_NODE
+                           ? element.getTagName() : "null"
                           };
 
         throw new KeyResolverException("utils.resolver.noClass", exArgs);
@@ -137,16 +134,14 @@
         for (KeyResolver resolver : resolverVector) {
             if (resolver == null) {
                 Object exArgs[] = {
-                                   (((element != null)
-                                       && (element.getNodeType() == Node.ELEMENT_NODE))
-                                       ? element.getTagName() : "null")
+                                   element != null
+                                       && element.getNodeType() == Node.ELEMENT_NODE
+                                       ? element.getTagName() : "null"
                 };
 
                 throw new KeyResolverException("utils.resolver.noClass", exArgs);
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
-            }
+            LOG.debug("check resolvability by class {}", resolver.getClass());
 
             PublicKey cert = resolver.resolvePublicKey(element, baseURI, storage);
             if (cert != null) {
@@ -155,8 +150,8 @@
         }
 
         Object exArgs[] = {
-                           (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
-                           ? element.getTagName() : "null")
+                           element != null && element.getNodeType() == Node.ELEMENT_NODE
+                           ? element.getTagName() : "null"
                           };
 
         throw new KeyResolverException("utils.resolver.noClass", exArgs);
@@ -184,7 +179,7 @@
         JavaUtils.checkRegisterPermission();
         @SuppressWarnings("deprecation")
         KeyResolverSpi keyResolverSpi =
-            (KeyResolverSpi) Class.forName(className).newInstance();
+            (KeyResolverSpi) ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
         keyResolverSpi.setGlobalResolver(globalResolver);
         register(keyResolverSpi, false);
     }
@@ -209,8 +204,10 @@
         Exception ex = null;
         try {
             @SuppressWarnings("deprecation")
-            Object tmp = Class.forName(className).newInstance();
-            keyResolverSpi = (KeyResolverSpi) tmp;
+            KeyResolverSpi tmp = (KeyResolverSpi) ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
+            keyResolverSpi = tmp;
+            keyResolverSpi.setGlobalResolver(globalResolver);
+            register(keyResolverSpi, true);
         } catch (ClassNotFoundException e) {
             ex = e;
         } catch (IllegalAccessException e) {
@@ -223,8 +220,6 @@
             throw (IllegalArgumentException) new
             IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
         }
-        keyResolverSpi.setGlobalResolver(globalResolver);
-        register(keyResolverSpi, true);
     }
 
     /**
@@ -273,11 +268,11 @@
     public static void registerClassNames(List<String> classNames)
         throws ClassNotFoundException, IllegalAccessException, InstantiationException {
         JavaUtils.checkRegisterPermission();
-        List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>(classNames.size());
+        List<KeyResolver> keyResolverList = new ArrayList<>(classNames.size());
         for (String className : classNames) {
             @SuppressWarnings("deprecation")
             KeyResolverSpi keyResolverSpi =
-                (KeyResolverSpi) Class.forName(className).newInstance();
+                (KeyResolverSpi)ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
             keyResolverSpi.setGlobalResolver(false);
             keyResolverList.add(new KeyResolver(keyResolverSpi));
         }
@@ -289,7 +284,7 @@
      */
     public static void registerDefaultResolvers() {
 
-        List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>();
+        List<KeyResolver> keyResolverList = new ArrayList<>();
         keyResolverList.add(new KeyResolver(new RSAKeyValueResolver()));
         keyResolverList.add(new KeyResolver(new DSAKeyValueResolver()));
         keyResolverList.add(new KeyResolver(new X509CertificateResolver()));
@@ -418,7 +413,7 @@
         public void remove() {
             throw new UnsupportedOperationException("Can't remove resolvers using the iterator");
         }
-    };
+    }
 
     public static Iterator<KeyResolverSpi> iterator() {
         return new ResolverIterator(resolverVector);
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,6 +39,10 @@
         super();
     }
 
+    public KeyResolverException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor KeyResolverException
      *
@@ -61,21 +65,31 @@
     /**
      * Constructor KeyResolverException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public KeyResolverException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public KeyResolverException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor KeyResolverException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public KeyResolverException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public KeyResolverException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public KeyResolverException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,15 +22,23 @@
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver;
 
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 import java.util.HashMap;
 
 import javax.crypto.SecretKey;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
 
 /**
  * This class is an abstract class for a child KeyInfo Element.
@@ -45,7 +53,7 @@
 public abstract class KeyResolverSpi {
 
     /** Field properties */
-    protected java.util.Map<String, String> properties = null;
+    protected java.util.Map<String, String> properties;
 
     protected boolean globalResolver = false;
 
@@ -84,7 +92,7 @@
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
         throw new UnsupportedOperationException();
-    };
+    }
 
     /**
      * Method engineLookupAndResolvePublicKey
@@ -107,19 +115,18 @@
     }
 
     private KeyResolverSpi cloneIfNeeded() throws KeyResolverException {
-        KeyResolverSpi tmp = this;
         if (globalResolver) {
             try {
                 @SuppressWarnings("deprecation")
-                KeyResolverSpi krs = getClass().newInstance();
-                tmp = krs;
+                KeyResolverSpi tmp = getClass().newInstance();
+                return tmp;
             } catch (InstantiationException e) {
-                throw new KeyResolverException("", e);
+                throw new KeyResolverException(e, "");
             } catch (IllegalAccessException e) {
-                throw new KeyResolverException("", e);
+                throw new KeyResolverException(e, "");
             }
         }
-        return tmp;
+        return this;
     }
 
     /**
@@ -136,7 +143,7 @@
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException{
         throw new UnsupportedOperationException();
-    };
+    }
 
     /**
      * Method engineLookupResolveX509Certificate
@@ -172,7 +179,7 @@
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException{
         throw new UnsupportedOperationException();
-    };
+    }
 
     /**
      * Method engineLookupAndResolveSecretKey
@@ -223,7 +230,7 @@
      */
     public void engineSetProperty(String key, String value) {
         if (properties == null) {
-            properties = new HashMap<String, String>();
+            properties = new HashMap<>();
         }
         properties.put(key, value);
     }
@@ -260,4 +267,27 @@
         this.globalResolver = globalResolver;
     }
 
+
+    /**
+     * Parses a byte array and returns the parsed Element.
+     *
+     * @param bytes
+     * @return the Document Element after parsing bytes
+     * @throws KeyResolverException if something goes wrong
+     */
+    protected static Element getDocFromBytes(byte[] bytes, boolean secureValidation) throws KeyResolverException {
+        DocumentBuilder db = null;
+        try (InputStream is = new ByteArrayInputStream(bytes)) {
+            db = XMLUtils.createDocumentBuilder(false, secureValidation);
+            Document doc = db.parse(is);
+            return doc.getDocumentElement();
+        } catch (SAXException ex) {
+            throw new KeyResolverException(ex);
+        } catch (IOException ex) {
+            throw new KeyResolverException(ex);
+        } catch (ParserConfigurationException ex) {
+            throw new KeyResolverException(ex);
+        }
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,6 +2,24 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.PrivateKey;
@@ -21,28 +39,24 @@
 
 /**
  * KeyResolverSpi implementation which resolves public keys from a
- * <code>dsig11:DEREncodedKeyValue</code> element.
+ * {@code dsig11:DEREncodedKeyValue} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class DEREncodedKeyValueResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DEREncodedKeyValueResolver.class);
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
         return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE);
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -52,27 +66,25 @@
             DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI);
             return derKeyValue.getPublicKey();
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
         return null;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,21 +35,20 @@
 
 public class DSAKeyValueResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DSAKeyValueResolver.class);
 
 
     /**
      * Method engineResolvePublicKey
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return null if no {@link PublicKey} could be obtained
      */
     public PublicKey engineLookupAndResolvePublicKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         if (element == null) {
             return null;
@@ -71,14 +70,12 @@
         }
 
         try {
-            DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI);
+            DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, baseURI);
             PublicKey pk = dsaKeyValue.getPublicKey();
 
             return pk;
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             //do nothing
         }
 
@@ -86,16 +83,16 @@
     }
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public X509Certificate engineLookupResolveX509Certificate(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         return null;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,150 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-import java.security.Key;
-import java.security.PublicKey;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.crypto.SecretKey;
-
-import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey;
-import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
-import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
-import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
-import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
-import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import org.w3c.dom.Element;
-
-/**
- * The <code>EncryptedKeyResolver</code> is not a generic resolver.  It can
- * only be for specific instantiations, as the key being unwrapped will
- * always be of a particular type and will always have been wrapped by
- * another key which needs to be recursively resolved.
- *
- * The <code>EncryptedKeyResolver</code> can therefore only be instantiated
- * with an algorithm.  It can also be instantiated with a key (the KEK) or
- * will search the static KeyResolvers to find the appropriate key.
- *
- * @author Berin Lautenbach
- */
-public class EncryptedKeyResolver extends KeyResolverSpi {
-
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName());
-
-    private Key kek;
-    private String algorithm;
-    private List<KeyResolverSpi> internalKeyResolvers;
-
-    /**
-     * Constructor for use when a KEK needs to be derived from a KeyInfo
-     * list
-     * @param algorithm
-     */
-    public EncryptedKeyResolver(String algorithm) {
-        kek = null;
-        this.algorithm = algorithm;
-    }
-
-    /**
-     * Constructor used for when a KEK has been set
-     * @param algorithm
-     * @param kek
-     */
-    public EncryptedKeyResolver(String algorithm, Key kek) {
-        this.algorithm = algorithm;
-        this.kek = kek;
-    }
-
-    /**
-     * This method is used to add a custom {@link KeyResolverSpi} to help
-     * resolve the KEK.
-     *
-     * @param realKeyResolver
-     */
-    public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) {
-        if (internalKeyResolvers == null) {
-            internalKeyResolvers = new ArrayList<KeyResolverSpi>();
-        }
-        internalKeyResolvers.add(realKeyResolver);
-    }
-
-    /** @inheritDoc */
-    public PublicKey engineLookupAndResolvePublicKey(
-        Element element, String BaseURI, StorageResolver storage
-    ) {
-        return null;
-    }
-
-    /** @inheritDoc */
-    public X509Certificate engineLookupResolveX509Certificate(
-        Element element, String BaseURI, StorageResolver storage
-    ) {
-        return null;
-    }
-
-    /** @inheritDoc */
-    public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-        Element element, String BaseURI, StorageResolver storage
-    ) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName());
-        }
-
-        if (element == null) {
-            return null;
-        }
-
-        SecretKey key = null;
-        boolean isEncryptedKey =
-            XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY);
-        if (isEncryptedKey) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key");
-            }
-            try {
-                XMLCipher cipher = XMLCipher.getInstance();
-                cipher.init(XMLCipher.UNWRAP_MODE, kek);
-                if (internalKeyResolvers != null) {
-                    int size = internalKeyResolvers.size();
-                    for (int i = 0; i < size; i++) {
-                        cipher.registerInternalKeyResolver(internalKeyResolvers.get(i));
-                    }
-                }
-                EncryptedKey ek = cipher.loadEncryptedKey(element);
-                key = (SecretKey) cipher.decryptKey(ek, algorithm);
-            } catch (XMLEncryptionException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-            }
-        }
-
-        return key;
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,19 +2,33 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 
 import javax.crypto.SecretKey;
-import javax.xml.XMLConstants;
 import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -29,34 +43,29 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.xml.sax.SAXException;
 
 /**
  * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a
- * <code>dsig11:KeyInfoReference</code> element.
+ * {@code dsig11:KeyInfoReference} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class KeyInfoReferenceResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyInfoReferenceResolver.class);
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
         return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE);
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -68,21 +77,17 @@
                 return referent.getPublicKey();
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -94,21 +99,17 @@
                 return referent.getX509Certificate();
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -120,21 +121,17 @@
                 return referent.getSecretKey();
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve " + element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -146,9 +143,7 @@
                 return referent.getPrivateKey();
             }
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
@@ -173,14 +168,12 @@
         try {
             referentElement = obtainReferenceElement(resource);
         } catch (Exception e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
             return null;
         }
 
         if (referentElement == null) {
-            log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue());
+            LOG.debug("De-reference of KeyInfoReference URI returned null: {}", uriAttr.getValue());
             return null;
         }
 
@@ -224,21 +217,20 @@
      * @param uri
      * @param baseURI
      * @param secureValidation
-     * @return
+     * @return the XML signature input represented by the specified URI.
      * @throws XMLSecurityException
      */
     private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation)
         throws XMLSecurityException {
         ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
-        XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
-        return resource;
+        return resRes.resolve(uri, baseURI, secureValidation);
     }
 
     /**
      * Resolve the Element effectively represented by the XML signature input source.
      *
      * @param resource
-     * @return
+     * @return the Element effectively represented by the XML signature input source.
      * @throws CanonicalizationException
      * @throws ParserConfigurationException
      * @throws IOException
@@ -253,38 +245,13 @@
         if (resource.isElement()){
             e = (Element) resource.getSubNode();
         } else if (resource.isNodeSet()) {
-            log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet");
+            LOG.debug("De-reference of KeyInfoReference returned an unsupported NodeSet");
             return null;
         } else {
             // Retrieved resource is a byte stream
             byte inputBytes[] = resource.getBytes();
-            e = getDocFromBytes(inputBytes);
+            e = getDocFromBytes(inputBytes, this.secureValidation);
         }
         return e;
     }
-
-    /**
-     * Parses a byte array and returns the parsed Element.
-     *
-     * @param bytes
-     * @return the Document Element after parsing bytes
-     * @throws KeyResolverException if something goes wrong
-     */
-    private Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
-        try {
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setNamespaceAware(true);
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            Document doc = db.parse(new ByteArrayInputStream(bytes));
-            return doc.getDocumentElement();
-        } catch (SAXException ex) {
-            throw new KeyResolverException("empty", ex);
-        } catch (IOException ex) {
-            throw new KeyResolverException("empty", ex);
-        } catch (ParserConfigurationException ex) {
-            throw new KeyResolverException("empty", ex);
-        }
-    }
-
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,6 +2,24 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.Key;
@@ -34,9 +52,9 @@
  * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore.
  */
 public class PrivateKeyResolver extends KeyResolverSpi {
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName());
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(PrivateKeyResolver.class);
 
     private KeyStore keyStore;
     private char[] password;
@@ -53,11 +71,11 @@
      * This method returns whether the KeyResolverSpi is able to perform the requested action.
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return whether the KeyResolverSpi is able to perform the requested action.
      */
-    public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {
+    public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
         if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)
             || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
             return true;
@@ -70,27 +88,27 @@
      * Method engineLookupAndResolvePublicKey
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return null if no {@link PublicKey} could be obtained
      * @throws KeyResolverException
      */
     public PublicKey engineLookupAndResolvePublicKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
         return null;
     }
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @throws KeyResolverException
      */
     public X509Certificate engineLookupResolveX509Certificate(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
         return null;
     }
@@ -99,21 +117,21 @@
      * Method engineResolveSecretKey
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
      *
      * @throws KeyResolverException
      */
     public SecretKey engineResolveSecretKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
         return null;
     }
 
     /**
      * Method engineResolvePrivateKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -123,9 +141,7 @@
     public PrivateKey engineLookupAndResolvePrivateKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
             PrivateKey privKey = resolveX509Data(element, baseURI);
@@ -133,7 +149,7 @@
                 return privKey;
             }
         } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?");
+            LOG.debug("Can I resolve KeyName?");
             String keyName = element.getFirstChild().getNodeValue();
 
             try {
@@ -142,16 +158,16 @@
                     return (PrivateKey) key;
                 }
             } catch (Exception e) {
-                log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                LOG.debug("Cannot recover the key", e);
             }
         }
 
-        log.log(java.util.logging.Level.FINE, "I can't");
+        LOG.debug("I can't");
         return null;
     }
 
     private PrivateKey resolveX509Data(Element element, String baseURI) {
-        log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?");
+        LOG.debug("Can I resolve X509Data?");
 
         try {
             X509Data x509Data = new X509Data(element, baseURI);
@@ -192,9 +208,9 @@
                 }
             }
         } catch (XMLSecurityException e) {
-            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+            LOG.debug("XMLSecurityException", e);
         } catch (KeyStoreException e) {
-            log.log(java.util.logging.Level.FINE, "KeyStoreException", e);
+            LOG.debug("KeyStoreException", e);
         }
 
         return null;
@@ -204,7 +220,7 @@
      * Search for a private key entry in the KeyStore with the same Subject Key Identifier
      */
     private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
-        log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?");
+        LOG.debug("Can I resolve X509SKI?");
 
         Enumeration<String> aliases = keyStore.aliases();
         while (aliases.hasMoreElements()) {
@@ -216,7 +232,7 @@
                     XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);
 
                     if (certSKI.equals(x509SKI)) {
-                        log.log(java.util.logging.Level.FINE, "match !!! ");
+                        LOG.debug("match !!! ");
 
                         try {
                             Key key = keyStore.getKey(alias, password);
@@ -224,7 +240,7 @@
                                 return (PrivateKey) key;
                             }
                         } catch (Exception e) {
-                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            LOG.debug("Cannot recover the key", e);
                             // Keep searching
                         }
                     }
@@ -239,7 +255,7 @@
      * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair.
      */
     private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException {
-        log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?");
+        LOG.debug("Can I resolve X509IssuerSerial?");
 
         Enumeration<String> aliases = keyStore.aliases();
         while (aliases.hasMoreElements()) {
@@ -252,7 +268,7 @@
                         new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert);
 
                     if (certSerial.equals(x509Serial)) {
-                        log.log(java.util.logging.Level.FINE, "match !!! ");
+                        LOG.debug("match !!! ");
 
                         try {
                             Key key = keyStore.getKey(alias, password);
@@ -260,7 +276,7 @@
                                 return (PrivateKey) key;
                             }
                         } catch (Exception e) {
-                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            LOG.debug("Cannot recover the key", e);
                             // Keep searching
                         }
                     }
@@ -275,7 +291,7 @@
      * Search for a private key entry in the KeyStore with the same Subject Name.
      */
     private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException {
-        log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?");
+        LOG.debug("Can I resolve X509SubjectName?");
 
         Enumeration<String> aliases = keyStore.aliases();
         while (aliases.hasMoreElements()) {
@@ -288,7 +304,7 @@
                         new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);
 
                     if (certSN.equals(x509SubjectName)) {
-                        log.log(java.util.logging.Level.FINE, "match !!! ");
+                        LOG.debug("match !!! ");
 
                         try {
                             Key key = keyStore.getKey(alias, password);
@@ -296,7 +312,7 @@
                                 return (PrivateKey) key;
                             }
                         } catch (Exception e) {
-                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            LOG.debug("Cannot recover the key", e);
                             // Keep searching
                         }
                     }
@@ -313,7 +329,7 @@
     private PrivateKey resolveX509Certificate(
         XMLX509Certificate x509Cert
     ) throws XMLSecurityException, KeyStoreException {
-        log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?");
+        LOG.debug("Can I resolve X509Certificate?");
         byte[] x509CertBytes = x509Cert.getCertificateBytes();
 
         Enumeration<String> aliases = keyStore.aliases();
@@ -328,10 +344,11 @@
                     try {
                         certBytes = cert.getEncoded();
                     } catch (CertificateEncodingException e1) {
+                        LOG.debug("Cannot recover the key", e1);
                     }
 
                     if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
-                        log.log(java.util.logging.Level.FINE, "match !!! ");
+                        LOG.debug("match !!! ");
 
                         try {
                             Key key = keyStore.getKey(alias, password);
@@ -340,7 +357,7 @@
                             }
                         }
                         catch (Exception e) {
-                            log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                            LOG.debug("Cannot recover the key", e);
                             // Keep searching
                         }
                     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,18 +36,15 @@
 
 public class RSAKeyValueResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(RSAKeyValueResolver.class);
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public PublicKey engineLookupAndResolvePublicKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
         if (element == null) {
             return null;
         }
@@ -68,28 +65,26 @@
         }
 
         try {
-            RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI);
+            RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, baseURI);
 
             return rsaKeyValue.getPublicKey();
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-            }
+            LOG.debug("XMLSecurityException", ex);
         }
 
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public X509Certificate engineLookupResolveX509Certificate(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         return null;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,6 +24,7 @@
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.security.PublicKey;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
@@ -34,9 +35,6 @@
 import java.util.ListIterator;
 import java.util.Set;
 
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -53,7 +51,6 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
@@ -67,17 +64,15 @@
  * RetrievalMethodResolver cannot handle itself, resolving of the extracted
  * element is delegated back to the KeyResolver mechanism.
  *
- * @author $Author: raul $ modified by Dave Garcia
  */
 public class RetrievalMethodResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(RetrievalMethodResolver.class);
 
     /**
      * Method engineResolvePublicKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -102,58 +97,46 @@
                 }
                 return null;
              }
-             Element e = obtainReferenceElement(resource);
+             Element e = obtainReferenceElement(resource, secureValidation);
 
              // Check to make sure that the reference is not to another RetrievalMethod
              // which points to this element
              if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
                  if (secureValidation) {
-                     String error = "Error: It is forbidden to have one RetrievalMethod "
-                         + "point to another with secure validation";
-                     if (log.isLoggable(java.util.logging.Level.FINE)) {
-                         log.log(java.util.logging.Level.FINE, error);
+                     if (LOG.isDebugEnabled()) {
+                         String error = "Error: It is forbidden to have one RetrievalMethod "
+                             + "point to another with secure validation";
+                         LOG.debug(error);
                      }
                      return null;
                  }
                  RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
                  XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
-                 Element e2 = obtainReferenceElement(resource2);
+                 Element e2 = obtainReferenceElement(resource2, secureValidation);
                  if (e2 == element) {
-                     if (log.isLoggable(java.util.logging.Level.FINE)) {
-                         log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other");
-                     }
+                     LOG.debug("Error: Can't have RetrievalMethods pointing to each other");
                      return null;
                  }
              }
 
              return resolveKey(e, baseURI, storage);
          } catch (XMLSecurityException ex) {
-             if (log.isLoggable(java.util.logging.Level.FINE)) {
-                 log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-             }
+             LOG.debug("XMLSecurityException", ex);
          } catch (CertificateException ex) {
-             if (log.isLoggable(java.util.logging.Level.FINE)) {
-                 log.log(java.util.logging.Level.FINE, "CertificateException", ex);
-             }
+             LOG.debug("CertificateException", ex);
          } catch (IOException ex) {
-             if (log.isLoggable(java.util.logging.Level.FINE)) {
-                 log.log(java.util.logging.Level.FINE, "IOException", ex);
-             }
+             LOG.debug("IOException", ex);
          } catch (ParserConfigurationException e) {
-             if (log.isLoggable(java.util.logging.Level.FINE)) {
-                 log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
-             }
+             LOG.debug("ParserConfigurationException", e);
          } catch (SAXException e) {
-             if (log.isLoggable(java.util.logging.Level.FINE)) {
-                 log.log(java.util.logging.Level.FINE, "SAXException", e);
-             }
+             LOG.debug("SAXException", e);
          }
          return null;
     }
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -172,51 +155,39 @@
                 return getRawCertificate(resource);
             }
 
-            Element e = obtainReferenceElement(resource);
+            Element e = obtainReferenceElement(resource, secureValidation);
 
             // Check to make sure that the reference is not to another RetrievalMethod
             // which points to this element
             if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
                 if (secureValidation) {
-                    String error = "Error: It is forbidden to have one RetrievalMethod "
-                        + "point to another with secure validation";
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, error);
+                    if (LOG.isDebugEnabled()) {
+                        String error = "Error: It is forbidden to have one RetrievalMethod "
+                            + "point to another with secure validation";
+                        LOG.debug(error);
                     }
                     return null;
                 }
                 RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
                 XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
-                Element e2 = obtainReferenceElement(resource2);
+                Element e2 = obtainReferenceElement(resource2, secureValidation);
                 if (e2 == element) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other");
-                    }
+                    LOG.debug("Error: Can't have RetrievalMethods pointing to each other");
                     return null;
                 }
             }
 
             return resolveCertificate(e, baseURI, storage);
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-            }
+            LOG.debug("XMLSecurityException", ex);
         } catch (CertificateException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "CertificateException", ex);
-            }
+            LOG.debug("CertificateException", ex);
         } catch (IOException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "IOException", ex);
-            }
+            LOG.debug("IOException", ex);
         } catch (ParserConfigurationException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
-            }
+            LOG.debug("ParserConfigurationException", e);
         } catch (SAXException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "SAXException", e);
-            }
+            LOG.debug("SAXException", e);
         }
         return null;
     }
@@ -226,14 +197,14 @@
      * @param e
      * @param baseURI
      * @param storage
-     * @return
+     * @return a x509Certificate from the given information
      * @throws KeyResolverException
      */
     private static X509Certificate resolveCertificate(
         Element e, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Now we have a {" + e.getNamespaceURI() + "}"
                 + e.getLocalName() + " Element");
         }
         // An element has been provided
@@ -248,14 +219,14 @@
      * @param e
      * @param baseURI
      * @param storage
-     * @return
+     * @return a PublicKey from the given information
      * @throws KeyResolverException
      */
     private static PublicKey resolveKey(
         Element e, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Now we have a {" + e.getNamespaceURI() + "}"
                 + e.getLocalName() + " Element");
         }
         // An element has been provided
@@ -265,7 +236,7 @@
         return null;
     }
 
-    private static Element obtainReferenceElement(XMLSignatureInput resource)
+    private static Element obtainReferenceElement(XMLSignatureInput resource, boolean secureValidation)
         throws CanonicalizationException, ParserConfigurationException,
         IOException, SAXException, KeyResolverException {
         Element e;
@@ -277,11 +248,9 @@
         } else {
             // Retrieved resource is an inputStream
             byte inputBytes[] = resource.getBytes();
-            e = getDocFromBytes(inputBytes);
+            e = getDocFromBytes(inputBytes, secureValidation);
             // otherwise, we parse the resource, create an Element and delegate
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes");
-            }
+            LOG.debug("we have to parse {} bytes", inputBytes.length);
         }
         return e;
     }
@@ -292,14 +261,14 @@
         // if the resource stores a raw certificate, we have to handle it
         CertificateFactory certFact =
             CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
-        X509Certificate cert = (X509Certificate)
-            certFact.generateCertificate(new ByteArrayInputStream(inputBytes));
-        return cert;
+        try (InputStream is = new ByteArrayInputStream(inputBytes)) {
+            return (X509Certificate) certFact.generateCertificate(is);
+        }
     }
 
     /**
      * Resolves the input from the given retrieval method
-     * @return
+     * @return the input from the given retrieval method
      * @throws XMLSecurityException
      */
     private static XMLSignatureInput resolveInput(
@@ -311,41 +280,15 @@
         ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
         XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
         if (transforms != null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "We have Transforms");
-            }
+            LOG.debug("We have Transforms");
             resource = transforms.performTransforms(resource);
         }
         return resource;
     }
 
     /**
-     * Parses a byte array and returns the parsed Element.
-     *
-     * @param bytes
-     * @return the Document Element after parsing bytes
-     * @throws KeyResolverException if something goes wrong
-     */
-    private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
-        try {
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setNamespaceAware(true);
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            Document doc = db.parse(new ByteArrayInputStream(bytes));
-            return doc.getDocumentElement();
-        } catch (SAXException ex) {
-            throw new KeyResolverException("empty", ex);
-        } catch (IOException ex) {
-            throw new KeyResolverException("empty", ex);
-        } catch (ParserConfigurationException ex) {
-            throw new KeyResolverException("empty", ex);
-        }
-    }
-
-    /**
      * Method engineResolveSecretKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -366,7 +309,7 @@
                 break;
             }
         }
-        List<Node> parents = new ArrayList<Node>();
+        List<Node> parents = new ArrayList<>();
 
         // Obtain all the parents of the elemnt
         while (e != null) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,6 +2,24 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.Key;
@@ -23,9 +41,8 @@
  */
 public class SecretKeyResolver extends KeyResolverSpi
 {
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SecretKeyResolver.class);
 
     private KeyStore keyStore;
     private char[] password;
@@ -67,7 +84,7 @@
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -92,9 +109,7 @@
     public SecretKey engineResolveSecretKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
             String keyName = element.getFirstChild().getNodeValue();
@@ -104,17 +119,17 @@
                     return (SecretKey) key;
                 }
             } catch (Exception e) {
-                log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+                LOG.debug("Cannot recover the key", e);
             }
         }
 
-        log.log(java.util.logging.Level.FINE, "I can't");
+        LOG.debug("I can't");
         return null;
     }
 
     /**
      * Method engineResolvePrivateKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,6 +2,24 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.PrivateKey;
@@ -18,11 +36,9 @@
 /**
  * Resolves a single Key based on the KeyName.
  */
-public class SingleKeyResolver extends KeyResolverSpi
-{
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName());
+public class SingleKeyResolver extends KeyResolverSpi {
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SingleKeyResolver.class);
 
     private String keyName;
     private PublicKey publicKey;
@@ -63,7 +79,7 @@
      * This method returns whether the KeyResolverSpi is able to perform the requested action.
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return whether the KeyResolverSpi is able to perform the requested action.
      */
@@ -83,9 +99,7 @@
     public PublicKey engineLookupAndResolvePublicKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         if (publicKey != null
             && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
@@ -95,13 +109,13 @@
             }
         }
 
-        log.log(java.util.logging.Level.FINE, "I can't");
+        LOG.debug("I can't");
         return null;
     }
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -126,9 +140,7 @@
     public SecretKey engineResolveSecretKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         if (secretKey != null
             && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
@@ -138,13 +150,13 @@
             }
         }
 
-        log.log(java.util.logging.Level.FINE, "I can't");
+        LOG.debug("I can't");
         return null;
     }
 
     /**
      * Method engineResolvePrivateKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -154,9 +166,7 @@
     public PrivateKey engineLookupAndResolvePrivateKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         if (privateKey != null
             && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
@@ -166,7 +176,7 @@
             }
         }
 
-        log.log(java.util.logging.Level.FINE, "I can't");
+        LOG.debug("I can't");
         return null;
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,31 +36,29 @@
 
 /**
  * Resolves Certificates which are directly contained inside a
- * <CODE>ds:X509Certificate</CODE> Element.
+ * {@code ds:X509Certificate} Element.
  *
- * @author $Author: coheigea $
  */
 public class X509CertificateResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509CertificateResolver.class);
 
     /**
      * Method engineResolvePublicKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      *
      * @throws KeyResolverException
      */
     public PublicKey engineLookupAndResolvePublicKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
 
         X509Certificate cert =
-            this.engineLookupResolveX509Certificate(element, BaseURI, storage);
+            this.engineLookupResolveX509Certificate(element, baseURI, storage);
 
         if (cert != null) {
             return cert.getPublicKey();
@@ -71,32 +69,32 @@
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      *
      * @throws KeyResolverException
      */
     public X509Certificate engineLookupResolveX509Certificate(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
 
         try {
             Element[] els =
                 XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
-            if ((els == null) || (els.length == 0)) {
+            if (els == null || els.length == 0) {
                 Element el =
                     XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0);
                 if (el != null) {
-                    return engineLookupResolveX509Certificate(el, BaseURI, storage);
+                    return engineLookupResolveX509Certificate(el, baseURI, storage);
                 }
                 return null;
             }
 
             // populate Object array
             for (int i = 0; i < els.length; i++) {
-                XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI);
+                XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], baseURI);
                 X509Certificate cert = xmlCert.getX509Certificate();
                 if (cert != null) {
                     return cert;
@@ -104,22 +102,20 @@
             }
             return null;
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-            }
-            throw new KeyResolverException("generic.EmptyMessage", ex);
+            LOG.debug("Security Exception", ex);
+            throw new KeyResolverException(ex);
         }
     }
 
     /**
      * Method engineResolveSecretKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      */
     public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
-        Element element, String BaseURI, StorageResolver storage
+        Element element, String baseURI, StorageResolver storage
     ) {
         return null;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,6 +2,24 @@
  * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
 
 import java.security.PublicKey;
@@ -24,17 +42,15 @@
 
 /**
  * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a
- * <code>dsig11:X509Digest</code> element.
+ * {@code dsig11:X509Digest} element.
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public class X509DigestResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509DigestResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509DigestResolver.class);
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
         if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
             try {
@@ -48,7 +64,7 @@
         }
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
@@ -61,13 +77,11 @@
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
-        }
+        LOG.debug("Can I resolve {}", element.getTagName());
 
         if (!engineCanResolve(element, baseURI, storage)) {
             return null;
@@ -76,15 +90,13 @@
         try {
             return resolveCertificate(element, baseURI, storage);
         } catch (XMLSecurityException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
-            }
+            LOG.debug("XMLSecurityException", e);
         }
 
         return null;
     }
 
-    /** {@inheritDoc}. */
+    /** {{@inheritDoc}}. */
     public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
         throws KeyResolverException {
         return null;
@@ -96,7 +108,7 @@
      * @param element
      * @param baseURI
      * @param storage
-     * @return
+     * @return the certificate represented by the digest.
      * @throws XMLSecurityException
      */
     private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage)
@@ -128,9 +140,7 @@
                     byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm());
 
                     if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName());
-                        }
+                        LOG.debug("Found certificate with: {}", cert.getSubjectX500Principal().getName());
                         return cert;
                     }
 
@@ -138,7 +148,7 @@
             }
 
         } catch (XMLSecurityException ex) {
-            throw new KeyResolverException("empty", ex);
+            throw new KeyResolverException(ex);
         }
 
         return null;
@@ -154,9 +164,7 @@
         if (storage == null) {
             Object exArgs[] = { Constants._TAG_X509DIGEST };
             KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "", ex);
-            }
+            LOG.debug("", ex);
             throw ex;
         }
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,12 +39,11 @@
 
 public class X509IssuerSerialResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509IssuerSerialResolver.class);
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public PublicKey engineLookupAndResolvePublicKey(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
@@ -59,26 +58,20 @@
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public X509Certificate engineLookupResolveX509Certificate(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
 
         X509Data x509data = null;
         try {
             x509data = new X509Data(element, baseURI);
         } catch (XMLSignatureException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+            LOG.debug("I can't");
             return null;
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+            LOG.debug("I can't");
             return null;
         }
 
@@ -91,9 +84,7 @@
                 KeyResolverException ex =
                     new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "", ex);
-                }
+                LOG.debug("", ex);
                 throw ex;
             }
 
@@ -104,44 +95,32 @@
                 X509Certificate cert = (X509Certificate)storageIterator.next();
                 XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert);
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName());
-                    log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString());
-                }
+                LOG.debug("Found Certificate Issuer: {}", certSerial.getIssuerName());
+                LOG.debug("Found Certificate Serial: {}", certSerial.getSerialNumber().toString());
 
                 for (int i = 0; i < noOfISS; i++) {
                     XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
 
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "Found Element Issuer:     "
-                                  + xmliss.getIssuerName());
-                        log.log(java.util.logging.Level.FINE, "Found Element Serial:     "
-                                  + xmliss.getSerialNumber().toString());
-                    }
+                    LOG.debug("Found Element Issuer:     {}", xmliss.getIssuerName());
+                    LOG.debug("Found Element Serial:     {}", xmliss.getSerialNumber().toString());
 
                     if (certSerial.equals(xmliss)) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "match !!! ");
-                        }
+                        LOG.debug("match !!! ");
                         return cert;
                     }
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "no match...");
-                    }
+                    LOG.debug("no match...");
                 }
             }
 
             return null;
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-            }
+            LOG.debug("XMLSecurityException", ex);
 
-            throw new KeyResolverException("generic.EmptyMessage", ex);
+            throw new KeyResolverException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
         Element element, String baseURI, StorageResolver storage
     ) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,9 +39,8 @@
 
 public class X509SKIResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509SKIResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SKIResolver.class);
 
 
     /**
@@ -69,7 +68,7 @@
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -79,13 +78,9 @@
     public X509Certificate engineLookupResolveX509Certificate(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
         if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+            LOG.debug("I can't");
             return null;
         }
         /** Field _x509childObject[] */
@@ -94,10 +89,8 @@
         Element x509childNodes[] = null;
         x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);
 
-        if (!((x509childNodes != null) && (x509childNodes.length > 0))) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+        if (!(x509childNodes != null && x509childNodes.length > 0)) {
+            LOG.debug("I can't");
             return null;
         }
         try {
@@ -106,9 +99,7 @@
                 KeyResolverException ex =
                     new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "", ex);
-                }
+                LOG.debug("", ex);
 
                 throw ex;
             }
@@ -126,16 +117,14 @@
 
                 for (int i = 0; i < x509childObject.length; i++) {
                     if (certSKI.equals(x509childObject[i])) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName());
-                        }
+                        LOG.debug("Return PublicKey from {}", cert.getSubjectX500Principal().getName());
 
                         return cert;
                     }
                 }
             }
         } catch (XMLSecurityException ex) {
-            throw new KeyResolverException("empty", ex);
+            throw new KeyResolverException(ex);
         }
 
         return null;
@@ -143,7 +132,7 @@
 
     /**
      * Method engineResolveSecretKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,16 +39,15 @@
 
 public class X509SubjectNameResolver extends KeyResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SubjectNameResolver.class);
 
 
     /**
      * Method engineResolvePublicKey
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @param storage
      * @return null if no {@link PublicKey} could be obtained
      * @throws KeyResolverException
@@ -69,7 +68,7 @@
 
     /**
      * Method engineResolveX509Certificate
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
@@ -79,26 +78,19 @@
     public X509Certificate engineLookupResolveX509Certificate(
         Element element, String baseURI, StorageResolver storage
     ) throws KeyResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
-        }
+        LOG.debug("Can I resolve {}?", element.getTagName());
         Element[] x509childNodes = null;
         XMLX509SubjectName x509childObject[] = null;
 
         if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+            LOG.debug("I can't");
             return null;
         }
         x509childNodes =
             XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);
 
-        if (!((x509childNodes != null)
-            && (x509childNodes.length > 0))) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I can't");
-            }
+        if (!(x509childNodes != null && x509childNodes.length > 0)) {
+            LOG.debug("I can't");
             return null;
         }
 
@@ -108,9 +100,7 @@
                 KeyResolverException ex =
                     new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "", ex);
-                }
+                LOG.debug("", ex);
 
                 throw ex;
             }
@@ -127,42 +117,31 @@
                 XMLX509SubjectName certSN =
                     new XMLX509SubjectName(element.getOwnerDocument(), cert);
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
-                }
+                LOG.debug("Found Certificate SN: {}", certSN.getSubjectName());
 
                 for (int i = 0; i < x509childObject.length; i++) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "Found Element SN:     "
-                              + x509childObject[i].getSubjectName());
-                    }
+                    LOG.debug("Found Element SN:     {}", x509childObject[i].getSubjectName());
 
                     if (certSN.equals(x509childObject[i])) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "match !!! ");
-                        }
+                        LOG.debug("match !!! ");
 
                         return cert;
                     }
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "no match...");
-                    }
+                    LOG.debug("no match...");
                 }
             }
 
             return null;
         } catch (XMLSecurityException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-            }
+            LOG.debug("XMLSecurityException", ex);
 
-            throw new KeyResolverException("generic.EmptyMessage", ex);
+            throw new KeyResolverException(ex);
         }
     }
 
     /**
      * Method engineResolveSecretKey
-     * @inheritDoc
+     * {@inheritDoc}
      * @param element
      * @param baseURI
      * @param storage
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-implementations for retrieval of certificates and public keys from elements.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-the resolver framework for retrieval of certificates and public keys from elements.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-general key related material.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -38,12 +38,11 @@
  */
 public class StorageResolver {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(StorageResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(StorageResolver.class);
 
     /** Field storageResolvers */
-    private List<StorageResolverSpi> storageResolvers = null;
+    private List<StorageResolverSpi> storageResolvers;
 
     /**
      * Constructor StorageResolver
@@ -67,7 +66,7 @@
      */
     public void add(StorageResolverSpi resolver) {
         if (storageResolvers == null) {
-            storageResolvers = new ArrayList<StorageResolverSpi>();
+            storageResolvers = new ArrayList<>();
         }
         this.storageResolvers.add(resolver);
     }
@@ -90,7 +89,7 @@
         try {
             this.add(new KeyStoreResolver(keyStore));
         } catch (StorageResolverException ex) {
-            log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex);
+            LOG.error("Could not add KeyStore because of: ", ex);
         }
     }
 
@@ -142,7 +141,7 @@
             currentResolver = findNextResolver();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public boolean hasNext() {
             if (currentResolver == null) {
                 return false;
@@ -153,10 +152,10 @@
             }
 
             currentResolver = findNextResolver();
-            return (currentResolver != null);
+            return currentResolver != null;
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public Certificate next() {
             if (hasNext()) {
                 return currentResolver.next();
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -40,6 +40,10 @@
         super();
     }
 
+    public StorageResolverException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor StorageResolverException
      *
@@ -62,22 +66,31 @@
     /**
      * Constructor StorageResolverException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public StorageResolverException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public StorageResolverException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor StorageResolverException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public StorageResolverException(String msgID, Object exArgs[],
-                                    Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public StorageResolverException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public StorageResolverException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,9 +23,11 @@
 package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateExpiredException;
@@ -33,12 +35,12 @@
 import java.security.cert.CertificateNotYetValidException;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
+import java.util.Base64;
 import java.util.Iterator;
 import java.util.List;
 
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 
 /**
  * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s
@@ -47,17 +49,16 @@
  */
 public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(
-            CertsInFilesystemDirectoryResolver.class.getName()
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(
+            CertsInFilesystemDirectoryResolver.class
         );
 
     /** Field merlinsCertificatesDir */
-    private String merlinsCertificatesDir = null;
+    private String merlinsCertificatesDir;
 
     /** Field certs */
-    private List<X509Certificate> certs = new ArrayList<X509Certificate>();
+    private List<X509Certificate> certs = new ArrayList<>();
 
     /**
      * @param directoryName
@@ -78,14 +79,16 @@
     private void readCertsFromHarddrive() throws StorageResolverException {
 
         File certDir = new File(this.merlinsCertificatesDir);
-        List<String> al = new ArrayList<String>();
+        List<String> al = new ArrayList<>();
         String[] names = certDir.list();
 
-        for (int i = 0; i < names.length; i++) {
-            String currentFileName = names[i];
+        if (names != null) {
+            for (int i = 0; i < names.length; i++) {
+                String currentFileName = names[i];
 
-            if (currentFileName.endsWith(".crt")) {
-                al.add(names[i]);
+                if (currentFileName.endsWith(".crt")) {
+                    al.add(names[i]);
+                }
             }
         }
 
@@ -94,24 +97,17 @@
         try {
             cf = CertificateFactory.getInstance("X.509");
         } catch (CertificateException ex) {
-            throw new StorageResolverException("empty", ex);
-        }
-
-        if (cf == null) {
-            throw new StorageResolverException("empty");
+            throw new StorageResolverException(ex);
         }
 
         for (int i = 0; i < al.size(); i++) {
             String filename = certDir.getAbsolutePath() + File.separator + al.get(i);
-            File file = new File(filename);
             boolean added = false;
             String dn = null;
 
-            FileInputStream fis = null;
-            try {
-                fis = new FileInputStream(file);
+            try (InputStream inputStream = Files.newInputStream(Paths.get(filename))) {
                 X509Certificate cert =
-                    (X509Certificate) cf.generateCertificate(fis);
+                    (X509Certificate) cf.generateCertificate(inputStream);
 
                 //add to ArrayList
                 cert.checkValidity();
@@ -120,40 +116,34 @@
                 dn = cert.getSubjectX500Principal().getName();
                 added = true;
             } catch (FileNotFoundException ex) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Could not add certificate from file " + filename, ex);
                 }
             } catch (CertificateNotYetValidException ex) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Could not add certificate from file " + filename, ex);
                 }
             } catch (CertificateExpiredException ex) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Could not add certificate from file " + filename, ex);
                 }
             } catch (CertificateException ex) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Could not add certificate from file " + filename, ex);
                 }
-            } finally {
-                try {
-                    if (fis != null) {
-                        fis.close();
-                    }
-                } catch (IOException ex) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex);
-                    }
+            } catch (IOException ex) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Could not add certificate from file " + filename, ex);
                 }
             }
 
-            if (added && log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Added certificate: " + dn);
+            if (added) {
+                LOG.debug("Added certificate: {}", dn);
             }
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public Iterator<Certificate> getIterator() {
         return new FilesystemIterator(this.certs);
     }
@@ -164,10 +154,10 @@
     private static class FilesystemIterator implements Iterator<Certificate> {
 
         /** Field certs */
-        List<X509Certificate> certs = null;
+        private List<X509Certificate> certs;
 
         /** Field i */
-        int i;
+        private int i;
 
         /**
          * Constructor FilesystemIterator
@@ -179,12 +169,12 @@
             this.i = 0;
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public boolean hasNext() {
-            return (this.i < this.certs.size());
+            return this.i < this.certs.size();
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public Certificate next() {
             return this.certs.get(this.i++);
         }
@@ -217,7 +207,7 @@
 
             System.out.println();
             System.out.println("Base64(SKI())=                 \""
-                               + Base64.encode(ski) + "\"");
+                               + Base64.getMimeEncoder().encodeToString(ski) + "\"");
             System.out.println("cert.getSerialNumber()=        \""
                                + cert.getSerialNumber().toString() + "\"");
             System.out.println("cert.getSubjectX500Principal().getName()= \""
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,7 +39,7 @@
 public class KeyStoreResolver extends StorageResolverSpi {
 
     /** Field keyStore */
-    private KeyStore keyStore = null;
+    private KeyStore keyStore;
 
     /**
      * Constructor KeyStoreResolver
@@ -53,11 +53,11 @@
         try {
             keyStore.aliases();
         } catch (KeyStoreException ex) {
-            throw new StorageResolverException("generic.EmptyMessage", ex);
+            throw new StorageResolverException(ex);
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public Iterator<Certificate> getIterator() {
         return new KeyStoreIterator(this.keyStore);
     }
@@ -98,16 +98,16 @@
             }
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public boolean hasNext() {
             if (nextCert == null) {
                 nextCert = findNextCert();
             }
 
-            return (nextCert != null);
+            return nextCert != null;
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public Certificate next() {
             if (nextCert == null) {
                 // maybe caller did not call hasNext()
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,7 +36,7 @@
 public class SingleCertificateResolver extends StorageResolverSpi {
 
     /** Field certificate */
-    private X509Certificate certificate = null;
+    private X509Certificate certificate;
 
     /**
      * @param x509cert the single {@link X509Certificate}
@@ -45,7 +45,7 @@
         this.certificate = x509cert;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public Iterator<Certificate> getIterator() {
         return new InternalIterator(this.certificate);
     }
@@ -70,12 +70,12 @@
             this.certificate = x509cert;
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public boolean hasNext() {
             return !this.alreadyReturned;
         }
 
-        /** @inheritDoc */
+        /** {@inheritDoc} */
         public Certificate next() {
             if (this.alreadyReturned) {
                 throw new NoSuchElementException();
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-implementations of resolvers for retrieval for certificates and public keys from user-specified locations.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-a resolver framework for certificates and public keys from user-specified locations.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-<HTML>
-  <HEAD> 
-	 <TITLE>com.sun.org.apache.xml.internal.security</TITLE> 
-  </HEAD> 
-  <BODY> 
-	 <H1>Canonical XML and XML Signature Implementation</H1> 
-	 <H2>Needs the following packages</H2> 
-	 <UL> 
-		<LI>Xerces v2.0.0 <A HREF="http://xml.apache.org/dist/xerces-j/">http://xml.apache.org/dist/xerces-j/</A></LI>
-		<LI>Xalan 2.2.0 <A HREF="http://xml.apache.org/dist/xalan-j/">http://xml.apache.org/dist/xalan-j/</A></LI>
-		<LI>JUnit 3.7 <A HREF="http://download.sourceforge.net/junit/junit3.7.zip">http://download.sourceforge.net/junit/junit3.5.zip</A></LI>
-		<LI>Jakarta Log4J 1.1.2 <A HREF="http://jakarta.apache.org/log4j/">http://jakarta.apache.org/log4j/</A></LI>
-		<LI>ANT <A HREF="http://jakarta.apache.org/builds/jakarta-ant/release/">http://jakarta.apache.org/builds/jakarta-ant/release/</A></LI> 
-	 </UL>
-	 <H1>Packages</H1> 
-	 <UL> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.algorithms} contains algorithm factories </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.c14n} contains Canonicalization related material and algorithms </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.exceptions} contains all exceptions used by this library </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.keys} contains key related material </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.samples} contains some sample applications and non-standard transforms </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.signature} contains the XML Signature specific classes </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.transforms} XML Signature transformations </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.utils} contains all utility classes </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.test} JUnit test cases </LI> 
-		<LI>{@link com.sun.org.apache.xml.internal.security.temp} is the playground for messing around </LI> 
-	 </UL> 
-	 <H2>Support</H2> 
-	 <P>See <A HREF="http://xml.apache.org/security/">the xml-security project</A> for further assistence</P> 
-	 <H2>Author</H2> 
-	 <P>Christian Geuer-Pollmann geuer-pollmann@nue.et-inf.uni-siegen.de<BR> 
-	    University of Siegen<BR> 
-	    Institute for Data Communications Systems<BR> 
-	 </P> 
-     </BODY>
-</HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,23 @@
 <?xml version="1.0"?>
 <!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License. You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied. See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
+<!--
 <!DOCTYPE Configuration SYSTEM "config.dtd">
 -->
 <!-- This configuration file is used for configuration of the com.sun.org.apache.xml.internal.security package -->
@@ -14,10 +32,12 @@
                               JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclOmitComments"/>
       <CanonicalizationMethod URI="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
                               JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments"/>
-      <CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11"
-                              JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments"/>
-      <CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11#WithComments"
-                              JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments"/>
+      <CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11"
+                              JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments"/>
+      <CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11#WithComments"
+                              JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments"/>
+      <CanonicalizationMethod URI="http://santuario.apache.org/c14n/physical"
+                              JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical"/>
    </CanonicalizationMethods>
    <TransformAlgorithms>
       <!-- Base64 -->
@@ -67,21 +87,50 @@
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSAMD5" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSARIPEMD160" />
+      <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha224"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA224" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA256" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA384" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" />
+                          
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#ripemd160-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSARIPEMD160MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA1MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA224MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA256MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA384MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512MGF1" />
+                          
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-224-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_224MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-256-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_256MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-384-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_384MGF1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-512-rsa-MGF1"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_512MGF1" />
+                          
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA1" />
+      <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA224" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA256" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA384" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA512" />
-
+      <SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160"
+                          JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSARIPEMD160" />
+                          
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
                           JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacMD5" />
       <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
@@ -114,6 +163,12 @@
                     AlgorithmClass="MessageDigest"
                     RequirementLevel="REQUIRED"
                     JCEName="SHA-1"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#sha224"
+                    Description="SHA-224 message digest"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="SHA-224"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#sha256"
                     Description="SHA-1 message digest with 256 bit"
@@ -133,12 +188,43 @@
                     AlgorithmClass="MessageDigest"
                     RequirementLevel="OPTIONAL"
                     JCEName="SHA-512"/>
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#whirlpool"
+                    Description="WHIRLPOOL message digest"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="WHIRLPOOL"/>
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-224"
+                    Description="SHA-3 message digest with 224 bit"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="SHA3-224"/>
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-256"
+                    Description="SHA-3 message digest with 256 bit"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="SHA3-256"/>                     
 
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-384"
+                    Description="SHA-3 message digest with 384 bit"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="SHA3-384"/>
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-512"
+                    Description="SHA-3 message digest with 512 bit"
+                    AlgorithmClass="MessageDigest"
+                    RequirementLevel="OPTIONAL"
+                    JCEName="SHA3-512"/>
+                               
          <!-- Signature Algorithms -->
          <Algorithm URI="http://www.w3.org/2000/09/xmldsig#dsa-sha1"
                     Description="Digital Signature Algorithm with SHA-1 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="REQUIRED"
+                    RequiredKey="DSA"
                     JCEName="SHA1withDSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-md5"
@@ -146,6 +232,7 @@
                     AlgorithmClass="Signature"
                     RequirementLevel="NOT RECOMMENDED"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
                     JCEName="MD5withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
@@ -153,19 +240,30 @@
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
                     JCEName="RIPEMD160withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"
                     Description="RSA Signature with SHA-1 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="RECOMMENDED"
+                    RequiredKey="RSA"
                     JCEName="SHA1withRSA"/>
 
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha2224"
+                    Description="RSA Signature with SHA-2224 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
+                    JCEName="SHA224withRSA"/>
+                    
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
                     Description="RSA Signature with SHA-256 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
                     JCEName="SHA256withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
@@ -173,6 +271,7 @@
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
                     JCEName="SHA384withRSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
@@ -180,8 +279,48 @@
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="RSA"
                     JCEName="SHA512withRSA"/>
                     
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1"
+                    Description="RSASSA-PSS Signature with SHA-1 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="RECOMMENDED"
+                    RequiredKey="RSA"
+                    JCEName="SHA1withRSAandMGF1"/>
+
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1"
+                    Description="RSASSA-PSS Signature with SHA-224 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
+                    RequiredKey="RSA"
+                    JCEName="SHA224withRSAandMGF1"/>
+
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1"
+                    Description="RSASSA-PSS Signature with SHA-256 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
+                    RequiredKey="RSA"
+                    JCEName="SHA256withRSAandMGF1"/>
+
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1"
+                    Description="RSASSA-PSS Signature with SHA-384 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
+                    RequiredKey="RSA"
+                    JCEName="SHA384withRSAandMGF1"/>
+
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1"
+                    Description="RSASSA-PSS Signature with SHA-512 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
+                    RequiredKey="RSA"
+                    JCEName="SHA512withRSAandMGF1"/>
+                    
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
                     Description="ECDSA Signature with SHA-1 message digest"
                     AlgorithmClass="Signature"
@@ -189,11 +328,20 @@
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA1withECDSA"/>
 
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224"
+                    Description="ECDSA Signature with SHA-224 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="EC"
+                    JCEName="SHA224withECDSA"/>
+                    
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
                     Description="ECDSA Signature with SHA-256 message digest"
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="EC"
                     JCEName="SHA256withECDSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
@@ -201,6 +349,7 @@
                     AlgorithmClass="Signature"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    RequiredKey="EC"
                     JCEName="SHA384withECDSA"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
@@ -209,13 +358,22 @@
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
                     JCEName="SHA512withECDSA"/>
-
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160"
+                    Description="ECDSA Signature with RIPEMD-160 message digest"
+                    AlgorithmClass="Signature"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="https://tools.ietf.org/html/rfc6931"
+                    RequiredKey="EC"
+                    JCEName="RIPEMD160withECDSA"/>
+                    
          <!-- MAC Algorithms -->
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
                     Description="Message Authentication code using MD5"
                     AlgorithmClass="Mac"
                     RequirementLevel="NOT RECOMMENDED"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
                     JCEName="HmacMD5"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
@@ -223,19 +381,30 @@
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
                     JCEName="HMACRIPEMD160"/>
 
          <Algorithm URI="http://www.w3.org/2000/09/xmldsig#hmac-sha1"
                     Description="Message Authentication code using SHA1"
                     AlgorithmClass="Mac"
                     RequirementLevel="REQUIRED"
+                    KeyLength="0"
                     JCEName="HmacSHA1"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha224"
+                    Description="Message Authentication code using SHA-224"
+                    AlgorithmClass="Mac"
+                    RequirementLevel="OPTIONAL"
+                    SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
+                    JCEName="HmacSHA224"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"
                     Description="Message Authentication code using SHA-256"
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
                     JCEName="HmacSHA256"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"
@@ -243,6 +412,7 @@
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
                     JCEName="HmacSHA384"/>
 
          <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"
@@ -250,6 +420,7 @@
                     AlgorithmClass="Mac"
                     RequirementLevel="OPTIONAL"
                     SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+                    KeyLength="0"
                     JCEName="HmacSHA512"/>
 
          <!-- Block encryption Algorithms -->
@@ -258,6 +429,7 @@
                     AlgorithmClass="BlockEncryption"
                     RequirementLevel="REQUIRED"
                     KeyLength="192"
+                    IVLength="64"
                     RequiredKey="DESede"
                     JCEName="DESede/CBC/ISO10126Padding"/>
 
@@ -266,6 +438,7 @@
                     AlgorithmClass="BlockEncryption"
                     RequirementLevel="REQUIRED"
                     KeyLength="128"
+                    IVLength="128"
                     RequiredKey="AES"
                     JCEName="AES/CBC/ISO10126Padding"/>
 
@@ -274,6 +447,7 @@
                     AlgorithmClass="BlockEncryption"
                     RequirementLevel="OPTIONAL"
                     KeyLength="192"
+                    IVLength="128"
                     RequiredKey="AES"
                     JCEName="AES/CBC/ISO10126Padding"/>
 
@@ -282,6 +456,7 @@
                     AlgorithmClass="BlockEncryption"
                     RequirementLevel="REQUIRED"
                     KeyLength="256"
+                    IVLength="128"
                     RequiredKey="AES"
                     JCEName="AES/CBC/ISO10126Padding"/>
                     
@@ -290,6 +465,7 @@
                    AlgorithmClass="BlockEncryption"
                    RequirementLevel="OPTIONAL"
                    KeyLength="128"
+                   IVLength="96"
                    RequiredKey="AES"
                    JCEName="AES/GCM/NoPadding"/>
                    
@@ -298,6 +474,7 @@
                    AlgorithmClass="BlockEncryption"
                    RequirementLevel="OPTIONAL"
                    KeyLength="192"
+                   IVLength="96"
                    RequiredKey="AES"
                    JCEName="AES/GCM/NoPadding"/>
 
@@ -306,8 +483,45 @@
                    AlgorithmClass="BlockEncryption"
                    RequirementLevel="OPTIONAL"
                    KeyLength="256"
+                   IVLength="96"
                    RequiredKey="AES"
                    JCEName="AES/GCM/NoPadding"/>
+                   
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#seed128-cbc"
+                    Description="Block encryption using SEED with a key length of 128 bit"
+                    AlgorithmClass="BlockEncryption"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="128"
+                    IVLength="128"
+                    RequiredKey="SEED"
+                    JCEName="SEED/CBC/ISO10126Padding"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia128-cbc"
+                    Description="Block encryption using Camellia with a key length of 128 bit"
+                    AlgorithmClass="BlockEncryption"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="128"
+                    IVLength="128"
+                    RequiredKey="Camellia"
+                    JCEName="Camellia/CBC/ISO10126Padding"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia192-cbc"
+                    Description="Block encryption using Camellia with a key length of 192 bit"
+                    AlgorithmClass="BlockEncryption"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="192"
+                    IVLength="128"
+                    RequiredKey="Camellia"
+                    JCEName="Camellia/CBC/ISO10126Padding"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia256-cbc"
+                    Description="Block encryption using Camellia with a key length of 256 bit"
+                    AlgorithmClass="BlockEncryption"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="256"
+                    IVLength="128"
+                    RequiredKey="Camellia"
+                    JCEName="Camellia/CBC/ISO10126Padding"/>
          
          <Algorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"
                     Description="Key Transport RSA-v1.5"
@@ -366,6 +580,38 @@
                     KeyLength="256"
                     RequiredKey="AES"
                     JCEName="AESWrap"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia128"
+                    Description="Symmetric Key Wrap using CAMELLIA with a key length of 128 bit"
+                    AlgorithmClass="SymmetricKeyWrap"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="128"
+                    RequiredKey="Camellia"
+                    JCEName="CamelliaWrap"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia192"
+                    Description="Symmetric Key Wrap using CAMELLIA with a key length of 192 bit"
+                    AlgorithmClass="SymmetricKeyWrap"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="192"
+                    RequiredKey="Camellia"
+                    JCEName="CamelliaWrap"/>
+                    
+         <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia256"
+                    Description="Symmetric Key Wrap using CAMELLIA with a key length of 256 bit"
+                    AlgorithmClass="SymmetricKeyWrap"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="256"
+                    RequiredKey="Camellia"
+                    JCEName="CamelliaWrap"/>
+                    
+         <Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#kw-seed128"
+                    Description="Symmetric Key Wrap using SEED with a key length of 128 bit"
+                    AlgorithmClass="SymmetricKeyWrap"
+                    RequirementLevel="OPTIONAL"
+                    KeyLength="128"
+                    RequiredKey="SEED"
+                    JCEName="SEEDWrap"/>
 
       </Algorithms>
    </JCEAlgorithmMappings>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML> <HEAD> </HEAD> <BODY> <P>
-software configuration and internationalization ({@link com.sun.org.apache.xml.internal.security.utils.I18n}).
-</P></BODY> </HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties	Tue Jun 19 16:33:07 2018 +0100
@@ -1,126 +1,196 @@
+#
+#
+#    Licensed to the Apache Software Foundation (ASF) under one
+#    or more contributor license agreements. See the NOTICE file
+#    distributed with this work for additional information
+#    regarding copyright ownership. The ASF licenses this file
+#    to you under the Apache License, Version 2.0 (the
+#    "License"); you may not use this file except in compliance
+#    with the License. You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing,
+#    software distributed under the License is distributed on an
+#    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#    KIND, either express or implied. See the License for the
+#    specific language governing permissions and limitations
+#    under the License.
+#
+#
+
 algorithm.alreadyRegistered = URI {0} wurde bereits an die Klasse {1} gebunden
-algorithm.classDoesNotExist = Kann URI {0} nicht für Klasse {1} registrieren weil sie nicht existiert
+algorithm.classDoesNotExist = Kann URI {0} nicht f\u00fcr Klasse {1} registrieren weil sie nicht existiert
 algorithm.ClassDoesNotExist = Klasse {0} existiert nicht
-algorithm.extendsWrongClass = Kann URI {0} nicht für Klasse {1} registrieren weil sie nicht {2} extended
-algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
-algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
-algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
-algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
-algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
-algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1}
-algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
-algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
-algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
-algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
-attributeValueIllegal = The attribute {0} has value {1} but must be {2}
-c14n.Canonicalizer.Exception = Exception während Kanonisierung:  Original Nachricht war {0}
-c14n.Canonicalizer.IllegalNode = Unzulässiger NodeType {0}, NodeName lautete {1}
-c14n.Canonicalizer.NoSuchCanonicalizer = Kein Canonicalizer mit dem URI {0} gefunden
-c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException während Kanonisierung:  Original Nachricht war {0}
+algorithm.extendsWrongClass = Kann URI {0} nicht f\u00fcr Klasse {1} registrieren weil sie nicht von {2} abgeleitet ist
+algorithms.CannotUseAlgorithmParameterSpecOnDSA = AlgorithmParameterSpec kann nicht f\u00fcr DSA Signaturen benutzt werden.
+algorithms.CannotUseAlgorithmParameterSpecOnRSA = AlgorithmParameterSpec kann nicht f\u00fcr RSA Signaturen benutzt werden.
+algorithms.CannotUseSecureRandomOnMAC = SecureRandom kann nicht f\u00fcr MAC's angewandt werden.
+algorithms.HMACOutputLengthMin = HMACOutputLength darf nicht kleiner als {0} sein
+algorithms.HMACOutputLengthOnlyForHMAC = Die HMACOutputLength kann nur bei HMAC integrit\u00e4ts Algorithmen angegeben werden
+algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar.
+algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar. Original Nachricht war\: {1}
+algorithms.NoSuchMap = Algorithmus URI "{0}" konnte auf keinen JCE Algorithmus gemappt werden
+algorithms.NoSuchProvider = Der angegebene Provider {0} existiert nicht. Original Nachricht war\: {1}
+algorithms.operationOnlyVerification = Ein \u00f6ffentlicher Schl\u00fcssel (public key) kann nur zur Verifizierung einer Signatur verwendet werden.
+algorithms.WrongKeyForThisOperation = Der angegebene Schl\u00fcssel-Typ kann nicht f\u00fcr diese Operation verwendet werden. Angegeben wurde {0} aber ein {1} wird ben\u00f6tigt.
+attributeValueIllegal = Das Attribut {0} hat den Wert {1} muss aber {2} sein.
+c14n.Canonicalizer.Exception = Fehler w\u00e4hrend der Kanonisierung\:  Original Nachricht war {0}
+c14n.Canonicalizer.IllegalNode = Unzul\u00e4ssiger NodeType {0}, NodeName lautete {1}
+c14n.Canonicalizer.NoSuchCanonicalizer = Kein Kanonisierer mit dem URI {0} gefunden
+c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException w\u00e4hrend der Kanonisierung\:  Original Nachricht war {0}
 c14n.Canonicalizer.RelativeNamespace = Das Element {0} hat einen relativen Namespace: {1}="{2}"
-c14n.Canonicalizer.SAXException = SAXException während Kanonisierung:  Original Nachricht war {0}
-c14n.Canonicalizer.TraversalNotSupported = Das DOM Dokument unterstützt keine Traversal {0}
-c14n.Canonicalizer.UnsupportedEncoding = Unbekannte Kodierung {0}
-c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
-c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
-certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
-certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
-certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
-defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
-ElementProxy.nullElement = Kann einen ElementProxy aus einem null Argument erzeugen
+c14n.Canonicalizer.SAXException = SAXException w\u00e4hrend der Kanonisierung\:  Original Nachricht war {0}
+c14n.Canonicalizer.TraversalNotSupported = Das DOM Dokument unterst\u00fctzt keine Traversal {0}
+c14n.Canonicalizer.UnsupportedEncoding = Nicht unterst\u00fctzte Kodierung {0}
+c14n.Canonicalizer.UnsupportedOperation = Der Kanonisierer unterst\u00fctzt diese Operation nicht
+c14n.XMLUtils.circumventBug2650forgotten = Die Baumstruktur wurde nicht vorbereitet f\u00fcr die Kanonisierung mit XMLUtils\#circumventBug2650(Document)
+certificate.noSki.lowVersion = Das Zertifikat dard kein SubjectKeyIdentifier enthalten da es nur ein X509v{0} ist
+certificate.noSki.notOctetString = Der SubjectKeyIdentifier des Zertifikates ist kein "OctetString"
+certificate.noSki.null = Das Zertifikat enth\u00e4lt kein SubjectKeyIdentifier
+defaultNamespaceCannotBeSetHere = Standard Namespace kann hier nicht gesetzt werden
+ElementProxy.nullElement = Kann keinen ElementProxy aus einem null Argument erzeugen
 empty = {0}
 encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
 encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
 encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
 encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
-encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
-encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
-encryption.RSAOAEP.dataHashWrong = data hash wrong
-encryption.RSAOAEP.dataStartWrong = data wrong start {0}
-encryption.RSAOAEP.dataTooShort = data too short
-encryption.RSAPKCS15.blockTruncated = block truncated
-encryption.RSAPKCS15.noDataInBlock = no data in block
-encryption.RSAPKCS15.unknownBlockType = unknown block type
-encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
-endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
-errorMessages.InvalidDigestValueException = Ungültige Signatur: Reference Validation fehlgeschlagen.
-errorMessages.InvalidSignatureValueException = Ungültige Signatur: Core Validation fehlgeschlagen.
+encryption.ExplicitKeySizeMismatch = Das xenc\:KeySize Element fordert eine Schl\u00fcssel-L\u00e4nge von {0} bits aber der Algorithmus besitzt {1} bits
+encryption.nonceLongerThanDecryptedPlaintext = Das angegebene "Nonce" ist l\u00e4nger als der verf\u00fcgbare Plaintext.
+encryption.RSAOAEP.dataHashWrong = Falscher Hash-Wert
+encryption.RSAOAEP.dataStartWrong = Falscher Start Input {0}
+encryption.RSAOAEP.dataTooShort = Zu wenig Input
+encryption.RSAPKCS15.blockTruncated = Block abgeschnitten
+encryption.RSAPKCS15.noDataInBlock = Im Block sind keine Daten enthalten
+encryption.RSAPKCS15.unknownBlockType = Unbekannter Block Typ
+encryption.nokey = Es ist kein verschl\u00fcsselungs Schl\u00fcssel geladen und es konnte kein Schl\u00fcssel mit Hilfe der "key resolvers" gefunden werden.
+endorsed.jdk1.4.0 = Leider scheint niemand unsere Installations-Anleitung zu lesen, deshalb m\u00fcssen wir es \u00fcber die Exception machen\: Du hast den "endorsing" Mechanismus vom JDK 1.4 nicht richtig angewandt. Schaue unter <http\://xml.apache.org/security/Java/installation.html> nach wie man das Problem l\u00f6st.
+errorMessages.InvalidDigestValueException = Ung\u00fcltige Signatur\: Referen-Validierung fehlgeschlagen.
+errorMessages.InvalidSignatureValueException = Ung\u00fcltige Signatur\: Core Validierung fehlgeschlagen.
 errorMessages.IOException = Datei oder Resource kann nicht gelesen werden.
-errorMessages.MissingKeyFailureException = Verifizieren fehlgeschlagen, weil der öffentliche Schlüssel (public key) nicht verfügbar ist. Resourcen via addResource() hinzufügen und erneut verifizieren.
-errorMessages.MissingResourceFailureException = Verifizieren fehlgeschlagen, weil Resourcen nicht verfügbar sind. Resourcen via addResource() hinzufügen und erneut verifizieren.
+errorMessages.MissingKeyFailureException = Verifizierung fehlgeschlagen, weil der \u00f6ffentliche Schl\u00fcssel (public key) nicht verf\u00fcgbar ist. Resourcen via addResource() hinzuf\u00fcgen und erneut versuchen.
+errorMessages.MissingResourceFailureException = Verifizierung fehlgeschlagen, weil Resourcen nicht verf\u00fcgbar sind. Resourcen via addResource() hinzuf\u00fcgen und erneut versuchen.
 errorMessages.NoSuchAlgorithmException = Unbekannter Algorithmus {0}
-errorMessages.NotYetImplementedException = Funktionalität noch nicht implementiert.
-errorMessages.XMLSignatureException = Verifizieren aus unbekanntem Grund fehlgeschlagen.
+errorMessages.NotYetImplementedException = Funktionalit\u00e4t noch nicht implementiert.
+errorMessages.XMLSignatureException = Verifizierung aus unbekanntem Grund fehlgeschlagen.
 decoding.divisible.four = It should be divisible by four
-decoding.general = Error while decoding
-FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
-FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
-FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
-FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
-generic.dontHaveConstructionElement = I do not have a construction Element
+decoding.general = Fehler beim Decodieren
+FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Methode addToDefaultFromRemote() wurde noch nicht implementiert.
+FileKeyStorageImpl.NoCert.Context = Kein X509-Zertifikat mit Kontext {0} gefunden
+FileKeyStorageImpl.NoCert.IssNameSerNo = Kein X509-Zertifikat mit IssuerName {0} und serial number {1} gefunden
+FileKeyStorageImpl.NoCert.SubjName = Kein X509-Zertifikat mit SubjectName {0} gefunden
+generic.dontHaveConstructionElement = Konstruktions-Element fehlt
 generic.EmptyMessage = {0}
 generic.NotYetImplemented = {0} Leider noch nicht implementiert ;-((
-java.security.InvalidKeyException = Ungültiger Schlüssel
-java.security.NoSuchProviderException = Unbekannter oder nicht unterstützter Provider
-java.security.UnknownKeyType = Unbekannter oder nicht unterstützter Key type {0}
-KeyInfo.needKeyResolver = Es müssen mehrere KeyResolver registriert sein
-KeyInfo.nokey = Kann keinen Schlüssel aus {0} gewinnen
-KeyInfo.noKey = Kann keinen öffentlichen Schlüssel finden
-KeyInfo.wrongNumberOfObject = Benötige {0} keyObjects
+java.security.InvalidKeyException = Ung\u00fcltiger Schl\u00fcssel
+java.security.NoSuchProviderException = Unbekannter oder nicht unterst\u00fctzter Provider
+java.security.UnknownKeyType = Unbekannter oder nicht unterst\u00fctzter Schl\u00fcssel-Typ {0}
+KeyInfo.error = Error loading Key Info
+KeyInfo.needKeyResolver = Es m\u00fcssen mehrere KeyResolver registriert sein
+KeyInfo.nokey = Kann keinen Schl\u00fcssel aus {0} gewinnen
+KeyInfo.noKey = Kann keinen \u00f6ffentlichen Schl\u00fcssel finden
+KeyInfo.wrongNumberOfObject = Ben\u00f6tige {0} keyObjects
 KeyInfo.wrongUse = Dieses Objekt wird verwendet, um {0} zu gewinnen
-keyResolver.alreadyRegistered = Die Klasse {1} wurde bereits registriert für {0}
-KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
+keyResolver.alreadyRegistered = Die Klasse {1} wurde bereits registriert f\u00fcr {0}
+KeyResolver.needStorageResolver = Es wird ein StorageResolver ben\u00f6tigt um ein Zertifikat aus {0} zu holen
 KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
 KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
 KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
 KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
-KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
-KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
+KeyResoverSpiImpl.keyStore = KeyStorage Fehler in der implementierenden Klasse {0}
+KeyResoverSpiImpl.need.Element = Es wird der Typ {1} ben\u00f6tigt in der implementierenden Klasse {0}
 KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
 KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
 KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
-KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
-KeyStore.register = {1} type class register error  in class {0}
-KeyStore.registerStore.register = Registeration error for type {0}
-KeyValue.IllegalArgument = Cannot create a {0} from {1}
-namespacePrefixAlreadyUsedByOtherURI = Namespace {0} already used by other URI {1}
+KeyStore.alreadyRegistered = Klasse {0} bereits registriert f\u00fcr {1}
+KeyStore.register = {1} type class register error in class {0}
+KeyStore.registerStore.register = Registrierungsfehler f\u00fcr Typ {0}
+KeyValue.IllegalArgument = Kann kein {0} aus {1} erzeugen
+namespacePrefixAlreadyUsedByOtherURI = Namespace {0} wird bereits von einer anderen URI {1} gebraucht
 notYetInitialized = Das Modul {0} ist noch nicht initialisiert
 prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er ist bereits an {2} zugewiesen
-signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0}
-signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
-signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
-signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
-signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
+signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Kanonisierer. Kein Handler installiert f\u00fcr URI {0}
+signature.DSA.invalidFormat = Ung\u00fcltige ASN.1 Kodierung der DSA Signatur
+signature.Generation.signBeforeGetValue = Es muss zuerst XMLSignature.sign(java.security.PrivateKey) aufgerufen werden
+signature.Reference.ForbiddenResolver = Der "Resolver" {0} ist bei aktivierter "secure validation" nicht erlaubt
+signature.Reference.NoDigestMethod = A Signature Reference Element must contain a DigestMethod child
+signature.Reference.NoDigestValue = A Signature Reference Element must contain a DigestValue child
+signature.signatureAlgorithm = Der Algorithmus {0} ist bei aktivierter "secure validation" nicht erlaubt
 signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein
-signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
-signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation
-signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf.
-signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled
+signature.tooManyReferences = Das Manifest enth\u00e4lt {0} Referenzen, bei aktivierter "secure validation" sind aber maximal {1} erlaubt
+signature.tooManyTransforms = Die Referenz enth\u00e4lt {0} Transformationen, bei aktivierter "secure validation" sind aber maximal {1} erlaubt
+signature.Transform.ErrorDuringTransform = W\u00e4hrend der Transformation {0} trat eine {1} auf.
+signature.Transform.ForbiddenTransform = Die Transformation {0} ist bei aktivierter "secure validation" nicht erlaubt
 signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert
-signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler?
-signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0}
-signature.Util.BignumNonPositive = bigInteger.signum() muß positiv sein
-signature.Util.NonTextNode = Kein Text Node
-signature.Util.TooManyChilds = Zu viele Child-Elemente vom Type {0} in {1}
+signature.Transform.NullPointerTransform = Null pointer als URI \u00fcbergeben. Programmierfehler?
+signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert f\u00fcr URI {0}
+signature.Util.BignumNonPositive = bigInteger.signum() muss positiv sein
+signature.Util.NonTextNode = Keine Text Node
+signature.Util.TooManyChilds = Zu viele Kind-Elemente vom Typ {0} in {1}
 signature.Verification.certificateError = Zertifikatsfehler
-signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
+signature.Verification.IndexOutOfBounds = Index {0} illegal. Es sind nur {1} Referenzen vorhanden
 signature.Verification.internalError = Interner Fehler
-signature.Verification.InvalidDigestOrReference = Ungültiger Digest Wert oder Reference Element {0}
-signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen
-signature.Verification.MissingID = Cannot resolve element with ID {0}
-signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen
-signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
-signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1}
-signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten.
+signature.Verification.InvalidDigestOrReference = Ung\u00fcltiger Digest Wert der Referenz {0}
+signature.Verification.keyStore = \u00d6ffnen des KeyStore fehlgeschlagen
+signature.Verification.MissingID = Element mit der ID {0} nicht gefunden
+signature.Verification.MissingResources = Kann die externe Resource {0} nicht aufl\u00f6sen
+signature.Verification.MultipleIDs = Mehrere Elemente mit der ID {0} gefunden
+signature.Verification.NoSignatureElement = Input Dokument enth\u00e4lt kein {0} Element mit dem Namespace {1}
+signature.Verification.Reference.NoInput = Die Referenz f\u00fcr den URI {0} hat keinen XMLSignatureInput erhalten.
 signature.Verification.SignatureError = Signatur Fehler
 signature.XMLSignatureInput.MissingConstuctor = Kann aus der Klasse {0} keinen XMLSignatureInput erzeugen
-signature.XMLSignatureInput.SerializeDOM = Input mit einem DOM Dokument initialisiert. Muß mit C14N serialisiert werden
-transform.Init.IllegalContextArgument = Unzulässiges Kontext Argument der Klasse {0}. Muss String, org.w3c.dom.NodeList oder java.io.InputStream sein.
+signature.XMLSignatureInput.SerializeDOM = Input mit einem DOM Dokument initialisiert. Muss mit C14N serialisiert werden
+transform.Init.IllegalContextArgument = Unzul\u00e4ssiges Kontext Argument der Klasse {0}. Muss String, org.w3c.dom.NodeList oder java.io.InputStream sein.
 transform.init.NotInitialized =
 transform.init.wrongURI = Initialisiert mit dem falschen URI. Das sollte nie passieren. Die Transformation implementiert {0} aber {1} wurde bei der Instantiierung verwendet.
-utils.Base64.IllegalBitlength = Ungültige Bytelänge; Muss ein vielfaches von 4 sein
-utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
+utils.Base64.IllegalBitlength = Ung\u00fcltige Byte-L\u00e4nge; Muss ein vielfaches von 4 sein
+utils.resolver.noClass = Keinen Resolver f\u00fcr URI {0} und Base {1} gefunden
 xml.WrongContent = Kann {0} nicht finden in {1}
 xml.WrongElement = Kann kein {0} aus einem {1} Element erzeugen
 xpath.funcHere.documentsDiffer = Der XPath ist nicht im selben Dokument wie der Kontext Node
-xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
+xpath.funcHere.noXPathContext = Versuch einer XPath-Evaluierung welcher die Funktion here() benutzt aber der XPath ist nicht innerhalb eines ds\:XPath Elements. XPath \: {0}
+signature.Transform.node = Aktuelle Node\: {0}
+signature.Transform.nodeAndType = Aktuelle Node\: {0}, Typ\: {1}
+signature.XMLSignatureInput.nodesetReference = Das Node-Set der Referenz konnte nicht konvertieren werden
+transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform konnte kein Signatur Element finden
+Base64Decoding = Fehler bei der Decodierung
+secureProcessing.MaximumAllowedTransformsPerReference = Die Referenz enth\u00e4lt {0} Transformationen. Es sind aber maximal {1} erlaubt. Die Limite kann \u00fcber das Konfigurations-Property "MaximumAllowedTransformsPerReference" erh\u00f6ht werden.
+secureProcessing.MaximumAllowedReferencesPerManifest = Das Manifest enh\u00e4lt {0} Referenzen. Es sind aber maximal {1} erlaubt. Die Limite kann \u00fcber das Konfigurations-Property "MaximumAllowedReferencesPerManifest" erh\u00f6ht werden.
+secureProcessing.DoNotThrowExceptionForManifests = Signatur-Manifests werden nicht unterst\u00fctzt. Das werfen dieser Exception kann durch das Konfigurations-Property "DoNotThrowExceptionForManifests" verhindert werden.
+secureProcessing.AllowMD5Algorithm = Vom Einsatz des MD5 Algorithmus wird strengstens abgeraten. Trotzdem kann er \u00fcber das Konfigurations-Property "AllowMD5Algorithm" erlaubt werden.
+secureProcessing.AllowNotSameDocumentReferences = Externe Referenzen gefunden. Die Verarbeitung von externen Referenzen ist standardm\u00e4ssig ausgeschaltet. Es kann \u00fcber das Konfigurations-Property "AllowNotSameDocumentReferences" aktiviert werden.
+secureProcessing.MaximumAllowedXMLStructureDepth = Die Maximum erlaubte Dokumenten-Tiefe von ({0}) wurde erreicht. Die Limite kann \u00fcber das Konfigurations-Property "MaximumAllowedXMLStructureDepth" erh\u00f6ht werden.
+secureProcessing.inputStreamLimitReached = Maximal erlaubte Anzahl bytes ({0}) erreicht.
+stax.duplicateActions=Doppelte Actions sind nicht erlaubt.
+stax.missingSecurityProperties = SecurityProperties darf nicht null sein\!
+stax.noOutputAction = Keine ausgehenden "Actions" definiert.
+stax.noKey = Kein Schl\u00fcssel geladen und es konnte kein Schl\u00fcssel gefunden werden f\u00fcr {0}
+stax.keyNotFound = Schl\u00fcssel nicht gefunden.
+stax.unsupportedKeyValue = Kein oder ung\u00fcltiger KeyValue.
+stax.emptyReferenceURI = Referenz enth\u00e4lt kein URI Attribut.
+stax.encryption.unprocessedReferences = Es wurden nicht alle Verschl\u00fcsselungs-Referenzen verarbeitet...
+stax.signature.unprocessedReferences = Es wurden nicht alle Signatur-Referenzen verarbeitet...
+stax.unsupportedToken = {0} nicht unterst\u00fctzt.
+stax.xmlStructureSizeExceeded = Maximal erlaubte ({0}) XML-Struktur Tiefe erreicht.
+stax.unexpectedXMLEvent = Unerwarteter StAX-Event\: {0}
+stax.encryption.noEncAlgo = xenc\:EncryptedKey enth\u00e4lt kein xenc\:EncryptionMethod/@Algorithm.
+stax.encryption.noCipherValue = EncryptedKey enth\u00e4lt kein xenc\:CipherData/xenc\:CipherValue.
+stax.unsecuredMessage = Ungesicherte Nachricht. Weder ein Signatur- noch ein EncryptedData- Element wurde gefunden.
+stax.signature.signedInfoMissing = SignedInfo Element fehlt.
+stax.signature.signatureMethodMissing = Signature method fehlt.
+stax.signature.canonicalizationMethodMissing = Signature canonicalization method fehlt.
+stax.signature.signatureValueMissing = Signature value fehlt.
+stax.signature.publicKeyOrCertificateMissing = Weder ein Zertifikat noch ein public-key wurde konfiguriert.
+stax.encryption.encryptionKeyMissing = Kein Schl\u00fcssel f\u00fcr die Verschl\u00fcsselung wurde konfiguriert.
+stax.unsupportedKeyTransp = Der public-key Algorithmus ist zu kurz um den symmetrischen Schl\u00fcssel zu verschl\u00fcsseln.
+stax.recursiveKeyReference = Rekursive Schl\u00fcssel referenzierung detektiert.
+stax.ecParametersNotSupported = ECParameters werden nicht unterst\u00fctzt.
+stax.namedCurveMissing = NamedCurve fehlt.
+stax.encryption.securePartNotFound = Part zum Verschl\u00fcsseln nicht gefunden: {0}
+stax.signature.securePartNotFound = Part zum Signieren nicht gefunden: {0}
+stax.multipleSignaturesNotSupported = Mehrere Signaturen werden nicht unterstützt.
+stax.signature.keyNameMissing = KeyName nicht konfiguriert.
+stax.keyNotFoundForName = Kein Schl\u00fcssel für Schl\u00fcsselname konfiguriert: {0}
+stax.keyTypeNotSupported = Key vom Typ {0} nicht f\u00fcr einen Key-Namenssuche unterst\u00fctzt
+stax.idsetbutnotgenerated = An Id attribute is specified, but Id generation is disabled
+stax.idgenerationdisablewithmultipleparts = Id generation must not be disabled when multiple parts need signing
\ No newline at end of file
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Tue Jun 19 16:33:07 2018 +0100
@@ -1,3 +1,24 @@
+#
+#
+#    Licensed to the Apache Software Foundation (ASF) under one
+#    or more contributor license agreements. See the NOTICE file
+#    distributed with this work for additional information
+#    regarding copyright ownership. The ASF licenses this file
+#    to you under the Apache License, Version 2.0 (the
+#    "License"); you may not use this file except in compliance
+#    with the License. You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing,
+#    software distributed under the License is distributed on an
+#    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#    KIND, either express or implied. See the License for the
+#    specific language governing permissions and limitations
+#    under the License.
+#
+#
+
 algorithm.alreadyRegistered = URI {0} already assigned to class {1}
 algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
 algorithm.ClassDoesNotExist = Class {0} does not exist
@@ -5,8 +26,9 @@
 algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
 algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
 algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
-algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
+algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
 algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
+algorithms.NoSuchAlgorithmNoEx = The requested algorithm {0} does not exist.
 algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
 algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
 algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
@@ -63,7 +85,8 @@
 java.security.InvalidKeyException = Invalid key
 java.security.NoSuchProviderException = Unknown or unsupported provider
 java.security.UnknownKeyType = Unknown or unsupported key type {0}
-KeyInfo.needKeyResolver = More than one keyResovler have to be registered
+KeyInfo.error = Error loading Key Info
+KeyInfo.needKeyResolver = More than one keyResolver have to be registered
 KeyInfo.nokey = Cannot get key from {0}
 KeyInfo.noKey = Cannot get the public key
 KeyInfo.wrongNumberOfObject = Need {0} keyObjects
@@ -80,8 +103,8 @@
 KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
 KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
 KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
-KeyStore.register = {1} type class register error  in class {0}
-KeyStore.registerStore.register = Registeration error for type {0}
+KeyStore.register = {1} type class register error in class {0}
+KeyStore.registerStore.register = Registration error for type {0}
 KeyValue.IllegalArgument = Cannot create a {0} from {1}
 namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
 notYetInitialized = The module {0} is not yet initialized
@@ -90,6 +113,8 @@
 signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
 signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
 signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
+signature.Reference.NoDigestMethod = A Signature Reference Element must contain a DigestMethod child
+signature.Reference.NoDigestValue = A Signature Reference Element must contain a DigestValue child
 signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
 signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
 signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
@@ -121,7 +146,7 @@
 transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
 transform.init.NotInitialized =
 transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
-transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element
+transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element
 utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
 Base64Decoding = Error while decoding
 utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
@@ -129,3 +154,43 @@
 xml.WrongElement = Cannot create a {0} from a {1} element
 xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
 xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
+secureProcessing.MaximumAllowedTransformsPerReference = {0} transforms are contained in the Reference, maximum {1} are allowed. You can raise the maximum via the \"MaximumAllowedTransformsPerReference\" property in the configuration.
+secureProcessing.MaximumAllowedReferencesPerManifest = {0} references are contained in the Manifest, maximum {1} are allowed. You can raise the maximum via the \"MaximumAllowedReferencesPerManifest\" property in the configuration.
+secureProcessing.DoNotThrowExceptionForManifests = Signature Manifests are not supported. You can disable throwing of an exception via the \"DoNotThrowExceptionForManifests\" property in the configuration.
+secureProcessing.AllowMD5Algorithm = The use of MD5 algorithm is strongly discouraged. Nonetheless can it be enabled via the \"AllowMD5Algorithm\" property in the configuration.
+secureProcessing.AllowNotSameDocumentReferences = External references found. Processing of external references is disabled by default. You can enable it via the \"AllowNotSameDocumentReferences\" property in the configuration.
+secureProcessing.MaximumAllowedXMLStructureDepth = Maximum depth ({0}) of the XML structure reached. You can raise the maximum via the \"MaximumAllowedXMLStructureDepth\" property in the configuration.
+secureProcessing.inputStreamLimitReached = Maximum byte count ({0}) reached.
+stax.duplicateActions = Duplicate Actions are not allowed.
+stax.missingSecurityProperties = SecurityProperties must not be null!
+stax.noOutputAction = No outgoing actions specified.
+stax.noKey = Key could not be resolved and no key was loaded for {0}
+stax.keyNotFound = Key not found.
+stax.unsupportedKeyValue = No or unsupported key in KeyValue.
+stax.emptyReferenceURI = Reference is missing an URI attribute.
+stax.encryption.unprocessedReferences = Some encryption references were not processed...
+stax.signature.unprocessedReferences = Some signature references were not processed...
+stax.unsupportedToken = {0} not supported.
+stax.xmlStructureSizeExceeded = Maximum ({0}) allowed XML Structure size exceeded.
+stax.unexpectedXMLEvent = Unexpected StAX-Event\: {0}
+stax.encryption.noEncAlgo = xenc:EncryptedKey does not contain xenc:EncryptionMethod/@Algorithm.
+stax.encryption.noCipherValue = EncryptedKey does not contain xenc:CipherData/xenc:CipherValue.
+stax.unsecuredMessage = Unsecured message. Neither a Signature nor a EncryptedData element found.
+stax.signature.signedInfoMissing = SignedInfo Element is missing.
+stax.signature.signatureMethodMissing = Signature method is missing.
+stax.signature.canonicalizationMethodMissing = Signature canonicalization method is missing.
+stax.signature.signatureValueMissing = Signature value is missing.
+stax.signature.publicKeyOrCertificateMissing = Certificate or public key not configured.
+stax.encryption.encryptionKeyMissing = Key for encryption not configured.
+stax.unsupportedKeyTransp = public key algorithm too weak to encrypt symmetric key.
+stax.recursiveKeyReference = Recursive key reference detected.
+stax.ecParametersNotSupported = ECParameters not supported.
+stax.namedCurveMissing = NamedCurve is missing.
+stax.encryption.securePartNotFound = Part to encrypt not found: {0}
+stax.signature.securePartNotFound = Part to sign not found: {0}
+stax.multipleSignaturesNotSupported = Multiple signatures are not supported.
+stax.signature.keyNameMissing = KeyName not configured.
+stax.keyNotFoundForName = No key configured for KeyName: {0}
+stax.keyTypeNotSupported = Key of type {0} not supported for a KeyName lookup
+stax.idsetbutnotgenerated = An Id attribute is specified, but Id generation is disabled
+stax.idgenerationdisablewithmultipleparts = Id generation must not be disabled when multiple parts need signing
\ No newline at end of file
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,7 +27,6 @@
  * Additional human readable info is passed to the constructor -- this being the benefit
  * of raising an exception or returning a value.
  *
- * @author Christian Geuer-Pollmann
  */
 public class InvalidDigestValueException extends XMLSignatureException {
 
@@ -66,21 +65,31 @@
     /**
      * Constructor InvalidDigestValueException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public InvalidDigestValueException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public InvalidDigestValueException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor InvalidDigestValueException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public InvalidDigestValueException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public InvalidDigestValueException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,7 +26,6 @@
  * Raised if testing the signature value over <i>DigestValue</i> fails because of invalid signature.
  *
  * @see InvalidDigestValueException  MissingKeyFailureException  MissingResourceFailureException
- * @author Christian Geuer-Pollmann
  */
 public class InvalidSignatureValueException extends XMLSignatureException {
 
@@ -65,21 +64,31 @@
     /**
      * Constructor InvalidSignatureValueException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public InvalidSignatureValueException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public InvalidSignatureValueException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor InvalidSignatureValueException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public InvalidSignatureValueException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public InvalidSignatureValueException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -50,8 +50,8 @@
 import org.xml.sax.SAXException;
 
 /**
- * Handles <code>&lt;ds:Manifest&gt;</code> elements.
- * <p> This element holds the <code>Reference</code> elements</p>
+ * Handles {@code &lt;ds:Manifest&gt;} elements.
+ * <p> This element holds the {@code Reference} elements</p>
  */
 public class Manifest extends SignatureElementProxy {
 
@@ -60,36 +60,35 @@
      */
     public static final int MAXIMUM_REFERENCE_COUNT = 30;
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Manifest.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(Manifest.class);
 
     /** Field references */
     private List<Reference> references;
     private Element[] referencesEl;
 
     /** Field verificationResults[] */
-    private boolean verificationResults[] = null;
+    private boolean[] verificationResults;
 
     /** Field resolverProperties */
-    private Map<String, String> resolverProperties = null;
+    private Map<String, String> resolverProperties;
 
     /** Field perManifestResolvers */
-    private List<ResourceResolver> perManifestResolvers = null;
+    private List<ResourceResolver> perManifestResolvers;
 
     private boolean secureValidation;
 
     /**
      * Constructs {@link Manifest}
      *
-     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     * @param doc the {@link Document} in which {@code XMLsignature} is placed
      */
     public Manifest(Document doc) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
-        this.references = new ArrayList<Reference>();
+        this.references = new ArrayList<>();
     }
 
     /**
@@ -100,7 +99,7 @@
      * @throws XMLSecurityException
      */
     public Manifest(Element element, String baseURI) throws XMLSecurityException {
-        this(element, baseURI, false);
+        this(element, baseURI, true);
 
     }
     /**
@@ -125,7 +124,7 @@
         // check out Reference children
         this.referencesEl =
             XMLUtils.selectDsNodes(
-                this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE
+                getFirstChild(), Constants._TAG_REFERENCE
             );
         int le = this.referencesEl.length;
         if (le == 0) {
@@ -143,7 +142,7 @@
         }
 
         // create List
-        this.references = new ArrayList<Reference>(le);
+        this.references = new ArrayList<>(le);
 
         for (int i = 0; i < le; i++) {
             Element refElem = referencesEl[i];
@@ -156,12 +155,12 @@
     }
 
     /**
-     * This <code>addDocument</code> method is used to add a new resource to the
+     * This {@code addDocument} method is used to add a new resource to the
      * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
      * from the supplied values.
      *
      * @param baseURI the URI of the resource where the XML instance was stored
-     * @param referenceURI <code>URI</code> attribute in <code>Reference</code> for specifying
+     * @param referenceURI {@code URI} attribute in {@code Reference} for specifying
      * where data is
      * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered
      * list of transformations to be performed.
@@ -176,7 +175,7 @@
     ) throws XMLSignatureException {
         // the this.doc is handed implicitly by the this.getOwnerDocument()
         Reference ref =
-            new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI);
+            new Reference(getDocument(), baseURI, referenceURI, this, transforms, digestURI);
 
         if (referenceId != null) {
             ref.setId(referenceId);
@@ -190,8 +189,8 @@
         this.references.add(ref);
 
         // add the Element of the Reference object to the Manifest/SignedInfo
-        this.constructionElement.appendChild(ref.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(ref);
+        addReturnToSelf();
     }
 
     /**
@@ -221,11 +220,11 @@
     }
 
     /**
-     * Return the <it>i</it><sup>th</sup> reference. Valid <code>i</code>
-     * values are 0 to <code>{link@ getSize}-1</code>.
+     * Return the <i>i</i><sup>th</sup> reference. Valid {@code i}
+     * values are 0 to {@code {link@ getSize}-1}.
      *
      * @param i Index of the requested {@link Reference}
-     * @return the <it>i</it><sup>th</sup> reference
+     * @return the <i>i</i><sup>th</sup> reference
      * @throws XMLSecurityException
      */
     public Reference item(int i) throws XMLSecurityException {
@@ -241,24 +240,23 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
+     * @param Id the {@code Id} attribute in {@code ds:Manifest}
      */
     public void setId(String Id) {
         if (Id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, Id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute in <code>ds:Manifest</code>
+     * @return the {@code Id} attribute in {@code ds:Manifest}
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
@@ -267,8 +265,8 @@
      *
      * <p>This step loops through all {@link Reference}s and does verify the hash
      * values. If one or more verifications fail, the method returns
-     * <code>false</code>. If <i>all</i> verifications are successful,
-     * it returns <code>true</code>. The results of the individual reference
+     * {@code false}. If <i>all</i> verifications are successful,
+     * it returns {@code true}. The results of the individual reference
      * validations are available by using the {@link #getVerificationResult(int)} method
      *
      * @return true if all References verify, false if one or more do not verify.
@@ -291,8 +289,8 @@
      *
      * <p>This step loops through all {@link Reference}s and does verify the hash
      * values. If one or more verifications fail, the method returns
-     * <code>false</code>. If <i>all</i> verifications are successful,
-     * it returns <code>true</code>. The results of the individual reference
+     * {@code false}. If <i>all</i> verifications are successful,
+     * it returns {@code true}. The results of the individual reference
      * validations are available by using the {@link #getVerificationResult(int)} method
      *
      * @param followManifests
@@ -310,16 +308,14 @@
         if (referencesEl == null) {
             this.referencesEl =
                 XMLUtils.selectDsNodes(
-                    this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE
+                    getFirstChild(), Constants._TAG_REFERENCE
                 );
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References");
-            log.log(java.util.logging.Level.FINE, "I am " + (followManifests
-                ? "" : "not") + " requested to follow nested Manifests");
-        }
+        LOG.debug("verify {} References", referencesEl.length);
+        LOG.debug("I am {} requested to follow nested Manifests", (followManifests
+            ? "" : "not"));
         if (referencesEl.length == 0) {
-            throw new XMLSecurityException("empty");
+            throw new XMLSecurityException("empty", new Object[]{"References are empty"});
         }
         if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) {
             Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT };
@@ -344,15 +340,11 @@
                 if (!currentRefVerified) {
                     verify = false;
                 }
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType());
-                }
+                LOG.debug("The Reference has Type {}", currentRef.getType());
 
                 // was verification successful till now and do we want to verify the Manifest?
                 if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
-                    }
+                    LOG.debug("We have to follow a nested Manifest");
 
                     try {
                         XMLSignatureInput signedManifestNodes =
@@ -361,10 +353,10 @@
                         Manifest referencedManifest = null;
                         Iterator<Node> nlIterator = nl.iterator();
 
-                        findManifest: while (nlIterator.hasNext()) {
+                        while (nlIterator.hasNext()) {
                             Node n = nlIterator.next();
 
-                            if ((n.getNodeType() == Node.ELEMENT_NODE)
+                            if (n.getNodeType() == Node.ELEMENT_NODE
                                 && ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS)
                                 && ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST)
                             ) {
@@ -373,11 +365,9 @@
                                         new Manifest(
                                              (Element)n, signedManifestNodes.getSourceURI(), secureValidation
                                         );
-                                    break findManifest;
+                                    break;
                                 } catch (XMLSecurityException ex) {
-                                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                        log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-                                    }
+                                    LOG.debug(ex.getMessage(), ex);
                                     // Hm, seems not to be a ds:Manifest
                                 }
                             }
@@ -386,7 +376,8 @@
                         if (referencedManifest == null) {
                             // The Reference stated that it points to a ds:Manifest
                             // but we did not find a ds:Manifest in the signed area
-                            throw new MissingResourceFailureException("empty", currentRef);
+                            throw new MissingResourceFailureException(currentRef, "empty",
+                                                                      new Object[]{"No Manifest found"});
                         }
 
                         referencedManifest.perManifestResolvers = this.perManifestResolvers;
@@ -398,25 +389,23 @@
                         if (!referencedManifestValid) {
                             verify = false;
 
-                            log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)");
+                            LOG.warn("The nested Manifest was invalid (bad)");
                         } else {
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)");
-                            }
+                            LOG.debug("The nested Manifest was valid (good)");
                         }
                     } catch (IOException ex) {
-                        throw new ReferenceNotInitializedException("empty", ex);
+                        throw new ReferenceNotInitializedException(ex);
                     } catch (ParserConfigurationException ex) {
-                        throw new ReferenceNotInitializedException("empty", ex);
+                        throw new ReferenceNotInitializedException(ex);
                     } catch (SAXException ex) {
-                        throw new ReferenceNotInitializedException("empty", ex);
+                        throw new ReferenceNotInitializedException(ex);
                     }
                 }
             } catch (ReferenceNotInitializedException ex) {
                 Object exArgs[] = { currentRef.getURI() };
 
                 throw new MissingResourceFailureException(
-                    "signature.Verification.Reference.NoInput", exArgs, ex, currentRef
+                    ex, currentRef, "signature.Verification.Reference.NoInput", exArgs
                 );
             }
         }
@@ -448,21 +437,21 @@
      * @throws XMLSecurityException
      */
     public boolean getVerificationResult(int index) throws XMLSecurityException {
-        if ((index < 0) || (index > this.getLength() - 1)) {
+        if (index < 0 || index > this.getLength() - 1) {
             Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) };
             Exception e =
                 new IndexOutOfBoundsException(
                     I18n.translate("signature.Verification.IndexOutOfBounds", exArgs)
                 );
 
-            throw new XMLSecurityException("generic.EmptyMessage", e);
+            throw new XMLSecurityException(e);
         }
 
         if (this.verificationResults == null) {
             try {
                 this.verifyReferences();
             } catch (Exception ex) {
-                throw new XMLSecurityException("generic.EmptyMessage", ex);
+                throw new XMLSecurityException(ex);
             }
         }
 
@@ -470,8 +459,8 @@
     }
 
     /**
-     * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
-     * in <code>reference</code> element
+     * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute
+     * in {@code reference} element
      *
      * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of
      * {@link ResourceResolverSpi} for retrieving resource.
@@ -481,14 +470,14 @@
             return;
         }
         if (perManifestResolvers == null) {
-            perManifestResolvers = new ArrayList<ResourceResolver>();
+            perManifestResolvers = new ArrayList<>();
         }
         this.perManifestResolvers.add(resolver);
     }
 
     /**
-     * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
-     * in <code>reference</code> element
+     * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute
+     * in {@code reference} element
      *
      * @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for
      * retrieving the resource.
@@ -498,7 +487,7 @@
             return;
         }
         if (perManifestResolvers == null) {
-            perManifestResolvers = new ArrayList<ResourceResolver>();
+            perManifestResolvers = new ArrayList<>();
         }
         perManifestResolvers.add(new ResourceResolver(resolverSpi));
     }
@@ -528,7 +517,7 @@
      */
     public void setResolverProperty(String key, String value) {
         if (resolverProperties == null) {
-            resolverProperties = new HashMap<String, String>(10);
+            resolverProperties = new HashMap<>(10);
         }
         this.resolverProperties.put(key, value);
     }
@@ -555,13 +544,13 @@
         try {
             return this.getReferencedContentAfterTransformsItem(i).getBytes();
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (CanonicalizationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -601,9 +590,13 @@
     /**
      * Method getBaseLocalName
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String getBaseLocalName() {
         return Constants._TAG_MANIFEST;
     }
+
+    public boolean isSecureValidation() {
+        return secureValidation;
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,7 +27,6 @@
  * testing the signature fails because of uninitialized
  * {@link com.sun.org.apache.xml.internal.security.signature.Reference}s.
  *
- * @author Christian Geuer-Pollmann
  * @see ReferenceNotInitializedException
  */
 public class MissingResourceFailureException extends XMLSignatureException {
@@ -38,65 +37,89 @@
     private static final long serialVersionUID = 1L;
 
     /** Field uninitializedReference */
-    private Reference uninitializedReference = null;
+    private Reference uninitializedReference;
 
     /**
      * MissingKeyResourceFailureException constructor.
+     * @param reference
      * @param msgID
-     * @param reference
      * @see #getReference
      */
-    public MissingResourceFailureException(String msgID, Reference reference) {
+    public MissingResourceFailureException(Reference reference, String msgID) {
         super(msgID);
 
         this.uninitializedReference = reference;
     }
 
+    @Deprecated
+    public MissingResourceFailureException(String msgID, Reference reference) {
+        this(reference, msgID);
+    }
+
     /**
      * Constructor MissingResourceFailureException
      *
+     * @param reference
      * @param msgID
      * @param exArgs
-     * @param reference
      * @see #getReference
      */
-    public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) {
+    public MissingResourceFailureException(Reference reference, String msgID, Object exArgs[]) {
         super(msgID, exArgs);
 
         this.uninitializedReference = reference;
     }
 
-    /**
-     * Constructor MissingResourceFailureException
-     *
-     * @param msgID
-     * @param originalException
-     * @param reference
-     * @see #getReference
-     */
-    public MissingResourceFailureException(
-        String msgID, Exception originalException, Reference reference
-    ) {
-        super(msgID, originalException);
-
-        this.uninitializedReference = reference;
+    @Deprecated
+    public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) {
+        this(reference, msgID, exArgs);
     }
 
     /**
      * Constructor MissingResourceFailureException
      *
-     * @param msgID
-     * @param exArgs
      * @param originalException
      * @param reference
+     * @param msgID
      * @see #getReference
      */
     public MissingResourceFailureException(
+        Exception originalException, Reference reference, String msgID
+    ) {
+        super(originalException, msgID);
+
+        this.uninitializedReference = reference;
+    }
+
+    @Deprecated
+    public MissingResourceFailureException(
+        String msgID, Exception originalException, Reference reference
+    ) {
+        this(originalException, reference, msgID);
+    }
+
+    /**
+     * Constructor MissingResourceFailureException
+     *
+     * @param originalException
+     * @param reference
+     * @param msgID
+     * @param exArgs
+     * @see #getReference
+     */
+    public MissingResourceFailureException(
+        Exception originalException, Reference reference, String msgID, Object exArgs[]
+    ) {
+        super(originalException, msgID, exArgs);
+
+        this.uninitializedReference = reference;
+    }
+
+    @Deprecated
+    public MissingResourceFailureException(
         String msgID, Object exArgs[], Exception originalException, Reference reference
     ) {
-        super(msgID, exArgs, originalException);
-
-        this.uninitializedReference = reference;
+        this(originalException, reference, msgID, exArgs);
     }
 
     /**
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,8 +33,8 @@
      * Tells if a node must be output in c14n.
      * @param n
      * @return 1 if the node should be output.
-     *         0 if node must not be output,
-     *         -1 if the node and all it's child must not be output.
+     *            0 if node must not be output,
+     *           -1 if the node and all it's child must not be output.
      *
      */
     int isNodeInclude(Node n);
@@ -47,8 +47,8 @@
      * @param n
      * @param level the relative level in the tree
      * @return 1 if the node should be output.
-     *         0 if node must not be output,
-     *         -1 if the node and all it's child must not be output.
+     *            0 if node must not be output,
+     *           -1 if the node and all it's child must not be output.
      */
     int isNodeIncludeDO(Node n, int level);
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,10 +31,9 @@
 
 
 /**
- * Handles <code>&lt;ds:Object&gt;</code> elements
- * <code>Object<code> {@link Element} supply facility which can contain any kind data
+ * Handles {@code &lt;ds:Object&gt;} elements
+ * {@code Object} {@link Element} supply facility which can contain any kind data
  *
- * @author Christian Geuer-Pollmann
  * $todo$ if we remove childen, the boolean values are not updated
  */
 public class ObjectContainer extends SignatureElementProxy {
@@ -42,7 +41,7 @@
     /**
      * Constructs {@link ObjectContainer}
      *
-     * @param doc the {@link Document} in which <code>Object</code> element is placed
+     * @param doc the {@link Document} in which {@code Object} element is placed
      */
     public ObjectContainer(Document doc) {
         super(doc);
@@ -51,7 +50,7 @@
     /**
      * Constructs {@link ObjectContainer} from {@link Element}
      *
-     * @param element is <code>Object</code> element
+     * @param element is {@code Object} element
      * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
      */
@@ -60,64 +59,63 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id <code>Id</code> attribute
+     * @param Id {@code Id} attribute
      */
     public void setId(String Id) {
         if (Id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, Id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
-     * Sets the <code>MimeType</code> attribute
+     * Sets the {@code MimeType} attribute
      *
-     * @param MimeType the <code>MimeType</code> attribute
+     * @param MimeType the {@code MimeType} attribute
      */
     public void setMimeType(String MimeType) {
         if (MimeType != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType);
+            setLocalAttribute(Constants._ATT_MIMETYPE, MimeType);
         }
     }
 
     /**
-     * Returns the <code>MimeType</code> attribute
+     * Returns the {@code MimeType} attribute
      *
-     * @return the <code>MimeType</code> attribute
+     * @return the {@code MimeType} attribute
      */
     public String getMimeType() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
+        return getLocalAttribute(Constants._ATT_MIMETYPE);
     }
 
     /**
-     * Sets the <code>Encoding</code> attribute
+     * Sets the {@code Encoding} attribute
      *
-     * @param Encoding the <code>Encoding</code> attribute
+     * @param Encoding the {@code Encoding} attribute
      */
     public void setEncoding(String Encoding) {
         if (Encoding != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding);
+            setLocalAttribute(Constants._ATT_ENCODING, Encoding);
         }
     }
 
     /**
-     * Returns the <code>Encoding</code> attribute
+     * Returns the {@code Encoding} attribute
      *
-     * @return the <code>Encoding</code> attribute
+     * @return the {@code Encoding} attribute
      */
     public String getEncoding() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
+        return getLocalAttribute(Constants._ATT_ENCODING);
     }
 
     /**
@@ -127,10 +125,11 @@
      * @return the new node in the tree.
      */
     public Node appendChild(Node node) {
-        return this.constructionElement.appendChild(node);
+        appendSelf(node);
+        return node;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_OBJECT;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,14 +26,15 @@
 import java.io.OutputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.Base64;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
 
+import com.sun.org.apache.xml.internal.security.algorithms.Algorithm;
 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData;
 import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData;
@@ -44,7 +45,6 @@
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -59,11 +59,11 @@
 import org.w3c.dom.Text;
 
 /**
- * Handles <code>&lt;ds:Reference&gt;</code> elements.
+ * Handles {@code &lt;ds:Reference&gt;} elements.
  *
  * This includes:
  *
- * Constructs a <CODE>ds:Reference</CODE> from an {@link org.w3c.dom.Element}.
+ * Construct a {@code ds:Reference} from an {@link org.w3c.dom.Element}.
  *
  * <p>Create a new reference</p>
  * <pre>
@@ -100,7 +100,6 @@
  *  &lt;/complexType&gt;
  * </pre>
  *
- * @author Christian Geuer-Pollmann
  * @see ObjectContainer
  * @see Manifest
  */
@@ -124,16 +123,12 @@
      * will be added if necessary when generating the signature. See section
      * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
      */
-    private static boolean useC14N11 = (
-        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
-            public Boolean run() {
-                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
-            }
-        })).booleanValue();
+    private static boolean useC14N11 =
+        AccessController.doPrivileged((PrivilegedAction<Boolean>)
+            () -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Reference.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(Reference.class);
 
     private Manifest manifest;
     private XMLSignatureInput transformsOutput;
@@ -149,7 +144,7 @@
     /**
      * Constructor Reference
      *
-     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+     * @param doc the {@link Document} in which {@code XMLsignature} is placed
      * @param baseURI the URI of the resource where the XML instance will be stored
      * @param referenceURI URI indicate where is data which will digested
      * @param manifest
@@ -165,7 +160,7 @@
     ) throws XMLSignatureException {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
         this.baseURI = baseURI;
         this.manifest = manifest;
@@ -178,29 +173,39 @@
         // this.manifest.appendChild(this.doc.createTextNode("\n"));
 
         if (transforms != null) {
-            this.transforms=transforms;
-            this.constructionElement.appendChild(transforms.getElement());
-            XMLUtils.addReturnToElement(this.constructionElement);
+            this.transforms = transforms;
+            appendSelf(transforms);
+            addReturnToSelf();
         }
-        MessageDigestAlgorithm mda =
-            MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
+
+        // Create DigestMethod Element without actually instantiating a MessageDigest Object
+        Algorithm digestAlgorithm = new Algorithm(getDocument(), messageDigestAlgorithm) {
+            public String getBaseNamespace() {
+                return Constants.SignatureSpecNS;
+            }
 
-        digestMethodElem = mda.getElement();
-        this.constructionElement.appendChild(digestMethodElem);
-        XMLUtils.addReturnToElement(this.constructionElement);
+            public String getBaseLocalName() {
+                return Constants._TAG_DIGESTMETHOD;
+            }
+        };
+
+        digestMethodElem = digestAlgorithm.getElement();
+
+        appendSelf(digestMethodElem);
+        addReturnToSelf();
 
         digestValueElement =
-            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
+            XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_DIGESTVALUE);
 
-        this.constructionElement.appendChild(digestValueElement);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(digestValueElement);
+        addReturnToSelf();
     }
 
 
     /**
      * Build a {@link Reference} from an {@link Element}
      *
-     * @param element <code>Reference</code> element
+     * @param element {@code Reference} element
      * @param baseURI the URI of the resource where the XML instance was stored
      * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
      * We need this because the Manifest has the individual {@link ResourceResolver}s which have
@@ -208,13 +213,13 @@
      * @throws XMLSecurityException
      */
     protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
-        this(element, baseURI, manifest, false);
+        this(element, baseURI, manifest, true);
     }
 
     /**
      * Build a {@link Reference} from an {@link Element}
      *
-     * @param element <code>Reference</code> element
+     * @param element {@code Reference} element
      * @param baseURI the URI of the resource where the XML instance was stored
      * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
      * @param secureValidation whether secure validation is enabled or not
@@ -228,7 +233,8 @@
         this.secureValidation = secureValidation;
         this.baseURI = baseURI;
         Element el = XMLUtils.getNextElement(element.getFirstChild());
-        if (Constants._TAG_TRANSFORMS.equals(el.getLocalName())
+
+        if (el != null && Constants._TAG_TRANSFORMS.equals(el.getLocalName())
             && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
             transforms = new Transforms(el, this.baseURI);
             transforms.setSecureValidation(secureValidation);
@@ -239,8 +245,16 @@
             }
             el = XMLUtils.getNextElement(el.getNextSibling());
         }
+
         digestMethodElem = el;
+        if (digestMethodElem == null) {
+            throw new XMLSecurityException("signature.Reference.NoDigestMethod");
+        }
+
         digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+        if (digestValueElement == null) {
+            throw new XMLSecurityException("signature.Reference.NoDigestValue");
+        }
         this.manifest = manifest;
     }
 
@@ -259,7 +273,7 @@
 
         String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
 
-        if (uri == null) {
+        if ("".equals(uri)) {
             return null;
         }
 
@@ -269,82 +283,81 @@
             throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
         }
 
-        return MessageDigestAlgorithm.getInstance(this.doc, uri);
+        return MessageDigestAlgorithm.getInstance(getDocument(), uri);
     }
 
     /**
-     * Sets the <code>URI</code> of this <code>Reference</code> element
+     * Sets the {@code URI} of this {@code Reference} element
      *
-     * @param uri the <code>URI</code> of this <code>Reference</code> element
+     * @param uri the {@code URI} of this {@code Reference} element
      */
     public void setURI(String uri) {
         if (uri != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+            setLocalAttribute(Constants._ATT_URI, uri);
         }
     }
 
     /**
-     * Returns the <code>URI</code> of this <code>Reference</code> element
+     * Returns the {@code URI} of this {@code Reference} element
      *
-     * @return URI the <code>URI</code> of this <code>Reference</code> element
+     * @return URI the {@code URI} of this {@code Reference} element
      */
     public String getURI() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+        return getLocalAttribute(Constants._ATT_URI);
     }
 
     /**
-     * Sets the <code>Id</code> attribute of this <code>Reference</code> element
+     * Sets the {@code Id} attribute of this {@code Reference} element
      *
-     * @param id the <code>Id</code> attribute of this <code>Reference</code> element
+     * @param id the {@code Id} attribute of this {@code Reference} element
      */
     public void setId(String id) {
         if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute of this <code>Reference</code> element
+     * Returns the {@code Id} attribute of this {@code Reference} element
      *
-     * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
+     * @return Id the {@code Id} attribute of this {@code Reference} element
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
-     * Sets the <code>type</code> atttibute of the Reference indicate whether an
-     * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+     * Sets the {@code type} atttibute of the Reference indicate whether an
+     * {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
      * element.
      *
-     * @param type the <code>type</code> attribute of the Reference
+     * @param type the {@code type} attribute of the Reference
      */
     public void setType(String type) {
         if (type != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+            setLocalAttribute(Constants._ATT_TYPE, type);
         }
     }
 
     /**
-     * Return the <code>type</code> atttibute of the Reference indicate whether an
-     * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+     * Return the {@code type} atttibute of the Reference indicate whether an
+     * {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
      * element
      *
-     * @return the <code>type</code> attribute of the Reference
+     * @return the {@code type} attribute of the Reference
      */
     public String getType() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+        return getLocalAttribute(Constants._ATT_TYPE);
     }
 
     /**
      * Method isReferenceToObject
      *
-     * This returns true if the <CODE>Type</CODE> attribute of the
-     * <CODE>Reference</CODE> element points to a <CODE>#Object</CODE> element
+     * This returns true if the {@code Type} attribute of the
+     * {@code Reference} element points to a {@code #Object} element
      *
      * @return true if the Reference type indicates that this Reference points to an
-     * <code>Object</code>
+     * {@code Object}
      */
     public boolean typeIsReferenceToObject() {
         if (Reference.OBJECT_URI.equals(this.getType())) {
@@ -357,8 +370,8 @@
     /**
      * Method isReferenceToManifest
      *
-     * This returns true if the <CODE>Type</CODE> attribute of the
-     * <CODE>Reference</CODE> element points to a <CODE>#Manifest</CODE> element
+     * This returns true if the {@code Type} attribute of the
+     * {@code Reference} element points to a {@code #Manifest} element
      *
      * @return true if the Reference type indicates that this Reference points to a
      * {@link Manifest}
@@ -383,8 +396,8 @@
             n = n.getNextSibling();
         }
 
-        String base64codedValue = Base64.encode(digestValue);
-        Text t = this.doc.createTextNode(base64codedValue);
+        String base64codedValue = Base64.getMimeEncoder().encodeToString(digestValue);
+        Text t = createText(base64codedValue);
 
         digestValueElement.appendChild(t);
     }
@@ -410,7 +423,7 @@
         throws ReferenceNotInitializedException {
         try {
             Attr uriAttr =
-                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+                getElement().getAttributeNodeNS(null, Constants._ATT_URI);
 
             ResourceResolver resolver =
                 ResourceResolver.getInstance(
@@ -420,7 +433,7 @@
 
             return resolver.resolve(uriAttr, this.baseURI, secureValidation);
         }  catch (ResourceResolverException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
+            throw new ReferenceNotInitializedException(ex);
         }
     }
 
@@ -442,15 +455,15 @@
 
             return output;
         } catch (ResourceResolverException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (CanonicalizationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (TransformationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -483,35 +496,37 @@
             Transforms transforms = this.getTransforms();
 
             if (transforms != null) {
-                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                for (int i = 0; i < transforms.getLength(); i++) {
                     Transform t = transforms.item(i);
                     String uri = t.getURI();
 
                     if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
                         || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)
                         || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS)
-                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
-                        break doTransforms;
+                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N11_WITH_COMMENTS)) {
+                        break;
                     }
 
                     output = t.performTransform(output, null);
                 }
 
-            output.setSourceURI(input.getSourceURI());
+                output.setSourceURI(input.getSourceURI());
             }
             return output;
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (ResourceResolverException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (CanonicalizationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (TransformationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -528,23 +543,23 @@
             Transform c14nTransform = null;
 
             if (transforms != null) {
-                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                for (int i = 0; i < transforms.getLength(); i++) {
                     Transform t = transforms.item(i);
                     String uri = t.getURI();
 
                     if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
                         || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
                         c14nTransform = t;
-                        break doTransforms;
+                        break;
                     }
                 }
             }
 
-            Set<String> inclusiveNamespaces = new HashSet<String>();
+            Set<String> inclusiveNamespaces = new HashSet<>();
             if (c14nTransform != null
-                && (c14nTransform.length(
+                && c14nTransform.length(
                     InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
+                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1) {
 
                 // there is one InclusiveNamespaces element
                 InclusiveNamespaces in =
@@ -562,11 +577,11 @@
 
             return nodes.getHTMLRepresentation(inclusiveNamespaces);
         } catch (TransformationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidTransformException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -588,7 +603,7 @@
 
     /**
      * This method returns the {@link XMLSignatureInput} which is referenced by the
-     * <CODE>URI</CODE> Attribute.
+     * {@code URI} Attribute.
      * @param os where to write the transformation can be null.
      * @return the element to digest
      *
@@ -605,7 +620,7 @@
             this.transformsOutput = output;
             return output;
         } catch (XMLSecurityException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
+            throw new ReferenceNotInitializedException(ex);
         }
     }
 
@@ -622,14 +637,17 @@
 
                             Iterator<Node> sIterator = s.iterator();
 
+                            @Override
                             public boolean hasNext() {
                                 return sIterator.hasNext();
                             }
 
+                            @Override
                             public Node next() {
                                 return sIterator.next();
                             }
 
+                            @Override
                             public void remove() {
                                 throw new UnsupportedOperationException();
                             }
@@ -637,8 +655,8 @@
                     }
                 };
             } catch (Exception e) {
-                // log a warning
-                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
+                // LOG a warning
+                LOG.warn("cannot cache dereferenced data: " + e);
             }
         } else if (input.isElement()) {
             referenceData = new ReferenceSubTreeData
@@ -649,8 +667,8 @@
                     (input.getOctetStream(), input.getSourceURI(),
                         input.getMIMEType());
             } catch (IOException ioe) {
-                // log a warning
-                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
+                // LOG a warning
+                LOG.warn("cannot cache dereferenced data: " + ioe);
             }
         }
     }
@@ -683,9 +701,9 @@
             XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
             return output.getBytes();
         } catch (IOException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
+            throw new ReferenceNotInitializedException(ex);
         } catch (CanonicalizationException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
+            throw new ReferenceNotInitializedException(ex);
         }
     }
 
@@ -700,22 +718,25 @@
      */
     private byte[] calculateDigest(boolean validating)
         throws ReferenceNotInitializedException, XMLSignatureException {
-        OutputStream os = null;
-        try {
-            MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+        XMLSignatureInput input = this.getContentsBeforeTransformation();
+        if (input.isPreCalculatedDigest()) {
+            return getPreCalculatedDigest(input);
+        }
 
-            mda.reset();
-            DigesterOutputStream diOs = new DigesterOutputStream(mda);
-            os = new UnsyncBufferedOutputStream(diOs);
+        MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+        mda.reset();
+
+        try (DigesterOutputStream diOs = new DigesterOutputStream(mda);
+            OutputStream os = new UnsyncBufferedOutputStream(diOs)) {
             XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
             // if signing and c14n11 property == true explicitly add
             // C14N11 transform if needed
             if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
                 && !output.isOctetStream()) {
                 if (transforms == null) {
-                    transforms = new Transforms(this.doc);
+                    transforms = new Transforms(getDocument());
                     transforms.setSecureValidation(secureValidation);
-                    this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
+                    getElement().insertBefore(transforms.getElement(), digestMethodElem);
                 }
                 transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
                 output.updateOutputStream(os, true);
@@ -733,28 +754,34 @@
 
             return diOs.getDigestValue();
         } catch (XMLSecurityException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
+            throw new ReferenceNotInitializedException(ex);
         } catch (IOException ex) {
-            throw new ReferenceNotInitializedException("empty", ex);
-        } finally {
-            if (os != null) {
-                try {
-                    os.close();
-                } catch (IOException ex) {
-                    throw new ReferenceNotInitializedException("empty", ex);
-                }
-            }
+            throw new ReferenceNotInitializedException(ex);
         }
     }
 
     /**
+     * Get the pre-calculated digest value from the XMLSignatureInput.
+     *
+     * @param input XMLSignature
+     * @return a pre-calculated digest value.
+     * @throws ReferenceNotInitializedException if there is an error decoding digest value
+     * in Base64. Properly encoded pre-calculated digest value must be set.
+     */
+    private byte[] getPreCalculatedDigest(XMLSignatureInput input)
+            throws ReferenceNotInitializedException {
+        LOG.debug("Verifying element with pre-calculated digest");
+        String preCalculatedDigest = input.getPreCalculatedDigest();
+        return Base64.getMimeDecoder().decode(preCalculatedDigest);
+    }
+
+    /**
      * Returns the digest value.
      *
      * @return the digest value.
-     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
      * @throws XMLSecurityException if the Reference does not contain a DigestValue element
      */
-    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
+    public byte[] getDigestValue() throws XMLSecurityException {
         if (digestValueElement == null) {
             // The required element is not in the XML!
             Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
@@ -762,7 +789,8 @@
                 "signature.Verification.NoSignatureElement", exArgs
             );
         }
-        return Base64.decode(digestValueElement);
+        String content = XMLUtils.getFullTextChildrenFromElement(digestValueElement);
+        return Base64.getMimeDecoder().decode(content);
     }
 
 
@@ -780,13 +808,11 @@
         boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
 
         if (!equal) {
-            log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
-            log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
-            log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
+            LOG.warn("Verification failed for URI \"" + this.getURI() + "\"");
+            LOG.warn("Expected Digest: " + Base64.getMimeEncoder().encodeToString(elemDig));
+            LOG.warn("Actual Digest: " + Base64.getMimeEncoder().encodeToString(calcDig));
         } else {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Verification successful for URI \"" + this.getURI() + "\"");
-            }
+            LOG.debug("Verification successful for URI \"{}\"", this.getURI());
         }
 
         return equal;
@@ -794,7 +820,7 @@
 
     /**
      * Method getBaseLocalName
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String getBaseLocalName() {
         return Constants._TAG_REFERENCE;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,7 +26,6 @@
  * Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
  * because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
  *
- * @author Christian Geuer-Pollmann
  */
 public class ReferenceNotInitializedException extends XMLSignatureException {
 
@@ -43,6 +42,10 @@
         super();
     }
 
+    public ReferenceNotInitializedException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor ReferenceNotInitializedException
      *
@@ -65,21 +68,31 @@
     /**
      * Constructor ReferenceNotInitializedException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public ReferenceNotInitializedException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public ReferenceNotInitializedException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor ReferenceNotInitializedException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public ReferenceNotInitializedException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public ReferenceNotInitializedException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,12 +31,11 @@
 import org.w3c.dom.Element;
 
 /**
- * Handles <code>&lt;ds:SignatureProperties&gt;</code> elements
- * This Element holds {@link SignatureProperty} that contian additional information items
+ * Handles {@code &lt;ds:SignatureProperties&gt;} elements
+ * This Element holds {@link SignatureProperty} properties that contain additional information items
  * concerning the generation of the signature.
  * for example, data-time stamp, serial number of cryptographic hardware.
  *
- * @author Christian Geuer-Pollmann
  */
 public class SignatureProperties extends SignatureElementProxy {
 
@@ -48,17 +47,17 @@
     public SignatureProperties(Document doc) {
         super(doc);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
     }
 
     /**
      * Constructs {@link SignatureProperties} from {@link Element}
-     * @param element <code>SignatureProperties</code> element
-     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @param element {@code SignatureProperties} element
+     * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
      */
-    public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public SignatureProperties(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
 
         Attr attr = element.getAttributeNodeNS(null, "Id");
         if (attr != null) {
@@ -68,7 +67,7 @@
         int length = getLength();
         for (int i = 0; i < length; i++) {
             Element propertyElem =
-                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+                XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
             Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
             if (propertyAttr != null) {
                 propertyElem.setIdAttributeNode(propertyAttr, true);
@@ -83,52 +82,51 @@
      */
     public int getLength() {
         Element[] propertyElems =
-            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
+            XMLUtils.selectDsNodes(getElement(), Constants._TAG_SIGNATUREPROPERTY);
 
         return propertyElems.length;
     }
 
     /**
-     * Return the <it>i</it><sup>th</sup> SignatureProperty. Valid <code>i</code>
-     * values are 0 to <code>{link@ getSize}-1</code>.
+     * Return the <i>i</i><sup>th</sup> SignatureProperty. Valid {@code i}
+     * values are 0 to {@code {link@ getSize}-1}.
      *
      * @param i Index of the requested {@link SignatureProperty}
-     * @return the <it>i</it><sup>th</sup> SignatureProperty
+     * @return the <i>i</i><sup>th</sup> SignatureProperty
      * @throws XMLSignatureException
      */
     public SignatureProperty item(int i) throws XMLSignatureException {
         try {
             Element propertyElem =
-                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+                XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
 
             if (propertyElem == null) {
                 return null;
             }
             return new SignatureProperty(propertyElem, this.baseURI);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
-     * @param Id the <code>Id</code> attribute
+     * @param Id the {@code Id} attribute
      */
     public void setId(String Id) {
         if (Id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, Id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
@@ -137,11 +135,11 @@
      * @param sp
      */
     public void addSignatureProperty(SignatureProperty sp) {
-        this.constructionElement.appendChild(sp.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(sp);
+        addReturnToSelf();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_SIGNATUREPROPERTIES;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Tue Jun 19 16:33:07 2018 +0100
@@ -30,19 +30,18 @@
 import org.w3c.dom.Node;
 
 /**
- * Handles <code>&lt;ds:SignatureProperty&gt;</code> elements
+ * Handles {@code &lt;ds:SignatureProperty&gt;} elements
  * Additional information item concerning the generation of the signature(s) can
  * be placed in this Element
  *
- * @author Christian Geuer-Pollmann
  */
 public class SignatureProperty extends SignatureElementProxy {
 
     /**
-     * Constructs{@link SignatureProperty} using specified <code>target</code> attribute
+     * Constructs{@link SignatureProperty} using specified {@code target} attribute
      *
-     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-     * @param target the <code>target</code> attribute references the <code>Signature</code>
+     * @param doc the {@link Document} in which {@code XMLsignature} is placed
+     * @param target the {@code target} attribute references the {@code Signature}
      * element to which the property applies SignatureProperty
      */
     public SignatureProperty(Document doc, String target) {
@@ -50,13 +49,13 @@
     }
 
     /**
-     * Constructs {@link SignatureProperty} using sepcified <code>target</code> attribute and
-     * <code>id</code> attribute
+     * Constructs {@link SignatureProperty} using sepcified {@code target} attribute and
+     * {@code id} attribute
      *
-     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
-     * @param target the <code>target</code> attribute references the <code>Signature</code>
+     * @param doc the {@link Document} in which {@code XMLsignature} is placed
+     * @param target the {@code target} attribute references the {@code Signature}
      *  element to which the property applies
-     * @param id the <code>id</code> will be specified by {@link Reference#getURI} in validation
+     * @param id the {@code id} will be specified by {@link Reference#getURI} in validation
      */
     public SignatureProperty(Document doc, String target, String id) {
         super(doc);
@@ -67,53 +66,52 @@
 
     /**
      * Constructs a {@link SignatureProperty} from an {@link Element}
-     * @param element <code>SignatureProperty</code> element
-     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @param element {@code SignatureProperty} element
+     * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
      */
-    public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public SignatureProperty(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
     }
 
     /**
-     *   Sets the <code>id</code> attribute
+     *   Sets the {@code id} attribute
      *
-     *   @param id the <code>id</code> attribute
+     *   @param id the {@code id} attribute
      */
     public void setId(String id) {
         if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, id);
         }
     }
 
     /**
-     * Returns the <code>id</code> attribute
+     * Returns the {@code id} attribute
      *
-     * @return the <code>id</code> attribute
+     * @return the {@code id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
-     * Sets the <code>target</code> attribute
+     * Sets the {@code target} attribute
      *
-     * @param target the <code>target</code> attribute
+     * @param target the {@code target} attribute
      */
     public void setTarget(String target) {
         if (target != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+            setLocalAttribute(Constants._ATT_TARGET, target);
         }
     }
 
     /**
-     * Returns the <code>target</code> attribute
+     * Returns the {@code target} attribute
      *
-     * @return the <code>target</code> attribute
+     * @return the {@code target} attribute
      */
     public String getTarget() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+        return getLocalAttribute(Constants._ATT_TARGET);
     }
 
     /**
@@ -123,10 +121,11 @@
      * @return the node in this element.
      */
     public Node appendChild(Node node) {
-        return this.constructionElement.appendChild(node);
+        appendSelf(node);
+        return node;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_SIGNATUREPROPERTY;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,10 +24,11 @@
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
+
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
-import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
@@ -35,28 +36,27 @@
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.xml.sax.SAXException;
 
 /**
- * Handles <code>&lt;ds:SignedInfo&gt;</code> elements
- * This <code>SignedInfo<code> element includes the canonicalization algorithm,
+ * Handles {@code &lt;ds:SignedInfo&gt;} elements
+ * This {@code SignedInfo} element includes the canonicalization algorithm,
  * a signature algorithm, and one or more references.
  *
- * @author Christian Geuer-Pollmann
  */
 public class SignedInfo extends Manifest {
 
     /** Field signatureAlgorithm */
-    private SignatureAlgorithm signatureAlgorithm = null;
+    private SignatureAlgorithm signatureAlgorithm;
 
     /** Field c14nizedBytes           */
-    private byte[] c14nizedBytes = null;
+    private byte[] c14nizedBytes;
 
     private Element c14nMethod;
     private Element signatureMethod;
@@ -65,7 +65,7 @@
      * Overwrites {@link Manifest#addDocument} because it creates another
      * Element.
      *
-     * @param doc the {@link Document} in which <code>XMLsignature</code> will
+     * @param doc the {@link Document} in which {@code XMLsignature} will
      *    be placed
      * @throws XMLSecurityException
      */
@@ -78,7 +78,7 @@
      * Constructs {@link SignedInfo} using given Canonicalization algorithm and
      * Signature algorithm.
      *
-     * @param doc <code>SignedInfo</code> is placed in this document
+     * @param doc {@code SignedInfo} is placed in this document
      * @param signatureMethodURI URI representation of the Digest and
      *    Signature algorithm
      * @param canonicalizationMethodURI URI representation of the
@@ -94,7 +94,7 @@
     /**
      * Constructor SignedInfo
      *
-     * @param doc <code>SignedInfo</code> is placed in this document
+     * @param doc {@code SignedInfo} is placed in this document
      * @param signatureMethodURI URI representation of the Digest and
      *    Signature algorithm
      * @param hMACOutputLength
@@ -109,22 +109,22 @@
         super(doc);
 
         c14nMethod =
-            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
+            XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_CANONICALIZATIONMETHOD);
 
         c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
-        this.constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(c14nMethod);
+        addReturnToSelf();
 
         if (hMACOutputLength > 0) {
             this.signatureAlgorithm =
-                new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
+                new SignatureAlgorithm(getDocument(), signatureMethodURI, hMACOutputLength);
         } else {
-            this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
+            this.signatureAlgorithm = new SignatureAlgorithm(getDocument(), signatureMethodURI);
         }
 
         signatureMethod = this.signatureAlgorithm.getElement();
-        this.constructionElement.appendChild(signatureMethod);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(signatureMethod);
+        addReturnToSelf();
     }
 
     /**
@@ -139,22 +139,22 @@
         super(doc);
         // Check this?
         this.c14nMethod = canonicalizationMethodElem;
-        this.constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(c14nMethod);
+        addReturnToSelf();
 
         this.signatureAlgorithm =
             new SignatureAlgorithm(signatureMethodElem, null);
 
         signatureMethod = this.signatureAlgorithm.getElement();
-        this.constructionElement.appendChild(signatureMethod);
+        appendSelf(signatureMethod);
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
     }
 
     /**
      * Build a {@link SignedInfo} from an {@link Element}
      *
-     * @param element <code>SignedInfo</code>
+     * @param element {@code SignedInfo}
      * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
      * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
@@ -163,13 +163,13 @@
      * Answer</A>
      */
     public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
-        this(element, baseURI, false);
+        this(element, baseURI, true);
     }
 
     /**
      * Build a {@link SignedInfo} from an {@link Element}
      *
-     * @param element <code>SignedInfo</code>
+     * @param element {@code SignedInfo}
      * @param baseURI the URI of the resource where the XML instance was stored
      * @param secureValidation whether secure validation is enabled or not
      * @throws XMLSecurityException
@@ -182,7 +182,7 @@
         Element element, String baseURI, boolean secureValidation
     ) throws XMLSecurityException {
         // Parse the Reference children and Id attribute in the Manifest
-        super(reparseSignedInfoElem(element), baseURI, secureValidation);
+        super(reparseSignedInfoElem(element, secureValidation), baseURI, secureValidation);
 
         c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
         signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
@@ -190,7 +190,7 @@
             new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
     }
 
-    private static Element reparseSignedInfoElem(Element element)
+    private static Element reparseSignedInfoElem(Element element, boolean secureValidation)
         throws XMLSecurityException {
         /*
          * If a custom canonicalizationMethod is used, canonicalize
@@ -212,27 +212,24 @@
             try {
                 Canonicalizer c14nizer =
                     Canonicalizer.getInstance(c14nMethodURI);
+                c14nizer.setSecureValidation(secureValidation);
 
                 byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
-                javax.xml.parsers.DocumentBuilderFactory dbf =
-                    javax.xml.parsers.DocumentBuilderFactory.newInstance();
-                dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-                javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
-                Document newdoc =
-                    db.parse(new ByteArrayInputStream(c14nizedBytes));
-                Node imported =
-                    element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
-
-                element.getParentNode().replaceChild(imported, element);
-
-                return (Element) imported;
+                javax.xml.parsers.DocumentBuilder db =
+                    XMLUtils.createDocumentBuilder(false, secureValidation);
+                try (InputStream is = new ByteArrayInputStream(c14nizedBytes)) {
+                    Document newdoc = db.parse(is);
+                    Node imported = element.getOwnerDocument().importNode(
+                            newdoc.getDocumentElement(), true);
+                    element.getParentNode().replaceChild(imported, element);
+                    return (Element) imported;
+                }
             } catch (ParserConfigurationException ex) {
-                throw new XMLSecurityException("empty", ex);
+                throw new XMLSecurityException(ex);
             } catch (IOException ex) {
-                throw new XMLSecurityException("empty", ex);
+                throw new XMLSecurityException(ex);
             } catch (SAXException ex) {
-                throw new XMLSecurityException("empty", ex);
+                throw new XMLSecurityException(ex);
             }
         }
         return element;
@@ -253,7 +250,7 @@
     /**
      * Tests core validation process
      *
-     * @param followManifests defines whether the verification process has to verify referenced <CODE>ds:Manifest</CODE>s, too
+     * @param followManifests defines whether the verification process has to verify referenced {@code ds:Manifest}s, too
      * @return true if verification was successful
      * @throws MissingResourceFailureException
      * @throws XMLSecurityException
@@ -266,7 +263,7 @@
     /**
      * Returns getCanonicalizedOctetStream
      *
-     * @return the canonicalization result octet stream of <code>SignedInfo</code> element
+     * @return the canonicalization result octet stream of {@code SignedInfo} element
      * @throws CanonicalizationException
      * @throws InvalidCanonicalizerException
      * @throws XMLSecurityException
@@ -276,9 +273,14 @@
         if (this.c14nizedBytes == null) {
             Canonicalizer c14nizer =
                 Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+            c14nizer.setSecureValidation(isSecureValidation());
 
-            this.c14nizedBytes =
-                c14nizer.canonicalizeSubtree(this.constructionElement);
+            String inclusiveNamespaces = this.getInclusiveNamespaces();
+            if (inclusiveNamespaces == null) {
+                this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement());
+            } else {
+                this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces);
+            }
         }
 
         // make defensive copy
@@ -297,13 +299,14 @@
         if (this.c14nizedBytes == null) {
             Canonicalizer c14nizer =
                 Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+            c14nizer.setSecureValidation(isSecureValidation());
             c14nizer.setWriter(os);
             String inclusiveNamespaces = this.getInclusiveNamespaces();
 
             if (inclusiveNamespaces == null) {
-                c14nizer.canonicalizeSubtree(this.constructionElement);
+                c14nizer.canonicalizeSubtree(getElement());
             } else {
-                c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+                c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces);
             }
         } else {
             try {
@@ -358,13 +361,13 @@
         return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
     }
 
-    protected SignatureAlgorithm getSignatureAlgorithm() {
+    public SignatureAlgorithm getSignatureAlgorithm() {
         return signatureAlgorithm;
     }
 
     /**
      * Method getBaseLocalName
-     * @inheritDoc
+     * {@inheritDoc}
      *
      */
     public String getBaseLocalName() {
@@ -372,7 +375,7 @@
     }
 
     public String getInclusiveNamespaces() {
-        String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        String c14nMethodURI = getCanonicalizationMethodURI();
         if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
             c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
             return null;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,6 +27,7 @@
 import java.security.Key;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
+import java.util.Base64;
 
 import javax.crypto.SecretKey;
 
@@ -34,12 +35,10 @@
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
 import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -52,11 +51,10 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
 /**
- * Handles <code>&lt;ds:Signature&gt;</code> elements.
+ * Handles {@code &lt;ds:Signature&gt;} elements.
  * This is the main class that deals with creating and verifying signatures.
  *
  * <p>There are 2 types of constructors for this class. The ones that take a
@@ -105,6 +103,10 @@
     public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 =
         Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160";
 
+    /** Signature - Optional RSAwithSHA224 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA224 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-sha224";
+
     /** Signature - Optional RSAwithSHA256 */
     public static final String ALGO_ID_SIGNATURE_RSA_SHA256 =
         Constants.MoreAlgorithmsSpecNS + "rsa-sha256";
@@ -117,6 +119,42 @@
     public static final String ALGO_ID_SIGNATURE_RSA_SHA512 =
         Constants.MoreAlgorithmsSpecNS + "rsa-sha512";
 
+    /** Signature - Optional RSAwithSHA1andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA1_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha1-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA224andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA224_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha224-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA256andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA256_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha256-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA384andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA384_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha384-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA512andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA512_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha512-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA3_224andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-224-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA3_256andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-256-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA3_384andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-384-rsa-MGF1";
+
+    /** Signature - Optional RSAwithSHA3_512andMGF1 */
+    public static final String ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1 =
+        Constants.XML_DSIG_NS_MORE_07_05 + "sha3-512-rsa-MGF1";
+
     /** HMAC - NOT Recommended HMAC-MD5 */
     public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
         Constants.MoreAlgorithmsSpecNS + "hmac-md5";
@@ -125,6 +163,10 @@
     public static final String ALGO_ID_MAC_HMAC_RIPEMD160 =
         Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160";
 
+    /** HMAC - Optional HMAC-SHA2224 */
+    public static final String ALGO_ID_MAC_HMAC_SHA224 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-sha224";
+
     /** HMAC - Optional HMAC-SHA256 */
     public static final String ALGO_ID_MAC_HMAC_SHA256 =
         Constants.MoreAlgorithmsSpecNS + "hmac-sha256";
@@ -141,6 +183,10 @@
     public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 =
         "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
 
+    /**Signature - Optional ECDSAwithSHA224 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_SHA224 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224";
+
     /**Signature - Optional ECDSAwithSHA256 */
     public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 =
         "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
@@ -153,9 +199,12 @@
     public static final String ALGO_ID_SIGNATURE_ECDSA_SHA512 =
         "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XMLSignature.class.getName());
+    /**Signature - Optional ECDSAwithRIPEMD160 */
+    public static final String ALGO_ID_SIGNATURE_ECDSA_RIPEMD160 =
+        "http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160";
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLSignature.class);
 
     /** ds:Signature.ds:SignedInfo element */
     private SignedInfo signedInfo;
@@ -177,9 +226,9 @@
     private int state = MODE_SIGN;
 
     /**
-     * This creates a new <CODE>ds:Signature</CODE> Element and adds an empty
-     * <CODE>ds:SignedInfo</CODE>.
-     * The <code>ds:SignedInfo</code> is initialized with the specified Signature
+     * This creates a new {@code ds:Signature} Element and adds an empty
+     * {@code ds:SignedInfo}.
+     * The {@code ds:SignedInfo} is initialized with the specified Signature
      * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED
      * by the spec. This method's main use is for creating a new signature.
      *
@@ -250,31 +299,31 @@
 
         String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
         if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
-            this.constructionElement.setAttributeNS(
+            getElement().setAttributeNS(
                 Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
             );
         } else {
-            this.constructionElement.setAttributeNS(
+            getElement().setAttributeNS(
                 Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
             );
         }
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
         this.baseURI = baseURI;
         this.signedInfo =
             new SignedInfo(
-                this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
+                getDocument(), signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
             );
 
-        this.constructionElement.appendChild(this.signedInfo.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(this.signedInfo);
+        addReturnToSelf();
 
         // create an empty SignatureValue; this is filled by setSignatureValueElement
         signatureValueElement =
-            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+            XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_SIGNATUREVALUE);
 
-        this.constructionElement.appendChild(signatureValueElement);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(signatureValueElement);
+        addReturnToSelf();
     }
 
     /**
@@ -295,29 +344,29 @@
 
         String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
         if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
-            this.constructionElement.setAttributeNS(
+            getElement().setAttributeNS(
                 Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
             );
         } else {
-            this.constructionElement.setAttributeNS(
+            getElement().setAttributeNS(
                 Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
             );
         }
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
 
         this.baseURI = baseURI;
         this.signedInfo =
-            new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem);
+            new SignedInfo(getDocument(), SignatureMethodElem, CanonicalizationMethodElem);
 
-        this.constructionElement.appendChild(this.signedInfo.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(this.signedInfo);
+        addReturnToSelf();
 
         // create an empty SignatureValue; this is filled by setSignatureValueElement
         signatureValueElement =
-            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+            XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_SIGNATUREVALUE);
 
-        this.constructionElement.appendChild(signatureValueElement);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(signatureValueElement);
+        addReturnToSelf();
     }
 
     /**
@@ -331,7 +380,7 @@
      */
     public XMLSignature(Element element, String baseURI)
         throws XMLSignatureException, XMLSecurityException {
-        this(element, baseURI, false);
+        this(element, baseURI, true);
     }
 
     /**
@@ -382,8 +431,8 @@
 
         // If it exists use it, but it's not mandatory
         if (keyInfoElem != null
-            && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS)
-            && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) {
+            && Constants.SignatureSpecNS.equals(keyInfoElem.getNamespaceURI())
+            && Constants._TAG_KEYINFO.equals(keyInfoElem.getLocalName())) {
             this.keyInfo = new KeyInfo(keyInfoElem, baseURI);
             this.keyInfo.setSecureValidation(secureValidation);
         }
@@ -397,20 +446,19 @@
                 objectElem.setIdAttributeNode(objectAttr, true);
             }
 
-            NodeList nodes = objectElem.getChildNodes();
-            int length = nodes.getLength();
+            Node firstChild = objectElem.getFirstChild();
             // Register Ids of the Object child elements
-            for (int i = 0; i < length; i++) {
-                Node child = nodes.item(i);
-                if (child.getNodeType() == Node.ELEMENT_NODE) {
-                    Element childElem = (Element)child;
+            while (firstChild != null) {
+                if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                    Element childElem = (Element)firstChild;
                     String tag = childElem.getLocalName();
-                    if (tag.equals("Manifest")) {
+                    if ("Manifest".equals(tag)) {
                         new Manifest(childElem, baseURI);
-                    } else if (tag.equals("SignatureProperties")) {
+                    } else if ("SignatureProperties".equals(tag)) {
                         new SignatureProperties(childElem, baseURI);
                     }
                 }
+                firstChild = firstChild.getNextSibling();
             }
 
             objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
@@ -420,30 +468,29 @@
     }
 
     /**
-     * Sets the <code>Id</code> attribute
+     * Sets the {@code Id} attribute
      *
      * @param id Id value for the id attribute on the Signature Element
      */
     public void setId(String id) {
         if (id != null) {
-            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
-            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+            setLocalIdAttribute(Constants._ATT_ID, id);
         }
     }
 
     /**
-     * Returns the <code>Id</code> attribute
+     * Returns the {@code Id} attribute
      *
-     * @return the <code>Id</code> attribute
+     * @return the {@code Id} attribute
      */
     public String getId() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+        return getLocalAttribute(Constants._ATT_ID);
     }
 
     /**
-     * Returns the completely parsed <code>SignedInfo</code> object.
+     * Returns the completely parsed {@code SignedInfo} object.
      *
-     * @return the completely parsed <code>SignedInfo</code> object.
+     * @return the completely parsed {@code SignedInfo} object.
      */
     public SignedInfo getSignedInfo() {
         return this.signedInfo;
@@ -457,11 +504,8 @@
      * @throws XMLSignatureException If there is no content
      */
     public byte[] getSignatureValue() throws XMLSignatureException {
-        try {
-            return Base64.decode(signatureValueElement);
-        } catch (Base64DecodingException ex) {
-            throw new XMLSignatureException("empty", ex);
-        }
+        String content = XMLUtils.getFullTextChildrenFromElement(signatureValueElement);
+        return Base64.getMimeDecoder().decode(content);
     }
 
     /**
@@ -476,13 +520,13 @@
             signatureValueElement.removeChild(signatureValueElement.getFirstChild());
         }
 
-        String base64codedValue = Base64.encode(bytes);
+        String base64codedValue = Base64.getMimeEncoder().encodeToString(bytes);
 
         if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
             base64codedValue = "\n" + base64codedValue + "\n";
         }
 
-        Text t = this.doc.createTextNode(base64codedValue);
+        Text t = createText(base64codedValue);
         signatureValueElement.appendChild(t);
     }
 
@@ -499,23 +543,23 @@
         if (this.state == MODE_SIGN && this.keyInfo == null) {
 
             // create the KeyInfo
-            this.keyInfo = new KeyInfo(this.doc);
+            this.keyInfo = new KeyInfo(getDocument());
 
             // get the Element from KeyInfo
             Element keyInfoElement = this.keyInfo.getElement();
             Element firstObject =
                 XMLUtils.selectDsNode(
-                    this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0
+                    getElement().getFirstChild(), Constants._TAG_OBJECT, 0
                 );
 
             if (firstObject != null) {
                 // add it before the object
-                this.constructionElement.insertBefore(keyInfoElement, firstObject);
-                XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject);
+                getElement().insertBefore(keyInfoElement, firstObject);
+                XMLUtils.addReturnBeforeChild(getElement(), firstObject);
             } else {
                 // add it as the last element to the signature
-                this.constructionElement.appendChild(keyInfoElement);
-                XMLUtils.addReturnToElement(this.constructionElement);
+                appendSelf(keyInfoElement);
+                addReturnToSelf();
             }
         }
 
@@ -523,7 +567,7 @@
     }
 
     /**
-     * Appends an Object (not a <code>java.lang.Object</code> but an Object
+     * Appends an Object (not a {@code java.lang.Object} but an Object
      * element) to the Signature. Please note that this is only possible
      * when signing.
      *
@@ -537,25 +581,25 @@
         //  "signature.operationOnlyBeforeSign");
         //}
 
-        this.constructionElement.appendChild(object.getElement());
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(object);
+        addReturnToSelf();
         //} catch (XMLSecurityException ex) {
-        // throw new XMLSignatureException("empty", ex);
+        // throw new XMLSignatureException(ex);
         //}
     }
 
     /**
-     * Returns the <code>i<code>th <code>ds:Object</code> child of the signature
-     * or null if no such <code>ds:Object</code> element exists.
+     * Returns the {@code i}th {@code ds:Object} child of the signature
+     * or null if no such {@code ds:Object} element exists.
      *
      * @param i
-     * @return the <code>i<code>th <code>ds:Object</code> child of the signature
-     * or null if no such <code>ds:Object</code> element exists.
+     * @return the {@code i}th {@code ds:Object} child of the signature
+     * or null if no such {@code ds:Object} element exists.
      */
     public ObjectContainer getObjectItem(int i) {
         Element objElem =
             XMLUtils.selectDsNode(
-                this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i
+                getFirstChild(), Constants._TAG_OBJECT, i
             );
 
         try {
@@ -566,9 +610,9 @@
     }
 
     /**
-     * Returns the number of all <code>ds:Object</code> elements.
+     * Returns the number of all {@code ds:Object} elements.
      *
-     * @return the number of all <code>ds:Object</code> elements.
+     * @return the number of all {@code ds:Object} elements.
      */
     public int getObjectLength() {
         return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
@@ -590,44 +634,33 @@
             );
         }
 
-        try {
-            //Create a SignatureAlgorithm object
-            SignedInfo si = this.getSignedInfo();
-            SignatureAlgorithm sa = si.getSignatureAlgorithm();
-            OutputStream so = null;
-            try {
-                // initialize SignatureAlgorithm for signing
-                sa.initSign(signingKey);
+        //Create a SignatureAlgorithm object
+        SignedInfo si = this.getSignedInfo();
+        SignatureAlgorithm sa = si.getSignatureAlgorithm();
+        try (SignerOutputStream output = new SignerOutputStream(sa);
+            OutputStream so = new UnsyncBufferedOutputStream(output)) {
 
-                // generate digest values for all References in this SignedInfo
-                si.generateDigestValues();
-                so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa));
-                // get the canonicalized bytes from SignedInfo
-                si.signInOctetStream(so);
-            } catch (XMLSecurityException ex) {
-                throw ex;
-            } finally {
-                if (so != null) {
-                    try {
-                        so.close();
-                    } catch (IOException ex) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-                        }
-                    }
-                }
-            }
+            // generate digest values for all References in this SignedInfo
+            si.generateDigestValues();
+
+            // initialize SignatureAlgorithm for signing
+            sa.initSign(signingKey);
+
+            // get the canonicalized bytes from SignedInfo
+            si.signInOctetStream(so);
 
             // set them on the SignatureValue element
             this.setSignatureValueElement(sa.sign());
         } catch (XMLSignatureException ex) {
             throw ex;
         } catch (CanonicalizationException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
+        } catch (IOException ex) {
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -699,28 +732,23 @@
             //create a SignatureAlgorithms from the SignatureMethod inside
             //SignedInfo. This is used to validate the signature.
             SignatureAlgorithm sa = si.getSignatureAlgorithm();
+            LOG.debug("signatureMethodURI = {}", sa.getAlgorithmURI());
+            LOG.debug("jceSigAlgorithm = {}", sa.getJCEAlgorithmString());
+            LOG.debug("jceSigProvider = {}", sa.getJCEProviderName());
+            LOG.debug("PublicKey = {}", pk);
+
             byte sigBytes[] = null;
-            try {
+            try (SignerOutputStream so = new SignerOutputStream(sa);
+                OutputStream bos = new UnsyncBufferedOutputStream(so)) {
+
                 sa.initVerify(pk);
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI());
-                    log.log(java.util.logging.Level.FINE, "jceSigAlgorithm    = " + sa.getJCEAlgorithmString());
-                    log.log(java.util.logging.Level.FINE, "jceSigProvider     = " + sa.getJCEProviderName());
-                    log.log(java.util.logging.Level.FINE, "PublicKey = " + pk);
-                }
 
                 // Get the canonicalized (normalized) SignedInfo
-                SignerOutputStream so = new SignerOutputStream(sa);
-                OutputStream bos = new UnsyncBufferedOutputStream(so);
-
                 si.signInOctetStream(bos);
-                bos.close();
                 // retrieve the byte[] from the stored signature
                 sigBytes = this.getSignatureValue();
             } catch (IOException ex) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-                }
+                LOG.debug(ex.getMessage(), ex);
                 // Impossible...
             } catch (XMLSecurityException ex) {
                 throw ex;
@@ -729,7 +757,7 @@
             // have SignatureAlgorithm sign the input bytes and compare them to
             // the bytes that were stored in the signature.
             if (!sa.verify(sigBytes)) {
-                log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
+                LOG.warn("Signature verification failed.");
                 return false;
             }
 
@@ -737,7 +765,7 @@
         } catch (XMLSignatureException ex) {
             throw ex;
         } catch (XMLSecurityException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         }
     }
 
@@ -820,7 +848,7 @@
      * @throws XMLSecurityException
      */
     public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
-        X509Data x509data = new X509Data(this.doc);
+        X509Data x509data = new X509Data(getDocument());
 
         x509data.addCertificate(cert);
         this.getKeyInfo().add(x509data);
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,7 +28,6 @@
  * All XML Signature related exceptions inherit herefrom.
  *
  * @see MissingResourceFailureException InvalidDigestValueException InvalidSignatureValueException
- * @author Christian Geuer-Pollmann
  */
 public class XMLSignatureException extends XMLSecurityException {
 
@@ -45,6 +44,10 @@
         super();
     }
 
+    public XMLSignatureException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor XMLSignatureException
      *
@@ -67,21 +70,31 @@
     /**
      * Constructor XMLSignatureException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public XMLSignatureException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public XMLSignatureException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor XMLSignatureException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public XMLSignatureException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public XMLSignatureException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,20 +27,19 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 
-import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
-import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
-import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException;
 import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
@@ -51,7 +50,6 @@
 /**
  * Class XMLSignatureInput
  *
- * @author Christian Geuer-Pollmann
  * $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set?
  */
 public class XMLSignatureInput {
@@ -68,19 +66,19 @@
      * Some InputStreams do not support the {@link java.io.InputStream#reset}
      * method, so we read it in completely and work on our Proxy.
      */
-    private InputStream inputOctetStreamProxy = null;
+    private InputStream inputOctetStreamProxy;
     /**
      * The original NodeSet for this XMLSignatureInput
      */
-    private Set<Node> inputNodeSet = null;
+    private Set<Node> inputNodeSet;
     /**
      * The original Element
      */
-    private Node subNode = null;
+    private Node subNode;
     /**
      * Exclude Node *for enveloped transformations*
      */
-    private Node excludeNode = null;
+    private Node excludeNode;
     /**
      *
      */
@@ -90,7 +88,8 @@
     /**
      * A cached bytes
      */
-    private byte[] bytes = null;
+    private byte[] bytes;
+    private boolean secureValidation;
 
     /**
      * Some Transforms may require explicit MIME type, charset (IANA registered
@@ -101,22 +100,25 @@
      * Transform algorithm and should be described in the specification for the
      * algorithm.
      */
-    private String mimeType = null;
+    private String mimeType;
 
     /**
      * Field sourceURI
      */
-    private String sourceURI = null;
+    private String sourceURI;
 
     /**
      * Node Filter list.
      */
-    private List<NodeFilter> nodeFilters = new ArrayList<NodeFilter>();
+    private List<NodeFilter> nodeFilters = new ArrayList<>();
 
     private boolean needsToBeExpanded = false;
-    private OutputStream outputStream = null;
+    private OutputStream outputStream;
 
-    private DocumentBuilderFactory dfactory;
+    /**
+     * Pre-calculated digest value of the object in base64.
+     */
+    private String preCalculatedDigest;
 
     /**
      * Construct a XMLSignatureInput from an octet array.
@@ -132,7 +134,7 @@
     }
 
     /**
-     * Constructs a <code>XMLSignatureInput</code> from an octet stream. The
+     * Constructs a {@code XMLSignatureInput} from an octet stream. The
      * stream is directly read.
      *
      * @param inputOctetStream
@@ -161,6 +163,15 @@
     }
 
     /**
+     * Construct a {@code XMLSignatureInput} from a known digest value in Base64.
+     * This makes it possible to compare the element digest with the provided digest value.
+     * @param preCalculatedDigest digest value in base64.
+     */
+    public XMLSignatureInput(String preCalculatedDigest) {
+        this.preCalculatedDigest = preCalculatedDigest;
+    }
+
+    /**
      * Check if the structure needs to be expanded.
      * @return true if so.
      */
@@ -286,8 +297,7 @@
      * @return true if the object has been set up with a Node set
      */
     public boolean isNodeSet() {
-        return ((inputOctetStreamProxy == null
-            && inputNodeSet != null) || isNodeSet);
+        return inputOctetStreamProxy == null && inputNodeSet != null || isNodeSet;
     }
 
     /**
@@ -296,8 +306,8 @@
      * @return true if the object has been set up with an Element
      */
     public boolean isElement() {
-        return (inputOctetStreamProxy == null && subNode != null
-            && inputNodeSet == null && !isNodeSet);
+        return inputOctetStreamProxy == null && subNode != null
+            && inputNodeSet == null && !isNodeSet;
     }
 
     /**
@@ -306,8 +316,8 @@
      * @return true if the object has been set up with an octet stream
      */
     public boolean isOctetStream() {
-        return ((inputOctetStreamProxy != null || bytes != null)
-          && (inputNodeSet == null && subNode == null));
+        return (inputOctetStreamProxy != null || bytes != null)
+          && inputNodeSet == null && subNode == null;
     }
 
     /**
@@ -327,7 +337,15 @@
      * @return true is the object has been set up with an octet stream
      */
     public boolean isByteArray() {
-        return (bytes != null && (this.inputNodeSet == null && subNode == null));
+        return bytes != null && this.inputNodeSet == null && subNode == null;
+    }
+
+    /**
+     * Determines if the object has been set up with a pre-calculated digest.
+     * @return
+     */
+    public boolean isPreCalculatedDigest() {
+        return preCalculatedDigest != null;
     }
 
     /**
@@ -377,7 +395,7 @@
 
     /**
      * Method toString
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String toString() {
         if (isNodeSet()) {
@@ -556,13 +574,7 @@
 
     void convertToNodes() throws CanonicalizationException,
         ParserConfigurationException, IOException, SAXException {
-        if (dfactory == null) {
-            dfactory = DocumentBuilderFactory.newInstance();
-            dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-            dfactory.setValidating(false);
-            dfactory.setNamespaceAware(true);
-        }
-        DocumentBuilder db = dfactory.newDocumentBuilder();
+        DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation);
         // select all nodes, also the comments.
         try {
             db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
@@ -570,16 +582,20 @@
             Document doc = db.parse(this.getOctetStream());
             this.subNode = doc;
         } catch (SAXException ex) {
+            byte[] result = null;
             // if a not-wellformed nodeset exists, put a container around it...
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
 
-            baos.write("<container>".getBytes("UTF-8"));
-            baos.write(this.getBytes());
-            baos.write("</container>".getBytes("UTF-8"));
+                baos.write("<container>".getBytes(StandardCharsets.UTF_8));
+                baos.write(this.getBytes());
+                baos.write("</container>".getBytes(StandardCharsets.UTF_8));
 
-            byte result[] = baos.toByteArray();
-            Document document = db.parse(new ByteArrayInputStream(result));
-            this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
+                result = baos.toByteArray();
+            }
+            try (InputStream is = new ByteArrayInputStream(result)) {
+                Document document = db.parse(is);
+                this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
+            }
         } finally {
             if (this.inputOctetStreamProxy != null) {
                 this.inputOctetStreamProxy.close();
@@ -589,4 +605,15 @@
         }
     }
 
+    public boolean isSecureValidation() {
+        return secureValidation;
+    }
+
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
+    public String getPreCalculatedDigest() {
+        return preCalculatedDigest;
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java	Tue Jun 19 16:33:07 2018 +0100
@@ -48,11 +48,8 @@
 
     private Set<String> inclusiveNamespaces;
 
-    /** Field doc */
-    private Document doc = null;
-
     /** Field writer */
-    private Writer writer = null;
+    private Writer writer;
 
     /** The HTML Prefix* */
     static final String HTMLPrefix =
@@ -148,27 +145,26 @@
      * @throws XMLSignatureException
      */
     public String getHTMLRepresentation() throws XMLSignatureException {
-        if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
+        if (this.xpathNodeSet == null || this.xpathNodeSet.isEmpty()) {
             return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
         }
 
         // get only a single node as anchor to fetch the owner document
         Node n = this.xpathNodeSet.iterator().next();
 
-        this.doc = XMLUtils.getOwnerDocument(n);
+        Document doc = XMLUtils.getOwnerDocument(n);
 
         try {
             this.writer = new StringWriter();
 
-            this.canonicalizeXPathNodeSet(this.doc);
+            this.canonicalizeXPathNodeSet(doc);
             this.writer.close();
 
             return this.writer.toString();
         } catch (IOException ex) {
-            throw new XMLSignatureException("empty", ex);
+            throw new XMLSignatureException(ex);
         } finally {
             this.xpathNodeSet = null;
-            this.doc = null;
             this.writer = null;
         }
     }
@@ -191,7 +187,7 @@
         case Node.NOTATION_NODE:
         case Node.DOCUMENT_FRAGMENT_NODE:
         case Node.ATTRIBUTE_NODE:
-            throw new XMLSignatureException("empty");
+            throw new XMLSignatureException("empty", new Object[]{"An incorrect node was provided for c14n: " + currentNodeType});
         case Node.DOCUMENT_NODE:
             this.writer.write(HTMLPrefix);
 
@@ -258,9 +254,9 @@
             outputTextToWriter(currentNode.getNodeValue());
 
             for (Node nextSibling = currentNode.getNextSibling();
-                (nextSibling != null)
-                && ((nextSibling.getNodeType() == Node.TEXT_NODE)
-                    || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE));
+                nextSibling != null
+                && (nextSibling.getNodeType() == Node.TEXT_NODE
+                    || nextSibling.getNodeType() == Node.CDATA_SECTION_NODE);
                 nextSibling = nextSibling.getNextSibling()) {
                 /*
                  * The XPath data model allows to select only the first of a
@@ -412,13 +408,13 @@
      *
      * The string value of the node is modified by replacing
      * <UL>
-     * <LI>all ampersands (&) with <CODE>&amp;amp;</CODE></LI>
-     * <LI>all open angle brackets (<) with <CODE>&amp;lt;</CODE></LI>
-     * <LI>all quotation mark characters with <CODE>&amp;quot;</CODE></LI>
-     * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD,
+     * <LI>all ampersands (&) with {@code &amp;amp;}</LI>
+     * <LI>all open angle brackets (<) with {@code &amp;lt;}</LI>
+     * <LI>all quotation mark characters with {@code &amp;quot;}</LI>
+     * <LI>and the whitespace characters {@code #x9}, #xA, and #xD,
      * with character references. The character references are written in
-     * uppercase hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE>
-     * is represented by the character reference <CODE>&amp;#xD;</CODE>)</LI>
+     * uppercase hexadecimal with no leading zeroes (for example, {@code #xD}
+     * is represented by the character reference {@code &amp;#xD;})</LI>
      * </UL>
      *
      * @param name
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-XML Signature specific classes.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
@@ -33,20 +33,20 @@
 import org.w3c.dom.Node;
 
 /**
- * An abstract representation of a <code>ReferenceData</code> type containing a node-set.
+ * An abstract representation of a {@code ReferenceData} type containing a node-set.
  */
 public interface ReferenceNodeSetData extends ReferenceData {
 
     /**
      * Returns a read-only iterator over the nodes contained in this
-     * <code>NodeSetData</code> in
+     * {@code NodeSetData} in
      * <a href="http://www.w3.org/TR/1999/REC-xpath-19991116#dt-document-order">
      * document order</a>. Attempts to modify the returned iterator
-     * via the <code>remove</code> method throw
-     * <code>UnsupportedOperationException</code>.
+     * via the {@code remove} method throw
+     * {@code UnsupportedOperationException}.
      *
-     * @return an <code>Iterator</code> over the nodes in this
-     *    <code>NodeSetData</code> in document order
+     * @return an {@code Iterator} over the nodes in this
+     *    {@code NodeSetData} in document order
      */
     Iterator<Node> iterator();
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
@@ -31,7 +31,7 @@
 import java.io.InputStream;
 
 /**
- * A representation of a <code>ReferenceData</code> type containing an OctetStream.
+ * A representation of a {@code ReferenceData} type containing an OctetStream.
  */
 public class ReferenceOctetStreamData implements ReferenceData {
     private InputStream octetStream;
@@ -39,11 +39,11 @@
     private String mimeType;
 
     /**
-     * Creates a new <code>ReferenceOctetStreamData</code>.
+     * Creates a new {@code ReferenceOctetStreamData}.
      *
      * @param octetStream the input stream containing the octets
-     * @throws NullPointerException if <code>octetStream</code> is
-     *    <code>null</code>
+     * @throws NullPointerException if {@code octetStream} is
+     *    {@code null}
      */
     public ReferenceOctetStreamData(InputStream octetStream) {
         if (octetStream == null) {
@@ -53,15 +53,15 @@
     }
 
     /**
-     * Creates a new <code>ReferenceOctetStreamData</code>.
+     * Creates a new {@code ReferenceOctetStreamData}.
      *
      * @param octetStream the input stream containing the octets
      * @param uri the URI String identifying the data object (may be
-     *    <code>null</code>)
+     *    {@code null})
      * @param mimeType the MIME type associated with the data object (may be
-     *    <code>null</code>)
-     * @throws NullPointerException if <code>octetStream</code> is
-     *    <code>null</code>
+     *    {@code null})
+     * @throws NullPointerException if {@code octetStream} is
+     *    {@code null}
      */
     public ReferenceOctetStreamData(InputStream octetStream, String uri,
         String mimeType) {
@@ -74,9 +74,9 @@
     }
 
     /**
-     * Returns the input stream of this <code>ReferenceOctetStreamData</code>.
+     * Returns the input stream of this {@code ReferenceOctetStreamData}.
      *
-     * @return the input stream of this <code>ReferenceOctetStreamData</code>.
+     * @return the input stream of this {@code ReferenceOctetStreamData}.
      */
     public InputStream getOctetStream() {
         return octetStream;
@@ -84,9 +84,9 @@
 
     /**
      * Returns the URI String identifying the data object represented by this
-     * <code>ReferenceOctetStreamData</code>.
+     * {@code ReferenceOctetStreamData}.
      *
-     * @return the URI String or <code>null</code> if not applicable
+     * @return the URI String or {@code null} if not applicable
      */
     public String getURI() {
         return uri;
@@ -94,9 +94,9 @@
 
     /**
      * Returns the MIME type associated with the data object represented by this
-     * <code>ReferenceOctetStreamData</code>.
+     * {@code ReferenceOctetStreamData}.
      *
-     * @return the MIME type or <code>null</code> if not applicable
+     * @return the MIME type or {@code null} if not applicable
      */
     public String getMimeType() {
         return mimeType;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
@@ -37,7 +37,7 @@
 import org.w3c.dom.Node;
 
 /**
- * A representation of a <code>ReferenceNodeSetData</code> type containing a node-set.
+ * A representation of a {@code ReferenceNodeSetData} type containing a node-set.
  * This is a subtype of NodeSetData that represents a dereferenced
  * same-document URI as the root of a subdocument. The main reason is
  * for efficiency and performance, as some transforms can operate
@@ -109,11 +109,11 @@
          * Dereferences a same-document URI fragment.
          *
          * @param node the node (document or element) referenced by the
-         *        URI fragment. If null, returns an empty set.
+         *     URI fragment. If null, returns an empty set.
          * @return a set of nodes (minus any comment nodes)
          */
         private List<Node> dereferenceSameDocumentURI(Node node) {
-            List<Node> nodeSet = new ArrayList<Node>();
+            List<Node> nodeSet = new ArrayList<>();
             if (node != null) {
                 nodeSetMinusCommentNodes(node, nodeSet, null);
             }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/ClassLoaderUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,211 +23,19 @@
 
 package com.sun.org.apache.xml.internal.security.transforms;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-/**
- * This class is extremely useful for loading resources and classes in a fault
- * tolerant manner that works across different applications servers. Do not
- * touch this unless you're a grizzled classloading guru veteran who is going to
- * verify any change on 6 different application servers.
- */
 // NOTE! This is a duplicate of utils.ClassLoaderUtils with public
 // modifiers changed to package-private. Make sure to integrate any future
 // changes to utils.ClassLoaderUtils to this file.
 final class ClassLoaderUtils {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
 
     private ClassLoaderUtils() {
     }
 
     /**
-     * Load a given resource. <p/> This method will try to load the resource
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static URL getResource(String resourceName, Class<?> callingClass) {
-        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url =
-                Thread.currentThread().getContextClassLoader().getResource(
-                    resourceName.substring(1)
-                );
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (url == null) {
-            url = cluClassloader.getResource(resourceName);
-        }
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url = cluClassloader.getResource(resourceName.substring(1));
-        }
-
-        if (url == null) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                url = cl.getResource(resourceName);
-            }
-        }
-
-        if (url == null) {
-            url = callingClass.getResource(resourceName);
-        }
-
-        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResource('/' + resourceName, callingClass);
-        }
-
-        return url;
-    }
-
-    /**
-     * Load a given resources. <p/> This method will try to load the resources
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static List<URL> getResources(String resourceName, Class<?> callingClass) {
-        List<URL> ret = new ArrayList<URL>();
-        Enumeration<URL> urls = new Enumeration<URL>() {
-            public boolean hasMoreElements() {
-                return false;
-            }
-            public URL nextElement() {
-                return null;
-            }
-
-        };
-        try {
-            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            //ignore
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls =
-                    Thread.currentThread().getContextClassLoader().getResources(
-                        resourceName.substring(1)
-                    );
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (!urls.hasMoreElements()) {
-            try {
-                urls = cluClassloader.getResources(resourceName);
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls = cluClassloader.getResources(resourceName.substring(1));
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                try {
-                    urls = cl.getResources(resourceName);
-                } catch (IOException e) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                    }
-                    // ignore
-                }
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            URL url = callingClass.getResource(resourceName);
-            if (url != null) {
-                ret.add(url);
-            }
-        }
-        while (urls.hasMoreElements()) {
-            ret.add(urls.nextElement());
-        }
-
-
-        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResources('/' + resourceName, callingClass);
-        }
-        return ret;
-    }
-
-
-    /**
-     * This is a convenience method to load a resource as a stream. <p/> The
-     * algorithm used to find the resource is given in getResource()
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
-        URL url = getResource(resourceName, callingClass);
-
-        try {
-            return (url != null) ? url.openStream() : null;
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            return null;
-        }
-    }
-
-    /**
-     * Load a class with a given name. <p/> It will try to load the class in the
+     * Load a class with a given name. <p></p> It will try to load the class in the
      * following order:
      * <ul>
      * <li>From Thread.currentThread().getContextClassLoader()
@@ -249,9 +57,7 @@
                 return cl.loadClass(className);
             }
         } catch (ClassNotFoundException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
             //ignore
         }
         return loadClass2(className, callingClass);
@@ -271,9 +77,7 @@
                     return callingClass.getClassLoader().loadClass(className);
                 }
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             throw ex;
         }
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,7 +26,6 @@
 
 /**
  *
- * @author Christian Geuer-Pollmann
  */
 public class InvalidTransformException extends XMLSecurityException {
 
@@ -68,8 +67,13 @@
      * @param msgId
      * @param originalException
      */
-    public InvalidTransformException(String msgId, Exception originalException) {
-        super(msgId, originalException);
+    public InvalidTransformException(Exception originalException, String msgId) {
+        super(originalException, msgId);
+    }
+
+    @Deprecated
+    public InvalidTransformException(String msgID, Exception originalException) {
+        this(originalException, msgID);
     }
 
     /**
@@ -79,7 +83,12 @@
      * @param exArgs
      * @param originalException
      */
-    public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) {
-        super(msgId, exArgs, originalException);
+    public InvalidTransformException(Exception originalException, String msgId, Object exArgs[]) {
+        super(originalException, msgId, exArgs);
+    }
+
+    @Deprecated
+    public InvalidTransformException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -55,36 +55,35 @@
 import org.xml.sax.SAXException;
 
 /**
- * Implements the behaviour of the <code>ds:Transform</code> element.
+ * Implements the behaviour of the {@code ds:Transform} element.
  *
- * This <code>Transform</code>(Factory) class acts as the Factory and Proxy of
+ * This {@code Transform}(Factory) class acts as the Factory and Proxy of
  * the implementing class that supports the functionality of <a
  * href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>a Transform
  * algorithm</a>.
  * Implements the Factory and Proxy pattern for ds:Transform algorithms.
  *
- * @author Christian Geuer-Pollmann
  * @see Transforms
  * @see TransformSpi
  */
 public final class Transform extends SignatureElementProxy {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Transform.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(Transform.class);
 
     /** All available Transform classes are registered here */
     private static Map<String, Class<? extends TransformSpi>> transformSpiHash =
         new ConcurrentHashMap<String, Class<? extends TransformSpi>>();
 
     private final TransformSpi transformSpi;
+    private boolean secureValidation;
 
     /**
      * Generates a Transform object that implements the specified
-     * <code>Transform algorithm</code> URI.
+     * {@code Transform algorithm} URI.
      *
      * @param doc the proxy {@link Document}
-     * @param algorithmURI <code>Transform algorithm</code> URI representation,
+     * @param algorithmURI {@code Transform algorithm} URI representation,
      * such as specified in
      * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
      * @throws InvalidTransformException
@@ -95,12 +94,12 @@
 
     /**
      * Generates a Transform object that implements the specified
-     * <code>Transform algorithm</code> URI.
+     * {@code Transform algorithm} URI.
      *
-     * @param algorithmURI <code>Transform algorithm</code> URI representation,
+     * @param algorithmURI {@code Transform algorithm} URI representation,
      * such as specified in
      * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
-     * @param contextChild the child element of <code>Transform</code> element
+     * @param contextChild the child element of {@code Transform} element
      * @param doc the proxy {@link Document}
      * @throws InvalidTransformException
      */
@@ -123,10 +122,10 @@
     /**
      * Constructs {@link Transform}
      *
-     * @param doc the {@link Document} in which <code>Transform</code> will be
+     * @param doc the {@link Document} in which {@code Transform} will be
      * placed
-     * @param algorithmURI URI representation of <code>Transform algorithm</code>
-     * @param contextNodes the child node list of <code>Transform</code> element
+     * @param algorithmURI URI representation of {@code Transform algorithm}
+     * @param contextNodes the child node list of {@code Transform} element
      * @throws InvalidTransformException
      */
     public Transform(Document doc, String algorithmURI, NodeList contextNodes)
@@ -136,15 +135,15 @@
     }
 
     /**
-     * @param element <code>ds:Transform</code> element
-     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @param element {@code ds:Transform} element
+     * @param baseURI the URI of the resource where the XML instance was stored
      * @throws InvalidTransformException
      * @throws TransformationException
      * @throws XMLSecurityException
      */
-    public Transform(Element element, String BaseURI)
+    public Transform(Element element, String baseURI)
         throws InvalidTransformException, TransformationException, XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
 
         // retrieve Algorithm Attribute from ds:Transform
         String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
@@ -166,12 +165,12 @@
         } catch (InstantiationException ex) {
             Object exArgs[] = { algorithmURI };
             throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex
+                ex, "signature.Transform.UnknownTransform", exArgs
             );
         } catch (IllegalAccessException ex) {
             Object exArgs[] = { algorithmURI };
             throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex
+                ex, "signature.Transform.UnknownTransform", exArgs
             );
         }
     }
@@ -179,8 +178,8 @@
     /**
      * Registers implementing class of the Transform algorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
-     * @param implementingClass <code>implementingClass</code> the implementing
+     * @param algorithmURI algorithmURI URI representation of {@code Transform algorithm}
+     * @param implementingClass {@code implementingClass} the implementing
      * class of {@link TransformSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
      * is already registered
@@ -207,8 +206,8 @@
     /**
      * Registers implementing class of the Transform algorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
-     * @param implementingClass <code>implementingClass</code> the implementing
+     * @param algorithmURI algorithmURI URI representation of {@code Transform algorithm}
+     * @param implementingClass {@code implementingClass} the implementing
      * class of {@link TransformSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
      * is already registered
@@ -272,7 +271,7 @@
      * @return the URI representation of Transformation algorithm
      */
     public String getURI() {
-        return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        return getLocalAttribute(Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -313,21 +312,22 @@
         XMLSignatureInput result = null;
 
         try {
+            transformSpi.secureValidation = secureValidation;
             result = transformSpi.enginePerformTransform(input, os, this);
         } catch (ParserConfigurationException ex) {
             Object exArgs[] = { this.getURI(), "ParserConfigurationException" };
             throw new CanonicalizationException(
-                "signature.Transform.ErrorDuringTransform", exArgs, ex);
+                ex, "signature.Transform.ErrorDuringTransform", exArgs);
         } catch (SAXException ex) {
             Object exArgs[] = { this.getURI(), "SAXException" };
             throw new CanonicalizationException(
-                "signature.Transform.ErrorDuringTransform", exArgs, ex);
+                ex, "signature.Transform.ErrorDuringTransform", exArgs);
         }
 
         return result;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_TRANSFORM;
     }
@@ -338,7 +338,7 @@
     private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes)
         throws InvalidTransformException {
 
-        this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+        setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
 
         Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
         if (transformSpiClass == null) {
@@ -353,28 +353,34 @@
         } catch (InstantiationException ex) {
             Object exArgs[] = { algorithmURI };
             throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex
+                ex, "signature.Transform.UnknownTransform", exArgs
             );
         } catch (IllegalAccessException ex) {
             Object exArgs[] = { algorithmURI };
             throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex
+                ex, "signature.Transform.UnknownTransform", exArgs
             );
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
-                      + newTransformSpi.getClass() + "\"");
-            log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
-        }
+        LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, newTransformSpi.getClass());
+        LOG.debug("The NodeList is {}", contextNodes);
 
         // give it to the current document
         if (contextNodes != null) {
-            for (int i = 0; i < contextNodes.getLength(); i++) {
-                this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
+            int length = contextNodes.getLength();
+            for (int i = 0; i < length; i++) {
+                appendSelf(contextNodes.item(i).cloneNode(true));
             }
         }
         return newTransformSpi;
     }
 
+    public boolean isSecureValidation() {
+        return secureValidation;
+    }
+
+    public void setSecureValidation(boolean secureValidation) {
+        this.secureValidation = secureValidation;
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,10 +36,11 @@
  * have to be overridden are the
  * {@link #enginePerformTransform(XMLSignatureInput, Transform)} method.
  *
- * @author Christian Geuer-Pollmann
  */
 public abstract class TransformSpi {
 
+    protected boolean secureValidation;
+
     /**
      * The mega method which MUST be implemented by the Transformation Algorithm.
      *
@@ -104,9 +105,9 @@
     }
 
     /**
-     * Returns the URI representation of <code>Transformation algorithm</code>
+     * Returns the URI representation of {@code Transformation algorithm}
      *
-     * @return the URI representation of <code>Transformation algorithm</code>
+     * @return the URI representation of {@code Transformation algorithm}
      */
     protected abstract String engineGetURI();
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,7 +26,6 @@
 
 /**
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformationException extends XMLSecurityException {
     /**
@@ -42,6 +41,10 @@
         super();
     }
 
+    public TransformationException(Exception ex) {
+        super(ex);
+    }
+
     /**
      * Constructor TransformationException
      *
@@ -64,21 +67,31 @@
     /**
      * Constructor TransformationException
      *
+     * @param originalException
      * @param msgID
-     * @param originalException
      */
+    public TransformationException(Exception originalException, String msgID) {
+        super(originalException, msgID);
+    }
+
+    @Deprecated
     public TransformationException(String msgID, Exception originalException) {
-        super(msgID, originalException);
+        this(originalException, msgID);
     }
 
     /**
      * Constructor TransformationException
      *
+     * @param originalException
      * @param msgID
      * @param exArgs
-     * @param originalException
      */
-    public TransformationException(String msgID, Object exArgs[], Exception originalException) {
-        super(msgID, exArgs, originalException);
+    public TransformationException(Exception originalException, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
+    }
+
+    @Deprecated
+    public TransformationException(String msgID, Object[] exArgs, Exception originalException) {
+        this(originalException, msgID, exArgs);
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Tue Jun 19 16:33:07 2018 +0100
@@ -43,11 +43,10 @@
  * Holder of the {@link com.sun.org.apache.xml.internal.security.transforms.Transform} steps to
  * be performed on the data.
  * The input to the first Transform is the result of dereferencing the
- * <code>URI</code> attribute of the <code>Reference</code> element.
+ * {@code URI} attribute of the {@code Reference} element.
  * The output from the last Transform is the input for the
- * <code>DigestMethod algorithm</code>
+ * {@code DigestMethod algorithm}
  *
- * @author Christian Geuer-Pollmann
  * @see Transform
  * @see com.sun.org.apache.xml.internal.security.signature.Reference
  */
@@ -101,43 +100,42 @@
     public static final String TRANSFORM_XPATH2FILTER
         = "http://www.w3.org/2002/06/xmldsig-filter2";
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(Transforms.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(Transforms.class);
 
     private Element[] transforms;
 
-    protected Transforms() { };
+    protected Transforms() { }
 
     private boolean secureValidation;
 
     /**
      * Constructs {@link Transforms}.
      *
-     * @param doc the {@link Document} in which <code>XMLSignature</code> will
+     * @param doc the {@link Document} in which {@code XMLSignature} will
      * be placed
      */
     public Transforms(Document doc) {
         super(doc);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
     }
 
     /**
      * Constructs {@link Transforms} from {@link Element} which is
-     * <code>Transforms</code> Element
+     * {@code Transforms} Element
      *
-     * @param element  is <code>Transforms</code> element
-     * @param BaseURI the URI where the XML instance was stored
+     * @param element  is {@code Transforms} element
+     * @param baseURI the URI where the XML instance was stored
      * @throws DOMException
      * @throws InvalidTransformException
      * @throws TransformationException
      * @throws XMLSecurityException
      * @throws XMLSignatureException
      */
-    public Transforms(Element element, String BaseURI)
+    public Transforms(Element element, String baseURI)
         throws DOMException, XMLSignatureException, InvalidTransformException,
             TransformationException, XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
 
         int numberOfTransformElems = this.getLength();
 
@@ -157,7 +155,7 @@
     }
 
     /**
-     * Adds the <code>Transform</code> with the specified <code>Transform
+     * Adds the {@code Transform} with the specified <code>Transform
      * algorithm URI</code>
      *
      * @param transformURI the URI form of transform that indicates which
@@ -166,20 +164,18 @@
      */
     public void addTransform(String transformURI) throws TransformationException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
-            }
+            LOG.debug("Transforms.addTransform({})", transformURI);
 
-            Transform transform = new Transform(this.doc, transformURI);
+            Transform transform = new Transform(getDocument(), transformURI);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
     /**
-     * Adds the <code>Transform</code> with the specified <code>Transform
+     * Adds the {@code Transform} with the specified <code>Transform
      * algorithm URI</code>
      *
      * @param transformURI the URI form of transform that indicates which
@@ -190,20 +186,18 @@
     public void addTransform(String transformURI, Element contextElement)
        throws TransformationException {
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
-            }
+            LOG.debug("Transforms.addTransform({})", transformURI);
 
-            Transform transform = new Transform(this.doc, transformURI, contextElement);
+            Transform transform = new Transform(getDocument(), transformURI, contextElement);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
     /**
-     * Adds the <code>Transform</code> with the specified <code>Transform
+     * Adds the {@code Transform} with the specified <code>Transform
      * algorithm URI</code>.
      *
      * @param transformURI the URI form of transform that indicates which
@@ -215,10 +209,10 @@
        throws TransformationException {
 
         try {
-            Transform transform = new Transform(this.doc, transformURI, contextNodes);
+            Transform transform = new Transform(getDocument(), transformURI, contextNodes);
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
@@ -228,22 +222,20 @@
      * @param transform {@link Transform} object
      */
     private void addTransform(Transform transform) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")");
-        }
+        LOG.debug("Transforms.addTransform({})", transform.getURI());
 
         Element transformElement = transform.getElement();
 
-        this.constructionElement.appendChild(transformElement);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendSelf(transformElement);
+        addReturnToSelf();
     }
 
     /**
-     * Applies all included <code>Transform</code>s to xmlSignatureInput and
+     * Applies all included {@code Transform}s to xmlSignatureInput and
      * returns the result of these transformations.
      *
-     * @param xmlSignatureInput the input for the <code>Transform</code>s
-     * @return the result of the <code>Transforms</code>
+     * @param xmlSignatureInput the input for the {@code Transform}s
+     * @return the result of the {@code Transforms}
      * @throws TransformationException
      */
     public XMLSignatureInput performTransforms(
@@ -253,12 +245,12 @@
     }
 
     /**
-     * Applies all included <code>Transform</code>s to xmlSignatureInput and
+     * Applies all included {@code Transform}s to xmlSignatureInput and
      * returns the result of these transformations.
      *
-     * @param xmlSignatureInput the input for the <code>Transform</code>s
+     * @param xmlSignatureInput the input for the {@code Transform}s
      * @param os where to output the last transformation.
-     * @return the result of the <code>Transforms</code>
+     * @return the result of the {@code Transforms}
      * @throws TransformationException
      */
     public XMLSignatureInput performTransforms(
@@ -268,26 +260,24 @@
             int last = this.getLength() - 1;
             for (int i = 0; i < last; i++) {
                 Transform t = this.item(i);
-                String uri = t.getURI();
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform");
-                }
+                LOG.debug("Perform the ({})th {} transform", i, t.getURI());
                 checkSecureValidation(t);
                 xmlSignatureInput = t.performTransform(xmlSignatureInput);
             }
             if (last >= 0) {
                 Transform t = this.item(last);
+                LOG.debug("Perform the ({})th {} transform", last, t.getURI());
                 checkSecureValidation(t);
                 xmlSignatureInput = t.performTransform(xmlSignatureInput, os);
             }
 
             return xmlSignatureInput;
         } catch (IOException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (CanonicalizationException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
@@ -300,6 +290,7 @@
                 "signature.Transform.ForbiddenTransform", exArgs
             );
         }
+        transform.setSecureValidation(secureValidation);
     }
 
     /**
@@ -308,34 +299,34 @@
      * @return the number of transformations
      */
     public int getLength() {
-        if (transforms == null) {
-            transforms =
-                XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform");
-        }
+        initTransforms();
         return transforms.length;
     }
 
     /**
-     * Return the <it>i</it><sup>th</sup> <code>{@link Transform}</code>.
-     * Valid <code>i</code> values are 0 to <code>{@link #getLength}-1</code>.
+     * Return the <i>i</i><sup>th</sup> {@code {@link Transform}}.
+     * Valid {@code i} values are 0 to {@code {@link #getLength}-1}.
      *
      * @param i index of {@link Transform} to return
-     * @return the <it>i</it><sup>th</sup> Transform
+     * @return the <i>i</i><sup>th</sup> Transform
      * @throws TransformationException
      */
     public Transform item(int i) throws TransformationException {
         try {
-            if (transforms == null) {
-                transforms =
-                    XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform");
-            }
+            initTransforms();
             return new Transform(transforms[i], this.baseURI);
         } catch (XMLSecurityException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
-    /** @inheritDoc */
+    private void initTransforms() {
+        if (transforms == null) {
+            transforms = XMLUtils.selectDsNodes(getFirstChild(), "Transform");
+        }
+    }
+
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_TRANSFORMS;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,10 +34,11 @@
 import com.sun.org.apache.xpath.internal.objects.XNodeSet;
 import com.sun.org.apache.xpath.internal.objects.XObject;
 import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
-import java.util.List;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 
+import java.util.List;
+
 /**
  * The 'here()' function returns a node-set containing the attribute or
  * processing instruction node or the parent element of the text node
@@ -73,9 +74,7 @@
      * @return the xobject
      * @throws javax.xml.transform.TransformerException
      */
-    @Override
-    public XObject execute(XPathContext xctxt)
-        throws javax.xml.transform.TransformerException {
+    public XObject execute(XPathContext xctxt) throws TransformerException {
 
         Node xpathOwnerNode = (Node) xctxt.getOwnerObject();
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,30 +22,29 @@
  */
 package com.sun.org.apache.xml.internal.security.transforms.implementations;
 
-import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.util.Base64;
 
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
 import com.sun.org.apache.xml.internal.security.transforms.TransformSpi;
 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.Text;
 import org.xml.sax.SAXException;
 
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
+
 /**
- * Implements the <CODE>http://www.w3.org/2000/09/xmldsig#base64</CODE> decoding
+ * Implements the {@code http://www.w3.org/2000/09/xmldsig#base64} decoding
  * transform.
  *
  * <p>The normative specification for base64 decoding transforms is
@@ -58,7 +57,7 @@
  * <p>This transform requires an octet stream for input.
  * If an XPath node-set (or sufficiently functional alternative) is
  * given as input, then it is converted to an octet stream by
- * performing operations logically equivalent to 1) applying an XPath
+ * performing operations LOGically equivalent to 1) applying an XPath
  * transform with expression self::text(), then 2) taking the string-value
  * of the node-set. Thus, if an XML element is identified by a barename
  * XPointer in the Reference URI, and its content consists solely of base64
@@ -67,8 +66,6 @@
  * elements as well as any descendant comments and processing instructions.
  * The output of this transform is an octet stream.</p>
  *
- * @author Christian Geuer-Pollmann
- * @see com.sun.org.apache.xml.internal.security.utils.Base64
  */
 public class TransformBase64Decode extends TransformSpi {
 
@@ -79,7 +76,7 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return TransformBase64Decode.implementedTransformURI;
@@ -90,7 +87,7 @@
      *
      * @param input
      * @return {@link XMLSignatureInput} as the result of transformation
-     * @inheritDoc
+     * {@inheritDoc}
      * @throws CanonicalizationException
      * @throws IOException
      * @throws TransformationException
@@ -104,64 +101,70 @@
     protected XMLSignatureInput enginePerformTransform(
         XMLSignatureInput input, OutputStream os, Transform transformObject
     ) throws IOException, CanonicalizationException, TransformationException {
-        try {
-            if (input.isElement()) {
-                Node el = input.getSubNode();
-                if (input.getSubNode().getNodeType() == Node.TEXT_NODE) {
-                    el = el.getParentNode();
-                }
-                StringBuilder sb = new StringBuilder();
-                traverseElement((Element)el, sb);
-                if (os == null) {
-                    byte[] decodedBytes = Base64.decode(sb.toString());
-                    return new XMLSignatureInput(decodedBytes);
-                }
-                Base64.decode(sb.toString(), os);
-                XMLSignatureInput output = new XMLSignatureInput((byte[])null);
-                output.setOutputStream(os);
+        if (input.isElement()) {
+            Node el = input.getSubNode();
+            if (input.getSubNode().getNodeType() == Node.TEXT_NODE) {
+                el = el.getParentNode();
+            }
+            StringBuilder sb = new StringBuilder();
+            traverseElement((Element)el, sb);
+            if (os == null) {
+                byte[] decodedBytes = Base64.getMimeDecoder().decode(sb.toString());
+                XMLSignatureInput output = new XMLSignatureInput(decodedBytes);
+                output.setSecureValidation(secureValidation);
+                return output;
+            }
+            byte[] bytes = Base64.getMimeDecoder().decode(sb.toString());
+            os.write(bytes);
+            XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+            output.setSecureValidation(secureValidation);
+            output.setOutputStream(os);
+            return output;
+        }
+
+        if (input.isOctetStream() || input.isNodeSet()) {
+            if (os == null) {
+                byte[] base64Bytes = input.getBytes();
+                byte[] decodedBytes = Base64.getMimeDecoder().decode(base64Bytes);
+                XMLSignatureInput output = new XMLSignatureInput(decodedBytes);
+                output.setSecureValidation(secureValidation);
                 return output;
             }
-
-            if (input.isOctetStream() || input.isNodeSet()) {
-                if (os == null) {
-                    byte[] base64Bytes = input.getBytes();
-                    byte[] decodedBytes = Base64.decode(base64Bytes);
-                    return new XMLSignatureInput(decodedBytes);
-                }
-                if (input.isByteArray() || input.isNodeSet()) {
-                    Base64.decode(input.getBytes(), os);
-                } else {
-                    Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os);
-                }
-                XMLSignatureInput output = new XMLSignatureInput((byte[])null);
-                output.setOutputStream(os);
-                return output;
+            if (input.isByteArray() || input.isNodeSet()) {
+                byte[] bytes = Base64.getMimeDecoder().decode(input.getBytes());
+                os.write(bytes);
+            } else {
+                byte[] inputBytes = JavaUtils.getBytesFromStream(input.getOctetStreamReal());
+                byte[] bytes = Base64.getMimeDecoder().decode(inputBytes);
+                os.write(bytes);
             }
+            XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+            output.setSecureValidation(secureValidation);
+            output.setOutputStream(os);
+            return output;
+        }
 
-            try {
-                //Exceptional case there is current not text case testing this(Before it was a
-                //a common case).
-                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-                Document doc =
-                    dbf.newDocumentBuilder().parse(input.getOctetStream());
+        try {
+            //Exceptional case there is current not text case testing this(Before it was a
+            //a common case).
+            Document doc =
+                XMLUtils.createDocumentBuilder(false, secureValidation).parse(input.getOctetStream());
 
-                Element rootNode = doc.getDocumentElement();
-                StringBuilder sb = new StringBuilder();
-                traverseElement(rootNode, sb);
-                byte[] decodedBytes = Base64.decode(sb.toString());
-                return new XMLSignatureInput(decodedBytes);
-            } catch (ParserConfigurationException e) {
-                throw new TransformationException("c14n.Canonicalizer.Exception",e);
-            } catch (SAXException e) {
-                throw new TransformationException("SAX exception", e);
-            }
-        } catch (Base64DecodingException e) {
-            throw new TransformationException("Base64Decoding", e);
+            Element rootNode = doc.getDocumentElement();
+            StringBuilder sb = new StringBuilder();
+            traverseElement(rootNode, sb);
+            byte[] decodedBytes = Base64.getMimeDecoder().decode(sb.toString());
+            XMLSignatureInput output = new XMLSignatureInput(decodedBytes);
+            output.setSecureValidation(secureValidation);
+            return output;
+        } catch (ParserConfigurationException e) {
+            throw new TransformationException(e, "c14n.Canonicalizer.Exception");
+        } catch (SAXException e) {
+            throw new TransformationException(e, "SAX exception");
         }
     }
 
-    void traverseElement(org.w3c.dom.Element node, StringBuilder sb) {
+    void traverseElement(Element node, StringBuilder sb) {
         Node sibling = node.getFirstChild();
         while (sibling != null) {
             switch (sibling.getNodeType()) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,10 +32,9 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 /**
- * Implements the <CODE>http://www.w3.org/TR/2001/REC-xml-c14n-20010315</CODE>
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformC14N extends TransformSpi {
 
@@ -44,7 +43,7 @@
         Transforms.TRANSFORM_C14N_OMIT_COMMENTS;
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return TransformC14N.implementedTransformURI;
@@ -54,12 +53,14 @@
         XMLSignatureInput input, OutputStream os, Transform transformObject
     ) throws CanonicalizationException {
         Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments();
+        c14n.setSecureValidation(secureValidation);
         if (os != null) {
             c14n.setWriter(os);
         }
         byte[] result = null;
         result = c14n.engineCanonicalize(input);
         XMLSignatureInput output = new XMLSignatureInput(result);
+        output.setSecureValidation(secureValidation);
         if (os != null) {
             output.setOutputStream(os);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,10 +32,9 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 /**
- * Implements the <CODE>http://www.w3.org/2006/12/xml-c14n11</CODE>
+ * Implements the {@code http://www.w3.org/2006/12/xml-c14n11}
  * (C14N 1.1) transform.
  *
- * @author Sean Mullan
  */
 public class TransformC14N11 extends TransformSpi {
 
@@ -47,12 +46,14 @@
         XMLSignatureInput input, OutputStream os, Transform transform
     ) throws CanonicalizationException {
         Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments();
+        c14n.setSecureValidation(secureValidation);
         if (os != null) {
             c14n.setWriter(os);
         }
         byte[] result = null;
         result = c14n.engineCanonicalize(input);
         XMLSignatureInput output = new XMLSignatureInput(result);
+        output.setSecureValidation(secureValidation);
         if (os != null) {
             output.setOutputStream(os);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,10 +32,9 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 /**
- * Implements the <CODE>http://www.w3.org/2006/12/xml-c14n-11#WithComments</CODE>
+ * Implements the {@code http://www.w3.org/2006/12/xml-c14n-11#WithComments}
  * (C14N 1.1 With Comments) transform.
  *
- * @author Sean Mullan
  */
 public class TransformC14N11_WithComments extends TransformSpi {
 
@@ -48,6 +47,7 @@
     ) throws CanonicalizationException {
 
         Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments();
+        c14n.setSecureValidation(secureValidation);
         if (os != null) {
             c14n.setWriter(os);
         }
@@ -55,6 +55,7 @@
         byte[] result = null;
         result = c14n.engineCanonicalize(input);
         XMLSignatureInput output = new XMLSignatureInput(result);
+        output.setSecureValidation(secureValidation);
         if (os != null) {
             output.setOutputStream(os);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java	Tue Jun 19 16:33:07 2018 +0100
@@ -48,7 +48,7 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return implementedTransformURI;
@@ -79,18 +79,20 @@
 
             Canonicalizer20010315ExclOmitComments c14n =
                 new Canonicalizer20010315ExclOmitComments();
+            c14n.setSecureValidation(secureValidation);
             if (os != null) {
                 c14n.setWriter(os);
             }
             byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
 
             XMLSignatureInput output = new XMLSignatureInput(result);
+            output.setSecureValidation(secureValidation);
             if (os != null) {
                 output.setOutputStream(os);
             }
             return output;
         } catch (XMLSecurityException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,10 +36,9 @@
 import org.w3c.dom.Element;
 
 /**
- * Implements the <CODE>http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments</CODE>
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformC14NExclusiveWithComments extends TransformSpi {
 
@@ -49,7 +48,7 @@
 
     /**
      * Method engineGetURI
-     *@inheritDoc
+     *{@inheritDoc}
      *
      */
     protected String engineGetURI() {
@@ -82,15 +81,17 @@
 
             Canonicalizer20010315ExclWithComments c14n =
                 new Canonicalizer20010315ExclWithComments();
+            c14n.setSecureValidation(secureValidation);
             if (os != null) {
                 c14n.setWriter(os);
             }
             byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
             XMLSignatureInput output = new XMLSignatureInput(result);
+            output.setSecureValidation(secureValidation);
 
             return output;
         } catch (XMLSecurityException ex) {
-            throw new CanonicalizationException("empty", ex);
+            throw new CanonicalizationException(ex);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,10 +32,9 @@
 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 /**
- * Implements the <CODE>http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments</CODE>
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformC14NWithComments extends TransformSpi {
 
@@ -43,17 +42,18 @@
     public static final String implementedTransformURI =
         Transforms.TRANSFORM_C14N_WITH_COMMENTS;
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetURI() {
         return implementedTransformURI;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected XMLSignatureInput enginePerformTransform(
         XMLSignatureInput input, OutputStream os, Transform transformObject
     ) throws CanonicalizationException {
 
         Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments();
+        c14n.setSecureValidation(secureValidation);
         if (os != null) {
             c14n.setWriter(os);
         }
@@ -61,6 +61,7 @@
         byte[] result = null;
         result = c14n.engineCanonicalize(input);
         XMLSignatureInput output = new XMLSignatureInput(result);
+        output.setSecureValidation(secureValidation);
         if (os != null) {
             output.setOutputStream(os);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,10 +36,9 @@
 import org.w3c.dom.Node;
 
 /**
- * Implements the <CODE>http://www.w3.org/2000/09/xmldsig#enveloped-signature</CODE>
+ * Implements the {@code http://www.w3.org/2000/09/xmldsig#enveloped-signature}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformEnvelopedSignature extends TransformSpi {
 
@@ -50,14 +49,14 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return implementedTransformURI;
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected XMLSignatureInput enginePerformTransform(
         XMLSignatureInput input, OutputStream os, Transform transformObject
@@ -136,7 +135,7 @@
                 return -1;
             }
             return 1;
-            //return !XMLUtils.isDescendantOrSelf(exclude,n);
+            //return !XMLUtils.isDescendantOrSelf(exclude, n);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java	Tue Jun 19 16:33:07 2018 +0100
@@ -44,10 +44,9 @@
 /**
  * Class TransformXPath
  *
- * Implements the <CODE>http://www.w3.org/TR/1999/REC-xpath-19991116</CODE>
+ * Implements the {@code http://www.w3.org/TR/1999/REC-xpath-19991116}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  * @see <a href="http://www.w3.org/TR/1999/REC-xpath-19991116">XPath</a>
  *
  */
@@ -59,7 +58,7 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return implementedTransformURI;
@@ -67,7 +66,7 @@
 
     /**
      * Method enginePerformTransform
-     * @inheritDoc
+     * {@inheritDoc}
      * @param input
      *
      * @throws TransformationException
@@ -96,14 +95,14 @@
 
                 throw new TransformationException("xml.WrongContent", exArgs);
             }
-            Node xpathnode = xpathElement.getChildNodes().item(0);
-            String str = XMLUtils.getStrFromNode(xpathnode);
-            input.setNeedsToBeExpanded(needsCircumvent(str));
+            Node xpathnode = xpathElement.getFirstChild();
             if (xpathnode == null) {
                 throw new DOMException(
                     DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath"
                 );
             }
+            String str = XMLUtils.getStrFromNode(xpathnode);
+            input.setNeedsToBeExpanded(needsCircumvent(str));
 
             XPathFactory xpathFactory = XPathFactory.newInstance();
             XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
@@ -111,7 +110,7 @@
             input.setNodeSet(true);
             return input;
         } catch (DOMException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 
@@ -120,7 +119,7 @@
      * @return true if needs to be circumvent for bug.
      */
     private boolean needsCircumvent(String str) {
-        return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1);
+        return str.indexOf("namespace") != -1 || str.indexOf("name()") != -1;
     }
 
     static class XPathNodeFilter implements NodeFilter {
@@ -151,7 +150,7 @@
                 Object[] eArgs = {currentNode};
                 throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e);
             } catch (Exception e) {
-                Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())};
+                Object[] eArgs = {currentNode, currentNode.getNodeType()};
                 throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e);
             }
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java	Tue Jun 19 16:33:07 2018 +0100
@@ -66,7 +66,7 @@
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return implementedTransformURI;
@@ -74,7 +74,7 @@
 
     /**
      * Method enginePerformTransform
-     * @inheritDoc
+     * {@inheritDoc}
      * @param input
      *
      * @throws TransformationException
@@ -83,9 +83,9 @@
         XMLSignatureInput input, OutputStream os, Transform transformObject
     ) throws TransformationException {
         try {
-            List<NodeList> unionNodes = new ArrayList<NodeList>();
-            List<NodeList> subtractNodes = new ArrayList<NodeList>();
-            List<NodeList> intersectNodes = new ArrayList<NodeList>();
+            List<NodeList> unionNodes = new ArrayList<>();
+            List<NodeList> subtractNodes = new ArrayList<>();
+            List<NodeList> intersectNodes = new ArrayList<>();
 
             Element[] xpathElements =
                 XMLUtils.selectNodes(
@@ -139,21 +139,21 @@
             input.setNodeSet(true);
             return input;
         } catch (TransformerException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (DOMException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (CanonicalizationException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (InvalidCanonicalizerException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (XMLSecurityException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (SAXException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (IOException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         } catch (ParserConfigurationException ex) {
-            throw new TransformationException("empty", ex);
+            throw new TransformationException(ex);
         }
     }
 }
@@ -208,7 +208,7 @@
     public int isNodeIncludeDO(Node n, int level) {
         int result = 1;
         if (hasSubtractFilter) {
-            if ((inSubtract == -1) || (level <= inSubtract)) {
+            if (inSubtract == -1 || level <= inSubtract) {
                 if (inList(n, subtractNodes)) {
                     inSubtract = level;
                 } else {
@@ -220,7 +220,7 @@
             }
         }
         if (result != -1 && hasIntersectFilter
-            && ((inIntersect == -1) || (level <= inIntersect))) {
+            && (inIntersect == -1 || level <= inIntersect)) {
             if (!inList(n, intersectNodes)) {
                 inIntersect = -1;
                 result = 0;
@@ -236,13 +236,13 @@
             return 1;
         }
         if (hasUnionFilter) {
-            if ((inUnion == -1) && inList(n, unionNodes)) {
+            if (inUnion == -1 && inList(n, unionNodes)) {
                 inUnion = level;
             }
             if (inUnion != -1) {
                 return 1;
             }
-            result=0;
+            result = 0;
         }
 
         return result;
@@ -282,7 +282,7 @@
     }
 
     private static Set<Node> convertNodeListToSet(List<NodeList> l) {
-        Set<Node> result = new HashSet<Node>();
+        Set<Node> result = new HashSet<>();
         for (NodeList rootNodes : l) {
             int length = rootNodes.getLength();
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,7 +33,6 @@
 /**
  * Class TransformXPointer
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformXPointer extends TransformSpi {
 
@@ -42,7 +41,7 @@
         Transforms.TRANSFORM_XPOINTER;
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     protected String engineGetURI() {
         return implementedTransformURI;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,6 +25,7 @@
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
 
 import javax.xml.XMLConstants;
@@ -49,10 +50,9 @@
 /**
  * Class TransformXSLT
  *
- * Implements the <CODE>http://www.w3.org/TR/1999/REC-xslt-19991116</CODE>
+ * Implements the {@code http://www.w3.org/TR/1999/REC-xslt-19991116}
  * transform.
  *
- * @author Christian Geuer-Pollmann
  */
 public class TransformXSLT extends TransformSpi {
 
@@ -60,17 +60,17 @@
     public static final String implementedTransformURI =
         Transforms.TRANSFORM_XSLT;
 
-    static final String XSLTSpecNS              = "http://www.w3.org/1999/XSL/Transform";
+    static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform";
     static final String defaultXSLTSpecNSprefix = "xslt";
-    static final String XSLTSTYLESHEET          = "stylesheet";
+    static final String XSLTSTYLESHEET = "stylesheet";
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(TransformXSLT.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(TransformXSLT.class);
 
     /**
      * Method engineGetURI
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     protected String engineGetURI() {
         return implementedTransformURI;
@@ -101,8 +101,6 @@
              * attempt to convert it to octets (apply Canonical XML]) as described
              * in the Reference Processing Model (section 4.3.3.2).
              */
-            Source xmlSource =
-                new StreamSource(new ByteArrayInputStream(input.getBytes()));
             Source stylesheet;
 
             /*
@@ -114,15 +112,16 @@
              * so we convert the stylesheet to byte[] and use this as input stream
              */
             {
-                ByteArrayOutputStream os = new ByteArrayOutputStream();
-                Transformer transformer = tFactory.newTransformer();
-                DOMSource source = new DOMSource(xsltElement);
-                StreamResult result = new StreamResult(os);
+                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
+                    Transformer transformer = tFactory.newTransformer();
+                    DOMSource source = new DOMSource(xsltElement);
+                    StreamResult result = new StreamResult(os);
 
-                transformer.transform(source, result);
+                    transformer.transform(source, result);
 
-                stylesheet =
-                    new StreamSource(new ByteArrayInputStream(os.toByteArray()));
+                    stylesheet =
+                        new StreamSource(new ByteArrayInputStream(os.toByteArray()));
+                }
             }
 
             Transformer transformer = tFactory.newTransformer(stylesheet);
@@ -135,33 +134,34 @@
             try {
                 transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n");
             } catch (Exception e) {
-                log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage());
+                LOG.warn("Unable to set Xalan line-separator property: " + e.getMessage());
             }
 
-            if (baos == null) {
-                ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
-                StreamResult outputTarget = new StreamResult(baos1);
+            try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
+                Source xmlSource = new StreamSource(is);
+                if (baos == null) {
+                    try (ByteArrayOutputStream baos1 = new ByteArrayOutputStream()) {
+                        StreamResult outputTarget = new StreamResult(baos1);
+                        transformer.transform(xmlSource, outputTarget);
+                        XMLSignatureInput output = new XMLSignatureInput(baos1.toByteArray());
+                        output.setSecureValidation(secureValidation);
+                        return output;
+                    }
+                }
+                StreamResult outputTarget = new StreamResult(baos);
+
                 transformer.transform(xmlSource, outputTarget);
-                return new XMLSignatureInput(baos1.toByteArray());
             }
-            StreamResult outputTarget = new StreamResult(baos);
-
-            transformer.transform(xmlSource, outputTarget);
             XMLSignatureInput output = new XMLSignatureInput((byte[])null);
+            output.setSecureValidation(secureValidation);
             output.setOutputStream(baos);
             return output;
         } catch (XMLSecurityException ex) {
-            Object exArgs[] = { ex.getMessage() };
-
-            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+            throw new TransformationException(ex);
         } catch (TransformerConfigurationException ex) {
-            Object exArgs[] = { ex.getMessage() };
-
-            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+            throw new TransformationException(ex);
         } catch (TransformerException ex) {
-            Object exArgs[] = { ex.getMessage() };
-
-            throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+            throw new TransformationException(ex);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-implementations of XML Signature transforms.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-the framework for XML Signature transforms.
-</P></BODY></HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,11 +35,10 @@
 /**
  * This Object serves as Content for the ds:Transforms for exclusive
  * Canonicalization.
- * <BR />
+ * <p></p>
  * It implements the {@link Element} interface
  * and can be used directly in a DOM tree.
  *
- * @author Christian Geuer-Pollmann
  */
 public class InclusiveNamespaces extends ElementProxy implements TransformParam {
 
@@ -82,27 +81,27 @@
 
         StringBuilder sb = new StringBuilder();
         for (String prefix : prefixList) {
-            if (prefix.equals("xmlns")) {
+            if ("xmlns".equals(prefix)) {
                 sb.append("#default ");
             } else {
-                sb.append(prefix).append(' ');
+                sb.append(prefix);
+                sb.append(" ");
             }
         }
 
-        this.constructionElement.setAttributeNS(
-            null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim());
+        setLocalAttribute(InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim());
     }
 
     /**
      * Constructor InclusiveNamespaces
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public InclusiveNamespaces(Element element, String BaseURI)
+    public InclusiveNamespaces(Element element, String baseURI)
         throws XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
     }
 
     /**
@@ -111,21 +110,21 @@
      * @return The Inclusive Namespace string
      */
     public String getInclusiveNamespaces() {
-        return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
+        return getLocalAttribute(InclusiveNamespaces._ATT_EC_PREFIXLIST);
     }
 
     /**
-     * Decodes the <code>inclusiveNamespaces</code> String and returns all
-     * selected namespace prefixes as a Set. The <code>#default</code>
+     * Decodes the {@code inclusiveNamespaces} String and returns all
+     * selected namespace prefixes as a Set. The {@code #default}
      * namespace token is represented as an empty namespace prefix
-     * (<code>"xmlns"</code>).
-     * <BR/>
-     * The String <code>inclusiveNamespaces=" xenc    ds #default"</code>
+     * ({@code "xmlns"}).
+     * <BR>
+     * The String {@code inclusiveNamespaces=" xenc    ds #default"}
      * is returned as a Set containing the following Strings:
      * <UL>
-     * <LI><code>xmlns</code></LI>
-     * <LI><code>xenc</code></LI>
-     * <LI><code>ds</code></LI>
+     * <LI>{@code xmlns}</LI>
+     * <LI>{@code xenc}</LI>
+     * <LI>{@code ds}</LI>
      * </UL>
      *
      * @param inclusiveNamespaces
@@ -134,7 +133,7 @@
     public static SortedSet<String> prefixStr2Set(String inclusiveNamespaces) {
         SortedSet<String> prefixes = new TreeSet<String>();
 
-        if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) {
+        if (inclusiveNamespaces == null || inclusiveNamespaces.length() == 0) {
             return prefixes;
         }
 
@@ -153,7 +152,7 @@
     /**
      * Method getBaseNamespace
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String getBaseNamespace() {
         return InclusiveNamespaces.ExclusiveCanonicalizationNamespace;
@@ -162,7 +161,7 @@
     /**
      * Method getBaseLocalName
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String getBaseLocalName() {
         return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,7 +36,6 @@
  * Implements the parameters for the <A
  * HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
  *
- * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
  */
 public class XPath2FilterContainer extends ElementProxy implements TransformParam {
@@ -90,24 +89,22 @@
     private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) {
         super(doc);
 
-        this.constructionElement.setAttributeNS(
-            null, XPath2FilterContainer._ATT_FILTER, filterType);
-        this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+        setLocalAttribute(XPath2FilterContainer._ATT_FILTER, filterType);
+        appendSelf(createText(xpath2filter));
     }
 
     /**
      * Constructor XPath2FilterContainer
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException {
+    private XPath2FilterContainer(Element element, String baseURI) throws XMLSecurityException {
 
-        super(element, BaseURI);
+        super(element, baseURI);
 
-        String filterStr =
-            this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER);
+        String filterStr = getLocalAttribute(XPath2FilterContainer._ATT_FILTER);
 
         if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
             && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
@@ -179,7 +176,7 @@
 
             if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
                 || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
-                || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){
+                || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))) {
                 throw new IllegalArgumentException("The type(" + i + ")=\"" + type
                                                    + "\" is illegal");
             }
@@ -197,47 +194,44 @@
      * Creates a XPath2FilterContainer from an existing Element; needed for verification.
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @return the filter
      *
      * @throws XMLSecurityException
      */
     public static XPath2FilterContainer newInstance(
-        Element element, String BaseURI
+        Element element, String baseURI
     ) throws XMLSecurityException {
-        return new XPath2FilterContainer(element, BaseURI);
+        return new XPath2FilterContainer(element, baseURI);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     * Returns {@code true} if the {@code Filter} attribute has value "intersect".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     * @return {@code true} if the {@code Filter} attribute has value "intersect".
      */
     public boolean isIntersect() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
         ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     * Returns {@code true} if the {@code Filter} attribute has value "subtract".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     * @return {@code true} if the {@code Filter} attribute has value "subtract".
      */
     public boolean isSubtract() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
         ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+     * Returns {@code true} if the {@code Filter} attribute has value "union".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+     * @return {@code true} if the {@code Filter} attribute has value "union".
      */
     public boolean isUnion() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
         ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
     }
 
@@ -255,18 +249,15 @@
      * Filter String. We must use this stupid hook to enable the here() function
      * to work.
      *
-     * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
      * @return the first Text node which contains information from the XPath 2 Filter String
      */
     public Node getXPathFilterTextNode() {
-
-        NodeList children = this.constructionElement.getChildNodes();
-        int length = children.getLength();
-
-        for (int i = 0; i < length; i++) {
-            if (children.item(i).getNodeType() == Node.TEXT_NODE) {
-                return children.item(i);
+        Node childNode = getElement().getFirstChild();
+        while (childNode != null) {
+            if (childNode.getNodeType() == Node.TEXT_NODE) {
+                return childNode;
             }
+            childNode = childNode.getNextSibling();
         }
 
         return null;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,17 +25,14 @@
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * Implements the parameters for the <A
  * HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
  *
- * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
  */
 public class XPath2FilterContainer04 extends ElementProxy implements TransformParam {
@@ -78,16 +75,15 @@
     private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) {
         super(doc);
 
-        this.constructionElement.setAttributeNS(
-            null, XPath2FilterContainer04._ATT_FILTER, filterType);
+        setLocalAttribute(XPath2FilterContainer04._ATT_FILTER, filterType);
 
-        if ((xpath2filter.length() > 2)
-            && (!Character.isWhitespace(xpath2filter.charAt(0)))) {
-            XMLUtils.addReturnToElement(this.constructionElement);
-            this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
-            XMLUtils.addReturnToElement(this.constructionElement);
+        if (xpath2filter.length() > 2
+            && !Character.isWhitespace(xpath2filter.charAt(0))) {
+            addReturnToSelf();
+            appendSelf(createText(xpath2filter));
+            addReturnToSelf();
         } else {
-            this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+            appendSelf(createText(xpath2filter));
         }
     }
 
@@ -95,16 +91,15 @@
      * Constructor XPath2FilterContainer04
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    private XPath2FilterContainer04(Element element, String BaseURI)
+    private XPath2FilterContainer04(Element element, String baseURI)
         throws XMLSecurityException {
 
-        super(element, BaseURI);
+        super(element, baseURI);
 
-        String filterStr =
-            this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER);
+        String filterStr = getLocalAttribute(XPath2FilterContainer04._ATT_FILTER);
 
         if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT)
             && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT)
@@ -166,47 +161,44 @@
      * Creates a XPath2FilterContainer04 from an existing Element; needed for verification.
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @return the instance
      *
      * @throws XMLSecurityException
      */
     public static XPath2FilterContainer04 newInstance(
-        Element element, String BaseURI
+        Element element, String baseURI
     ) throws XMLSecurityException {
-        return new XPath2FilterContainer04(element, BaseURI);
+        return new XPath2FilterContainer04(element, baseURI);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     * Returns {@code true} if the {@code Filter} attribute has value "intersect".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+     * @return {@code true} if the {@code Filter} attribute has value "intersect".
      */
     public boolean isIntersect() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer04._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
         ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     * Returns {@code true} if the {@code Filter} attribute has value "subtract".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+     * @return {@code true} if the {@code Filter} attribute has value "subtract".
      */
     public boolean isSubtract() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer04._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
         ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
     }
 
     /**
-     * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+     * Returns {@code true} if the {@code Filter} attribute has value "union".
      *
-     * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+     * @return {@code true} if the {@code Filter} attribute has value "union".
      */
     public boolean isUnion() {
-        return this.constructionElement.getAttributeNS(
-            null, XPath2FilterContainer04._ATT_FILTER
+        return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
         ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
     }
 
@@ -224,28 +216,26 @@
      * Filter String. We must use this stupid hook to enable the here() function
      * to work.
      *
-     * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
      * @return the first Text node which contains information from the XPath 2 Filter String
      */
     public Node getXPathFilterTextNode() {
-        NodeList children = this.constructionElement.getChildNodes();
-        int length = children.getLength();
-
-        for (int i = 0; i < length; i++) {
-            if (children.item(i).getNodeType() == Node.TEXT_NODE) {
-                return children.item(i);
+        Node childNode = getElement().getFirstChild();
+        while (childNode != null) {
+            if (childNode.getNodeType() == Node.TEXT_NODE) {
+                return childNode;
             }
+            childNode = childNode.getNextSibling();
         }
 
         return null;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String getBaseLocalName() {
         return XPath2FilterContainer04._TAG_XPATH2;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public final String getBaseNamespace() {
         return XPath2FilterContainer04.XPathFilter2NS;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,15 +27,14 @@
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
 import org.w3c.dom.Text;
 
 /**
  * This Object serves both as namespace prefix resolver and as container for
- * the <CODE>ds:XPath</CODE> Element. It implements the {@link org.w3c.dom.Element} interface
+ * the {@code ds:XPath} Element. It implements the {@link org.w3c.dom.Element} interface
  * and can be used directly in a DOM tree.
  *
- * @author Christian Geuer-Pollmann
  */
 public class XPathContainer extends SignatureElementProxy implements TransformParam {
 
@@ -49,33 +48,32 @@
     }
 
     /**
-     * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     * Sets the TEXT value of the {@code ds:XPath} Element.
      *
      * @param xpath
      */
     public void setXPath(String xpath) {
-        if (this.constructionElement.getChildNodes() != null) {
-            NodeList nl = this.constructionElement.getChildNodes();
-
-            for (int i = 0; i < nl.getLength(); i++) {
-                this.constructionElement.removeChild(nl.item(i));
-            }
+        Node childNode = getElement().getFirstChild();
+        while (childNode != null) {
+            Node nodeToBeRemoved = childNode;
+            childNode = childNode.getNextSibling();
+            getElement().removeChild(nodeToBeRemoved);
         }
 
-        Text xpathText = this.doc.createTextNode(xpath);
-        this.constructionElement.appendChild(xpathText);
+        Text xpathText = createText(xpath);
+        appendSelf(xpathText);
     }
 
     /**
-     * Returns the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     * Returns the TEXT value of the {@code ds:XPath} Element.
      *
-     * @return the TEXT value of the <CODE>ds:XPath</CODE> Element.
+     * @return the TEXT value of the {@code ds:XPath} Element.
      */
     public String getXPath() {
         return this.getTextFromTextChild();
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseLocalName() {
         return Constants._TAG_XPATH;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,7 +35,6 @@
  * Implements the parameters for a custom Transform which has a better performance
  * than the xfilter2.
  *
- * @author $Author: coheigea $
  */
 public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam {
 
@@ -87,52 +86,48 @@
         super(doc);
 
         if (includeSlashPolicy) {
-            this.constructionElement.setAttributeNS(
-                null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"
-            );
+            setLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true");
         } else {
-            this.constructionElement.setAttributeNS(
-                null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"
-            );
+            setLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false");
         }
 
-        if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) {
+        if (includeButSearch != null && includeButSearch.trim().length() > 0) {
             Element includeButSearchElem =
                 ElementProxy.createElementForFamily(
                     doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH
                 );
 
             includeButSearchElem.appendChild(
-                this.doc.createTextNode(indentXPathText(includeButSearch))
+                createText(indentXPathText(includeButSearch))
             );
-            XMLUtils.addReturnToElement(this.constructionElement);
-            this.constructionElement.appendChild(includeButSearchElem);
+            addReturnToSelf();
+            appendSelf(includeButSearchElem);
         }
 
-        if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) {
+        if (excludeButSearch != null && excludeButSearch.trim().length() > 0) {
             Element excludeButSearchElem =
                 ElementProxy.createElementForFamily(
                     doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH
                 );
 
             excludeButSearchElem.appendChild(
-                this.doc.createTextNode(indentXPathText(excludeButSearch)));
+                createText(indentXPathText(excludeButSearch)));
 
-            XMLUtils.addReturnToElement(this.constructionElement);
-            this.constructionElement.appendChild(excludeButSearchElem);
+            addReturnToSelf();
+            appendSelf(excludeButSearchElem);
         }
 
-        if ((exclude != null) && (exclude.trim().length() > 0)) {
+        if (exclude != null && exclude.trim().length() > 0) {
             Element excludeElem =
                 ElementProxy.createElementForFamily(
                    doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE);
 
-            excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude)));
-            XMLUtils.addReturnToElement(this.constructionElement);
-            this.constructionElement.appendChild(excludeElem);
+            excludeElem.appendChild(createText(indentXPathText(exclude)));
+            addReturnToSelf();
+            appendSelf(excludeElem);
         }
 
-        XMLUtils.addReturnToElement(this.constructionElement);
+        addReturnToSelf();
     }
 
     /**
@@ -142,7 +137,7 @@
      * @return the string with enters
      */
     static String indentXPathText(String xp) {
-        if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) {
+        if (xp.length() > 2 && !Character.isWhitespace(xp.charAt(0))) {
             return "\n" + xp + "\n";
         }
         return xp;
@@ -152,12 +147,12 @@
      * Constructor XPathFilterCHGPContainer
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    private XPathFilterCHGPContainer(Element element, String BaseURI)
+    private XPathFilterCHGPContainer(Element element, String baseURI)
         throws XMLSecurityException {
-        super(element, BaseURI);
+        super(element, baseURI);
     }
 
     /**
@@ -182,15 +177,15 @@
      * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification.
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      *
      * @throws XMLSecurityException
      * @return the created object.
      */
     public static XPathFilterCHGPContainer getInstance(
-        Element element, String BaseURI
+        Element element, String baseURI
     ) throws XMLSecurityException {
-        return new XPathFilterCHGPContainer(element, BaseURI);
+        return new XPathFilterCHGPContainer(element, baseURI);
     }
 
     /**
@@ -206,7 +201,7 @@
 
         Element xElem =
             XMLUtils.selectNode(
-                this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+                getElement().getFirstChild(), this.getBaseNamespace(), type, 0
             );
 
         return XMLUtils.getFullTextChildrenFromElement(xElem);
@@ -245,8 +240,7 @@
      * @return the string
      */
     public boolean getIncludeSlashPolicy() {
-        return this.constructionElement.getAttributeNS(
-            null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
+        return getLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
     }
 
     /**
@@ -265,7 +259,7 @@
         }
 
         return XMLUtils.selectNodeText(
-            this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+            getFirstChild(), this.getBaseNamespace(), type, 0
         );
     }
 
@@ -299,7 +293,7 @@
     /**
      * Method getBaseLocalName
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public final String getBaseLocalName() {
         return XPathFilterCHGPContainer._TAG_XPATHCHGP;
@@ -308,7 +302,7 @@
     /**
      * Method getBaseNamespace
      *
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public final String getBaseNamespace() {
         return TRANSFORM_XPATHFILTERCHGP;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,12 +39,10 @@
  * Optimized code. (raw version taken from oreilly.jonathan.util,
  * and currently org.apache.xerces.ds.util.Base64)
  *
- * @author Raul Benito(Of the xerces copy, and little adaptations).
- * @author Anli Shundi
- * @author Christian Geuer-Pollmann
  * @see <A HREF="ftp://ftp.isi.edu/in-notes/rfc2045.txt">RFC 2045</A>
  * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode
  */
+@Deprecated
 public class Base64 {
 
     /** Field BASE64DEFAULTLENGTH */
@@ -105,9 +103,9 @@
      * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
      * returns eventually longer arrays because of the leading sign-bit.
      *
-     * @param big <code>BigInteger<code> to be converted
-     * @param bitlen <code>int<code> the desired length in bits of the representation
-     * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+     * @param big {@code BigInteger} to be converted
+     * @param bitlen {@code int} the desired length in bits of the representation
+     * @return a byte array with {@code bitlen} bits of {@code big}
      */
     static final byte[] getBytes(BigInteger big, int bitlen) {
 
@@ -120,8 +118,8 @@
 
         byte[] bigBytes = big.toByteArray();
 
-        if (((big.bitLength() % 8) != 0)
-            && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+        if (big.bitLength() % 8 != 0
+            && big.bitLength() / 8 + 1 == bitlen / 8) {
             return bigBytes;
         }
 
@@ -129,7 +127,7 @@
         int startSrc = 0;    // no need to skip anything
         int bigLen = bigBytes.length;    //valid length of the string
 
-        if ((big.bitLength() % 8) == 0) {    // correct values
+        if (big.bitLength() % 8 == 0) {    // correct values
             startSrc = 1;    // skip sign bit
 
             bigLen--;    // valid length of the string
@@ -144,7 +142,7 @@
     }
 
     /**
-     * Encode in Base64 the given <code>{@link BigInteger}<code>.
+     * Encode in Base64 the given {@code {@link BigInteger}}.
      *
      * @param big
      * @return String with Base64 encoding
@@ -154,17 +152,17 @@
     }
 
     /**
-     * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
+     * Returns a byte-array representation of a {@code {@link BigInteger}}.
      * No sign-bit is output.
      *
-     * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
+     * <b>N.B.:</B> {@code {@link BigInteger}}'s toByteArray
      * returns eventually longer arrays because of the leading sign-bit.
      *
-     * @param big <code>BigInteger<code> to be converted
-     * @param bitlen <code>int<code> the desired length in bits of the representation
-     * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+     * @param big {@code BigInteger} to be converted
+     * @param bitlen {@code int} the desired length in bits of the representation
+     * @return a byte array with {@code bitlen} bits of {@code big}
      */
-    public static final  byte[] encode(BigInteger big, int bitlen) {
+    public static final byte[] encode(BigInteger big, int bitlen) {
 
         //round bitlen
         bitlen = ((bitlen + 7) >> 3) << 3;
@@ -175,8 +173,8 @@
 
         byte[] bigBytes = big.toByteArray();
 
-        if (((big.bitLength() % 8) != 0)
-            && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+        if (big.bitLength() % 8 != 0
+            && big.bitLength() / 8 + 1 == bitlen / 8) {
             return bigBytes;
         }
 
@@ -184,7 +182,7 @@
         int startSrc = 0;    // no need to skip anything
         int bigLen = bigBytes.length;    //valid length of the string
 
-        if ((big.bitLength() % 8) == 0) {    // correct values
+        if (big.bitLength() % 8 == 0) {    // correct values
             startSrc = 1;    // skip sign bit
 
             bigLen--;    // valid length of the string
@@ -211,15 +209,14 @@
     }
 
     /**
-     * Method decodeBigIntegerFromText
-     *
-     * @param text
-     * @return the biginter obtained from the text node
+     * Decode a base 64 string into a {@link BigInteger}
+     * @param base64str Base 64 encoded string.
+     * @return a decoded BigInteger
      * @throws Base64DecodingException
      */
-    public static final BigInteger decodeBigIntegerFromText(Text text)
-        throws Base64DecodingException {
-        return new BigInteger(1, Base64.decode(text.getData()));
+    public static BigInteger decodeBigIntegerFromString(String base64str)
+            throws Base64DecodingException {
+        return new BigInteger(1, Base64.decode(base64str));
     }
 
     /**
@@ -246,8 +243,8 @@
     /**
      * Method decode
      *
-     * Takes the <CODE>Text</CODE> children of the Element and interprets
-     * them as input for the <CODE>Base64.decode()</CODE> function.
+     * Takes the {@code Text} children of the Element and interprets
+     * them as input for the {@code Base64.decode()} function.
      *
      * @param element
      * @return the byte obtained of the decoding the element
@@ -305,8 +302,8 @@
      * Encode a byte array and fold lines at the standard 76th character unless
      * ignore line breaks property is set.
      *
-     * @param binaryData <code>byte[]<code> to be base64 encoded
-     * @return the <code>String<code> with encoded data
+     * @param binaryData {@code byte[]} to be base64 encoded
+     * @return the {@code String} with encoded data
      */
     public static final String encode(byte[] binaryData) {
         return XMLUtils.ignoreLineBreaks()
@@ -328,11 +325,9 @@
         throws IOException, Base64DecodingException {
 
         byte[] retBytes = null;
-        UnsyncByteArrayOutputStream baos = null;
+        UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
         try {
-            baos = new UnsyncByteArrayOutputStream();
             String line;
-
             while (null != (line = reader.readLine())) {
                 byte[] bytes = decode(line);
                 baos.write(bytes);
@@ -345,12 +340,12 @@
         return retBytes;
     }
 
-    protected static final boolean isWhiteSpace(byte octect) {
-        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
+    protected static final boolean isWhiteSpace(byte octet) {
+        return octet == 0x20 || octet == 0xd || octet == 0xa || octet == 0x9;
     }
 
-    protected static final boolean isPad(byte octect) {
-        return (octect == PAD);
+    protected static final boolean isPad(byte octet) {
+        return octet == PAD;
     }
 
     /**
@@ -363,11 +358,11 @@
      * Encode a byte array in Base64 format and return an optionally
      * wrapped line.
      *
-     * @param binaryData <code>byte[]</code> data to be encoded
-     * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4.
-     * @return a <code>String</code> with encoded data
+     * @param binaryData {@code byte[]} data to be encoded
+     * @param length {@code int} length of wrapped lines; No wrapping if less than 4.
+     * @return a {@code String} with encoded data
      */
-    public static final String  encode(byte[] binaryData,int length) {
+    public static final String  encode(byte[] binaryData, int length) {
         if (length < 4) {
             length = Integer.MAX_VALUE;
         }
@@ -381,14 +376,14 @@
             return "";
         }
 
-        long fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+        long fewerThan24bits = lengthDataBits % ((long) TWENTYFOURBITGROUP);
         int numberTriplets = (int) (lengthDataBits / TWENTYFOURBITGROUP);
         int numberQuartet = fewerThan24bits != 0L ? numberTriplets + 1 : numberTriplets;
         int quartesPerLine = length / 4;
         int numberLines = (numberQuartet - 1) / quartesPerLine;
         char encodedData[] = null;
 
-        encodedData = new char[numberQuartet * 4 + numberLines];
+        encodedData = new char[numberQuartet * 4 + numberLines * 2];
 
         byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
         int encodedIndex = 0;
@@ -401,8 +396,8 @@
                 b2 = binaryData[dataIndex++];
                 b3 = binaryData[dataIndex++];
 
-                l  = (byte)(b2 & 0x0f);
-                k  = (byte)(b1 & 0x03);
+                l = (byte)(b2 & 0x0f);
+                k = (byte)(b1 & 0x03);
 
                 byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0);
 
@@ -417,6 +412,7 @@
 
                 i++;
             }
+            encodedData[encodedIndex++] = 0xd;
             encodedData[encodedIndex++] = 0xa;
         }
 
@@ -425,8 +421,8 @@
             b2 = binaryData[dataIndex++];
             b3 = binaryData[dataIndex++];
 
-            l  = (byte)(b2 & 0x0f);
-            k  = (byte)(b1 & 0x03);
+            l = (byte)(b2 & 0x0f);
+            k = (byte)(b1 & 0x03);
 
             byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
 
@@ -510,7 +506,7 @@
             //should be divisible by four
         }
 
-        int numberQuadruple = (len / FOURBYTE);
+        int numberQuadruple = len / FOURBYTE;
 
         if (numberQuadruple == 0) {
             return new byte[0];
@@ -529,7 +525,7 @@
         //first last bits.
         b1 = base64Alphabet[base64Data[dataIndex++]];
         b2 = base64Alphabet[base64Data[dataIndex++]];
-        if ((b1==-1) || (b2==-1)) {
+        if (b1 == -1 || b2 == -1) {
              //if found "no data" just return null
             throw new Base64DecodingException("decoding.general");
         }
@@ -538,7 +534,7 @@
         byte d3, d4;
         b3 = base64Alphabet[d3 = base64Data[dataIndex++]];
         b4 = base64Alphabet[d4 = base64Data[dataIndex++]];
-        if ((b3 == -1) || (b4 == -1) ) {
+        if (b3 == -1 || b4 == -1) {
             //Check if they are PAD characters
             if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
                 if ((b2 & 0xf) != 0) { //last 4 bits should be zero
@@ -573,10 +569,7 @@
             b3 = base64Alphabet[base64Data[dataIndex++]];
             b4 = base64Alphabet[base64Data[dataIndex++]];
 
-            if ((b1 == -1) ||
-                (b2 == -1) ||
-                (b3 == -1) ||
-                (b4 == -1)) {
+            if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) {
                 //if found "no data" just return null
                 throw new Base64DecodingException("decoding.general");
             }
@@ -600,7 +593,7 @@
         throws Base64DecodingException, IOException {
         byte[] bytes = new byte[base64Data.length()];
         int len = getBytesInternal(base64Data, bytes);
-        decode(bytes,os,len);
+        decode(bytes, os, len);
     }
 
     /**
@@ -613,7 +606,7 @@
      */
     public static final void decode(byte[] base64Data, OutputStream os)
         throws Base64DecodingException, IOException {
-        decode(base64Data,os,-1);
+        decode(base64Data, os, -1);
     }
 
     protected static final void decode(byte[] base64Data, OutputStream os, int len)
@@ -628,7 +621,7 @@
             //should be divisible by four
         }
 
-        int numberQuadruple = (len / FOURBYTE);
+        int numberQuadruple = len / FOURBYTE;
 
         if (numberQuadruple == 0) {
             return;
@@ -641,28 +634,25 @@
         int dataIndex = 0;
 
         //the begin
-        for (i=numberQuadruple - 1; i > 0; i--) {
+        for (i = numberQuadruple - 1; i > 0; i--) {
             b1 = base64Alphabet[base64Data[dataIndex++]];
             b2 = base64Alphabet[base64Data[dataIndex++]];
             b3 = base64Alphabet[base64Data[dataIndex++]];
             b4 = base64Alphabet[base64Data[dataIndex++]];
-            if ((b1 == -1) ||
-                (b2 == -1) ||
-                (b3 == -1) ||
-                (b4 == -1) ) {
+            if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) {
                 //if found "no data" just return null
                 throw new Base64DecodingException("decoding.general");
             }
 
             os.write((byte)(b1 << 2 | b2 >> 4));
             os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf)));
-            os.write( (byte)(b3 << 6 | b4));
+            os.write((byte)(b3 << 6 | b4));
         }
         b1 = base64Alphabet[base64Data[dataIndex++]];
         b2 = base64Alphabet[base64Data[dataIndex++]];
 
         //  first last bits.
-        if ((b1 == -1) || (b2 == -1) ) {
+        if (b1 == -1 || b2 == -1) {
             //if found "no data" just return null
             throw new Base64DecodingException("decoding.general");
         }
@@ -670,7 +660,7 @@
         byte d3, d4;
         b3 = base64Alphabet[d3 = base64Data[dataIndex++]];
         b4 = base64Alphabet[d4 = base64Data[dataIndex++]];
-        if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters
+        if (b3 == -1 || b4 == -1) { //Check if they are PAD characters
             if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
                 if ((b2 & 0xf) != 0) { //last 4 bits should be zero
                     throw new Base64DecodingException("decoding.general");
@@ -707,7 +697,7 @@
         //byte decodedData[] = null;
         byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
 
-        int index=0;
+        int index = 0;
         byte[] data = new byte[4];
         int read;
         //the begin
@@ -748,7 +738,7 @@
         b2 = base64Alphabet[d2];
         b3 = base64Alphabet[d3];
         b4 = base64Alphabet[d4];
-        if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters
+        if (b3 == -1 || b4 == -1) { //Check if they are PAD characters
             if (isPad(d3) && isPad(d4)) {               //Two PAD e.g. 3c[Pad][Pad]
                 if ((b2 & 0xf) != 0) { //last 4 bits should be zero
                     throw new Base64DecodingException("decoding.general");
@@ -777,7 +767,7 @@
      * remove WhiteSpace from MIME containing encoded Base64 data.
      *
      * @param data  the byte array of base64 data (with WS)
-     * @return      the new length
+     * @return the new length
      */
     protected static final int removeWhiteSpace(byte[] data) {
         if (data == null) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,208 +23,22 @@
 
 package com.sun.org.apache.xml.internal.security.utils;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
 /**
- * This class is extremely useful for loading resources and classes in a fault
+ * This class is extremely useful for loading classes in a fault
  * tolerant manner that works across different applications servers. Do not
  * touch this unless you're a grizzled classloading guru veteran who is going to
  * verify any change on 6 different application servers.
  */
 final class ClassLoaderUtils {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
 
     private ClassLoaderUtils() {
     }
 
     /**
-     * Load a given resource. <p/> This method will try to load the resource
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static URL getResource(String resourceName, Class<?> callingClass) {
-        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url =
-                Thread.currentThread().getContextClassLoader().getResource(
-                    resourceName.substring(1)
-                );
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (url == null) {
-            url = cluClassloader.getResource(resourceName);
-        }
-        if (url == null && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            url = cluClassloader.getResource(resourceName.substring(1));
-        }
-
-        if (url == null) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                url = cl.getResource(resourceName);
-            }
-        }
-
-        if (url == null) {
-            url = callingClass.getResource(resourceName);
-        }
-
-        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResource('/' + resourceName, callingClass);
-        }
-
-        return url;
-    }
-
-    /**
-     * Load a given resources. <p/> This method will try to load the resources
-     * using the following methods (in order):
-     * <ul>
-     * <li>From Thread.currentThread().getContextClassLoader()
-     * <li>From ClassLoaderUtil.class.getClassLoader()
-     * <li>callingClass.getClassLoader()
-     * </ul>
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static List<URL> getResources(String resourceName, Class<?> callingClass) {
-        List<URL> ret = new ArrayList<URL>();
-        Enumeration<URL> urls = new Enumeration<URL>() {
-            public boolean hasMoreElements() {
-                return false;
-            }
-            public URL nextElement() {
-                return null;
-            }
-
-        };
-        try {
-            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            //ignore
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls =
-                    Thread.currentThread().getContextClassLoader().getResources(
-                        resourceName.substring(1)
-                    );
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
-        if (cluClassloader == null) {
-            cluClassloader = ClassLoader.getSystemClassLoader();
-        }
-        if (!urls.hasMoreElements()) {
-            try {
-                urls = cluClassloader.getResources(resourceName);
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
-            //certain classloaders need it without the leading /
-            try {
-                urls = cluClassloader.getResources(resourceName.substring(1));
-            } catch (IOException e) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                }
-                // ignore
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            ClassLoader cl = callingClass.getClassLoader();
-
-            if (cl != null) {
-                try {
-                    urls = cl.getResources(resourceName);
-                } catch (IOException e) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                    }
-                    // ignore
-                }
-            }
-        }
-
-        if (!urls.hasMoreElements()) {
-            URL url = callingClass.getResource(resourceName);
-            if (url != null) {
-                ret.add(url);
-            }
-        }
-        while (urls.hasMoreElements()) {
-            ret.add(urls.nextElement());
-        }
-
-
-        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
-            return getResources('/' + resourceName, callingClass);
-        }
-        return ret;
-    }
-
-
-    /**
-     * This is a convenience method to load a resource as a stream. <p/> The
-     * algorithm used to find the resource is given in getResource()
-     *
-     * @param resourceName The name of the resource to load
-     * @param callingClass The Class object of the calling object
-     */
-    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
-        URL url = getResource(resourceName, callingClass);
-
-        try {
-            return (url != null) ? url.openStream() : null;
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            return null;
-        }
-    }
-
-    /**
-     * Load a class with a given name. <p/> It will try to load the class in the
+     * Load a class with a given name. <p></p> It will try to load the class in the
      * following order:
      * <ul>
      * <li>From Thread.currentThread().getContextClassLoader()
@@ -246,9 +60,7 @@
                 return cl.loadClass(className);
             }
         } catch (ClassNotFoundException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
             //ignore
         }
         return loadClass2(className, callingClass);
@@ -268,9 +80,7 @@
                     return callingClass.getClassLoader().loadClass(className);
                 }
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             throw ex;
         }
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,9 +29,8 @@
  * <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg">XML
  * Signature specification</A>.
  *
- * @author $Author: coheigea $
  */
-public class Constants {
+public final class Constants {
 
     /** Field configurationFile */
     public static final String configurationFile = "data/websig.conf";
@@ -41,9 +40,9 @@
 
     /** Field exceptionMessagesResourceBundleDir */
     public static final String exceptionMessagesResourceBundleDir =
-        "com/sun/org/apache/xml/internal/security/resource";
+        "com.sun.org.apache.xml.internal.security/resource";
 
-    /** Field exceptionMessagesResourceBundleBase is the location of the <CODE>ResourceBundle</CODE> */
+    /** Field exceptionMessagesResourceBundleBase is the location of the {@code ResourceBundle} */
     public static final String exceptionMessagesResourceBundleBase =
         exceptionMessagesResourceBundleDir + "/" + "xmlsecurity";
 
@@ -69,6 +68,9 @@
     /** The URL for more algorithms **/
     public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#";
 
+    /** The (newer) URL for more algorithms **/
+    public static final String XML_DSIG_NS_MORE_07_05 = "http://www.w3.org/2007/05/xmldsig-more#";
+
     /** The URI for XML spec*/
     public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
 
@@ -197,7 +199,7 @@
     public static final String _TAG_P = "P";
 
     /** Tag of Element Q **/
-    public static final String _TAG_Q   = "Q";
+    public static final String _TAG_Q = "Q";
 
     /** Tag of Element G **/
     public static final String _TAG_G = "G";
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,6 +25,7 @@
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.Map.Entry;
 
 import javax.xml.namespace.NamespaceContext;
 
@@ -37,7 +38,7 @@
  */
 public class DOMNamespaceContext implements NamespaceContext {
 
-    private Map<String, String> namespaceMap = new HashMap<String, String>();
+    private Map<String, String> namespaceMap = new HashMap<>();
 
     public DOMNamespaceContext(Node contextNode) {
         addNamespaces(contextNode);
@@ -48,10 +49,9 @@
     }
 
     public String getPrefix(String arg0) {
-        for (String key : namespaceMap.keySet()) {
-            String value = namespaceMap.get(key);
-            if (value.equals(arg0)) {
-                return key;
+        for (Entry<String, String> entry : namespaceMap.entrySet()) {
+            if (entry.getValue().equals(arg0)) {
+                return entry.getKey();
             }
         }
         return null;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,12 +27,11 @@
 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
 
 /**
- * @author raul
  *
  */
 public class DigesterOutputStream extends ByteArrayOutputStream {
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DigesterOutputStream.class);
 
     final MessageDigestAlgorithm mda;
 
@@ -43,25 +42,25 @@
         this.mda = mda;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(byte[] arg0) {
         write(arg0, 0, arg0.length);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(int arg0) {
         mda.update((byte)arg0);
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(byte[] arg0, int arg1, int arg2) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Pre-digested input:");
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Pre-digested input:");
             StringBuilder sb = new StringBuilder(arg2);
             for (int i = arg1; i < (arg1 + arg2); i++) {
                 sb.append((char)arg0[i]);
             }
-            log.log(java.util.logging.Level.FINE, sb.toString());
+            LOG.debug(sb.toString());
         }
         mda.update(arg0, arg1, arg2);
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**@deprecated*/
-@Deprecated
-public interface ElementChecker {
-    /**
-     * Check that the element is the one expect
-     *
-     * @throws XMLSecurityException
-     */
-    void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual)
-        throws XMLSecurityException;
-
-    boolean isNamespaceElement(Node el, String type, String ns);
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,90 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**@deprecated*/
-@Deprecated
-public abstract class ElementCheckerImpl implements ElementChecker {
-
-    public boolean isNamespaceElement(Node el, String type, String ns) {
-        if ((el == null) ||
-            ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){
-            return false;
-        }
-
-        return true;
-    }
-
-    /** A checker for DOM that interns NS */
-    public static class InternedNsChecker extends ElementCheckerImpl {
-        public void guaranteeThatElementInCorrectSpace(
-            ElementProxy expected, Element actual
-        ) throws XMLSecurityException {
-
-            String expectedLocalname = expected.getBaseLocalName();
-            String expectedNamespace = expected.getBaseNamespace();
-
-            String localnameIS = actual.getLocalName();
-            String namespaceIS = actual.getNamespaceURI();
-            if ((expectedNamespace != namespaceIS) ||
-                !expectedLocalname.equals(localnameIS)) {
-                Object exArgs[] = { namespaceIS + ":" + localnameIS,
-                                    expectedNamespace + ":" + expectedLocalname};
-                throw new XMLSecurityException("xml.WrongElement", exArgs);
-            }
-        }
-    }
-
-    /** A checker for DOM that interns NS */
-    public static class FullChecker extends ElementCheckerImpl {
-
-        public void guaranteeThatElementInCorrectSpace(
-            ElementProxy expected, Element actual
-        ) throws XMLSecurityException {
-            String expectedLocalname = expected.getBaseLocalName();
-            String expectedNamespace = expected.getBaseNamespace();
-
-            String localnameIS = actual.getLocalName();
-            String namespaceIS = actual.getNamespaceURI();
-            if ((!expectedNamespace.equals(namespaceIS)) ||
-                !expectedLocalname.equals(localnameIS) ) {
-                Object exArgs[] = { namespaceIS + ":" + localnameIS,
-                                    expectedNamespace + ":" + expectedLocalname};
-                throw new XMLSecurityException("xml.WrongElement", exArgs);
-            }
-        }
-    }
-
-    /** An empty checker if schema checking is used */
-    public static class EmptyChecker extends ElementCheckerImpl {
-        public void guaranteeThatElementInCorrectSpace(
-            ElementProxy expected, Element actual
-        ) throws XMLSecurityException {
-            // empty
-        }
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,9 +24,9 @@
 
 import java.math.BigInteger;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.Base64;
 import java.util.Map;
 
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
@@ -41,17 +41,19 @@
  */
 public abstract class ElementProxy {
 
-    protected static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ElementProxy.class.getName());
+    protected static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ElementProxy.class);
 
-    /** Field constructionElement */
-    protected Element constructionElement = null;
+    /**
+     * What XML element does this ElementProxy instance wrap?
+     */
+    private Element wrappedElement;
 
     /** Field baseURI */
-    protected String baseURI = null;
+    protected String baseURI;
 
     /** Field doc */
-    protected Document doc = null;
+    private Document wrappedDoc;
 
     /** Field prefixMappings */
     private static Map<String, String> prefixMappings = new ConcurrentHashMap<String, String>();
@@ -73,30 +75,26 @@
             throw new RuntimeException("Document is null");
         }
 
-        this.doc = doc;
-        this.constructionElement =
-            createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName());
+        this.wrappedDoc = doc;
+        this.wrappedElement = createElementForFamilyLocal(this.getBaseNamespace(), this.getBaseLocalName());
     }
 
     /**
      * Constructor ElementProxy
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public ElementProxy(Element element, String BaseURI) throws XMLSecurityException {
+    public ElementProxy(Element element, String baseURI) throws XMLSecurityException {
         if (element == null) {
             throw new XMLSecurityException("ElementProxy.nullElement");
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
-        }
+        LOG.debug("setElement(\"{}\", \"{}\")", element.getTagName(), baseURI);
 
-        this.doc = element.getOwnerDocument();
-        this.constructionElement = element;
-        this.baseURI = BaseURI;
+        setElement(element);
+        this.baseURI = baseURI;
 
         this.guaranteeThatElementInCorrectSpace();
     }
@@ -117,15 +115,16 @@
 
 
     protected Element createElementForFamilyLocal(
-        Document doc, String namespace, String localName
+        String namespace, String localName
     ) {
+        Document doc = getDocument();
         Element result = null;
         if (namespace == null) {
             result = doc.createElementNS(null, localName);
         } else {
             String baseName = this.getBaseNamespace();
             String prefix = ElementProxy.getDefaultPrefix(baseName);
-            if ((prefix == null) || (prefix.length() == 0)) {
+            if (prefix == null || prefix.length() == 0) {
                 result = doc.createElementNS(namespace, localName);
                 result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
             } else {
@@ -141,7 +140,7 @@
      * This method creates an Element in a given namespace with a given localname.
      * It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
      * a particular prefix is bound to that namespace.
-     * <BR />
+     * <p></p>
      * This method was refactored out of the constructor.
      *
      * @param doc
@@ -156,7 +155,7 @@
         if (namespace == null) {
             result = doc.createElementNS(null, localName);
         } else {
-            if ((prefix == null) || (prefix.length() == 0)) {
+            if (prefix == null || prefix.length() == 0) {
                 result = doc.createElementNS(namespace, localName);
                 result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
             } else {
@@ -172,31 +171,27 @@
      * Method setElement
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public void setElement(Element element, String BaseURI) throws XMLSecurityException {
+    public void setElement(Element element, String baseURI) throws XMLSecurityException {
         if (element == null) {
             throw new XMLSecurityException("ElementProxy.nullElement");
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
-        }
+        LOG.debug("setElement({}, \"{}\")", element.getTagName(), baseURI);
 
-        this.doc = element.getOwnerDocument();
-        this.constructionElement = element;
-        this.baseURI = BaseURI;
+        setElement(element);
+        this.baseURI = baseURI;
     }
 
-
     /**
      * Returns the Element which was constructed by the Object.
      *
      * @return the Element which was constructed by the Object.
      */
     public final Element getElement() {
-        return this.constructionElement;
+        return this.wrappedElement;
     }
 
     /**
@@ -208,20 +203,27 @@
 
         HelperNodeList nl = new HelperNodeList();
 
-        nl.appendChild(this.doc.createTextNode("\n"));
-        nl.appendChild(this.getElement());
-        nl.appendChild(this.doc.createTextNode("\n"));
+        nl.appendChild(createText("\n"));
+        nl.appendChild(getElement());
+        nl.appendChild(createText("\n"));
 
         return nl;
     }
 
+    protected Text createText(String text) {
+        return this.wrappedDoc.createTextNode(text);
+    }
+
     /**
      * Method getDocument
      *
      * @return the Document where this element is contained.
      */
     public Document getDocument() {
-        return this.doc;
+        if (wrappedDoc == null) {
+            wrappedDoc = XMLUtils.getOwnerDocument(wrappedElement);
+        }
+        return wrappedDoc;
     }
 
     /**
@@ -243,8 +245,8 @@
         String expectedLocalName = this.getBaseLocalName();
         String expectedNamespaceUri = this.getBaseNamespace();
 
-        String actualLocalName = this.constructionElement.getLocalName();
-        String actualNamespaceUri = this.constructionElement.getNamespaceURI();
+        String actualLocalName = getElement().getLocalName();
+        String actualNamespaceUri = getElement().getNamespaceURI();
 
         if(!expectedNamespaceUri.equals(actualNamespaceUri)
             && !expectedLocalName.equals(actualLocalName)) {
@@ -262,14 +264,25 @@
      */
     public void addBigIntegerElement(BigInteger bi, String localname) {
         if (bi != null) {
-            Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
+            Element e = XMLUtils.createElementInSignatureSpace(getDocument(), localname);
+
+            byte[] bytes = XMLUtils.getBytes(bi, bi.bitLength());
+            String encodedInt = Base64.getMimeEncoder().encodeToString(bytes);
+
+            Document doc = e.getOwnerDocument();
+            Text text = doc.createTextNode(encodedInt);
 
-            Base64.fillElementWithBigInteger(e, bi);
-            this.constructionElement.appendChild(e);
-            XMLUtils.addReturnToElement(this.constructionElement);
+            e.appendChild(text);
+
+            appendSelf(e);
+            addReturnToSelf();
         }
     }
 
+    protected void addReturnToSelf() {
+        XMLUtils.addReturnToElement(getElement());
+    }
+
     /**
      * Method addBase64Element
      *
@@ -278,11 +291,14 @@
      */
     public void addBase64Element(byte[] bytes, String localname) {
         if (bytes != null) {
-            Element e = Base64.encodeToElement(this.doc, localname, bytes);
+            Element el = XMLUtils.createElementInSignatureSpace(getDocument(), localname);
+            Text text = getDocument().createTextNode(Base64.getMimeEncoder().encodeToString(bytes));
 
-            this.constructionElement.appendChild(e);
+            el.appendChild(text);
+
+            appendSelf(el);
             if (!XMLUtils.ignoreLineBreaks()) {
-                this.constructionElement.appendChild(this.doc.createTextNode("\n"));
+                appendSelf(createText("\n"));
             }
         }
     }
@@ -294,12 +310,12 @@
      * @param localname
      */
     public void addTextElement(String text, String localname) {
-        Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
-        Text t = this.doc.createTextNode(text);
+        Element e = XMLUtils.createElementInSignatureSpace(getDocument(), localname);
+        Text t = createText(text);
 
-        e.appendChild(t);
-        this.constructionElement.appendChild(e);
-        XMLUtils.addReturnToElement(this.constructionElement);
+        appendOther(e, t);
+        appendSelf(e);
+        addReturnToSelf();
     }
 
     /**
@@ -310,12 +326,24 @@
     public void addBase64Text(byte[] bytes) {
         if (bytes != null) {
             Text t = XMLUtils.ignoreLineBreaks()
-                ? this.doc.createTextNode(Base64.encode(bytes))
-                : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
-            this.constructionElement.appendChild(t);
+                ? createText(Base64.getMimeEncoder().encodeToString(bytes))
+                : createText("\n" + Base64.getMimeEncoder().encodeToString(bytes) + "\n");
+            appendSelf(t);
         }
     }
 
+    protected void appendSelf(ElementProxy toAppend) {
+        getElement().appendChild(toAppend.getElement());
+    }
+
+    protected void appendSelf(Node toAppend) {
+        getElement().appendChild(toAppend);
+    }
+
+    protected void appendOther(Element parent, Node toAppend) {
+        parent.appendChild(toAppend);
+    }
+
     /**
      * Method addText
      *
@@ -323,9 +351,9 @@
      */
     public void addText(String text) {
         if (text != null) {
-            Text t = this.doc.createTextNode(text);
+            Text t = createText(text);
 
-            this.constructionElement.appendChild(t);
+            appendSelf(t);
         }
     }
 
@@ -335,35 +363,15 @@
      * @param localname
      * @param namespace
      * @return The biginteger contained in the given element
-     * @throws Base64DecodingException
      */
     public BigInteger getBigIntegerFromChildElement(
         String localname, String namespace
-    ) throws Base64DecodingException {
-        return Base64.decodeBigIntegerFromText(
+    ) {
+        return new BigInteger(1, Base64.getMimeDecoder().decode(
             XMLUtils.selectNodeText(
-                this.constructionElement.getFirstChild(), namespace, localname, 0
-            )
-        );
-    }
-
-    /**
-     * Method getBytesFromChildElement
-     * @deprecated
-     * @param localname
-     * @param namespace
-     * @return the bytes
-     * @throws XMLSecurityException
-     */
-    @Deprecated
-    public byte[] getBytesFromChildElement(String localname, String namespace)
-        throws XMLSecurityException {
-        Element e =
-            XMLUtils.selectNode(
-                this.constructionElement.getFirstChild(), namespace, localname, 0
-            );
-
-        return Base64.decode(e);
+                getFirstChild(), namespace, localname, 0
+            ).getNodeValue()
+        ));
     }
 
     /**
@@ -375,7 +383,7 @@
      */
     public String getTextFromChildElement(String localname, String namespace) {
         return XMLUtils.selectNode(
-                this.constructionElement.getFirstChild(),
+                getFirstChild(),
                 namespace,
                 localname,
                 0).getTextContent();
@@ -388,7 +396,7 @@
      * @throws XMLSecurityException
      */
     public byte[] getBytesFromTextChild() throws XMLSecurityException {
-        return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement));
+        return Base64.getMimeDecoder().decode(getTextFromTextChild());
     }
 
     /**
@@ -398,7 +406,7 @@
      *    element
      */
     public String getTextFromTextChild() {
-        return XMLUtils.getFullTextChildrenFromElement(this.constructionElement);
+        return XMLUtils.getFullTextChildrenFromElement(getElement());
     }
 
     /**
@@ -410,7 +418,7 @@
      */
     public int length(String namespace, String localname) {
         int number = 0;
-        Node sibling = this.constructionElement.getFirstChild();
+        Node sibling = getFirstChild();
         while (sibling != null) {
             if (localname.equals(sibling.getLocalName())
                 && namespace.equals(sibling.getNamespaceURI())) {
@@ -438,9 +446,9 @@
         throws XMLSecurityException {
         String ns;
 
-        if ((prefix == null) || (prefix.length() == 0)) {
+        if (prefix == null || prefix.length() == 0) {
             throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
-        } else if (prefix.equals("xmlns")) {
+        } else if ("xmlns".equals(prefix)) {
             throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
         } else if (prefix.startsWith("xmlns:")) {
             ns = prefix;//"xmlns:" + prefix.substring("xmlns:".length());
@@ -448,18 +456,18 @@
             ns = "xmlns:" + prefix;
         }
 
-        Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
+        Attr a = getElement().getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
 
         if (a != null) {
             if (!a.getNodeValue().equals(uri)) {
-                Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) };
+                Object exArgs[] = { ns, getElement().getAttributeNS(null, ns) };
 
                 throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs);
             }
             return;
         }
 
-        this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
+        getElement().setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
     }
 
     /**
@@ -474,6 +482,11 @@
     public static void setDefaultPrefix(String namespace, String prefix)
         throws XMLSecurityException {
         JavaUtils.checkRegisterPermission();
+        setNamespacePrefix(namespace, prefix);
+    }
+
+    private static void setNamespacePrefix(String namespace, String prefix)
+        throws XMLSecurityException {
         if (prefixMappings.containsValue(prefix)) {
             String storedPrefix = prefixMappings.get(namespace);
             if (!storedPrefix.equals(prefix)) {
@@ -496,14 +509,14 @@
      * This method registers the default prefixes.
      */
     public static void registerDefaultPrefixes() throws XMLSecurityException {
-        setDefaultPrefix("http://www.w3.org/2000/09/xmldsig#", "ds");
-        setDefaultPrefix("http://www.w3.org/2001/04/xmlenc#", "xenc");
-        setDefaultPrefix("http://www.w3.org/2009/xmlenc11#", "xenc11");
-        setDefaultPrefix("http://www.xmlsecurity.org/experimental#", "experimental");
-        setDefaultPrefix("http://www.w3.org/2002/04/xmldsig-filter2", "dsig-xpath-old");
-        setDefaultPrefix("http://www.w3.org/2002/06/xmldsig-filter2", "dsig-xpath");
-        setDefaultPrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
-        setDefaultPrefix(
+        setNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ds");
+        setNamespacePrefix("http://www.w3.org/2001/04/xmlenc#", "xenc");
+        setNamespacePrefix("http://www.w3.org/2009/xmlenc11#", "xenc11");
+        setNamespacePrefix("http://www.xmlsecurity.org/experimental#", "experimental");
+        setNamespacePrefix("http://www.w3.org/2002/04/xmldsig-filter2", "dsig-xpath-old");
+        setNamespacePrefix("http://www.w3.org/2002/06/xmldsig-filter2", "dsig-xpath");
+        setNamespacePrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
+        setNamespacePrefix(
             "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter", "xx"
         );
     }
@@ -518,4 +531,51 @@
         return prefixMappings.get(namespace);
     }
 
+    /**
+     * New value for the wrapped XML element that this object is a proxy for.
+     *
+     * @param elem  New element
+     *
+     * @see #getElement()
+     */
+    protected void setElement(Element elem) {
+        wrappedElement = elem;
+    }
+
+    /**
+     * Set a new value for the wrapped document that this object is a proxy for.
+     *
+     * @param doc New document object being wrapped.
+     *
+     * @see #getDocument()
+     */
+    protected void setDocument(Document doc) {
+        wrappedDoc = doc;
+    }
+
+    protected String getLocalAttribute(String attrName) {
+        return getElement().getAttributeNS(null, attrName);
+    }
+
+    protected void setLocalAttribute(String attrName, String value) {
+        getElement().setAttributeNS(null, attrName, value);
+    }
+
+    protected void setLocalIdAttribute(String attrName, String value) {
+
+        if (value != null) {
+            Attr attr = getDocument().createAttributeNS(null, attrName);
+            attr.setValue(value);
+            getElement().setAttributeNodeNS(attr);
+            getElement().setIdAttributeNode(attr, true);
+        }
+        else {
+            getElement().removeAttributeNS(null, attrName);
+        }
+    }
+
+    protected Node getFirstChild() {
+        return getElement().getFirstChild();
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,96 +22,7 @@
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-public class EncryptionConstants {
-    // Attributes that exist in XML Signature in the same way
-    /** Tag of Attr Algorithm **/
-    public static final String _ATT_ALGORITHM              = Constants._ATT_ALGORITHM;
-
-    /** Tag of Attr Id**/
-    public static final String _ATT_ID                     = Constants._ATT_ID;
-
-    /** Tag of Attr Target **/
-    public static final String _ATT_TARGET                 = Constants._ATT_TARGET;
-
-    /** Tag of Attr Type **/
-    public static final String _ATT_TYPE                   = Constants._ATT_TYPE;
-
-    /** Tag of Attr URI **/
-    public static final String _ATT_URI                    = Constants._ATT_URI;
-
-    // Attributes new in XML Encryption
-    /** Tag of Attr encoding **/
-    public static final String _ATT_ENCODING               = "Encoding";
-
-    /** Tag of Attr recipient **/
-    public static final String _ATT_RECIPIENT              = "Recipient";
-
-    /** Tag of Attr mimetype **/
-    public static final String _ATT_MIMETYPE               = "MimeType";
-
-    /** Tag of Element CarriedKeyName **/
-    public static final String _TAG_CARRIEDKEYNAME         = "CarriedKeyName";
-
-    /** Tag of Element CipherData **/
-    public static final String _TAG_CIPHERDATA             = "CipherData";
-
-    /** Tag of Element CipherReference **/
-    public static final String _TAG_CIPHERREFERENCE        = "CipherReference";
-
-    /** Tag of Element CipherValue **/
-    public static final String _TAG_CIPHERVALUE            = "CipherValue";
-
-    /** Tag of Element DataReference **/
-    public static final String _TAG_DATAREFERENCE          = "DataReference";
-
-    /** Tag of Element EncryptedData **/
-    public static final String _TAG_ENCRYPTEDDATA          = "EncryptedData";
-
-    /** Tag of Element EncryptedKey **/
-    public static final String _TAG_ENCRYPTEDKEY           = "EncryptedKey";
-
-    /** Tag of Element EncryptionMethod **/
-    public static final String _TAG_ENCRYPTIONMETHOD       = "EncryptionMethod";
-
-    /** Tag of Element EncryptionProperties **/
-    public static final String _TAG_ENCRYPTIONPROPERTIES   = "EncryptionProperties";
-
-    /** Tag of Element EncryptionProperty **/
-    public static final String _TAG_ENCRYPTIONPROPERTY     = "EncryptionProperty";
-
-    /** Tag of Element KeyReference **/
-    public static final String _TAG_KEYREFERENCE           = "KeyReference";
-
-    /** Tag of Element KeySize **/
-    public static final String _TAG_KEYSIZE                = "KeySize";
-
-    /** Tag of Element OAEPparams **/
-    public static final String _TAG_OAEPPARAMS             = "OAEPparams";
-
-    /** Tag of Element MGF **/
-    public static final String _TAG_MGF                    = "MGF";
-
-    /** Tag of Element ReferenceList **/
-    public static final String _TAG_REFERENCELIST          = "ReferenceList";
-
-    /** Tag of Element Transforms **/
-    public static final String _TAG_TRANSFORMS             = "Transforms";
-
-    /** Tag of Element AgreementMethod **/
-    public static final String _TAG_AGREEMENTMETHOD        = "AgreementMethod";
-
-    /** Tag of Element KA-Nonce **/
-    public static final String _TAG_KA_NONCE               = "KA-Nonce";
-
-    /** Tag of Element OriginatorKeyInfo **/
-    public static final String _TAG_ORIGINATORKEYINFO      = "OriginatorKeyInfo";
-
-    /** Tag of Element RecipientKeyInfo **/
-    public static final String _TAG_RECIPIENTKEYINFO       = "RecipientKeyInfo";
-
-    /** Field ENCRYPTIONSPECIFICATION_URL */
-    public static final String ENCRYPTIONSPECIFICATION_URL =
-        "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/";
+public final class EncryptionConstants {
 
     /** The namespace of the
      * <A HREF="http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/">
@@ -119,119 +30,6 @@
     public static final String EncryptionSpecNS =
         "http://www.w3.org/2001/04/xmlenc#";
 
-    /**
-     * The namespace of the XML Encryption 1.1 specification
-     */
-    public static final String EncryptionSpec11NS =
-        "http://www.w3.org/2009/xmlenc11#";
-
-    /** URI for content*/
-    public static final String TYPE_CONTENT                = EncryptionSpecNS + "Content";
-
-    /** URI for element*/
-    public static final String TYPE_ELEMENT                = EncryptionSpecNS + "Element";
-
-    /** URI for mediatype*/
-    public static final String TYPE_MEDIATYPE              =
-        "http://www.isi.edu/in-notes/iana/assignments/media-types/";
-
-    /** Block Encryption - REQUIRED TRIPLEDES */
-    public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES =
-        EncryptionConstants.EncryptionSpecNS + "tripledes-cbc";
-
-    /** Block Encryption - REQUIRED AES-128 */
-    public static final String ALGO_ID_BLOCKCIPHER_AES128 =
-        EncryptionConstants.EncryptionSpecNS + "aes128-cbc";
-
-    /** Block Encryption - REQUIRED AES-256 */
-    public static final String ALGO_ID_BLOCKCIPHER_AES256 =
-        EncryptionConstants.EncryptionSpecNS + "aes256-cbc";
-
-    /** Block Encryption - OPTIONAL AES-192 */
-    public static final String ALGO_ID_BLOCKCIPHER_AES192 =
-        EncryptionConstants.EncryptionSpecNS + "aes192-cbc";
-
-    /** Block Encryption - OPTIONAL AES-128-GCM */
-    public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM =
-        "http://www.w3.org/2009/xmlenc11#aes128-gcm";
-
-    /** Block Encryption - OPTIONAL AES-192-GCM */
-    public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM =
-        "http://www.w3.org/2009/xmlenc11#aes192-gcm";
-
-    /** Block Encryption - OPTIONAL AES-256-GCM */
-    public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM =
-        "http://www.w3.org/2009/xmlenc11#aes256-gcm";
-
-    /** Key Transport - REQUIRED RSA-v1.5*/
-    public static final String ALGO_ID_KEYTRANSPORT_RSA15 =
-        EncryptionConstants.EncryptionSpecNS + "rsa-1_5";
-
-    /** Key Transport - REQUIRED RSA-OAEP */
-    public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP =
-        EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p";
-
-    /** Key Transport - OPTIONAL RSA-OAEP_11 */
-    public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 =
-        EncryptionConstants.EncryptionSpec11NS + "rsa-oaep";
-
-    /** Key Agreement - OPTIONAL Diffie-Hellman */
-    public static final String ALGO_ID_KEYAGREEMENT_DH =
-        EncryptionConstants.EncryptionSpecNS + "dh";
-
-    /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */
-    public static final String ALGO_ID_KEYWRAP_TRIPLEDES =
-        EncryptionConstants.EncryptionSpecNS + "kw-tripledes";
-
-    /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */
-    public static final String ALGO_ID_KEYWRAP_AES128 =
-        EncryptionConstants.EncryptionSpecNS + "kw-aes128";
-
-    /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */
-    public static final String ALGO_ID_KEYWRAP_AES256 =
-        EncryptionConstants.EncryptionSpecNS + "kw-aes256";
-
-    /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */
-    public static final String ALGO_ID_KEYWRAP_AES192 =
-        EncryptionConstants.EncryptionSpecNS + "kw-aes192";
-
-    /** Message Authentication - RECOMMENDED XML Digital Signature */
-    public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE =
-        "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
-
-    /** Canonicalization - OPTIONAL Canonical XML with Comments */
-    public static final String ALGO_ID_C14N_WITHCOMMENTS =
-        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
-
-    /** Canonicalization - OPTIONAL Canonical XML (omits comments) */
-    public static final String ALGO_ID_C14N_OMITCOMMENTS =
-        "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
-
-    /** Encoding - REQUIRED base64 */
-    public static final String ALGO_ID_ENCODING_BASE64 =
-        "http://www.w3.org/2000/09/xmldsig#base64";
-
-    /** MGF1 with SHA-1 */
-    public static final String MGF1_SHA1 =
-        EncryptionConstants.EncryptionSpec11NS + "mgf1sha1";
-
-    /** MGF1 with SHA-224 */
-    public static final String MGF1_SHA224 =
-        EncryptionConstants.EncryptionSpec11NS + "mgf1sha224";
-
-    /** MGF1 with SHA-256 */
-    public static final String MGF1_SHA256 =
-        EncryptionConstants.EncryptionSpec11NS + "mgf1sha256";
-
-    /** MGF1 with SHA-384 */
-    public static final String MGF1_SHA384 =
-        EncryptionConstants.EncryptionSpec11NS + "mgf1sha384";
-
-    /** MGF1 with SHA-512 */
-    public static final String MGF1_SHA512 =
-        EncryptionConstants.EncryptionSpec11NS + "mgf1sha512";
-
-
     private EncryptionConstants() {
         // we don't allow instantiation
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.utils;
-
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * This is the base object for all objects which map directly to an Element from
- * the xenc spec.
- *
- * @author $Author: coheigea $
- */
-public abstract class EncryptionElementProxy extends ElementProxy {
-
-    /**
-     * Constructor EncryptionElementProxy
-     *
-     * @param doc
-     */
-    public EncryptionElementProxy(Document doc) {
-        super(doc);
-    }
-
-    /**
-     * Constructor EncryptionElementProxy
-     *
-     * @param element
-     * @param BaseURI
-     * @throws XMLSecurityException
-     */
-    public EncryptionElementProxy(Element element, String BaseURI)
-        throws XMLSecurityException {
-        super(element, BaseURI);
-    }
-
-    /** @inheritDoc */
-    public final String getBaseNamespace() {
-        return EncryptionConstants.EncryptionSpecNS;
-    }
-}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java	Tue Jun 19 16:33:07 2018 +0100
@@ -30,12 +30,11 @@
 import org.w3c.dom.NodeList;
 
 /**
- * @author Christian Geuer-Pollmann
  */
 public class HelperNodeList implements NodeList {
 
     /** Field nodes */
-    List<Node> nodes = new ArrayList<Node>();
+    List<Node> nodes = new ArrayList<>();
     boolean allNodesMustHaveSameParent = false;
 
     /**
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,7 +29,6 @@
 /**
  * The Internationalization (I18N) pack.
  *
- * @author Christian Geuer-Pollmann
  */
 public class I18n {
 
@@ -57,13 +56,13 @@
      * Method translate
      *
      * translates a message ID into an internationalized String, see alse
-     * <CODE>XMLSecurityException.getExceptionMEssage()</CODE>. The strings are
-     * stored in the <CODE>ResourceBundle</CODE>, which is identified in
-     * <CODE>exceptionMessagesResourceBundleBase</CODE>
+     * {@code XMLSecurityException.getExceptionMEssage()}. The strings are
+     * stored in the {@code ResourceBundle}, which is identified in
+     * {@code exceptionMessagesResourceBundleBase}
      *
      * @param message
-     * @param args is an <CODE>Object[]</CODE> array of strings which are inserted into
-     * the String which is retrieved from the <CODE>ResouceBundle</CODE>
+     * @param args is an {@code Object[]} array of strings which are inserted into
+     * the String which is retrieved from the {@code ResouceBundle}
      * @return message translated
      */
     public static String translate(String message, Object[] args) {
@@ -74,7 +73,7 @@
      * Method translate
      *
      * translates a message ID into an internationalized String, see also
-     * <CODE>XMLSecurityException.getExceptionMessage()</CODE>
+     * {@code XMLSecurityException.getExceptionMessage()}
      *
      * @param message
      * @return message translated
@@ -153,7 +152,7 @@
      * @param languageCode
      * @param countryCode
      */
-    public synchronized static void init(String languageCode, String countryCode) {
+    public static synchronized void init(String languageCode, String countryCode) {
         if (alreadyInitialized) {
             return;
         }
@@ -165,4 +164,17 @@
             );
         alreadyInitialized = true;
     }
+
+    /**
+     * Method init
+     * @param resourceBundle
+     */
+    public static synchronized void init(ResourceBundle resourceBundle) {
+        if (alreadyInitialized) {
+            return;
+        }
+
+        I18n.resourceBundle = resourceBundle;
+        alreadyInitialized = true;
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,41 +27,33 @@
 import org.xml.sax.SAXParseException;
 
 /**
- * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log
+ * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but LOG
  * the events.
  *
- * @author Christian Geuer-Pollmann
  */
 public class IgnoreAllErrorHandler implements ErrorHandler {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(IgnoreAllErrorHandler.class);
 
     /** Field throwExceptions */
-    private static final boolean warnOnExceptions = getProperty(
-            "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions");
+    private static final boolean warnOnExceptions =
+        getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions");
 
     /** Field throwExceptions           */
-    private static final boolean throwExceptions = getProperty(
-            "com.sun.org.apache.xml.internal.security.test.throw.exceptions");
+    private static final boolean throwExceptions =
+        getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions");
 
-    private static boolean getProperty(String name) {
+    private static boolean getProperty(final String name) {
         return java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction<Boolean>() {
-
-                    @Override
-                    public Boolean run() {
-                        return Boolean.getBoolean(name);
-                    }
-                });
+            (java.security.PrivilegedAction<Boolean>) () -> Boolean.getBoolean(name));
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     @Override
     public void warning(SAXParseException ex) throws SAXException {
         if (IgnoreAllErrorHandler.warnOnExceptions) {
-            log.log(java.util.logging.Level.WARNING, "", ex);
+            LOG.warn("", ex);
         }
         if (IgnoreAllErrorHandler.throwExceptions) {
             throw ex;
@@ -69,11 +61,11 @@
     }
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     @Override
     public void error(SAXParseException ex) throws SAXException {
         if (IgnoreAllErrorHandler.warnOnExceptions) {
-            log.log(java.util.logging.Level.SEVERE, "", ex);
+            LOG.error("", ex);
         }
         if (IgnoreAllErrorHandler.throwExceptions) {
             throw ex;
@@ -81,11 +73,11 @@
     }
 
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     @Override
     public void fatalError(SAXParseException ex) throws SAXException {
         if (IgnoreAllErrorHandler.warnOnExceptions) {
-            log.log(java.util.logging.Level.WARNING, "", ex);
+            LOG.warn("", ex);
         }
         if (IgnoreAllErrorHandler.throwExceptions) {
             throw ex;
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java	Tue Jun 19 16:33:07 2018 +0100
@@ -66,7 +66,7 @@
                 try {
                     xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
                 } catch (XPathFactoryConfigurationException ex) {
-                    throw new TransformerException("empty", ex);
+                    throw new TransformerException(ex);
                 }
             }
             XPath xpath = xpf.newXPath();
@@ -75,13 +75,13 @@
             try {
                 xpathExpression = xpath.compile(xpathStr);
             } catch (XPathExpressionException ex) {
-                throw new TransformerException("empty", ex);
+                throw new TransformerException(ex);
             }
         }
         try {
             return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET);
         } catch (XPathExpressionException ex) {
-            throw new TransformerException("empty", ex);
+            throw new TransformerException(ex);
         }
     }
 
@@ -100,7 +100,7 @@
                 try {
                     xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
                 } catch (XPathFactoryConfigurationException ex) {
-                    throw new TransformerException("empty", ex);
+                    throw new TransformerException(ex);
                 }
             }
             XPath xpath = xpf.newXPath();
@@ -109,14 +109,13 @@
             try {
                 xpathExpression = xpath.compile(xpathStr);
             } catch (XPathExpressionException ex) {
-                throw new TransformerException("empty", ex);
+                throw new TransformerException(ex);
             }
         }
         try {
-            Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN);
-            return result.booleanValue();
+            return (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN);
         } catch (XPathExpressionException ex) {
-            throw new TransformerException("empty", ex);
+            throw new TransformerException(ex);
         }
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,27 +22,24 @@
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.security.SecurityPermission;
 
 /**
  * A collection of different, general-purpose methods for JAVA-specific things
- * @author Christian Geuer-Pollmann
  */
-public class JavaUtils {
+public final class JavaUtils {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(JavaUtils.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(JavaUtils.class);
 
     private static final SecurityPermission REGISTER_PERMISSION =
-        new SecurityPermission(
-            "com.sun.org.apache.xml.internal.security.register");
+        new SecurityPermission("com.sun.org.apache.xml.internal.security.register");
 
     private JavaUtils() {
         // we don't allow instantiation
@@ -62,26 +59,16 @@
 
         byte refBytes[] = null;
 
-        FileInputStream fisRef = null;
-        UnsyncByteArrayOutputStream baos = null;
-        try {
-            fisRef = new FileInputStream(fileName);
-            baos = new UnsyncByteArrayOutputStream();
+        try (InputStream inputStream = Files.newInputStream(Paths.get(fileName));
+            UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream()) {
             byte buf[] = new byte[1024];
             int len;
 
-            while ((len = fisRef.read(buf)) > 0) {
+            while ((len = inputStream.read(buf)) > 0) {
                 baos.write(buf, 0, len);
             }
 
             refBytes = baos.toByteArray();
-        } finally {
-            if (baos != null) {
-                baos.close();
-            }
-            if (fisRef != null) {
-                fisRef.close();
-            }
         }
 
         return refBytes;
@@ -94,30 +81,14 @@
      * @param bytes
      */
     public static void writeBytesToFilename(String filename, byte[] bytes) {
-        FileOutputStream fos = null;
-        try {
-            if (filename != null && bytes != null) {
-                File f = new File(filename);
-
-                fos = new FileOutputStream(f);
-
-                fos.write(bytes);
-                fos.close();
-            } else {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed");
-                }
+        if (filename != null && bytes != null) {
+            try (OutputStream outputStream = Files.newOutputStream(Paths.get(filename))) {
+                outputStream.write(bytes);
+            } catch (IOException ex) {
+                LOG.debug(ex.getMessage(), ex);
             }
-        } catch (IOException ex) {
-            if (fos != null) {
-                try {
-                    fos.close();
-                } catch (IOException ioe) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe);
-                    }
-                }
-            }
+        } else {
+            LOG.debug("writeBytesToFilename got null byte[] pointed");
         }
     }
 
@@ -132,46 +103,20 @@
      * @throws IOException
      */
     public static byte[] getBytesFromStream(InputStream inputStream) throws IOException {
-        UnsyncByteArrayOutputStream baos = null;
-
-        byte[] retBytes = null;
-        try {
-            baos = new UnsyncByteArrayOutputStream();
+        try (UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream()) {
             byte buf[] = new byte[4 * 1024];
             int len;
-
             while ((len = inputStream.read(buf)) > 0) {
                 baos.write(buf, 0, len);
             }
-            retBytes = baos.toByteArray();
-        } finally {
-            baos.close();
-        }
-
-        return retBytes;
-    }
-
-    /**
-     * Throws a {@code SecurityException} if a security manager is installed
-     * and the caller is not allowed to register an implementation of an
-     * algorithm, transform, or other security sensitive XML Signature function.
-     *
-     * @throws SecurityException if a security manager is installed and the
-     *    caller has not been granted the
-     *    {@literal "com.sun.org.apache.xml.internal.security.register"}
-     *    {@code SecurityPermission}
-     */
-    public static void checkRegisterPermission() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            sm.checkPermission(REGISTER_PERMISSION);
+            return baos.toByteArray();
         }
     }
 
     /**
      * Converts an ASN.1 DSA value to a XML Signature DSA Value.
      *
-     * The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * The JCE DSA Signature algorithm creates ASN.1 encoded (r, s) value
      * pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
      * core BigInteger values.
      *
@@ -191,12 +136,11 @@
 
         byte rLength = asn1Bytes[3];
         int i;
-        for (i = rLength; i > 0 && asn1Bytes[4 + rLength - i] == 0; i--);
+        for (i = rLength; i > 0 && asn1Bytes[4 + rLength - i] == 0; i--); //NOPMD
 
         byte sLength = asn1Bytes[5 + rLength];
         int j;
-        for (j = sLength;
-             j > 0 && asn1Bytes[6 + rLength + sLength - j] == 0; j--);
+        for (j = sLength; j > 0 && asn1Bytes[6 + rLength + sLength - j] == 0; j--); //NOPMD
 
         if (i > size || asn1Bytes[4 + rLength] != 2 || j > size) {
             throw new IOException("Invalid ASN.1 format of DSA signature");
@@ -213,7 +157,7 @@
     /**
      * Converts an XML Signature DSA Value to a ASN.1 DSA value.
      *
-     * The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
+     * The JCE DSA Signature algorithm creates ASN.1 encoded (r, s) value
      * pairs (see section 2.2.2 of RFC 3279); the XML Signature requires the
      * core BigInteger values.
      *
@@ -232,7 +176,7 @@
         }
 
         int i;
-        for (i = size; i > 0 && xmldsigBytes[size - i] == 0; i--);
+        for (i = size; i > 0 && xmldsigBytes[size - i] == 0; i--); //NOPMD
 
         int j = i;
         if (xmldsigBytes[size - i] < 0) {
@@ -240,7 +184,7 @@
         }
 
         int k;
-        for (k = size; k > 0 && xmldsigBytes[totalSize - k] == 0; k--);
+        for (k = size; k > 0 && xmldsigBytes[totalSize - k] == 0; k--); //NOPMD
 
         int l = k;
         if (xmldsigBytes[totalSize - k] < 0) {
@@ -261,4 +205,21 @@
 
         return asn1Bytes;
     }
+
+    /**
+     * Throws a {@code SecurityException} if a security manager is installed
+     * and the caller is not allowed to register an implementation of an
+     * algorithm, transform, or other security sensitive XML Signature function.
+     *
+     * @throws SecurityException if a security manager is installed and the
+     *    caller has not been granted the
+     *    {@literal "com.sun.org.apache.xml.internal.security.register"}
+     *    {@code SecurityPermission}
+     */
+    public static void checkRegisterPermission() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(REGISTER_PERMISSION);
+        }
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java	Tue Jun 19 16:33:07 2018 +0100
@@ -72,7 +72,7 @@
      */
     public static String normalize(String dn, boolean toXml) {
         //if empty string
-        if ((dn == null) || dn.equals("")) {
+        if (dn == null || dn.equals("")) {
             return "";
         }
 
@@ -87,8 +87,8 @@
             for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) {
                 l += countQuotes(DN, j, k);
 
-                if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) {
-                    sb.append(parseRDN(DN.substring(i, k).trim(), toXml)).append(',');
+                if (k > 0 && DN.charAt(k - 1) != '\\' && (l % 2) == 0) {
+                    sb.append(parseRDN(DN.substring(i, k).trim(), toXml)).append(",");
 
                     i = k + 1;
                     l = 0;
@@ -120,8 +120,8 @@
         for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) {
             l += countQuotes(str, j, k);
 
-            if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
-                sb.append(parseATAV(trim(str.substring(i, k)), toXml)).append('+');
+            if (k > 0 && str.charAt(k - 1) != '\\' && (l % 2) == 0) {
+                sb.append(parseATAV(trim(str.substring(i, k)), toXml)).append("+");
 
                 i = k + 1;
                 l = 0;
@@ -144,7 +144,7 @@
     static String parseATAV(String str, boolean toXml) throws IOException {
         int i = str.indexOf('=');
 
-        if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) {
+        if (i == -1 || i > 0 && str.charAt(i - 1) == '\\') {
             return str;
         }
         String attrType = normalizeAT(str.substring(0, i));
@@ -198,8 +198,8 @@
                 c = (char) i;
 
                 //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253
-                if ((c == ',') || (c == '=') || (c == '+') || (c == '<')
-                    || (c == '>') || (c == '#') || (c == ';')) {
+                if (c == ',' || c == '=' || c == '+' || c == '<'
+                    || c == '>' || c == '#' || c == ';') {
                     sb.append('\\');
                 }
 
@@ -277,10 +277,10 @@
                 char c2 = (char) sr.read();
 
                 //65 (A) 97 (a)
-                if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102)))
-                    && (((c2 >= 48) && (c2 <= 57))
-                        || ((c2 >= 65) && (c2 <= 70))
-                        || ((c2 >= 97) && (c2 <= 102)))) {
+                if ((c1 >= 48 && c1 <= 57 || c1 >= 65 && c1 <= 70 || c1 >= 97 && c1 <= 102)
+                    && (c2 >= 48 && c2 <= 57
+                        || c2 >= 65 && c2 <= 70
+                        || c2 >= 97 && c2 <= 102)) {
                     char ch = (char) Byte.parseByte("" + c1 + c2, 16);
 
                     sb.append(ch);
@@ -417,7 +417,7 @@
         for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
             l += countQuotes(str, j, k);
 
-            if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
+            if (k > 0 && str.charAt(k - 1) != '\\' && (l % 2) == 0) {
                 sb.append(trim(str.substring(i, k))).append(replace);
 
                 i = k + 1;
@@ -463,8 +463,8 @@
         String trimed = str.trim();
         int i = str.indexOf(trimed) + trimed.length();
 
-        if ((str.length() > i) && trimed.endsWith("\\")
-            && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) {
+        if (str.length() > i && trimed.endsWith("\\")
+            && !trimed.endsWith("\\\\") && str.charAt(i) == ' ') {
             trimed = trimed + " ";
         }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,12 +29,11 @@
 /**
  * Class SignatureElementProxy
  *
- * @author Brent Putman (putmanb@georgetown.edu)
  */
 public abstract class Signature11ElementProxy extends ElementProxy {
 
     protected Signature11ElementProxy() {
-    };
+    }
 
     /**
      * Constructor Signature11ElementProxy
@@ -46,24 +45,23 @@
             throw new RuntimeException("Document is null");
         }
 
-        this.doc = doc;
-        this.constructionElement =
-            XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName());
+        setDocument(doc);
+        setElement(XMLUtils.createElementInSignature11Space(doc, this.getBaseLocalName()));
     }
 
     /**
      * Constructor Signature11ElementProxy
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public Signature11ElementProxy(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
 
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseNamespace() {
         return Constants.SignatureSpec11NS;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,12 +29,11 @@
 /**
  * Class SignatureElementProxy
  *
- * @author $Author: coheigea $
  */
 public abstract class SignatureElementProxy extends ElementProxy {
 
     protected SignatureElementProxy() {
-    };
+    }
 
     /**
      * Constructor SignatureElementProxy
@@ -46,24 +45,24 @@
             throw new RuntimeException("Document is null");
         }
 
-        this.doc = doc;
-        this.constructionElement =
-            XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName());
+        setDocument(doc);
+        setElement(XMLUtils.createElementInSignatureSpace(doc,
+                this.getBaseLocalName()));
     }
 
     /**
      * Constructor SignatureElementProxy
      *
      * @param element
-     * @param BaseURI
+     * @param baseURI
      * @throws XMLSecurityException
      */
-    public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException {
-        super(element, BaseURI);
+    public SignatureElementProxy(Element element, String baseURI) throws XMLSecurityException {
+        super(element, baseURI);
 
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String getBaseNamespace() {
         return Constants.SignatureSpecNS;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,12 +28,11 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 
 /**
- * @author raul
  *
  */
 public class SignerOutputStream extends ByteArrayOutputStream {
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(SignerOutputStream.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignerOutputStream.class);
 
     final SignatureAlgorithm sa;
 
@@ -44,7 +43,7 @@
         this.sa = sa;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(byte[] arg0)  {
         try {
             sa.update(arg0);
@@ -53,7 +52,7 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(int arg0) {
         try {
             sa.update((byte)arg0);
@@ -62,15 +61,15 @@
         }
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public void write(byte[] arg0, int arg1, int arg2) {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:");
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Canonicalized SignedInfo:");
             StringBuilder sb = new StringBuilder(arg2);
             for (int i = arg1; i < (arg1 + arg2); i++) {
                 sb.append((char)arg0[i]);
             }
-            log.log(java.util.logging.Level.FINE, sb.toString());
+            LOG.debug(sb.toString());
         }
         try {
             sa.update(arg0, arg1, arg2);
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -2,97 +2,84 @@
  * 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
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
  */
+
 package com.sun.org.apache.xml.internal.security.utils;
 
+import java.io.FilterOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 
-/**
- * A class that buffers without synchronizing its methods
- * @author raul
- */
-public class UnsyncBufferedOutputStream extends OutputStream {
-    static final int size = 8*1024;
-
-    private int pointer = 0;
-    private final OutputStream out;
-
-    private final byte[] buf;
+public class UnsyncBufferedOutputStream extends FilterOutputStream {
 
-    /**
-     * Creates a buffered output stream without synchronization
-     * @param out the outputstream to buffer
-     */
+    protected byte[] buffer;
+    protected int count;
+
     public UnsyncBufferedOutputStream(OutputStream out) {
-        buf = new byte[size];
-        this.out = out;
-    }
-
-    /** @inheritDoc */
-    public void write(byte[] arg0) throws IOException {
-        write(arg0, 0, arg0.length);
+        super(out);
+        buffer = new byte[8192];
     }
 
-    /** @inheritDoc */
-    public void write(byte[] arg0, int arg1, int len) throws IOException {
-        int newLen = pointer+len;
-        if (newLen > size) {
-            flushBuffer();
-            if (len > size) {
-                out.write(arg0, arg1,len);
-                return;
-            }
-            newLen = len;
+    public UnsyncBufferedOutputStream(OutputStream out, int size) {
+        super(out);
+        if (size <= 0) {
+            throw new IllegalArgumentException("size must be > 0");
         }
-        System.arraycopy(arg0, arg1, buf, pointer, len);
-        pointer = newLen;
+        buffer = new byte[size];
     }
 
-    private void flushBuffer() throws IOException {
-        if (pointer > 0) {
-            out.write(buf, 0, pointer);
-        }
-        pointer = 0;
-
-    }
-
-    /** @inheritDoc */
-    public void write(int arg0) throws IOException {
-        if (pointer >= size) {
-            flushBuffer();
-        }
-        buf[pointer++] = (byte)arg0;
-
-    }
-
-    /** @inheritDoc */
+    @Override
     public void flush() throws IOException {
-        flushBuffer();
+        flushInternal();
         out.flush();
     }
 
-    /** @inheritDoc */
-    public void close() throws IOException {
-        flush();
-        out.close();
+    @Override
+    public void write(byte[] bytes, int offset, int length) throws IOException {
+        if (length >= buffer.length) {
+            flushInternal();
+            out.write(bytes, offset, length);
+            return;
+        }
+
+        // flush the internal buffer first if we have not enough space left
+        if (length >= (buffer.length - count)) {
+            flushInternal();
+        }
+
+        // the length is always less than (internalBuffer.length - count) here so arraycopy is safe
+        System.arraycopy(bytes, offset, buffer, count, length);
+        count += length;
     }
 
+    @Override
+    public void write(int oneByte) throws IOException {
+        if (count == buffer.length) {
+            out.write(buffer, 0, count);
+            count = 0;
+        }
+        buffer[count++] = (byte) oneByte;
+    }
+
+    private void flushInternal() throws IOException {
+        if (count > 0) {
+            out.write(buffer, 0, count);
+            count = 0;
+        }
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,27 +22,30 @@
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
+import java.io.IOException;
 import java.io.OutputStream;
 
 /**
  * A simple Unsynced ByteArrayOutputStream
- * @author raul
  *
  */
 public class UnsyncByteArrayOutputStream extends OutputStream  {
 
+    // Maximum array size. Using same value as ArrayList in OpenJDK.
+    // Integer.MAX_VALUE doesn't work on some VMs, as some header values are reserved
+    private static final int VM_ARRAY_INDEX_MAX_VALUE = Integer.MAX_VALUE - 8;
     private static final int INITIAL_SIZE = 8192;
 
     private byte[] buf;
     private int size = INITIAL_SIZE;
-    private int pos = 0;
+    private int pos;
 
     public UnsyncByteArrayOutputStream() {
         buf = new byte[INITIAL_SIZE];
     }
 
     public void write(byte[] arg0) {
-        if ((Integer.MAX_VALUE - pos) < arg0.length) {
+        if ((VM_ARRAY_INDEX_MAX_VALUE - pos) < arg0.length) {
             throw new OutOfMemoryError();
         }
         int newPos = pos + arg0.length;
@@ -54,7 +57,7 @@
     }
 
     public void write(byte[] arg0, int arg1, int arg2) {
-        if ((Integer.MAX_VALUE - pos) < arg2) {
+        if ((VM_ARRAY_INDEX_MAX_VALUE - pos) < arg2) {
             throw new OutOfMemoryError();
         }
         int newPos = pos + arg2;
@@ -66,7 +69,7 @@
     }
 
     public void write(int arg0) {
-        if ((Integer.MAX_VALUE - pos) == 0) {
+        if (VM_ARRAY_INDEX_MAX_VALUE - pos == 0) {
             throw new OutOfMemoryError();
         }
         int newPos = pos + 1;
@@ -86,13 +89,26 @@
         pos = 0;
     }
 
+    /**
+     * Takes the contents of this stream and writes it to the output stream
+     * {@code out}.
+     *
+     * @param out
+     *            an OutputStream on which to write the contents of this stream.
+     * @throws IOException
+     *             if an error occurs while writing to {@code out}.
+     */
+    public void writeTo(OutputStream out) throws IOException {
+        out.write(buf, 0, pos);
+    }
+
     private void expandSize(int newPos) {
         int newSize = size;
         while (newPos > newSize) {
             newSize = newSize << 1;
             // Deal with overflow
             if (newSize < 0) {
-                newSize = Integer.MAX_VALUE;
+                newSize = VM_ARRAY_INDEX_MAX_VALUE;
             }
         }
         byte newBuf[] = new byte[newSize];
@@ -100,4 +116,4 @@
         buf = newBuf;
         size = newSize;
     }
-}
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/WeakObjectPool.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,118 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import java.lang.ref.WeakReference;
+import java.util.Collections;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingDeque;
+
+/**
+ * Abstract base class for pooling objects.  The two public methods are
+ * {@link #getObject()} and ({@link #repool(Object)}.  Objects are held through
+ * weak references so even objects that are not repooled are subject to garbage collection.
+ *
+ * Subclasses must implement the abstract {@link #createObject()}.
+ * <p>
+ *
+ * Internally, the pool is stored in a java.util.concurrent.LinkedBlockingDeque
+ * instance.
+ */
+public abstract class WeakObjectPool<T, E extends Throwable> {
+
+    private static final Integer MARKER_VALUE = Integer.MAX_VALUE;//once here rather than auto-box it?
+
+    /** created, available objects to be checked out to clients */
+    private final BlockingQueue<WeakReference<T>> available;
+
+    /**
+     * Synchronized, identity map of loaned out objects (WeakHashMap);
+     * use to ensure we repool only object originating from here
+     * and do it once.
+     */
+    private final Map<T, Integer> onLoan;
+
+    /**
+     * The lone constructor.
+     */
+    protected WeakObjectPool() {
+        //alternative implementations: ArrayBlockingQueue has a fixed size
+        //  PriorityBlockingQueue: requires a dummy comparator; less memory but more overhead
+        available = new LinkedBlockingDeque<WeakReference<T>>();
+        this.onLoan = Collections.synchronizedMap(new WeakHashMap<T, Integer>());
+    }
+
+    /**
+     * Called whenever a new pool object is desired; subclasses must implement.
+     *
+     * @return object of the type desired by the subclass
+     * @throws E Throwable's subclass
+     */
+    protected abstract T createObject() throws E;
+
+
+    /**
+     * Subclasses can subclass to return a more specific type.
+     *
+     * @return an object from the pool; will block until an object is available
+     * @throws E
+     */
+    public T getObject() throws E {
+        WeakReference<T> ref;
+        T retValue = null;
+        do {
+            //remove any stale entries as well
+            ref = available.poll();
+        } while (ref != null && (retValue = ref.get()) == null);
+
+        if (retValue == null) {
+            //empty pool; create & add new one
+            retValue = createObject();
+        }
+        onLoan.put(retValue, MARKER_VALUE);
+        return retValue;
+    }
+
+
+    /**
+     * Adds the given object to the pool, provided that the object
+     * was created by this pool.
+     *
+     * @param obj the object to return to the pool
+     * @return whether the object was successfully added as available
+     */
+    public boolean repool(T obj) {
+        if (obj != null && onLoan.containsKey(obj)) {
+            //synchronize to protect against a caller returning the same object again...
+            synchronized (obj) {
+                //...and check to see that it was removed
+                if (onLoan.remove(obj) != null) {
+                    return available.offer(new WeakReference<T>(obj));
+                }
+            }
+        }
+        return false;
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,6 +24,7 @@
 
 import java.io.IOException;
 import java.io.OutputStream;
+import java.math.BigInteger;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
@@ -32,6 +33,10 @@
 import java.util.List;
 import java.util.Set;
 
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
@@ -41,32 +46,25 @@
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
-import org.w3c.dom.ProcessingInstruction;
 import org.w3c.dom.Text;
 
 /**
  * DOM and XML accessibility and comfort functions.
  *
- * @author Christian Geuer-Pollmann
  */
-public class XMLUtils {
+public final class XMLUtils {
 
     private static boolean ignoreLineBreaks =
-        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
-            public Boolean run() {
-                return Boolean.valueOf(Boolean.getBoolean
-                    ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"));
-            }
-        }).booleanValue();
+        AccessController.doPrivileged(
+            (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"));
 
     private static volatile String dsPrefix = "ds";
     private static volatile String ds11Prefix = "dsig11";
     private static volatile String xencPrefix = "xenc";
     private static volatile String xenc11Prefix = "xenc11";
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static final java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XMLUtils.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLUtils.class);
 
 
     /**
@@ -123,7 +121,7 @@
 
     public static Element getNextElement(Node el) {
         Node node = el;
-        while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) {
+        while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
             node = node.getNextSibling();
         }
         return (Element)node;
@@ -136,7 +134,7 @@
      * @param com whether comments or not
      */
     public static void getSet(Node rootNode, Set<Node> result, Node exclude, boolean com) {
-        if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) {
+        if (exclude != null && isDescendantOrSelf(exclude, rootNode)) {
             return;
         }
         getSetRec(rootNode, result, exclude, com);
@@ -154,7 +152,8 @@
             Element el = (Element)rootNode;
             if (el.hasAttributes()) {
                 NamedNodeMap nl = el.getAttributes();
-                for (int i = 0;i < nl.getLength(); i++) {
+                int length = nl.getLength();
+                for (int i = 0; i < length; i++) {
                     result.add(nl.item(i));
                 }
             }
@@ -163,7 +162,7 @@
             for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
                 if (r.getNodeType() == Node.TEXT_NODE) {
                     result.add(r);
-                    while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) {
+                    while (r != null && r.getNodeType() == Node.TEXT_NODE) {
                         r = r.getNextSibling();
                     }
                     if (r == null) {
@@ -208,37 +207,31 @@
     public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) {
         try {
             if (addPreamble) {
-                os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8"));
+                os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
             }
 
             os.write(Canonicalizer.getInstance(
-                Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode)
+                Canonicalizer.ALGO_ID_C14N_PHYSICAL).canonicalizeSubtree(contextNode)
             );
         } catch (IOException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
         }
         catch (InvalidCanonicalizerException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
         } catch (CanonicalizationException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
         }
     }
 
     /**
-     * Serializes the <CODE>contextNode</CODE> into the OutputStream, <I>but
+     * Serializes the {@code contextNode} into the OutputStream, <I>but
      * suppresses all Exceptions</I>.
-     * <BR />
+     * <p></p>
      * NOTE: <I>This should only be used for debugging purposes,
      * NOT in a production environment; this method ignores all exceptions,
      * so you won't notice if something goes wrong. If you're asking what is to
      * be used in a production environment, simply use the code inside the
-     * <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
+     * {@code try{}} statement, but handle the Exceptions appropriately.</I>
      *
      * @param contextNode
      * @param os
@@ -249,19 +242,13 @@
                 Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode)
             );
         } catch (IOException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             // throw new RuntimeException(ex.getMessage());
         } catch (InvalidCanonicalizerException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             // throw new RuntimeException(ex.getMessage());
         } catch (CanonicalizationException ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
             // throw new RuntimeException(ex.getMessage());
         }
     }
@@ -298,7 +285,7 @@
             throw new RuntimeException("Document is null");
         }
 
-        if ((dsPrefix == null) || (dsPrefix.length() == 0)) {
+        if (dsPrefix == null || dsPrefix.length() == 0) {
             return doc.createElementNS(Constants.SignatureSpecNS, elementName);
         }
         return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName);
@@ -316,55 +303,13 @@
             throw new RuntimeException("Document is null");
         }
 
-        if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) {
+        if (ds11Prefix == null || ds11Prefix.length() == 0) {
             return doc.createElementNS(Constants.SignatureSpec11NS, elementName);
         }
         return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName);
     }
 
     /**
-     * Creates an Element in the XML Encryption specification namespace.
-     *
-     * @param doc the factory Document
-     * @param elementName the local name of the Element
-     * @return the Element
-     */
-    public static Element createElementInEncryptionSpace(Document doc, String elementName) {
-        if (doc == null) {
-            throw new RuntimeException("Document is null");
-        }
-
-        if ((xencPrefix == null) || (xencPrefix.length() == 0)) {
-            return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName);
-        }
-        return
-            doc.createElementNS(
-                EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName
-            );
-    }
-
-    /**
-     * Creates an Element in the XML Encryption 1.1 specification namespace.
-     *
-     * @param doc the factory Document
-     * @param elementName the local name of the Element
-     * @return the Element
-     */
-    public static Element createElementInEncryption11Space(Document doc, String elementName) {
-        if (doc == null) {
-            throw new RuntimeException("Document is null");
-        }
-
-        if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) {
-            return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName);
-        }
-        return
-            doc.createElementNS(
-                EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName
-            );
-    }
-
-    /**
      * Returns true if the element is in XML Signature namespace and the local
      * name equals the supplied one.
      *
@@ -401,43 +346,9 @@
     }
 
     /**
-     * Returns true if the element is in XML Encryption namespace and the local
-     * name equals the supplied one.
-     *
-     * @param element
-     * @param localName
-     * @return true if the element is in XML Encryption namespace and the local name
-     * equals the supplied one
-     */
-    public static boolean elementIsInEncryptionSpace(Element element, String localName) {
-        if (element == null){
-            return false;
-        }
-        return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
-            && element.getLocalName().equals(localName);
-    }
-
-    /**
-     * Returns true if the element is in XML Encryption 1.1 namespace and the local
-     * name equals the supplied one.
-     *
-     * @param element
-     * @param localName
-     * @return true if the element is in XML Encryption 1.1 namespace and the local name
-     * equals the supplied one
-     */
-    public static boolean elementIsInEncryption11Space(Element element, String localName) {
-        if (element == null){
-            return false;
-        }
-        return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI())
-            && element.getLocalName().equals(localName);
-    }
-
-    /**
      * This method returns the owner document of a particular node.
      * This method is necessary because it <I>always</I> returns a
-     * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
+     * {@link Document}. {@link Node#getOwnerDocument} returns {@code null}
      * if the {@link Node} is a {@link Document}.
      *
      * @param node
@@ -459,7 +370,7 @@
     /**
      * This method returns the first non-null owner document of the Nodes in this Set.
      * This method is necessary because it <I>always</I> returns a
-     * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
+     * {@link Document}. {@link Node#getOwnerDocument} returns {@code null}
      * if the {@link Node} is a {@link Document}.
      *
      * @param xpathNodeSet
@@ -496,7 +407,7 @@
      * @return the element.
      */
     public static Element createDSctx(Document doc, String prefix, String namespace) {
-        if ((prefix == null) || (prefix.trim().length() == 0)) {
+        if (prefix == null || prefix.trim().length() == 0) {
             throw new IllegalArgumentException("You must supply a prefix");
         }
 
@@ -540,11 +451,11 @@
      */
     public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
         if (xpathNodeSet == null) {
-            return new HashSet<Node>();
+            return new HashSet<>();
         }
 
         int length = xpathNodeSet.getLength();
-        Set<Node> set = new HashSet<Node>(length);
+        Set<Node> set = new HashSet<>(length);
 
         for (int i = 0; i < length; i++) {
             set.add(xpathNodeSet.item(i));
@@ -632,7 +543,7 @@
                 sibling = node.getFirstChild();
                 break;
             }
-            while ((sibling == null) && (parent != null)) {
+            while (sibling == null && parent != null) {
                 sibling = parent.getNextSibling();
                 parent = parent.getParentNode();
             }
@@ -691,29 +602,8 @@
      * @param number
      * @return nodes with the constrain
      */
-    public static Element selectXencNode(Node sibling, String nodeName, int number) {
-        while (sibling != null) {
-            if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())
-                && sibling.getLocalName().equals(nodeName)) {
-                if (number == 0){
-                    return (Element)sibling;
-                }
-                number--;
-            }
-            sibling = sibling.getNextSibling();
-        }
-        return null;
-    }
-
-
-    /**
-     * @param sibling
-     * @param nodeName
-     * @param number
-     * @return nodes with the constrain
-     */
     public static Text selectDsNodeText(Node sibling, String nodeName, int number) {
-        Node n = selectDsNode(sibling,nodeName,number);
+        Node n = selectDsNode(sibling, nodeName, number);
         if (n == null) {
             return null;
         }
@@ -731,7 +621,7 @@
      * @return nodes with the constrain
      */
     public static Text selectDs11NodeText(Node sibling, String nodeName, int number) {
-        Node n = selectDs11Node(sibling,nodeName,number);
+        Node n = selectDs11Node(sibling, nodeName, number);
         if (n == null) {
             return null;
         }
@@ -750,7 +640,7 @@
      * @return nodes with the constrain
      */
     public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) {
-        Node n = selectNode(sibling,uri,nodeName,number);
+        Node n = selectNode(sibling, uri, nodeName, number);
         if (n == null) {
             return null;
         }
@@ -807,7 +697,7 @@
      * @return nodes with the constraint
      */
     public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
-        List<Element> list = new ArrayList<Element>();
+        List<Element> list = new ArrayList<>();
         while (sibling != null) {
             if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
                 && sibling.getLocalName().equals(nodeName)) {
@@ -824,7 +714,7 @@
      * @return nodes with the constrain
      */
     public static Set<Node> excludeNodeFromSet(Node signatureElement, Set<Node> inputSet) {
-        Set<Node> resultSet = new HashSet<Node>();
+        Set<Node> resultSet = new HashSet<>();
         Iterator<Node> iterator = inputSet.iterator();
 
         while (iterator.hasNext()) {
@@ -859,9 +749,9 @@
 
             return sb.toString();
         } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
-            return ((Attr) xpathnode).getNodeValue();
+            return xpathnode.getNodeValue();
         } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
-            return ((ProcessingInstruction) xpathnode).getNodeValue();
+            return xpathnode.getNodeValue();
         }
 
         return null;
@@ -909,7 +799,7 @@
      * the empty string if the attribute value is empty.
      *
      * <p>This works around a limitation of the DOM
-     * <code>Element.getAttributeNode</code> method, which does not distinguish
+     * {@code Element.getAttributeNode} method, which does not distinguish
      * between an unspecified attribute and an attribute with a value of
      * "" (it returns "" for both cases).
      *
@@ -929,29 +819,33 @@
      * a matching Element has been found, just that no wrapping attack has been detected.
      */
     public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
-        Node startParent = startNode.getParentNode();
-        Node processedNode = null;
-        Element foundElement = null;
-
         String id = value.trim();
         if (!id.isEmpty() && id.charAt(0) == '#') {
             id = id.substring(1);
         }
 
+        Node startParent = null;
+        Node processedNode = null;
+        Element foundElement = null;
+        if (startNode != null) {
+            startParent = startNode.getParentNode();
+        }
+
         while (startNode != null) {
             if (startNode.getNodeType() == Node.ELEMENT_NODE) {
                 Element se = (Element) startNode;
 
                 NamedNodeMap attributes = se.getAttributes();
                 if (attributes != null) {
-                    for (int i = 0; i < attributes.getLength(); i++) {
+                    int length = attributes.getLength();
+                    for (int i = 0; i < length; i++) {
                         Attr attr = (Attr)attributes.item(i);
                         if (attr.isId() && id.equals(attr.getValue())) {
                             if (foundElement == null) {
                                 // Continue searching to find duplicates
                                 foundElement = attr.getOwnerElement();
                             } else {
-                                log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
+                                LOG.debug("Multiple elements with the same 'Id' attribute value!");
                                 return false;
                             }
                         }
@@ -990,24 +884,28 @@
     public static boolean protectAgainstWrappingAttack(
         Node startNode, Element knownElement, String value
     ) {
-        Node startParent = startNode.getParentNode();
-        Node processedNode = null;
-
         String id = value.trim();
         if (!id.isEmpty() && id.charAt(0) == '#') {
             id = id.substring(1);
         }
 
+        Node startParent = null;
+        Node processedNode = null;
+        if (startNode != null) {
+            startParent = startNode.getParentNode();
+        }
+
         while (startNode != null) {
             if (startNode.getNodeType() == Node.ELEMENT_NODE) {
                 Element se = (Element) startNode;
 
                 NamedNodeMap attributes = se.getAttributes();
                 if (attributes != null) {
-                    for (int i = 0; i < attributes.getLength(); i++) {
+                    int length = attributes.getLength();
+                    for (int i = 0; i < length; i++) {
                         Attr attr = (Attr)attributes.item(i);
                         if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) {
-                            log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
+                            LOG.debug("Multiple elements with the same 'Id' attribute value!");
                             return false;
                         }
                     }
@@ -1037,4 +935,68 @@
         return true;
     }
 
+    public static DocumentBuilder createDocumentBuilder(boolean validating)
+            throws ParserConfigurationException {
+        return createDocumentBuilder(validating, true);
+    }
+
+    // The current implementation does not throw a ParserConfigurationException.
+    // Kept here in case we create the DocumentBuilder inline again.
+    public static DocumentBuilder createDocumentBuilder(
+        boolean validating, boolean disAllowDocTypeDeclarations
+    ) throws ParserConfigurationException {
+        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+        dfactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
+        if (disAllowDocTypeDeclarations) {
+            dfactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+        }
+        dfactory.setValidating(validating);
+        dfactory.setNamespaceAware(true);
+        return dfactory.newDocumentBuilder();
+    }
+
+    /**
+     * Returns a byte-array representation of a {@code {@link BigInteger}}.
+     * No sign-bit is output.
+     *
+     * <b>N.B.:</B> {@code {@link BigInteger}}'s toByteArray
+     * returns eventually longer arrays because of the leading sign-bit.
+     *
+     * @param big {@code BigInteger} to be converted
+     * @param bitlen {@code int} the desired length in bits of the representation
+     * @return a byte array with {@code bitlen} bits of {@code big}
+     */
+    public static byte[] getBytes(BigInteger big, int bitlen) {
+
+        //round bitlen
+        bitlen = ((bitlen + 7) >> 3) << 3;
+
+        if (bitlen < big.bitLength()) {
+            throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
+        }
+
+        byte[] bigBytes = big.toByteArray();
+
+        if (big.bitLength() % 8 != 0
+            && big.bitLength() / 8 + 1 == bitlen / 8) {
+            return bigBytes;
+        }
+
+        // some copying needed
+        int startSrc = 0;    // no need to skip anything
+        int bigLen = bigBytes.length;    //valid length of the string
+
+        if (big.bitLength() % 8 == 0) {    // correct values
+            startSrc = 1;    // skip sign bit
+
+            bigLen--;    // valid length of the string
+        }
+
+        int startDst = bitlen / 8 - bigLen;    //pad with leading nulls
+        byte[] resizedBytes = new byte[bitlen / 8];
+
+        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
+
+        return resizedBytes;
+    }
 }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -38,12 +38,12 @@
             if (funcTableClass != null) {
                 xalanInstalled = true;
             }
-        } catch (Exception e) {
+        } catch (Exception e) { //NOPMD
             //ignore
         }
     }
 
-    protected synchronized static boolean isXalanInstalled() {
+    protected static synchronized boolean isXalanInstalled() {
         return xalanInstalled;
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java	Tue Jun 19 16:33:07 2018 +0100
@@ -48,14 +48,14 @@
  */
 public class XalanXPathAPI implements XPathAPI {
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(XalanXPathAPI.class);
 
-    private String xpathStr = null;
+    private String xpathStr;
 
-    private XPath xpath = null;
+    private XPath xpath;
 
-    private static FunctionTable funcTable = null;
+    private static FunctionTable funcTable;
 
     private static boolean installed;
 
@@ -111,7 +111,7 @@
         context = null;
     }
 
-    public synchronized static boolean isInstalled() {
+    public static synchronized boolean isInstalled() {
         return installed;
     }
 
@@ -150,14 +150,12 @@
         Class<?>[] classes = new Class<?>[]{String.class, SourceLocator.class, PrefixResolver.class, int.class,
                                       ErrorListener.class, FunctionTable.class};
         Object[] objects =
-            new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable};
+            new Object[]{str, null, prefixResolver, XPath.SELECT, null, funcTable};
         try {
             Constructor<?> constructor = XPath.class.getConstructor(classes);
             xpath = (XPath) constructor.newInstance(objects);
         } catch (Exception ex) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
-            }
+            LOG.debug(ex.getMessage(), ex);
         }
         if (xpath == null) {
             xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
@@ -165,18 +163,14 @@
         return xpath;
     }
 
-    private synchronized static void fixupFunctionTable() {
+    private static synchronized void fixupFunctionTable() {
         installed = false;
         if (new FunctionTable().functionAvailable("here")) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Here function already registered");
-            }
+            LOG.debug("Here function already registered");
             installed = true;
             return;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Registering Here function");
-        }
+        LOG.debug("Registering Here function");
         /**
          * Try to register our here() implementation as internal function.
          */
@@ -189,7 +183,7 @@
                 installed = true;
             }
         } catch (Exception ex) {
-            log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+            LOG.debug("Error installing function using the static installFunction method", ex);
         }
         if (!installed) {
             try {
@@ -200,17 +194,13 @@
                 installFunction.invoke(funcTable, params);
                 installed = true;
             } catch (Exception ex) {
-                log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+                LOG.debug("Error installing function using the static installFunction method", ex);
             }
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            if (installed) {
-                log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName()
-                          + " for XPath function 'here()' function in internal table");
-            } else {
-                log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName()
-                          + " for XPath function 'here()' function in internal table");
-            }
+        if (installed) {
+            LOG.debug("Registered class {} for XPath function 'here()' function in internal table", FuncHere.class.getName());
+        } else {
+            LOG.debug("Unable to register class {} for XPath function 'here()' function in internal table", FuncHere.class.getName());
         }
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-<HTML><HEAD></HEAD><BODY><P>
-general utility classes.
-</P></BODY></HTML>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ClassLoaderUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,84 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.utils.resolver;
+
+// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
+// modifiers changed to package-private. Make sure to integrate any future
+// changes to utils.ClassLoaderUtils to this file.
+final class ClassLoaderUtils {
+
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a class with a given name. <p></p> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            LOG.debug(e.getMessage(), e);
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            LOG.debug(ex.getMessage(), ex);
+            throw ex;
+        }
+    }
+}
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -42,12 +42,11 @@
  */
 public class ResourceResolver {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResourceResolver.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResourceResolver.class);
 
     /** these are the system-wide resolvers */
-    private static List<ResourceResolver> resolverList = new ArrayList<ResourceResolver>();
+    private static final List<ResourceResolver> resolverList = new ArrayList<>();
 
     /** Field resolverSpi */
     private final ResourceResolverSpi resolverSpi;
@@ -64,21 +63,7 @@
     /**
      * Method getInstance
      *
-     * @param uri
-     * @param baseURI
-     * @return the instance
-     *
-     * @throws ResourceResolverException
-     */
-    public static final ResourceResolver getInstance(Attr uri, String baseURI)
-        throws ResourceResolverException {
-        return getInstance(uri, baseURI, false);
-    }
-
-    /**
-     * Method getInstance
-     *
-     * @param uri
+     * @param uriAttr
      * @param baseURI
      * @param secureValidation
      * @return the instance
@@ -100,30 +85,26 @@
                 if (!resolver.resolverSpi.engineIsThreadSafe()) {
                     try {
                         @SuppressWarnings("deprecation")
-                        ResourceResolver tmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
+                        ResourceResolver tmp =
+                            new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
                         resolverTmp = tmp;
-                            ;
                     } catch (InstantiationException e) {
-                        throw new ResourceResolverException("", e, context.attr, context.baseUri);
+                        throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "");
                     } catch (IllegalAccessException e) {
-                        throw new ResourceResolverException("", e, context.attr, context.baseUri);
+                        throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "");
                     }
                 }
 
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE,
-                        "check resolvability by class " + resolverTmp.getClass().getName()
-                    );
-                }
+                LOG.debug("check resolvability by class {}", resolverTmp.getClass().getName());
 
-                if ((resolverTmp != null) && resolverTmp.canResolve(context)) {
+                if (resolverTmp != null && resolverTmp.canResolve(context)) {
                     // Check to see whether the Resolver is allowed
                     if (context.secureValidation
                         && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem
                             || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) {
                         Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() };
                         throw new ResourceResolverException(
-                            "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri
+                            "signature.Reference.ForbiddenResolver", exArgs, context.uriToResolve, context.baseUri
                         );
                     }
                     return resolverTmp;
@@ -131,10 +112,10 @@
             }
         }
 
-        Object exArgs[] = { ((context.uriToResolve != null)
-                ? context.uriToResolve : "null"), context.baseUri };
+        Object exArgs[] = { context.uriToResolve != null
+                ? context.uriToResolve : "null", context.baseUri };
 
-        throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri);
+        throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.uriToResolve, context.baseUri);
     }
 
     /**
@@ -150,7 +131,7 @@
     public static ResourceResolver getInstance(
         Attr uri, String baseURI, List<ResourceResolver> individualResolvers
     ) throws ResourceResolverException {
-        return getInstance(uri, baseURI, individualResolvers, false);
+        return getInstance(uri, baseURI, individualResolvers, true);
     }
 
     /**
@@ -167,12 +148,10 @@
     public static ResourceResolver getInstance(
         Attr uri, String baseURI, List<ResourceResolver> individualResolvers, boolean secureValidation
     ) throws ResourceResolverException {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE,
-                "I was asked to create a ResourceResolver and got "
-                + (individualResolvers == null ? 0 : individualResolvers.size())
-            );
-        }
+        LOG.debug(
+            "I was asked to create a ResourceResolver and got {}",
+            (individualResolvers == null ? 0 : individualResolvers.size())
+        );
 
         ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation);
 
@@ -182,10 +161,8 @@
                 ResourceResolver resolver = individualResolvers.get(i);
 
                 if (resolver != null) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        String currentClass = resolver.resolverSpi.getClass().getName();
-                        log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
-                    }
+                    String currentClass = resolver.resolverSpi.getClass().getName();
+                    LOG.debug("check resolvability by class {}", currentClass);
 
                     if (resolver.canResolve(context)) {
                         return resolver;
@@ -198,7 +175,7 @@
     }
 
     /**
-     * Registers a ResourceResolverSpi class. This method logs a warning if
+     * Registers a ResourceResolverSpi class. This method LOGs a warning if
      * the class cannot be registered.
      *
      * @param className the name of the ResourceResolverSpi class to be registered
@@ -210,16 +187,17 @@
         JavaUtils.checkRegisterPermission();
         try {
             Class<ResourceResolverSpi> resourceResolverClass =
-                (Class<ResourceResolverSpi>) Class.forName(className);
+                (Class<ResourceResolverSpi>)
+                ClassLoaderUtils.loadClass(className, ResourceResolver.class);
             register(resourceResolverClass, false);
         } catch (ClassNotFoundException e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+            LOG.warn("Error loading resolver " + className + " disabling it");
         }
     }
 
     /**
      * Registers a ResourceResolverSpi class at the beginning of the provider
-     * list. This method logs a warning if the class cannot be registered.
+     * list. This method LOGs a warning if the class cannot be registered.
      *
      * @param className the name of the ResourceResolverSpi class to be registered
      * @throws SecurityException if a security manager is installed and the
@@ -230,15 +208,16 @@
         JavaUtils.checkRegisterPermission();
         try {
             Class<ResourceResolverSpi> resourceResolverClass =
-                (Class<ResourceResolverSpi>) Class.forName(className);
+                (Class<ResourceResolverSpi>)
+                ClassLoaderUtils.loadClass(className, ResourceResolver.class);
             register(resourceResolverClass, true);
         } catch (ClassNotFoundException e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+            LOG.warn("Error loading resolver " + className + " disabling it");
         }
     }
 
     /**
-     * Registers a ResourceResolverSpi class. This method logs a warning if the class
+     * Registers a ResourceResolverSpi class. This method LOGs a warning if the class
      * cannot be registered.
      * @param className
      * @param start
@@ -252,14 +231,14 @@
             ResourceResolverSpi resourceResolverSpi = className.newInstance();
             register(resourceResolverSpi, start);
         } catch (IllegalAccessException e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+            LOG.warn("Error loading resolver " + className + " disabling it");
         } catch (InstantiationException e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+            LOG.warn("Error loading resolver " + className + " disabling it");
         }
     }
 
     /**
-     * Registers a ResourceResolverSpi instance. This method logs a warning if the class
+     * Registers a ResourceResolverSpi instance. This method LOGs a warning if the class
      * cannot be registered.
      * @param resourceResolverSpi
      * @param start
@@ -275,9 +254,7 @@
                 resolverList.add(new ResourceResolver(resourceResolverSpi));
             }
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Registered resolver: " + resourceResolverSpi.toString());
-        }
+        LOG.debug("Registered resolver: {}", resourceResolverSpi.toString());
     }
 
     /**
@@ -293,15 +270,6 @@
     }
 
     /**
-     * @deprecated New clients should use {@link #resolve(Attr, String, boolean)}
-     */
-    @Deprecated
-    public XMLSignatureInput resolve(Attr uri, String baseURI)
-        throws ResourceResolverException {
-        return resolve(uri, baseURI, true);
-    }
-
-    /**
      * Method resolve
      *
      * @param uri
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,21 +23,19 @@
 package com.sun.org.apache.xml.internal.security.utils.resolver;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import org.w3c.dom.Attr;
 
 /**
  * This Exception is thrown if something related to the
  * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong.
  *
- * @author $Author: coheigea $
  */
 public class ResourceResolverException extends XMLSecurityException {
 
     private static final long serialVersionUID = 1L;
 
-    private Attr uri = null;
+    private String uri;
 
-    private String baseURI = null;
+    private String baseURI;
 
     /**
      * Constructor ResourceResolverException
@@ -46,7 +44,7 @@
      * @param uri
      * @param baseURI
      */
-    public ResourceResolverException(String msgID, Attr uri, String baseURI) {
+    public ResourceResolverException(String msgID, String uri, String baseURI) {
         super(msgID);
 
         this.uri = uri;
@@ -61,7 +59,7 @@
      * @param uri
      * @param baseURI
      */
-    public ResourceResolverException(String msgID, Object exArgs[], Attr uri,
+    public ResourceResolverException(String msgID, Object exArgs[], String uri,
                                      String baseURI) {
         super(msgID, exArgs);
 
@@ -72,42 +70,54 @@
     /**
      * Constructor ResourceResolverException
      *
-     * @param msgID
      * @param originalException
      * @param uri
      * @param baseURI
+     * @param msgID
      */
-    public ResourceResolverException(String msgID, Exception originalException,
-                                     Attr uri, String baseURI) {
-        super(msgID, originalException);
+    public ResourceResolverException(Exception originalException,
+                                     String uri, String baseURI, String msgID) {
+        super(originalException, msgID);
 
         this.uri = uri;
         this.baseURI = baseURI;
     }
 
+    @Deprecated
+    public ResourceResolverException(String msgID, Exception originalException,
+                                     String uri, String baseURI) {
+        this(originalException, uri, baseURI, msgID);
+    }
+
     /**
      * Constructor ResourceResolverException
      *
-     * @param msgID
-     * @param exArgs
      * @param originalException
      * @param uri
      * @param baseURI
+     * @param msgID
+     * @param exArgs
      */
-    public ResourceResolverException(String msgID, Object exArgs[],
-                                     Exception originalException, Attr uri,
-                                     String baseURI) {
-        super(msgID, exArgs, originalException);
+    public ResourceResolverException(Exception originalException, String uri,
+                                     String baseURI, String msgID, Object exArgs[]) {
+        super(originalException, msgID, exArgs);
 
         this.uri = uri;
         this.baseURI = baseURI;
     }
 
+    @Deprecated
+    public ResourceResolverException(String msgID, Object exArgs[],
+                                     Exception originalException, String uri,
+                                     String baseURI) {
+        this(originalException, uri, baseURI, msgID, exArgs);
+    }
+
     /**
      *
      * @param uri
      */
-    public void setURI(Attr uri) {
+    public void setURI(String uri) {
         this.uri = uri;
     }
 
@@ -115,7 +125,7 @@
      *
      * @return the uri
      */
-    public Attr getURI() {
+    public String getURI() {
         return this.uri;
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,47 +26,18 @@
 import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import org.w3c.dom.Attr;
 
 /**
  * During reference validation, we have to retrieve resources from somewhere.
  *
- * @author $Author: coheigea $
  */
 public abstract class ResourceResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResourceResolverSpi.class);
 
     /** Field properties */
-    protected java.util.Map<String, String> properties = null;
-
-    /**
-     * Deprecated - used to carry state about whether resolution was being done in a secure fashion,
-     * but was not thread safe, so the resolution information is now passed as parameters to methods.
-     *
-     * @deprecated Secure validation flag is now passed to methods.
-     */
-    @Deprecated
-    protected final boolean secureValidation = true;
-
-    /**
-     * This is the workhorse method used to resolve resources.
-     *
-     * @param uri
-     * @param BaseURI
-     * @return the resource wrapped around a XMLSignatureInput
-     *
-     * @throws ResourceResolverException
-     *
-     * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)}
-     */
-    @Deprecated
-    public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
-        throws ResourceResolverException {
-        throw new UnsupportedOperationException();
-    }
+    protected Map<String, String> properties;
 
     /**
      * This is the workhorse method used to resolve resources.
@@ -76,12 +47,8 @@
      *
      * @throws ResourceResolverException
      */
-    public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
-        throws ResourceResolverException {
-        // The default implementation, to preserve backwards compatibility in the
-        // test cases, calls the old resolver API.
-        return engineResolve(context.attr, context.baseUri);
-    }
+    public abstract XMLSignatureInput engineResolveURI(ResourceResolverContext context)
+        throws ResourceResolverException;
 
     /**
      * Method engineSetProperty
@@ -91,7 +58,7 @@
      */
     public void engineSetProperty(String key, String value) {
         if (properties == null) {
-            properties = new HashMap<String, String>();
+            properties = new HashMap<>();
         }
         properties.put(key, value);
     }
@@ -116,7 +83,7 @@
     public void engineAddProperies(Map<String, String> newProperties) {
         if (newProperties != null && !newProperties.isEmpty()) {
             if (properties == null) {
-                properties = new HashMap<String, String>();
+                properties = new HashMap<>();
             }
             properties.putAll(newProperties);
         }
@@ -125,7 +92,7 @@
     /**
      * Tells if the implementation does can be reused by several threads safely.
      * It normally means that the implementation does not have any member, or there is
-     * member change between engineCanResolve & engineResolve invocations. Or it maintains all
+     * member change between engineCanResolve and engineResolve invocations. Or it maintains all
      * member info in ThreadLocal methods.
      */
     public boolean engineIsThreadSafe() {
@@ -136,32 +103,10 @@
      * This method helps the {@link ResourceResolver} to decide whether a
      * {@link ResourceResolverSpi} is able to perform the requested action.
      *
-     * @param uri
-     * @param BaseURI
-     * @return true if the engine can resolve the uri
-     *
-     * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)}
-     */
-    @Deprecated
-    public boolean engineCanResolve(Attr uri, String BaseURI) {
-        // This method used to be abstract, so any calls to "super" are bogus.
-        throw new UnsupportedOperationException();
-    }
-
-    /**
-     * This method helps the {@link ResourceResolver} to decide whether a
-     * {@link ResourceResolverSpi} is able to perform the requested action.
-     *
-     * <p>New clients should override this method, and not override {@link #engineCanResolve(Attr, String)}
-     * </p>
      * @param context Context in which to do resolution.
      * @return true if the engine can resolve the uri
      */
-    public boolean engineCanResolveURI(ResourceResolverContext context) {
-        // To preserve backward compatibility with existing resolvers that might override the old method,
-        // call the old deprecated API.
-        return engineCanResolve( context.attr, context.baseUri );
-    }
+    public abstract boolean engineCanResolveURI(ResourceResolverContext context);
 
     /**
      * Method engineGetPropertyKeys
@@ -182,8 +127,8 @@
         String[] understood = this.engineGetPropertyKeys();
 
         if (understood != null) {
-            for (int i = 0; i < understood.length; i++) {
-                if (understood[i].equals(propertyToTest)) {
+            for (String str : understood) {
+                if (str.equals(propertyToTest)) {
                     return true;
                 }
             }
@@ -212,12 +157,12 @@
             char ch1 = str.charAt(1);
             char ch2 = str.charAt(2);
             char ch3 = str.charAt(3);
-            boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z'))
-                && (ch1 == ':') && (ch2 == '/')
-                && (ch3 != '/'));
+            boolean isDosFilename = 'A' <= ch0 && ch0 <= 'Z'
+                && ch1 == ':' && ch2 == '/'
+                && ch3 != '/';
 
-            if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str);
+            if (isDosFilename) {
+                LOG.debug("Found DOS filename: {}", str);
             }
         }
 
@@ -228,7 +173,7 @@
             if (ch1 == ':') {
                 char ch0 = Character.toUpperCase(str.charAt(0));
 
-                if (('A' <= ch0) && (ch0 <= 'Z')) {
+                if ('A' <= ch0 && ch0 <= 'Z') {
                     str = "/" + str;
                 }
             }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,21 +23,21 @@
 
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
 
 /**
- * @author $Author: coheigea $
  */
 public class ResolverAnonymous extends ResourceResolverSpi {
 
-    private InputStream inStream = null;
+    private InputStream inStream;
 
     @Override
     public boolean engineIsThreadSafe() {
@@ -50,7 +50,7 @@
      * @throws IOException
      */
     public ResolverAnonymous(String filename) throws FileNotFoundException, IOException {
-        inStream = new FileInputStream(filename);
+        inStream = Files.newInputStream(Paths.get(filename));
     }
 
     /**
@@ -60,14 +60,16 @@
         inStream = is;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     @Override
     public XMLSignatureInput engineResolveURI(ResourceResolverContext context) {
-        return new XMLSignatureInput(inStream);
+        XMLSignatureInput input = new XMLSignatureInput(inStream);
+        input.setSecureValidation(context.secureValidation);
+        return input;
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     @Override
     public boolean engineCanResolveURI(ResourceResolverContext context) {
@@ -77,7 +79,7 @@
         return false;
     }
 
-    /** @inheritDoc */
+    /** {@inheritDoc} */
     public String[] engineGetPropertyKeys() {
         return new String[0];
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,9 +32,10 @@
 import java.net.URI;
 import java.net.URL;
 import java.net.URLConnection;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
@@ -61,9 +62,8 @@
  */
 public class ResolverDirectHTTP extends ResourceResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResolverDirectHTTP.class);
 
     /** Field properties[] */
     private static final String properties[] = {
@@ -96,26 +96,17 @@
     }
 
     /**
-     * Method resolve
-     *
-     * @param uri
-     * @param baseURI
-     *
-     * @throws ResourceResolverException
-     * @return
-     * $todo$ calculate the correct URI from the attribute and the baseURI
+     * {@inheritDoc}
      */
     @Override
     public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
         throws ResourceResolverException {
-        InputStream inputStream = null;
+
         try {
-
             // calculate new URI
             URI uriNew = getNewURI(context.uriToResolve, context.baseUri);
             URL url = uriNew.toURL();
-            URLConnection urlConnection;
-            urlConnection = openConnection(url);
+            URLConnection urlConnection = openConnection(url);
 
             // check if Basic authentication is required
             String auth = urlConnection.getHeaderField("WWW-Authenticate");
@@ -127,11 +118,11 @@
                 String pass =
                     engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]);
 
-                if ((user != null) && (pass != null)) {
+                if (user != null && pass != null) {
                     urlConnection = openConnection(url);
 
                     String password = user + ":" + pass;
-                    String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));
+                    String encodedPassword = Base64.getMimeEncoder().encodeToString(password.getBytes(StandardCharsets.ISO_8859_1));
 
                     // set authentication property in the http header
                     urlConnection.setRequestProperty("Authorization",
@@ -140,45 +131,36 @@
             }
 
             String mimeType = urlConnection.getHeaderField("Content-Type");
-            inputStream = urlConnection.getInputStream();
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            byte buf[] = new byte[4096];
-            int read = 0;
-            int summarized = 0;
+            try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                InputStream inputStream = urlConnection.getInputStream()) {
+                byte[] buf = new byte[4096];
+                int read = 0;
+                int summarized = 0;
 
-            while ((read = inputStream.read(buf)) >= 0) {
-                baos.write(buf, 0, read);
-                summarized += read;
-            }
+                while ((read = inputStream.read(buf)) >= 0) {
+                    baos.write(buf, 0, read);
+                    summarized += read;
+                }
+
+                LOG.debug("Fetched {} bytes from URI {}", summarized, uriNew.toString());
 
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString());
+                XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
+                result.setSecureValidation(context.secureValidation);
+
+                result.setSourceURI(uriNew.toString());
+                result.setMIMEType(mimeType);
+
+                return result;
             }
 
-            XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
-
-            result.setSourceURI(uriNew.toString());
-            result.setMIMEType(mimeType);
-
-            return result;
         } catch (URISyntaxException ex) {
-            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+            throw new ResourceResolverException(ex, context.uriToResolve, context.baseUri, "generic.EmptyMessage");
         } catch (MalformedURLException ex) {
-            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+            throw new ResourceResolverException(ex, context.uriToResolve, context.baseUri, "generic.EmptyMessage");
         } catch (IOException ex) {
-            throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri);
+            throw new ResourceResolverException(ex, context.uriToResolve, context.baseUri, "generic.EmptyMessage");
         } catch (IllegalArgumentException e) {
-            throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri);
-        } finally {
-            if (inputStream != null) {
-                try {
-                    inputStream.close();
-                } catch (IOException e) {
-                    if (log.isLoggable(java.util.logging.Level.FINE)) {
-                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-                    }
-                }
-            }
+            throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "generic.EmptyMessage");
         }
     }
 
@@ -194,7 +176,7 @@
                 engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]);
 
         Proxy proxy = null;
-        if ((proxyHostProp != null) && (proxyPortProp != null)) {
+        if (proxyHostProp != null && proxyPortProp != null) {
             int port = Integer.parseInt(proxyPortProp);
             proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port));
         }
@@ -203,9 +185,9 @@
         if (proxy != null) {
             urlConnection = url.openConnection(proxy);
 
-            if ((proxyUser != null) && (proxyPass != null)) {
+            if (proxyUser != null && proxyPass != null) {
                 String password = proxyUser + ":" + proxyPass;
-                String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1"));
+                String authString = "Basic " + Base64.getMimeEncoder().encodeToString(password.getBytes(StandardCharsets.ISO_8859_1));
 
                 urlConnection.setRequestProperty("Proxy-Authorization", authString);
             }
@@ -219,46 +201,35 @@
     /**
      * We resolve http URIs <I>without</I> fragment...
      *
-     * @param uri
-     * @param baseURI
+     * @param context
      * @return true if can be resolved
      */
     public boolean engineCanResolveURI(ResourceResolverContext context) {
         if (context.uriToResolve == null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "quick fail, uri == null");
-            }
+            LOG.debug("quick fail, uri == null");
             return false;
         }
 
-        if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
-            }
+        if (context.uriToResolve.equals("") || context.uriToResolve.charAt(0) == '#') {
+            LOG.debug("quick fail for empty URIs and local ones");
             return false;
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve);
-        }
+        LOG.debug("I was asked whether I can resolve {}", context.uriToResolve);
 
         if (context.uriToResolve.startsWith("http:") ||
-            (context.baseUri != null && context.baseUri.startsWith("http:") )) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve);
-            }
+            context.baseUri != null && context.baseUri.startsWith("http:")) {
+            LOG.debug("I state that I can resolve {}", context.uriToResolve);
             return true;
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve);
-        }
+        LOG.debug("I state that I can't resolve {}", context.uriToResolve);
 
         return false;
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public String[] engineGetPropertyKeys() {
         return ResolverDirectHTTP.properties.clone();
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,16 +34,14 @@
 /**
  * This resolver is used for resolving same-document URIs like URI="" of URI="#id".
  *
- * @author $Author: coheigea $
  * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel">The Reference processing model in the XML Signature spec</A>
  * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-Same-Document">Same-Document URI-References in the XML Signature spec</A>
  * @see <A HREF="http://www.ietf.org/rfc/rfc2396.txt">Section 4.2 of RFC 2396</A>
  */
 public class ResolverFragment extends ResourceResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResolverFragment.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResolverFragment.class);
 
     @Override
     public boolean engineIsThreadSafe() {
@@ -51,12 +49,9 @@
     }
 
     /**
-     * Method engineResolve
-     *
-     * @inheritDoc
-     * @param uri
-     * @param baseURI
+     * {@inheritDoc}
      */
+    @Override
     public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
         throws ResourceResolverException {
 
@@ -68,9 +63,7 @@
              * Identifies the node-set (minus any comment nodes) of the XML
              * resource containing the signature
              */
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
-            }
+            LOG.debug("ResolverFragment with empty URI (means complete document)");
             selectedElem = doc;
         } else {
             /*
@@ -87,7 +80,7 @@
             if (selectedElem == null) {
                 Object exArgs[] = { id };
                 throw new ResourceResolverException(
-                    "signature.Verification.MissingID", exArgs, context.attr, context.baseUri
+                    "signature.Verification.MissingID", exArgs, context.uriToResolve, context.baseUri
                 );
             }
             if (context.secureValidation) {
@@ -95,18 +88,17 @@
                 if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
                     Object exArgs[] = { id };
                     throw new ResourceResolverException(
-                        "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri
+                        "signature.Verification.MultipleIDs", exArgs, context.uriToResolve, context.baseUri
                     );
                 }
             }
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE,
-                    "Try to catch an Element with ID " + id + " and Element was " + selectedElem
-                );
-            }
+            LOG.debug(
+                "Try to catch an Element with ID {} and Element was {}", id, selectedElem
+            );
         }
 
         XMLSignatureInput result = new XMLSignatureInput(selectedElem);
+        result.setSecureValidation(context.secureValidation);
         result.setExcludeComments(true);
 
         result.setMIMEType("text/xml");
@@ -120,29 +112,22 @@
 
     /**
      * Method engineCanResolve
-     * @inheritDoc
-     * @param uri
-     * @param baseURI
+     * {@inheritDoc}
+     * @param context
      */
     public boolean engineCanResolveURI(ResourceResolverContext context) {
         if (context.uriToResolve == null) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Quick fail for null uri");
-            }
+            LOG.debug("Quick fail for null uri");
             return false;
         }
 
         if (context.uriToResolve.equals("") ||
-            ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer("))
+            context.uriToResolve.charAt(0) == '#' && !context.uriToResolve.startsWith("#xpointer(")
         ) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\"");
-            }
+            LOG.debug("State I can resolve reference: \"{}\"", context.uriToResolve);
             return true;
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\"");
-        }
+        LOG.debug("Do not seem to be able to resolve reference: \"{}\"", context.uriToResolve);
         return false;
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,9 +22,11 @@
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
 
-import java.io.FileInputStream;
+import java.io.InputStream;
 import java.net.URI;
 import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
@@ -38,9 +40,8 @@
 
     private static final int FILE_URI_LENGTH = "file:/".length();
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResolverLocalFilesystem.class);
 
     @Override
     public boolean engineIsThreadSafe() {
@@ -48,7 +49,7 @@
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     @Override
     public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
@@ -59,14 +60,15 @@
 
             String fileName =
                 ResolverLocalFilesystem.translateUriToFilename(uriNew.toString());
-            FileInputStream inputStream = new FileInputStream(fileName);
+            InputStream inputStream = Files.newInputStream(Paths.get(fileName));
             XMLSignatureInput result = new XMLSignatureInput(inputStream);
+            result.setSecureValidation(context.secureValidation);
 
             result.setSourceURI(uriNew.toString());
 
             return result;
         } catch (Exception e) {
-            throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri);
+            throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "generic.EmptyMessage");
         }
     }
 
@@ -106,38 +108,30 @@
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public boolean engineCanResolveURI(ResourceResolverContext context) {
         if (context.uriToResolve == null) {
             return false;
         }
 
-        if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') ||
+        if (context.uriToResolve.equals("") || context.uriToResolve.charAt(0) == '#' ||
             context.uriToResolve.startsWith("http:")) {
             return false;
         }
 
         try {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve);
-            }
+            LOG.debug("I was asked whether I can resolve {}", context.uriToResolve);
 
             if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve);
-                }
+                LOG.debug("I state that I can resolve {}", context.uriToResolve);
                 return true;
             }
         } catch (Exception e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
         }
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "But I can't");
-        }
+        LOG.debug("But I can't");
 
         return false;
     }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -33,10 +33,10 @@
 
 /**
  * Handles barename XPointer Reference URIs.
- * <BR />
+ * <p></p>
  * To retain comments while selecting an element by an identifier ID,
  * use the following full XPointer: URI='#xpointer(id('ID'))'.
- * <BR />
+ * <p></p>
  * To retain comments while selecting the entire document,
  * use the following full XPointer: URI='#xpointer(/)'.
  * This XPointer contains a simple XPath expression that includes
@@ -44,13 +44,11 @@
  * nodes of the parse tree (all descendants, plus all attributes,
  * plus all namespaces nodes).
  *
- * @author $Author: coheigea $
  */
 public class ResolverXPointer extends ResourceResolverSpi {
 
-    /** {@link org.apache.commons.logging} logging facility */
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger(ResolverXPointer.class.getName());
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResolverXPointer.class);
 
     private static final String XP = "#xpointer(id(";
     private static final int XP_LENGTH = XP.length();
@@ -61,7 +59,7 @@
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     @Override
     public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
@@ -81,7 +79,7 @@
                 if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
                     Object exArgs[] = { id };
                     throw new ResourceResolverException(
-                        "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri
+                        "signature.Verification.MultipleIDs", exArgs, context.uriToResolve, context.baseUri
                     );
                 }
             }
@@ -90,12 +88,13 @@
                 Object exArgs[] = { id };
 
                 throw new ResourceResolverException(
-                    "signature.Verification.MissingID", exArgs, context.attr, context.baseUri
+                    "signature.Verification.MissingID", exArgs, context.uriToResolve, context.baseUri
                 );
             }
         }
 
         XMLSignatureInput result = new XMLSignatureInput(resultNode);
+        result.setSecureValidation(context.secureValidation);
 
         result.setMIMEType("text/xml");
         if (context.baseUri != null && context.baseUri.length() > 0) {
@@ -108,7 +107,7 @@
     }
 
     /**
-     * @inheritDoc
+     * {@inheritDoc}
      */
     public boolean engineCanResolveURI(ResourceResolverContext context) {
         if (context.uriToResolve == null) {
@@ -146,11 +145,9 @@
             String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2);
 
             int idLen = idPlusDelim.length() -1;
-            if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"'))
-                || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen));
-                }
+            if (idPlusDelim.charAt(0) == '"' && idPlusDelim.charAt(idLen) == '"'
+                || idPlusDelim.charAt(0) == '\'' && idPlusDelim.charAt(idLen) == '\'') {
+                LOG.debug("Id = {}", idPlusDelim.substring(1, idLen));
                 return true;
             }
         }
@@ -166,11 +163,11 @@
      */
     private static String getXPointerId(String uri) {
         if (uri.startsWith(XP) && uri.endsWith("))")) {
-            String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2);
+            String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2);
 
             int idLen = idPlusDelim.length() -1;
-            if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"'))
-                || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) {
+            if (idPlusDelim.charAt(0) == '"' && idPlusDelim.charAt(idLen) == '"'
+                || idPlusDelim.charAt(0) == '\'' && idPlusDelim.charAt(idLen) == '\'') {
                 return idPlusDelim.substring(1, idLen);
             }
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-<HTML> 
-<HEAD> </HEAD> 
-<BODY> 
-<P>
-implememtations of different ResourceResolver classes used to resolve ds:Reference URIs.
-</P>
-</BODY> 
-</HTML>
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/package.html	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-<HTML> 
-<HEAD> </HEAD> 
-<BODY> 
-<P>
-the ResourceResolver classes used to resolve ds:Reference URIs.
-</P>
-</BODY> 
-</HTML>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/slf4j/internal/Logger.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.org.slf4j.internal;
+
+// Bridge to java.util.logging.
+public class Logger {
+
+    private final java.util.logging.Logger impl;
+
+    public Logger(String name) {
+        impl = java.util.logging.Logger.getLogger(name);
+    }
+
+    public boolean isDebugEnabled() {
+        return impl.isLoggable(java.util.logging.Level.FINE);
+    }
+
+    public boolean isTraceEnabled() {
+        return impl.isLoggable(java.util.logging.Level.FINE);
+    }
+
+    public void debug(String s) {
+        impl.log(java.util.logging.Level.FINE, s);
+    }
+
+    public void debug(String s, Throwable e) {
+        impl.log(java.util.logging.Level.FINE, s, e);
+    }
+
+    public void debug(String s, Object... o) {
+        impl.log(java.util.logging.Level.FINE, s, o);
+    }
+
+    public void trace(String s) {
+        impl.log(java.util.logging.Level.FINE, s);
+    }
+
+    public void error(String s) {
+        impl.log(java.util.logging.Level.SEVERE, s);
+    }
+
+    public void error(String s, Throwable e) {
+        impl.log(java.util.logging.Level.SEVERE, s, e);
+    }
+
+    public void error(String s, Object... o) {
+        impl.log(java.util.logging.Level.SEVERE, s, o);
+    }
+
+    public void warn(String s) {
+        impl.log(java.util.logging.Level.WARNING, s);
+    }
+
+    public void warn(String s, Throwable e) {
+        impl.log(java.util.logging.Level.WARNING, s, e);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/com/sun/org/slf4j/internal/LoggerFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.org.slf4j.internal;
+
+// Bridge to java.util.logging.
+public class LoggerFactory {
+
+    public static Logger getLogger(Class<?> clazz) {
+        return new Logger(clazz.getName());
+    }
+}
--- a/src/java.xml.crypto/share/classes/javax/xml/crypto/dsig/DigestMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/javax/xml/crypto/dsig/DigestMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -59,29 +59,79 @@
  */
 public interface DigestMethod extends XMLStructure, AlgorithmMethod {
 
+    // All methods can be found in RFC 6931.
+
     /**
      * The <a href="http://www.w3.org/2000/09/xmldsig#sha1">
      * SHA1</a> digest method algorithm URI.
      */
-    static final String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1";
+    String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#sha224">
+     * SHA224</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA224 = "http://www.w3.org/2001/04/xmldsig-more#sha224";
 
     /**
      * The <a href="http://www.w3.org/2001/04/xmlenc#sha256">
      * SHA256</a> digest method algorithm URI.
      */
-    static final String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256";
+    String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#sha384">
+     * SHA384</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384";
 
     /**
      * The <a href="http://www.w3.org/2001/04/xmlenc#sha512">
      * SHA512</a> digest method algorithm URI.
      */
-    static final String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512";
+    String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512";
 
     /**
      * The <a href="http://www.w3.org/2001/04/xmlenc#ripemd160">
      * RIPEMD-160</a> digest method algorithm URI.
      */
-    static final String RIPEMD160 = "http://www.w3.org/2001/04/xmlenc#ripemd160";
+    String RIPEMD160 = "http://www.w3.org/2001/04/xmlenc#ripemd160";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha3-224">
+     * SHA3-224</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA3_224 = "http://www.w3.org/2007/05/xmldsig-more#sha3-224";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha3-256">
+     * SHA3-256</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA3_256 = "http://www.w3.org/2007/05/xmldsig-more#sha3-256";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha3-384">
+     * SHA3-384</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA3_384 = "http://www.w3.org/2007/05/xmldsig-more#sha3-384";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha3-512">
+     * SHA3-512</a> digest method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA3_512 = "http://www.w3.org/2007/05/xmldsig-more#sha3-512";
 
     /**
      * Returns the algorithm-specific input parameters associated with this
--- a/src/java.xml.crypto/share/classes/javax/xml/crypto/dsig/SignatureMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/javax/xml/crypto/dsig/SignatureMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -60,28 +60,182 @@
  */
 public interface SignatureMethod extends XMLStructure, AlgorithmMethod {
 
+    // All methods can be found in RFC 6931.
+
     /**
-     * The <a href="http://www.w3.org/2000/09/xmldsig#dsa-sha1">DSAwithSHA1</a>
+     * The <a href="http://www.w3.org/2000/09/xmldsig#dsa-sha1">DSA-SHA1</a>
      * (DSS) signature method algorithm URI.
      */
-    static final String DSA_SHA1 =
+    String DSA_SHA1 =
         "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
 
     /**
-     * The <a href="http://www.w3.org/2000/09/xmldsig#rsa-sha1">RSAwithSHA1</a>
+     * The <a href="http://www.w3.org/2009/xmldsig11#dsa-sha256">DSA-SHA256</a>
+     * (DSS) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String DSA_SHA256 = "http://www.w3.org/2009/xmldsig11#dsa-sha256";
+
+    /**
+     * The <a href="http://www.w3.org/2000/09/xmldsig#rsa-sha1">RSA-SHA1</a>
      * (PKCS #1) signature method algorithm URI.
      */
-    static final String RSA_SHA1 =
+    String RSA_SHA1 =
         "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
 
     /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#rsa-sha224">
+     * RSA-SHA224</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String RSA_SHA224 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha224";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256">
+     * RSA-SHA256</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String RSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384">
+     * RSA-SHA384</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String RSA_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512">
+     * RSA-SHA512</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String RSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1">
+     * SHA1-RSA-MGF1</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA1_RSA_MGF1 = "http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1">
+     * SHA224-RSA-MGF1</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA224_RSA_MGF1 = "http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1">
+     * SHA256-RSA-MGF1</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA256_RSA_MGF1 = "http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1">
+     * SHA384-RSA-MGF1</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA384_RSA_MGF1 = "http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1";
+
+    /**
+     * The <a href="http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1">
+     * SHA512-RSA-MGF1</a> (PKCS #1) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String SHA512_RSA_MGF1 = "http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1">
+     * ECDSA-SHA1</a> (FIPS 180-4) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String ECDSA_SHA1 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224">
+     * ECDSA-SHA224</a> (FIPS 180-4) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String ECDSA_SHA224 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256">
+     * ECDSA-SHA256</a> (FIPS 180-4) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String ECDSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384">
+     * ECDSA-SHA384</a> (FIPS 180-4) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String ECDSA_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512">
+     * ECDSA-SHA512</a> (FIPS 180-4) signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String ECDSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
+
+    /**
      * The <a href="http://www.w3.org/2000/09/xmldsig#hmac-sha1">HMAC-SHA1</a>
      * MAC signature method algorithm URI
      */
-    static final String HMAC_SHA1 =
+    String HMAC_SHA1 =
         "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
 
     /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#hmac-sha224">
+     * HMAC-SHA224</a> MAC signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String HMAC_SHA224 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha224";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256">
+     * HMAC-SHA256</a> MAC signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String HMAC_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384">
+     * HMAC-SHA384</a> MAC signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String HMAC_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
+
+    /**
+     * The <a href="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512">
+     * HMAC-SHA512</a> MAC signature method algorithm URI.
+     *
+     * @since 11
+     */
+    String HMAC_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
+
+    /**
      * Returns the algorithm-specific input parameters of this
      * <code>SignatureMethod</code>.
      *
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DigesterOutputStream.java,v 1.5 2005/12/20 20:02:39 mullan Exp $
+ * $Id: DigesterOutputStream.java, v 1.5 2005/12/20 20:02:39 mullan Exp $
  */
 package org.jcp.xml.dsig.internal;
 
@@ -42,12 +42,10 @@
  * com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm objects.
  * It also optionally caches the input bytes.
  *
- * @author raul
- * @author Sean Mullan
  */
 public class DigesterOutputStream extends OutputStream {
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DigesterOutputStream.class);
 
     private final boolean buffer;
     private UnsyncByteArrayOutputStream bos;
@@ -88,13 +86,13 @@
         if (buffer) {
             bos.write(input, offset, len);
         }
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Pre-digested input:");
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Pre-digested input:");
             StringBuilder sb = new StringBuilder(len);
             for (int i = offset; i < (offset + len); i++) {
                 sb.append((char)input[i]);
             }
-            log.log(java.util.logging.Level.FINE, sb.toString());
+            LOG.debug(sb.toString());
         }
         md.update(input, offset, len);
     }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,8 +29,6 @@
  * Derived from Apache sources and changed to use Mac objects instead of
  * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects.
  *
- * @author raul
- * @author Sean Mullan
  *
  */
 public class MacOutputStream extends ByteArrayOutputStream {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: SignerOutputStream.java,v 1.2 2005/09/15 14:29:02 mullan Exp $
+ * $Id: SignerOutputStream.java, v 1.2 2005/09/15 14:29:02 mullan Exp $
  */
 package org.jcp.xml.dsig.internal;
 
@@ -37,8 +37,6 @@
  * objects as input instead of
  * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects.
  *
- * @author raul
- * @author Sean Mullan
  */
 public class SignerOutputStream extends ByteArrayOutputStream {
     private final Signature sig;
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -29,23 +29,19 @@
 import java.security.SignatureException;
 import java.security.spec.AlgorithmParameterSpec;
 import javax.xml.crypto.MarshalException;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.SignatureMethod;
-import javax.xml.crypto.dsig.SignedInfo;
 import javax.xml.crypto.dsig.XMLSignature;
 import javax.xml.crypto.dsig.XMLSignatureException;
 import javax.xml.crypto.dsig.XMLSignContext;
 import javax.xml.crypto.dsig.XMLValidateContext;
 import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * An abstract class representing a SignatureMethod. Subclasses implement
  * a specific XML DSig signature algorithm.
  */
-abstract class AbstractDOMSignatureMethod extends DOMStructure
+abstract class AbstractDOMSignatureMethod extends BaseStructure
     implements SignatureMethod {
 
     // denotes the type of signature algorithm
@@ -59,17 +55,17 @@
      * @param si the SignedInfo
      * @param sig the signature bytes to be verified
      * @param context the XMLValidateContext
-     * @return <code>true</code> if the signature verified successfully,
-     *    <code>false</code> if not
-     * @throws NullPointerException if <code>key</code>, <code>si</code> or
-     *    <code>sig</code> are <code>null</code>
+     * @return {@code true} if the signature verified successfully,
+     *    {@code false} if not
+     * @throws NullPointerException if {@code key}, {@code si} or
+     *    {@code sig} are {@code null}
      * @throws InvalidKeyException if the key is improperly encoded, of
      *    the wrong type, or parameters are missing, etc
      * @throws SignatureException if an unexpected error occurs, such
      *    as the passed in signature is improperly encoded
      * @throws XMLSignatureException if an unexpected error occurs
      */
-    abstract boolean verify(Key key, SignedInfo si, byte[] sig,
+    abstract boolean verify(Key key, DOMSignedInfo si, byte[] sig,
                             XMLValidateContext context)
         throws InvalidKeyException, SignatureException, XMLSignatureException;
 
@@ -81,13 +77,13 @@
      * @param si the SignedInfo
      * @param context the XMLSignContext
      * @return the signature
-     * @throws NullPointerException if <code>key</code> or
-     *    <code>si</code> are <code>null</code>
+     * @throws NullPointerException if {@code key} or
+     *    {@code si} are {@code null}
      * @throws InvalidKeyException if the key is improperly encoded, of
      *    the wrong type, or parameters are missing, etc
      * @throws XMLSignatureException if an unexpected error occurs
      */
-    abstract byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+    abstract byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
         throws InvalidKeyException, XMLSignatureException;
 
     /**
@@ -105,20 +101,16 @@
      * This method invokes the {@link #marshalParams marshalParams}
      * method to marshal any algorithm-specific parameters.
      */
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public void marshal(XmlWriter xwriter, String dsPrefix)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
-                                                XMLSignature.XMLNS, dsPrefix);
-        DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());
+        xwriter.writeStartElement(dsPrefix, "SignatureMethod", XMLSignature.XMLNS);
+        xwriter.writeAttribute("", "", "Algorithm", getAlgorithm());
 
         if (getParameterSpec() != null) {
-            marshalParams(smElem, dsPrefix);
+            marshalParams(xwriter, dsPrefix);
         }
-
-        parent.appendChild(smElem);
+        xwriter.writeEndElement(); // "SignatureMethod"
     }
 
     /**
@@ -131,7 +123,7 @@
      * @param paramsPrefix the algorithm parameters prefix to use
      * @throws MarshalException if the parameters cannot be marshalled
      */
-    void marshalParams(Element parent, String paramsPrefix)
+    void marshalParams(XmlWriter xwriter, String paramsPrefix)
         throws MarshalException
     {
         throw new MarshalException("no parameters should " +
@@ -140,13 +132,13 @@
     }
 
     /**
-     * Unmarshals <code>SignatureMethodParameterSpec</code> from the specified
-     * <code>Element</code>. By default, this method throws an exception since
+     * Unmarshals {@code SignatureMethodParameterSpec} from the specified
+     * {@code Element}. By default, this method throws an exception since
      * most SignatureMethod algorithms do not have parameters. Subclasses should
      * override it if they have parameters.
      *
-     * @param paramsElem the <code>Element</code> holding the input params
-     * @return the algorithm-specific <code>SignatureMethodParameterSpec</code>
+     * @param paramsElem the {@code Element} holding the input params
+     * @return the algorithm-specific {@code SignatureMethodParameterSpec}
      * @throws MarshalException if the parameters cannot be unmarshalled
      */
     SignatureMethodParameterSpec unmarshalParams(Element paramsElem)
@@ -163,7 +155,7 @@
      * since most SignatureMethod algorithms do not have parameters. Subclasses
      * should override it if they have parameters.
      *
-     * @param params the algorithm-specific params (may be <code>null</code>)
+     * @param params the algorithm-specific params (may be {@code null})
      * @throws InvalidAlgorithmParameterException if the parameters are not
      *    appropriate for this signature method
      */
@@ -189,8 +181,8 @@
         }
         SignatureMethod osm = (SignatureMethod)o;
 
-        return (getAlgorithm().equals(osm.getAlgorithm()) &&
-            paramsEqual(osm.getParameterSpec()));
+        return getAlgorithm().equals(osm.getAlgorithm()) &&
+            paramsEqual(osm.getParameterSpec());
     }
 
     @Override
@@ -213,6 +205,6 @@
      */
     boolean paramsEqual(AlgorithmParameterSpec spec)
     {
-        return (getParameterSpec() == spec);
+        return getParameterSpec() == spec;
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: ApacheCanonicalizer.java 1785016 2017-03-01 18:23:48Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -34,6 +34,7 @@
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.InvalidAlgorithmParameterException;
 import java.util.Set;
+
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.TransformException;
@@ -54,8 +55,8 @@
         com.sun.org.apache.xml.internal.security.Init.init();
     }
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ApacheCanonicalizer.class);
     protected Canonicalizer apacheCanonicalizer;
     private Transform apacheTransform;
     protected String inclusiveNamespaces;
@@ -68,6 +69,7 @@
         return params;
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException
     {
@@ -86,6 +88,7 @@
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -116,9 +119,9 @@
         if (apacheCanonicalizer == null) {
             try {
                 apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm());
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Created canonicalizer for algorithm: " + getAlgorithm());
-                }
+                boolean secVal = Utils.secureValidation(xc);
+                apacheCanonicalizer.setSecureValidation(secVal);
+                LOG.debug("Created canonicalizer for algorithm: {}", getAlgorithm());
             } catch (InvalidCanonicalizerException ice) {
                 throw new TransformException
                     ("Couldn't find Canonicalizer for: " + getAlgorithm() +
@@ -167,11 +170,9 @@
                 }
             } else if (data instanceof NodeSetData) {
                 NodeSetData<?> nsd = (NodeSetData<?>)data;
-                // convert Iterator to Set<Node>
+                // convert Iterator to Set
                 nodeSet = Utils.toNodeSet(nsd.iterator());
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes");
-                }
+                LOG.debug("Canonicalizing {} nodes", nodeSet.size());
             } else {
                 return new OctetStreamData(new ByteArrayInputStream(
                     apacheCanonicalizer.canonicalize(
@@ -210,9 +211,9 @@
                 apacheTransform =
                     new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm());
-                }
+                boolean secVal = Utils.secureValidation(xc);
+                apacheTransform.setSecureValidation(secVal);
+                LOG.debug("Created transform for algorithm: {}", getAlgorithm());
             } catch (Exception ex) {
                 throw new TransformException
                     ("Couldn't find Transform for: " + getAlgorithm(), ex);
@@ -221,27 +222,22 @@
 
         XMLSignatureInput in;
         if (data instanceof ApacheData) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "ApacheData = true");
-            }
+            LOG.debug("ApacheData = true");
             in = ((ApacheData)data).getXMLSignatureInput();
         } else if (data instanceof NodeSetData) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "isNodeSet() = true");
-            }
+            LOG.debug("isNodeSet() = true");
             if (data instanceof DOMSubTreeData) {
                 DOMSubTreeData subTree = (DOMSubTreeData)data;
                 in = new XMLSignatureInput(subTree.getRoot());
                 in.setExcludeComments(subTree.excludeComments());
             } else {
+                @SuppressWarnings("unchecked")
                 Set<Node> nodeSet =
                     Utils.toNodeSet(((NodeSetData)data).iterator());
                 in = new XMLSignatureInput(nodeSet);
             }
         } else {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "isNodeSet() = false");
-            }
+            LOG.debug("isNodeSet() = false");
             try {
                 in = new XMLSignatureInput
                     (((OctetStreamData)data).getOctetStream());
@@ -250,6 +246,9 @@
             }
         }
 
+        boolean secVal = Utils.secureValidation(xc);
+        in.setSecureValidation(secVal);
+
         try {
             in = apacheTransform.performTransform(in, os);
             if (!in.isNodeSet() && !in.isElement()) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheData.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: ApacheData.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -34,7 +34,6 @@
 /**
  * XMLSignatureInput Data wrapper.
  *
- * @author Sean Mullan
  */
 public interface ApacheData extends Data {
 
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $
+ * $Id: ApacheNodeSetData.java 1496478 2013-06-25 14:01:16Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheOctetStreamData.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: ApacheOctetStreamData.java 1667527 2015-03-18 12:54:20Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -45,6 +45,7 @@
         this.xi = xi;
     }
 
+    @Override
     public XMLSignatureInput getXMLSignatureInput() {
         return xi;
     }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: ApacheTransform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -32,10 +32,10 @@
 import java.security.InvalidAlgorithmParameterException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.util.Set;
+
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
 
@@ -48,8 +48,6 @@
  * This is a wrapper/glue class which invokes the Apache XML-Security
  * Transform.
  *
- * @author Sean Mullan
- * @author Erwin van der Koogh
  */
 public abstract class ApacheTransform extends TransformService {
 
@@ -57,17 +55,19 @@
         com.sun.org.apache.xml.internal.security.Init.init();
     }
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(ApacheTransform.class);
     private Transform apacheTransform;
     protected Document ownerDoc;
     protected Element transformElem;
     protected TransformParameterSpec params;
 
+    @Override
     public final AlgorithmParameterSpec getParameterSpec() {
         return params;
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException
     {
@@ -86,6 +86,7 @@
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -104,15 +105,17 @@
         ownerDoc = DOMUtils.getOwnerDocument(transformElem);
     }
 
+    @Override
     public Data transform(Data data, XMLCryptoContext xc)
         throws TransformException
     {
         if (data == null) {
             throw new NullPointerException("data must not be null");
         }
-        return transformIt(data, xc, (OutputStream)null);
+        return transformIt(data, xc, null);
     }
 
+    @Override
     public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
         throws TransformException
     {
@@ -137,10 +140,9 @@
                 apacheTransform =
                     new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " +
-                            getAlgorithm());
-                }
+                boolean secVal = Utils.secureValidation(xc);
+                apacheTransform.setSecureValidation(secVal);
+                LOG.debug("Created transform for algorithm: {}", getAlgorithm());
             } catch (Exception ex) {
                 throw new TransformException("Couldn't find Transform for: " +
                                              getAlgorithm(), ex);
@@ -158,30 +160,23 @@
 
         XMLSignatureInput in;
         if (data instanceof ApacheData) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "ApacheData = true");
-            }
+            LOG.debug("ApacheData = true");
             in = ((ApacheData)data).getXMLSignatureInput();
         } else if (data instanceof NodeSetData) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "isNodeSet() = true");
-            }
+            LOG.debug("isNodeSet() = true");
             if (data instanceof DOMSubTreeData) {
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "DOMSubTreeData = true");
-                }
+                LOG.debug("DOMSubTreeData = true");
                 DOMSubTreeData subTree = (DOMSubTreeData)data;
                 in = new XMLSignatureInput(subTree.getRoot());
                 in.setExcludeComments(subTree.excludeComments());
             } else {
+                @SuppressWarnings("unchecked")
                 Set<Node> nodeSet =
                     Utils.toNodeSet(((NodeSetData)data).iterator());
                 in = new XMLSignatureInput(nodeSet);
             }
         } else {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "isNodeSet() = false");
-            }
+            LOG.debug("isNodeSet() = false");
             try {
                 in = new XMLSignatureInput
                     (((OctetStreamData)data).getOctetStream());
@@ -189,6 +184,8 @@
                 throw new TransformException(ex);
             }
         }
+        boolean secVal = Utils.secureValidation(xc);
+        in.setSecureValidation(secVal);
 
         try {
             if (os != null) {
@@ -209,6 +206,7 @@
         }
     }
 
+    @Override
     public final boolean isFeatureSupported(String feature) {
         if (feature == null) {
             throw new NullPointerException();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/BaseStructure.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,49 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jcp.xml.dsig.internal.dom;
+
+import javax.xml.crypto.XMLStructure;
+
+import org.w3c.dom.Node;
+
+public abstract class BaseStructure implements XMLStructure {
+
+    /**
+     * Just return the text of the immediate child of a node.
+     *
+     * @param node
+     * @return the text of a Node
+     */
+    public static String textOfNode(Node node) {
+        return node.getFirstChild().getNodeValue();
+    }
+
+    public final boolean isFeatureSupported(String feature) {
+        if (feature == null) {
+            throw new NullPointerException();
+        } else {
+            return false;
+        }
+    }
+
+}
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMBase64Transform.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMBase64Transform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -36,10 +36,10 @@
  * DOM-based implementation of Base64 Encoding Transform.
  * (Uses Apache XML-Sec Transform implementation)
  *
- * @author Sean Mullan
  */
 public final class DOMBase64Transform extends ApacheTransform {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException {
         if (params != null) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
@@ -41,7 +41,6 @@
  * DOM-based implementation of CanonicalizationMethod for Canonical XML 1.1
  * (with or without comments). Uses Apache XML-Sec Canonicalizer.
  *
- * @author Sean Mullan
  */
 public final class DOMCanonicalXMLC14N11Method extends ApacheCanonicalizer {
 
@@ -49,6 +48,7 @@
     public static final String C14N_11_WITH_COMMENTS
         = "http://www.w3.org/2006/12/xml-c14n11#WithComments";
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException {
         if (params != null) {
@@ -57,6 +57,7 @@
         }
     }
 
+    @Override
     public Data transform(Data data, XMLCryptoContext xc)
         throws TransformException {
 
@@ -68,6 +69,8 @@
             if (subTree.excludeComments()) {
                 try {
                     apacheCanonicalizer = Canonicalizer.getInstance(C14N_11);
+                    boolean secVal = Utils.secureValidation(xc);
+                    apacheCanonicalizer.setSecureValidation(secVal);
                 } catch (InvalidCanonicalizerException ice) {
                     throw new TransformException
                         ("Couldn't find Canonicalizer for: " +
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCanonicalXMLC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMCanonicalXMLC14NMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -41,10 +41,10 @@
  * DOM-based implementation of CanonicalizationMethod for Canonical XML
  * (with or without comments). Uses Apache XML-Sec Canonicalizer.
  *
- * @author Sean Mullan
  */
 public final class DOMCanonicalXMLC14NMethod extends ApacheCanonicalizer {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException {
         if (params != null) {
@@ -53,6 +53,7 @@
         }
     }
 
+    @Override
     public Data transform(Data data, XMLCryptoContext xc)
         throws TransformException {
 
@@ -65,6 +66,8 @@
                 try {
                     apacheCanonicalizer = Canonicalizer.getInstance
                         (CanonicalizationMethod.INCLUSIVE);
+                    boolean secVal = Utils.secureValidation(xc);
+                    apacheCanonicalizer.setSecureValidation(secVal);
                 } catch (InvalidCanonicalizerException ice) {
                     throw new TransformException
                         ("Couldn't find Canonicalizer for: " +
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMCanonicalizationMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMCanonicalizationMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -41,13 +41,12 @@
 /**
  * DOM-based abstract implementation of CanonicalizationMethod.
  *
- * @author Sean Mullan
  */
 public class DOMCanonicalizationMethod extends DOMTransform
     implements CanonicalizationMethod {
 
     /**
-     * Creates a <code>DOMCanonicalizationMethod</code>.
+     * Creates a {@code DOMCanonicalizationMethod}.
      *
      * @param spi TransformService
      */
@@ -55,17 +54,14 @@
         throws InvalidAlgorithmParameterException
     {
         super(spi);
-        if (!(spi instanceof ApacheCanonicalizer) &&
-                !isC14Nalg(spi.getAlgorithm())) {
-            throw new InvalidAlgorithmParameterException(
-                "Illegal CanonicalizationMethod");
+        if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) {
+            throw new InvalidAlgorithmParameterException("Illegal CanonicalizationMethod");
         }
     }
 
     /**
-     * Creates a <code>DOMCanonicalizationMethod</code> from an element. This
-     * ctor invokes the abstract {@link #unmarshalParams unmarshalParams}
-     * method to unmarshal any algorithm-specific input parameters.
+     * Creates a {@code DOMCanonicalizationMethod} from an element. It unmarshals any
+     * algorithm-specific input parameters.
      *
      * @param cmElem a CanonicalizationMethod element
      */
@@ -74,8 +70,7 @@
         throws MarshalException
     {
         super(cmElem, context, provider);
-        if (!(spi instanceof ApacheCanonicalizer) &&
-                !isC14Nalg(spi.getAlgorithm())) {
+        if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) {
             throw new MarshalException("Illegal CanonicalizationMethod");
         }
     }
@@ -86,10 +81,10 @@
      * the {@link #transform transform} method.
      *
      * @param data the data to be canonicalized
-     * @param xc the <code>XMLCryptoContext</code> containing
-     *     additional context (may be <code>null</code> if not applicable)
+     * @param xc the {@code XMLCryptoContext} containing
+     *     additional context (may be {@code null} if not applicable)
      * @return the canonicalized data
-     * @throws NullPointerException if <code>data</code> is <code>null</code>
+     * @throws NullPointerException if {@code data} is {@code null}
      * @throws TransformException if an unexpected error occurs while
      *    canonicalizing the data
      */
@@ -116,8 +111,8 @@
         }
         CanonicalizationMethod ocm = (CanonicalizationMethod)o;
 
-        return (getAlgorithm().equals(ocm.getAlgorithm()) &&
-            DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec()));
+        return getAlgorithm().equals(ocm.getAlgorithm()) &&
+            DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec());
     }
 
     @Override
@@ -133,11 +128,21 @@
     }
 
     private static boolean isC14Nalg(String alg) {
-        return (alg.equals(CanonicalizationMethod.INCLUSIVE) ||
-                alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) ||
-                alg.equals(CanonicalizationMethod.EXCLUSIVE) ||
-                alg.equals(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS) ||
-                alg.equals(DOMCanonicalXMLC14N11Method.C14N_11) ||
-                alg.equals(DOMCanonicalXMLC14N11Method.C14N_11_WITH_COMMENTS));
+        return isInclusiveC14Nalg(alg) || isExclusiveC14Nalg(alg) || isC14N11alg(alg);
+    }
+
+    private static boolean isInclusiveC14Nalg(String alg) {
+        return alg.equals(CanonicalizationMethod.INCLUSIVE)
+            || alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
+    }
+
+    private static boolean isExclusiveC14Nalg(String alg) {
+        return alg.equals(CanonicalizationMethod.EXCLUSIVE)
+            || alg.equals(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS);
+    }
+
+    private static boolean isC14N11alg(String alg) {
+        return alg.equals(DOMCanonicalXMLC14N11Method.C14N_11)
+            || alg.equals(DOMCanonicalXMLC14N11Method.C14N_11_WITH_COMMENTS);
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,103 +0,0 @@
-/*
- * 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
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
- */
-/*
- * $Id: DOMCryptoBinary.java 1197150 2011-11-03 14:34:57Z coheigea $
- */
-package org.jcp.xml.dsig.internal.dom;
-
-import java.math.BigInteger;
-import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-import com.sun.org.apache.xml.internal.security.utils.Base64;
-
-/**
- * A DOM-based representation of the XML <code>CryptoBinary</code> simple type
- * as defined in the W3C specification for XML-Signature Syntax and Processing.
- * The XML Schema Definition is defined as:
- *
- * <pre>{@code
- * <simpleType name="CryptoBinary">
- *   <restriction base = "base64Binary">
- *   </restriction>
- * </simpleType>
- * }</pre>
- *
- * @author Sean Mullan
- */
-public final class DOMCryptoBinary extends DOMStructure {
-
-    private final BigInteger bigNum;
-    private final String value;
-
-    /**
-     * Create a <code>DOMCryptoBinary</code> instance from the specified
-     * <code>BigInteger</code>
-     *
-     * @param bigNum the arbitrary-length integer
-     * @throws NullPointerException if <code>bigNum</code> is <code>null</code>
-     */
-    public DOMCryptoBinary(BigInteger bigNum) {
-        if (bigNum == null) {
-            throw new NullPointerException("bigNum is null");
-        }
-        this.bigNum = bigNum;
-        // convert to bitstring
-        value = Base64.encode(bigNum);
-    }
-
-    /**
-     * Creates a <code>DOMCryptoBinary</code> from a node.
-     *
-     * @param cbNode a CryptoBinary text node
-     * @throws MarshalException if value cannot be decoded (invalid format)
-     */
-    public DOMCryptoBinary(Node cbNode) throws MarshalException {
-        value = cbNode.getNodeValue();
-        try {
-            bigNum = Base64.decodeBigIntegerFromText((Text) cbNode);
-        } catch (Exception ex) {
-            throw new MarshalException(ex);
-        }
-    }
-
-    /**
-     * Returns the <code>BigInteger</code> that this object contains.
-     *
-     * @return the <code>BigInteger</code> that this object contains
-     */
-    public BigInteger getBigNum() {
-        return bigNum;
-    }
-
-    public void marshal(Node parent, String prefix, DOMCryptoContext context)
-        throws MarshalException {
-        parent.appendChild
-            (DOMUtils.getOwnerDocument(parent).createTextNode(value));
-    }
-}
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,40 +21,49 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMDigestMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMDigestMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec;
 
 import java.security.InvalidAlgorithmParameterException;
 import java.security.spec.AlgorithmParameterSpec;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * DOM-based abstract implementation of DigestMethod.
  *
- * @author Sean Mullan
  */
-public abstract class DOMDigestMethod extends DOMStructure
+public abstract class DOMDigestMethod extends BaseStructure
     implements DigestMethod {
 
+    static final String SHA224 =
+        "http://www.w3.org/2001/04/xmldsig-more#sha224"; // see RFC 4051
     static final String SHA384 =
         "http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051
+    static final String WHIRLPOOL =
+        "http://www.w3.org/2007/05/xmldsig-more#whirlpool"; // see RFC 6931
+    static final String SHA3_224 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha3-224"; // see RFC 6931
+    static final String SHA3_256 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha3-256"; // see RFC 6931
+    static final String SHA3_384 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha3-384"; // see RFC 6931
+    static final String SHA3_512 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha3-512"; // see RFC 6931
+
     private DigestMethodParameterSpec params;
 
     /**
-     * Creates a <code>DOMDigestMethod</code>.
+     * Creates a {@code DOMDigestMethod}.
      *
-     * @param params the algorithm-specific params (may be <code>null</code>)
+     * @param params the algorithm-specific params (may be {@code null})
      * @throws InvalidAlgorithmParameterException if the parameters are not
      *    appropriate for this digest method
      */
@@ -70,7 +79,7 @@
     }
 
     /**
-     * Creates a <code>DOMDigestMethod</code> from an element. This constructor
+     * Creates a {@code DOMDigestMethod} from an element. This constructor
      * invokes the abstract {@link #unmarshalParams unmarshalParams} method to
      * unmarshal any algorithm-specific input parameters.
      *
@@ -92,12 +101,26 @@
         String alg = DOMUtils.getAttributeValue(dmElem, "Algorithm");
         if (alg.equals(DigestMethod.SHA1)) {
             return new SHA1(dmElem);
+        } else if (alg.equals(SHA224)) {
+            return new SHA224(dmElem);
         } else if (alg.equals(DigestMethod.SHA256)) {
             return new SHA256(dmElem);
         } else if (alg.equals(SHA384)) {
             return new SHA384(dmElem);
         } else if (alg.equals(DigestMethod.SHA512)) {
             return new SHA512(dmElem);
+        } else if (alg.equals(DigestMethod.RIPEMD160)) {
+            return new RIPEMD160(dmElem);
+        } else if (alg.equals(WHIRLPOOL)) {
+            return new WHIRLPOOL(dmElem);
+        } else if (alg.equals(SHA3_224)) {
+            return new SHA3_224(dmElem);
+        } else if (alg.equals(SHA3_256)) {
+            return new SHA3_256(dmElem);
+        } else if (alg.equals(SHA3_384)) {
+            return new SHA3_384(dmElem);
+        } else if (alg.equals(SHA3_512)) {
+            return new SHA3_512(dmElem);
         } else {
             throw new MarshalException("unsupported DigestMethod algorithm: " +
                                        alg);
@@ -110,7 +133,7 @@
      * since most DigestMethod algorithms do not have parameters. Subclasses
      * should override it if they have parameters.
      *
-     * @param params the algorithm-specific params (may be <code>null</code>)
+     * @param params the algorithm-specific params (may be {@code null})
      * @throws InvalidAlgorithmParameterException if the parameters are not
      *    appropriate for this digest method
      */
@@ -124,18 +147,19 @@
         }
     }
 
+    @Override
     public final AlgorithmParameterSpec getParameterSpec() {
         return params;
     }
 
     /**
-     * Unmarshals <code>DigestMethodParameterSpec</code> from the specified
-     * <code>Element</code>.  By default, this method throws an exception since
+     * Unmarshals {@code DigestMethodParameterSpec} from the specified
+     * {@code Element}.  By default, this method throws an exception since
      * most DigestMethod algorithms do not have parameters. Subclasses should
      * override it if they have parameters.
      *
-     * @param paramsElem the <code>Element</code> holding the input params
-     * @return the algorithm-specific <code>DigestMethodParameterSpec</code>
+     * @param paramsElem the {@code Element} holding the input params
+     * @return the algorithm-specific {@code DigestMethodParameterSpec}
      * @throws MarshalException if the parameters cannot be unmarshalled
      */
     DigestMethodParameterSpec unmarshalParams(Element paramsElem)
@@ -151,20 +175,17 @@
      * This method invokes the abstract {@link #marshalParams marshalParams}
      * method to marshal any algorithm-specific parameters.
      */
-    public void marshal(Node parent, String prefix, DOMCryptoContext context)
+    public static void marshal(XmlWriter xwriter, DigestMethod digest, String prefix)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod",
-                                                XMLSignature.XMLNS, prefix);
-        DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm());
+        xwriter.writeStartElement(prefix, "DigestMethod", XMLSignature.XMLNS);
+        xwriter.writeAttribute("", "", "Algorithm", digest.getAlgorithm());
 
-        if (params != null) {
-            marshalParams(dmElem, prefix);
+        // this is totally over-engineered - nothing implements marshalParams.
+        if (digest.getParameterSpec() != null && digest instanceof DOMDigestMethod) {
+            ( (DOMDigestMethod) digest).marshalParams(xwriter, prefix);
         }
-
-        parent.appendChild(dmElem);
+        xwriter.writeEndElement(); // "DigestMethod"
     }
 
     @Override
@@ -178,10 +199,10 @@
         }
         DigestMethod odm = (DigestMethod)o;
 
-        boolean paramsEqual = (params == null ? odm.getParameterSpec() == null :
-            params.equals(odm.getParameterSpec()));
+        boolean paramsEqual = params == null ? odm.getParameterSpec() == null :
+            params.equals(odm.getParameterSpec());
 
-        return (getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual);
+        return getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual;
     }
 
     @Override
@@ -205,7 +226,7 @@
      * @param the namespace prefix to use
      * @throws MarshalException if the parameters cannot be marshalled
      */
-    void marshalParams(Element parent, String prefix)
+    void marshalParams(XmlWriter xwriter, String prefix)
         throws MarshalException
     {
         throw new MarshalException("no parameters should " +
@@ -227,14 +248,34 @@
         SHA1(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return DigestMethod.SHA1;
         }
+        @Override
         String getMessageDigestAlgorithm() {
             return "SHA-1";
         }
     }
 
+    static final class SHA224 extends DOMDigestMethod {
+        SHA224(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA224(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return SHA224;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "SHA-224";
+        }
+    }
+
     static final class SHA256 extends DOMDigestMethod {
         SHA256(AlgorithmParameterSpec params)
             throws InvalidAlgorithmParameterException {
@@ -243,9 +284,11 @@
         SHA256(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return DigestMethod.SHA256;
         }
+        @Override
         String getMessageDigestAlgorithm() {
             return "SHA-256";
         }
@@ -259,9 +302,11 @@
         SHA384(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return SHA384;
         }
+        @Override
         String getMessageDigestAlgorithm() {
             return "SHA-384";
         }
@@ -275,11 +320,121 @@
         SHA512(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return DigestMethod.SHA512;
         }
+        @Override
         String getMessageDigestAlgorithm() {
             return "SHA-512";
         }
     }
+
+    static final class RIPEMD160 extends DOMDigestMethod {
+        RIPEMD160(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        RIPEMD160(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return DigestMethod.RIPEMD160;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "RIPEMD160";
+        }
+    }
+
+    static final class WHIRLPOOL extends DOMDigestMethod {
+        WHIRLPOOL(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        WHIRLPOOL(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return WHIRLPOOL;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "WHIRLPOOL";
+        }
+    }
+
+    static final class SHA3_224 extends DOMDigestMethod {
+        SHA3_224(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA3_224(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return SHA3_224;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "SHA3-224";
+        }
+    }
+
+    static final class SHA3_256 extends DOMDigestMethod {
+        SHA3_256(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA3_256(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return SHA3_256;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "SHA3-256";
+        }
+    }
+
+    static final class SHA3_384 extends DOMDigestMethod {
+        SHA3_384(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA3_384(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return SHA3_384;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "SHA3-384";
+        }
+    }
+
+    static final class SHA3_512 extends DOMDigestMethod {
+        SHA3_512(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA3_512(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return SHA3_512;
+        }
+        @Override
+        String getMessageDigestAlgorithm() {
+            return "SHA3-512";
+        }
+    }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMEnvelopedTransform.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMEnvelopedTransform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -35,10 +35,10 @@
  * DOM-based implementation of Enveloped Signature Transform.
  * (Uses Apache XML-Sec Transform implementation)
  *
- * @author Sean Mullan
  */
 public final class DOMEnvelopedTransform extends ApacheTransform {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException {
         if (params != null) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMExcC14NMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -37,8 +37,8 @@
 import java.security.InvalidAlgorithmParameterException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.util.*;
+
 import org.w3c.dom.Element;
-
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
 
@@ -47,10 +47,10 @@
  * Canonical XML algorithm (with or without comments).
  * Uses Apache XML-Sec Canonicalizer.
  *
- * @author Sean Mullan
  */
 public final class DOMExcC14NMethod extends ApacheCanonicalizer {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException
     {
@@ -63,6 +63,7 @@
         }
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException
     {
@@ -81,7 +82,7 @@
         this.inclusiveNamespaces = prefixListAttr;
         int begin = 0;
         int end = prefixListAttr.indexOf(' ');
-        List<String> prefixList = new ArrayList<String>();
+        List<String> prefixList = new ArrayList<>();
         while (end != -1) {
             prefixList.add(prefixListAttr.substring(begin, end));
             begin = end + 1;
@@ -93,6 +94,12 @@
         this.params = new ExcC14NParameterSpec(prefixList);
     }
 
+    @SuppressWarnings("unchecked")
+    public List<String> getParameterSpecPrefixList(ExcC14NParameterSpec paramSpec) {
+        return paramSpec.getPrefixList();
+    }
+
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -102,39 +109,32 @@
             return;
         }
 
-        String prefix = DOMUtils.getNSPrefix(context,
-                                             CanonicalizationMethod.EXCLUSIVE);
-        Element eElem = DOMUtils.createElement(ownerDoc,
-                                               "InclusiveNamespaces",
-                                               CanonicalizationMethod.EXCLUSIVE,
-                                               prefix);
-        if (prefix == null || prefix.length() == 0) {
-            eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
-                                 CanonicalizationMethod.EXCLUSIVE);
-        } else {
-            eElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
-                                   "xmlns:" + prefix,
-                                   CanonicalizationMethod.EXCLUSIVE);
-        }
+        XmlWriterToTree xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), transformElem);
+
+        String prefix =
+            DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE);
+        xwriter.writeStartElement(prefix, "InclusiveNamespaces", CanonicalizationMethod.EXCLUSIVE);
+        xwriter.writeNamespace(prefix, CanonicalizationMethod.EXCLUSIVE);
 
         ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec;
         StringBuilder prefixListAttr = new StringBuilder("");
-        List<String> prefixList = params.getPrefixList();
+        List<String> prefixList = getParameterSpecPrefixList(params);
         for (int i = 0, size = prefixList.size(); i < size; i++) {
             prefixListAttr.append(prefixList.get(i));
             if (i < size - 1) {
                 prefixListAttr.append(" ");
             }
         }
-        DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString());
+        xwriter.writeAttribute("", "", "PrefixList", prefixListAttr.toString());
         this.inclusiveNamespaces = prefixListAttr.toString();
-        transformElem.appendChild(eElem);
+        xwriter.writeEndElement(); // "InclusiveNamespaces"
     }
 
     public String getParamsNSURI() {
         return CanonicalizationMethod.EXCLUSIVE;
     }
 
+    @Override
     public Data transform(Data data, XMLCryptoContext xc)
         throws TransformException
     {
@@ -147,6 +147,8 @@
                 try {
                     apacheCanonicalizer = Canonicalizer.getInstance
                         (CanonicalizationMethod.EXCLUSIVE);
+                    boolean secVal = Utils.secureValidation(xc);
+                    apacheCanonicalizer.setSecureValidation(secVal);
                 } catch (InvalidCanonicalizerException ice) {
                     throw new TransformException
                         ("Couldn't find Canonicalizer for: " +
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMHMACSignatureMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -42,7 +42,6 @@
 import java.security.spec.AlgorithmParameterSpec;
 import javax.crypto.Mac;
 import javax.crypto.SecretKey;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 import org.jcp.xml.dsig.internal.MacOutputStream;
@@ -50,20 +49,23 @@
 /**
  * DOM-based implementation of HMAC SignatureMethod.
  *
- * @author Sean Mullan
  */
 public abstract class DOMHMACSignatureMethod extends AbstractDOMSignatureMethod {
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DOMHMACSignatureMethod.class);
 
     // see RFC 4051 for these algorithm definitions
+    static final String HMAC_SHA224 =
+        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha224";
     static final String HMAC_SHA256 =
         "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
     static final String HMAC_SHA384 =
         "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
     static final String HMAC_SHA512 =
         "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
+    static final String HMAC_RIPEMD160 =
+        "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
 
     private Mac hmac;
     private int outputLength;
@@ -71,9 +73,9 @@
     private SignatureMethodParameterSpec params;
 
     /**
-     * Creates a <code>DOMHMACSignatureMethod</code> with the specified params
+     * Creates a {@code DOMHMACSignatureMethod} with the specified params
      *
-     * @param params algorithm-specific parameters (may be <code>null</code>)
+     * @param params algorithm-specific parameters (may be {@code null})
      * @throws InvalidAlgorithmParameterException if params are inappropriate
      */
     DOMHMACSignatureMethod(AlgorithmParameterSpec params)
@@ -84,7 +86,7 @@
     }
 
     /**
-     * Creates a <code>DOMHMACSignatureMethod</code> from an element.
+     * Creates a {@code DOMHMACSignatureMethod} from an element.
      *
      * @param smElem a SignatureMethod element
      */
@@ -100,6 +102,7 @@
         }
     }
 
+    @Override
     void checkParams(SignatureMethodParameterSpec params)
         throws InvalidAlgorithmParameterException
     {
@@ -110,40 +113,34 @@
             }
             outputLength = ((HMACParameterSpec)params).getOutputLength();
             outputLengthSet = true;
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength);
-            }
+            LOG.debug("Setting outputLength from HMACParameterSpec to: {}", outputLength);
         }
     }
 
+    @Override
     public final AlgorithmParameterSpec getParameterSpec() {
         return params;
     }
 
+    @Override
     SignatureMethodParameterSpec unmarshalParams(Element paramsElem)
         throws MarshalException
     {
-        outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue();
+        outputLength = Integer.parseInt(textOfNode(paramsElem));
         outputLengthSet = true;
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength);
-        }
+        LOG.debug("unmarshalled outputLength: {}", outputLength);
         return new HMACParameterSpec(outputLength);
     }
 
-    void marshalParams(Element parent, String prefix)
+    @Override
+    void marshalParams(XmlWriter xwriter, String prefix)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength",
-                                                  XMLSignature.XMLNS, prefix);
-        hmacElem.appendChild(ownerDoc.createTextNode
-           (String.valueOf(outputLength)));
-
-        parent.appendChild(hmacElem);
+        xwriter.writeTextElement(prefix, "HMACOutputLength", XMLSignature.XMLNS, String.valueOf(outputLength));
     }
 
-    boolean verify(Key key, SignedInfo si, byte[] sig,
+    @Override
+    boolean verify(Key key, DOMSignedInfo si, byte[] sig,
                    XMLValidateContext context)
         throws InvalidKeyException, SignatureException, XMLSignatureException
     {
@@ -164,14 +161,15 @@
             throw new XMLSignatureException
                 ("HMACOutputLength must not be less than " + getDigestLength());
         }
-        hmac.init((SecretKey)key);
-        ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
+        hmac.init(key);
+        si.canonicalize(context, new MacOutputStream(hmac));
         byte[] result = hmac.doFinal();
 
         return MessageDigest.isEqual(sig, result);
     }
 
-    byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+    @Override
+    byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
         throws InvalidKeyException, XMLSignatureException
     {
         if (key == null || si == null) {
@@ -191,11 +189,12 @@
             throw new XMLSignatureException
                 ("HMACOutputLength must not be less than " + getDigestLength());
         }
-        hmac.init((SecretKey)key);
-        ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
+        hmac.init(key);
+        si.canonicalize(context, new MacOutputStream(hmac));
         return hmac.doFinal();
     }
 
+    @Override
     boolean paramsEqual(AlgorithmParameterSpec spec) {
         if (getParameterSpec() == spec) {
             return true;
@@ -205,9 +204,10 @@
         }
         HMACParameterSpec ospec = (HMACParameterSpec)spec;
 
-        return (outputLength == ospec.getOutputLength());
+        return outputLength == ospec.getOutputLength();
     }
 
+    @Override
     Type getAlgorithmType() {
         return Type.HMAC;
     }
@@ -225,17 +225,42 @@
         SHA1(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return SignatureMethod.HMAC_SHA1;
         }
+        @Override
         String getJCAAlgorithm() {
             return "HmacSHA1";
         }
+        @Override
         int getDigestLength() {
             return 160;
         }
     }
 
+    static final class SHA224 extends DOMHMACSignatureMethod {
+        SHA224(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA224(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return HMAC_SHA224;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "HmacSHA224";
+        }
+        @Override
+        int getDigestLength() {
+            return 224;
+        }
+    }
+
     static final class SHA256 extends DOMHMACSignatureMethod {
         SHA256(AlgorithmParameterSpec params)
             throws InvalidAlgorithmParameterException {
@@ -244,12 +269,15 @@
         SHA256(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return HMAC_SHA256;
         }
+        @Override
         String getJCAAlgorithm() {
             return "HmacSHA256";
         }
+        @Override
         int getDigestLength() {
             return 256;
         }
@@ -263,12 +291,15 @@
         SHA384(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return HMAC_SHA384;
         }
+        @Override
         String getJCAAlgorithm() {
             return "HmacSHA384";
         }
+        @Override
         int getDigestLength() {
             return 384;
         }
@@ -282,14 +313,39 @@
         SHA512(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return HMAC_SHA512;
         }
+        @Override
         String getJCAAlgorithm() {
             return "HmacSHA512";
         }
+        @Override
         int getDigestLength() {
             return 512;
         }
     }
+
+    static final class RIPEMD160 extends DOMHMACSignatureMethod {
+        RIPEMD160(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        RIPEMD160(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return HMAC_RIPEMD160;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "HMACRIPEMD160";
+        }
+        @Override
+        int getDigestLength() {
+            return 160;
+        }
+    }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,66 +21,79 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: DOMKeyInfo.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
-import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dsig.keyinfo.KeyInfo;
-import javax.xml.crypto.dom.*;
+import java.security.Provider;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 
-import java.security.Provider;
-import java.util.*;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.XMLStructure;
+import javax.xml.crypto.dsig.XMLSignature;
+import javax.xml.crypto.dsig.dom.DOMSignContext;
+import javax.xml.crypto.dsig.keyinfo.KeyInfo;
 
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * DOM-based implementation of KeyInfo.
  *
- * @author Sean Mullan
  */
-public final class DOMKeyInfo extends DOMStructure implements KeyInfo {
+public final class DOMKeyInfo extends BaseStructure implements KeyInfo {
 
     private final String id;
     private final List<XMLStructure> keyInfoTypes;
 
     /**
-     * Creates a <code>DOMKeyInfo</code>.
+     * A utility function to suppress casting warnings.
+     * @param ki
+     * @return the content of a KeyInfo Object
+     */
+    @SuppressWarnings("unchecked")
+    public static List<XMLStructure> getContent(KeyInfo ki) {
+        return ki.getContent();
+    }
+
+    /**
+     * Creates a {@code DOMKeyInfo}.
      *
      * @param content a list of one or more {@link XMLStructure}s representing
      *    key information types. The list is defensively copied to protect
      *    against subsequent modification.
      * @param id an ID attribute
-     * @throws NullPointerException if <code>content</code> is <code>null</code>
-     * @throws IllegalArgumentException if <code>content</code> is empty
-     * @throws ClassCastException if <code>content</code> contains any entries
+     * @throws NullPointerException if {@code content} is {@code null}
+     * @throws IllegalArgumentException if {@code content} is empty
+     * @throws ClassCastException if {@code content} contains any entries
      *    that are not of type {@link XMLStructure}
      */
     public DOMKeyInfo(List<? extends XMLStructure> content, String id) {
         if (content == null) {
             throw new NullPointerException("content cannot be null");
         }
-        List<XMLStructure> tempList =
-            Collections.checkedList(new ArrayList<XMLStructure>(),
-                                    XMLStructure.class);
-        tempList.addAll(content);
-        this.keyInfoTypes = Collections.unmodifiableList(tempList);
+        this.keyInfoTypes =
+            Collections.unmodifiableList(new ArrayList<>(content));
         if (this.keyInfoTypes.isEmpty()) {
             throw new IllegalArgumentException("content cannot be empty");
         }
+        for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) {
+            if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) {
+                throw new ClassCastException
+                    ("content["+i+"] is not a valid KeyInfo type");
+            }
+        }
         this.id = id;
     }
 
     /**
-     * Creates a <code>DOMKeyInfo</code> from XML.
+     * Creates a {@code DOMKeyInfo} from XML.
      *
      * @param kiElem KeyInfo element
      */
@@ -88,57 +101,50 @@
                       Provider provider)
         throws MarshalException
     {
-        // get Id attribute, if specified
-        Attr attr = kiElem.getAttributeNodeNS(null, "Id");
-        if (attr != null) {
-            id = attr.getValue();
-            kiElem.setIdAttributeNode(attr, true);
-        } else {
-            id = null;
-        }
+        id = DOMUtils.getIdAttributeValue(kiElem, "Id");
 
         // get all children nodes
-        NodeList nl = kiElem.getChildNodes();
-        int length = nl.getLength();
-        if (length < 1) {
-            throw new MarshalException
-                ("KeyInfo must contain at least one type");
+        List<XMLStructure> content = new ArrayList<>();
+        Node firstChild = kiElem.getFirstChild();
+        if (firstChild == null) {
+            throw new MarshalException("KeyInfo must contain at least one type");
         }
-        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
-        for (int i = 0; i < length; i++) {
-            Node child = nl.item(i);
-            // ignore all non-Element nodes
-            if (child.getNodeType() != Node.ELEMENT_NODE) {
-                continue;
+        while (firstChild != null) {
+            if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                Element childElem = (Element)firstChild;
+                String localName = childElem.getLocalName();
+                String namespace = childElem.getNamespaceURI();
+                if ("X509Data".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    content.add(new DOMX509Data(childElem));
+                } else if ("KeyName".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    content.add(new DOMKeyName(childElem));
+                } else if ("KeyValue".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    content.add(DOMKeyValue.unmarshal(childElem));
+                } else if ("RetrievalMethod".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    content.add(new DOMRetrievalMethod(childElem,
+                                                       context, provider));
+                } else if ("PGPData".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    content.add(new DOMPGPData(childElem));
+                } else { //may be MgmtData, SPKIData or element from other namespace
+                    content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
+                }
             }
-            Element childElem = (Element)child;
-            String localName = childElem.getLocalName();
-            if (localName.equals("X509Data")) {
-                content.add(new DOMX509Data(childElem));
-            } else if (localName.equals("KeyName")) {
-                content.add(new DOMKeyName(childElem));
-            } else if (localName.equals("KeyValue")) {
-                content.add(DOMKeyValue.unmarshal(childElem));
-            } else if (localName.equals("RetrievalMethod")) {
-                content.add(new DOMRetrievalMethod(childElem,
-                                                   context, provider));
-            } else if (localName.equals("PGPData")) {
-                content.add(new DOMPGPData(childElem));
-            } else { //may be MgmtData, SPKIData or element from other namespace
-                content.add(new javax.xml.crypto.dom.DOMStructure((childElem)));
-            }
+            firstChild = firstChild.getNextSibling();
         }
         keyInfoTypes = Collections.unmodifiableList(content);
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public List<XMLStructure> getContent() {
         return keyInfoTypes;
     }
 
+    @Override
     public void marshal(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -149,56 +155,44 @@
             throw new ClassCastException("parent must be of type DOMStructure");
         }
 
-        Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
-        String dsPrefix = DOMUtils.getSignaturePrefix(context);
-        Element kiElem = DOMUtils.createElement
-            (DOMUtils.getOwnerDocument(pNode), "KeyInfo",
-             XMLSignature.XMLNS, dsPrefix);
-        if (dsPrefix == null || dsPrefix.length() == 0) {
-            kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
-                                  "xmlns", XMLSignature.XMLNS);
-        } else {
-            kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
-                                  "xmlns:" + dsPrefix, XMLSignature.XMLNS);
-        }
-        marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context);
+        internalMarshal( (javax.xml.crypto.dom.DOMStructure) parent, context);
     }
 
-    public void marshal(Node parent, String dsPrefix,
-                        DOMCryptoContext context)
-        throws MarshalException
-    {
-        marshal(parent, null, dsPrefix, context);
+    private void internalMarshal(javax.xml.crypto.dom.DOMStructure parent, XMLCryptoContext context)
+            throws MarshalException {
+        Node pNode = parent.getNode();
+        String dsPrefix = DOMUtils.getSignaturePrefix(context);
+
+        Node nextSibling = null;
+        if (context instanceof DOMSignContext) {
+            nextSibling = ((DOMSignContext)context).getNextSibling();
+        }
+
+        XmlWriterToTree xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), pNode, nextSibling);
+        marshalInternal(xwriter, this, dsPrefix, context, true);
     }
 
-    public void marshal(Node parent, Node nextSibling, String dsPrefix,
-                        DOMCryptoContext context)
-        throws MarshalException
-    {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo",
-                                                XMLSignature.XMLNS, dsPrefix);
-        marshal(parent, kiElem, nextSibling, dsPrefix, context);
+    public static void marshal(XmlWriter xwriter, KeyInfo ki, String dsPrefix,
+    XMLCryptoContext context) throws MarshalException {
+        marshalInternal(xwriter, ki, dsPrefix, context, false);
     }
 
-    private void marshal(Node parent, Element kiElem, Node nextSibling,
-                         String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        // create and append KeyInfoType elements
-        for (XMLStructure kiType : keyInfoTypes) {
-            if (kiType instanceof DOMStructure) {
-                ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context);
-            } else {
-                DOMUtils.appendChild(kiElem,
-                    ((javax.xml.crypto.dom.DOMStructure)kiType).getNode());
-            }
+    private static void marshalInternal(XmlWriter xwriter, KeyInfo ki,
+        String dsPrefix, XMLCryptoContext context, boolean declareNamespace) throws MarshalException {
+
+        xwriter.writeStartElement(dsPrefix, "KeyInfo", XMLSignature.XMLNS);
+        if (declareNamespace) {
+            xwriter.writeNamespace(dsPrefix, XMLSignature.XMLNS);
         }
 
-        // append id attribute
-        DOMUtils.setAttributeID(kiElem, "Id", id);
+        xwriter.writeIdAttribute("", "", "Id", ki.getId());
+        // create and append KeyInfoType elements
+        List<XMLStructure> keyInfoTypes = getContent(ki);
+        for (XMLStructure kiType : keyInfoTypes) {
+            xwriter.marshalStructure(kiType, dsPrefix, context);
+        }
 
-        parent.insertBefore(kiElem, nextSibling);
+        xwriter.writeEndElement(); // "KeyInfo"
     }
 
     @Override
@@ -212,10 +206,10 @@
         }
         KeyInfo oki = (KeyInfo)o;
 
-        boolean idsEqual = (id == null ? oki.getId() == null
-                                       : id.equals(oki.getId()));
+        boolean idsEqual = id == null ? oki.getId() == null
+                                       : id.equals(oki.getId());
 
-        return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
+        return keyInfoTypes.equals(oki.getContent()) && idsEqual;
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,21 +21,26 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: DOMKeyInfoFactory.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.math.BigInteger;
 import java.security.KeyException;
 import java.security.PublicKey;
+import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
 import java.util.List;
+
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.Transform;
+import javax.xml.crypto.dsig.XMLSignature;
 import javax.xml.crypto.dsig.keyinfo.*;
+
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -43,72 +48,87 @@
 /**
  * DOM-based implementation of KeyInfoFactory.
  *
- * @author Sean Mullan
  */
 public final class DOMKeyInfoFactory extends KeyInfoFactory {
 
     public DOMKeyInfoFactory() { }
 
-    public KeyInfo newKeyInfo(List<? extends XMLStructure> content) {
+    @Override
+    @SuppressWarnings("rawtypes")
+    public KeyInfo newKeyInfo(List content) {
         return newKeyInfo(content, null);
     }
 
-    public KeyInfo newKeyInfo(List<? extends XMLStructure> content, String id) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public KeyInfo newKeyInfo(List content, String id) {
         return new DOMKeyInfo(content, id);
     }
 
+    @Override
     public KeyName newKeyName(String name) {
         return new DOMKeyName(name);
     }
 
+    @Override
     public KeyValue newKeyValue(PublicKey key)  throws KeyException {
         String algorithm = key.getAlgorithm();
-        if (algorithm.equals("DSA")) {
-            return new DOMKeyValue.DSA(key);
-        } else if (algorithm.equals("RSA")) {
-            return new DOMKeyValue.RSA(key);
-        } else if (algorithm.equals("EC")) {
-            return new DOMKeyValue.EC(key);
+        if ("DSA".equals(algorithm)) {
+            return new DOMKeyValue.DSA((DSAPublicKey) key);
+        } else if ("RSA".equals(algorithm)) {
+            return new DOMKeyValue.RSA((RSAPublicKey) key);
+        } else if ("EC".equals(algorithm)) {
+            return new DOMKeyValue.EC((ECPublicKey) key);
         } else {
             throw new KeyException("unsupported key algorithm: " + algorithm);
         }
     }
 
+    @Override
     public PGPData newPGPData(byte[] keyId) {
         return newPGPData(keyId, null, null);
     }
 
-    public PGPData newPGPData(byte[] keyId, byte[] keyPacket,
-        List<? extends XMLStructure> other) {
+    @Override
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) {
         return new DOMPGPData(keyId, keyPacket, other);
     }
 
-    public PGPData newPGPData(byte[] keyPacket,
-        List<? extends XMLStructure> other) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public PGPData newPGPData(byte[] keyPacket, List other) {
         return new DOMPGPData(keyPacket, other);
     }
 
+    @Override
     public RetrievalMethod newRetrievalMethod(String uri) {
         return newRetrievalMethod(uri, null, null);
     }
 
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
     public RetrievalMethod newRetrievalMethod(String uri, String type,
-        List<? extends Transform> transforms) {
+        List transforms) {
         if (uri == null) {
             throw new NullPointerException("uri must not be null");
         }
         return new DOMRetrievalMethod(uri, type, transforms);
     }
 
-    public X509Data newX509Data(List<?> content) {
+    @Override
+    @SuppressWarnings("rawtypes")
+    public X509Data newX509Data(List content) {
         return new DOMX509Data(content);
     }
 
+    @Override
     public X509IssuerSerial newX509IssuerSerial(String issuerName,
         BigInteger serialNumber) {
         return new DOMX509IssuerSerial(issuerName, serialNumber);
     }
 
+    @Override
     public boolean isFeatureSupported(String feature) {
         if (feature == null) {
             throw new NullPointerException();
@@ -117,10 +137,12 @@
         }
     }
 
+    @Override
     public URIDereferencer getURIDereferencer() {
         return DOMURIDereferencer.INSTANCE;
     }
 
+    @Override
     public KeyInfo unmarshalKeyInfo(XMLStructure xmlStructure)
         throws MarshalException {
         if (xmlStructure == null) {
@@ -145,14 +167,15 @@
 
         // check tag
         String tag = element.getLocalName();
-        if (tag == null) {
+        String namespace = element.getNamespaceURI();
+        if (tag == null || namespace == null) {
             throw new MarshalException("Document implementation must " +
                 "support DOM Level 2 and be namespace aware");
         }
-        if (tag.equals("KeyInfo")) {
+        if ("KeyInfo".equals(tag) && XMLSignature.XMLNS.equals(namespace)) {
             return new DOMKeyInfo(element, new UnmarshalContext(), getProvider());
         } else {
-            throw new MarshalException("invalid KeyInfo tag: " + tag);
+            throw new MarshalException("invalid KeyInfo tag: " + namespace + ":" + tag);
         }
     }
 
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,36 +21,30 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyName.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMKeyName.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
-import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.keyinfo.KeyName;
 
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * DOM-based implementation of KeyName.
  *
- * @author Sean Mullan
  */
-public final class DOMKeyName extends DOMStructure implements KeyName {
+public final class DOMKeyName extends BaseStructure implements KeyName {
 
     private final String name;
 
     /**
-     * Creates a <code>DOMKeyName</code>.
+     * Creates a {@code DOMKeyName}.
      *
      * @param name the name of the key identifier
-     * @throws NullPointerException if <code>name</code> is null
+     * @throws NullPointerException if {@code name} is null
      */
     public DOMKeyName(String name) {
         if (name == null) {
@@ -60,27 +54,17 @@
     }
 
     /**
-     * Creates a <code>DOMKeyName</code> from a KeyName element.
+     * Creates a {@code DOMKeyName} from a KeyName element.
      *
      * @param knElem a KeyName element
      */
     public DOMKeyName(Element knElem) {
-        name = knElem.getFirstChild().getNodeValue();
-    }
-
-    public String getName() {
-        return name;
+        name = textOfNode(knElem);
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        // prepend namespace prefix, if necessary
-        Element knElem = DOMUtils.createElement(ownerDoc, "KeyName",
-                                                XMLSignature.XMLNS, dsPrefix);
-        knElem.appendChild(ownerDoc.createTextNode(name));
-        parent.appendChild(knElem);
+    @Override
+    public String getName() {
+        return name;
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,15 +21,14 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMKeyValue.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.keyinfo.KeyValue;
 
@@ -54,25 +53,22 @@
 import java.security.spec.KeySpec;
 import java.security.spec.RSAPublicKeySpec;
 import java.util.Arrays;
-import org.w3c.dom.Document;
+import java.util.Base64;
+
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 
 /**
  * DOM-based implementation of KeyValue.
  *
- * @author Sean Mullan
  */
-public abstract class DOMKeyValue extends DOMStructure implements KeyValue {
+public abstract class DOMKeyValue<K extends PublicKey> extends BaseStructure implements KeyValue {
 
     private static final String XMLDSIG_11_XMLNS
         = "http://www.w3.org/2009/xmldsig11#";
-    private final PublicKey publicKey;
+    private final K publicKey;
 
-    public DOMKeyValue(PublicKey key) throws KeyException {
+    public DOMKeyValue(K key) throws KeyException {
         if (key == null) {
             throw new NullPointerException("key cannot be null");
         }
@@ -80,7 +76,7 @@
     }
 
     /**
-     * Creates a <code>DOMKeyValue</code> from an element.
+     * Creates a {@code DOMKeyValue} from an element.
      *
      * @param kvtElem a KeyValue child element
      */
@@ -90,17 +86,23 @@
 
     static KeyValue unmarshal(Element kvElem) throws MarshalException {
         Element kvtElem = DOMUtils.getFirstChildElement(kvElem);
-        if (kvtElem.getLocalName().equals("DSAKeyValue")) {
+        if (kvtElem == null) {
+            throw new MarshalException("KeyValue must contain at least one type");
+        }
+
+        String namespace = kvtElem.getNamespaceURI();
+        if (kvtElem.getLocalName().equals("DSAKeyValue") && XMLSignature.XMLNS.equals(namespace)) {
             return new DSA(kvtElem);
-        } else if (kvtElem.getLocalName().equals("RSAKeyValue")) {
+        } else if (kvtElem.getLocalName().equals("RSAKeyValue") && XMLSignature.XMLNS.equals(namespace)) {
             return new RSA(kvtElem);
-        } else if (kvtElem.getLocalName().equals("ECKeyValue")) {
+        } else if (kvtElem.getLocalName().equals("ECKeyValue") && XMLDSIG_11_XMLNS.equals(namespace)) {
             return new EC(kvtElem);
         } else {
             return new Unknown(kvtElem);
         }
     }
 
+    @Override
     public PublicKey getPublicKey() throws KeyException {
         if (publicKey == null) {
             throw new KeyException("can't convert KeyValue to PublicKey");
@@ -109,30 +111,26 @@
         }
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
         // create KeyValue element
-        Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue",
-                                                XMLSignature.XMLNS, dsPrefix);
-        marshalPublicKey(kvElem, ownerDoc, dsPrefix, context);
-
-        parent.appendChild(kvElem);
+        xwriter.writeStartElement(dsPrefix, "KeyValue", XMLSignature.XMLNS);
+        marshalPublicKey(xwriter, publicKey, dsPrefix, context);
+        xwriter.writeEndElement(); // "KeyValue"
     }
 
-    abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException;
+    abstract void marshalPublicKey(XmlWriter xwriter, K key, String dsPrefix,
+        XMLCryptoContext context) throws MarshalException;
 
-    abstract PublicKey unmarshalKeyValue(Element kvtElem)
+    abstract K unmarshalKeyValue(Element kvtElem)
         throws MarshalException;
 
     private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) {
         try {
             return kf.generatePublic(keyspec);
         } catch (InvalidKeySpecException e) {
-            //@@@ should dump exception to log
+            //@@@ should dump exception to LOG
             return null;
         }
     }
@@ -162,6 +160,27 @@
         return true;
     }
 
+    public static BigInteger decode(Element elem) throws MarshalException {
+        try {
+            String base64str = BaseStructure.textOfNode(elem);
+            return new BigInteger(1, Base64.getMimeDecoder().decode(base64str));
+        } catch (Exception ex) {
+            throw new MarshalException(ex);
+        }
+    }
+
+    public static void writeBase64BigIntegerElement(
+        XmlWriter xwriter, String prefix, String localName, String namespaceURI, BigInteger value
+    ) {
+        byte[] bytes = XMLUtils.getBytes(value, value.bitLength());
+        xwriter.writeTextElement(prefix, localName, namespaceURI, Base64.getMimeEncoder().encodeToString(bytes));
+    }
+
+    public static void marshal(XmlWriter xwriter, BigInteger bigNum) {
+        byte[] bytes = XMLUtils.getBytes(bigNum, bigNum.bitLength());
+        xwriter.writeCharacters(Base64.getMimeEncoder().encodeToString(bytes));
+    }
+
     @Override
     public int hashCode() {
         int result = 17;
@@ -172,41 +191,31 @@
         return result;
     }
 
-    static final class RSA extends DOMKeyValue {
+    static final class RSA extends DOMKeyValue<RSAPublicKey> {
         // RSAKeyValue CryptoBinaries
-        private DOMCryptoBinary modulus, exponent;
         private KeyFactory rsakf;
 
-        RSA(PublicKey key) throws KeyException {
+        RSA(RSAPublicKey key) throws KeyException {
             super(key);
-            RSAPublicKey rkey = (RSAPublicKey)key;
-            exponent = new DOMCryptoBinary(rkey.getPublicExponent());
-            modulus = new DOMCryptoBinary(rkey.getModulus());
         }
 
         RSA(Element elem) throws MarshalException {
             super(elem);
         }
 
-        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-            DOMCryptoContext context) throws MarshalException {
-            Element rsaElem = DOMUtils.createElement(doc, "RSAKeyValue",
-                                                     XMLSignature.XMLNS,
-                                                     dsPrefix);
-            Element modulusElem = DOMUtils.createElement(doc, "Modulus",
-                                                         XMLSignature.XMLNS,
-                                                         dsPrefix);
-            Element exponentElem = DOMUtils.createElement(doc, "Exponent",
-                                                          XMLSignature.XMLNS,
-                                                          dsPrefix);
-            modulus.marshal(modulusElem, dsPrefix, context);
-            exponent.marshal(exponentElem, dsPrefix, context);
-            rsaElem.appendChild(modulusElem);
-            rsaElem.appendChild(exponentElem);
-            parent.appendChild(rsaElem);
+        @Override
+        void marshalPublicKey(XmlWriter xwriter, RSAPublicKey publicKey, String dsPrefix,
+            XMLCryptoContext context) throws MarshalException {
+            xwriter.writeStartElement(dsPrefix, "RSAKeyValue", XMLSignature.XMLNS);
+
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "Modulus", XMLSignature.XMLNS, publicKey.getModulus());
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "Exponent", XMLSignature.XMLNS, publicKey.getPublicExponent());
+
+            xwriter.writeEndElement(); // "RSAKeyValue"
         }
 
-        PublicKey unmarshalKeyValue(Element kvtElem)
+        @Override
+        RSAPublicKey unmarshalKeyValue(Element kvtElem)
             throws MarshalException
         {
             if (rsakf == null) {
@@ -218,64 +227,50 @@
                 }
             }
             Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
-                                                                "Modulus");
-            modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
+                                                                "Modulus",
+                                                                XMLSignature.XMLNS);
+            BigInteger modulus = decode(modulusElem);
             Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
-                                                                  "Exponent");
-            exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
-            RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
-                                                         exponent.getBigNum());
-            return generatePublicKey(rsakf, spec);
+                                                                  "Exponent",
+                                                                  XMLSignature.XMLNS);
+            BigInteger exponent = decode(exponentElem);
+            RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
+            return (RSAPublicKey) generatePublicKey(rsakf, spec);
         }
     }
 
-    static final class DSA extends DOMKeyValue {
+    static final class DSA extends DOMKeyValue<DSAPublicKey> {
         // DSAKeyValue CryptoBinaries
-        private DOMCryptoBinary p, q, g, y, j; //, seed, pgen;
         private KeyFactory dsakf;
 
-        DSA(PublicKey key) throws KeyException {
+        DSA(DSAPublicKey key) throws KeyException {
             super(key);
-            DSAPublicKey dkey = (DSAPublicKey) key;
-            DSAParams params = dkey.getParams();
-            p = new DOMCryptoBinary(params.getP());
-            q = new DOMCryptoBinary(params.getQ());
-            g = new DOMCryptoBinary(params.getG());
-            y = new DOMCryptoBinary(dkey.getY());
         }
 
         DSA(Element elem) throws MarshalException {
             super(elem);
         }
 
-        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-                              DOMCryptoContext context)
+        @Override
+        void marshalPublicKey(XmlWriter xwriter, DSAPublicKey publicKey, String dsPrefix,
+                XMLCryptoContext context)
             throws MarshalException
         {
-            Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue",
-                                                     XMLSignature.XMLNS,
-                                                     dsPrefix);
+            DSAParams params = publicKey.getParams();
+
+            xwriter.writeStartElement(dsPrefix, "DSAKeyValue", XMLSignature.XMLNS);
+
             // parameters J, Seed & PgenCounter are not included
-            Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS,
-                                                   dsPrefix);
-            Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS,
-                                                   dsPrefix);
-            Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS,
-                                                   dsPrefix);
-            Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS,
-                                                   dsPrefix);
-            p.marshal(pElem, dsPrefix, context);
-            q.marshal(qElem, dsPrefix, context);
-            g.marshal(gElem, dsPrefix, context);
-            y.marshal(yElem, dsPrefix, context);
-            dsaElem.appendChild(pElem);
-            dsaElem.appendChild(qElem);
-            dsaElem.appendChild(gElem);
-            dsaElem.appendChild(yElem);
-            parent.appendChild(dsaElem);
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "P", XMLSignature.XMLNS, params.getP());
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "Q", XMLSignature.XMLNS, params.getQ());
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "G", XMLSignature.XMLNS, params.getG());
+            writeBase64BigIntegerElement(xwriter, dsPrefix, "Y", XMLSignature.XMLNS, publicKey.getY() );
+
+            xwriter.writeEndElement(); // "DSAKeyValue"
         }
 
-        PublicKey unmarshalKeyValue(Element kvtElem)
+        @Override
+        DSAPublicKey unmarshalKeyValue(Element kvtElem)
             throws MarshalException
         {
             if (dsakf == null) {
@@ -287,40 +282,41 @@
                 }
             }
             Element curElem = DOMUtils.getFirstChildElement(kvtElem);
+            if (curElem == null) {
+                throw new MarshalException("KeyValue must contain at least one type");
+            }
             // check for P and Q
-            if (curElem.getLocalName().equals("P")) {
-                p = new DOMCryptoBinary(curElem.getFirstChild());
-                curElem = DOMUtils.getNextSiblingElement(curElem, "Q");
-                q = new DOMCryptoBinary(curElem.getFirstChild());
+            BigInteger p = null;
+            BigInteger q = null;
+            if (curElem.getLocalName().equals("P") && XMLSignature.XMLNS.equals(curElem.getNamespaceURI())) {
+                p = decode(curElem);
+                curElem = DOMUtils.getNextSiblingElement(curElem, "Q", XMLSignature.XMLNS);
+                q = decode(curElem);
                 curElem = DOMUtils.getNextSiblingElement(curElem);
             }
-            if (curElem.getLocalName().equals("G")) {
-                g = new DOMCryptoBinary(curElem.getFirstChild());
-                curElem = DOMUtils.getNextSiblingElement(curElem, "Y");
+            BigInteger g = null;
+            if (curElem != null
+                && curElem.getLocalName().equals("G") && XMLSignature.XMLNS.equals(curElem.getNamespaceURI())) {
+                g = decode(curElem);
+                curElem = DOMUtils.getNextSiblingElement(curElem, "Y", XMLSignature.XMLNS);
             }
-            y = new DOMCryptoBinary(curElem.getFirstChild());
-            curElem = DOMUtils.getNextSiblingElement(curElem);
-            if (curElem != null && curElem.getLocalName().equals("J")) {
-                j = new DOMCryptoBinary(curElem.getFirstChild());
-                // curElem = DOMUtils.getNextSiblingElement(curElem);
-            }
-            /*
+            BigInteger y = null;
             if (curElem != null) {
-                seed = new DOMCryptoBinary(curElem.getFirstChild());
+                y = decode(curElem);
                 curElem = DOMUtils.getNextSiblingElement(curElem);
-                pgen = new DOMCryptoBinary(curElem.getFirstChild());
             }
-            */
+            //if (curElem != null && curElem.getLocalName().equals("J")) {
+                //j = new DOMCryptoBinary(curElem.getFirstChild());
+                // curElem = DOMUtils.getNextSiblingElement(curElem);
+            //}
             //@@@ do we care about j, pgenCounter or seed?
-            DSAPublicKeySpec spec = new DSAPublicKeySpec(y.getBigNum(),
-                                                         p.getBigNum(),
-                                                         q.getBigNum(),
-                                                         g.getBigNum());
-            return generatePublicKey(dsakf, spec);
+            DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
+            return (DSAPublicKey) generatePublicKey(dsakf, spec);
         }
     }
 
-    static final class EC extends DOMKeyValue {
+    static final class EC extends DOMKeyValue<ECPublicKey> {
+
         // ECKeyValue CryptoBinaries
         private byte[] ecPublicKey;
         private KeyFactory eckf;
@@ -376,9 +372,8 @@
             return new Curve(name, oid, curve, g, bigInt(n), h);
         }
 
-        EC(PublicKey key) throws KeyException {
-            super(key);
-            ECPublicKey ecKey = (ECPublicKey)key;
+        EC(ECPublicKey ecKey) throws KeyException {
+            super(ecKey);
             ECPoint ecPoint = ecKey.getW();
             ecParams = ecKey.getParams();
             ecPublicKey = encodePoint(ecPoint, ecParams.getCurve());
@@ -390,14 +385,14 @@
 
         private static ECPoint decodePoint(byte[] data, EllipticCurve curve)
                 throws IOException {
-            if ((data.length == 0) || (data[0] != 4)) {
+            if (data.length == 0 || data[0] != 4) {
                 throw new IOException("Only uncompressed point format " +
                                       "supported");
             }
             // Per ANSI X9.62, an encoded point is a 1 byte type followed by
-            // ceiling(log base 2 field-size / 8) bytes of x and the same of y.
+            // ceiling(LOG base 2 field-size / 8) bytes of x and the same of y.
             int n = (data.length - 1) / 2;
-            if (n != ((curve.getField().getFieldSize() + 7) >> 3)) {
+            if (n != (curve.getField().getFieldSize() + 7) >> 3) {
                 throw new IOException("Point does not match field size");
             }
 
@@ -412,7 +407,7 @@
             int n = (curve.getField().getFieldSize() + 7) >> 3;
             byte[] xb = trimZeroes(point.getAffineX().toByteArray());
             byte[] yb = trimZeroes(point.getAffineY().toByteArray());
-            if ((xb.length > n) || (yb.length > n)) {
+            if (xb.length > n || yb.length > n) {
                 throw new RuntimeException("Point coordinates do not " +
                                            "match field size");
             }
@@ -425,7 +420,7 @@
 
         private static byte[] trimZeroes(byte[] b) {
             int i = 0;
-            while ((i < b.length - 1) && (b[i] == 0)) {
+            while (i < b.length - 1 && b[i] == 0) {
                 i++;
             }
             if (i == 0) {
@@ -464,51 +459,32 @@
             }
         }
 
-        private static ECParameterSpec getECParameterSpec(String oid) {
-            if (oid.equals(SECP256R1.getObjectId())) {
-                return SECP256R1;
-            } else if (oid.equals(SECP384R1.getObjectId())) {
-                return SECP384R1;
-            } else if (oid.equals(SECP521R1.getObjectId())) {
-                return SECP521R1;
-            } else {
-                return null;
-            }
-        }
-
-        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-                              DOMCryptoContext context)
+        @Override
+        void marshalPublicKey(XmlWriter xwriter, ECPublicKey publicKey, String dsPrefix,
+                XMLCryptoContext context)
             throws MarshalException
         {
             String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS);
-            Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue",
-                                                            XMLDSIG_11_XMLNS,
-                                                            prefix);
-            Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve",
-                                                            XMLDSIG_11_XMLNS,
-                                                            prefix);
-            Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey",
-                                                           XMLDSIG_11_XMLNS,
-                                                           prefix);
-            Object[] args = new Object[] { ecParams };
+            xwriter.writeStartElement(prefix, "ECKeyValue", XMLDSIG_11_XMLNS);
+
+            xwriter.writeStartElement(prefix, "NamedCurve", XMLDSIG_11_XMLNS);
+            xwriter.writeNamespace(prefix, XMLDSIG_11_XMLNS);
             String oid = getCurveOid(ecParams);
             if (oid == null) {
                 throw new MarshalException("Invalid ECParameterSpec");
             }
-            DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid);
-            String qname = (prefix == null || prefix.length() == 0)
-                       ? "xmlns" : "xmlns:" + prefix;
-            namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
-                                          qname, XMLDSIG_11_XMLNS);
-            ecKeyValueElem.appendChild(namedCurveElem);
-            String encoded = Base64.encode(ecPublicKey);
-            publicKeyElem.appendChild
-                (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded));
-            ecKeyValueElem.appendChild(publicKeyElem);
-            parent.appendChild(ecKeyValueElem);
+            xwriter.writeAttribute("", "", "URI", "urn:oid:" + oid);
+            xwriter.writeEndElement();
+
+            xwriter.writeStartElement(prefix, "PublicKey", XMLDSIG_11_XMLNS);
+            String encoded = Base64.getMimeEncoder().encodeToString(ecPublicKey);
+            xwriter.writeCharacters(encoded);
+            xwriter.writeEndElement(); // "PublicKey"
+            xwriter.writeEndElement(); // "ECKeyValue"
         }
 
-        PublicKey unmarshalKeyValue(Element kvtElem)
+        @Override
+        ECPublicKey unmarshalKeyValue(Element kvtElem)
             throws MarshalException
         {
             if (eckf == null) {
@@ -521,14 +497,20 @@
             }
             ECParameterSpec ecParams = null;
             Element curElem = DOMUtils.getFirstChildElement(kvtElem);
-            if (curElem.getLocalName().equals("ECParameters")) {
+            if (curElem == null) {
+                throw new MarshalException("KeyValue must contain at least one type");
+            }
+
+            if (curElem.getLocalName().equals("ECParameters")
+                && XMLDSIG_11_XMLNS.equals(curElem.getNamespaceURI())) {
                 throw new UnsupportedOperationException
                     ("ECParameters not supported");
-            } else if (curElem.getLocalName().equals("NamedCurve")) {
+            } else if (curElem.getLocalName().equals("NamedCurve")
+                && XMLDSIG_11_XMLNS.equals(curElem.getNamespaceURI())) {
                 String uri = DOMUtils.getAttributeValue(curElem, "URI");
                 // strip off "urn:oid"
                 if (uri.startsWith("urn:oid:")) {
-                    String oid = uri.substring(8);
+                    String oid = uri.substring("urn:oid:".length());
                     ecParams = getECParameterSpec(oid);
                     if (ecParams == null) {
                         throw new MarshalException("Invalid curve OID");
@@ -539,20 +521,31 @@
             } else {
                 throw new MarshalException("Invalid ECKeyValue");
             }
-            curElem = DOMUtils.getNextSiblingElement(curElem, "PublicKey");
+            curElem = DOMUtils.getNextSiblingElement(curElem, "PublicKey", XMLDSIG_11_XMLNS);
             ECPoint ecPoint = null;
 
             try {
-                ecPoint = decodePoint(Base64.decode(curElem),
+                String content = XMLUtils.getFullTextChildrenFromElement(curElem);
+                ecPoint = decodePoint(Base64.getMimeDecoder().decode(content),
                                       ecParams.getCurve());
-            } catch (Base64DecodingException bde) {
-                throw new MarshalException("Invalid EC PublicKey", bde);
             } catch (IOException ioe) {
                 throw new MarshalException("Invalid EC Point", ioe);
             }
 
             ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams);
-            return generatePublicKey(eckf, spec);
+            return (ECPublicKey) generatePublicKey(eckf, spec);
+        }
+
+        private static ECParameterSpec getECParameterSpec(String oid) {
+            if (oid.equals(SECP256R1.getObjectId())) {
+                return SECP256R1;
+            } else if (oid.equals(SECP384R1.getObjectId())) {
+                return SECP384R1;
+            } else if (oid.equals(SECP521R1.getObjectId())) {
+                return SECP521R1;
+            } else {
+                return null;
+            }
         }
 
         static final class Curve extends ECParameterSpec {
@@ -580,20 +573,22 @@
         return new BigInteger(s, 16);
     }
 
-    static final class Unknown extends DOMKeyValue {
-        private javax.xml.crypto.dom.DOMStructure externalPublicKey;
+    static final class Unknown extends DOMKeyValue<PublicKey> {
+        private XMLStructure externalPublicKey;
         Unknown(Element elem) throws MarshalException {
             super(elem);
         }
+        @Override
         PublicKey unmarshalKeyValue(Element kvElem) throws MarshalException {
             externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvElem);
             return null;
         }
-        void marshalPublicKey(Node parent, Document doc, String dsPrefix,
-                              DOMCryptoContext context)
+        @Override
+        void marshalPublicKey(XmlWriter xwriter, PublicKey publicKey, String dsPrefix,
+                XMLCryptoContext context)
             throws MarshalException
         {
-            parent.appendChild(externalPublicKey.getNode());
+            xwriter.marshalStructure(externalPublicKey, dsPrefix, context);
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,66 +21,64 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMManifest.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 
 import java.security.Provider;
 import java.util.*;
 
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * DOM-based implementation of Manifest.
  *
- * @author Sean Mullan
  */
-public final class DOMManifest extends DOMStructure implements Manifest {
+public final class DOMManifest extends BaseStructure implements Manifest {
 
     private final List<Reference> references;
     private final String id;
 
     /**
-     * Creates a <code>DOMManifest</code> containing the specified
+     * Creates a {@code DOMManifest} containing the specified
      * list of {@link Reference}s and optional id.
      *
-     * @param references a list of one or more <code>Reference</code>s. The list
+     * @param references a list of one or more {@code Reference}s. The list
      *    is defensively copied to protect against subsequent modification.
-     * @param id the id (may be <code>null</code>
-     * @throws NullPointerException if <code>references</code> is
-     *    <code>null</code>
-     * @throws IllegalArgumentException if <code>references</code> is empty
-     * @throws ClassCastException if <code>references</code> contains any
+     * @param id the id (may be {@code null}
+     * @throws NullPointerException if {@code references} is
+     *    {@code null}
+     * @throws IllegalArgumentException if {@code references} is empty
+     * @throws ClassCastException if {@code references} contains any
      *    entries that are not of type {@link Reference}
      */
-    public DOMManifest(List<? extends Reference> references, String id) {
+    public DOMManifest(List<DOMReference> references, String id) {
         if (references == null) {
             throw new NullPointerException("references cannot be null");
         }
-        List<Reference> tempList =
-            Collections.checkedList(new ArrayList<Reference>(),
-                                    Reference.class);
-        tempList.addAll(references);
-        this.references = Collections.unmodifiableList(tempList);
+        this.references =
+            Collections.unmodifiableList(new ArrayList<>(references));
         if (this.references.isEmpty()) {
             throw new IllegalArgumentException("list of references must " +
                 "contain at least one entry");
         }
+        for (int i = 0, size = this.references.size(); i < size; i++) {
+            if (!(this.references.get(i) instanceof Reference)) {
+                throw new ClassCastException
+                    ("references["+i+"] is not a valid type");
+            }
+        }
         this.id = id;
     }
 
     /**
-     * Creates a <code>DOMManifest</code> from an element.
+     * Creates a {@code DOMManifest} from an element.
      *
      * @param manElem a Manifest element
      */
@@ -88,30 +86,25 @@
                        Provider provider)
         throws MarshalException
     {
-        Attr attr = manElem.getAttributeNodeNS(null, "Id");
-        if (attr != null) {
-            this.id = attr.getValue();
-            manElem.setIdAttributeNode(attr, true);
-        } else {
-            this.id = null;
-        }
+        this.id = DOMUtils.getIdAttributeValue(manElem, "Id");
 
         boolean secVal = Utils.secureValidation(context);
 
-        Element refElem = DOMUtils.getFirstChildElement(manElem, "Reference");
-        List<Reference> refs = new ArrayList<Reference>();
+        Element refElem = DOMUtils.getFirstChildElement(manElem, "Reference", XMLSignature.XMLNS);
+        List<Reference> refs = new ArrayList<>();
         refs.add(new DOMReference(refElem, context, provider));
 
         refElem = DOMUtils.getNextSiblingElement(refElem);
         while (refElem != null) {
             String localName = refElem.getLocalName();
-            if (!localName.equals("Reference")) {
+            String namespace = refElem.getNamespaceURI();
+            if (!"Reference".equals(localName) || !XMLSignature.XMLNS.equals(namespace)) {
                 throw new MarshalException("Invalid element name: " +
-                                           localName + ", expected Reference");
+                                           namespace + ":" + localName + ", expected Reference");
             }
             refs.add(new DOMReference(refElem, context, provider));
             if (secVal && Policy.restrictNumReferences(refs.size())) {
-                String error = "A maximum of " + Policy.maxReferences()
+                String error = "A maxiumum of " + Policy.maxReferences()
                     + " references per Manifest are allowed when"
                     + " secure validation is enabled";
                 throw new MarshalException(error);
@@ -121,32 +114,33 @@
         this.references = Collections.unmodifiableList(refs);
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
-    static List<Reference> getManifestReferences(Manifest mf) {
+    @SuppressWarnings("unchecked")
+    public static List<Reference> getManifestReferences(Manifest mf) {
         return mf.getReferences();
     }
 
+    @Override
     public List<Reference> getReferences() {
         return references;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element manElem = DOMUtils.createElement(ownerDoc, "Manifest",
-                                                 XMLSignature.XMLNS, dsPrefix);
-
-        DOMUtils.setAttributeID(manElem, "Id", id);
+    public static void marshal(XmlWriter xwriter, Manifest manif, String dsPrefix, XMLCryptoContext context)
+    throws MarshalException {
+        xwriter.writeStartElement(dsPrefix, "Manifest", XMLSignature.XMLNS);
+        xwriter.writeIdAttribute("", "", "Id", manif.getId());
 
         // add references
+        @SuppressWarnings("unchecked")
+        List<Reference> references = manif.getReferences();
         for (Reference ref : references) {
-            ((DOMReference)ref).marshal(manElem, dsPrefix, context);
+            ((DOMReference)ref).marshal(xwriter, dsPrefix, context);
         }
-        parent.appendChild(manElem);
+        xwriter.writeEndElement(); // "Manifest"
     }
 
     @Override
@@ -160,10 +154,10 @@
         }
         Manifest oman = (Manifest)o;
 
-        boolean idsEqual = (id == null ? oman.getId() == null
-                                       : id.equals(oman.getId()));
+        boolean idsEqual = id == null ? oman.getId() == null
+                                       : id.equals(oman.getId());
 
-        return (idsEqual && references.equals(oman.getReferences()));
+        return idsEqual && references.equals(oman.getReferences());
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,39 +21,36 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMPGPData.java 1203846 2011-11-18 21:18:17Z mullan $
+ * $Id: DOMPGPData.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.util.*;
+
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.*;
+import javax.xml.crypto.dsig.XMLSignature;
 import javax.xml.crypto.dsig.keyinfo.PGPData;
-import org.w3c.dom.Document;
+
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 
 /**
  * DOM-based implementation of PGPData.
  *
- * @author Sean Mullan
  */
-public final class DOMPGPData extends DOMStructure implements PGPData {
+public final class DOMPGPData extends BaseStructure implements PGPData {
 
     private final byte[] keyId;
     private final byte[] keyPacket;
     private final List<XMLStructure> externalElements;
 
     /**
-     * Creates a <code>DOMPGPData</code> containing the specified key packet.
+     * Creates a {@code DOMPGPData} containing the specified key packet.
      * and optional list of external elements.
      *
      * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of
@@ -61,32 +58,37 @@
      *    array is cloned to prevent subsequent modification.
      * @param other a list of {@link XMLStructure}s representing elements from
      *    an external namespace. The list is defensively copied to prevent
-     *    subsequent modification. May be <code>null</code> or empty.
-     * @throws NullPointerException if <code>keyPacket</code> is
-     *    <code>null</code>
+     *    subsequent modification. May be {@code null} or empty.
+     * @throws NullPointerException if {@code keyPacket} is
+     *    {@code null}
      * @throws IllegalArgumentException if the key packet is not in the
      *    correct format
-     * @throws ClassCastException if <code>other</code> contains any
+     * @throws ClassCastException if {@code other} contains any
      *    entries that are not of type {@link XMLStructure}
      */
     public DOMPGPData(byte[] keyPacket, List<? extends XMLStructure> other) {
         if (keyPacket == null) {
             throw new NullPointerException("keyPacket cannot be null");
         }
-        List<XMLStructure> tempList =
-            Collections.checkedList(new ArrayList<XMLStructure>(),
-                                    XMLStructure.class);
-        if (other != null) {
-            tempList.addAll(other);
+        if (other == null || other.isEmpty()) {
+            this.externalElements = Collections.emptyList();
+        } else {
+            this.externalElements =
+                Collections.unmodifiableList(new ArrayList<>(other));
+            for (int i = 0, size = this.externalElements.size(); i < size; i++) {
+                if (!(this.externalElements.get(i) instanceof XMLStructure)) {
+                    throw new ClassCastException
+                        ("other["+i+"] is not a valid PGPData type");
+                }
+            }
         }
-        this.externalElements = Collections.unmodifiableList(tempList);
         this.keyPacket = keyPacket.clone();
         checkKeyPacket(keyPacket);
         this.keyId = null;
     }
 
     /**
-     * Creates a <code>DOMPGPData</code> containing the specified key id and
+     * Creates a {@code DOMPGPData} containing the specified key id and
      * optional key packet and list of external elements.
      *
      * @param keyId a PGP public key id as defined in section 11.2 of
@@ -94,15 +96,15 @@
      *    array is cloned to prevent subsequent modification.
      * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of
      *    <a href="http://www.ietf.org/rfc/rfc2440.txt">RFC 2440</a> (may
-     *    be <code>null</code>). The array is cloned to prevent subsequent
+     *    be {@code null}). The array is cloned to prevent subsequent
      *    modification.
      * @param other a list of {@link XMLStructure}s representing elements from
      *    an external namespace. The list is defensively copied to prevent
-     *    subsequent modification. May be <code>null</code> or empty.
-     * @throws NullPointerException if <code>keyId</code> is <code>null</code>
+     *    subsequent modification. May be {@code null} or empty.
+     * @throws NullPointerException if {@code keyId} is {@code null}
      * @throws IllegalArgumentException if the key id or packet is not in the
      *    correct format
-     * @throws ClassCastException if <code>other</code> contains any
+     * @throws ClassCastException if {@code other} contains any
      *    entries that are not of type {@link XMLStructure}
      */
     public DOMPGPData(byte[] keyId, byte[] keyPacket,
@@ -115,13 +117,18 @@
         if (keyId.length != 8) {
             throw new IllegalArgumentException("keyId must be 8 bytes long");
         }
-        List<XMLStructure> tempList =
-            Collections.checkedList(new ArrayList<XMLStructure>(),
-                                    XMLStructure.class);
-        if (other != null) {
-            tempList.addAll(other);
+        if (other == null || other.isEmpty()) {
+            this.externalElements = Collections.emptyList();
+        } else {
+            this.externalElements =
+                Collections.unmodifiableList(new ArrayList<>(other));
+            for (int i = 0, size = this.externalElements.size(); i < size; i++) {
+                if (!(this.externalElements.get(i) instanceof XMLStructure)) {
+                    throw new ClassCastException
+                        ("other["+i+"] is not a valid PGPData type");
+                }
+            }
         }
-        this.externalElements = Collections.unmodifiableList(tempList);
         this.keyId = keyId.clone();
         this.keyPacket = keyPacket == null ? null
                                            : keyPacket.clone();
@@ -131,88 +138,53 @@
     }
 
     /**
-     * Creates a <code>DOMPGPData</code> from an element.
+     * Creates a {@code DOMPGPData} from an element.
      *
      * @param pdElem a PGPData element
      */
     public DOMPGPData(Element pdElem) throws MarshalException {
         // get all children nodes
-        byte[] keyId = null;
-        byte[] keyPacket = null;
-        NodeList nl = pdElem.getChildNodes();
-        int length = nl.getLength();
-        List<XMLStructure> other = new ArrayList<XMLStructure>(length);
-        for (int x = 0; x < length; x++) {
-            Node n = nl.item(x);
-            if (n.getNodeType() == Node.ELEMENT_NODE) {
-                Element childElem = (Element)n;
+        byte[] pgpKeyId = null;
+        byte[] pgpKeyPacket = null;
+
+        List<XMLStructure> other = new ArrayList<>();
+        Node firstChild = pdElem.getFirstChild();
+        while (firstChild != null) {
+            if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                Element childElem = (Element)firstChild;
                 String localName = childElem.getLocalName();
-                try {
-                    if (localName.equals("PGPKeyID")) {
-                        keyId = Base64.decode(childElem);
-                    } else if (localName.equals("PGPKeyPacket")){
-                        keyPacket = Base64.decode(childElem);
-                    } else {
-                        other.add
-                            (new javax.xml.crypto.dom.DOMStructure(childElem));
-                    }
-                } catch (Base64DecodingException bde) {
-                    throw new MarshalException(bde);
+                String namespace = childElem.getNamespaceURI();
+                if ("PGPKeyID".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    String content = XMLUtils.getFullTextChildrenFromElement(childElem);
+                    pgpKeyId = Base64.getMimeDecoder().decode(content);
+                } else if ("PGPKeyPacket".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    String content = XMLUtils.getFullTextChildrenFromElement(childElem);
+                    pgpKeyPacket = Base64.getMimeDecoder().decode(content);
+                } else {
+                    other.add
+                    (new javax.xml.crypto.dom.DOMStructure(childElem));
                 }
             }
+            firstChild = firstChild.getNextSibling();
         }
-        this.keyId = keyId;
-        this.keyPacket = keyPacket;
+        this.keyId = pgpKeyId;
+        this.keyPacket = pgpKeyPacket;
         this.externalElements = Collections.unmodifiableList(other);
     }
 
+    @Override
     public byte[] getKeyId() {
-        return (keyId == null ? null : keyId.clone());
-    }
-
-    public byte[] getKeyPacket() {
-        return (keyPacket == null ? null : keyPacket.clone());
-    }
-
-    public List<XMLStructure> getExternalElements() {
-        return externalElements;
+        return keyId == null ? null : keyId.clone();
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData",
-                                                XMLSignature.XMLNS, dsPrefix);
-
-        // create and append PGPKeyID element
-        if (keyId != null) {
-            Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID",
-                                                       XMLSignature.XMLNS,
-                                                       dsPrefix);
-            keyIdElem.appendChild
-                (ownerDoc.createTextNode(Base64.encode(keyId)));
-            pdElem.appendChild(keyIdElem);
-        }
+    @Override
+    public byte[] getKeyPacket() {
+        return keyPacket == null ? null : keyPacket.clone();
+    }
 
-        // create and append PGPKeyPacket element
-        if (keyPacket != null) {
-            Element keyPktElem = DOMUtils.createElement(ownerDoc,
-                                                        "PGPKeyPacket",
-                                                        XMLSignature.XMLNS,
-                                                        dsPrefix);
-            keyPktElem.appendChild
-                (ownerDoc.createTextNode(Base64.encode(keyPacket)));
-            pdElem.appendChild(keyPktElem);
-        }
-
-        // create and append any elements
-        for (XMLStructure extElem : externalElements) {
-            DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure)
-                extElem).getNode());
-        }
-
-        parent.appendChild(pdElem);
+    @Override
+    public List<XMLStructure> getExternalElements() {
+        return externalElements;
     }
 
     /**
@@ -243,8 +215,8 @@
         }
 
         // tag value must be 6, 14, 5 or 7
-        if (((tag & 6) != 6) && ((tag & 14) != 14) &&
-            ((tag & 5) != 5) && ((tag & 7) != 7)) {
+        if ((tag & 6) != 6 && (tag & 14) != 14 &&
+            (tag & 5) != 5 && (tag & 7) != 7) {
             throw new IllegalArgumentException("keypacket tag is invalid: " +
                                                "must be 6, 14, 5, or 7");
         }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Portions copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * ===========================================================================
@@ -31,13 +31,12 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMReference.java 1334007 2012-05-04 14:59:46Z coheigea $
+ * $Id: DOMReference.java 1803518 2017-07-31 11:02:52Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dom.DOMURIReference;
 
 import java.io.*;
@@ -45,27 +44,30 @@
 import java.net.URISyntaxException;
 import java.security.*;
 import java.util.*;
+
 import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+
 import org.jcp.xml.dsig.internal.DigesterOutputStream;
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
 
 /**
  * DOM-based implementation of Reference.
  *
- * @author Sean Mullan
- * @author Joyce Leung
  */
 public final class DOMReference extends DOMStructure
     implements Reference, DOMURIReference {
 
    /**
+    * The maximum number of transforms per reference, if secure validation is enabled.
+    */
+   public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+
+   /**
     * Look up useC14N11 system property. If true, an explicit C14N11 transform
     * will be added if necessary when generating the signature. See section
     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
@@ -73,15 +75,11 @@
     * If true, overrides the same property if set in the XMLSignContext.
     */
     private static boolean useC14N11 =
-        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
-            public Boolean run() {
-                return Boolean.valueOf(Boolean.getBoolean
-                    ("com.sun.org.apache.xml.internal.security.useC14N11"));
-            }
-        });
+        AccessController.doPrivileged((PrivilegedAction<Boolean>)
+            () -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DOMReference.class);
 
     private final DigestMethod digestMethod;
     private final String id;
@@ -103,18 +101,18 @@
     private Provider provider;
 
     /**
-     * Creates a <code>Reference</code> from the specified parameters.
+     * Creates a {@code Reference} from the specified parameters.
      *
      * @param uri the URI (may be null)
      * @param type the type (may be null)
      * @param dm the digest method
      * @param transforms a list of {@link Transform}s. The list
      *    is defensively copied to protect against subsequent modification.
-     *    May be <code>null</code> or empty.
-     * @param id the reference ID (may be <code>null</code>)
-     * @throws NullPointerException if <code>dm</code> is <code>null</code>
-     * @throws ClassCastException if any of the <code>transforms</code> are
-     *    not of type <code>Transform</code>
+     *    May be {@code null} or empty.
+     * @param id the reference ID (may be {@code null})
+     * @throws NullPointerException if {@code dm} is {@code null}
+     * @throws ClassCastException if any of the {@code transforms} are
+     *    not of type {@code Transform}
      */
     public DOMReference(String uri, String type, DigestMethod dm,
                         List<? extends Transform> transforms, String id,
@@ -140,24 +138,32 @@
         if (dm == null) {
             throw new NullPointerException("DigestMethod must be non-null");
         }
-        List<Transform> tempList =
-            Collections.checkedList(new ArrayList<Transform>(),
-                                    Transform.class);
-        if (appliedTransforms != null) {
-            tempList.addAll(appliedTransforms);
+        if (appliedTransforms == null) {
+            this.allTransforms = new ArrayList<>();
+        } else {
+            this.allTransforms = new ArrayList<>(appliedTransforms);
+            for (int i = 0, size = this.allTransforms.size(); i < size; i++) {
+                if (!(this.allTransforms.get(i) instanceof Transform)) {
+                    throw new ClassCastException
+                        ("appliedTransforms["+i+"] is not a valid type");
+                }
+            }
         }
-        List<Transform> tempList2 =
-            Collections.checkedList(new ArrayList<Transform>(),
-                                    Transform.class);
-        if (transforms != null) {
-            tempList.addAll(transforms);
-            tempList2.addAll(transforms);
+        if (transforms == null) {
+            this.transforms = Collections.emptyList();
+        } else {
+            this.transforms = new ArrayList<>(transforms);
+            for (int i = 0, size = this.transforms.size(); i < size; i++) {
+                if (!(this.transforms.get(i) instanceof Transform)) {
+                    throw new ClassCastException
+                        ("transforms["+i+"] is not a valid type");
+                }
+            }
+            this.allTransforms.addAll(this.transforms);
         }
-        this.allTransforms = Collections.unmodifiableList(tempList);
-        this.transforms = tempList2;
         this.digestMethod = dm;
         this.uri = uri;
-        if ((uri != null) && (!uri.equals(""))) {
+        if (uri != null && !uri.equals("")) {
             try {
                 new URI(uri);
             } catch (URISyntaxException e) {
@@ -175,7 +181,7 @@
     }
 
     /**
-     * Creates a <code>DOMReference</code> from an element.
+     * Creates a {@code DOMReference} from an element.
      *
      * @param refElem a Reference element
      */
@@ -187,22 +193,25 @@
 
         // unmarshal Transforms, if specified
         Element nextSibling = DOMUtils.getFirstChildElement(refElem);
-        List<Transform> transforms = new ArrayList<Transform>(5);
-        if (nextSibling.getLocalName().equals("Transforms")) {
+        List<Transform> newTransforms = new ArrayList<>(MAXIMUM_TRANSFORM_COUNT);
+        if (nextSibling.getLocalName().equals("Transforms")
+            && XMLSignature.XMLNS.equals(nextSibling.getNamespaceURI())) {
             Element transformElem = DOMUtils.getFirstChildElement(nextSibling,
-                                                                  "Transform");
-            transforms.add(new DOMTransform(transformElem, context, provider));
+                                                                  "Transform",
+                                                                  XMLSignature.XMLNS);
+            newTransforms.add(new DOMTransform(transformElem, context, provider));
             transformElem = DOMUtils.getNextSiblingElement(transformElem);
             while (transformElem != null) {
                 String localName = transformElem.getLocalName();
-                if (!localName.equals("Transform")) {
+                String namespace = transformElem.getNamespaceURI();
+                if (!"Transform".equals(localName) || !XMLSignature.XMLNS.equals(namespace)) {
                     throw new MarshalException(
                         "Invalid element name: " + localName +
                         ", expected Transform");
                 }
-                transforms.add
+                newTransforms.add
                     (new DOMTransform(transformElem, context, provider));
-                if (secVal && Policy.restrictNumTransforms(transforms.size())) {
+                if (secVal && Policy.restrictNumTransforms(newTransforms.size())) {
                     String error = "A maximum of " + Policy.maxTransforms()
                         + " transforms per Reference are allowed when"
                         + " secure validation is enabled";
@@ -212,7 +221,8 @@
             }
             nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
         }
-        if (!nextSibling.getLocalName().equals("DigestMethod")) {
+        if (!nextSibling.getLocalName().equals("DigestMethod")
+            && XMLSignature.XMLNS.equals(nextSibling.getNamespaceURI())) {
             throw new MarshalException("Invalid element name: " +
                                        nextSibling.getLocalName() +
                                        ", expected DigestMethod");
@@ -230,12 +240,9 @@
         }
 
         // unmarshal DigestValue
-        Element dvElem = DOMUtils.getNextSiblingElement(dmElem, "DigestValue");
-        try {
-            this.digestValue = Base64.decode(dvElem);
-        } catch (Base64DecodingException bde) {
-            throw new MarshalException(bde);
-        }
+        Element dvElem = DOMUtils.getNextSiblingElement(dmElem, "DigestValue", XMLSignature.XMLNS);
+        String content = XMLUtils.getFullTextChildrenFromElement(dvElem);
+        this.digestValue = Base64.getMimeDecoder().decode(content);
 
         // check for extra elements
         if (DOMUtils.getNextSiblingElement(dvElem) != null) {
@@ -245,101 +252,87 @@
 
         // unmarshal attributes
         this.uri = DOMUtils.getAttributeValue(refElem, "URI");
-
-        Attr attr = refElem.getAttributeNodeNS(null, "Id");
-        if (attr != null) {
-            this.id = attr.getValue();
-            refElem.setIdAttributeNode(attr, true);
-        } else {
-            this.id = null;
-        }
+        this.id = DOMUtils.getIdAttributeValue(refElem, "Id");
 
         this.type = DOMUtils.getAttributeValue(refElem, "Type");
         this.here = refElem.getAttributeNodeNS(null, "URI");
         this.refElem = refElem;
-        this.transforms = transforms;
+        this.transforms = newTransforms;
         this.allTransforms = transforms;
         this.appliedTransformData = null;
         this.provider = provider;
     }
 
+    @Override
     public DigestMethod getDigestMethod() {
         return digestMethod;
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public String getURI() {
         return uri;
     }
 
+    @Override
     public String getType() {
         return type;
     }
 
+    @Override
     public List<Transform> getTransforms() {
         return Collections.unmodifiableList(allTransforms);
     }
 
+    @Override
     public byte[] getDigestValue() {
-        return (digestValue == null ? null : digestValue.clone());
+        return digestValue == null ? null : digestValue.clone();
     }
 
+    @Override
     public byte[] getCalculatedDigestValue() {
-        return (calcDigestValue == null ? null
-                                        : calcDigestValue.clone());
+        return calcDigestValue == null ? null
+                                        : calcDigestValue.clone();
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    @Override
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Marshalling Reference");
-        }
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        refElem = DOMUtils.createElement(ownerDoc, "Reference",
-                                         XMLSignature.XMLNS, dsPrefix);
+        LOG.debug("Marshalling Reference");
+        xwriter.writeStartElement(dsPrefix, "Reference", XMLSignature.XMLNS);
+        XMLStructure refStruct = xwriter.getCurrentNodeAsStructure();
+        refElem = (Element) ((javax.xml.crypto.dom.DOMStructure) refStruct).getNode();
 
         // set attributes
-        DOMUtils.setAttributeID(refElem, "Id", id);
-        DOMUtils.setAttribute(refElem, "URI", uri);
-        DOMUtils.setAttribute(refElem, "Type", type);
+        xwriter.writeIdAttribute("", "", "Id", id);
+        here = xwriter.writeAttribute("", "", "URI", uri);
+        xwriter.writeAttribute("", "", "Type", type);
 
         // create and append Transforms element
         if (!allTransforms.isEmpty()) {
-            Element transformsElem = DOMUtils.createElement(ownerDoc,
-                                                            "Transforms",
-                                                            XMLSignature.XMLNS,
-                                                            dsPrefix);
-            refElem.appendChild(transformsElem);
+            xwriter.writeStartElement(dsPrefix, "Transforms", XMLSignature.XMLNS);
             for (Transform transform : allTransforms) {
-                ((DOMStructure)transform).marshal(transformsElem,
-                                                  dsPrefix, context);
+                xwriter.marshalStructure(transform, dsPrefix, context);
             }
+            xwriter.writeEndElement(); // "Transforms"
         }
 
         // create and append DigestMethod element
-        ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context);
+        DOMDigestMethod.marshal(xwriter, digestMethod, dsPrefix);
 
         // create and append DigestValue element
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Adding digestValueElem");
-        }
-        Element digestValueElem = DOMUtils.createElement(ownerDoc,
-                                                         "DigestValue",
-                                                         XMLSignature.XMLNS,
-                                                         dsPrefix);
+        LOG.debug("Adding digestValueElem");
+        xwriter.writeStartElement(dsPrefix, "DigestValue", XMLSignature.XMLNS);
         if (digestValue != null) {
-            digestValueElem.appendChild
-                (ownerDoc.createTextNode(Base64.encode(digestValue)));
+            xwriter.writeCharacters(Base64.getMimeEncoder().encodeToString(digestValue));
         }
-        refElem.appendChild(digestValueElem);
-
-        parent.appendChild(refElem);
-        here = refElem.getAttributeNodeNS(null, "URI");
+        xwriter.writeEndElement(); // "DigestValue"
+        xwriter.writeEndElement(); // "Reference"
     }
 
     public void digest(XMLSignContext signContext)
@@ -354,10 +347,8 @@
         digestValue = transform(data, signContext);
 
         // insert digestValue into DigestValue element
-        String encodedDV = Base64.encode(digestValue);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri);
-        }
+        String encodedDV = Base64.getMimeEncoder().encodeToString(digestValue);
+        LOG.debug("Reference object uri = {}", uri);
         Element digestElem = DOMUtils.getLastChildElement(refElem);
         if (digestElem == null) {
             throw new XMLSignatureException("DigestValue element expected");
@@ -367,11 +358,10 @@
             (refElem.getOwnerDocument().createTextNode(encodedDV));
 
         digested = true;
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Reference digesting completed");
-        }
+        LOG.debug("Reference digesting completed");
     }
 
+    @Override
     public boolean validate(XMLValidateContext validateContext)
         throws XMLSignatureException
     {
@@ -384,9 +374,9 @@
         Data data = dereference(validateContext);
         calcDigestValue = transform(data, validateContext);
 
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue));
-            log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue));
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Expected digest: " + Base64.getMimeEncoder().encodeToString(digestValue));
+            LOG.debug("Actual digest: " + Base64.getMimeEncoder().encodeToString(calcDigestValue));
         }
 
         validationStatus = Arrays.equals(digestValue, calcDigestValue);
@@ -394,10 +384,12 @@
         return validationStatus;
     }
 
+    @Override
     public Data getDereferencedData() {
         return derefData;
     }
 
+    @Override
     public InputStream getDigestInputStream() {
         return dis;
     }
@@ -414,10 +406,8 @@
         }
         try {
             data = deref.dereference(this, context);
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "URIDereferencer class name: " + deref.getClass().getName());
-                log.log(java.util.logging.Level.FINE, "Data class name: " + data.getClass().getName());
-            }
+            LOG.debug("URIDereferencer class name: {}", deref.getClass().getName());
+            LOG.debug("Data class name: {}", data.getClass().getName());
         } catch (URIReferenceException ure) {
             throw new XMLSignatureException(ure);
         }
@@ -441,16 +431,14 @@
         DigesterOutputStream dos;
         Boolean cache = (Boolean)
             context.getProperty("javax.xml.crypto.dsig.cacheReference");
-        if (cache != null && cache.booleanValue()) {
+        if (cache != null && cache) {
             this.derefData = copyDerefData(dereferencedData);
             dos = new DigesterOutputStream(md, true);
         } else {
             dos = new DigesterOutputStream(md);
         }
-        OutputStream os = null;
         Data data = dereferencedData;
-        try {
-            os = new UnsyncBufferedOutputStream(dos);
+        try (OutputStream os = new UnsyncBufferedOutputStream(dos)) {
             for (int i = 0, size = transforms.size(); i < size; i++) {
                 DOMTransform transform = (DOMTransform)transforms.get(i);
                 if (i < size - 1) {
@@ -470,7 +458,7 @@
                     if (!c14n11) {
                         Boolean prop = (Boolean)context.getProperty
                             ("com.sun.org.apache.xml.internal.security.useC14N11");
-                        c14n11 = (prop != null && prop.booleanValue());
+                        c14n11 = prop != null && prop;
                         if (c14n11) {
                             c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
                         }
@@ -500,6 +488,9 @@
                 } else {
                     throw new XMLSignatureException("unrecognized Data type");
                 }
+
+                boolean secVal = Utils.secureValidation(context);
+                xi.setSecureValidation(secVal);
                 if (context instanceof XMLSignContext && c14n11
                     && !xi.isOctetStream() && !xi.isOutputStreamSet()) {
                     TransformService spi = null;
@@ -525,8 +516,8 @@
                     } else {
                         transformsElem = DOMUtils.getFirstChildElement(refElem);
                     }
-                    t.marshal(transformsElem, dsPrefix,
-                              (DOMCryptoContext)context);
+                    XmlWriter xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), transformsElem);
+                    t.marshal(xwriter, dsPrefix, context);
                     allTransforms.add(t);
                     xi.updateOutputStream(os, true);
                 } else {
@@ -534,7 +525,7 @@
                 }
             }
             os.flush();
-            if (cache != null && cache.booleanValue()) {
+            if (cache != null && cache) {
                 this.dis = dos.getInputStream();
             }
             return dos.getDigestValue();
@@ -549,13 +540,6 @@
         } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) {
             throw new XMLSignatureException(e);
         } finally {
-            if (os != null) {
-                try {
-                    os.close();
-                } catch (IOException e) {
-                    throw new XMLSignatureException(e);
-                }
-            }
             if (dos != null) {
                 try {
                     dos.close();
@@ -566,6 +550,7 @@
         }
     }
 
+    @Override
     public Node getHere() {
         return here;
     }
@@ -581,12 +566,12 @@
         }
         Reference oref = (Reference)o;
 
-        boolean idsEqual = (id == null ? oref.getId() == null
-                                       : id.equals(oref.getId()));
-        boolean urisEqual = (uri == null ? oref.getURI() == null
-                                         : uri.equals(oref.getURI()));
-        boolean typesEqual = (type == null ? oref.getType() == null
-                                           : type.equals(oref.getType()));
+        boolean idsEqual = id == null ? oref.getId() == null
+                                       : id.equals(oref.getId());
+        boolean urisEqual = uri == null ? oref.getURI() == null
+                                         : uri.equals(oref.getURI());
+        boolean typesEqual = type == null ? oref.getType() == null
+                                           : type.equals(oref.getType());
         boolean digestValuesEqual =
             Arrays.equals(digestValue, oref.getDigestValue());
 
@@ -629,11 +614,12 @@
                 try {
                     final Set<Node> s = xsi.getNodeSet();
                     return new NodeSetData<Node>() {
+                        @Override
                         public Iterator<Node> iterator() { return s.iterator(); }
                     };
                 } catch (Exception e) {
-                    // log a warning
-                    log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
+                    // LOG a warning
+                    LOG.warn("cannot cache dereferenced data: " + e);
                     return null;
                 }
             } else if (xsi.isElement()) {
@@ -645,8 +631,8 @@
                         (xsi.getOctetStream(), xsi.getSourceURI(),
                          xsi.getMIMEType());
                 } catch (IOException ioe) {
-                    // log a warning
-                    log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
+                    // LOG a warning
+                    LOG.warn("cannot cache dereferenced data: " + ioe);
                     return null;
                 }
             }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Portions copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * ===========================================================================
@@ -31,23 +31,34 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMRetrievalMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMRetrievalMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.io.ByteArrayInputStream;
+import java.io.InputStream;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.security.Provider;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
 
-import javax.xml.XMLConstants;
-import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
+import javax.xml.crypto.Data;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.NodeSetData;
+import javax.xml.crypto.URIDereferencer;
+import javax.xml.crypto.URIReferenceException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.XMLStructure;
 import javax.xml.crypto.dom.DOMURIReference;
+import javax.xml.crypto.dsig.Transform;
+import javax.xml.crypto.dsig.XMLSignature;
 import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
-import javax.xml.parsers.*;
+import javax.xml.parsers.DocumentBuilder;
+
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -56,8 +67,6 @@
 /**
  * DOM-based implementation of RetrievalMethod.
  *
- * @author Sean Mullan
- * @author Joyce Leung
  */
 public final class DOMRetrievalMethod extends DOMStructure
     implements RetrievalMethod, DOMURIReference {
@@ -68,20 +77,20 @@
     private Attr here;
 
     /**
-     * Creates a <code>DOMRetrievalMethod</code> containing the specified
+     * Creates a {@code DOMRetrievalMethod} containing the specified
      * URIReference and List of Transforms.
      *
      * @param uri the URI
      * @param type the type
      * @param transforms a list of {@link Transform}s. The list is defensively
-     *    copied to prevent subsequent modification. May be <code>null</code>
+     *    copied to prevent subsequent modification. May be {@code null}
      *    or empty.
-     * @throws IllegalArgumentException if the format of <code>uri</code> is
+     * @throws IllegalArgumentException if the format of {@code uri} is
      *    invalid, as specified by Reference's URI attribute in the W3C
      *    specification for XML-Signature Syntax and Processing
-     * @throws NullPointerException if <code>uriReference</code>
-     *    is <code>null</code>
-     * @throws ClassCastException if <code>transforms</code> contains any
+     * @throws NullPointerException if {@code uriReference}
+     *    is {@code null}
+     * @throws ClassCastException if {@code transforms} contains any
      *    entries that are not of type {@link Transform}
      */
     public DOMRetrievalMethod(String uri, String type,
@@ -90,13 +99,18 @@
         if (uri == null) {
             throw new NullPointerException("uri cannot be null");
         }
-        List<Transform> tempList =
-            Collections.checkedList(new ArrayList<Transform>(),
-                                    Transform.class);
-        if (transforms != null) {
-            tempList.addAll(transforms);
+        if (transforms == null || transforms.isEmpty()) {
+            this.transforms = Collections.emptyList();
+        } else {
+            this.transforms = Collections.unmodifiableList(
+                new ArrayList<>(transforms));
+            for (int i = 0, size = this.transforms.size(); i < size; i++) {
+                if (!(this.transforms.get(i) instanceof Transform)) {
+                    throw new ClassCastException
+                        ("transforms["+i+"] is not a valid type");
+                }
+            }
         }
-        this.transforms = Collections.unmodifiableList(tempList);
         this.uri = uri;
         if (!uri.equals("")) {
             try {
@@ -110,7 +124,7 @@
     }
 
     /**
-     * Creates a <code>DOMRetrievalMethod</code> from an element.
+     * Creates a {@code DOMRetrievalMethod} from an element.
      *
      * @param rmElem a RetrievalMethod element
      */
@@ -128,28 +142,28 @@
         boolean secVal = Utils.secureValidation(context);
 
         // get Transforms, if specified
-        List<Transform> transforms = new ArrayList<Transform>();
+        List<Transform> newTransforms = new ArrayList<>();
         Element transformsElem = DOMUtils.getFirstChildElement(rmElem);
 
         if (transformsElem != null) {
             String localName = transformsElem.getLocalName();
-            if (!localName.equals("Transforms")) {
+            String namespace = transformsElem.getNamespaceURI();
+            if (!"Transforms".equals(localName) || !XMLSignature.XMLNS.equals(namespace)) {
                 throw new MarshalException("Invalid element name: " +
-                                           localName + ", expected Transforms");
+                                           namespace + ":" + localName + ", expected Transforms");
             }
             Element transformElem =
-                DOMUtils.getFirstChildElement(transformsElem, "Transform");
-            transforms.add(new DOMTransform(transformElem, context, provider));
-            transformElem = DOMUtils.getNextSiblingElement(transformElem);
+                DOMUtils.getFirstChildElement(transformsElem, "Transform", XMLSignature.XMLNS);
             while (transformElem != null) {
                 String name = transformElem.getLocalName();
-                if (!name.equals("Transform")) {
+                namespace = transformElem.getNamespaceURI();
+                if (!"Transform".equals(name) || !XMLSignature.XMLNS.equals(namespace)) {
                     throw new MarshalException("Invalid element name: " +
                                                name + ", expected Transform");
                 }
-                transforms.add
+                newTransforms.add
                     (new DOMTransform(transformElem, context, provider));
-                if (secVal && Policy.restrictNumTransforms(transforms.size())) {
+                if (secVal && Policy.restrictNumTransforms(newTransforms.size())) {
                     String error = "A maximum of " + Policy.maxTransforms()
                         + " transforms per Reference are allowed when"
                         + " secure validation is enabled";
@@ -158,59 +172,57 @@
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
             }
         }
-        if (transforms.isEmpty()) {
+        if (newTransforms.isEmpty()) {
             this.transforms = Collections.emptyList();
         } else {
-            this.transforms = Collections.unmodifiableList(transforms);
+            this.transforms = Collections.unmodifiableList(newTransforms);
         }
     }
 
+    @Override
     public String getURI() {
         return uri;
     }
 
+    @Override
     public String getType() {
         return type;
     }
 
+    @Override
     public List<Transform> getTransforms() {
         return transforms;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    @Override
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod",
-                                                XMLSignature.XMLNS, dsPrefix);
+        xwriter.writeStartElement(dsPrefix, "RetrievalMethod", XMLSignature.XMLNS);
 
+        // TODO - see whether it is important to capture the "here" attribute as part of the
+        // marshalling - do any of the tests fail?
         // add URI and Type attributes
-        DOMUtils.setAttribute(rmElem, "URI", uri);
-        DOMUtils.setAttribute(rmElem, "Type", type);
+        here = xwriter.writeAttribute("", "", "URI", uri);
+        xwriter.writeAttribute("", "", "Type", type);
 
         // add Transforms elements
         if (!transforms.isEmpty()) {
-            Element transformsElem = DOMUtils.createElement(ownerDoc,
-                                                            "Transforms",
-                                                            XMLSignature.XMLNS,
-                                                            dsPrefix);
-            rmElem.appendChild(transformsElem);
+            xwriter.writeStartElement(dsPrefix, "Transforms", XMLSignature.XMLNS);
             for (Transform transform : transforms) {
-                ((DOMTransform)transform).marshal(transformsElem,
-                                                   dsPrefix, context);
+                ((DOMTransform)transform).marshal(xwriter, dsPrefix, context);
             }
+            xwriter.writeEndElement(); // "Transforms"
         }
-
-        parent.appendChild(rmElem);
-
-        // save here node
-        here = rmElem.getAttributeNodeNS(null, "URI");
+        xwriter.writeEndElement(); // "RetrievalMethod"
     }
 
+    @Override
     public Node getHere() {
         return here;
     }
 
+    @Override
     public Data dereference(XMLCryptoContext context)
         throws URIReferenceException
     {
@@ -232,15 +244,15 @@
         // pass dereferenced data through Transforms
         try {
             for (Transform transform : transforms) {
-                data = ((DOMTransform)transform).transform(data, context);
+                data = transform.transform(data, context);
             }
         } catch (Exception e) {
             throw new URIReferenceException(e);
         }
 
         // guard against RetrievalMethod loops
-        if ((data instanceof NodeSetData) && Utils.secureValidation(context)
-            && Policy.restrictRetrievalMethodLoops()) {
+        if (data instanceof NodeSetData && Utils.secureValidation(context)
+                && Policy.restrictRetrievalMethodLoops()) {
             NodeSetData<?> nsd = (NodeSetData<?>)data;
             Iterator<?> i = nsd.iterator();
             if (i.hasNext()) {
@@ -259,16 +271,15 @@
     public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context)
         throws URIReferenceException
     {
-        try {
-            ApacheData data = (ApacheData)dereference(context);
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setNamespaceAware(true);
-            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            Document doc = db.parse(new ByteArrayInputStream
-                (data.getXMLSignatureInput().getBytes()));
+        DocumentBuilder db = null;
+        boolean secVal = Utils.secureValidation(context);
+        ApacheData data = (ApacheData)dereference(context);
+        try (InputStream is = new ByteArrayInputStream(data.getXMLSignatureInput().getBytes())) {
+            db = XMLUtils.createDocumentBuilder(false, secVal);
+            Document doc = db.parse(is);
             Element kiElem = doc.getDocumentElement();
-            if (kiElem.getLocalName().equals("X509Data")) {
+            if (kiElem.getLocalName().equals("X509Data")
+                && XMLSignature.XMLNS.equals(kiElem.getNamespaceURI())) {
                 return new DOMX509Data(kiElem);
             } else {
                 return null; // unsupported
@@ -288,11 +299,11 @@
         }
         RetrievalMethod orm = (RetrievalMethod)obj;
 
-        boolean typesEqual = (type == null ? orm.getType() == null
-                                           : type.equals(orm.getType()));
+        boolean typesEqual = type == null ? orm.getType() == null
+                                           : type.equals(orm.getType());
 
-        return (uri.equals(orm.getURI()) &&
-            transforms.equals(orm.getTransforms()) && typesEqual);
+        return uri.equals(orm.getURI()) &&
+            transforms.equals(orm.getTransforms()) && typesEqual;
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMSignatureMethod.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -36,6 +36,9 @@
 import java.security.*;
 import java.security.interfaces.DSAKey;
 import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.MGF1ParameterSpec;
+import java.security.spec.PSSParameterSpec;
+
 import org.w3c.dom.Element;
 
 import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
@@ -46,25 +49,30 @@
 /**
  * DOM-based abstract implementation of SignatureMethod.
  *
- * @author Sean Mullan
  */
 public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DOMSignatureMethod.class);
 
     private SignatureMethodParameterSpec params;
     private Signature signature;
 
     // see RFC 4051 for these algorithm definitions
+    static final String RSA_SHA224 =
+        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha224";
     static final String RSA_SHA256 =
         "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
     static final String RSA_SHA384 =
         "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
     static final String RSA_SHA512 =
         "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
+    static final String RSA_RIPEMD160 =
+        "http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160";
     static final String ECDSA_SHA1 =
         "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+    static final String ECDSA_SHA224 =
+        "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224";
     static final String ECDSA_SHA256 =
         "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
     static final String ECDSA_SHA384 =
@@ -74,10 +82,26 @@
     static final String DSA_SHA256 =
         "http://www.w3.org/2009/xmldsig11#dsa-sha256";
 
+    // see RFC 6931 for these algorithm definitions
+    static final String ECDSA_RIPEMD160 =
+        "http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160";
+    static final String RSA_SHA1_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1";
+    static final String RSA_SHA224_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1";
+    static final String RSA_SHA256_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1";
+    static final String RSA_SHA384_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1";
+    static final String RSA_SHA512_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1";
+    static final String RSA_RIPEMD160_MGF1 =
+        "http://www.w3.org/2007/05/xmldsig-more#ripemd160-rsa-MGF1";
+
     /**
-     * Creates a <code>DOMSignatureMethod</code>.
+     * Creates a {@code DOMSignatureMethod}.
      *
-     * @param params the algorithm-specific params (may be <code>null</code>)
+     * @param params the algorithm-specific params (may be {@code null})
      * @throws InvalidAlgorithmParameterException if the parameters are not
      *    appropriate for this signature method
      */
@@ -94,7 +118,7 @@
     }
 
     /**
-     * Creates a <code>DOMSignatureMethod</code> from an element. This ctor
+     * Creates a {@code DOMSignatureMethod} from an element. This ctor
      * invokes the {@link #unmarshalParams unmarshalParams} method to
      * unmarshal any algorithm-specific input parameters.
      *
@@ -144,38 +168,63 @@
         String alg = DOMUtils.getAttributeValue(smElem, "Algorithm");
         if (alg.equals(SignatureMethod.RSA_SHA1)) {
             return new SHA1withRSA(smElem);
+        } else if (alg.equals(RSA_SHA224)) {
+            return new SHA224withRSA(smElem);
         } else if (alg.equals(RSA_SHA256)) {
             return new SHA256withRSA(smElem);
         } else if (alg.equals(RSA_SHA384)) {
             return new SHA384withRSA(smElem);
         } else if (alg.equals(RSA_SHA512)) {
             return new SHA512withRSA(smElem);
+        } else if (alg.equals(RSA_RIPEMD160)) {
+            return new RIPEMD160withRSA(smElem);
+        } else if (alg.equals(RSA_SHA1_MGF1)) {
+            return new SHA1withRSAandMGF1(smElem);
+        } else if (alg.equals(RSA_SHA224_MGF1)) {
+            return new SHA224withRSAandMGF1(smElem);
+        } else if (alg.equals(RSA_SHA256_MGF1)) {
+            return new SHA256withRSAandMGF1(smElem);
+        } else if (alg.equals(RSA_SHA384_MGF1)) {
+            return new SHA384withRSAandMGF1(smElem);
+        } else if (alg.equals(RSA_SHA512_MGF1)) {
+            return new SHA512withRSAandMGF1(smElem);
+        } else if (alg.equals(RSA_RIPEMD160_MGF1)) {
+            return new RIPEMD160withRSAandMGF1(smElem);
         } else if (alg.equals(SignatureMethod.DSA_SHA1)) {
             return new SHA1withDSA(smElem);
         } else if (alg.equals(DSA_SHA256)) {
             return new SHA256withDSA(smElem);
         } else if (alg.equals(ECDSA_SHA1)) {
             return new SHA1withECDSA(smElem);
+        } else if (alg.equals(ECDSA_SHA224)) {
+            return new SHA224withECDSA(smElem);
         } else if (alg.equals(ECDSA_SHA256)) {
             return new SHA256withECDSA(smElem);
         } else if (alg.equals(ECDSA_SHA384)) {
             return new SHA384withECDSA(smElem);
         } else if (alg.equals(ECDSA_SHA512)) {
             return new SHA512withECDSA(smElem);
+        } else if (alg.equals(ECDSA_RIPEMD160)) {
+            return new RIPEMD160withECDSA(smElem);
         } else if (alg.equals(SignatureMethod.HMAC_SHA1)) {
             return new DOMHMACSignatureMethod.SHA1(smElem);
+        } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA224)) {
+            return new DOMHMACSignatureMethod.SHA224(smElem);
         } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
             return new DOMHMACSignatureMethod.SHA256(smElem);
         } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
             return new DOMHMACSignatureMethod.SHA384(smElem);
         } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
             return new DOMHMACSignatureMethod.SHA512(smElem);
+        } else if (alg.equals(DOMHMACSignatureMethod.HMAC_RIPEMD160)) {
+            return new DOMHMACSignatureMethod.RIPEMD160(smElem);
         } else {
             throw new MarshalException
                 ("unsupported SignatureMethod algorithm: " + alg);
         }
     }
 
+    @Override
     public final AlgorithmParameterSpec getParameterSpec() {
         return params;
     }
@@ -197,7 +246,8 @@
             : Signature.getInstance(getJCAAlgorithm(), p);
     }
 
-    boolean verify(Key key, SignedInfo si, byte[] sig,
+    @Override
+    boolean verify(Key key, DOMSignedInfo si, byte[] sig,
                    XMLValidateContext context)
         throws InvalidKeyException, SignatureException, XMLSignatureException
     {
@@ -210,8 +260,8 @@
         }
         checkKeySize(context, key);
         if (signature == null) {
-            Provider p = (Provider)context.getProperty(
-                    "org.jcp.xml.dsig.internal.dom.SignatureProvider");
+            Provider p = (Provider) context.getProperty
+                    ("org.jcp.xml.dsig.internal.dom.SignatureProvider");
             try {
                 signature = getSignature(p);
             } catch (NoSuchAlgorithmException nsae) {
@@ -219,15 +269,14 @@
             }
         }
         signature.initVerify((PublicKey)key);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE,
-                    "Signature provider:" + signature.getProvider());
-            log.log(java.util.logging.Level.FINE, "verifying with key: " + key);
-        }
-        ((DOMSignedInfo)si).canonicalize(context,
-                                         new SignerOutputStream(signature));
+        LOG.debug("Signature provider: {}", signature.getProvider());
+        LOG.debug("Verifying with key: {}", key);
+        LOG.debug("JCA Algorithm: {}", getJCAAlgorithm());
+        LOG.debug("Signature Bytes length: {}", sig.length);
+
         byte[] s;
-        try {
+        try (SignerOutputStream outputStream = new SignerOutputStream(signature)) {
+            si.canonicalize(context, outputStream);
             // Do any necessary format conversions
             s = preVerifyFormat(key, sig);
         } catch (IOException ioe) {
@@ -252,10 +301,8 @@
                 // key size cannot be determined, so we cannot check against
                 // restrictions. Note that a DSA key w/o params will be
                 // rejected later if the certificate chain is validated.
-                if (log.isLoggable(java.util.logging.Level.FINE)) {
-                    log.log(java.util.logging.Level.FINE, "Size for " +
+                LOG.debug("Size for " +
                             key.getAlgorithm() + " key cannot be determined");
-                }
                 return;
             }
             if (Policy.restrictKey(key.getAlgorithm(), size)) {
@@ -267,7 +314,8 @@
         }
     }
 
-    byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+    @Override
+    byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
         throws InvalidKeyException, XMLSignatureException
     {
         if (key == null || si == null) {
@@ -279,8 +327,8 @@
         }
         checkKeySize(context, key);
         if (signature == null) {
-            Provider p = (Provider)context.getProperty(
-                    "org.jcp.xml.dsig.internal.dom.SignatureProvider");
+            Provider p = (Provider)context.getProperty
+                    ("org.jcp.xml.dsig.internal.dom.SignatureProvider");
             try {
                 signature = getSignature(p);
             } catch (NoSuchAlgorithmException nsae) {
@@ -288,16 +336,12 @@
             }
         }
         signature.initSign((PrivateKey)key);
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE,
-                    "Signature provider:" + signature.getProvider());
-            log.log(java.util.logging.Level.FINE, "Signing with key: " + key);
-        }
+        LOG.debug("Signature provider: {}", signature.getProvider());
+        LOG.debug("Signing with key: {}", key);
+        LOG.debug("JCA Algorithm: {}", getJCAAlgorithm());
 
-        ((DOMSignedInfo)si).canonicalize(context,
-                                         new SignerOutputStream(signature));
-
-        try {
+        try (SignerOutputStream outputStream = new SignerOutputStream(signature)) {
+            si.canonicalize(context, outputStream);
             // Return signature with any necessary format conversions
             return postSignFormat(key, signature.sign());
         } catch (SignatureException | IOException ex){
@@ -334,6 +378,40 @@
         }
     }
 
+    abstract static class AbstractRSAPSSSignatureMethod
+            extends AbstractRSASignatureMethod {
+
+        AbstractRSAPSSSignatureMethod(AlgorithmParameterSpec params)
+                throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+
+        AbstractRSAPSSSignatureMethod(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+
+        abstract public PSSParameterSpec getPSSParameterSpec();
+
+        @Override
+        Signature getSignature(Provider p)
+                throws NoSuchAlgorithmException {
+            try {
+                Signature s = (p == null)
+                        ? Signature.getInstance("RSASSA-PSS")
+                        : Signature.getInstance("RSASSA-PSS", p);
+                try {
+                    s.setParameter(getPSSParameterSpec());
+                } catch (InvalidAlgorithmParameterException e) {
+                    throw new NoSuchAlgorithmException("Should not happen", e);
+                }
+                return s;
+            } catch (NoSuchAlgorithmException nsae) {
+                return (p == null)
+                        ? Signature.getInstance(getJCAAlgorithm())
+                        : Signature.getInstance(getJCAAlgorithm(), p);
+            }
+        }
+    }
     /**
      * Abstract class to support signature algorithms that sign and verify
      * signatures in the IEEE P1363 format. The P1363 format is the
@@ -470,12 +548,37 @@
         SHA1withRSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return SignatureMethod.RSA_SHA1;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA1withRSA";
         }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA224withRSA extends AbstractRSASignatureMethod {
+        SHA224withRSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA224withRSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA224;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA224withRSA";
+        }
+        @Override
         Type getAlgorithmType() {
             return Type.RSA;
         }
@@ -489,12 +592,15 @@
         SHA256withRSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return RSA_SHA256;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA256withRSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.RSA;
         }
@@ -508,12 +614,15 @@
         SHA384withRSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return RSA_SHA384;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA384withRSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.RSA;
         }
@@ -527,12 +636,214 @@
         SHA512withRSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return RSA_SHA512;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA512withRSA";
         }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class RIPEMD160withRSA extends AbstractRSASignatureMethod {
+        RIPEMD160withRSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        RIPEMD160withRSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_RIPEMD160;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "RIPEMD160withRSA";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA1withRSAandMGF1 extends AbstractRSAPSSSignatureMethod {
+
+        private static PSSParameterSpec spec
+                = new PSSParameterSpec("SHA-1", "MGF1", MGF1ParameterSpec.SHA1,
+                20, PSSParameterSpec.TRAILER_FIELD_BC);
+
+        SHA1withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA1withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA1_MGF1;
+        }
+        @Override
+        public PSSParameterSpec getPSSParameterSpec() {
+            return spec;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA1withRSAandMGF1";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA224withRSAandMGF1 extends AbstractRSAPSSSignatureMethod {
+
+        private static PSSParameterSpec spec
+                = new PSSParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA224,
+                28, PSSParameterSpec.TRAILER_FIELD_BC);
+
+        SHA224withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA224withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA224_MGF1;
+        }
+        @Override
+        public PSSParameterSpec getPSSParameterSpec() {
+            return spec;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA224withRSAandMGF1";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA256withRSAandMGF1 extends AbstractRSAPSSSignatureMethod {
+
+        private static PSSParameterSpec spec
+                = new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
+                32, PSSParameterSpec.TRAILER_FIELD_BC);
+
+        SHA256withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA256withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA256_MGF1;
+        }
+        @Override
+        public PSSParameterSpec getPSSParameterSpec() {
+            return spec;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA256withRSAandMGF1";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA384withRSAandMGF1 extends AbstractRSAPSSSignatureMethod {
+
+        private static PSSParameterSpec spec
+                = new PSSParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384,
+                48, PSSParameterSpec.TRAILER_FIELD_BC);
+
+        SHA384withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA384withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA384_MGF1;
+        }
+        @Override
+        public PSSParameterSpec getPSSParameterSpec() {
+            return spec;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA384withRSAandMGF1";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class SHA512withRSAandMGF1 extends AbstractRSAPSSSignatureMethod {
+
+        private static PSSParameterSpec spec
+                = new PSSParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512,
+                64, PSSParameterSpec.TRAILER_FIELD_BC);
+
+        SHA512withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA512withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_SHA512_MGF1;
+        }
+        @Override
+        public PSSParameterSpec getPSSParameterSpec() {
+            return spec;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA512withRSAandMGF1";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.RSA;
+        }
+    }
+
+    static final class RIPEMD160withRSAandMGF1 extends AbstractRSASignatureMethod {
+        RIPEMD160withRSAandMGF1(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        RIPEMD160withRSAandMGF1(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return RSA_RIPEMD160_MGF1;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "RIPEMD160withRSAandMGF1";
+        }
+        @Override
         Type getAlgorithmType() {
             return Type.RSA;
         }
@@ -546,15 +857,18 @@
         SHA1withDSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return SignatureMethod.DSA_SHA1;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA1withDSAinP1363Format";
         }
         String getJCAFallbackAlgorithm() {
             return "SHA1withDSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.DSA;
         }
@@ -590,15 +904,43 @@
         SHA1withECDSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return ECDSA_SHA1;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA1withECDSAinP1363Format";
         }
         String getJCAFallbackAlgorithm() {
             return "SHA1withECDSA";
         }
+        @Override
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
+    }
+
+    static final class SHA224withECDSA extends AbstractECDSASignatureMethod {
+        SHA224withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        SHA224withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return ECDSA_SHA224;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "SHA224withECDSAinP1363Format";
+        }
+        String getJCAFallbackAlgorithm() {
+            return "SHA224withECDSA";
+        }
+        @Override
         Type getAlgorithmType() {
             return Type.ECDSA;
         }
@@ -612,15 +954,18 @@
         SHA256withECDSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return ECDSA_SHA256;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA256withECDSAinP1363Format";
         }
         String getJCAFallbackAlgorithm() {
             return "SHA256withECDSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.ECDSA;
         }
@@ -634,15 +979,18 @@
         SHA384withECDSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return ECDSA_SHA384;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA384withECDSAinP1363Format";
         }
         String getJCAFallbackAlgorithm() {
             return "SHA384withECDSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.ECDSA;
         }
@@ -656,17 +1004,46 @@
         SHA512withECDSA(Element dmElem) throws MarshalException {
             super(dmElem);
         }
+        @Override
         public String getAlgorithm() {
             return ECDSA_SHA512;
         }
+        @Override
         String getJCAAlgorithm() {
             return "SHA512withECDSAinP1363Format";
         }
         String getJCAFallbackAlgorithm() {
             return "SHA512withECDSA";
         }
+        @Override
         Type getAlgorithmType() {
             return Type.ECDSA;
         }
     }
+
+    static final class RIPEMD160withECDSA extends AbstractECDSASignatureMethod {
+        RIPEMD160withECDSA(AlgorithmParameterSpec params)
+            throws InvalidAlgorithmParameterException {
+            super(params);
+        }
+        RIPEMD160withECDSA(Element dmElem) throws MarshalException {
+            super(dmElem);
+        }
+        @Override
+        public String getAlgorithm() {
+            return ECDSA_RIPEMD160;
+        }
+        @Override
+        String getJCAAlgorithm() {
+            return "RIPEMD160withECDSAinP1363Format"; // Is this real?
+        }
+        String getJCAFallbackAlgorithm() {
+            return "RIPEMD160withECDSA";
+        }
+        @Override
+        Type getAlgorithmType() {
+            return Type.ECDSA;
+        }
+    }
+
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,133 +21,122 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMSignatureProperties.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
 
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * DOM-based implementation of SignatureProperties.
  *
- * @author Sean Mullan
  */
-public final class DOMSignatureProperties extends DOMStructure
+public final class DOMSignatureProperties extends BaseStructure
     implements SignatureProperties {
 
     private final String id;
     private final List<SignatureProperty> properties;
 
     /**
-     * Creates a <code>DOMSignatureProperties</code> from the specified
+     * Creates a {@code DOMSignatureProperties} from the specified
      * parameters.
      *
      * @param properties a list of one or more {@link SignatureProperty}s. The
      *    list is defensively copied to protect against subsequent modification.
-     * @param id the Id (may be <code>null</code>)
-     * @throws ClassCastException if <code>properties</code> contains any
+     * @param id the Id (may be {@code null})
+     * @throws ClassCastException if {@code properties} contains any
      *    entries that are not of type {@link SignatureProperty}
-     * @throws IllegalArgumentException if <code>properties</code> is empty
-     * @throws NullPointerException if <code>properties</code>
+     * @throws IllegalArgumentException if {@code properties} is empty
+     * @throws NullPointerException if {@code properties}
      */
-    public DOMSignatureProperties(List<? extends SignatureProperty> properties,
+    public DOMSignatureProperties(List<DOMSignatureProperty> properties,
                                   String id)
     {
         if (properties == null) {
             throw new NullPointerException("properties cannot be null");
+        } else if (properties.isEmpty()) {
+            throw new IllegalArgumentException("properties cannot be empty");
+        } else {
+            this.properties = Collections.unmodifiableList(
+                new ArrayList<>(properties));
+            for (int i = 0, size = this.properties.size(); i < size; i++) {
+                if (!(this.properties.get(i) instanceof SignatureProperty)) {
+                    throw new ClassCastException
+                        ("properties["+i+"] is not a valid type");
+                }
+            }
         }
-        List<SignatureProperty> tempList =
-            Collections.checkedList(new ArrayList<SignatureProperty>(),
-                                    SignatureProperty.class);
-        tempList.addAll(properties);
-        if (tempList.isEmpty()) {
-            throw new IllegalArgumentException("properties cannot be empty");
-        }
-        this.properties = Collections.unmodifiableList(tempList);
         this.id = id;
     }
 
     /**
-     * Creates a <code>DOMSignatureProperties</code> from an element.
+     * Creates a {@code DOMSignatureProperties} from an element.
      *
      * @param propsElem a SignatureProperties element
      * @throws MarshalException if a marshalling error occurs
      */
-    public DOMSignatureProperties(Element propsElem, XMLCryptoContext context)
+    public DOMSignatureProperties(Element propsElem)
         throws MarshalException
     {
         // unmarshal attributes
-        Attr attr = propsElem.getAttributeNodeNS(null, "Id");
-        if (attr != null) {
-            id = attr.getValue();
-            propsElem.setIdAttributeNode(attr, true);
-        } else {
-            id = null;
-        }
+        id = DOMUtils.getIdAttributeValue(propsElem, "Id");
 
-        NodeList nodes = propsElem.getChildNodes();
-        int length = nodes.getLength();
-        List<SignatureProperty> properties =
-            new ArrayList<SignatureProperty>(length);
-        for (int i = 0; i < length; i++) {
-            Node child = nodes.item(i);
-            if (child.getNodeType() == Node.ELEMENT_NODE) {
-                String name = child.getLocalName();
-                if (!name.equals("SignatureProperty")) {
-                    throw new MarshalException("Invalid element name: " + name +
+        List<SignatureProperty> newProperties = new ArrayList<>();
+        Node firstChild = propsElem.getFirstChild();
+        while (firstChild != null) {
+            if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                String name = firstChild.getLocalName();
+                String namespace = firstChild.getNamespaceURI();
+                if (!"SignatureProperty".equals(name) || !XMLSignature.XMLNS.equals(namespace)) {
+                    throw new MarshalException("Invalid element name: " + namespace + ":" + name +
                                                ", expected SignatureProperty");
                 }
-                properties.add(new DOMSignatureProperty((Element)child,
-                                                        context));
+                newProperties.add(new DOMSignatureProperty((Element)firstChild));
             }
+            firstChild = firstChild.getNextSibling();
         }
-        if (properties.isEmpty()) {
+        if (newProperties.isEmpty()) {
             throw new MarshalException("properties cannot be empty");
         } else {
-            this.properties = Collections.unmodifiableList(properties);
+            this.properties = Collections.unmodifiableList(newProperties);
         }
     }
 
+    @Override
     public List<SignatureProperty> getProperties() {
         return properties;
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public static void marshal(XmlWriter xwriter, SignatureProperties sigProps, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element propsElem = DOMUtils.createElement(ownerDoc,
-                                                   "SignatureProperties",
-                                                   XMLSignature.XMLNS,
-                                                   dsPrefix);
+        xwriter.writeStartElement(dsPrefix, "SignatureProperties", XMLSignature.XMLNS);
 
         // set attributes
-        DOMUtils.setAttributeID(propsElem, "Id", id);
+        xwriter.writeIdAttribute("", "", "Id", sigProps.getId());
 
         // create and append any properties
+        @SuppressWarnings("unchecked")
+        List<SignatureProperty> properties = sigProps.getProperties();
         for (SignatureProperty property : properties) {
-            ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix,
-                                                     context);
+            DOMSignatureProperty.marshal(xwriter, property, dsPrefix, context);
         }
 
-        parent.appendChild(propsElem);
+        xwriter.writeEndElement(); // "SignatureProperties"
     }
 
     @Override
@@ -161,10 +150,10 @@
         }
         SignatureProperties osp = (SignatureProperties)o;
 
-        boolean idsEqual = (id == null ? osp.getId() == null
-                                       : id.equals(osp.getId()));
+        boolean idsEqual = id == null ? osp.getId() == null
+                                       : id.equals(osp.getId());
 
-        return (properties.equals(osp.getProperties()) && idsEqual);
+        return properties.equals(osp.getProperties()) && idsEqual;
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,31 +21,26 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMSignatureProperty.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
 
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * DOM-based implementation of SignatureProperty.
  *
- * @author Sean Mullan
  */
-public final class DOMSignatureProperty extends DOMStructure
+public final class DOMSignatureProperty extends BaseStructure
     implements SignatureProperty {
 
     private final String id;
@@ -53,45 +48,47 @@
     private final List<XMLStructure> content;
 
     /**
-     * Creates a <code>SignatureProperty</code> from the specified parameters.
+     * Creates a {@code SignatureProperty} from the specified parameters.
      *
      * @param content a list of one or more {@link XMLStructure}s. The list
      *    is defensively copied to protect against subsequent modification.
      * @param target the target URI
-     * @param id the Id (may be <code>null</code>)
-     * @throws ClassCastException if <code>content</code> contains any
+     * @param id the Id (may be {@code null})
+     * @throws ClassCastException if {@code content} contains any
      *    entries that are not of type {@link XMLStructure}
-     * @throws IllegalArgumentException if <code>content</code> is empty
-     * @throws NullPointerException if <code>content</code> or
-     *    <code>target</code> is <code>null</code>
+     * @throws IllegalArgumentException if {@code content} is empty
+     * @throws NullPointerException if {@code content} or
+     *    {@code target} is {@code null}
      */
     public DOMSignatureProperty(List<? extends XMLStructure> content,
                                 String target, String id)
     {
         if (target == null) {
             throw new NullPointerException("target cannot be null");
-        }
-        if (content == null) {
+        } else if (content == null) {
             throw new NullPointerException("content cannot be null");
+        } else if (content.isEmpty()) {
+            throw new IllegalArgumentException("content cannot be empty");
+        } else {
+            this.content = Collections.unmodifiableList(
+                new ArrayList<>(content));
+            for (int i = 0, size = this.content.size(); i < size; i++) {
+                if (!(this.content.get(i) instanceof XMLStructure)) {
+                    throw new ClassCastException
+                        ("content["+i+"] is not a valid type");
+                }
+            }
         }
-        List<XMLStructure> tempList =
-            Collections.checkedList(new ArrayList<XMLStructure>(),
-                                    XMLStructure.class);
-        tempList.addAll(content);
-        if (tempList.isEmpty()) {
-            throw new IllegalArgumentException("content cannot be empty");
-        }
-        this.content = Collections.unmodifiableList(tempList);
         this.target = target;
         this.id = id;
     }
 
     /**
-     * Creates a <code>DOMSignatureProperty</code> from an element.
+     * Creates a {@code DOMSignatureProperty} from an element.
      *
      * @param propElem a SignatureProperty element
      */
-    public DOMSignatureProperty(Element propElem, XMLCryptoContext context)
+    public DOMSignatureProperty(Element propElem)
         throws MarshalException
     {
         // unmarshal attributes
@@ -99,57 +96,52 @@
         if (target == null) {
             throw new MarshalException("target cannot be null");
         }
-        Attr attr = propElem.getAttributeNodeNS(null, "Id");
-        if (attr != null) {
-            id = attr.getValue();
-            propElem.setIdAttributeNode(attr, true);
-        } else {
-            id = null;
-        }
+        id = DOMUtils.getIdAttributeValue(propElem, "Id");
 
-        NodeList nodes = propElem.getChildNodes();
-        int length = nodes.getLength();
-        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
-        for (int i = 0; i < length; i++) {
-            content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i)));
+        List<XMLStructure> newContent = new ArrayList<>();
+        Node firstChild = propElem.getFirstChild();
+        while (firstChild != null) {
+            newContent.add(new javax.xml.crypto.dom.DOMStructure(firstChild));
+            firstChild = firstChild.getNextSibling();
         }
-        if (content.isEmpty()) {
+        if (newContent.isEmpty()) {
             throw new MarshalException("content cannot be empty");
         } else {
-            this.content = Collections.unmodifiableList(content);
+            this.content = Collections.unmodifiableList(newContent);
         }
     }
 
+    @Override
     public List<XMLStructure> getContent() {
         return content;
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public String getTarget() {
         return target;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public static void marshal(XmlWriter xwriter, SignatureProperty sigProp, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty",
-                                                  XMLSignature.XMLNS, dsPrefix);
+        xwriter.writeStartElement(dsPrefix, "SignatureProperty", XMLSignature.XMLNS);
 
         // set attributes
-        DOMUtils.setAttributeID(propElem, "Id", id);
-        DOMUtils.setAttribute(propElem, "Target", target);
+        xwriter.writeIdAttribute("", "", "Id", sigProp.getId());
+        xwriter.writeAttribute("", "", "Target", sigProp.getTarget());
 
         // create and append any elements and mixed content
+        List<XMLStructure> content = getContent(sigProp);
         for (XMLStructure property : content) {
-            DOMUtils.appendChild(propElem,
-                ((javax.xml.crypto.dom.DOMStructure)property).getNode());
+            xwriter.marshalStructure(property, dsPrefix, context);
         }
 
-        parent.appendChild(propElem);
+        xwriter.writeEndElement(); // "SignatureProperty"
     }
 
     @Override
@@ -163,12 +155,13 @@
         }
         SignatureProperty osp = (SignatureProperty)o;
 
-        boolean idsEqual = (id == null ? osp.getId() == null
-                                       : id.equals(osp.getId()));
+        boolean idsEqual = id == null ? osp.getId() == null
+                                       : id.equals(osp.getId());
 
+        @SuppressWarnings("unchecked")
         List<XMLStructure> ospContent = osp.getContent();
-        return (equalsContent(ospContent) &&
-                target.equals(osp.getTarget()) && idsEqual);
+        return equalsContent(ospContent) &&
+                target.equals(osp.getTarget()) && idsEqual;
     }
 
     @Override
@@ -183,6 +176,10 @@
         return result;
     }
 
+    @SuppressWarnings("unchecked")
+    private static List<XMLStructure> getContent(SignatureProperty prop) {
+        return prop.getContent();
+    }
     private boolean equalsContent(List<XMLStructure> otherContent) {
         int osize = otherContent.size();
         if (content.size() != osize) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,15 +21,14 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMSignedInfo.java 1820179 2018-01-04 19:09:52Z mullan $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 
 import java.io.ByteArrayInputStream;
@@ -40,44 +39,38 @@
 import java.security.Provider;
 import java.util.*;
 
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
 
 /**
  * DOM-based implementation of SignedInfo.
  *
- * @author Sean Mullan
  */
 public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DOMSignedInfo.class);
 
     private List<Reference> references;
     private CanonicalizationMethod canonicalizationMethod;
     private SignatureMethod signatureMethod;
     private String id;
-    private Document ownerDoc;
     private Element localSiElem;
     private InputStream canonData;
 
     /**
-     * Creates a <code>DOMSignedInfo</code> from the specified parameters. Use
-     * this constructor when the <code>Id</code> is not specified.
+     * Creates a {@code DOMSignedInfo} from the specified parameters. Use
+     * this constructor when the {@code Id} is not specified.
      *
      * @param cm the canonicalization method
      * @param sm the signature method
      * @param references the list of references. The list is copied.
      * @throws NullPointerException if
-     *    <code>cm</code>, <code>sm</code>, or <code>references</code> is
-     *    <code>null</code>
-     * @throws IllegalArgumentException if <code>references</code> is empty
+     *    {@code cm}, {@code sm}, or {@code references} is
+     *    {@code null}
+     * @throws IllegalArgumentException if {@code references} is empty
      * @throws ClassCastException if any of the references are not of
-     *    type <code>Reference</code>
+     *    type {@code Reference}
      */
     public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
                          List<? extends Reference> references) {
@@ -86,30 +79,35 @@
         }
         this.canonicalizationMethod = cm;
         this.signatureMethod = sm;
-        List<Reference> tempList =
-            Collections.checkedList(new ArrayList<Reference>(),
-                                    Reference.class);
-        tempList.addAll(references);
-        if (tempList.isEmpty()) {
-            throw new IllegalArgumentException("references cannot be empty");
+        this.references = Collections.unmodifiableList(
+            new ArrayList<>(references));
+        if (this.references.isEmpty()) {
+            throw new IllegalArgumentException("list of references must " +
+                "contain at least one entry");
         }
-        this.references = Collections.unmodifiableList(tempList);
+        for (int i = 0, size = this.references.size(); i < size; i++) {
+            Object obj = this.references.get(i);
+            if (!(obj instanceof Reference)) {
+                throw new ClassCastException("list of references contains " +
+                    "an illegal type");
+            }
+        }
     }
 
     /**
-     * Creates a <code>DOMSignedInfo</code> from the specified parameters.
+     * Creates a {@code DOMSignedInfo} from the specified parameters.
      *
      * @param cm the canonicalization method
      * @param sm the signature method
      * @param references the list of references. The list is copied.
      * @param id an optional identifer that will allow this
-     *    <code>SignedInfo</code> to be referenced by other signatures and
+     *    {@code SignedInfo} to be referenced by other signatures and
      *    objects
-     * @throws NullPointerException if <code>cm</code>, <code>sm</code>,
-     *    or <code>references</code> is <code>null</code>
-     * @throws IllegalArgumentException if <code>references</code> is empty
+     * @throws NullPointerException if {@code cm}, {@code sm},
+     *    or {@code references} is {@code null}
+     * @throws IllegalArgumentException if {@code references} is empty
      * @throws ClassCastException if any of the references are not of
-     *    type <code>Reference</code>
+     *    type {@code Reference}
      */
     public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
                          List<? extends Reference> references, String id) {
@@ -118,27 +116,28 @@
     }
 
     /**
-     * Creates a <code>DOMSignedInfo</code> from an element.
+     * Creates a {@code DOMSignedInfo} from an element.
      *
      * @param siElem a SignedInfo element
      */
     public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider)
         throws MarshalException {
         localSiElem = siElem;
-        ownerDoc = siElem.getOwnerDocument();
 
         // get Id attribute, if specified
         id = DOMUtils.getAttributeValue(siElem, "Id");
 
         // unmarshal CanonicalizationMethod
         Element cmElem = DOMUtils.getFirstChildElement(siElem,
-                                                       "CanonicalizationMethod");
+                                                       "CanonicalizationMethod",
+                                                       XMLSignature.XMLNS);
         canonicalizationMethod = new DOMCanonicalizationMethod(cmElem, context,
                                                                provider);
 
         // unmarshal SignatureMethod
         Element smElem = DOMUtils.getNextSiblingElement(cmElem,
-                                                        "SignatureMethod");
+                                                        "SignatureMethod",
+                                                        XMLSignature.XMLNS);
         signatureMethod = DOMSignatureMethod.unmarshal(smElem);
 
         boolean secVal = Utils.secureValidation(context);
@@ -152,21 +151,21 @@
         }
 
         // unmarshal References
-        ArrayList<Reference> refList = new ArrayList<Reference>(5);
-        Element refElem = DOMUtils.getNextSiblingElement(smElem, "Reference");
+        ArrayList<Reference> refList = new ArrayList<>(5);
+        Element refElem = DOMUtils.getNextSiblingElement(smElem, "Reference", XMLSignature.XMLNS);
         refList.add(new DOMReference(refElem, context, provider));
 
         refElem = DOMUtils.getNextSiblingElement(refElem);
         while (refElem != null) {
             String name = refElem.getLocalName();
-            if (!name.equals("Reference")) {
+            String namespace = refElem.getNamespaceURI();
+            if (!"Reference".equals(name) || !XMLSignature.XMLNS.equals(namespace)) {
                 throw new MarshalException("Invalid element name: " +
-                                           name + ", expected Reference");
+                                           namespace + ":" + name + ", expected Reference");
             }
             refList.add(new DOMReference(refElem, context, provider));
-
             if (secVal && Policy.restrictNumReferences(refList.size())) {
-                String error = "A maximum of " + Policy.maxReferences()
+                String error = "A maxiumum of " + Policy.maxReferences()
                     + " references per Manifest are allowed when"
                     + " secure validation is enabled";
                 throw new MarshalException(error);
@@ -176,22 +175,27 @@
         references = Collections.unmodifiableList(refList);
     }
 
+    @Override
     public CanonicalizationMethod getCanonicalizationMethod() {
         return canonicalizationMethod;
     }
 
+    @Override
     public SignatureMethod getSignatureMethod() {
         return signatureMethod;
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public List<Reference> getReferences() {
         return references;
     }
 
+    @Override
     public InputStream getCanonicalizedData() {
         return canonData;
     }
@@ -202,75 +206,62 @@
             throw new NullPointerException("context cannot be null");
         }
 
-        OutputStream os = new UnsyncBufferedOutputStream(bos);
-
         DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true);
-        try {
+        try (OutputStream os = new UnsyncBufferedOutputStream(bos)) {
             ((DOMCanonicalizationMethod)
                 canonicalizationMethod).canonicalize(subTree, context, os);
+
+            os.flush();
+
+            byte[] signedInfoBytes = bos.toByteArray();
+
+            // this whole block should only be done if LOGging is enabled
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Canonicalized SignedInfo:");
+                StringBuilder sb = new StringBuilder(signedInfoBytes.length);
+                for (int i = 0; i < signedInfoBytes.length; i++) {
+                    sb.append((char)signedInfoBytes[i]);
+                }
+                LOG.debug(sb.toString());
+                LOG.debug("Data to be signed/verified:" + Base64.getMimeEncoder().encodeToString(signedInfoBytes));
+            }
+
+            this.canonData = new ByteArrayInputStream(signedInfoBytes);
         } catch (TransformException te) {
             throw new XMLSignatureException(te);
-        }
-
-        try {
-            os.flush();
         } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
-            // Impossible
-        }
-
-        byte[] signedInfoBytes = bos.toByteArray();
-
-        // this whole block should only be done if logging is enabled
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:");
-            StringBuilder sb = new StringBuilder(signedInfoBytes.length);
-            for (int i = 0; i < signedInfoBytes.length; i++) {
-                sb.append((char)signedInfoBytes[i]);
-            }
-            log.log(java.util.logging.Level.FINE, sb.toString());
-            log.log(java.util.logging.Level.FINE, "Data to be signed/verified:" + Base64.encode(signedInfoBytes));
-        }
-
-        this.canonData = new ByteArrayInputStream(signedInfoBytes);
-
-        try {
-            os.close();
-        } catch (IOException e) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
-            }
+            LOG.debug(e.getMessage(), e);
             // Impossible
         }
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    @Override
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo",
-                                                XMLSignature.XMLNS, dsPrefix);
+        xwriter.writeStartElement(dsPrefix, "SignedInfo", XMLSignature.XMLNS);
+        XMLStructure siStruct = xwriter.getCurrentNodeAsStructure();
+        localSiElem = (Element) ((javax.xml.crypto.dom.DOMStructure) siStruct).getNode();
+
+        // append Id attribute
+        xwriter.writeIdAttribute("", "", "Id", id);
 
         // create and append CanonicalizationMethod element
         DOMCanonicalizationMethod dcm =
             (DOMCanonicalizationMethod)canonicalizationMethod;
-        dcm.marshal(siElem, dsPrefix, context);
+        dcm.marshal(xwriter, dsPrefix, context);
 
         // create and append SignatureMethod element
-        ((DOMStructure)signatureMethod).marshal(siElem, dsPrefix, context);
+        ((AbstractDOMSignatureMethod)signatureMethod).marshal(xwriter, dsPrefix);
 
         // create and append Reference elements
         for (Reference reference : references) {
-            ((DOMReference)reference).marshal(siElem, dsPrefix, context);
+            // TODO - either suppress warning here, or figure out how to get rid of the cast.
+            DOMReference domRef = (DOMReference)reference;
+            domRef.marshal(xwriter, dsPrefix, context);
         }
 
-        // append Id attribute
-        DOMUtils.setAttributeID(siElem, "Id", id);
-
-        parent.appendChild(siElem);
-        localSiElem = siElem;
+        xwriter.writeEndElement(); // "SignedInfo"
     }
 
     @Override
@@ -284,12 +275,17 @@
         }
         SignedInfo osi = (SignedInfo)o;
 
-        boolean idEqual = (id == null ? osi.getId() == null
-                                      : id.equals(osi.getId()));
+        boolean idEqual = id == null ? osi.getId() == null
+                                      : id.equals(osi.getId());
 
-        return (canonicalizationMethod.equals(osi.getCanonicalizationMethod())
+        return canonicalizationMethod.equals(osi.getCanonicalizationMethod())
                 && signatureMethod.equals(osi.getSignatureMethod()) &&
-                references.equals(osi.getReferences()) && idEqual);
+                references.equals(osi.getReferences()) && idEqual;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static List<Reference> getSignedInfoReferences(SignedInfo si) {
+        return si.getReferences();
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,33 +21,21 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMStructure.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMStructure.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.MarshalException;
-import javax.xml.crypto.XMLStructure;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import org.w3c.dom.Node;
+import javax.xml.crypto.XMLCryptoContext;
 
 /**
  * DOM-based abstract implementation of XMLStructure.
  *
- * @author Sean Mullan
  */
-public abstract class DOMStructure implements XMLStructure {
+public abstract class DOMStructure extends BaseStructure {
 
-    public final boolean isFeatureSupported(String feature) {
-        if (feature == null) {
-            throw new NullPointerException();
-        } else {
-            return false;
-        }
-    }
-
-    public abstract void marshal(Node parent, String dsPrefix,
-        DOMCryptoContext context) throws MarshalException;
+    public abstract void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context) throws MarshalException;
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id$
@@ -54,6 +54,7 @@
         this.excludeComments = excludeComments;
     }
 
+    @Override
     public Iterator<Node> iterator() {
         return new DelayedNodeIterator(root, excludeComments);
     }
@@ -81,6 +82,7 @@
             this.withComments = !excludeComments;
         }
 
+        @Override
         public boolean hasNext() {
             if (nodeSet == null) {
                 nodeSet = dereferenceSameDocumentURI(root);
@@ -89,6 +91,7 @@
             return li.hasNext();
         }
 
+        @Override
         public Node next() {
             if (nodeSet == null) {
                 nodeSet = dereferenceSameDocumentURI(root);
@@ -101,6 +104,7 @@
             }
         }
 
+        @Override
         public void remove() {
             throw new UnsupportedOperationException();
         }
@@ -109,15 +113,15 @@
          * Dereferences a same-document URI fragment.
          *
          * @param node the node (document or element) referenced by the
-         *        URI fragment. If null, returns an empty set.
+         *     URI fragment. If null, returns an empty set.
          * @return a set of nodes (minus any comment nodes)
          */
         private List<Node> dereferenceSameDocumentURI(Node node) {
-            List<Node> nodeSet = new ArrayList<Node>();
+            List<Node> nodes = new ArrayList<>();
             if (node != null) {
-                nodeSetMinusCommentNodes(node, nodeSet, null);
+                nodeSetMinusCommentNodes(node, nodes, null);
             }
-            return nodeSet;
+            return nodes;
         }
 
         /**
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMTransform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -34,21 +34,23 @@
 import java.security.Provider;
 import java.security.spec.AlgorithmParameterSpec;
 
-import org.w3c.dom.Document;
+import javax.xml.crypto.Data;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.dsig.Transform;
+import javax.xml.crypto.dsig.TransformException;
+import javax.xml.crypto.dsig.TransformService;
+import javax.xml.crypto.dsig.XMLSignature;
+import javax.xml.crypto.dsig.dom.DOMSignContext;
+
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.dom.DOMSignContext;
-
 /**
  * DOM-based abstract implementation of Transform.
  *
- * @author Sean Mullan
  */
-public class DOMTransform extends DOMStructure implements Transform {
+public class DOMTransform extends BaseStructure implements Transform {
 
     protected TransformService spi;
 
@@ -62,9 +64,8 @@
     }
 
     /**
-     * Creates a {@code DOMTransform} from an element. This constructor
-     * invokes the abstract {@link #unmarshalParams unmarshalParams} method to
-     * unmarshal any algorithm-specific input parameters.
+     * Creates a {@code DOMTransform} from an element. It unmarshals any
+     * algorithm-specific input parameters.
      *
      * @param transElem a Transform element
      */
@@ -73,7 +74,6 @@
         throws MarshalException
     {
         String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm");
-
         if (provider == null) {
             try {
                 spi = TransformService.getInstance(algorithm, "DOM");
@@ -98,40 +98,31 @@
         }
     }
 
+    @Override
     public final AlgorithmParameterSpec getParameterSpec() {
         return spi.getParameterSpec();
     }
 
+    @Override
     public final String getAlgorithm() {
         return spi.getAlgorithm();
     }
 
     /**
-     * This method invokes the abstract {@link #marshalParams marshalParams}
-     * method to marshal any algorithm-specific parameters.
+     * This method marshals any algorithm-specific parameters.
      */
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
+        String parentLocalName = xwriter.getCurrentLocalName();
+        String localName = "Transforms".equals(parentLocalName) ? "Transform" : "CanonicalizationMethod";
+        xwriter.writeStartElement(dsPrefix, localName, XMLSignature.XMLNS);
+        xwriter.writeAttribute("", "", "Algorithm", getAlgorithm());
 
-        Element transformElem = null;
-        if (parent.getLocalName().equals("Transforms")) {
-            transformElem = DOMUtils.createElement(ownerDoc, "Transform",
-                                                   XMLSignature.XMLNS,
-                                                   dsPrefix);
-        } else {
-            transformElem = DOMUtils.createElement(ownerDoc,
-                                                   "CanonicalizationMethod",
-                                                   XMLSignature.XMLNS,
-                                                   dsPrefix);
-        }
-        DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm());
+        javax.xml.crypto.XMLStructure xmlStruct = xwriter.getCurrentNodeAsStructure();
+        spi.marshalParams(xmlStruct, context);
 
-        spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem),
-                          context);
-
-        parent.appendChild(transformElem);
+        xwriter.writeEndElement(); // "Transforms" or "CanonicalizationMethod"
     }
 
     /**
@@ -139,12 +130,13 @@
      *
      * @param data the data to be transformed
      * @param xc the {@code XMLCryptoContext} containing
-     *     additional context (may be {@code null} if not applicable)
+     *    additional context (may be {@code null} if not applicable)
      * @return the transformed data
      * @throws NullPointerException if {@code data} is {@code null}
      * @throws XMLSignatureException if an unexpected error occurs while
-     *     executing the transform
+     *    executing the transform
      */
+    @Override
     public Data transform(Data data, XMLCryptoContext xc)
         throws TransformException
     {
@@ -155,15 +147,16 @@
      * Transforms the specified data using the underlying transform algorithm.
      *
      * @param data the data to be transformed
-     * @param xc the {@code XMLCryptoContext} containing
-     *     additional context (may be {@code null} if not applicable)
+     * @param xc     the {@code XMLCryptoContext} containing
+     *    additional context (may be {@code null} if not applicable)
      * @param os the {@code OutputStream} that should be used to write
-     *     the transformed data to
+     *    the transformed data to
      * @return the transformed data
      * @throws NullPointerException if {@code data} is {@code null}
      * @throws XMLSignatureException if an unexpected error occurs while
-     *     executing the transform
+     *    executing the transform
      */
+    @Override
     public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
         throws TransformException
     {
@@ -181,9 +174,9 @@
         }
         Transform otransform = (Transform)o;
 
-        return (getAlgorithm().equals(otransform.getAlgorithm()) &&
+        return getAlgorithm().equals(otransform.getAlgorithm()) &&
                 DOMUtils.paramsEqual(getParameterSpec(),
-                                     otransform.getParameterSpec()));
+                                     otransform.getParameterSpec());
     }
 
     @Override
@@ -217,8 +210,9 @@
     Data transform(Data data, XMLCryptoContext xc, DOMSignContext context)
         throws MarshalException, TransformException
     {
-        marshal(context.getParent(),
-                DOMUtils.getSignaturePrefix(context), context);
+        Node parent = context.getParent();
+        XmlWriter xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), parent);
+        marshal(xwriter, DOMUtils.getSignaturePrefix(context), context);
         return transform(data, xc);
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $
+ * $Id: DOMURIDereferencer.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -43,9 +43,8 @@
 /**
  * DOM-based implementation of URIDereferencer.
  *
- * @author Sean Mullan
  */
-public class DOMURIDereferencer implements URIDereferencer {
+public final class DOMURIDereferencer implements URIDereferencer {
 
     static final URIDereferencer INSTANCE = new DOMURIDereferencer();
 
@@ -55,6 +54,7 @@
         Init.init();
     }
 
+    @Override
     public Data dereference(URIReference uriRef, XMLCryptoContext context)
         throws URIReferenceException {
 
@@ -106,6 +106,7 @@
                 }
 
                 XMLSignatureInput result = new XMLSignatureInput(referencedElem);
+                result.setSecureValidation(secVal);
                 if (!uri.substring(1).startsWith("xpointer(id(")) {
                     result.setExcludeComments(true);
                 }
@@ -123,8 +124,7 @@
         try {
             ResourceResolver apacheResolver =
                 ResourceResolver.getInstance(uriAttr, baseURI, false);
-            XMLSignatureInput in = apacheResolver.resolve(uriAttr,
-                                                          baseURI, false);
+            XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI, false);
             if (in.isOctetStream()) {
                 return new ApacheOctetStreamData(in);
             } else {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMUtils.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -35,6 +35,8 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
+
+import javax.xml.XMLConstants;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.*;
@@ -42,9 +44,8 @@
 /**
  * Useful static DOM utility methods.
  *
- * @author Sean Mullan
  */
-public class DOMUtils {
+public final class DOMUtils {
 
     // class cannot be instantiated
     private DOMUtils() {}
@@ -64,6 +65,21 @@
     }
 
     /**
+     * Create a QName string from a prefix and local name.
+     *
+     * @param prefix    The prefix, if any. Can be either null or empty.
+     * @param localName The local name.
+     *
+     * @return The string for the qName, for example, "xsd:element".
+     */
+    public static String getQNameString(String prefix, String localName) {
+        String qName = prefix == null || prefix.length() == 0
+                ? localName : prefix + ":" + localName;
+
+        return qName;
+    }
+
+    /**
      * Creates an element in the specified namespace, with the specified tag
      * and namespace prefix.
      *
@@ -76,9 +92,7 @@
     public static Element createElement(Document doc, String tag,
                                         String nsURI, String prefix)
     {
-        String qName = (prefix == null || prefix.length() == 0)
-                       ? tag : prefix + ":" + tag;
-        return doc.createElementNS(nsURI, qName);
+        return doc.createElementNS(nsURI, getQNameString(prefix, tag));
     }
 
     /**
@@ -121,7 +135,7 @@
      * @param node the node
      * @return the first child element of the specified node, or null if there
      *    is no such element
-     * @throws NullPointerException if <code>node == null</code>
+     * @throws NullPointerException if {@code node == null}
      */
     public static Element getFirstChildElement(Node node) {
         Node child = node.getFirstChild();
@@ -141,12 +155,30 @@
      * @throws MarshalException if no such element or the local name is not
      *    equal to {@code localName}
      */
+    @Deprecated
     public static Element getFirstChildElement(Node node, String localName)
         throws MarshalException
     {
         return verifyElement(getFirstChildElement(node), localName);
     }
 
+    /**
+     * Returns the first child element of the specified node and checks that
+     * the local name is equal to {@code localName} and the namespace is equal to
+     * {@code namespaceURI}
+     *
+     * @param node the node
+     * @return the first child element of the specified node
+     * @throws NullPointerException if {@code node == null}
+     * @throws MarshalException if no such element or the local name is not
+     *    equal to {@code localName}
+     */
+    public static Element getFirstChildElement(Node node, String localName, String namespaceURI)
+        throws MarshalException
+    {
+        return verifyElement(getFirstChildElement(node), localName, namespaceURI);
+    }
+
     private static Element verifyElement(Element elem, String localName)
         throws MarshalException
     {
@@ -161,6 +193,22 @@
         return elem;
     }
 
+    private static Element verifyElement(Element elem, String localName, String namespaceURI)
+        throws MarshalException
+    {
+        if (elem == null) {
+            throw new MarshalException("Missing " + localName + " element");
+        }
+        String name = elem.getLocalName();
+        String namespace = elem.getNamespaceURI();
+        if (!name.equals(localName) || namespace == null && namespaceURI != null
+            || namespace != null && !namespace.equals(namespaceURI)) {
+            throw new MarshalException("Invalid element name: " +
+                namespace + ":" + name + ", expected " + namespaceURI + ":" + localName);
+        }
+        return elem;
+    }
+
     /**
      * Returns the last child element of the specified node, or null if there
      * is no such element.
@@ -168,7 +216,7 @@
      * @param node the node
      * @return the last child element of the specified node, or null if there
      *    is no such element
-     * @throws NullPointerException if <code>node == null</code>
+     * @throws NullPointerException if {@code node == null}
      */
     public static Element getLastChildElement(Node node) {
         Node child = node.getLastChild();
@@ -185,7 +233,7 @@
      * @param node the node
      * @return the next sibling element of the specified node, or null if there
      *    is no such element
-     * @throws NullPointerException if <code>node == null</code>
+     * @throws NullPointerException if {@code node == null}
      */
     public static Element getNextSiblingElement(Node node) {
         Node sibling = node.getNextSibling();
@@ -203,8 +251,9 @@
      * @return the next sibling element of the specified node
      * @throws NullPointerException if {@code node == null}
      * @throws MarshalException if no such element or the local name is not
-     *    equal to {@code localName}
+     * equal to {@code localName}
      */
+    @Deprecated
     public static Element getNextSiblingElement(Node node, String localName)
         throws MarshalException
     {
@@ -212,12 +261,29 @@
     }
 
     /**
+     * Returns the next sibling element of the specified node and checks that
+     * the local name is equal to {@code localName} and the namespace is equal to
+     * {@code namespaceURI}
+     *
+     * @param node the node
+     * @return the next sibling element of the specified node
+     * @throws NullPointerException if {@code node == null}
+     * @throws MarshalException if no such element or the local name is not
+     * equal to {@code localName}
+     */
+    public static Element getNextSiblingElement(Node node, String localName, String namespaceURI)
+        throws MarshalException
+    {
+        return verifyElement(getNextSiblingElement(node), localName, namespaceURI);
+    }
+
+    /**
      * Returns the attribute value for the attribute with the specified name.
      * Returns null if there is no such attribute, or
      * the empty string if the attribute value is empty.
      *
      * <p>This works around a limitation of the DOM
-     * <code>Element.getAttributeNode</code> method, which does not distinguish
+     * {@code Element.getAttributeNode} method, which does not distinguish
      * between an unspecified attribute and an attribute with a value of
      * "" (it returns "" for both cases).
      *
@@ -231,8 +297,30 @@
     }
 
     /**
-     * Returns a Set of <code>Node</code>s, backed by the specified
-     * <code>NodeList</code>.
+     * Returns the attribute value for the attribute with the specified name.
+     * Returns null if there is no such attribute, or
+     * the empty string if the attribute value is empty.
+     *
+     * <p>This works around a limitation of the DOM
+     * {@code Element.getAttributeNode} method, which does not distinguish
+     * between an unspecified attribute and an attribute with a value of
+     * "" (it returns "" for both cases).
+     *
+     * @param elem the element containing the attribute
+     * @param name the name of the attribute
+     * @return the attribute value (may be null if unspecified)
+     */
+    public static <N> String getIdAttributeValue(Element elem, String name) {
+        Attr attr = elem.getAttributeNodeNS(null, name);
+        if (attr != null && !attr.isId()) {
+            elem.setIdAttributeNode(attr, true);
+        }
+        return (attr == null) ? null : attr.getValue();
+    }
+
+    /**
+     * Returns a Set of {@code Node}s, backed by the specified
+     * {@code NodeList}.
      *
      * @param nl the NodeList
      * @return a Set of Nodes
@@ -247,22 +335,27 @@
             this.nl = nl;
         }
 
+        @Override
         public int size() { return nl.getLength(); }
+        @Override
         public Iterator<Node> iterator() {
             return new Iterator<Node>() {
-                int index = 0;
+                private int index;
 
+                @Override
                 public void remove() {
                     throw new UnsupportedOperationException();
                 }
+                @Override
                 public Node next() {
                     if (!hasNext()) {
                         throw new NoSuchElementException();
                     }
                     return nl.item(index++);
                 }
+                @Override
                 public boolean hasNext() {
-                    return index < nl.getLength() ? true : false;
+                    return index < nl.getLength();
                 }
             };
         }
@@ -302,9 +395,11 @@
      * @param node the parent node whose children are to be removed
      */
     public static void removeAllChildren(Node node) {
-        NodeList children = node.getChildNodes();
-        for (int i = 0, length = children.getLength(); i < length; i++) {
-            node.removeChild(children.item(i));
+        Node firstChild = node.getFirstChild();
+        while (firstChild != null) {
+            Node nodeToRemove = firstChild;
+            firstChild = firstChild.getNextSibling();
+            node.removeChild(nodeToRemove);
         }
     }
 
@@ -367,7 +462,9 @@
     private static boolean paramsEqual(XPathFilter2ParameterSpec spec1,
                                        XPathFilter2ParameterSpec spec2)
     {
+        @SuppressWarnings("unchecked")
         List<XPathType> types = spec1.getXPathList();
+        @SuppressWarnings("unchecked")
         List<XPathType> otypes = spec2.getXPathList();
         int size = types.size();
         if (size != otypes.size()) {
@@ -394,8 +491,8 @@
     private static boolean paramsEqual(XPathFilterParameterSpec spec1,
                                        XPathFilterParameterSpec spec2)
     {
-        return (spec1.getXPath().equals(spec2.getXPath()) &&
-                spec1.getNamespaceMap().equals(spec2.getNamespaceMap()));
+        return spec1.getXPath().equals(spec2.getXPath()) &&
+                spec1.getNamespaceMap().equals(spec2.getNamespaceMap());
     }
 
     private static boolean paramsEqual(XSLTTransformParameterSpec spec1,
@@ -413,4 +510,14 @@
             ((javax.xml.crypto.dom.DOMStructure) stylesheet).getNode();
         return nodesEqual(stylesheetElem, ostylesheetElem);
     }
+
+    public static boolean isNamespace(Node node)
+    {
+        final short nodeType = node.getNodeType();
+        if (nodeType == Node.ATTRIBUTE_NODE) {
+            final String namespaceURI = node.getNamespaceURI();
+            return XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI);
+        }
+        return false;
+    }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,37 +21,34 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMX509Data.java 1789702 2017-03-31 15:15:04Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import java.io.ByteArrayInputStream;
+import java.io.IOException;
 import java.security.cert.*;
 import java.util.*;
+
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
 import javax.xml.crypto.dsig.keyinfo.X509Data;
 import javax.security.auth.x500.X500Principal;
-import org.w3c.dom.Document;
+
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 
 /**
  * DOM-based implementation of X509Data.
  *
- * @author Sean Mullan
  */
 //@@@ check for illegal combinations of data violating MUSTs in W3c spec
-public final class DOMX509Data extends DOMStructure implements X509Data {
+public final class DOMX509Data extends BaseStructure implements X509Data {
 
     private final List<Object> content;
     private CertificateFactory cf;
@@ -60,21 +57,21 @@
      * Creates a DOMX509Data.
      *
      * @param content a list of one or more X.509 data types. Valid types are
-     *    {@link String} (subject names), <code>byte[]</code> (subject key ids),
+     *    {@link String} (subject names), {@code byte[]} (subject key ids),
      *    {@link java.security.cert.X509Certificate}, {@link X509CRL},
-     *    or {@link javax.xml.dsig.XMLStructure} ({@link X509IssuerSerial}
+     *    or {@link javax.xml.dsig.XMLStructure}
      *    objects or elements from an external namespace). The list is
      *    defensively copied to protect against subsequent modification.
-     * @throws NullPointerException if <code>content</code> is <code>null</code>
-     * @throws IllegalArgumentException if <code>content</code> is empty
-     * @throws ClassCastException if <code>content</code> contains any entries
+     * @throws NullPointerException if {@code content} is {@code null}
+     * @throws IllegalArgumentException if {@code content} is empty
+     * @throws ClassCastException if {@code content} contains any entries
      *    that are not of one of the valid types mentioned above
      */
     public DOMX509Data(List<?> content) {
         if (content == null) {
             throw new NullPointerException("content cannot be null");
         }
-        List<Object> contentCopy = new ArrayList<Object>(content);
+        List<Object> contentCopy = new ArrayList<>(content);
         if (contentCopy.isEmpty()) {
             throw new IllegalArgumentException("content cannot be empty");
         }
@@ -94,148 +91,123 @@
     }
 
     /**
-     * Creates a <code>DOMX509Data</code> from an element.
+     * Creates a {@code DOMX509Data} from an element.
      *
      * @param xdElem an X509Data element
      * @throws MarshalException if there is an error while unmarshalling
      */
     public DOMX509Data(Element xdElem) throws MarshalException {
         // get all children nodes
-        NodeList nl = xdElem.getChildNodes();
-        int length = nl.getLength();
-        List<Object> content = new ArrayList<Object>(length);
-        for (int i = 0; i < length; i++) {
-            Node child = nl.item(i);
-            // ignore all non-Element nodes
-            if (child.getNodeType() != Node.ELEMENT_NODE) {
-                continue;
+        List<Object> newContent = new ArrayList<>();
+        Node firstChild = xdElem.getFirstChild();
+        while (firstChild != null) {
+            if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                Element childElem = (Element)firstChild;
+                String localName = childElem.getLocalName();
+                String namespace = childElem.getNamespaceURI();
+                if ("X509Certificate".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(unmarshalX509Certificate(childElem));
+                } else if ("X509IssuerSerial".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(new DOMX509IssuerSerial(childElem));
+                } else if ("X509SubjectName".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(childElem.getFirstChild().getNodeValue());
+                } else if ("X509SKI".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    String content = XMLUtils.getFullTextChildrenFromElement(childElem);
+                    newContent.add(Base64.getMimeDecoder().decode(content));
+                } else if ("X509CRL".equals(localName) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(unmarshalX509CRL(childElem));
+                } else {
+                    newContent.add(new javax.xml.crypto.dom.DOMStructure(childElem));
+                }
             }
-
-            Element childElem = (Element)child;
-            String localName = childElem.getLocalName();
-            if (localName.equals("X509Certificate")) {
-                content.add(unmarshalX509Certificate(childElem));
-            } else if (localName.equals("X509IssuerSerial")) {
-                content.add(new DOMX509IssuerSerial(childElem));
-            } else if (localName.equals("X509SubjectName")) {
-                content.add(childElem.getFirstChild().getNodeValue());
-            } else if (localName.equals("X509SKI")) {
-                try {
-                    content.add(Base64.decode(childElem));
-                } catch (Base64DecodingException bde) {
-                    throw new MarshalException("cannot decode X509SKI", bde);
-                }
-            } else if (localName.equals("X509CRL")) {
-                content.add(unmarshalX509CRL(childElem));
-            } else {
-                content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
-            }
+            firstChild = firstChild.getNextSibling();
         }
-        this.content = Collections.unmodifiableList(content);
+        this.content = Collections.unmodifiableList(newContent);
     }
 
-    public List<?> getContent() {
+    @Override
+    public List<Object> getContent() {
         return content;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public static void marshal(XmlWriter xwriter, X509Data x509Data, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-        Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
-                                                XMLSignature.XMLNS, dsPrefix);
+        xwriter.writeStartElement(dsPrefix, "X509Data", XMLSignature.XMLNS);
 
+        List<?> content = x509Data.getContent();
         // append children and preserve order
         for (int i = 0, size = content.size(); i < size; i++) {
             Object object = content.get(i);
             if (object instanceof X509Certificate) {
-                marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
+                marshalCert(xwriter, (X509Certificate) object, dsPrefix);
             } else if (object instanceof XMLStructure) {
-                if (object instanceof X509IssuerSerial) {
-                    ((DOMX509IssuerSerial)object).marshal
-                        (xdElem, dsPrefix, context);
-                } else {
-                    javax.xml.crypto.dom.DOMStructure domContent =
-                        (javax.xml.crypto.dom.DOMStructure)object;
-                    DOMUtils.appendChild(xdElem, domContent.getNode());
-                }
+                xwriter.marshalStructure((XMLStructure) object, dsPrefix, context);
             } else if (object instanceof byte[]) {
-                marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
+                marshalSKI(xwriter, (byte[]) object, dsPrefix);
             } else if (object instanceof String) {
-                marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
+                marshalSubjectName(xwriter, (String) object, dsPrefix);
             } else if (object instanceof X509CRL) {
-                marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
+                marshalCRL(xwriter, (X509CRL) object, dsPrefix);
             }
         }
-
-        parent.appendChild(xdElem);
+        xwriter.writeEndElement(); // "X509Data"
     }
 
-    private void marshalSKI(byte[] skid, Node parent, Document doc,
-                            String dsPrefix)
+    private static void marshalSKI(XmlWriter xwriter, byte[] skid, String dsPrefix)
     {
-        Element skidElem = DOMUtils.createElement(doc, "X509SKI",
-                                                  XMLSignature.XMLNS, dsPrefix);
-        skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
-        parent.appendChild(skidElem);
+        xwriter.writeTextElement(dsPrefix, "X509SKI", XMLSignature.XMLNS,
+                                 Base64.getMimeEncoder().encodeToString(skid));
     }
 
-    private void marshalSubjectName(String name, Node parent, Document doc,
-                                    String dsPrefix)
+    private static void marshalSubjectName(XmlWriter xwriter, String name, String dsPrefix)
     {
-        Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
-                                                XMLSignature.XMLNS, dsPrefix);
-        snElem.appendChild(doc.createTextNode(name));
-        parent.appendChild(snElem);
+        xwriter.writeTextElement(dsPrefix, "X509SubjectName", XMLSignature.XMLNS, name);
     }
 
-    private void marshalCert(X509Certificate cert, Node parent, Document doc,
-                             String dsPrefix)
+    private static void marshalCert(XmlWriter xwriter, X509Certificate cert, String dsPrefix)
         throws MarshalException
     {
-        Element certElem = DOMUtils.createElement(doc, "X509Certificate",
-                                                  XMLSignature.XMLNS, dsPrefix);
         try {
-            certElem.appendChild(doc.createTextNode
-                                 (Base64.encode(cert.getEncoded())));
+            byte[] encoded = cert.getEncoded();
+            xwriter.writeTextElement(dsPrefix, "X509Certificate", XMLSignature.XMLNS,
+                                     Base64.getMimeEncoder().encodeToString(encoded));
         } catch (CertificateEncodingException e) {
             throw new MarshalException("Error encoding X509Certificate", e);
         }
-        parent.appendChild(certElem);
     }
 
-    private void marshalCRL(X509CRL crl, Node parent, Document doc,
-                            String dsPrefix)
+    private static void marshalCRL(XmlWriter xwriter, X509CRL crl, String dsPrefix)
         throws MarshalException
     {
-        Element crlElem = DOMUtils.createElement(doc, "X509CRL",
-                                                 XMLSignature.XMLNS, dsPrefix);
         try {
-            crlElem.appendChild(doc.createTextNode
-                                (Base64.encode(crl.getEncoded())));
+            byte[] encoded = crl.getEncoded();
+            xwriter.writeTextElement(dsPrefix, "X509CRL", XMLSignature.XMLNS,
+                                     Base64.getMimeEncoder().encodeToString(encoded));
         } catch (CRLException e) {
             throw new MarshalException("Error encoding X509CRL", e);
         }
-        parent.appendChild(crlElem);
     }
 
     private X509Certificate unmarshalX509Certificate(Element elem)
         throws MarshalException
     {
-        try {
-            ByteArrayInputStream bs = unmarshalBase64Binary(elem);
+        try (ByteArrayInputStream bs = unmarshalBase64Binary(elem)) {
             return (X509Certificate)cf.generateCertificate(bs);
         } catch (CertificateException e) {
             throw new MarshalException("Cannot create X509Certificate", e);
+        } catch (IOException e) {
+            throw new MarshalException("Error closing stream", e);
         }
     }
 
     private X509CRL unmarshalX509CRL(Element elem) throws MarshalException {
-        try {
-            ByteArrayInputStream bs = unmarshalBase64Binary(elem);
+        try (ByteArrayInputStream bs = unmarshalBase64Binary(elem)) {
             return (X509CRL)cf.generateCRL(bs);
         } catch (CRLException e) {
             throw new MarshalException("Cannot create X509CRL", e);
+        } catch (IOException e) {
+            throw new MarshalException("Error closing stream", e);
         }
     }
 
@@ -245,11 +217,10 @@
             if (cf == null) {
                 cf = CertificateFactory.getInstance("X.509");
             }
-            return new ByteArrayInputStream(Base64.decode(elem));
+            String content = XMLUtils.getFullTextChildrenFromElement(elem);
+            return new ByteArrayInputStream(Base64.getMimeDecoder().decode(content));
         } catch (CertificateException e) {
             throw new MarshalException("Cannot create CertificateFactory", e);
-        } catch (Base64DecodingException bde) {
-            throw new MarshalException("Cannot decode Base64-encoded val", bde);
         }
     }
 
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,46 +21,44 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMX509IssuerSerial.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMX509IssuerSerial.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
-import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.*;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.dsig.XMLSignature;
 import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
 
 import java.math.BigInteger;
+
 import javax.security.auth.x500.X500Principal;
-import org.w3c.dom.Document;
+
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
 
 /**
  * DOM-based implementation of X509IssuerSerial.
  *
- * @author Sean Mullan
  */
-public final class DOMX509IssuerSerial extends DOMStructure
+public final class DOMX509IssuerSerial extends BaseStructure
     implements X509IssuerSerial {
 
     private final String issuerName;
     private final BigInteger serialNumber;
 
     /**
-     * Creates a <code>DOMX509IssuerSerial</code> containing the specified
+     * Creates a {@code DOMX509IssuerSerial} containing the specified
      * issuer distinguished name/serial number pair.
      *
      * @param issuerName the X.509 issuer distinguished name in RFC 2253
      *    String format
      * @param serialNumber the serial number
-     * @throws IllegalArgumentException if the format of <code>issuerName</code>
+     * @throws IllegalArgumentException if the format of {@code issuerName}
      *    is not RFC 2253 compliant
-     * @throws NullPointerException if <code>issuerName</code> or
-     *    <code>serialNumber</code> is <code>null</code>
+     * @throws NullPointerException if {@code issuerName} or
+     *    {@code serialNumber} is {@code null}
      */
     public DOMX509IssuerSerial(String issuerName, BigInteger serialNumber) {
         if (issuerName == null) {
@@ -76,45 +74,31 @@
     }
 
     /**
-     * Creates a <code>DOMX509IssuerSerial</code> from an element.
+     * Creates a {@code DOMX509IssuerSerial} from an element.
      *
      * @param isElem an X509IssuerSerial element
      */
     public DOMX509IssuerSerial(Element isElem) throws MarshalException {
         Element iNElem = DOMUtils.getFirstChildElement(isElem,
-                                                       "X509IssuerName");
+                                                       "X509IssuerName",
+                                                       XMLSignature.XMLNS);
         Element sNElem = DOMUtils.getNextSiblingElement(iNElem,
-                                                        "X509SerialNumber");
+                                                        "X509SerialNumber",
+                                                        XMLSignature.XMLNS);
         issuerName = iNElem.getFirstChild().getNodeValue();
         serialNumber = new BigInteger(sNElem.getFirstChild().getNodeValue());
     }
 
+    @Override
     public String getIssuerName() {
         return issuerName;
     }
 
+    @Override
     public BigInteger getSerialNumber() {
         return serialNumber;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
-        Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial",
-                                                XMLSignature.XMLNS, dsPrefix);
-        Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName",
-                                                XMLSignature.XMLNS, dsPrefix);
-        Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber",
-                                                XMLSignature.XMLNS, dsPrefix);
-        inElem.appendChild(ownerDoc.createTextNode(issuerName));
-        snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString()));
-        isElem.appendChild(inElem);
-        isElem.appendChild(snElem);
-        parent.appendChild(isElem);
-    }
-
     @Override
     public boolean equals(Object obj) {
         if (this == obj) {
@@ -124,8 +108,8 @@
             return false;
         }
         X509IssuerSerial ois = (X509IssuerSerial)obj;
-        return (issuerName.equals(ois.getIssuerName()) &&
-                serialNumber.equals(ois.getSerialNumber()));
+        return issuerName.equals(ois.getIssuerName()) &&
+                serialNumber.equals(ois.getSerialNumber());
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,68 +21,69 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMXMLObject.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.DOMCryptoContext;
 import javax.xml.crypto.dsig.*;
 
 import java.security.Provider;
 import java.util.*;
 
 import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * DOM-based implementation of XMLObject.
  *
- * @author Sean Mullan
  */
-public final class DOMXMLObject extends DOMStructure implements XMLObject {
+public final class DOMXMLObject extends BaseStructure implements XMLObject {
 
     private final String id;
     private final String mimeType;
     private final String encoding;
     private final List<XMLStructure> content;
-    private Element objectElem;
 
     /**
-     * Creates an <code>XMLObject</code> from the specified parameters.
+     * Creates an {@code XMLObject} from the specified parameters.
      *
      * @param content a list of {@link XMLStructure}s. The list
      *    is defensively copied to protect against subsequent modification.
-     *    May be <code>null</code> or empty.
-     * @param id the Id (may be <code>null</code>)
-     * @param mimeType the mime type (may be <code>null</code>)
-     * @param encoding the encoding (may be <code>null</code>)
-     * @throws ClassCastException if <code>content</code> contains any
+     *    May be {@code null} or empty.
+     * @param id the Id (may be {@code null})
+     * @param mimeType the mime type (may be {@code null})
+     * @param encoding the encoding (may be {@code null})
+     * @throws ClassCastException if {@code content} contains any
      *    entries that are not of type {@link XMLStructure}
      */
     public DOMXMLObject(List<? extends XMLStructure> content, String id,
                         String mimeType, String encoding)
     {
-        List<XMLStructure> tempList =
-            Collections.checkedList(new ArrayList<XMLStructure>(),
-                                    XMLStructure.class);
-        if (content != null) {
-            tempList.addAll(content);
+        if (content == null || content.isEmpty()) {
+            this.content = Collections.emptyList();
+        } else {
+            this.content = Collections.unmodifiableList(
+                new ArrayList<>(content));
+            for (int i = 0, size = this.content.size(); i < size; i++) {
+                if (!(this.content.get(i) instanceof XMLStructure)) {
+                    throw new ClassCastException
+                        ("content["+i+"] is not a valid type");
+                }
+            }
         }
-        this.content = Collections.unmodifiableList(tempList);
         this.id = id;
         this.mimeType = mimeType;
         this.encoding = encoding;
     }
 
     /**
-     * Creates an <code>XMLObject</code> from an element.
+     * Creates an {@code XMLObject} from an element.
      *
      * @param objElem an Object element
      * @throws MarshalException if there is an error when unmarshalling
@@ -103,79 +104,87 @@
         }
         this.mimeType = DOMUtils.getAttributeValue(objElem, "MimeType");
 
-        NodeList nodes = objElem.getChildNodes();
-        int length = nodes.getLength();
-        List<XMLStructure> content = new ArrayList<XMLStructure>(length);
-        for (int i = 0; i < length; i++) {
-            Node child = nodes.item(i);
-            if (child.getNodeType() == Node.ELEMENT_NODE) {
-                Element childElem = (Element)child;
+        List<XMLStructure> newContent = new ArrayList<>();
+        Node firstChild = objElem.getFirstChild();
+        while (firstChild != null) {
+            if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+                Element childElem = (Element)firstChild;
                 String tag = childElem.getLocalName();
-                if (tag.equals("Manifest")) {
-                    content.add(new DOMManifest(childElem, context, provider));
-                    continue;
-                } else if (tag.equals("SignatureProperties")) {
-                    content.add(new DOMSignatureProperties(childElem, context));
-                    continue;
-                } else if (tag.equals("X509Data")) {
-                    content.add(new DOMX509Data(childElem));
-                    continue;
+                String namespace = childElem.getNamespaceURI();
+                if ("Manifest".equals(tag) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(new DOMManifest(childElem, context, provider));
+                } else if ("SignatureProperties".equals(tag) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(new DOMSignatureProperties(childElem));
+                } else if ("X509Data".equals(tag) && XMLSignature.XMLNS.equals(namespace)) {
+                    newContent.add(new DOMX509Data(childElem));
+                } else {
+                    //@@@FIXME: check for other dsig structures
+                    newContent.add(new javax.xml.crypto.dom.DOMStructure(firstChild));
                 }
-                //@@@FIXME: check for other dsig structures
+            } else {
+                newContent.add(new javax.xml.crypto.dom.DOMStructure(firstChild));
             }
-            content.add(new javax.xml.crypto.dom.DOMStructure(child));
+            firstChild = firstChild.getNextSibling();
         }
-        if (content.isEmpty()) {
+
+        // Here we capture namespace declarations, so that when they're marshalled back
+        // out, we can make copies of them. Note that attributes are NOT captured.
+        NamedNodeMap nnm = objElem.getAttributes();
+        for (int idx = 0 ; idx < nnm.getLength() ; idx++) {
+            Node nsDecl = nnm.item(idx);
+            if (DOMUtils.isNamespace(nsDecl)) {
+                newContent.add(new javax.xml.crypto.dom.DOMStructure(nsDecl));
+            }
+        }
+
+        if (newContent.isEmpty()) {
             this.content = Collections.emptyList();
         } else {
-            this.content = Collections.unmodifiableList(content);
+            this.content = Collections.unmodifiableList(newContent);
         }
-        this.objectElem = objElem;
     }
 
+    @Override
     public List<XMLStructure> getContent() {
         return content;
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public String getMimeType() {
         return mimeType;
     }
 
+    @Override
     public String getEncoding() {
         return encoding;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
+    public static void marshal(XmlWriter xwriter, XMLObject xmlObj, String dsPrefix, XMLCryptoContext context)
         throws MarshalException {
-        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
+        xwriter.writeStartElement(dsPrefix, "Object", XMLSignature.XMLNS);
 
-        Element objElem = objectElem != null ? objectElem : null;
-        if (objElem == null) {
-            objElem = DOMUtils.createElement(ownerDoc, "Object",
-                                             XMLSignature.XMLNS, dsPrefix);
-
-            // set attributes
-            DOMUtils.setAttributeID(objElem, "Id", id);
-            DOMUtils.setAttribute(objElem, "MimeType", mimeType);
-            DOMUtils.setAttribute(objElem, "Encoding", encoding);
+        // set attributes
+        xwriter.writeIdAttribute("", "", "Id", xmlObj.getId());
+        xwriter.writeAttribute("", "", "MimeType", xmlObj.getMimeType());
+        xwriter.writeAttribute("", "", "Encoding", xmlObj.getEncoding());
 
-            // create and append any elements and mixed content, if necessary
-            for (XMLStructure object : content) {
-                if (object instanceof DOMStructure) {
-                    ((DOMStructure)object).marshal(objElem, dsPrefix, context);
-                } else {
-                    javax.xml.crypto.dom.DOMStructure domObject =
-                        (javax.xml.crypto.dom.DOMStructure)object;
-                    DOMUtils.appendChild(objElem, domObject.getNode());
-                }
-            }
+        // create and append any elements and mixed content, if necessary
+        @SuppressWarnings("unchecked")
+        List<XMLStructure> content = xmlObj.getContent();
+        for (XMLStructure object : content) {
+            xwriter.marshalStructure(object, dsPrefix, context);
         }
+        xwriter.writeEndElement(); // "Object"
+    }
 
-        parent.appendChild(objElem);
+    @SuppressWarnings("unchecked")
+    public static List<XMLStructure> getXmlObjectContent(XMLObject xo) {
+        return xo.getContent();
     }
 
     @Override
@@ -189,18 +198,17 @@
         }
         XMLObject oxo = (XMLObject)o;
 
-        boolean idsEqual = (id == null ? oxo.getId() == null
-                                       : id.equals(oxo.getId()));
+        boolean idsEqual = id == null ? oxo.getId() == null
+                                       : id.equals(oxo.getId());
         boolean encodingsEqual =
-            (encoding == null ? oxo.getEncoding() == null
-                              : encoding.equals(oxo.getEncoding()));
+            encoding == null ? oxo.getEncoding() == null
+                              : encoding.equals(oxo.getEncoding());
         boolean mimeTypesEqual =
-            (mimeType == null ? oxo.getMimeType() == null
-                              : mimeType.equals(oxo.getMimeType()));
+            mimeType == null ? oxo.getMimeType() == null
+                              : mimeType.equals(oxo.getMimeType());
 
-        List<XMLStructure> oxoContent = oxo.getContent();
-        return (idsEqual && encodingsEqual && mimeTypesEqual &&
-                equalsContent(oxoContent));
+        return idsEqual && encodingsEqual && mimeTypesEqual &&
+                equalsContent(getXmlObjectContent(oxo));
     }
 
     @Override
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Portions copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * ===========================================================================
@@ -31,12 +31,11 @@
  * ===========================================================================
  */
 /*
- * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $
+ * $Id: DOMXMLSignature.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
 import javax.xml.crypto.*;
-import javax.xml.crypto.dom.*;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.dom.DOMSignContext;
 import javax.xml.crypto.dsig.dom.DOMValidateContext;
@@ -47,57 +46,51 @@
 import java.security.Provider;
 import java.util.Collections;
 import java.util.ArrayList;
+import java.util.Base64;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 
 /**
  * DOM-based implementation of XMLSignature.
  *
- * @author Sean Mullan
- * @author Joyce Leung
  */
 public final class DOMXMLSignature extends DOMStructure
     implements XMLSignature {
 
-    private static java.util.logging.Logger log =
-        java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+    private static final com.sun.org.slf4j.internal.Logger LOG =
+        com.sun.org.slf4j.internal.LoggerFactory.getLogger(DOMXMLSignature.class);
     private String id;
     private SignatureValue sv;
     private KeyInfo ki;
     private List<XMLObject> objects;
     private SignedInfo si;
-    private Document ownerDoc = null;
-    private Element localSigElem = null;
-    private Element sigElem = null;
     private boolean validationStatus;
     private boolean validated = false;
     private KeySelectorResult ksr;
-    private HashMap<String, XMLStructure> signatureIdMap;
+    private Map<String, XMLStructure> signatureIdMap;
 
     static {
         com.sun.org.apache.xml.internal.security.Init.init();
     }
 
     /**
-     * Creates a <code>DOMXMLSignature</code> from the specified components.
+     * Creates a {@code DOMXMLSignature} from the specified components.
      *
-     * @param si the <code>SignedInfo</code>
-     * @param ki the <code>KeyInfo</code>, or <code>null</code> if not specified
-     * @param objs a list of <code>XMLObject</code>s or <code>null</code>
+     * @param si the {@code SignedInfo}
+     * @param ki the {@code KeyInfo}, or {@code null} if not specified
+     * @param objs a list of {@code XMLObject}s or {@code null}
      *  if not specified. The list is copied to protect against subsequent
      *  modification.
-     * @param id an optional id (specify <code>null</code> to omit)
-     * @param signatureValueId an optional id (specify <code>null</code> to
+     * @param id an optional id (specify {@code null} to omit)
+     * @param signatureValueId an optional id (specify {@code null} to
      *  omit)
-     * @throws NullPointerException if <code>si</code> is <code>null</code>
+     * @throws NullPointerException if {@code si} is {@code null}
      */
     public DOMXMLSignature(SignedInfo si, KeyInfo ki,
                            List<? extends XMLObject> objs,
@@ -109,18 +102,23 @@
         this.si = si;
         this.id = id;
         this.sv = new DOMSignatureValue(signatureValueId);
-        List<XMLObject> tempList =
-            Collections.checkedList(new ArrayList<XMLObject>(),
-                                    XMLObject.class);
-        if (objs != null) {
-            tempList.addAll(objs);
+        if (objs == null) {
+            this.objects = Collections.emptyList();
+        } else {
+            this.objects =
+                Collections.unmodifiableList(new ArrayList<>(objs));
+            for (int i = 0, size = this.objects.size(); i < size; i++) {
+                if (!(this.objects.get(i) instanceof XMLObject)) {
+                    throw new ClassCastException
+                        ("objs["+i+"] is not an XMLObject");
+                }
+            }
         }
-        this.objects = Collections.unmodifiableList(tempList);
         this.ki = ki;
     }
 
     /**
-     * Creates a <code>DOMXMLSignature</code> from XML.
+     * Creates a {@code DOMXMLSignature} from XML.
      *
      * @param sigElem Signature element
      * @throws MarshalException if XMLSignature cannot be unmarshalled
@@ -129,25 +127,26 @@
                            Provider provider)
         throws MarshalException
     {
-        localSigElem = sigElem;
-        ownerDoc = localSigElem.getOwnerDocument();
+        Element localSigElem = sigElem;
 
         // get Id attribute, if specified
         id = DOMUtils.getAttributeValue(localSigElem, "Id");
-
         // unmarshal SignedInfo
         Element siElem = DOMUtils.getFirstChildElement(localSigElem,
-                                                       "SignedInfo");
+                                                       "SignedInfo",
+                                                       XMLSignature.XMLNS);
         si = new DOMSignedInfo(siElem, context, provider);
 
         // unmarshal SignatureValue
         Element sigValElem = DOMUtils.getNextSiblingElement(siElem,
-                                                            "SignatureValue");
-        sv = new DOMSignatureValue(sigValElem, context);
+                                                            "SignatureValue",
+                                                            XMLSignature.XMLNS);
+        sv = new DOMSignatureValue(sigValElem);
 
         // unmarshal KeyInfo, if specified
         Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem);
-        if (nextSibling != null && nextSibling.getLocalName().equals("KeyInfo")) {
+        if (nextSibling != null && nextSibling.getLocalName().equals("KeyInfo")
+            && XMLSignature.XMLNS.equals(nextSibling.getNamespaceURI())) {
             ki = new DOMKeyInfo(nextSibling, context, provider);
             nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
         }
@@ -156,11 +155,12 @@
         if (nextSibling == null) {
             objects = Collections.emptyList();
         } else {
-            List<XMLObject> tempObjects = new ArrayList<XMLObject>();
+            List<XMLObject> tempObjects = new ArrayList<>();
             while (nextSibling != null) {
                 String name = nextSibling.getLocalName();
-                if (!name.equals("Object")) {
-                    throw new MarshalException("Invalid element name: " + name +
+                String namespace = nextSibling.getNamespaceURI();
+                if (!"Object".equals(name) || !XMLSignature.XMLNS.equals(namespace)) {
+                    throw new MarshalException("Invalid element name: " + namespace + ":" + name +
                                                ", expected KeyInfo or Object");
                 }
                 tempObjects.add(new DOMXMLObject(nextSibling,
@@ -171,75 +171,72 @@
         }
     }
 
+    @Override
     public String getId() {
         return id;
     }
 
+    @Override
     public KeyInfo getKeyInfo() {
         return ki;
     }
 
+    @Override
     public SignedInfo getSignedInfo() {
         return si;
     }
 
+    @Override
     public List<XMLObject> getObjects() {
         return objects;
     }
 
+    @Override
     public SignatureValue getSignatureValue() {
         return sv;
     }
 
+    @Override
     public KeySelectorResult getKeySelectorResult() {
         return ksr;
     }
 
-    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
-        throws MarshalException
-    {
-        marshal(parent, null, dsPrefix, context);
-    }
-
-    public void marshal(Node parent, Node nextSibling, String dsPrefix,
-                        DOMCryptoContext context)
+    @Override
+    public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context)
         throws MarshalException
     {
-        ownerDoc = DOMUtils.getOwnerDocument(parent);
-        sigElem = DOMUtils.createElement(ownerDoc, "Signature",
-                                         XMLSignature.XMLNS, dsPrefix);
+        // rationalize the prefix.
+        String prefix = dsPrefix;
+        if (prefix == null) {
+            prefix = "";
+        }
+        xwriter.writeStartElement(prefix, "Signature", XMLSignature.XMLNS);
 
-        // append xmlns attribute
-        if (dsPrefix == null || dsPrefix.length() == 0) {
-            sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
-                                   XMLSignature.XMLNS);
-        } else {
-            sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
-                                   dsPrefix, XMLSignature.XMLNS);
-        }
+        xwriter.writeNamespace(prefix, XMLSignature.XMLNS);
+
+        // append Id attribute
+        xwriter.writeIdAttribute("", "", "Id", id);
 
         // create and append SignedInfo element
-        ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context);
+        ((DOMSignedInfo) si).marshal(xwriter, prefix, context);
 
         // create and append SignatureValue element
-        ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context);
+        ((DOMSignatureValue) sv).marshal(xwriter, prefix, context);
 
         // create and append KeyInfo element if necessary
         if (ki != null) {
-            ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context);
+            DOMKeyInfo.marshal(xwriter, ki, prefix, context);
         }
 
         // create and append Object elements if necessary
-        for (int i = 0, size = objects.size(); i < size; i++) {
-            ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context);
+        for (XMLObject xmlObj : objects) {
+            DOMXMLObject.marshal(xwriter, xmlObj, prefix, context);
         }
 
-        // append Id attribute
-        DOMUtils.setAttributeID(sigElem, "Id", id);
-
-        parent.insertBefore(sigElem, nextSibling);
+        xwriter.writeEndElement(); // "Signature"
     }
 
+    @Override
     public boolean validate(XMLValidateContext vc)
         throws XMLSignatureException
     {
@@ -265,20 +262,16 @@
         }
 
         // validate all References
-        List<Reference> refs = this.si.getReferences();
+        List<Reference> refs = DOMSignedInfo.getSignedInfoReferences(this.si);
         boolean validateRefs = true;
         for (int i = 0, size = refs.size(); validateRefs && i < size; i++) {
             Reference ref = refs.get(i);
             boolean refValid = ref.validate(vc);
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid);
-            }
+            LOG.debug("Reference [{}] is valid: {}", ref.getURI(), refValid);
             validateRefs &= refValid;
         }
         if (!validateRefs) {
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "Couldn't validate the References");
-            }
+            LOG.debug("Couldn't validate the References");
             validationStatus = false;
             validated = true;
             return validationStatus;
@@ -291,25 +284,21 @@
         {
             for (int i=0, size=objects.size(); validateMans && i < size; i++) {
                 XMLObject xo = objects.get(i);
-                List<XMLStructure> content = xo.getContent();
+                List<XMLStructure> content = DOMXMLObject.getXmlObjectContent(xo);
                 int csize = content.size();
                 for (int j = 0; validateMans && j < csize; j++) {
                     XMLStructure xs = content.get(j);
                     if (xs instanceof Manifest) {
-                        if (log.isLoggable(java.util.logging.Level.FINE)) {
-                            log.log(java.util.logging.Level.FINE, "validating manifest");
-                        }
+                        LOG.debug("validating manifest");
                         Manifest man = (Manifest)xs;
-                        List<Reference> manRefs = man.getReferences();
+                        List<Reference> manRefs = DOMManifest.getManifestReferences(man);
                         int rsize = manRefs.size();
                         for (int k = 0; validateMans && k < rsize; k++) {
                             Reference ref = manRefs.get(k);
                             boolean refValid = ref.validate(vc);
-                            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                                log.log(java.util.logging.Level.FINE,
-                                    "Manifest ref[" + ref.getURI() + "] is valid: " + refValid
-                                );
-                            }
+                            LOG.debug(
+                                "Manifest ref [{}] is valid: {}", ref.getURI(),  refValid
+                            );
                             validateMans &= refValid;
                         }
                     }
@@ -322,6 +311,7 @@
         return validationStatus;
     }
 
+    @Override
     public void sign(XMLSignContext signContext)
         throws MarshalException, XMLSignatureException
     {
@@ -329,29 +319,34 @@
             throw new NullPointerException("signContext cannot be null");
         }
         DOMSignContext context = (DOMSignContext)signContext;
-        marshal(context.getParent(), context.getNextSibling(),
-                DOMUtils.getSignaturePrefix(context), context);
+        Node nextSibling = context.getNextSibling();
+
+        XmlWriterToTree xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), context.getParent(), nextSibling);
+        marshal(xwriter,
+            DOMUtils.getSignaturePrefix(signContext), signContext);
+
+        Element sigElem = xwriter.getCreatedElement();
 
         // generate references and signature value
-        List<Reference> allReferences = new ArrayList<Reference>();
+        List<Reference> allReferences = new ArrayList<>();
 
         // traverse the Signature and register all objects with IDs that
         // may contain References
-        signatureIdMap = new HashMap<String, XMLStructure>();
+        signatureIdMap = new HashMap<>();
         signatureIdMap.put(id, this);
         signatureIdMap.put(si.getId(), si);
-        List<Reference> refs = si.getReferences();
+        List<Reference> refs = DOMSignedInfo.getSignedInfoReferences(si);
         for (Reference ref : refs) {
             signatureIdMap.put(ref.getId(), ref);
         }
         for (XMLObject obj : objects) {
             signatureIdMap.put(obj.getId(), obj);
-            List<XMLStructure> content = obj.getContent();
+            List<XMLStructure> content = DOMXMLObject.getXmlObjectContent(obj);
             for (XMLStructure xs : content) {
                 if (xs instanceof Manifest) {
                     Manifest man = (Manifest)xs;
                     signatureIdMap.put(man.getId(), man);
-                    List<Reference> manRefs = man.getReferences();
+                    List<Reference> manRefs = DOMManifest.getManifestReferences(man);
                     for (Reference ref : manRefs) {
                         allReferences.add(ref);
                         signatureIdMap.put(ref.getId(), ref);
@@ -377,32 +372,31 @@
         }
 
         Key signingKey = null;
-        KeySelectorResult ksr = null;
         try {
-            ksr = signContext.getKeySelector().select(ki,
+            KeySelectorResult keySelectorResult = signContext.getKeySelector().select(ki,
                                                       KeySelector.Purpose.SIGN,
                                                       si.getSignatureMethod(),
                                                       signContext);
-            signingKey = ksr.getKey();
+            signingKey = keySelectorResult.getKey();
             if (signingKey == null) {
                 throw new XMLSignatureException("the keySelector did not " +
                                                 "find a signing key");
             }
+            ksr = keySelectorResult;
         } catch (KeySelectorException kse) {
             throw new XMLSignatureException("cannot find signing key", kse);
         }
 
         // calculate signature value
         try {
+            Element sigValue = (Element) sigElem.getElementsByTagNameNS(XMLSignature.XMLNS, "SignatureValue").item(0);
+            xwriter.resetToNewParent(sigValue);
             byte[] val = ((AbstractDOMSignatureMethod)
-                si.getSignatureMethod()).sign(signingKey, si, signContext);
-            ((DOMSignatureValue)sv).setValue(val);
+                si.getSignatureMethod()).sign(signingKey, (DOMSignedInfo) si, signContext);
+            ((DOMSignatureValue)sv).setValue(xwriter, val);
         } catch (InvalidKeyException ike) {
             throw new XMLSignatureException(ike);
         }
-
-        this.localSigElem = sigElem;
-        this.ksr = ksr;
     }
 
     @Override
@@ -417,15 +411,15 @@
         XMLSignature osig = (XMLSignature)o;
 
         boolean idEqual =
-            (id == null ? osig.getId() == null : id.equals(osig.getId()));
+            id == null ? osig.getId() == null : id.equals(osig.getId());
         boolean keyInfoEqual =
-            (ki == null ? osig.getKeyInfo() == null
-                        : ki.equals(osig.getKeyInfo()));
+            ki == null ? osig.getKeyInfo() == null
+                        : ki.equals(osig.getKeyInfo());
 
-        return (idEqual && keyInfoEqual &&
+        return idEqual && keyInfoEqual &&
                 sv.equals(osig.getSignatureValue()) &&
                 si.equals(osig.getSignedInfo()) &&
-                objects.equals(osig.getObjects()));
+                objects.equals(osig.getObjects());
     }
 
     @Override
@@ -453,15 +447,14 @@
         // check dependencies
         String uri = ref.getURI();
         if (Utils.sameDocumentURI(uri)) {
-            String id = Utils.parseIdFromSameDocumentURI(uri);
-            if (id != null && signatureIdMap.containsKey(id)) {
-                XMLStructure xs = signatureIdMap.get(id);
+            String parsedId = Utils.parseIdFromSameDocumentURI(uri);
+            if (parsedId != null && signatureIdMap.containsKey(parsedId)) {
+                XMLStructure xs = signatureIdMap.get(parsedId);
                 if (xs instanceof DOMReference) {
                     digestReference((DOMReference)xs, signContext);
                 } else if (xs instanceof Manifest) {
                     Manifest man = (Manifest)xs;
-                    List<Reference> manRefs =
-                        DOMManifest.getManifestReferences(man);
+                    List<Reference> manRefs = DOMManifest.getManifestReferences(man);
                     for (int i = 0, size = manRefs.size(); i < size; i++) {
                         digestReference((DOMReference)manRefs.get(i),
                                         signContext);
@@ -491,7 +484,6 @@
         private String id;
         private byte[] value;
         private String valueBase64;
-        private Element sigValueElem;
         private boolean validated = false;
         private boolean validationStatus;
 
@@ -499,34 +491,31 @@
             this.id = id;
         }
 
-        DOMSignatureValue(Element sigValueElem, XMLCryptoContext context)
+        DOMSignatureValue(Element sigValueElem)
             throws MarshalException
         {
-            try {
-                // base64 decode signatureValue
-                value = Base64.decode(sigValueElem);
-            } catch (Base64DecodingException bde) {
-                throw new MarshalException(bde);
-            }
+            // base64 decode signatureValue
+            String content = XMLUtils.getFullTextChildrenFromElement(sigValueElem);
+            value = Base64.getMimeDecoder().decode(content);
 
-            Attr attr = sigValueElem.getAttributeNodeNS(null, "Id");
-            if (attr != null) {
-                id = attr.getValue();
-                sigValueElem.setIdAttributeNode(attr, true);
-            } else {
-                id = null;
-            }
-            this.sigValueElem = sigValueElem;
+            id = DOMUtils.getIdAttributeValue(sigValueElem, "Id");
         }
 
+        @Override
         public String getId() {
             return id;
         }
 
+        @Override
         public byte[] getValue() {
             return (value == null) ? null : value.clone();
         }
 
+        public String getEncodedValue() {
+            return valueBase64;
+        }
+
+        @Override
         public boolean validate(XMLValidateContext validateContext)
             throws XMLSignatureException
         {
@@ -541,11 +530,16 @@
             // get validating key
             SignatureMethod sm = si.getSignatureMethod();
             Key validationKey = null;
-            KeySelectorResult ksResult;
+            KeySelectorResult ksResult = null;
             try {
-                ksResult = validateContext.getKeySelector().select
-                    (ki, KeySelector.Purpose.VERIFY, sm, validateContext);
-                validationKey = ksResult.getKey();
+                KeySelector keySelector = validateContext.getKeySelector();
+                if (keySelector != null) {
+                    ksResult = keySelector.select
+                        (ki, KeySelector.Purpose.VERIFY, sm, validateContext);
+                    if (ksResult != null) {
+                        validationKey = ksResult.getKey();
+                    }
+                }
                 if (validationKey == null) {
                     throw new XMLSignatureException("the keyselector did not " +
                                                     "find a validation key");
@@ -558,7 +552,7 @@
             // canonicalize SignedInfo and verify signature
             try {
                 validationStatus = ((AbstractDOMSignatureMethod)sm).verify
-                    (validationKey, si, value, validateContext);
+                    (validationKey, (DOMSignedInfo) si, value, validateContext);
             } catch (Exception e) {
                 throw new XMLSignatureException(e);
             }
@@ -580,7 +574,7 @@
             SignatureValue osv = (SignatureValue)o;
 
             boolean idEqual =
-                (id == null ? osv.getId() == null : id.equals(osv.getId()));
+                id == null ? osv.getId() == null : id.equals(osv.getId());
 
             //XXX compare signature values?
             return idEqual;
@@ -596,26 +590,29 @@
             return result;
         }
 
-        public void marshal(Node parent, String dsPrefix,
-                            DOMCryptoContext context)
+        @Override
+        public void marshal(XmlWriter xwriter, String dsPrefix,
+                XMLCryptoContext context)
             throws MarshalException
         {
             // create SignatureValue element
-            sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue",
-                                                  XMLSignature.XMLNS, dsPrefix);
-            if (valueBase64 != null) {
-                sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64));
-            }
+            xwriter.writeStartElement(dsPrefix, "SignatureValue", XMLSignature.XMLNS);
 
             // append Id attribute, if specified
-            DOMUtils.setAttributeID(sigValueElem, "Id", id);
-            parent.appendChild(sigValueElem);
+            xwriter.writeIdAttribute("", "", "Id", id);
+            if (valueBase64 != null) {
+                xwriter.writeCharacters(valueBase64);
+            }
+
+            xwriter.writeEndElement(); // "SignatureValue"
         }
 
-        void setValue(byte[] value) {
+        void setValue(XmlWriter xwriter, byte[] value) {
             this.value = value;
-            valueBase64 = Base64.encode(value);
-            sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64));
+            valueBase64 = Base64.getMimeEncoder().encodeToString(value);
+            if (xwriter != null) {
+                xwriter.writeCharacters(valueBase64);
+            }
         }
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
+ * $Id: DOMXMLSignatureFactory.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -38,6 +38,7 @@
 import java.security.InvalidAlgorithmParameterException;
 import java.security.NoSuchAlgorithmException;
 import java.util.List;
+
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -45,7 +46,6 @@
 /**
  * DOM-based implementation of XMLSignatureFactory.
  *
- * @author Sean Mullan
  */
 public final class DOMXMLSignatureFactory extends XMLSignatureFactory {
 
@@ -54,27 +54,35 @@
      */
     public DOMXMLSignatureFactory() {}
 
+    @Override
     public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki) {
         return new DOMXMLSignature(si, ki, null, null, null);
     }
 
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
     public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki,
-        List<? extends XMLObject> objects, String id, String signatureValueId) {
+        List objects, String id, String signatureValueId) {
         return new DOMXMLSignature(si, ki, objects, id, signatureValueId);
     }
 
+    @Override
     public Reference newReference(String uri, DigestMethod dm) {
         return newReference(uri, dm, null, null, null);
     }
 
-    public Reference newReference(String uri, DigestMethod dm,
-        List<? extends Transform> transforms, String type, String id) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public Reference newReference(String uri, DigestMethod dm, List transforms,
+        String type, String id) {
         return new DOMReference(uri, type, dm, transforms, id, getProvider());
     }
 
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
     public Reference newReference(String uri, DigestMethod dm,
-        List<? extends Transform> appliedTransforms, Data result,
-        List<? extends Transform> transforms, String type, String id) {
+        List appliedTransforms, Data result, List transforms, String type,
+        String id) {
         if (appliedTransforms == null) {
             throw new NullPointerException("appliedTransforms cannot be null");
         }
@@ -88,9 +96,10 @@
             (uri, type, dm, appliedTransforms, result, transforms, id, getProvider());
     }
 
-    public Reference newReference(String uri, DigestMethod dm,
-        List<? extends Transform> transforms, String type, String id,
-        byte[] digestValue) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public Reference newReference(String uri, DigestMethod dm, List transforms,
+        String type, String id, byte[] digestValue) {
         if (digestValue == null) {
             throw new NullPointerException("digestValue cannot be null");
         }
@@ -98,41 +107,54 @@
             (uri, type, dm, null, null, transforms, id, digestValue, getProvider());
     }
 
+    @Override
+    @SuppressWarnings({ "rawtypes" })
     public SignedInfo newSignedInfo(CanonicalizationMethod cm,
-        SignatureMethod sm, List<? extends Reference> references) {
+        SignatureMethod sm, List references) {
         return newSignedInfo(cm, sm, references, null);
     }
 
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
     public SignedInfo newSignedInfo(CanonicalizationMethod cm,
-        SignatureMethod sm, List<? extends Reference> references, String id) {
+        SignatureMethod sm, List references, String id) {
         return new DOMSignedInfo(cm, sm, references, id);
     }
 
     // Object factory methods
-    public XMLObject newXMLObject(List<? extends XMLStructure> content,
-        String id, String mimeType, String encoding) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public XMLObject newXMLObject(List content, String id, String mimeType,
+        String encoding) {
         return new DOMXMLObject(content, id, mimeType, encoding);
     }
 
-    public Manifest newManifest(List<? extends Reference> references) {
+    @Override
+    @SuppressWarnings({ "rawtypes" })
+    public Manifest newManifest(List references) {
         return newManifest(references, null);
     }
 
-    public Manifest newManifest(List<? extends Reference> references,
-        String id) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public Manifest newManifest(List references, String id) {
         return new DOMManifest(references, id);
     }
 
-    public SignatureProperties newSignatureProperties(
-        List<? extends SignatureProperty> props, String id) {
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public SignatureProperties newSignatureProperties(List props, String id) {
         return new DOMSignatureProperties(props, id);
     }
 
+    @Override
+    @SuppressWarnings({ "unchecked", "rawtypes" })
     public SignatureProperty newSignatureProperty
-        (List<? extends XMLStructure> info, String target, String id) {
+        (List info, String target, String id) {
         return new DOMSignatureProperty(info, target, id);
     }
 
+    @Override
     public XMLSignature unmarshalXMLSignature(XMLValidateContext context)
         throws MarshalException {
 
@@ -142,6 +164,7 @@
         return unmarshal(((DOMValidateContext) context).getNode(), context);
     }
 
+    @Override
     public XMLSignature unmarshalXMLSignature(XMLStructure xmlStructure)
         throws MarshalException {
 
@@ -177,17 +200,19 @@
 
         // check tag
         String tag = element.getLocalName();
-        if (tag == null) {
+        String namespace = element.getNamespaceURI();
+        if (tag == null || namespace == null) {
             throw new MarshalException("Document implementation must " +
                 "support DOM Level 2 and be namespace aware");
         }
-        if (tag.equals("Signature")) {
+        if ("Signature".equals(tag) && XMLSignature.XMLNS.equals(namespace)) {
             return new DOMXMLSignature(element, context, getProvider());
         } else {
-            throw new MarshalException("invalid Signature tag: " + tag);
+            throw new MarshalException("invalid Signature tag: " + namespace + ":" + tag);
         }
     }
 
+    @Override
     public boolean isFeatureSupported(String feature) {
         if (feature == null) {
             throw new NullPointerException();
@@ -196,6 +221,7 @@
         }
     }
 
+    @Override
     public DigestMethod newDigestMethod(String algorithm,
         DigestMethodParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -204,17 +230,32 @@
         }
         if (algorithm.equals(DigestMethod.SHA1)) {
             return new DOMDigestMethod.SHA1(params);
+        } else if (algorithm.equals(DOMDigestMethod.SHA224)) {
+            return new DOMDigestMethod.SHA224(params);
         } else if (algorithm.equals(DigestMethod.SHA256)) {
             return new DOMDigestMethod.SHA256(params);
         } else if (algorithm.equals(DOMDigestMethod.SHA384)) {
             return new DOMDigestMethod.SHA384(params);
         } else if (algorithm.equals(DigestMethod.SHA512)) {
             return new DOMDigestMethod.SHA512(params);
+        } else if (algorithm.equals(DigestMethod.RIPEMD160)) {
+            return new DOMDigestMethod.RIPEMD160(params);
+        } else if (algorithm.equals(DOMDigestMethod.WHIRLPOOL)) {
+            return new DOMDigestMethod.WHIRLPOOL(params);
+        } else if (algorithm.equals(DOMDigestMethod.SHA3_224)) {
+            return new DOMDigestMethod.SHA3_224(params);
+        } else if (algorithm.equals(DOMDigestMethod.SHA3_256)) {
+            return new DOMDigestMethod.SHA3_256(params);
+        } else if (algorithm.equals(DOMDigestMethod.SHA3_384)) {
+            return new DOMDigestMethod.SHA3_384(params);
+        } else if (algorithm.equals(DOMDigestMethod.SHA3_512)) {
+            return new DOMDigestMethod.SHA3_512(params);
         } else {
             throw new NoSuchAlgorithmException("unsupported algorithm");
         }
     }
 
+    @Override
     public SignatureMethod newSignatureMethod(String algorithm,
         SignatureMethodParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -223,37 +264,64 @@
         }
         if (algorithm.equals(SignatureMethod.RSA_SHA1)) {
             return new DOMSignatureMethod.SHA1withRSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA224)) {
+            return new DOMSignatureMethod.SHA224withRSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA256)) {
             return new DOMSignatureMethod.SHA256withRSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA384)) {
             return new DOMSignatureMethod.SHA384withRSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA512)) {
             return new DOMSignatureMethod.SHA512withRSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA512)) {
+            return new DOMSignatureMethod.SHA512withRSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_RIPEMD160)) {
+            return new DOMSignatureMethod.RIPEMD160withRSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA1_MGF1)) {
+            return new DOMSignatureMethod.SHA1withRSAandMGF1(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA224_MGF1)) {
+            return new DOMSignatureMethod.SHA224withRSAandMGF1(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA256_MGF1)) {
+            return new DOMSignatureMethod.SHA256withRSAandMGF1(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA384_MGF1)) {
+            return new DOMSignatureMethod.SHA384withRSAandMGF1(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_SHA512_MGF1)) {
+            return new DOMSignatureMethod.SHA512withRSAandMGF1(params);
+        } else if (algorithm.equals(DOMSignatureMethod.RSA_RIPEMD160_MGF1)) {
+            return new DOMSignatureMethod.RIPEMD160withRSAandMGF1(params);
         } else if (algorithm.equals(SignatureMethod.DSA_SHA1)) {
             return new DOMSignatureMethod.SHA1withDSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.DSA_SHA256)) {
             return new DOMSignatureMethod.SHA256withDSA(params);
         } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) {
             return new DOMHMACSignatureMethod.SHA1(params);
+        } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA224)) {
+            return new DOMHMACSignatureMethod.SHA224(params);
         } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
             return new DOMHMACSignatureMethod.SHA256(params);
         } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
             return new DOMHMACSignatureMethod.SHA384(params);
         } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
             return new DOMHMACSignatureMethod.SHA512(params);
+        } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_RIPEMD160)) {
+            return new DOMHMACSignatureMethod.RIPEMD160(params);
         } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) {
             return new DOMSignatureMethod.SHA1withECDSA(params);
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA224)) {
+            return new DOMSignatureMethod.SHA224withECDSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) {
             return new DOMSignatureMethod.SHA256withECDSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) {
             return new DOMSignatureMethod.SHA384withECDSA(params);
         } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) {
             return new DOMSignatureMethod.SHA512withECDSA(params);
-        } else {
+        } else if (algorithm.equals(DOMSignatureMethod.ECDSA_RIPEMD160)) {
+            return new DOMSignatureMethod.RIPEMD160withECDSA(params);
+        }else {
             throw new NoSuchAlgorithmException("unsupported algorithm");
         }
     }
 
+    @Override
     public Transform newTransform(String algorithm,
         TransformParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -273,6 +341,7 @@
         return new DOMTransform(spi);
     }
 
+    @Override
     public Transform newTransform(String algorithm,
         XMLStructure params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -295,6 +364,7 @@
         return new DOMTransform(spi);
     }
 
+    @Override
     public CanonicalizationMethod newCanonicalizationMethod(String algorithm,
         C14NMethodParameterSpec params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -313,6 +383,7 @@
         return new DOMCanonicalizationMethod(spi);
     }
 
+    @Override
     public CanonicalizationMethod newCanonicalizationMethod(String algorithm,
         XMLStructure params) throws NoSuchAlgorithmException,
         InvalidAlgorithmParameterException {
@@ -335,6 +406,7 @@
         return new DOMCanonicalizationMethod(spi);
     }
 
+    @Override
     public URIDereferencer getURIDereferencer() {
         return DOMURIDereferencer.INSTANCE;
     }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,10 +28,10 @@
  * ===========================================================================
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Portions copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $
+ * $Id: DOMXPathFilter2Transform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -54,10 +54,10 @@
  * DOM-based implementation of XPath Filter 2.0 Transform.
  * (Uses Apache XML-Sec Transform implementation)
  *
- * @author Joyce Leung
  */
 public final class DOMXPathFilter2Transform extends ApacheTransform {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException
     {
@@ -70,6 +70,7 @@
         this.params = params;
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException
     {
@@ -83,34 +84,35 @@
 
     private void unmarshalParams(Element curXPathElem) throws MarshalException
     {
-        List<XPathType> list = new ArrayList<XPathType>();
-        while (curXPathElem != null) {
-            String xPath = curXPathElem.getFirstChild().getNodeValue();
-            String filterVal = DOMUtils.getAttributeValue(curXPathElem,
+        List<XPathType> list = new ArrayList<>();
+        Element currentElement = curXPathElem;
+        while (currentElement != null) {
+            String xPath = currentElement.getFirstChild().getNodeValue();
+            String filterVal = DOMUtils.getAttributeValue(currentElement,
                                                           "Filter");
             if (filterVal == null) {
                 throw new MarshalException("filter cannot be null");
             }
             XPathType.Filter filter = null;
-            if (filterVal.equals("intersect")) {
+            if ("intersect".equals(filterVal)) {
                 filter = XPathType.Filter.INTERSECT;
-            } else if (filterVal.equals("subtract")) {
+            } else if ("subtract".equals(filterVal)) {
                 filter = XPathType.Filter.SUBTRACT;
-            } else if (filterVal.equals("union")) {
+            } else if ("union".equals(filterVal)) {
                 filter = XPathType.Filter.UNION;
             } else {
                 throw new MarshalException("Unknown XPathType filter type" +
                                            filterVal);
             }
-            NamedNodeMap attributes = curXPathElem.getAttributes();
+            NamedNodeMap attributes = currentElement.getAttributes();
             if (attributes != null) {
                 int length = attributes.getLength();
                 Map<String, String> namespaceMap =
-                    new HashMap<String, String>(length);
+                    new HashMap<>(length);
                 for (int i = 0; i < length; i++) {
                     Attr attr = (Attr)attributes.item(i);
                     String prefix = attr.getPrefix();
-                    if (prefix != null && prefix.equals("xmlns")) {
+                    if (prefix != null && "xmlns".equals(prefix)) {
                         namespaceMap.put(attr.getLocalName(), attr.getValue());
                     }
                 }
@@ -119,11 +121,12 @@
                 list.add(new XPathType(xPath, filter));
             }
 
-            curXPathElem = DOMUtils.getNextSiblingElement(curXPathElem);
+            currentElement = DOMUtils.getNextSiblingElement(currentElement);
         }
         this.params = new XPathFilter2ParameterSpec(list);
     }
 
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -131,8 +134,9 @@
         XPathFilter2ParameterSpec xp =
             (XPathFilter2ParameterSpec)getParameterSpec();
         String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2);
-        String qname = (prefix == null || prefix.length() == 0)
+        String qname = prefix == null || prefix.length() == 0
                        ? "xmlns" : "xmlns:" + prefix;
+        @SuppressWarnings("unchecked")
         List<XPathType> xpathList = xp.getXPathList();
         for (XPathType xpathType : xpathList) {
             Element elem = DOMUtils.createElement(ownerDoc, "XPath",
@@ -145,6 +149,7 @@
                                 Transform.XPATH2);
 
             // add namespace attributes, if necessary
+            @SuppressWarnings("unchecked")
             Set<Map.Entry<String, String>> entries =
                 xpathType.getNamespaceMap().entrySet();
             for (Map.Entry<String, String> entry : entries) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $
+ * $Id: DOMXPathTransform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -44,10 +44,10 @@
  * DOM-based implementation of XPath Filtering Transform.
  * (Uses Apache XML-Sec Transform implementation)
  *
- * @author Sean Mullan
  */
 public final class DOMXPathTransform extends ApacheTransform {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException
     {
@@ -60,6 +60,7 @@
         this.params = params;
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException
     {
@@ -74,11 +75,11 @@
         if (attributes != null) {
             int length = attributes.getLength();
             Map<String, String> namespaceMap =
-                new HashMap<String, String>(length);
+                new HashMap<>(length);
             for (int i = 0; i < length; i++) {
                 Attr attr = (Attr)attributes.item(i);
                 String prefix = attr.getPrefix();
-                if (prefix != null && prefix.equals("xmlns")) {
+                if (prefix != null && "xmlns".equals(prefix)) {
                     namespaceMap.put(attr.getLocalName(), attr.getValue());
                 }
             }
@@ -88,6 +89,7 @@
         }
     }
 
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException
     {
@@ -99,6 +101,7 @@
         xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath()));
 
         // add namespace attributes, if necessary
+        @SuppressWarnings("unchecked")
         Set<Map.Entry<String, String>> entries =
             xp.getNamespaceMap().entrySet();
         for (Map.Entry<String, String> entry : entries) {
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: DOMXSLTTransform.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -40,10 +40,10 @@
  * DOM-based implementation of XSLT Transform.
  * (Uses Apache XML-Sec Transform implementation)
  *
- * @author Sean Mullan
  */
 public final class DOMXSLTTransform extends ApacheTransform {
 
+    @Override
     public void init(TransformParameterSpec params)
         throws InvalidAlgorithmParameterException {
         if (params == null) {
@@ -55,6 +55,7 @@
         this.params = params;
     }
 
+    @Override
     public void init(XMLStructure parent, XMLCryptoContext context)
         throws InvalidAlgorithmParameterException {
 
@@ -67,6 +68,7 @@
             (new javax.xml.crypto.dom.DOMStructure(sheet));
     }
 
+    @Override
     public void marshalParams(XMLStructure parent, XMLCryptoContext context)
         throws MarshalException {
         super.marshalParams(parent, context);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Marshaller.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,353 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jcp.xml.dsig.internal.dom;
+
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+
+import javax.xml.XMLConstants;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.XMLStructure;
+import javax.xml.crypto.dsig.DigestMethod;
+import javax.xml.crypto.dsig.Manifest;
+import javax.xml.crypto.dsig.SignatureProperties;
+import javax.xml.crypto.dsig.SignatureProperty;
+import javax.xml.crypto.dsig.XMLSignature;
+import javax.xml.crypto.dsig.keyinfo.KeyInfo;
+import javax.xml.crypto.dsig.keyinfo.KeyName;
+import javax.xml.crypto.dsig.keyinfo.KeyValue;
+import javax.xml.crypto.dsig.keyinfo.PGPData;
+import javax.xml.crypto.dsig.keyinfo.X509Data;
+import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * Defines the individual marshallers for each of the different javax.xml.crypto structures.
+ */
+class Marshaller {
+
+    private Marshaller() {
+        // complete
+    }
+
+    public static List<XmlWriter.ToMarshal<? extends XMLStructure>> getMarshallers() {
+        return MARSHALLERS;
+    }
+
+    /**
+     * Marshals a {@link KeyName}.
+     *
+     * @param xwriter
+     * @param keyName
+     * @param dsPrefix
+     */
+    public static void marshalKeyName(XmlWriter xwriter, KeyName keyName, String dsPrefix) {
+        xwriter.writeTextElement(dsPrefix, "KeyName", XMLSignature.XMLNS, keyName.getName());
+    }
+
+    /**
+     * Marshals a {@link PGPData}
+     *
+     * @param xwriter
+     * @param pgpData
+     * @param dsPrefix
+     * @param context
+     * @throws MarshalException
+     */
+    public static void marshalPGPData(XmlWriter xwriter, PGPData pgpData, String dsPrefix, XMLCryptoContext context)
+    throws MarshalException {
+        xwriter.writeStartElement(dsPrefix, "PGPData", XMLSignature.XMLNS);
+
+        // create and append PGPKeyID element
+        byte[] keyId = pgpData.getKeyId();
+        if (keyId != null) {
+            xwriter.writeTextElement(dsPrefix, "PGPKeyID", XMLSignature.XMLNS,
+                                     Base64.getMimeEncoder().encodeToString(keyId));
+        }
+
+        // create and append PGPKeyPacket element
+        byte[] keyPacket = pgpData.getKeyPacket();
+        if (keyPacket != null) {
+            xwriter.writeTextElement(dsPrefix, "XMLSignature.XMLNS", XMLSignature.XMLNS,
+                                     Base64.getMimeEncoder().encodeToString(keyPacket));
+        }
+
+        // create and append any elements
+        @SuppressWarnings("unchecked")
+        List<XMLStructure> externalElements = pgpData.getExternalElements();
+        for (XMLStructure externalItem : externalElements) {
+            xwriter.marshalStructure(externalItem, dsPrefix, context);
+        }
+
+        xwriter.writeEndElement(); // "PGPData"
+    }
+
+    /**
+     * Marshals an {@link X509IssuerSerial}
+     *
+     * @param xwriter
+     * @param issuerSerial
+     * @param dsPrefix
+     */
+    public static void marshalX509IssuerSerial(XmlWriter xwriter, X509IssuerSerial issuerSerial, String dsPrefix) {
+        xwriter.writeStartElement(dsPrefix, "X509IssuerSerial", XMLSignature.XMLNS);
+        xwriter.writeTextElement(dsPrefix, "X509IssuerName", XMLSignature.XMLNS,
+                issuerSerial.getIssuerName());
+
+        xwriter.writeTextElement(dsPrefix, "X509SerialNumber", XMLSignature.XMLNS,
+                issuerSerial.getSerialNumber().toString());
+
+        xwriter.writeEndElement(); // "X509IssuerSerial"
+    }
+
+    private static XmlWriter.ToMarshal<KeyName> Marshal_KeyName = new XmlWriter.ToMarshal<KeyName>(KeyName.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, KeyName toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            Marshaller.marshalKeyName(xwriter, toMarshal, dsPrefix);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<KeyInfo> Marshal_KeyInfo = new XmlWriter.ToMarshal<KeyInfo>(KeyInfo.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, KeyInfo toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMKeyInfo.marshal(xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<KeyValue> Marshal_KeyValue = new XmlWriter.ToMarshal<KeyValue>(KeyValue.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, KeyValue toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            // Since DOMKeyValue allows for deserializing unrecognized keys, and that
+            // capability isn't available via the KeyValue interface, this must continue
+            // to cast to DOMKeyValue.
+            DOMKeyValue<?> dkv = (DOMKeyValue<?>) toMarshal;
+            dkv.marshal( xwriter, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<X509IssuerSerial> Marshal_X509IssuerSerial =
+            new XmlWriter.ToMarshal<X509IssuerSerial>(X509IssuerSerial.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, X509IssuerSerial toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            Marshaller.marshalX509IssuerSerial( xwriter, toMarshal, dsPrefix);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<X509Data> Marshal_X509Data =
+            new XmlWriter.ToMarshal<X509Data>(X509Data.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, X509Data toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMX509Data.marshal( xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<DigestMethod> Marshal_DigestMethod =
+            new XmlWriter.ToMarshal<DigestMethod>(DigestMethod.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, DigestMethod toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMDigestMethod.marshal( xwriter, toMarshal, dsPrefix);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<PGPData> Marshal_PGPData =
+            new XmlWriter.ToMarshal<PGPData>(PGPData.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, PGPData toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            Marshaller.marshalPGPData( xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<SignatureProperty> Marshal_SignatureProperty =
+            new XmlWriter.ToMarshal<SignatureProperty>(SignatureProperty.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, SignatureProperty toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMSignatureProperty.marshal(xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<SignatureProperties> Marshal_SignatureProperties =
+            new XmlWriter.ToMarshal<SignatureProperties>(SignatureProperties.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, SignatureProperties toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMSignatureProperties.marshal(xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<DOMSignatureMethod> Marshal_DOMSignatureMethod =
+            new XmlWriter.ToMarshal<DOMSignatureMethod>(DOMSignatureMethod.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, DOMSignatureMethod toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            toMarshal.marshal(xwriter, dsPrefix);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<DOMTransform> Marshal_DOMTransform =
+            new XmlWriter.ToMarshal<DOMTransform>(DOMTransform.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, DOMTransform toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            toMarshal.marshal(xwriter, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<Manifest> Marshal_Manifest =
+            new XmlWriter.ToMarshal<Manifest>(Manifest.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, Manifest toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            DOMManifest.marshal(xwriter, toMarshal, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<DOMStructure> Marshal_DOMStructure =
+            new XmlWriter.ToMarshal<DOMStructure>(DOMStructure.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, DOMStructure toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            toMarshal.marshal(xwriter, dsPrefix, context);
+        }
+    };
+
+    private static XmlWriter.ToMarshal<javax.xml.crypto.dom.DOMStructure> Marshal_JavaXDOMStructure =
+            new XmlWriter.ToMarshal<javax.xml.crypto.dom.DOMStructure>(javax.xml.crypto.dom.DOMStructure.class) {
+        @Override
+        public void marshalObject(XmlWriter xwriter, javax.xml.crypto.dom.DOMStructure toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException {
+            marshalGenericNode(xwriter, toMarshal);
+        }
+    };
+
+    private static final List<XmlWriter.ToMarshal<? extends XMLStructure>> MARSHALLERS =
+        new ArrayList<XmlWriter.ToMarshal<? extends XMLStructure>>();
+
+    static {
+        MARSHALLERS.add(Marshal_KeyName);
+        MARSHALLERS.add(Marshal_KeyInfo);
+        MARSHALLERS.add(Marshal_KeyValue);
+        MARSHALLERS.add(Marshal_X509IssuerSerial);
+        MARSHALLERS.add(Marshal_X509Data);
+        MARSHALLERS.add(Marshal_DigestMethod);
+        MARSHALLERS.add(Marshal_PGPData);
+        MARSHALLERS.add(Marshal_SignatureProperty);
+        MARSHALLERS.add(Marshal_SignatureProperties);
+        MARSHALLERS.add(Marshal_DOMSignatureMethod);
+        MARSHALLERS.add(Marshal_DOMTransform);
+        MARSHALLERS.add(Marshal_Manifest);
+        MARSHALLERS.add(Marshal_DOMStructure);
+        MARSHALLERS.add(Marshal_JavaXDOMStructure);
+    }
+
+    private static void marshalGenericNode(XmlWriter xwriter, javax.xml.crypto.dom.DOMStructure xmlStruct) {
+        Node node = xmlStruct.getNode();
+
+        // if it is a namespace, make a copy.
+        if (DOMUtils.isNamespace(node)) {
+            xwriter.writeNamespace(node.getLocalName(), node.getTextContent());
+        }
+        else if (Node.ATTRIBUTE_NODE == node.getNodeType() ) {
+            sendAttributeToWriter(xwriter, (Attr) node);
+        }
+        else {
+            marshalGenericNode(xwriter, node);
+        }
+    }
+
+    private static void marshalGenericNode(XmlWriter xwriter, Node node) {
+
+        short nodeType = node.getNodeType();
+        if (DOMUtils.isNamespace(node)) {
+            xwriter.writeNamespace(node.getLocalName(), node.getTextContent());
+        }
+        else if (nodeType == Node.ATTRIBUTE_NODE) {
+            // if it is an attribute, make a copy.
+            sendAttributeToWriter(xwriter, (Attr) node);
+        }
+        else {
+            switch (nodeType) {
+            case Node.ELEMENT_NODE:
+                xwriter.writeStartElement(node.getPrefix(), node.getLocalName(), node.getNamespaceURI());
+
+                // emit all the namespaces and attributes.
+                NamedNodeMap nnm = node.getAttributes();
+                for (int idx = 0 ; idx < nnm.getLength() ; idx++) {
+                    Attr attr = (Attr) nnm.item(idx);
+                    // is this a namespace node?
+                    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(node.getNamespaceURI())) {
+                        xwriter.writeNamespace(attr.getLocalName(), attr.getValue());
+                    }
+                    else {
+                        // nope - standard attribute.
+                        sendAttributeToWriter(xwriter, attr);
+                    }
+                }
+                // now loop through all the children.
+                for (Node child = node.getFirstChild() ; child != null ; child = child.getNextSibling()) {
+                    marshalGenericNode(xwriter, child);
+                }
+                xwriter.writeEndElement();
+                break;
+            case Node.COMMENT_NODE:
+                xwriter.writeComment(node.getTextContent());
+                break;
+            case Node.TEXT_NODE:
+                xwriter.writeCharacters(node.getTextContent());
+                break;
+            default:
+                // unhandled - don't care to deal with processing instructions.
+                break;
+            }
+        }
+    }
+
+    private static void sendAttributeToWriter(XmlWriter xwriter, Attr attr) {
+        if (attr.isId()) {
+            xwriter.writeIdAttribute(attr.getPrefix(), attr.getNamespaceURI(),
+                    attr.getLocalName(), attr.getTextContent());
+        }
+        else {
+            if (attr.getNamespaceURI() == null && attr.getLocalName() == null) {
+                // Level 1 DOM attribute
+                xwriter.writeAttribute(null, null, attr.getName(), attr.getTextContent());
+            } else {
+                xwriter.writeAttribute(attr.getPrefix(), attr.getNamespaceURI(), attr.getLocalName(),
+                                       attr.getTextContent());
+            }
+        }
+    }
+
+}
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -21,10 +21,10 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $
+ * $Id: Utils.java 1788465 2017-03-24 15:10:51Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -39,7 +39,6 @@
 /**
  * Miscellaneous static utility methods for use in JSR 105 RI.
  *
- * @author Sean Mullan
  */
 public final class Utils {
 
@@ -48,19 +47,20 @@
     public static byte[] readBytesFromStream(InputStream is)
         throws IOException
     {
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        byte[] buf = new byte[1024];
-        while (true) {
-            int read = is.read(buf);
-            if (read == -1) { // EOF
-                break;
+        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+            byte[] buf = new byte[1024];
+            while (true) {
+                int read = is.read(buf);
+                if (read == -1) { // EOF
+                    break;
+                }
+                baos.write(buf, 0, read);
+                if (read < 1024) {
+                    break;
+                }
             }
-            baos.write(buf, 0, read);
-            if (read < 1024) {
-                break;
-            }
+            return baos.toByteArray();
         }
-        return baos.toByteArray();
     }
 
     /**
@@ -71,7 +71,7 @@
      * @return the Set of Nodes
      */
     static Set<Node> toNodeSet(Iterator<?> i) {
-        Set<Node> nodeSet = new HashSet<Node>();
+        Set<Node> nodeSet = new HashSet<>();
         while (i.hasNext()) {
             Node n = (Node)i.next();
             nodeSet.add(n);
@@ -106,7 +106,7 @@
      * Returns true if uri is a same-document URI, false otherwise.
      */
     public static boolean sameDocumentURI(String uri) {
-        return (uri != null && (uri.length() == 0 || uri.charAt(0) == '#'));
+        return uri != null && (uri.length() == 0 || uri.charAt(0) == '#');
     }
 
     static boolean secureValidation(XMLCryptoContext xc) {
@@ -118,6 +118,6 @@
 
     private static boolean getBoolean(XMLCryptoContext xc, String name) {
         Boolean value = (Boolean)xc.getProperty(name);
-        return (value != null && value.booleanValue());
+        return value != null && value.booleanValue();
     }
 }
--- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,10 +28,10 @@
  * ===========================================================================
  */
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Portions copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  */
 /*
- * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $
+ * $Id: XMLDSigRI.java 1804972 2017-08-14 09:59:23Z coheigea $
  */
 package org.jcp.xml.dsig.internal.dom;
 
@@ -43,7 +43,6 @@
 /**
  * The XMLDSig RI Provider.
  *
- * @author Joyce Leung
  */
 
 /**
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XmlWriter.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,112 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jcp.xml.dsig.internal.dom;
+
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.XMLStructure;
+
+import org.w3c.dom.Attr;
+
+/**
+ * This interface is used to construct XML via a sequence of API calls.
+ *
+ * <p>This is written to be similar to javax.xml.stream.XMLStreamWriter, but
+ * has slightly different requirements. Specifically, we need to be able to create
+ * an "ID" type attribute, and get the current node.
+ * </p>
+ */
+public interface XmlWriter {
+
+    /**
+     * Utility class that brings together the class, and the method for marshaling an
+     * instance of said class.
+     *
+     * @param <CLZ>
+     */
+    abstract static class ToMarshal<CLZ extends XMLStructure> { //NOPMD
+        public final Class<CLZ> clazzToMatch;
+
+        public ToMarshal(Class<CLZ> clazzToMatch) {
+            this.clazzToMatch = clazzToMatch;
+        }
+
+        public abstract void marshalObject(XmlWriter xwriter, CLZ toMarshal, String dsPrefix,
+                XMLCryptoContext context) throws MarshalException;
+    }
+
+    /**
+     *
+     * @param prefix    What prefix to use?
+     * @param localName What local name to use?
+     * @param namespaceURI  What namespace URI?
+     *
+     * See also {@link javax.xml.stream.XMLStreamWriter#writeStartElement(String, String, String)}
+     */
+    void writeStartElement(String prefix, String localName, String namespaceURI);
+
+    /**
+     * See also {@link javax.xml.stream.XMLStreamWriter#writeEndElement()}
+     */
+    void writeEndElement();
+
+    /**
+     * Convenience method that writes both a start and end tag, with text contents as
+     * provided.
+     *
+     * @param prefix
+     * @param localName
+     * @param namespaceURI
+     * @param value
+     */
+    void writeTextElement(String prefix, String localName, String namespaceURI, String value);
+
+    void writeNamespace(String prefix, String namespaceURI);
+
+    void writeCharacters(String text);
+
+    void writeComment(String text);
+
+    Attr writeAttribute(String prefix, String namespaceURI, String localName, String value);
+
+    void writeIdAttribute(String prefix, String namespaceURI, String localName, String value);
+
+    /**
+     * Get the local name of the current element.
+     * @return the local name of the current element.
+     */
+    String getCurrentLocalName();
+
+    XMLStructure getCurrentNodeAsStructure();
+
+    /**
+     * This method marshals a structure, and relies on implementation specific details for how
+     * an instance of a particular class maps to the method that actually does the marshaling.
+     *
+     * @param toMarshal The object to be marshaled.
+     * @param dsPrefix  The digital signature prefix.
+     * @param context   The context for marshaling.
+     * @throws MarshalException Thrown if something goes wrong during the marshaling.
+     */
+    void marshalStructure(XMLStructure toMarshal, String dsPrefix, XMLCryptoContext context) throws MarshalException;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XmlWriterToTree.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,208 @@
+/*
+ * 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jcp.xml.dsig.internal.dom;
+
+import java.util.List;
+
+import javax.xml.XMLConstants;
+import javax.xml.crypto.MarshalException;
+import javax.xml.crypto.XMLCryptoContext;
+import javax.xml.crypto.XMLStructure;
+import javax.xml.crypto.dom.DOMStructure;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+/**
+ * Manifestation of XmlWriter interface designed to write to a tree.
+ */
+public class XmlWriterToTree implements XmlWriter {
+
+    private Document factory;
+
+    private Element createdElement;
+
+    private Node nextSibling;
+
+    private Node currentNode;
+
+    private List<XmlWriter.ToMarshal<? extends XMLStructure>> m_marshallers;
+
+    public XmlWriterToTree(List<XmlWriter.ToMarshal<? extends XMLStructure>> marshallers, Node parent) {
+        m_marshallers = marshallers;
+        factory = parent instanceof Document ? (Document)parent : parent.getOwnerDocument();
+        currentNode = parent;
+    }
+
+    /**
+     * Reset to a new parent so that the writer can be re-used.
+     * @param newParent
+     */
+    public void resetToNewParent(Node newParent) {
+        currentNode = newParent;
+        createdElement = null;
+    }
+
+    /**
+     * Get the root element created with this writer.
+     * @return the root element created with this writer.
+     */
+    public Element getCreatedElement() {
+        return createdElement;
+    }
+
+    /**
+     * In cases where the serialization is supposed to precede a specific
+     * element, we add an extra parameter to capture that. Only affects the
+     * first element insertion (obviously?).
+     *
+     * @param marshallers
+     * @param parent
+     * @param nextSibling The first element created will be created *before* this element.
+     */
+    public XmlWriterToTree(List<XmlWriter.ToMarshal<? extends XMLStructure>> marshallers, Node parent, Node nextSibling) {
+        this(marshallers, parent);
+        this.nextSibling = nextSibling;
+    }
+
+    @Override
+    public void writeStartElement(String prefix, String localName, String namespaceURI) {
+        if ("".equals(namespaceURI)) {
+            // Map global namespace from StAX to DOM
+            namespaceURI = null;
+        }
+
+        Element newElem = factory.createElementNS(namespaceURI, DOMUtils.getQNameString(prefix, localName));
+        if (nextSibling != null) {
+            newElem = (Element)nextSibling.getParentNode().insertBefore(newElem, nextSibling);
+        }
+        else {
+            newElem = (Element)currentNode.appendChild(newElem);
+        }
+        nextSibling = null;
+        currentNode = newElem;
+
+        if (createdElement == null) {
+            createdElement = newElem;
+        }
+    }
+
+    @Override
+    public void writeEndElement() {
+        currentNode = currentNode.getParentNode();
+    }
+
+
+    @Override
+    public void writeTextElement(String prefix, String localName, String namespaceURI, String value) {
+        writeStartElement(prefix, localName, namespaceURI);
+        writeCharacters(value);
+        writeEndElement();
+    }
+
+    @Override
+    public void writeNamespace(String prefix, String namespaceURI) {
+        if ("".equals(prefix) || prefix == null) {
+            writeAttribute(null, XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns", namespaceURI);
+        }
+        else {
+            writeAttribute("xmlns", XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix, namespaceURI);
+        }
+    }
+
+    @Override
+    public void writeCharacters(String text) {
+        Text textNode = factory.createTextNode(text);
+        currentNode.appendChild(textNode);
+    }
+
+
+    @Override
+    public void writeComment(String text) {
+        Comment commentNode = factory.createComment(text);
+        currentNode.appendChild(commentNode);
+    }
+
+    @Override
+    public Attr writeAttribute(String prefix, String namespaceURI, String localName, String value) {
+
+        Attr result = null;
+        if (value != null) {
+            if ("".equals(namespaceURI)) {
+                // Map global namespace from StAX to DOM
+                namespaceURI = null;
+            }
+
+            result = factory.createAttributeNS(namespaceURI, DOMUtils.getQNameString(prefix, localName));
+            result.setTextContent(value);
+            if (! (currentNode instanceof Element)) {
+                throw new IllegalStateException(
+                        "Attempting to add an attribute to something other than an element node. Node is "
+                                + currentNode.toString());
+            }
+            ( (Element)currentNode).setAttributeNodeNS(result);
+        }
+        return result;
+    }
+
+    @Override
+    public void writeIdAttribute(String prefix, String namespaceURI, String localName, String value) {
+        if (value == null) {
+            return;
+        }
+        Attr newAttr = writeAttribute(prefix, namespaceURI, localName, value);
+        ( (Element)currentNode).setIdAttributeNode(newAttr, true);
+    }
+
+
+    @Override
+    public String getCurrentLocalName() {
+        return currentNode.getLocalName();
+    }
+
+    @Override
+    public XMLStructure getCurrentNodeAsStructure() {
+        return new DOMStructure(currentNode);
+    }
+
+    @Override
+    public void marshalStructure(XMLStructure toMarshal, String dsPrefix, XMLCryptoContext context) throws MarshalException {
+
+        // look for the first isInstance match, and marshal to that.
+        for (int idx = 0 ; idx < m_marshallers.size() ; idx++) {
+            @SuppressWarnings("unchecked")
+            XmlWriter.ToMarshal<XMLStructure> marshaller = (ToMarshal<XMLStructure>) m_marshallers.get(idx);
+            if (marshaller.clazzToMatch.isInstance(toMarshal)) {
+                marshaller.marshalObject(this, toMarshal, dsPrefix, context);
+                return;
+            }
+        }
+        throw new IllegalArgumentException("Unable to marshal unexpected object of class " + toMarshal.getClass().toString());
+    }
+
+
+}
--- a/src/java.xml.crypto/share/legal/santuario.md	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/java.xml.crypto/share/legal/santuario.md	Tue Jun 19 16:33:07 2018 +0100
@@ -1,10 +1,10 @@
-## Apache Santuario v1.5.4
+## Apache Santuario v2.1.1
 
 ### Apache Santuario Notice
 <pre>
 
   Apache Santuario - XML Security for Java
-  Copyright 1999-2015 The Apache Software Foundation
+  Copyright 1999-2018 The Apache Software Foundation
 
   This product includes software developed at
   The Apache Software Foundation (http://www.apache.org/).
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java	Tue Jun 19 16:33:07 2018 +0100
@@ -676,10 +676,21 @@
 
             public Type getType(Type site) {
                 site = removeWildcards(site);
-                if (!chk.checkValidGenericType(site)) {
-                    //if the inferred functional interface type is not well-formed,
-                    //or if it's not a subtype of the original target, issue an error
-                    throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
+                if (site.isIntersection()) {
+                    IntersectionClassType ict = (IntersectionClassType)site;
+                    for (Type component : ict.getExplicitComponents()) {
+                        if (!chk.checkValidGenericType(component)) {
+                            //if the inferred functional interface type is not well-formed,
+                            //or if it's not a subtype of the original target, issue an error
+                            throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
+                        }
+                    }
+                } else {
+                    if (!chk.checkValidGenericType(site)) {
+                        //if the inferred functional interface type is not well-formed,
+                        //or if it's not a subtype of the original target, issue an error
+                        throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
+                    }
                 }
                 return memberType(site, descSym);
             }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Jun 19 16:33:07 2018 +0100
@@ -69,8 +69,6 @@
 
 import javax.lang.model.element.ElementVisitor;
 
-import com.sun.tools.javac.comp.Infer.InferenceException;
-
 import static com.sun.tools.javac.code.Flags.*;
 import static com.sun.tools.javac.code.Flags.BLOCK;
 import static com.sun.tools.javac.code.Flags.STATIC;
@@ -818,8 +816,28 @@
             String key = inferDiag ? diag.inferKey : diag.basicKey;
             throw inferDiag ?
                 infer.error(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args)) :
-                new InapplicableMethodException(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
-        }
+                methodCheckFailure.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
+        }
+
+        /**
+         * To eliminate the overhead associated with allocating an exception object in such an
+         * hot execution path, we use flyweight pattern - and share the same exception instance
+         * across multiple method check failures.
+         */
+        class SharedInapplicableMethodException extends InapplicableMethodException {
+            private static final long serialVersionUID = 0;
+
+            SharedInapplicableMethodException() {
+                super(null);
+            }
+
+            SharedInapplicableMethodException setMessage(JCDiagnostic details) {
+                this.diagnostic = details;
+                return this;
+            }
+        }
+
+        SharedInapplicableMethodException methodCheckFailure = new SharedInapplicableMethodException();
 
         public MethodCheck mostSpecificCheck(List<Type> actuals) {
             return nilMethodCheck;
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapImplTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapImplTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapLargeTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapLargeTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicMapTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicSetTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EconomicSetTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EquivalenceTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/EquivalenceTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/PairTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections.test/src/jdk/internal/vm/compiler/collections/test/PairTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicMap.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicMap.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicMapImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicMapImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicSet.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/EconomicSet.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/Equivalence.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/Equivalence.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/MapCursor.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/MapCursor.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/Pair.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/Pair.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableEconomicMap.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableEconomicMap.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableEconomicSet.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableEconomicSet.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableMapCursor.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/UnmodifiableMapCursor.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/package-info.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.collections/src/jdk/internal/vm/compiler/collections/package-info.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/ComparableWord.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/ComparableWord.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/LocationIdentity.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/LocationIdentity.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/Pointer.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/Pointer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/PointerBase.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/PointerBase.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/SignedWord.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/SignedWord.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/UnsignedWord.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/UnsignedWord.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/WordBase.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/WordBase.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/WordFactory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/WordFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordBoxFactory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordBoxFactory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordFactoryOpcode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordFactoryOpcode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordFactoryOperation.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/impl/WordFactoryOperation.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/package-info.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/jdk.internal.vm.compiler.word/src/jdk/internal/vm/compiler/word/package-info.java	Tue Jun 19 16:33:07 2018 +0100
@@ -4,9 +4,7 @@
  *
  * 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.
+ * 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
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.aarch64/src/org/graalvm/compiler/asm/aarch64/AArch64Assembler.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.aarch64/src/org/graalvm/compiler/asm/aarch64/AArch64Assembler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -102,6 +102,7 @@
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.STXR;
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.SUB;
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.SUBS;
+import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.SWP;
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.TBZ;
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.TBNZ;
 import static org.graalvm.compiler.asm.aarch64.AArch64Assembler.Instruction.UBFM;
@@ -519,6 +520,7 @@
 
         CAS(0x08A07C00),
         LDADD(0x38200000),
+        SWP(0x38208000),
 
         ADR(0x00000000),
         ADRP(0x80000000),
@@ -1391,6 +1393,30 @@
         emitInt(transferSizeEncoding | instr.encoding | rs2(rs) | rn(rn) | rt(rt) | (acquire ? 1 : 0) << LDADDAcquireOffset | (release ? 1 : 0) << LDADDReleaseOffset);
     }
 
+    /**
+     * Atomic swap. This reads a value from an address rn, stores the value in rt, and then stores
+     * the value in rs back at address rn.
+     *
+     * @param size size of operand to read from memory. Must be 8, 16, 32, or 64.
+     * @param rs general purpose register to be stored. May not be null.
+     * @param rt general purpose register to be loaded. May not be null.
+     * @param rn general purpose register or stack pointer holding an address from which to load.
+     * @param acquire boolean value signifying if the load should use acquire semantics.
+     * @param release boolean value signifying if the store should use release semantics.
+     */
+    public void swp(int size, Register rs, Register rt, Register rn, boolean acquire, boolean release) {
+        assert size == 8 || size == 16 || size == 32 || size == 64;
+        int transferSize = NumUtil.log2Ceil(size / 8);
+        swapInstruction(SWP, rs, rt, rn, transferSize, acquire, release);
+    }
+
+    private void swapInstruction(Instruction instr, Register rs, Register rt, Register rn, int log2TransferSize, boolean acquire, boolean release) {
+        assert log2TransferSize >= 0 && log2TransferSize < 4;
+        assert rt.getRegisterCategory().equals(CPU) && rs.getRegisterCategory().equals(CPU) && !rs.equals(rt);
+        int transferSizeEncoding = log2TransferSize << LoadStoreTransferSizeOffset;
+        emitInt(transferSizeEncoding | instr.encoding | rs2(rs) | rn(rn) | rt(rt) | (acquire ? 1 : 0) << LDADDAcquireOffset | (release ? 1 : 0) << LDADDReleaseOffset);
+    }
+
     /* PC-relative Address Calculation (5.4.4) */
 
     /**
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.aarch64/src/org/graalvm/compiler/asm/aarch64/AArch64MacroAssembler.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.aarch64/src/org/graalvm/compiler/asm/aarch64/AArch64MacroAssembler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -641,6 +641,26 @@
     }
 
     /**
+     * dst = src + immediate.
+     *
+     * @param size register size. Has to be 32 or 64.
+     * @param dst general purpose register. May not be null or zero-register.
+     * @param src general purpose register. May not be null or zero-register.
+     * @param immediate 64-bit signed int
+     */
+    public void add(int size, Register dst, Register src, long immediate) {
+        if (NumUtil.isInt(immediate)) {
+            add(size, dst, src, (int) immediate);
+        } else {
+            assert (!dst.equals(zr) && !src.equals(zr));
+            assert !dst.equals(src);
+            assert size == 64;
+            mov(dst, immediate);
+            add(size, src, dst, dst);
+        }
+    }
+
+    /**
      * dst = src + aimm and sets condition flags.
      *
      * @param size register size. Has to be 32 or 64.
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.amd64/src/org/graalvm/compiler/asm/amd64/AMD64Assembler.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.amd64/src/org/graalvm/compiler/asm/amd64/AMD64Assembler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1859,7 +1859,7 @@
      * values were equal, and cleared otherwise.
      */
     public final void cmpxchgb(Register reg, AMD64Address adr) { // cmpxchg
-        prefix(adr, reg);
+        prefixb(adr, reg);
         emitByte(0x0F);
         emitByte(0xB0);
         emitOperandHelper(reg, adr, 0);
@@ -2136,7 +2136,7 @@
 
     public final void movb(AMD64Address dst, Register src) {
         assert src.getRegisterCategory().equals(AMD64.CPU) : "must have byte register";
-        prefix(dst, src, true);
+        prefixb(dst, src);
         emitByte(0x88);
         emitOperandHelper(src, dst, 0);
     }
@@ -3282,6 +3282,10 @@
         }
     }
 
+    private void prefixb(AMD64Address adr, Register reg) {
+        prefix(adr, reg, true);
+    }
+
     private void prefix(AMD64Address adr, Register reg) {
         prefix(adr, reg, false);
     }
@@ -3705,7 +3709,7 @@
     }
 
     public final void xaddb(AMD64Address dst, Register src) {
-        prefix(dst, src);
+        prefixb(dst, src);
         emitByte(0x0F);
         emitByte(0xC0);
         emitOperandHelper(src, dst, 0);
@@ -3734,7 +3738,7 @@
     }
 
     public final void xchgb(Register dst, AMD64Address src) {
-        prefix(src, dst);
+        prefixb(src, dst);
         emitByte(0x86);
         emitOperandHelper(dst, src, 0);
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.amd64/src/org/graalvm/compiler/asm/amd64/AMD64VectorAssembler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,851 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.asm.amd64;
+
+import java.util.EnumSet;
+
+import org.graalvm.compiler.core.common.calc.Condition;
+import org.graalvm.compiler.debug.GraalError;
+
+import org.graalvm.compiler.asm.amd64.AVXKind.AVXSize;
+
+import jdk.vm.ci.amd64.AMD64;
+import jdk.vm.ci.amd64.AMD64.CPUFeature;
+import jdk.vm.ci.amd64.AMD64Kind;
+import jdk.vm.ci.code.Register;
+import jdk.vm.ci.code.Register.RegisterCategory;
+import jdk.vm.ci.code.TargetDescription;
+
+/**
+ * This class extends the AMD64 assembler with functions that emit instructions from the AVX
+ * extension.
+ */
+public class AMD64VectorAssembler extends AMD64MacroAssembler {
+
+    public AMD64VectorAssembler(TargetDescription target) {
+        super(target);
+        assert ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
+    }
+
+    private static final int L128 = 0;
+    private static final int L256 = 1;
+    private static final int LIG = 0;
+
+    private static final int W0 = 0;
+    private static final int W1 = 1;
+    private static final int WIG = 0;
+
+    private static final int P_ = 0x0;
+    private static final int P_66 = 0x1;
+    private static final int P_F3 = 0x2;
+    private static final int P_F2 = 0x3;
+
+    private static final int M_0F = 0x1;
+    private static final int M_0F38 = 0x2;
+    private static final int M_0F3A = 0x3;
+
+    /**
+     * Low-level function to encode and emit the VEX prefix.
+     * <p>
+     * 2 byte form: [1100 0101] [R vvvv L pp]<br>
+     * 3 byte form: [1100 0100] [RXB m-mmmm] [W vvvv L pp]
+     * <p>
+     * The RXB and vvvv fields are stored in 1's complement in the prefix encoding. This function
+     * performs the 1s complement conversion, the caller is expected to pass plain unencoded
+     * arguments.
+     * <p>
+     * The pp field encodes an extension to the opcode:<br>
+     * 00: no extension<br>
+     * 01: 66<br>
+     * 10: F3<br>
+     * 11: F2
+     * <p>
+     * The m-mmmm field encodes the leading bytes of the opcode:<br>
+     * 00001: implied 0F leading opcode byte (default in 2-byte encoding)<br>
+     * 00010: implied 0F 38 leading opcode bytes<br>
+     * 00011: implied 0F 3A leading opcode bytes
+     * <p>
+     * This function automatically chooses the 2 or 3 byte encoding, based on the XBW flags and the
+     * m-mmmm field.
+     */
+    private void emitVEX(int l, int pp, int mmmmm, int w, int rxb, int vvvv) {
+        assert ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX) : "emitting VEX prefix on a CPU without AVX support";
+
+        assert l == L128 || l == L256 || l == LIG : "invalid value for VEX.L";
+        assert pp == P_ || pp == P_66 || pp == P_F3 || pp == P_F2 : "invalid value for VEX.pp";
+        assert mmmmm == M_0F || mmmmm == M_0F38 || mmmmm == M_0F3A : "invalid value for VEX.m-mmmm";
+        assert w == W0 || w == W1 || w == WIG : "invalid value for VEX.W";
+
+        assert (rxb & 0x07) == rxb : "invalid value for VEX.RXB";
+        assert (vvvv & 0x0F) == vvvv : "invalid value for VEX.vvvv";
+
+        int rxb1s = rxb ^ 0x07;
+        int vvvv1s = vvvv ^ 0x0F;
+        if ((rxb & 0x03) == 0 && w == WIG && mmmmm == M_0F) {
+            // 2 byte encoding
+            int byte2 = 0;
+            byte2 |= (rxb1s & 0x04) << 5;
+            byte2 |= vvvv1s << 3;
+            byte2 |= l << 2;
+            byte2 |= pp;
+
+            emitByte(0xC5);
+            emitByte(byte2);
+        } else {
+            // 3 byte encoding
+            int byte2 = 0;
+            byte2 = (rxb1s & 0x07) << 5;
+            byte2 |= mmmmm;
+
+            int byte3 = 0;
+            byte3 |= w << 7;
+            byte3 |= vvvv1s << 3;
+            byte3 |= l << 2;
+            byte3 |= pp;
+
+            emitByte(0xC4);
+            emitByte(byte2);
+            emitByte(byte3);
+        }
+    }
+
+    private static int getLFlag(AVXSize size) {
+        switch (size) {
+            case XMM:
+                return L128;
+            case YMM:
+                return L256;
+            default:
+                return LIG;
+        }
+    }
+
+    /**
+     * Emit instruction with VEX prefix and two register operands.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, Register rm) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), 0);
+        emitByte(op);
+        emitModRM(reg, rm);
+    }
+
+    /**
+     * Emit instruction with VEX prefix and three register operands.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, Register vvvv, Register rm) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), vvvv.encoding());
+        emitByte(op);
+        emitModRM(reg, rm);
+    }
+
+    /**
+     * Emit instruction with VEX prefix and four register operands.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M] [Imm8[7:4]]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, Register vvvv, Register rm, Register imm8) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), vvvv.encoding());
+        emitByte(op);
+        emitModRM(reg, rm);
+        emitByte(imm8.encoding() << 4);
+    }
+
+    /**
+     * Emit instruction with VEX prefix and three register operands and one memory operand.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M] [Imm8[7:4]]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, Register vvvv, AMD64Address rm, Register imm8, int additionalInstructionSize) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), vvvv.encoding());
+        emitByte(op);
+        emitOperandHelper(reg, rm, additionalInstructionSize);
+        emitByte(imm8.encoding() << 4);
+    }
+
+    /**
+     * Emit instruction with VEX prefix and two register operands and an opcode extension in the r
+     * field.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, int r, Register vvvv, Register rm) {
+        emitVEX(l, pp, mmmmm, w, getRXB(null, rm), vvvv.encoding());
+        emitByte(op);
+        emitModRM(r, rm);
+    }
+
+    /**
+     * Emit instruction with VEX prefix, one register operand and one memory operand.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M] [SIB] [Disp]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, AMD64Address rm, int additionalInstructionSize) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), 0);
+        emitByte(op);
+        emitOperandHelper(reg, rm, additionalInstructionSize);
+    }
+
+    /**
+     * Emit instruction with VEX prefix, two register operands and one memory operand.
+     * <p>
+     * Format: [VEX] [Opcode] [ModR/M] [SIB] [Disp]
+     */
+    private void emitVexOp(int l, int pp, int mmmmm, int w, int op, Register reg, Register vvvv, AMD64Address rm, int additionalInstructionSize) {
+        emitVEX(l, pp, mmmmm, w, getRXB(reg, rm), vvvv.encoding());
+        emitByte(op);
+        emitOperandHelper(reg, rm, additionalInstructionSize);
+    }
+
+    private static final OpAssertion AVX1 = new OpAssertion(CPUFeature.AVX, CPUFeature.AVX);
+    private static final OpAssertion AVX1_2 = new OpAssertion(CPUFeature.AVX, CPUFeature.AVX2);
+    private static final OpAssertion AVX2 = new OpAssertion(CPUFeature.AVX2, CPUFeature.AVX2);
+
+    private static final OpAssertion AVX1_128ONLY = new OpAssertion(CPUFeature.AVX, null);
+    private static final OpAssertion AVX1_256ONLY = new OpAssertion(null, CPUFeature.AVX);
+    private static final OpAssertion AVX2_256ONLY = new OpAssertion(null, CPUFeature.AVX2);
+
+    private static final OpAssertion XMM_CPU = new OpAssertion(CPUFeature.AVX, null, AMD64.XMM, null, AMD64.CPU, null);
+    private static final OpAssertion XMM_XMM_CPU = new OpAssertion(CPUFeature.AVX, null, AMD64.XMM, AMD64.XMM, AMD64.CPU, null);
+    private static final OpAssertion CPU_XMM = new OpAssertion(CPUFeature.AVX, null, AMD64.CPU, null, AMD64.XMM, null);
+
+    private static final class OpAssertion {
+        private final CPUFeature avx128feature;
+        private final CPUFeature avx256feature;
+
+        private final RegisterCategory rCategory;
+        private final RegisterCategory vCategory;
+        private final RegisterCategory mCategory;
+        private final RegisterCategory imm8Category;
+
+        private OpAssertion(CPUFeature avx128feature, CPUFeature avx256feature) {
+            this(avx128feature, avx256feature, AMD64.XMM, AMD64.XMM, AMD64.XMM, AMD64.XMM);
+        }
+
+        private OpAssertion(CPUFeature avx128feature, CPUFeature avx256feature, RegisterCategory rCategory, RegisterCategory vCategory, RegisterCategory mCategory, RegisterCategory imm8Category) {
+            this.avx128feature = avx128feature;
+            this.avx256feature = avx256feature;
+            this.rCategory = rCategory;
+            this.vCategory = vCategory;
+            this.mCategory = mCategory;
+            this.imm8Category = imm8Category;
+        }
+
+        public boolean check(AMD64 arch, AVXSize size, Register r, Register v, Register m) {
+            return check(arch, size, r, v, m, null);
+        }
+
+        public boolean check(AMD64 arch, AVXSize size, Register r, Register v, Register m, Register imm8) {
+            switch (size) {
+                case XMM:
+                    assert avx128feature != null && arch.getFeatures().contains(avx128feature) : "emitting illegal 128 bit instruction";
+                    break;
+                case YMM:
+                    assert avx256feature != null && arch.getFeatures().contains(avx256feature) : "emitting illegal 256 bit instruction";
+                    break;
+            }
+            if (r != null) {
+                assert r.getRegisterCategory().equals(rCategory);
+            }
+            if (v != null) {
+                assert v.getRegisterCategory().equals(vCategory);
+            }
+            if (m != null) {
+                assert m.getRegisterCategory().equals(mCategory);
+            }
+            if (imm8 != null) {
+                assert imm8.getRegisterCategory().equals(imm8Category);
+            }
+            return true;
+        }
+
+        public boolean supports(EnumSet<CPUFeature> features, AVXSize avxSize) {
+            switch (avxSize) {
+                case XMM:
+                    return features.contains(avx128feature);
+                case YMM:
+                    return features.contains(avx256feature);
+                default:
+                    throw GraalError.shouldNotReachHere();
+            }
+        }
+    }
+
+    /**
+     * Base class for VEX-encoded instructions.
+     */
+    private static class VexOp {
+        protected final int pp;
+        protected final int mmmmm;
+        protected final int w;
+        protected final int op;
+
+        private final String opcode;
+        protected final OpAssertion assertion;
+
+        protected VexOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            this.pp = pp;
+            this.mmmmm = mmmmm;
+            this.w = w;
+            this.op = op;
+            this.opcode = opcode;
+            this.assertion = assertion;
+        }
+
+        public boolean isSupported(AMD64VectorAssembler vasm, AMD64Kind kind) {
+            return assertion.supports(((AMD64) vasm.target.arch).getFeatures(), AVXKind.getRegisterSize(kind));
+        }
+
+        @Override
+        public String toString() {
+            return opcode;
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RM, but the M operand must be a register.
+     */
+    public static class VexRROp extends VexOp {
+        // @formatter:off
+        public static final VexRROp VMASKMOVDQU = new VexRROp("VMASKMOVDQU", P_66, M_0F, WIG, 0xF7, AVX1_128ONLY);
+        // @formatter:on
+
+        protected VexRROp(String opcode, int pp, int mmmmm, int w, int op) {
+            this(opcode, pp, mmmmm, w, op, AVX1);
+        }
+
+        protected VexRROp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, null, src);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src);
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RM.
+     */
+    public static class VexRMOp extends VexRROp {
+        // @formatter:off
+        public static final VexRMOp VCVTTSS2SI     = new VexRMOp("VCVTTSS2SI",     P_F3, M_0F,   W0,  0x2C, CPU_XMM);
+        public static final VexRMOp VCVTTSS2SQ     = new VexRMOp("VCVTTSS2SQ",     P_F3, M_0F,   W1,  0x2C, CPU_XMM);
+        public static final VexRMOp VCVTTSD2SI     = new VexRMOp("VCVTTSD2SI",     P_F2, M_0F,   W0,  0x2C, CPU_XMM);
+        public static final VexRMOp VCVTTSD2SQ     = new VexRMOp("VCVTTSD2SQ",     P_F2, M_0F,   W1,  0x2C, CPU_XMM);
+        public static final VexRMOp VCVTPS2PD      = new VexRMOp("VCVTPS2PD",      P_,   M_0F,   WIG, 0x5A);
+        public static final VexRMOp VCVTPD2PS      = new VexRMOp("VCVTPD2PS",      P_66, M_0F,   WIG, 0x5A);
+        public static final VexRMOp VCVTDQ2PS      = new VexRMOp("VCVTDQ2PS",      P_,   M_0F,   WIG, 0x5B);
+        public static final VexRMOp VCVTTPS2DQ     = new VexRMOp("VCVTTPS2DQ",     P_F3, M_0F,   WIG, 0x5B);
+        public static final VexRMOp VCVTTPD2DQ     = new VexRMOp("VCVTTPD2DQ",     P_66, M_0F,   WIG, 0xE6);
+        public static final VexRMOp VCVTDQ2PD      = new VexRMOp("VCVTDQ2PD",      P_F3, M_0F,   WIG, 0xE6);
+        public static final VexRMOp VBROADCASTSS   = new VexRMOp("VBROADCASTSS",   P_66, M_0F38, W0,  0x18);
+        public static final VexRMOp VBROADCASTSD   = new VexRMOp("VBROADCASTSD",   P_66, M_0F38, W0,  0x19, AVX1_256ONLY);
+        public static final VexRMOp VBROADCASTF128 = new VexRMOp("VBROADCASTF128", P_66, M_0F38, W0,  0x1A, AVX1_256ONLY);
+        public static final VexRMOp VBROADCASTI128 = new VexRMOp("VBROADCASTI128", P_66, M_0F38, W0,  0x5A, AVX2_256ONLY);
+        public static final VexRMOp VPBROADCASTB   = new VexRMOp("VPBROADCASTB",   P_66, M_0F38, W0,  0x78, AVX2);
+        public static final VexRMOp VPBROADCASTW   = new VexRMOp("VPBROADCASTW",   P_66, M_0F38, W0,  0x79, AVX2);
+        public static final VexRMOp VPBROADCASTD   = new VexRMOp("VPBROADCASTD",   P_66, M_0F38, W0,  0x58, AVX2);
+        public static final VexRMOp VPBROADCASTQ   = new VexRMOp("VPBROADCASTQ",   P_66, M_0F38, W0,  0x59, AVX2);
+        public static final VexRMOp VPMOVSXBW      = new VexRMOp("VPMOVSXBW",      P_66, M_0F38, WIG, 0x20);
+        public static final VexRMOp VPMOVSXBD      = new VexRMOp("VPMOVSXBD",      P_66, M_0F38, WIG, 0x21);
+        public static final VexRMOp VPMOVSXBQ      = new VexRMOp("VPMOVSXBQ",      P_66, M_0F38, WIG, 0x22);
+        public static final VexRMOp VPMOVSXWD      = new VexRMOp("VPMOVSXWD",      P_66, M_0F38, WIG, 0x23);
+        public static final VexRMOp VPMOVSXWQ      = new VexRMOp("VPMOVSXWQ",      P_66, M_0F38, WIG, 0x24);
+        public static final VexRMOp VPMOVSXDQ      = new VexRMOp("VPMOVSXDQ",      P_66, M_0F38, WIG, 0x25);
+        public static final VexRMOp VPMOVZXBW      = new VexRMOp("VPMOVZXBW",      P_66, M_0F38, WIG, 0x30);
+        public static final VexRMOp VPMOVZXBD      = new VexRMOp("VPMOVZXBD",      P_66, M_0F38, WIG, 0x31);
+        public static final VexRMOp VPMOVZXBQ      = new VexRMOp("VPMOVZXBQ",      P_66, M_0F38, WIG, 0x32);
+        public static final VexRMOp VPMOVZXWD      = new VexRMOp("VPMOVZXWD",      P_66, M_0F38, WIG, 0x33);
+        public static final VexRMOp VPMOVZXWQ      = new VexRMOp("VPMOVZXWQ",      P_66, M_0F38, WIG, 0x34);
+        public static final VexRMOp VPMOVZXDQ      = new VexRMOp("VPMOVZXDQ",      P_66, M_0F38, WIG, 0x35);
+        public static final VexRMOp VSQRTPD        = new VexRMOp("VSQRTPD",        P_66, M_0F,   WIG, 0x51);
+        public static final VexRMOp VSQRTPS        = new VexRMOp("VSQRTPS",        P_,   M_0F,   WIG, 0x51);
+        public static final VexRMOp VSQRTSD        = new VexRMOp("VSQRTSD",        P_F2, M_0F,   WIG, 0x51);
+        public static final VexRMOp VSQRTSS        = new VexRMOp("VSQRTSS",        P_F3, M_0F,   WIG, 0x51);
+        public static final VexRMOp VUCOMISS       = new VexRMOp("VUCOMISS",       P_,   M_0F,   WIG, 0x2E);
+        public static final VexRMOp VUCOMISD       = new VexRMOp("VUCOMISD",       P_66, M_0F,   WIG, 0x2E);
+        // @formatter:on
+
+        protected VexRMOp(String opcode, int pp, int mmmmm, int w, int op) {
+            this(opcode, pp, mmmmm, w, op, AVX1);
+        }
+
+        protected VexRMOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, AMD64Address src) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, null, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src, 0);
+        }
+    }
+
+    /**
+     * VEX-encoded move instructions.
+     * <p>
+     * These instructions have two opcodes: op is the forward move instruction with an operand order
+     * of RM, and opReverse is the reverse move instruction with an operand order of MR.
+     */
+    public static final class VexMoveOp extends VexRMOp {
+        // @formatter:off
+        public static final VexMoveOp VMOVDQA = new VexMoveOp("VMOVDQA", P_66, M_0F, WIG, 0x6F, 0x7F);
+        public static final VexMoveOp VMOVDQU = new VexMoveOp("VMOVDQU", P_F3, M_0F, WIG, 0x6F, 0x7F);
+        public static final VexMoveOp VMOVAPS = new VexMoveOp("VMOVAPS", P_,   M_0F, WIG, 0x28, 0x29);
+        public static final VexMoveOp VMOVAPD = new VexMoveOp("VMOVAPD", P_66, M_0F, WIG, 0x28, 0x29);
+        public static final VexMoveOp VMOVUPS = new VexMoveOp("VMOVUPS", P_,   M_0F, WIG, 0x10, 0x11);
+        public static final VexMoveOp VMOVUPD = new VexMoveOp("VMOVUPD", P_66, M_0F, WIG, 0x10, 0x11);
+        public static final VexMoveOp VMOVSS  = new VexMoveOp("VMOVSS",  P_F3, M_0F, WIG, 0x10, 0x11);
+        public static final VexMoveOp VMOVSD  = new VexMoveOp("VMOVSD",  P_F2, M_0F, WIG, 0x10, 0x11);
+        public static final VexMoveOp VMOVD   = new VexMoveOp("VMOVD",   P_66, M_0F, W0,  0x6E, 0x7E, XMM_CPU);
+        public static final VexMoveOp VMOVQ   = new VexMoveOp("VMOVQ",   P_66, M_0F, W1,  0x6E, 0x7E, XMM_CPU);
+        // @formatter:on
+
+        private final int opReverse;
+
+        private VexMoveOp(String opcode, int pp, int mmmmm, int w, int op, int opReverse) {
+            this(opcode, pp, mmmmm, w, op, opReverse, AVX1);
+        }
+
+        private VexMoveOp(String opcode, int pp, int mmmmm, int w, int op, int opReverse, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+            this.opReverse = opReverse;
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, AMD64Address dst, Register src) {
+            assert assertion.check((AMD64) asm.target.arch, size, src, null, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, opReverse, src, dst, 0);
+        }
+
+        public void emitReverse(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src) {
+            assert assertion.check((AMD64) asm.target.arch, size, src, null, dst);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, opReverse, src, dst);
+        }
+    }
+
+    public interface VexRRIOp {
+        void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src, int imm8);
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RMI.
+     */
+    public static final class VexRMIOp extends VexOp implements VexRRIOp {
+        // @formatter:off
+        public static final VexRMIOp VPERMQ   = new VexRMIOp("VPERMQ",   P_66, M_0F3A, W1,  0x00, AVX2_256ONLY);
+        public static final VexRMIOp VPSHUFLW = new VexRMIOp("VPSHUFLW", P_F2, M_0F,   WIG, 0x70, AVX1_2);
+        public static final VexRMIOp VPSHUFHW = new VexRMIOp("VPSHUFHW", P_F3, M_0F,   WIG, 0x70, AVX1_2);
+        public static final VexRMIOp VPSHUFD  = new VexRMIOp("VPSHUFD",  P_66, M_0F,   WIG, 0x70, AVX1_2);
+        // @formatter:on
+
+        private VexRMIOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        @Override
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, null, src);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src);
+            asm.emitByte(imm8);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, AMD64Address src, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, null, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src, 1);
+            asm.emitByte(imm8);
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of MRI.
+     */
+    public static final class VexMRIOp extends VexOp implements VexRRIOp {
+        // @formatter:off
+        public static final VexMRIOp VEXTRACTF128 = new VexMRIOp("VEXTRACTF128", P_66, M_0F3A, W0, 0x19, AVX1_256ONLY);
+        public static final VexMRIOp VEXTRACTI128 = new VexMRIOp("VEXTRACTI128", P_66, M_0F3A, W0, 0x39, AVX2_256ONLY);
+        public static final VexMRIOp VPEXTRB      = new VexMRIOp("VPEXTRB",      P_66, M_0F3A, W0, 0x14, XMM_CPU);
+        public static final VexMRIOp VPEXTRW      = new VexMRIOp("VPEXTRW",      P_66, M_0F3A, W0, 0x15, XMM_CPU);
+        public static final VexMRIOp VPEXTRD      = new VexMRIOp("VPEXTRD",      P_66, M_0F3A, W0, 0x16, XMM_CPU);
+        public static final VexMRIOp VPEXTRQ      = new VexMRIOp("VPEXTRQ",      P_66, M_0F3A, W1, 0x16, XMM_CPU);
+        // @formatter:on
+
+        private VexMRIOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        @Override
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, src, null, dst);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, src, dst);
+            asm.emitByte(imm8);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, AMD64Address dst, Register src, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, src, null, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, src, dst, 1);
+            asm.emitByte(imm8);
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RVMR.
+     */
+    public static class VexRVMROp extends VexOp {
+        // @formatter:off
+        public static final VexRVMROp VPBLENDVB  = new VexRVMROp("VPBLENDVB",  P_66, M_0F3A, W0, 0x4C, AVX1_2);
+        public static final VexRVMROp VPBLENDVPS = new VexRVMROp("VPBLENDVPS", P_66, M_0F3A, W0, 0x4A, AVX1);
+        public static final VexRVMROp VPBLENDVPD = new VexRVMROp("VPBLENDVPD", P_66, M_0F3A, W0, 0x4B, AVX1);
+        // @formatter:on
+
+        protected VexRVMROp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register mask, Register src1, Register src2) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, mask, src1, src2);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2, mask);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register mask, Register src1, AMD64Address src2) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, mask, src1, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2, mask, 0);
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RVM.
+     */
+    public static class VexRVMOp extends VexOp {
+        // @formatter:off
+        public static final VexRVMOp VANDPS    = new VexRVMOp("VANDPS",    P_,   M_0F,   WIG, 0x54);
+        public static final VexRVMOp VANDPD    = new VexRVMOp("VANDPD",    P_66, M_0F,   WIG, 0x54);
+        public static final VexRVMOp VORPS     = new VexRVMOp("VORPS",     P_,   M_0F,   WIG, 0x56);
+        public static final VexRVMOp VORPD     = new VexRVMOp("VORPD",     P_66, M_0F,   WIG, 0x56);
+        public static final VexRVMOp VADDPS    = new VexRVMOp("VADDPS",    P_,   M_0F,   WIG, 0x58);
+        public static final VexRVMOp VADDPD    = new VexRVMOp("VADDPD",    P_66, M_0F,   WIG, 0x58);
+        public static final VexRVMOp VADDSS    = new VexRVMOp("VADDSS",    P_F3, M_0F,   WIG, 0x58);
+        public static final VexRVMOp VADDSD    = new VexRVMOp("VADDSD",    P_F2, M_0F,   WIG, 0x58);
+        public static final VexRVMOp VXORPS    = new VexRVMOp("VXORPS",    P_,   M_0F,   WIG, 0x57);
+        public static final VexRVMOp VXORPD    = new VexRVMOp("VXORPD",    P_66, M_0F,   WIG, 0x57);
+        public static final VexRVMOp VMULPS    = new VexRVMOp("VMULPS",    P_,   M_0F,   WIG, 0x59);
+        public static final VexRVMOp VMULPD    = new VexRVMOp("VMULPD",    P_66, M_0F,   WIG, 0x59);
+        public static final VexRVMOp VMULSS    = new VexRVMOp("VMULSS",    P_F3, M_0F,   WIG, 0x59);
+        public static final VexRVMOp VMULSD    = new VexRVMOp("VMULSD",    P_F2, M_0F,   WIG, 0x59);
+        public static final VexRVMOp VSUBPS    = new VexRVMOp("VSUBPS",    P_,   M_0F,   WIG, 0x5C);
+        public static final VexRVMOp VSUBPD    = new VexRVMOp("VSUBPD",    P_66, M_0F,   WIG, 0x5C);
+        public static final VexRVMOp VSUBSS    = new VexRVMOp("VSUBSS",    P_F3, M_0F,   WIG, 0x5C);
+        public static final VexRVMOp VSUBSD    = new VexRVMOp("VSUBSD",    P_F2, M_0F,   WIG, 0x5C);
+        public static final VexRVMOp VDIVPS    = new VexRVMOp("VDIVPS",    P_,   M_0F,   WIG, 0x5E);
+        public static final VexRVMOp VDIVPD    = new VexRVMOp("VDIVPD",    P_66, M_0F,   WIG, 0x5E);
+        public static final VexRVMOp VDIVSS    = new VexRVMOp("VDIVPS",    P_F3, M_0F,   WIG, 0x5E);
+        public static final VexRVMOp VDIVSD    = new VexRVMOp("VDIVPD",    P_F2, M_0F,   WIG, 0x5E);
+        public static final VexRVMOp VADDSUBPS = new VexRVMOp("VADDSUBPS", P_F2, M_0F,   WIG, 0xD0);
+        public static final VexRVMOp VADDSUBPD = new VexRVMOp("VADDSUBPD", P_66, M_0F,   WIG, 0xD0);
+        public static final VexRVMOp VPAND     = new VexRVMOp("VPAND",     P_66, M_0F,   WIG, 0xDB, AVX1_2);
+        public static final VexRVMOp VPOR      = new VexRVMOp("VPOR",      P_66, M_0F,   WIG, 0xEB, AVX1_2);
+        public static final VexRVMOp VPXOR     = new VexRVMOp("VPXOR",     P_66, M_0F,   WIG, 0xEF, AVX1_2);
+        public static final VexRVMOp VPADDB    = new VexRVMOp("VPADDB",    P_66, M_0F,   WIG, 0xFC, AVX1_2);
+        public static final VexRVMOp VPADDW    = new VexRVMOp("VPADDW",    P_66, M_0F,   WIG, 0xFD, AVX1_2);
+        public static final VexRVMOp VPADDD    = new VexRVMOp("VPADDD",    P_66, M_0F,   WIG, 0xFE, AVX1_2);
+        public static final VexRVMOp VPADDQ    = new VexRVMOp("VPADDQ",    P_66, M_0F,   WIG, 0xD4, AVX1_2);
+        public static final VexRVMOp VPMULHUW  = new VexRVMOp("VPMULHUW",  P_66, M_0F,   WIG, 0xE4, AVX1_2);
+        public static final VexRVMOp VPMULHW   = new VexRVMOp("VPMULHW",   P_66, M_0F,   WIG, 0xE5, AVX1_2);
+        public static final VexRVMOp VPMULLW   = new VexRVMOp("VPMULLW",   P_66, M_0F,   WIG, 0xD5, AVX1_2);
+        public static final VexRVMOp VPMULLD   = new VexRVMOp("VPMULLD",   P_66, M_0F38, WIG, 0x40, AVX1_2);
+        public static final VexRVMOp VPSUBB    = new VexRVMOp("VPSUBB",    P_66, M_0F,   WIG, 0xF8, AVX1_2);
+        public static final VexRVMOp VPSUBW    = new VexRVMOp("VPSUBW",    P_66, M_0F,   WIG, 0xF9, AVX1_2);
+        public static final VexRVMOp VPSUBD    = new VexRVMOp("VPSUBD",    P_66, M_0F,   WIG, 0xFA, AVX1_2);
+        public static final VexRVMOp VPSUBQ    = new VexRVMOp("VPSUBQ",    P_66, M_0F,   WIG, 0xFB, AVX1_2);
+        public static final VexRVMOp VPSHUFB   = new VexRVMOp("VPSHUFB",   P_66, M_0F38, WIG, 0x00, AVX1_2);
+        public static final VexRVMOp VCVTSD2SS = new VexRVMOp("VCVTSD2SS", P_F2, M_0F,   WIG, 0x5A);
+        public static final VexRVMOp VCVTSS2SD = new VexRVMOp("VCVTSS2SD", P_F3, M_0F,   WIG, 0x5A);
+        public static final VexRVMOp VCVTSI2SD = new VexRVMOp("VCVTSI2SD", P_F2, M_0F,   W0,  0x2A, XMM_XMM_CPU);
+        public static final VexRVMOp VCVTSQ2SD = new VexRVMOp("VCVTSQ2SD", P_F2, M_0F,   W1,  0x2A, XMM_XMM_CPU);
+        public static final VexRVMOp VCVTSI2SS = new VexRVMOp("VCVTSI2SS", P_F3, M_0F,   W0,  0x2A, XMM_XMM_CPU);
+        public static final VexRVMOp VCVTSQ2SS = new VexRVMOp("VCVTSQ2SS", P_F3, M_0F,   W1,  0x2A, XMM_XMM_CPU);
+        public static final VexRVMOp VPCMPEQB  = new VexRVMOp("VPCMPEQB",  P_66, M_0F,   WIG, 0x74, AVX1_2);
+        public static final VexRVMOp VPCMPEQW  = new VexRVMOp("VPCMPEQW",  P_66, M_0F,   WIG, 0x75, AVX1_2);
+        public static final VexRVMOp VPCMPEQD  = new VexRVMOp("VPCMPEQD",  P_66, M_0F,   WIG, 0x76, AVX1_2);
+        public static final VexRVMOp VPCMPEQQ  = new VexRVMOp("VPCMPEQQ",  P_66, M_0F38, WIG, 0x76, AVX1_2);
+        public static final VexRVMOp VPCMPGTB  = new VexRVMOp("VPCMPGTB",  P_66, M_0F,   WIG, 0x64, AVX1_2);
+        public static final VexRVMOp VPCMPGTW  = new VexRVMOp("VPCMPGTW",  P_66, M_0F,   WIG, 0x65, AVX1_2);
+        public static final VexRVMOp VPCMPGTD  = new VexRVMOp("VPCMPGTD",  P_66, M_0F,   WIG, 0x66, AVX1_2);
+        public static final VexRVMOp VPCMPGTQ  = new VexRVMOp("VPCMPGTQ",  P_66, M_0F38, WIG, 0x37, AVX1_2);
+        // @formatter:on
+
+        private VexRVMOp(String opcode, int pp, int mmmmm, int w, int op) {
+            this(opcode, pp, mmmmm, w, op, AVX1);
+        }
+
+        protected VexRVMOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, Register src2) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, src2);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, AMD64Address src2) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2, 0);
+        }
+    }
+
+    /**
+     * VEX-encoded shift instructions with an operand order of either RVM or VMI.
+     */
+    public static final class VexShiftOp extends VexRVMOp implements VexRRIOp {
+        // @formatter:off
+        public static final VexShiftOp VPSRLW = new VexShiftOp("VPSRLW", P_66, M_0F, WIG, 0xD1, 0x71, 2);
+        public static final VexShiftOp VPSRLD = new VexShiftOp("VPSRLD", P_66, M_0F, WIG, 0xD2, 0x72, 2);
+        public static final VexShiftOp VPSRLQ = new VexShiftOp("VPSRLQ", P_66, M_0F, WIG, 0xD3, 0x73, 2);
+        public static final VexShiftOp VPSRAW = new VexShiftOp("VPSRAW", P_66, M_0F, WIG, 0xE1, 0x71, 4);
+        public static final VexShiftOp VPSRAD = new VexShiftOp("VPSRAD", P_66, M_0F, WIG, 0xE2, 0x72, 4);
+        public static final VexShiftOp VPSLLW = new VexShiftOp("VPSLLW", P_66, M_0F, WIG, 0xF1, 0x71, 6);
+        public static final VexShiftOp VPSLLD = new VexShiftOp("VPSLLD", P_66, M_0F, WIG, 0xF2, 0x72, 6);
+        public static final VexShiftOp VPSLLQ = new VexShiftOp("VPSLLQ", P_66, M_0F, WIG, 0xF3, 0x73, 6);
+        // @formatter:on
+
+        private final int immOp;
+        private final int r;
+
+        private VexShiftOp(String opcode, int pp, int mmmmm, int w, int op, int immOp, int r) {
+            super(opcode, pp, mmmmm, w, op, AVX1_2);
+            this.immOp = immOp;
+            this.r = r;
+        }
+
+        @Override
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, null, dst, src);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, immOp, r, dst, src);
+            asm.emitByte(imm8);
+        }
+    }
+
+    public static final class VexMaskMoveOp extends VexOp {
+        // @formatter:off
+        public static final VexMaskMoveOp VMASKMOVPS = new VexMaskMoveOp("VMASKMOVPS", P_66, M_0F38, W0, 0x2C, 0x2E);
+        public static final VexMaskMoveOp VMASKMOVPD = new VexMaskMoveOp("VMASKMOVPD", P_66, M_0F38, W0, 0x2D, 0x2F);
+        public static final VexMaskMoveOp VPMASKMOVD = new VexMaskMoveOp("VPMASKMOVD", P_66, M_0F38, W0, 0x8C, 0x8E, AVX2);
+        public static final VexMaskMoveOp VPMASKMOVQ = new VexMaskMoveOp("VPMASKMOVQ", P_66, M_0F38, W1, 0x8C, 0x8E, AVX2);
+        // @formatter:on
+
+        private final int opReverse;
+
+        private VexMaskMoveOp(String opcode, int pp, int mmmmm, int w, int op, int opReverse) {
+            this(opcode, pp, mmmmm, w, op, opReverse, AVX1);
+        }
+
+        private VexMaskMoveOp(String opcode, int pp, int mmmmm, int w, int op, int opReverse, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+            this.opReverse = opReverse;
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register mask, AMD64Address src) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, mask, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, mask, src, 0);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, AMD64Address dst, Register mask, Register src) {
+            assert assertion.check((AMD64) asm.target.arch, size, src, mask, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, opReverse, src, mask, dst, 0);
+        }
+    }
+
+    /**
+     * VEX-encoded instructions with an operand order of RVMI.
+     */
+    public static final class VexRVMIOp extends VexOp {
+        // @formatter:off
+        public static final VexRVMIOp VSHUFPS     = new VexRVMIOp("VSHUFPS",     P_,   M_0F,   WIG, 0xC6);
+        public static final VexRVMIOp VSHUFPD     = new VexRVMIOp("VSHUFPD",     P_66, M_0F,   WIG, 0xC6);
+        public static final VexRVMIOp VINSERTF128 = new VexRVMIOp("VINSERTF128", P_66, M_0F3A, W0,  0x18, AVX1_256ONLY);
+        public static final VexRVMIOp VINSERTI128 = new VexRVMIOp("VINSERTI128", P_66, M_0F3A, W0,  0x38, AVX2_256ONLY);
+        // @formatter:on
+
+        private VexRVMIOp(String opcode, int pp, int mmmmm, int w, int op) {
+            this(opcode, pp, mmmmm, w, op, AVX1);
+        }
+
+        private VexRVMIOp(String opcode, int pp, int mmmmm, int w, int op, OpAssertion assertion) {
+            super(opcode, pp, mmmmm, w, op, assertion);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, Register src2, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, src2);
+            assert (imm8 & 0xFF) == imm8;
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2);
+            asm.emitByte(imm8);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, AMD64Address src2, int imm8) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, null);
+            assert (imm8 & 0xFF) == imm8;
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2, 1);
+            asm.emitByte(imm8);
+        }
+    }
+
+    /**
+     * VEX-encoded comparison operation with an operand order of RVMI. The immediate operand is a
+     * comparison operator.
+     */
+    public static final class VexFloatCompareOp extends VexOp {
+        // @formatter:off
+        public static final VexFloatCompareOp VCMPPS = new VexFloatCompareOp("VCMPPS", P_,   M_0F, WIG, 0xC2);
+        public static final VexFloatCompareOp VCMPPD = new VexFloatCompareOp("VCMPPD", P_66, M_0F, WIG, 0xC2);
+        public static final VexFloatCompareOp VCMPSS = new VexFloatCompareOp("VCMPSS", P_F2, M_0F, WIG, 0xC2);
+        public static final VexFloatCompareOp VCMPSD = new VexFloatCompareOp("VCMPSD", P_F2, M_0F, WIG, 0xC2);
+        // @formatter:on
+
+        public enum Predicate {
+            EQ_OQ(0x00),
+            LT_OS(0x01),
+            LE_OS(0x02),
+            UNORD_Q(0x03),
+            NEQ_UQ(0x04),
+            NLT_US(0x05),
+            NLE_US(0x06),
+            ORD_Q(0x07),
+            EQ_UQ(0x08),
+            NGE_US(0x09),
+            NGT_US(0x0a),
+            FALSE_OQ(0x0b),
+            NEQ_OQ(0x0c),
+            GE_OS(0x0d),
+            GT_OS(0x0e),
+            TRUE_UQ(0x0f),
+            EQ_OS(0x10),
+            LT_OQ(0x11),
+            LE_OQ(0x12),
+            UNORD_S(0x13),
+            NEQ_US(0x14),
+            NLT_UQ(0x15),
+            NLE_UQ(0x16),
+            ORD_S(0x17),
+            EQ_US(0x18),
+            NGE_UQ(0x19),
+            NGT_UQ(0x1a),
+            FALSE_OS(0x1b),
+            NEQ_OS(0x1c),
+            GE_OQ(0x1d),
+            GT_OQ(0x1e),
+            TRUE_US(0x1f);
+
+            private int imm8;
+
+            Predicate(int imm8) {
+                this.imm8 = imm8;
+            }
+
+            public static Predicate getPredicate(Condition condition, boolean unorderedIsTrue) {
+                if (unorderedIsTrue) {
+                    switch (condition) {
+                        case EQ:
+                            return EQ_UQ;
+                        case NE:
+                            return NEQ_UQ;
+                        case LT:
+                            return NGE_UQ;
+                        case LE:
+                            return NGT_UQ;
+                        case GT:
+                            return NLE_UQ;
+                        case GE:
+                            return NLT_UQ;
+                        default:
+                            throw GraalError.shouldNotReachHere();
+                    }
+                } else {
+                    switch (condition) {
+                        case EQ:
+                            return EQ_OQ;
+                        case NE:
+                            return NEQ_OQ;
+                        case LT:
+                            return LT_OQ;
+                        case LE:
+                            return LE_OQ;
+                        case GT:
+                            return GT_OQ;
+                        case GE:
+                            return GE_OQ;
+                        default:
+                            throw GraalError.shouldNotReachHere();
+                    }
+                }
+            }
+        }
+
+        private VexFloatCompareOp(String opcode, int pp, int mmmmm, int w, int op) {
+            super(opcode, pp, mmmmm, w, op, AVX1);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, Register src2, Predicate p) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, src2);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2);
+            asm.emitByte(p.imm8);
+        }
+
+        public void emit(AMD64VectorAssembler asm, AVXSize size, Register dst, Register src1, AMD64Address src2, Predicate p) {
+            assert assertion.check((AMD64) asm.target.arch, size, dst, src1, null);
+            asm.emitVexOp(getLFlag(size), pp, mmmmm, w, op, dst, src1, src2, 1);
+            asm.emitByte(p.imm8);
+        }
+    }
+
+    @Override
+    public void movflt(Register dst, Register src) {
+        VexMoveOp.VMOVAPS.emit(this, AVXSize.XMM, dst, src);
+    }
+
+    @Override
+    public void movflt(Register dst, AMD64Address src) {
+        VexMoveOp.VMOVSS.emit(this, AVXSize.XMM, dst, src);
+    }
+
+    @Override
+    public void movflt(AMD64Address dst, Register src) {
+        VexMoveOp.VMOVSS.emit(this, AVXSize.XMM, dst, src);
+    }
+
+    @Override
+    public void movdbl(Register dst, Register src) {
+        VexMoveOp.VMOVAPD.emit(this, AVXSize.XMM, dst, src);
+    }
+
+    @Override
+    public void movdbl(Register dst, AMD64Address src) {
+        VexMoveOp.VMOVSD.emit(this, AVXSize.XMM, dst, src);
+    }
+
+    @Override
+    public void movdbl(AMD64Address dst, Register src) {
+        VexMoveOp.VMOVSD.emit(this, AVXSize.XMM, dst, src);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.asm.amd64/src/org/graalvm/compiler/asm/amd64/AVXKind.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.asm.amd64;
+
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.DWORD;
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.QWORD;
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.XMM;
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.YMM;
+
+import jdk.vm.ci.meta.Value;
+import org.graalvm.compiler.debug.GraalError;
+
+import jdk.vm.ci.amd64.AMD64Kind;
+
+/**
+ * Helper methods for dealing with AVX and SSE {@link AMD64Kind AMD64Kinds}.
+ */
+public final class AVXKind {
+
+    public enum AVXSize {
+        DWORD,
+        QWORD,
+        XMM,
+        YMM;
+
+        public int getBytes() {
+            switch (this) {
+                case DWORD:
+                    return 4;
+                case QWORD:
+                    return 8;
+                case XMM:
+                    return 16;
+                case YMM:
+                    return 32;
+                default:
+                    return 0;
+            }
+        }
+    }
+
+    private AVXKind() {
+    }
+
+    public static AVXSize getRegisterSize(Value a) {
+        AMD64Kind kind = (AMD64Kind) a.getPlatformKind();
+        if (kind.isXMM()) {
+            return getRegisterSize(kind);
+        } else {
+            return XMM;
+        }
+    }
+
+    public static AVXSize getDataSize(AMD64Kind kind) {
+        assert kind.isXMM() : "unexpected kind " + kind;
+        switch (kind.getSizeInBytes()) {
+            case 4:
+                return DWORD;
+            case 8:
+                return QWORD;
+            case 16:
+                return XMM;
+            case 32:
+                return YMM;
+            default:
+                throw GraalError.shouldNotReachHere("unsupported kind: " + kind);
+        }
+    }
+
+    public static AVXSize getRegisterSize(AMD64Kind kind) {
+        assert kind.isXMM() : "unexpected kind " + kind;
+        if (kind.getSizeInBytes() > 16) {
+            return YMM;
+        } else {
+            return XMM;
+        }
+    }
+
+    public static AMD64Kind changeSize(AMD64Kind kind, AVXSize newSize) {
+        return getAVXKind(kind.getScalar(), newSize);
+    }
+
+    public static AMD64Kind getAVXKind(AMD64Kind base, AVXSize size) {
+        for (AMD64Kind ret : AMD64Kind.values()) {
+            if (ret.getScalar() == base && ret.getSizeInBytes() == size.getBytes()) {
+                return ret;
+            }
+        }
+        throw GraalError.shouldNotReachHere(String.format("unsupported vector kind: %s x %s", size, base));
+    }
+
+    public static AMD64Kind getAVXKind(AMD64Kind base, int length) {
+        for (AMD64Kind ret : AMD64Kind.values()) {
+            if (ret.getScalar() == base && ret.getVectorLength() == length) {
+                return ret;
+            }
+        }
+        throw GraalError.shouldNotReachHere(String.format("unsupported vector kind: %d x %s", length, base));
+    }
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.aarch64/src/org/graalvm/compiler/core/aarch64/AArch64AddressLoweringByUse.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.aarch64/src/org/graalvm/compiler/core/aarch64/AArch64AddressLoweringByUse.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
-  * Copyright (c) 2017, Red Hat Inc. All rights reserved.
+ * Copyright (c) 2017, Red Hat Inc. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.aarch64/src/org/graalvm/compiler/core/aarch64/AArch64LIRGenerator.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.aarch64/src/org/graalvm/compiler/core/aarch64/AArch64LIRGenerator.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,9 +51,12 @@
 import org.graalvm.compiler.lir.aarch64.AArch64ControlFlow.CondMoveOp;
 import org.graalvm.compiler.lir.aarch64.AArch64ControlFlow.StrategySwitchOp;
 import org.graalvm.compiler.lir.aarch64.AArch64ControlFlow.TableSwitchOp;
+import org.graalvm.compiler.lir.aarch64.AArch64LIRFlagsVersioned;
 import org.graalvm.compiler.lir.aarch64.AArch64Move;
 import org.graalvm.compiler.lir.aarch64.AArch64AtomicMove.AtomicReadAndAddOp;
+import org.graalvm.compiler.lir.aarch64.AArch64AtomicMove.AtomicReadAndAddLSEOp;
 import org.graalvm.compiler.lir.aarch64.AArch64AtomicMove.CompareAndSwapOp;
+import org.graalvm.compiler.lir.aarch64.AArch64AtomicMove.AtomicReadAndWriteOp;
 import org.graalvm.compiler.lir.aarch64.AArch64Move.MembarOp;
 import org.graalvm.compiler.lir.aarch64.AArch64PauseOp;
 import org.graalvm.compiler.lir.gen.LIRGenerationResult;
@@ -147,12 +150,21 @@
     }
 
     @Override
+    public Value emitAtomicReadAndWrite(Value address, ValueKind<?> kind, Value newValue) {
+        Variable result = newVariable(kind);
+        Variable scratch = newVariable(kind);
+        append(new AtomicReadAndWriteOp((AArch64Kind) kind.getPlatformKind(), asAllocatable(result), asAllocatable(address), asAllocatable(newValue), asAllocatable(scratch)));
+        return result;
+    }
+
+    @Override
     public Value emitAtomicReadAndAdd(Value address, ValueKind<?> kind, Value delta) {
         Variable result = newVariable(kind);
-        Variable scratch1 = newVariable(kind);
-        Variable scratch2 = newVariable(kind);
-
-        append(new AtomicReadAndAddOp((AArch64Kind) kind.getPlatformKind(), asAllocatable(result), asAllocatable(address), asAllocatable(delta), asAllocatable(scratch1), asAllocatable(scratch2)));
+        if (AArch64LIRFlagsVersioned.useLSE(target().arch)) {
+            append(new AtomicReadAndAddLSEOp((AArch64Kind) kind.getPlatformKind(), asAllocatable(result), asAllocatable(address), asAllocatable(delta)));
+        } else {
+            append(new AtomicReadAndAddOp((AArch64Kind) kind.getPlatformKind(), asAllocatable(result), asAllocatable(address), delta));
+        }
         return result;
     }
 
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/CompareCanonicalizerTest3.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/CompareCanonicalizerTest3.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,7 +27,11 @@
 import org.graalvm.compiler.nodes.ValueNode;
 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
+import org.graalvm.compiler.phases.OptimisticOptimizations;
 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
+import org.graalvm.compiler.phases.common.FrameStateAssignmentPhase;
+import org.graalvm.compiler.phases.common.GuardLoweringPhase;
+import org.graalvm.compiler.phases.tiers.MidTierContext;
 import org.graalvm.compiler.phases.tiers.PhaseContext;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -39,6 +43,7 @@
     @SuppressWarnings("unused") private static int sink0;
     @SuppressWarnings("unused") private static int sink1;
 
+    @Ignore("Subword input cannot be trusted.")
     @Test
     public void test00() {
         assertCanonicallyEqual("integerTestCanonicalization00", "referenceSnippet00");
@@ -232,6 +237,8 @@
         PhaseContext context = new PhaseContext(getProviders());
         CanonicalizerPhase canonicalizer = new CanonicalizerPhase();
         canonicalizer.apply(graph, context);
+        new GuardLoweringPhase().apply(graph, new MidTierContext(getProviders(), getTargetProvider(), OptimisticOptimizations.ALL, graph.getProfilingInfo()));
+        new FrameStateAssignmentPhase().apply(graph);
         canonicalizer.apply(graph, context);
         StructuredGraph referenceGraph = parseEager(reference, AllowAssumptions.YES);
         canonicalizer.apply(referenceGraph, context);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/CustomizedBytecodePatternTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import org.objectweb.asm.Opcodes;
+
+public abstract class CustomizedBytecodePatternTest extends GraalCompilerTest implements Opcodes {
+
+    protected Class<?> getClass(String className) throws ClassNotFoundException {
+        return new CachedLoader(CustomizedBytecodePatternTest.class.getClassLoader(), className).findClass(className);
+    }
+
+    private class CachedLoader extends ClassLoader {
+
+        final String className;
+        Class<?> loaded;
+
+        CachedLoader(ClassLoader parent, String className) {
+            super(parent);
+            this.className = className;
+        }
+
+        @Override
+        protected Class<?> findClass(String name) throws ClassNotFoundException {
+            if (name.equals(className)) {
+                if (loaded == null) {
+                    byte[] gen = generateClass(name.replace('.', '/'));
+                    loaded = defineClass(name, gen, 0, gen.length);
+                }
+                return loaded;
+            } else {
+                return super.findClass(name);
+            }
+        }
+
+    }
+
+    protected abstract byte[] generateClass(String internalClassName);
+
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/GraalCompilerTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/GraalCompilerTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,14 +41,13 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.EnumMap;
-import java.util.HashMap;
 import java.util.List;
 import java.util.ListIterator;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.Supplier;
 
-import jdk.vm.ci.meta.JavaConstant;
 import org.graalvm.compiler.api.directives.GraalDirectives;
 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
 import org.graalvm.compiler.api.test.Graal;
@@ -135,6 +134,7 @@
 import jdk.vm.ci.meta.Assumptions.Assumption;
 import jdk.vm.ci.meta.ConstantReflectionProvider;
 import jdk.vm.ci.meta.DeoptimizationReason;
+import jdk.vm.ci.meta.JavaConstant;
 import jdk.vm.ci.meta.JavaKind;
 import jdk.vm.ci.meta.JavaType;
 import jdk.vm.ci.meta.MetaAccessProvider;
@@ -882,7 +882,7 @@
         }
     }
 
-    private Map<ResolvedJavaMethod, InstalledCode> cache = new HashMap<>();
+    private Map<ResolvedJavaMethod, InstalledCode> cache = new ConcurrentHashMap<>();
 
     /**
      * Gets installed code for a given method, compiling it first if necessary. The graph is parsed
@@ -1075,7 +1075,7 @@
         return backend.createDefaultInstalledCode(debug, method, compilationResult);
     }
 
-    private final Map<ResolvedJavaMethod, Executable> methodMap = new HashMap<>();
+    private final Map<ResolvedJavaMethod, Executable> methodMap = new ConcurrentHashMap<>();
 
     /**
      * Converts a reflection {@link Method} to a {@link ResolvedJavaMethod}.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/NestedArithmeticTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import org.junit.Test;
+
+public class NestedArithmeticTest extends GraalCompilerTest {
+    public static int runNestedLoopTry() {
+        int checksum = 0;
+        int i3 = 240;
+        int i5 = 13485;
+        for (int i4 = 303; i4 > 15; i4 -= 2) {
+            int f = 1;
+            do {
+                try {
+                    i3 = (38726 / i5);
+                    i3 = (i4 % -21500);
+                    i5 = (i3 % 787);
+                } catch (ArithmeticException a_e) {
+                    checksum += f + i3 + i5;
+                    return checksum;
+                }
+                i3 <<= i4;
+                i5 <<= i5;
+                i3 += (8 + (f * f));
+                i5 >>= i5;
+                checksum += f;
+            } while (++f < 11);
+        }
+        return checksum;
+    }
+
+    @Test
+    public void nestedLoopTryTest() {
+        test("runNestedLoopTry");
+    }
+
+    private interface FloatSupplier {
+        float get();
+    }
+
+    private static volatile FloatSupplier problematicFloatValue = new FloatSupplier() {
+        @Override
+        public float get() {
+            return Float.intBitsToFloat(1585051832);
+        }
+    };
+
+    @SuppressWarnings("unused") private static volatile FloatSupplier normalFloatValue = new FloatSupplier() {
+        @Override
+        public float get() {
+            return 0;
+        }
+    };
+
+    public static int absConvert() {
+        int i2 = -51498;
+        int i16 = -12;
+        int i17 = -121;
+        int i18 = 1;
+        int i19 = 11;
+        long l1 = -275151857L;
+        for (int i1 = 21; 22 > i1; ++i1) {
+            float f = problematicFloatValue.get();
+            float absolute = Math.abs(f);
+            i2 = (int) absolute;
+            i2 += i2;
+        }
+        long result = i2 + l1 + i16 + i17 + i18 + i19;
+        return (int) result;
+    }
+
+    @Test
+    public void absConvertTest() {
+        test("absConvert");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordArrayStoreTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.graalvm.compiler.debug.GraalError;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+
+import jdk.vm.ci.meta.JavaKind;
+
+@RunWith(Parameterized.class)
+public class SubWordArrayStoreTest extends CustomizedBytecodePatternTest {
+
+    @Parameterized.Parameters(name = "{0}, {1}, {2}, {3}")
+    public static List<Object[]> data() {
+        ArrayList<Object[]> ret = new ArrayList<>();
+        for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF, 0x01020304}) {
+            for (boolean unsafeStore : new boolean[]{false, true}) {
+                for (boolean unsafeLoad : new boolean[]{false, true}) {
+                    ret.add(new Object[]{JavaKind.Boolean, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Byte, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Short, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Char, i, unsafeStore, unsafeLoad});
+                }
+            }
+        }
+        return ret;
+    }
+
+    private static final String SNIPPET = "snippet";
+
+    private final JavaKind kind;
+    private final int value;
+    private final boolean unsafeStore;
+    private final boolean unsafeLoad;
+
+    public SubWordArrayStoreTest(JavaKind kind, int value, boolean unsafeStore, boolean unsafeLoad) {
+        this.kind = kind;
+        this.value = value;
+        this.unsafeStore = unsafeStore;
+        this.unsafeLoad = unsafeLoad;
+    }
+
+    @Test
+    public void testArrayStore() throws ClassNotFoundException {
+        Class<?> testClass = getClass(SubWordArrayStoreTest.class.getName() + "$" + kind.toString() + "Getter");
+        test(getResolvedJavaMethod(testClass, SNIPPET), null);
+    }
+
+    private static long arrayBaseOffset(JavaKind kind) {
+        switch (kind) {
+            case Boolean:
+                return UNSAFE.arrayBaseOffset(boolean[].class);
+            case Byte:
+                return UNSAFE.arrayBaseOffset(byte[].class);
+            case Short:
+                return UNSAFE.arrayBaseOffset(short[].class);
+            case Char:
+                return UNSAFE.arrayBaseOffset(char[].class);
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    static int toASMType(JavaKind kind) {
+        switch (kind) {
+            case Boolean:
+                return T_BOOLEAN;
+            case Byte:
+                return T_BYTE;
+            case Short:
+                return T_SHORT;
+            case Char:
+                return T_CHAR;
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    private static int toArrayStoreOpcode(JavaKind kind) {
+        switch (kind) {
+            case Boolean:
+            case Byte:
+                return BASTORE;
+            case Short:
+                return SASTORE;
+            case Char:
+                return CASTORE;
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    private static int toArrayLoadOpcode(JavaKind kind) {
+        switch (kind) {
+            case Boolean:
+            case Byte:
+                return BALOAD;
+            case Short:
+                return SALOAD;
+            case Char:
+                return CALOAD;
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    @Override
+    protected byte[] generateClass(String internalClassName) {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
+        cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null);
+
+        final String fieldName = "array";
+        final String fieldDescriptor = "[" + kind.getTypeChar();
+
+        FieldVisitor field = cw.visitField(ACC_PUBLIC | ACC_STATIC, fieldName, fieldDescriptor, null, null);
+        field.visitEnd();
+
+        MethodVisitor clinit = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
+        clinit.visitCode();
+        clinit.visitIntInsn(BIPUSH, 16);
+        clinit.visitIntInsn(NEWARRAY, toASMType(kind));
+        clinit.visitFieldInsn(PUTSTATIC, internalClassName, fieldName, fieldDescriptor);
+        clinit.visitInsn(RETURN);
+        clinit.visitMaxs(1, 0);
+        clinit.visitEnd();
+
+        MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, SNIPPET, "()Z", null, null);
+        snippet.visitCode();
+
+        if (unsafeStore) {
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor);
+            snippet.visitLdcInsn(arrayBaseOffset(kind));
+            snippet.visitLdcInsn(value);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "put" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J" + kind.getTypeChar() + ")V", false);
+        } else {
+            snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor);
+            snippet.visitInsn(ICONST_0);
+            snippet.visitLdcInsn(value);
+            snippet.visitInsn(toArrayStoreOpcode(kind));
+        }
+
+        if (unsafeLoad) {
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor);
+            snippet.visitLdcInsn(arrayBaseOffset(kind));
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "get" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J)" + kind.getTypeChar(), false);
+        } else {
+            snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor);
+            snippet.visitInsn(ICONST_0);
+            snippet.visitInsn(toArrayLoadOpcode(kind));
+        }
+
+        snippet.visitLdcInsn(value);
+        SubWordTestUtil.convertToKind(snippet, kind);
+        SubWordTestUtil.testEqual(snippet);
+
+        snippet.visitMaxs(5, 0);
+        snippet.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordFieldStoreTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Type;
+
+import jdk.vm.ci.meta.JavaKind;
+
+@RunWith(Parameterized.class)
+public class SubWordFieldStoreTest extends CustomizedBytecodePatternTest {
+
+    @Parameterized.Parameters(name = "{0}, {1}, {2}, {3}")
+    public static List<Object[]> data() {
+        ArrayList<Object[]> ret = new ArrayList<>();
+        for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF, 0x01020304}) {
+            for (boolean unsafeStore : new boolean[]{false, true}) {
+                for (boolean unsafeLoad : new boolean[]{false, true}) {
+                    ret.add(new Object[]{JavaKind.Boolean, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Byte, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Short, i, unsafeStore, unsafeLoad});
+                    ret.add(new Object[]{JavaKind.Char, i, unsafeStore, unsafeLoad});
+                }
+            }
+        }
+        return ret;
+    }
+
+    private static final String SNIPPET = "snippet";
+
+    private final JavaKind kind;
+    private final int value;
+    private final boolean unsafeStore;
+    private final boolean unsafeLoad;
+
+    public SubWordFieldStoreTest(JavaKind kind, int value, boolean unsafeStore, boolean unsafeLoad) {
+        this.kind = kind;
+        this.value = value;
+        this.unsafeStore = unsafeStore;
+        this.unsafeLoad = unsafeLoad;
+    }
+
+    @Test
+    public void testFieldStore() throws ClassNotFoundException {
+        Class<?> testClass = getClass(SubWordFieldStoreTest.class.getName() + "$" + kind.toString() + "Getter");
+        test(getResolvedJavaMethod(testClass, SNIPPET), null);
+    }
+
+    @Override
+    protected byte[] generateClass(String internalClassName) {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
+        cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null);
+
+        final String fieldName = "field";
+        final String fieldDescriptor = Character.toString(kind.getTypeChar());
+
+        FieldVisitor field = cw.visitField(ACC_PUBLIC | ACC_STATIC, fieldName, fieldDescriptor, null, value);
+        field.visitEnd();
+
+        MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, SNIPPET, "()Z", null, new String[]{"java/lang/NoSuchFieldException"});
+        snippet.visitCode();
+
+        if (unsafeStore) {
+            snippet.visitLdcInsn(Type.getObjectType(internalClassName));
+            snippet.visitLdcInsn(fieldName);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", false);
+            snippet.visitVarInsn(ASTORE, 0);
+
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitVarInsn(ALOAD, 0);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "staticFieldBase", "(Ljava/lang/reflect/Field;)Ljava/lang/Object;", false);
+            snippet.visitVarInsn(ASTORE, 1);
+
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitVarInsn(ALOAD, 0);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "staticFieldOffset", "(Ljava/lang/reflect/Field;)J", false);
+            snippet.visitVarInsn(LSTORE, 2);
+
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitVarInsn(ALOAD, 1);
+            snippet.visitVarInsn(LLOAD, 2);
+            snippet.visitLdcInsn(value);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "put" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J" + kind.getTypeChar() + ")V", false);
+        } else {
+            snippet.visitLdcInsn(value);
+            snippet.visitFieldInsn(PUTSTATIC, internalClassName, fieldName, fieldDescriptor);
+        }
+
+        if (unsafeLoad) {
+            if (!unsafeStore) {
+                snippet.visitLdcInsn(Type.getObjectType(internalClassName));
+                snippet.visitLdcInsn(fieldName);
+                snippet.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", false);
+                snippet.visitVarInsn(ASTORE, 0);
+
+                SubWordTestUtil.getUnsafe(snippet);
+                snippet.visitVarInsn(ALOAD, 0);
+                snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "staticFieldBase", "(Ljava/lang/reflect/Field;)Ljava/lang/Object;", false);
+                snippet.visitVarInsn(ASTORE, 1);
+
+                SubWordTestUtil.getUnsafe(snippet);
+                snippet.visitVarInsn(ALOAD, 0);
+                snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "staticFieldOffset", "(Ljava/lang/reflect/Field;)J", false);
+                snippet.visitVarInsn(LSTORE, 2);
+            }
+            SubWordTestUtil.getUnsafe(snippet);
+            snippet.visitVarInsn(ALOAD, 1);
+            snippet.visitVarInsn(LLOAD, 2);
+            snippet.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "get" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J)" + kind.getTypeChar(), false);
+        } else {
+            snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor);
+        }
+
+        snippet.visitLdcInsn(value);
+        SubWordTestUtil.convertToKind(snippet, kind);
+        SubWordTestUtil.testEqual(snippet);
+
+        snippet.visitMaxs(5, 4);
+        snippet.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordInputTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.MethodVisitor;
+
+import jdk.vm.ci.meta.DeoptimizationReason;
+import jdk.vm.ci.meta.JavaKind;
+import jdk.vm.ci.meta.ResolvedJavaMethod;
+
+@RunWith(Parameterized.class)
+public class SubWordInputTest extends CustomizedBytecodePatternTest {
+
+    @Parameterized.Parameters(name = "{0}, {1}")
+    public static List<Object[]> data() {
+        ArrayList<Object[]> ret = new ArrayList<>();
+        for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF}) {
+            ret.add(new Object[]{JavaKind.Boolean, i});
+            ret.add(new Object[]{JavaKind.Byte, i});
+            ret.add(new Object[]{JavaKind.Short, i});
+            ret.add(new Object[]{JavaKind.Char, i});
+        }
+        return ret;
+    }
+
+    private static final String GET = "get";
+    private static final String WRAPPER = "wrapper";
+
+    private final JavaKind kind;
+    private final int value;
+
+    public SubWordInputTest(JavaKind kind, int value) {
+        this.kind = kind;
+        this.value = value;
+    }
+
+    @Test
+    public void testSubWordInput() throws ClassNotFoundException {
+        Class<?> testClass = getClass(SubWordInputTest.class.getName() + "$" + kind.toString() + "Getter");
+        ResolvedJavaMethod wrapper = getResolvedJavaMethod(testClass, WRAPPER);
+        Result expected = executeExpected(wrapper, null, value);
+        // test standalone callee
+        getCode(getResolvedJavaMethod(testClass, GET), null, false, true, getInitialOptions());
+        assertEquals(executeExpected(wrapper, null, value), expected);
+        // test with inlining
+        testAgainstExpected(wrapper, expected, Collections.<DeoptimizationReason> emptySet(), null, value);
+    }
+
+    @Override
+    protected byte[] generateClass(String internalClassName) {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
+        cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null);
+
+        final char typeChar = kind.getTypeChar();
+
+        // Generates a method that returns the input subword immediately.
+        String getDescriptor = "(" + typeChar + ")" + typeChar;
+        MethodVisitor get = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, GET, getDescriptor, null, null);
+        get.visitCode();
+        get.visitVarInsn(ILOAD, 0);
+        get.visitInsn(IRETURN);
+        get.visitMaxs(1, 1);
+        get.visitEnd();
+
+        // Genearates a method that compares the return value of the preceding method by passing the
+        // input value, and a manual masking of the input value.
+        MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, WRAPPER, "(I)Z", null, null);
+        snippet.visitCode();
+        snippet.visitVarInsn(ILOAD, 0);
+        snippet.visitMethodInsn(INVOKESTATIC, internalClassName, GET, getDescriptor, false);
+
+        snippet.visitVarInsn(ILOAD, 0);
+        SubWordTestUtil.convertToKind(snippet, kind);
+        SubWordTestUtil.testEqual(snippet);
+
+        snippet.visitMaxs(2, 1);
+        snippet.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordInputTest2.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+
+import jdk.vm.ci.meta.DeoptimizationReason;
+import jdk.vm.ci.meta.JavaKind;
+import jdk.vm.ci.meta.ResolvedJavaMethod;
+
+@RunWith(Parameterized.class)
+public class SubWordInputTest2 extends CustomizedBytecodePatternTest {
+
+    @Parameterized.Parameters(name = "{0}, {1}")
+    public static List<Object[]> data() {
+        ArrayList<Object[]> ret = new ArrayList<>();
+        for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF}) {
+            ret.add(new Object[]{JavaKind.Byte, i});
+            ret.add(new Object[]{JavaKind.Short, i});
+            ret.add(new Object[]{JavaKind.Char, i});
+        }
+        return ret;
+    }
+
+    private static final String GET = "get";
+    private static final String WRAPPER = "wrapper";
+
+    private final JavaKind kind;
+    private final int value;
+
+    public SubWordInputTest2(JavaKind kind, int value) {
+        this.kind = kind;
+        this.value = value;
+    }
+
+    @Test
+    public void testSubWordInput() throws ClassNotFoundException {
+        Class<?> testClass = getClass(SubWordInputTest2.class.getName() + "$" + kind.toString() + "Getter");
+        ResolvedJavaMethod wrapper = getResolvedJavaMethod(testClass, WRAPPER);
+        Result expected = executeExpected(wrapper, null, value);
+        // test standalone callee
+        getCode(getResolvedJavaMethod(testClass, GET), null, false, true, getInitialOptions());
+        assertEquals(executeExpected(wrapper, null, value), expected);
+        // test with inlining
+        testAgainstExpected(wrapper, expected, Collections.<DeoptimizationReason> emptySet(), null, value);
+    }
+
+    @Override
+    protected byte[] generateClass(String internalClassName) {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
+        cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null);
+
+        final char typeChar = kind.getTypeChar();
+        String getDescriptor = "(" + typeChar + ")" + "Z";
+        MethodVisitor get = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, GET, getDescriptor, null, null);
+        get.visitCode();
+        get.visitVarInsn(ILOAD, 0);
+        Label label = new Label();
+        get.visitJumpInsn(IFGE, label);
+        get.visitInsn(ICONST_0);
+        get.visitInsn(IRETURN);
+        get.visitLabel(label);
+        get.visitInsn(ICONST_1);
+        get.visitInsn(IRETURN);
+        get.visitMaxs(1, 1);
+        get.visitEnd();
+
+        MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, WRAPPER, "(I)Z", null, null);
+        snippet.visitCode();
+        snippet.visitVarInsn(ILOAD, 0);
+        snippet.visitMethodInsn(INVOKESTATIC, internalClassName, GET, getDescriptor, false);
+        snippet.visitInsn(IRETURN);
+        snippet.visitMaxs(1, 1);
+        snippet.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordReturnTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordReturnTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,8 +24,7 @@
 
 import java.util.ArrayList;
 import java.util.List;
-import jdk.vm.ci.meta.JavaKind;
-import jdk.vm.ci.meta.ResolvedJavaMethod;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
@@ -33,38 +32,16 @@
 import org.objectweb.asm.ClassWriter;
 import org.objectweb.asm.FieldVisitor;
 import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
+
+import jdk.vm.ci.meta.JavaKind;
+import jdk.vm.ci.meta.ResolvedJavaMethod;
 
 @RunWith(Parameterized.class)
-public class SubWordReturnTest extends GraalCompilerTest {
+public class SubWordReturnTest extends CustomizedBytecodePatternTest {
 
     private final JavaKind kind;
     private final int value;
 
-    private final String generatedClassName;
-    private final String generatedClassNameInternal;
-
-    private final String testMethodName;
-
-    /**
-     * The {@link AsmLoader} generates a class looking like this for the types byte, short, int and
-     * char.
-     */
-    static class ByteGetter {
-
-        // private static int intField = 1000000;
-
-        private static byte get() {
-            // GETSTATIC intField
-            // IRETURN
-            return 0;
-        }
-
-        public static int testByteSnippet() {
-            return get();
-        }
-    }
-
     @Parameters(name = "{0}, {1}")
     public static List<Object[]> data() {
         ArrayList<Object[]> ret = new ArrayList<>();
@@ -80,64 +57,58 @@
     public SubWordReturnTest(JavaKind kind, int value) {
         this.kind = kind;
         this.value = value;
-
-        this.generatedClassName = SubWordReturnTest.class.getName() + "$" + kind.toString() + "Getter";
-        this.generatedClassNameInternal = generatedClassName.replace('.', '/');
-        this.testMethodName = "test" + kind.name() + "Snippet";
     }
 
     @Test
-    public void test() throws ClassNotFoundException {
-        Class<?> testClass = new AsmLoader(SubWordReturnTest.class.getClassLoader()).findClass(generatedClassName);
-        ResolvedJavaMethod method = getResolvedJavaMethod(testClass, testMethodName);
+    public void testSubWordReturn() throws ClassNotFoundException {
+        Class<?> testClass = getClass(SubWordReturnTest.class.getName() + "$" + kind.toString() + "Getter");
+        ResolvedJavaMethod method = getResolvedJavaMethod(testClass, "testSnippet");
         test(method, null);
     }
 
-    class AsmLoader extends ClassLoader implements Opcodes {
-
-        Class<?> loaded;
-
-        AsmLoader(ClassLoader parent) {
-            super(parent);
-        }
+    /**
+     * {@link #generateClass} generates a class looking like this for the types boolean, byte,
+     * short, and char.
+     */
+    static class ByteGetter {
 
-        @Override
-        protected Class<?> findClass(String name) throws ClassNotFoundException {
-            if (name.equals(generatedClassName)) {
-                if (loaded == null) {
-                    byte[] gen = generateClass();
-                    loaded = defineClass(name, gen, 0, gen.length);
-                }
-                return loaded;
-            } else {
-                return super.findClass(name);
-            }
+        // private static int intField = 1000000;
+
+        private static byte get() {
+            // GETSTATIC intField
+            // IRETURN
+            return 0;
         }
 
-        private byte[] generateClass() {
-            ClassWriter cw = new ClassWriter(0);
-            cw.visit(52, ACC_SUPER | ACC_PUBLIC, generatedClassNameInternal, null, "java/lang/Object", null);
-
-            FieldVisitor intField = cw.visitField(ACC_PRIVATE | ACC_STATIC, "intField", "I", null, value);
-            intField.visitEnd();
-
-            MethodVisitor get = cw.visitMethod(ACC_PRIVATE | ACC_STATIC, "get", "()" + kind.getTypeChar(), null, null);
-            get.visitCode();
-            get.visitFieldInsn(GETSTATIC, generatedClassNameInternal, "intField", "I");
-            get.visitInsn(IRETURN);
-            get.visitMaxs(1, 0);
-            get.visitEnd();
-
-            MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, testMethodName, "()I", null, null);
-            snippet.visitCode();
-            snippet.visitMethodInsn(INVOKESTATIC, generatedClassNameInternal, "get", "()" + kind.getTypeChar(), false);
-            snippet.visitInsn(IRETURN);
-            snippet.visitMaxs(1, 0);
-            snippet.visitEnd();
-
-            cw.visitEnd();
-            return cw.toByteArray();
+        public static int testByteSnippet() {
+            return get();
         }
     }
 
+    @Override
+    protected byte[] generateClass(String internalClassName) {
+        ClassWriter cw = new ClassWriter(0);
+        cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null);
+
+        FieldVisitor intField = cw.visitField(ACC_PRIVATE | ACC_STATIC, "intField", "I", null, value);
+        intField.visitEnd();
+
+        MethodVisitor get = cw.visitMethod(ACC_PRIVATE | ACC_STATIC, "get", "()" + kind.getTypeChar(), null, null);
+        get.visitCode();
+        get.visitFieldInsn(GETSTATIC, internalClassName, "intField", "I");
+        get.visitInsn(IRETURN);
+        get.visitMaxs(1, 0);
+        get.visitEnd();
+
+        MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "testSnippet", "()I", null, null);
+        snippet.visitCode();
+        snippet.visitMethodInsn(INVOKESTATIC, internalClassName, "get", "()" + kind.getTypeChar(), false);
+        snippet.visitInsn(IRETURN);
+        snippet.visitMaxs(1, 0);
+        snippet.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.core.test/src/org/graalvm/compiler/core/test/SubWordTestUtil.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.core.test;
+
+import org.graalvm.compiler.debug.GraalError;
+import org.graalvm.compiler.test.GraalTest;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+
+import jdk.vm.ci.meta.JavaKind;
+
+public final class SubWordTestUtil implements Opcodes {
+
+    private SubWordTestUtil() {
+    }
+
+    static void convertToKind(MethodVisitor snippet, JavaKind kind) {
+        switch (kind) {
+            case Boolean:
+                snippet.visitInsn(ICONST_1);
+                snippet.visitInsn(IAND);
+                break;
+            case Byte:
+                snippet.visitInsn(I2B);
+                break;
+            case Short:
+                snippet.visitInsn(I2S);
+                break;
+            case Char:
+                snippet.visitInsn(I2C);
+                break;
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    static void testEqual(MethodVisitor snippet) {
+        Label label = new Label();
+        snippet.visitJumpInsn(IF_ICMPNE, label);
+        snippet.visitInsn(ICONST_1);
+        snippet.visitInsn(IRETURN);
+        snippet.visitLabel(label);
+        snippet.visitInsn(ICONST_0);
+        snippet.visitInsn(IRETURN);
+    }
+
+    static void getUnsafe(MethodVisitor snippet) {
+        snippet.visitFieldInsn(GETSTATIC, GraalTest.class.getName().replace('.', '/'), "UNSAFE", "Lsun/misc/Unsafe;");
+    }
+
+    static String getUnsafePutMethodName(JavaKind kind) {
+        String name = kind.getJavaName();
+        return name.substring(0, 1).toUpperCase() + name.substring(1);
+    }
+
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.debug/src/org/graalvm/compiler/debug/DiagnosticsOutputDirectory.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.debug/src/org/graalvm/compiler/debug/DiagnosticsOutputDirectory.java	Tue Jun 19 16:33:07 2018 +0100
@@ -135,7 +135,7 @@
                                 String name = dir.relativize(file).toString();
                                 ZipEntry ze = new ZipEntry(name);
                                 zos.putNextEntry(ze);
-                                zos.write(Files.readAllBytes(file));
+                                Files.copy(file, zos);
                                 zos.closeEntry();
                             }
                             toDelete.add(file);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java	Tue Jun 19 16:33:07 2018 +0100
@@ -30,12 +30,14 @@
 import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
 import static org.graalvm.compiler.core.common.GraalOptions.ZapStackOnMethodEntry;
 
+import jdk.vm.ci.amd64.AMD64.CPUFeature;
 import jdk.internal.vm.compiler.collections.EconomicSet;
 import org.graalvm.compiler.asm.Assembler;
 import org.graalvm.compiler.asm.Label;
 import org.graalvm.compiler.asm.amd64.AMD64Address;
 import org.graalvm.compiler.asm.amd64.AMD64Assembler.ConditionFlag;
 import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
 import org.graalvm.compiler.code.CompilationResult;
 import org.graalvm.compiler.core.amd64.AMD64NodeMatchRules;
 import org.graalvm.compiler.core.common.CompilationIdentifier;
@@ -195,7 +197,11 @@
 
     @Override
     protected Assembler createAssembler(FrameMap frameMap) {
-        return new AMD64MacroAssembler(getTarget());
+        if (((AMD64) getTarget().arch).getFeatures().contains(CPUFeature.AVX)) {
+            return new AMD64VectorAssembler(getTarget());
+        } else {
+            return new AMD64MacroAssembler(getTarget());
+        }
     }
 
     @Override
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java	Tue Jun 19 16:33:07 2018 +0100
@@ -27,7 +27,9 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Formatter;
 import java.util.List;
+import java.util.ServiceLoader;
 import java.util.Set;
 import java.util.TreeSet;
 import java.util.stream.Collectors;
@@ -47,6 +49,8 @@
 import org.graalvm.compiler.test.GraalTest;
 import org.junit.Test;
 
+import jdk.vm.ci.amd64.AMD64;
+import jdk.vm.ci.code.Architecture;
 import jdk.vm.ci.hotspot.HotSpotVMConfigStore;
 import jdk.vm.ci.hotspot.VMIntrinsicMethod;
 import jdk.vm.ci.meta.MetaAccessProvider;
@@ -57,8 +61,8 @@
 /**
  * Checks the intrinsics implemented by Graal against the set of intrinsics declared by HotSpot. The
  * purpose of this test is to detect when new intrinsics are added to HotSpot and process them
- * appropriately in Graal. This will be achieved by working through {@link #TO_BE_INVESTIGATED} and
- * either implementing the intrinsic or moving it to {@link #IGNORE} .
+ * appropriately in Graal. This will be achieved by working through {@link #toBeInvestigated} and
+ * either implementing the intrinsic or moving it to {@link #ignore} .
  */
 public class CheckGraalIntrinsics extends GraalTest {
 
@@ -118,16 +122,33 @@
     }
 
     /**
-     * The HotSpot intrinsics implemented without {@link InvocationPlugin}s or whose
-     * {@link InvocationPlugin} registration is guarded by a condition that is false in the current
-     * VM context.
+     * The HotSpot intrinsics that:
+     * <ul>
+     * <li>will never implemented by Graal (comments must explain why)</li>
+     * <li>are implemented without {@link InvocationPlugin}s, or</li>
+     * <li>whose {@link InvocationPlugin} registration is guarded by a condition that is false in
+     * the current VM context.</li>
+     * </ul>
      */
-    private static final Set<String> IGNORE = new TreeSet<>();
+    public final Set<String> ignore = new TreeSet<>();
 
     /**
-     * The HotSpot intrinsics yet to be implemented or moved to {@link #IGNORE}.
+     * The HotSpot intrinsics whose {@link InvocationPlugin} registration is guarded by a condition
+     * too complex to duplicate here.
+     * </ul>
      */
-    private static final Set<String> TO_BE_INVESTIGATED = new TreeSet<>();
+    public final Set<String> complexGuard = new TreeSet<>();
+
+    /**
+     * The HotSpot intrinsics implemented downstream.
+     * </ul>
+     */
+    public final Set<String> downstream = new TreeSet<>();
+
+    /**
+     * The HotSpot intrinsics yet to be implemented or moved to {@link #ignore}.
+     */
+    public final Set<String> toBeInvestigated = new TreeSet<>();
 
     private static Collection<String> add(Collection<String> c, String... elements) {
         String[] sorted = elements.clone();
@@ -142,9 +163,13 @@
         return c;
     }
 
-    static {
+    public final HotSpotGraalRuntimeProvider rt = (HotSpotGraalRuntimeProvider) Graal.getRequiredCapability(RuntimeProvider.class);
+    public final Architecture arch = rt.getHostBackend().getTarget().arch;
+    public final GraalHotSpotVMConfig config = rt.getVMConfig();
+
+    public CheckGraalIntrinsics() {
         // These are dead
-        add(IGNORE,
+        add(ignore,
                         "java/lang/Math.atan2(DD)D",
                         "jdk/internal/misc/Unsafe.park(ZJ)V",
                         "jdk/internal/misc/Unsafe.unpark(Ljava/lang/Object;)V",
@@ -156,34 +181,34 @@
                         "sun/misc/Unsafe.unpark(Ljava/lang/Object;)V");
 
         // These only exist to assist escape analysis in C2
-        add(IGNORE,
+        add(ignore,
                         "java/lang/Throwable.fillInStackTrace()Ljava/lang/Throwable;");
 
         // These are only used for the security handling during stack walking
-        add(IGNORE,
+        add(ignore,
                         "java/lang/reflect/Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
 
         // These are marker intrinsic ids only
-        add(IGNORE,
+        add(ignore,
                         "java/lang/invoke/MethodHandle.<compiledLambdaForm>*",
                         "java/lang/invoke/MethodHandle.invoke*");
 
         // These are implemented through lowering
-        add(IGNORE,
+        add(ignore,
                         "java/lang/ref/Reference.get()Ljava/lang/Object;");
 
         // These are only used by C1
-        add(IGNORE,
+        add(ignore,
                         "java/nio/Buffer.checkIndex(I)I");
 
         // These do general compiler optimizations and convert min/max to cmov instructions. We are
         // ignoring them as cmovs are not necessarily beneficial.
-        add(IGNORE,
+        add(ignore,
                         "java/lang/Math.max(II)I",
                         "java/lang/Math.min(II)I");
 
         // These are known to be implemented down stream
-        add(IGNORE,
+        add(downstream,
                         "java/lang/Integer.toString(I)Ljava/lang/String;",
                         "java/lang/String.<init>(Ljava/lang/String;)V",
                         "java/lang/StringBuffer.<init>()V",
@@ -203,9 +228,7 @@
                         "java/util/Arrays.copyOf([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object;",
                         "java/util/Arrays.copyOfRange([Ljava/lang/Object;IILjava/lang/Class;)[Ljava/lang/Object;");
 
-        // These are known to be implemented but the platform dependent conditions
-        // for when they are enabled are complex so just ignore them all the time.
-        add(IGNORE,
+        add(complexGuard,
                         "java/lang/Integer.bitCount(I)I",
                         "java/lang/Integer.numberOfLeadingZeros(I)I",
                         "java/lang/Integer.numberOfTrailingZeros(I)I",
@@ -214,30 +237,17 @@
                         "java/lang/Long.numberOfTrailingZeros(J)I");
 
         // Relevant for Java flight recorder
-        add(TO_BE_INVESTIGATED,
+        add(toBeInvestigated,
                         "oracle/jrockit/jfr/Timing.counterTime()J",
                         "oracle/jrockit/jfr/VMJFR.classID0(Ljava/lang/Class;)J",
                         "oracle/jrockit/jfr/VMJFR.threadID()I");
 
-        add(TO_BE_INVESTIGATED,
-                        // Should be fairly easy to implement - C2 intrinsifies these to use "v !=
-                        // v" to check for NaN instead of looking at the bit pattern.
-                        "java/lang/Double.doubleToLongBits(D)J",
-                        "java/lang/Float.floatToIntBits(F)I",
-
-                        // Should be trivial to implement because we already have existing nodes
-                        "java/lang/Math.decrementExact(I)I",
-                        "java/lang/Math.decrementExact(J)J",
-                        "java/lang/Math.incrementExact(I)I",
-                        "java/lang/Math.incrementExact(J)J",
-
+        add(toBeInvestigated,
                         // Similar to addExact
                         "java/lang/Math.negateExact(I)I",
                         // Similar to addExact
                         "java/lang/Math.negateExact(J)J",
                         // HotSpot MacroAssembler-based intrinsic
-                        "java/lang/String.compareTo(Ljava/lang/String;)I",
-                        // HotSpot MacroAssembler-based intrinsic
                         "java/lang/String.indexOf(Ljava/lang/String;)I",
                         // Can share most implementation parts with with
                         // Unsafe.allocateUninitializedArray0
@@ -249,12 +259,12 @@
 
         if (isJDK9OrHigher()) {
             // Relevant for Java flight recorder
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             "jdk/jfr/internal/JVM.counterTime()J",
                             "jdk/jfr/internal/JVM.getBufferWriter()Ljava/lang/Object;",
                             "jdk/jfr/internal/JVM.getClassId(Ljava/lang/Class;)J");
 
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             // Some logic and a stub call
                             "com/sun/crypto/provider/CounterMode.implCrypt([BII[BI)I",
                             // Stub and very little logic
@@ -263,10 +273,6 @@
                             "java/lang/Math.fma(DDD)D",
                             // HotSpot MacroAssembler-based intrinsic
                             "java/lang/Math.fma(FFF)F",
-                            // Just a runtime call (the called C code has a better fast path)
-                            "java/lang/Object.notify()V",
-                            // Just a runtime call (the called C code has a better fast path)
-                            "java/lang/Object.notifyAll()V",
                             // Emit pause instruction if os::is_MP()
                             "java/lang/Thread.onSpinWait()V",
                             // Just check if the argument is a compile time constant
@@ -279,51 +285,23 @@
                             "java/util/zip/Adler32.updateByteBuffer(IJII)I",
                             // Only implemented on non-AMD64 platforms (some logic and runtime call)
                             "java/util/zip/Adler32.updateBytes(I[BII)I",
-                            // similar to CRC32.updateBytes
-                            "java/util/zip/CRC32C.updateBytes(I[BII)I",
-                            // similar to CRC32.updateDirectByteBuffer
-                            "java/util/zip/CRC32C.updateDirectByteBuffer(IJII)I",
                             // Emits a slow and a fast path and some dispatching logic
                             "jdk/internal/misc/Unsafe.allocateUninitializedArray0(Ljava/lang/Class;I)Ljava/lang/Object;",
 
-                            // Should be easy to implement as it seems to match the logic that is
-                            // already implemented in ValueCompareAndSwapNode. On the high-level, we
-                            // would need something similar to UnsafeCompareAndSwapNode but with a
-                            // different result type.
-                            "jdk/internal/misc/Unsafe.compareAndExchangeByte(Ljava/lang/Object;JBB)B",
-                            "jdk/internal/misc/Unsafe.compareAndExchangeInt(Ljava/lang/Object;JII)I",
-                            "jdk/internal/misc/Unsafe.compareAndExchangeLong(Ljava/lang/Object;JJJ)J",
-                            "jdk/internal/misc/Unsafe.compareAndExchangeObject(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;",
-                            "jdk/internal/misc/Unsafe.compareAndExchangeShort(Ljava/lang/Object;JSS)S",
-
-                            // Should be easy to implement as we already have an implementation for
-                            // int, long, and Object.
-                            "jdk/internal/misc/Unsafe.compareAndSetByte(Ljava/lang/Object;JBB)Z",
-                            "jdk/internal/misc/Unsafe.compareAndSetShort(Ljava/lang/Object;JSS)Z",
-
-                            // Should be easy to implement as we already have an implementation for
-                            // int and long.
-                            "jdk/internal/misc/Unsafe.getAndAddByte(Ljava/lang/Object;JB)B",
-                            "jdk/internal/misc/Unsafe.getAndAddShort(Ljava/lang/Object;JS)S",
-
-                            // Should be easy to implement as we already have an implementation for
-                            // int, long, and Object.
-                            "jdk/internal/misc/Unsafe.getAndSetByte(Ljava/lang/Object;JB)B",
-                            "jdk/internal/misc/Unsafe.getAndSetShort(Ljava/lang/Object;JS)S",
-
                             // Control flow, deopts, and a cast
                             "jdk/internal/util/Preconditions.checkIndex(IILjava/util/function/BiFunction;)I",
                             // HotSpot MacroAssembler-based intrinsic
                             "sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray([CI[BII)I",
                             // Runtime call and some complex compiler logic
                             "sun/security/provider/DigestBase.implCompressMultiBlock0([BII)I");
+
             /*
              * Per default, all these operations are mapped to some generic method for which we
              * already have compiler intrinsics. Performance-wise it would be better to support them
              * explicitly as the more generic method might be more restrictive and therefore slower
              * than necessary.
              */
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             // Mapped to compareAndExchange*
                             "jdk/internal/misc/Unsafe.compareAndExchangeByteAcquire(Ljava/lang/Object;JBB)B",
                             "jdk/internal/misc/Unsafe.compareAndExchangeByteRelease(Ljava/lang/Object;JBB)B",
@@ -336,37 +314,6 @@
                             "jdk/internal/misc/Unsafe.compareAndExchangeShortAcquire(Ljava/lang/Object;JSS)S",
                             "jdk/internal/misc/Unsafe.compareAndExchangeShortRelease(Ljava/lang/Object;JSS)S",
 
-                            // Mapped to get*Volatile
-                            "jdk/internal/misc/Unsafe.getBooleanAcquire(Ljava/lang/Object;J)Z",
-                            "jdk/internal/misc/Unsafe.getBooleanOpaque(Ljava/lang/Object;J)Z",
-                            "jdk/internal/misc/Unsafe.getByteAcquire(Ljava/lang/Object;J)B",
-                            "jdk/internal/misc/Unsafe.getByteOpaque(Ljava/lang/Object;J)B",
-                            "jdk/internal/misc/Unsafe.getCharAcquire(Ljava/lang/Object;J)C",
-                            "jdk/internal/misc/Unsafe.getCharOpaque(Ljava/lang/Object;J)C",
-                            "jdk/internal/misc/Unsafe.getDoubleAcquire(Ljava/lang/Object;J)D",
-                            "jdk/internal/misc/Unsafe.getDoubleOpaque(Ljava/lang/Object;J)D",
-                            "jdk/internal/misc/Unsafe.getFloatAcquire(Ljava/lang/Object;J)F",
-                            "jdk/internal/misc/Unsafe.getFloatOpaque(Ljava/lang/Object;J)F",
-                            "jdk/internal/misc/Unsafe.getIntAcquire(Ljava/lang/Object;J)I",
-                            "jdk/internal/misc/Unsafe.getIntOpaque(Ljava/lang/Object;J)I",
-                            "jdk/internal/misc/Unsafe.getLongAcquire(Ljava/lang/Object;J)J",
-                            "jdk/internal/misc/Unsafe.getLongOpaque(Ljava/lang/Object;J)J",
-                            "jdk/internal/misc/Unsafe.getObjectAcquire(Ljava/lang/Object;J)Ljava/lang/Object;",
-                            "jdk/internal/misc/Unsafe.getObjectOpaque(Ljava/lang/Object;J)Ljava/lang/Object;",
-                            "jdk/internal/misc/Unsafe.getShortAcquire(Ljava/lang/Object;J)S",
-                            "jdk/internal/misc/Unsafe.getShortOpaque(Ljava/lang/Object;J)S",
-
-                            // Mapped to put*Volatile
-                            "jdk/internal/misc/Unsafe.putBooleanOpaque(Ljava/lang/Object;JZ)V",
-                            "jdk/internal/misc/Unsafe.putByteOpaque(Ljava/lang/Object;JB)V",
-                            "jdk/internal/misc/Unsafe.putCharOpaque(Ljava/lang/Object;JC)V",
-                            "jdk/internal/misc/Unsafe.putDoubleOpaque(Ljava/lang/Object;JD)V",
-                            "jdk/internal/misc/Unsafe.putFloatOpaque(Ljava/lang/Object;JF)V",
-                            "jdk/internal/misc/Unsafe.putIntOpaque(Ljava/lang/Object;JI)V",
-                            "jdk/internal/misc/Unsafe.putLongOpaque(Ljava/lang/Object;JJ)V",
-                            "jdk/internal/misc/Unsafe.putObjectOpaque(Ljava/lang/Object;JLjava/lang/Object;)V",
-                            "jdk/internal/misc/Unsafe.putShortOpaque(Ljava/lang/Object;JS)V",
-
                             // Mapped to compareAndSet*
                             "jdk/internal/misc/Unsafe.weakCompareAndSetByte(Ljava/lang/Object;JBB)Z",
                             "jdk/internal/misc/Unsafe.weakCompareAndSetByteAcquire(Ljava/lang/Object;JBB)Z",
@@ -390,18 +337,14 @@
                             "jdk/internal/misc/Unsafe.weakCompareAndSetShortRelease(Ljava/lang/Object;JSS)Z");
 
             // Compact string support - HotSpot MacroAssembler-based intrinsic or complex C2 logic.
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             "java/lang/StringCoding.hasNegatives([BII)Z",
                             "java/lang/StringCoding.implEncodeISOArray([BI[BII)I",
-                            "java/lang/StringLatin1.compareTo([B[B)I",
-                            "java/lang/StringLatin1.compareToUTF16([B[B)I",
                             "java/lang/StringLatin1.equals([B[B)Z",
                             "java/lang/StringLatin1.indexOf([BI[BII)I",
                             "java/lang/StringLatin1.indexOf([B[B)I",
                             "java/lang/StringLatin1.inflate([BI[BII)V",
                             "java/lang/StringLatin1.inflate([BI[CII)V",
-                            "java/lang/StringUTF16.compareTo([B[B)I",
-                            "java/lang/StringUTF16.compareToLatin1([B[B)I",
                             "java/lang/StringUTF16.compress([BI[BII)I",
                             "java/lang/StringUTF16.compress([CI[BII)I",
                             "java/lang/StringUTF16.equals([B[B)Z",
@@ -417,20 +360,36 @@
         }
 
         if (isJDK10OrHigher()) {
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             "java/lang/Math.multiplyHigh(JJ)J",
                             "jdk/internal/util/ArraysSupport.vectorizedMismatch(Ljava/lang/Object;JLjava/lang/Object;JII)I");
         }
 
         if (isJDK11OrHigher()) {
             // Relevant for Java flight recorder
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
                             "jdk/jfr/internal/JVM.getEventWriter()Ljava/lang/Object;");
         }
 
-        if (!getHostArchitectureName().equals("amd64")) {
+        if (!config.inlineNotify()) {
+            add(ignore, "java/lang/Object.notify()V");
+        }
+        if (!config.inlineNotifyAll()) {
+            add(ignore, "java/lang/Object.notifyAll()V");
+        }
+
+        if (!(arch instanceof AMD64)) {
             // Can we implement these on non-AMD64 platforms? C2 seems to.
-            add(TO_BE_INVESTIGATED,
+            add(toBeInvestigated,
+                            "java/lang/String.compareTo(Ljava/lang/String;)I",
+                            "jdk/internal/misc/Unsafe.compareAndExchangeByte(Ljava/lang/Object;JBB)B",
+                            "jdk/internal/misc/Unsafe.compareAndExchangeShort(Ljava/lang/Object;JSS)S",
+                            "jdk/internal/misc/Unsafe.compareAndSetByte(Ljava/lang/Object;JBB)Z",
+                            "jdk/internal/misc/Unsafe.compareAndSetShort(Ljava/lang/Object;JSS)Z",
+                            "jdk/internal/misc/Unsafe.getAndAddByte(Ljava/lang/Object;JB)B",
+                            "jdk/internal/misc/Unsafe.getAndAddShort(Ljava/lang/Object;JS)S",
+                            "jdk/internal/misc/Unsafe.getAndSetByte(Ljava/lang/Object;JB)B",
+                            "jdk/internal/misc/Unsafe.getAndSetShort(Ljava/lang/Object;JS)S",
                             "sun/misc/Unsafe.getAndAddInt(Ljava/lang/Object;JI)I",
                             "sun/misc/Unsafe.getAndAddLong(Ljava/lang/Object;JJ)J",
                             "sun/misc/Unsafe.getAndSetInt(Ljava/lang/Object;JI)I",
@@ -438,7 +397,11 @@
                             "sun/misc/Unsafe.getAndSetObject(Ljava/lang/Object;JLjava/lang/Object;)Ljava/lang/Object;");
 
             if (isJDK9OrHigher()) {
-                add(TO_BE_INVESTIGATED,
+                add(toBeInvestigated,
+                                "java/lang/StringLatin1.compareTo([B[B)I",
+                                "java/lang/StringLatin1.compareToUTF16([B[B)I",
+                                "java/lang/StringUTF16.compareTo([B[B)I",
+                                "java/lang/StringUTF16.compareToLatin1([B[B)I",
                                 "jdk/internal/misc/Unsafe.getAndAddInt(Ljava/lang/Object;JI)I",
                                 "jdk/internal/misc/Unsafe.getAndAddLong(Ljava/lang/Object;JJ)J",
                                 "jdk/internal/misc/Unsafe.getAndSetInt(Ljava/lang/Object;JI)I",
@@ -455,9 +418,6 @@
             }
         }
 
-        HotSpotGraalRuntimeProvider rt = (HotSpotGraalRuntimeProvider) Graal.getRequiredCapability(RuntimeProvider.class);
-        GraalHotSpotVMConfig config = rt.getVMConfig();
-
         /*
          * The intrinsics down here are known to be implemented but they are not always enabled on
          * the HotSpot side (e.g., because they require certain CPU features). So, we are ignoring
@@ -466,13 +426,13 @@
 
         // CRC32 intrinsics
         if (!config.useCRC32Intrinsics) {
-            add(IGNORE, "java/util/zip/CRC32.update(II)I");
+            add(ignore, "java/util/zip/CRC32.update(II)I");
             if (isJDK9OrHigher()) {
-                add(IGNORE,
+                add(ignore,
                                 "java/util/zip/CRC32.updateByteBuffer0(IJII)I",
                                 "java/util/zip/CRC32.updateBytes0(I[BII)I");
             } else {
-                add(IGNORE,
+                add(ignore,
                                 "java/util/zip/CRC32.updateByteBuffer(IJII)I",
                                 "java/util/zip/CRC32.updateBytes(I[BII)I");
             }
@@ -480,7 +440,7 @@
 
         // CRC32C intrinsics
         if (!config.useCRC32CIntrinsics) {
-            add(IGNORE,
+            add(ignore,
                             "java/util/zip/CRC32C.updateBytes(I[BII)I",
                             "java/util/zip/CRC32C.updateDirectByteBuffer(IJII)I");
         }
@@ -488,13 +448,13 @@
         // AES intrinsics
         if (!config.useAESIntrinsics) {
             if (isJDK9OrHigher()) {
-                add(IGNORE,
+                add(ignore,
                                 "com/sun/crypto/provider/AESCrypt.implDecryptBlock([BI[BI)V",
                                 "com/sun/crypto/provider/AESCrypt.implEncryptBlock([BI[BI)V",
                                 "com/sun/crypto/provider/CipherBlockChaining.implDecrypt([BII[BI)I",
                                 "com/sun/crypto/provider/CipherBlockChaining.implEncrypt([BII[BI)I");
             } else {
-                add(IGNORE,
+                add(ignore,
                                 "com/sun/crypto/provider/AESCrypt.decryptBlock([BI[BI)V",
                                 "com/sun/crypto/provider/AESCrypt.encryptBlock([BI[BI)V",
                                 "com/sun/crypto/provider/CipherBlockChaining.decrypt([BII[BI)I",
@@ -505,44 +465,44 @@
         // BigInteger intrinsics
         if (!config.useMultiplyToLenIntrinsic()) {
             if (isJDK9OrHigher()) {
-                add(IGNORE, "java/math/BigInteger.implMultiplyToLen([II[II[I)[I");
+                add(ignore, "java/math/BigInteger.implMultiplyToLen([II[II[I)[I");
             } else {
-                add(IGNORE, "java/math/BigInteger.multiplyToLen([II[II[I)[I");
+                add(ignore, "java/math/BigInteger.multiplyToLen([II[II[I)[I");
             }
         }
         if (!config.useMulAddIntrinsic()) {
-            add(IGNORE, "java/math/BigInteger.implMulAdd([I[IIII)I");
+            add(ignore, "java/math/BigInteger.implMulAdd([I[IIII)I");
         }
         if (!config.useMontgomeryMultiplyIntrinsic()) {
-            add(IGNORE, "java/math/BigInteger.implMontgomeryMultiply([I[I[IIJ[I)[I");
+            add(ignore, "java/math/BigInteger.implMontgomeryMultiply([I[I[IIJ[I)[I");
         }
         if (!config.useMontgomerySquareIntrinsic()) {
-            add(IGNORE, "java/math/BigInteger.implMontgomerySquare([I[IIJ[I)[I");
+            add(ignore, "java/math/BigInteger.implMontgomerySquare([I[IIJ[I)[I");
         }
         if (!config.useSquareToLenIntrinsic()) {
-            add(IGNORE, "java/math/BigInteger.implSquareToLen([II[II)[I");
+            add(ignore, "java/math/BigInteger.implSquareToLen([II[II)[I");
         }
 
         // SHA intrinsics
         if (!config.useSHA1Intrinsics()) {
             if (isJDK9OrHigher()) {
-                add(IGNORE, "sun/security/provider/SHA.implCompress0([BI)V");
+                add(ignore, "sun/security/provider/SHA.implCompress0([BI)V");
             } else {
-                add(IGNORE, "sun/security/provider/SHA.implCompress([BI)V");
+                add(ignore, "sun/security/provider/SHA.implCompress([BI)V");
             }
         }
         if (!config.useSHA256Intrinsics()) {
             if (isJDK9OrHigher()) {
-                add(IGNORE, "sun/security/provider/SHA2.implCompress0([BI)V");
+                add(ignore, "sun/security/provider/SHA2.implCompress0([BI)V");
             } else {
-                add(IGNORE, "sun/security/provider/SHA2.implCompress([BI)V");
+                add(ignore, "sun/security/provider/SHA2.implCompress([BI)V");
             }
         }
         if (!config.useSHA512Intrinsics()) {
             if (isJDK9OrHigher()) {
-                add(IGNORE, "sun/security/provider/SHA5.implCompress0([BI)V");
+                add(ignore, "sun/security/provider/SHA5.implCompress0([BI)V");
             } else {
-                add(IGNORE, "sun/security/provider/SHA5.implCompress([BI)V");
+                add(ignore, "sun/security/provider/SHA5.implCompress([BI)V");
             }
         }
     }
@@ -559,31 +519,31 @@
         return GraalServices.JAVA_SPECIFICATION_VERSION >= 11;
     }
 
-    private static String getHostArchitectureName() {
-        String arch = System.getProperty("os.arch");
-        if (arch.equals("x86_64")) {
-            arch = "amd64";
-        } else if (arch.equals("sparcv9")) {
-            arch = "sparc";
-        }
-        return arch;
+    public interface Refiner {
+        void refine(CheckGraalIntrinsics checker);
     }
 
     @Test
     @SuppressWarnings("try")
     public void test() throws ClassNotFoundException {
-        HotSpotGraalRuntimeProvider rt = (HotSpotGraalRuntimeProvider) Graal.getRequiredCapability(RuntimeProvider.class);
         HotSpotProviders providers = rt.getHostBackend().getProviders();
         Plugins graphBuilderPlugins = providers.getGraphBuilderPlugins();
         InvocationPlugins invocationPlugins = graphBuilderPlugins.getInvocationPlugins();
 
-        HotSpotVMConfigStore store = rt.getVMConfig().getStore();
+        HotSpotVMConfigStore store = config.getStore();
         List<VMIntrinsicMethod> intrinsics = store.getIntrinsics();
 
+        for (Refiner refiner : ServiceLoader.load(Refiner.class)) {
+            refiner.refine(this);
+        }
+
         List<String> missing = new ArrayList<>();
+        List<String> mischaracterizedAsToBeInvestigated = new ArrayList<>();
+        List<String> mischaracterizedAsIgnored = new ArrayList<>();
         EconomicMap<String, List<Binding>> bindings = invocationPlugins.getBindings(true);
         for (VMIntrinsicMethod intrinsic : intrinsics) {
             InvocationPlugin plugin = findPlugin(bindings, intrinsic);
+            String m = String.format("%s.%s%s", intrinsic.declaringClass, intrinsic.name, intrinsic.descriptor);
             if (plugin == null) {
                 ResolvedJavaMethod method = resolveIntrinsic(providers.getMetaAccess(), intrinsic);
                 if (method != null) {
@@ -592,17 +552,37 @@
                         continue;
                     }
                 }
-                String m = String.format("%s.%s%s", intrinsic.declaringClass, intrinsic.name, intrinsic.descriptor);
-                if (!TO_BE_INVESTIGATED.contains(m) && !IGNORE.contains(m)) {
+                if (!toBeInvestigated.contains(m) && !ignore.contains(m) && !complexGuard.contains(m) && !downstream.contains(m)) {
                     missing.add(m);
                 }
+            } else {
+                if (toBeInvestigated.contains(m)) {
+                    mischaracterizedAsToBeInvestigated.add(m);
+                } else if (ignore.contains(m)) {
+                    mischaracterizedAsIgnored.add(m);
+                }
             }
         }
 
+        Formatter errorMsgBuf = new Formatter();
         if (!missing.isEmpty()) {
             Collections.sort(missing);
             String missingString = missing.stream().collect(Collectors.joining(String.format("%n    ")));
-            fail("missing Graal intrinsics for:%n    %s", missingString);
+            errorMsgBuf.format("missing Graal intrinsics for:%n    %s%n", missingString);
+        }
+        if (!mischaracterizedAsToBeInvestigated.isEmpty()) {
+            Collections.sort(mischaracterizedAsToBeInvestigated);
+            String missingString = mischaracterizedAsToBeInvestigated.stream().collect(Collectors.joining(String.format("%n    ")));
+            errorMsgBuf.format("found plugins for intrinsics characterized as toBeInvestigated:%n    %s%n", missingString);
+        }
+        if (!mischaracterizedAsIgnored.isEmpty()) {
+            Collections.sort(mischaracterizedAsIgnored);
+            String missingString = mischaracterizedAsIgnored.stream().collect(Collectors.joining(String.format("%n    ")));
+            errorMsgBuf.format("found plugins for intrinsics characterized as IGNORED:%n    %s%n", missingString);
+        }
+        String errorMsg = errorMsgBuf.toString();
+        if (!errorMsg.isEmpty()) {
+            fail(errorMsg);
         }
     }
 }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfigVersioned.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfigVersioned.java	Tue Jun 19 16:33:07 2018 +0100
@@ -40,8 +40,13 @@
         super(store);
     }
 
+    private boolean initInlineNotify() {
+        String syncKnobs = getFlag("SyncKnobs", String.class, "");
+        return syncKnobs == null || !syncKnobs.contains("InlineNotify=0");
+    }
+
     // JSK-8132287
-    final boolean inlineNotify = !getFlag("SyncKnobs", String.class, "").contains("InlineNotify=0");
+    final boolean inlineNotify = initInlineNotify();
 
     // JDK-8073583
     final boolean useCRC32CIntrinsics = getFlag("UseCRC32CIntrinsics", Boolean.class);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/HotSpotGraalCompiler.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/HotSpotGraalCompiler.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,6 +34,7 @@
 
 import org.graalvm.compiler.api.runtime.GraalJVMCICompiler;
 import org.graalvm.compiler.bytecode.Bytecode;
+import org.graalvm.compiler.bytecode.BytecodeProvider;
 import org.graalvm.compiler.code.CompilationResult;
 import org.graalvm.compiler.core.GraalCompiler;
 import org.graalvm.compiler.core.common.CompilationIdentifier;
@@ -218,11 +219,18 @@
         if (subst != null) {
             ResolvedJavaMethod substMethod = subst.getMethod();
             assert !substMethod.equals(method);
-            StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(substMethod).compilationId(compilationId).build();
+            BytecodeProvider bytecodeProvider = subst.getOrigin();
+            // @formatter:off
+            StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).
+                            method(substMethod).
+                            compilationId(compilationId).
+                            recordInlinedMethods(bytecodeProvider.shouldRecordMethodDependencies()).
+                            build();
+            // @formatter:on
             try (DebugContext.Scope scope = debug.scope("GetIntrinsicGraph", graph)) {
                 Plugins plugins = new Plugins(providers.getGraphBuilderPlugins());
                 GraphBuilderConfiguration config = GraphBuilderConfiguration.getSnippetDefault(plugins);
-                IntrinsicContext initialReplacementContext = new IntrinsicContext(method, substMethod, subst.getOrigin(), ROOT_COMPILATION);
+                IntrinsicContext initialReplacementContext = new IntrinsicContext(method, substMethod, bytecodeProvider, ROOT_COMPILATION);
                 new GraphBuilderPhase.Instance(providers.getMetaAccess(), providers.getStampProvider(), providers.getConstantReflection(), providers.getConstantFieldProvider(), config,
                                 OptimisticOptimizations.NONE, initialReplacementContext).apply(graph);
                 assert !graph.isFrozen();
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotInvocationPlugins.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotInvocationPlugins.java	Tue Jun 19 16:33:07 2018 +0100
@@ -55,14 +55,14 @@
     }
 
     @Override
-    public void register(InvocationPlugin plugin, Type declaringClass, String name, Type... argumentTypes) {
+    protected void register(InvocationPlugin plugin, boolean isOptional, boolean allowOverwrite, Type declaringClass, String name, Type... argumentTypes) {
         if (!config.usePopCountInstruction) {
             if (name.equals("bitCount")) {
                 assert declaringClass.equals(Integer.class) || declaringClass.equals(Long.class);
                 return;
             }
         }
-        super.register(plugin, declaringClass, name, argumentTypes);
+        super.register(plugin, isOptional, allowOverwrite, declaringClass, name, argumentTypes);
     }
 
     @Override
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/replacements/ObjectCloneNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/replacements/ObjectCloneNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -98,7 +98,7 @@
                 Assumptions assumptions = graph().getAssumptions();
                 type = getConcreteType(getObject().stamp(NodeView.DEFAULT));
                 if (type != null) {
-                    StructuredGraph newGraph = new StructuredGraph.Builder(graph().getOptions(), graph().getDebug(), AllowAssumptions.ifNonNull(assumptions)).build();
+                    StructuredGraph newGraph = new StructuredGraph.Builder(graph().getOptions(), graph().getDebug(), AllowAssumptions.ifNonNull(assumptions)).name("<clone>").build();
                     ParameterNode param = newGraph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(getObject().stamp(NodeView.DEFAULT))));
                     NewInstanceNode newInstance = newGraph.add(new NewInstanceNode(type, true));
                     newGraph.addAfterFixed(newGraph.start(), newInstance);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java	Tue Jun 19 16:33:07 2018 +0100
@@ -852,7 +852,7 @@
 
             try (DebugCloseable context = openNodeContext()) {
                 if (method.isSynchronized()) {
-                    finishPrepare(lastInstr, BytecodeFrame.BEFORE_BCI);
+                    finishPrepare(lastInstr, BytecodeFrame.BEFORE_BCI, frameState);
 
                     // add a monitor enter to the start block
                     methodSynchronizedObject = synchronizedObject(frameState, method);
@@ -867,7 +867,7 @@
                     profilingPlugin.profileInvoke(this, method, stateBefore);
                 }
 
-                finishPrepare(lastInstr, 0);
+                finishPrepare(lastInstr, 0, frameState);
 
                 genInfoPointNode(InfopointReason.METHOD_START, null);
             }
@@ -914,8 +914,9 @@
      *
      * @param instruction the current last instruction
      * @param bci the current bci
+     * @param state The current frame state.
      */
-    protected void finishPrepare(FixedWithNextNode instruction, int bci) {
+    protected void finishPrepare(FixedWithNextNode instruction, int bci, FrameStateBuilder state) {
     }
 
     protected void cleanupFinalGraph() {
@@ -1393,7 +1394,7 @@
     }
 
     protected void genStoreField(ValueNode receiver, ResolvedJavaField field, ValueNode value) {
-        StoreFieldNode storeFieldNode = new StoreFieldNode(receiver, field, value);
+        StoreFieldNode storeFieldNode = new StoreFieldNode(receiver, field, maskSubWordValue(value, field.getJavaKind()));
         append(storeFieldNode);
         storeFieldNode.setStateAfter(this.createFrameState(stream.nextBCI(), storeFieldNode));
     }
@@ -2528,12 +2529,7 @@
 
             // the bytecode verifier doesn't check that the value is in the correct range
             if (stamp.lowerBound() < returnKind.getMinValue() || returnKind.getMaxValue() < stamp.upperBound()) {
-                ValueNode narrow = append(genNarrow(value, returnKind.getBitCount()));
-                if (returnKind.isUnsigned()) {
-                    return append(genZeroExtend(narrow, 32));
-                } else {
-                    return append(genSignExtend(narrow, 32));
-                }
+                return maskSubWordValue(value, returnKind);
             }
         }
 
@@ -2926,7 +2922,7 @@
 
     private void handleUnwindBlock(ExceptionDispatchBlock block) {
         if (parent == null) {
-            finishPrepare(lastInstr, block.deoptBci);
+            finishPrepare(lastInstr, block.deoptBci, frameState);
             frameState.setRethrowException(false);
             createUnwind();
         } else {
@@ -2966,7 +2962,7 @@
                 }
                 genMonitorExit(methodSynchronizedObject, currentReturnValue, bci);
                 assert !frameState.rethrowException();
-                finishPrepare(lastInstr, bci);
+                finishPrepare(lastInstr, bci, frameState);
             }
             if (frameState.lockDepth(false) != 0) {
                 throw bailout("unbalanced monitors: too few exits exiting frame");
@@ -3632,7 +3628,7 @@
         frameState.storeLocal(index, kind, value);
     }
 
-    private void genLoadConstant(int cpi, int opcode) {
+    protected void genLoadConstant(int cpi, int opcode) {
         Object con = lookupConstant(cpi, opcode);
 
         if (con instanceof JavaType) {
@@ -3651,6 +3647,21 @@
         }
     }
 
+    private JavaKind refineComponentType(ValueNode array, JavaKind kind) {
+        if (kind == JavaKind.Byte) {
+            JavaType type = array.stamp(NodeView.DEFAULT).javaType(metaAccess);
+            if (type.isArray()) {
+                JavaType componentType = type.getComponentType();
+                if (componentType != null) {
+                    JavaKind refinedKind = componentType.getJavaKind();
+                    assert refinedKind == JavaKind.Byte || refinedKind == JavaKind.Boolean;
+                    return refinedKind;
+                }
+            }
+        }
+        return kind;
+    }
+
     private void genLoadIndexed(JavaKind kind) {
         ValueNode index = frameState.pop(JavaKind.Int);
         ValueNode array = frameState.pop(JavaKind.Object);
@@ -3664,7 +3675,8 @@
             }
         }
 
-        frameState.push(kind, append(genLoadIndexed(array, index, boundsCheck, kind)));
+        JavaKind actualKind = refineComponentType(array, kind);
+        frameState.push(actualKind, append(genLoadIndexed(array, index, boundsCheck, actualKind)));
     }
 
     private void genStoreIndexed(JavaKind kind) {
@@ -3682,7 +3694,8 @@
             }
         }
 
-        genStoreIndexed(array, index, boundsCheck, storeCheck, kind, value);
+        JavaKind actualKind = refineComponentType(array, kind);
+        genStoreIndexed(array, index, boundsCheck, storeCheck, actualKind, maskSubWordValue(value, actualKind));
     }
 
     private void genArithmeticOp(JavaKind kind, int opcode) {
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/FrameStateBuilder.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/FrameStateBuilder.java	Tue Jun 19 16:33:07 2018 +0100
@@ -221,7 +221,12 @@
                 stamp = plugins.getOverridingStamp(tool, type, false);
             }
             if (stamp == null) {
-                stamp = StampFactory.forDeclaredType(assumptions, type, false);
+                // GR-714: subword inputs cannot be trusted
+                if (kind.getStackKind() != kind) {
+                    stamp = StampPair.createSingle(StampFactory.forKind(JavaKind.Int));
+                } else {
+                    stamp = StampFactory.forDeclaredType(assumptions, type, false);
+                }
             }
 
             FloatingNode param = null;
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64AtomicMove.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64AtomicMove.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,12 +23,15 @@
 package org.graalvm.compiler.lir.aarch64;
 
 import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.CONST;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
 
 import org.graalvm.compiler.asm.Label;
 import org.graalvm.compiler.asm.aarch64.AArch64Assembler;
-import org.graalvm.compiler.asm.aarch64.AArch64Assembler.ShiftType;
 import org.graalvm.compiler.asm.aarch64.AArch64MacroAssembler;
+import org.graalvm.compiler.asm.aarch64.AArch64MacroAssembler.ScratchRegister;
 import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.LIRValueUtil;
 import org.graalvm.compiler.lir.Opcode;
 import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
 
@@ -75,7 +78,7 @@
             Register address = asRegister(addressValue);
             Register result = asRegister(resultValue);
             Register newVal = asRegister(newValue);
-            if (AArch64LIRFlagsVersioned.useLSE(masm)) {
+            if (AArch64LIRFlagsVersioned.useLSE(masm.target.arch)) {
                 Register expected = asRegister(expectedValue);
                 masm.mov(size, result, expected);
                 masm.cas(size, expected, newVal, address, true /* acquire */, true /* release */);
@@ -113,20 +116,79 @@
 
         private final AArch64Kind accessKind;
 
-        @Def protected AllocatableValue resultValue;
-        @Alive protected AllocatableValue addressValue;
-        @Alive protected Value deltaValue;
-        @Temp protected AllocatableValue scratchValue1;
-        @Temp protected AllocatableValue scratchValue2;
+        @Def({REG}) protected AllocatableValue resultValue;
+        @Alive({REG}) protected AllocatableValue addressValue;
+        @Alive({REG, CONST}) protected Value deltaValue;
 
-        public AtomicReadAndAddOp(AArch64Kind kind, AllocatableValue result, AllocatableValue address, Value delta, AllocatableValue scratch1, AllocatableValue scratch2) {
+        public AtomicReadAndAddOp(AArch64Kind kind, AllocatableValue result, AllocatableValue address, Value delta) {
             super(TYPE);
             this.accessKind = kind;
             this.resultValue = result;
             this.addressValue = address;
             this.deltaValue = delta;
-            this.scratchValue1 = scratch1;
-            this.scratchValue2 = scratch2;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AArch64MacroAssembler masm) {
+            assert accessKind.isInteger();
+            final int size = accessKind.getSizeInBytes() * Byte.SIZE;
+
+            Register address = asRegister(addressValue);
+            Register result = asRegister(resultValue);
+
+            Label retry = new Label();
+            masm.bind(retry);
+            masm.ldaxr(size, result, address);
+            try (ScratchRegister scratchRegister1 = masm.getScratchRegister()) {
+                Register scratch1 = scratchRegister1.getRegister();
+                if (LIRValueUtil.isConstantValue(deltaValue)) {
+                    long delta = LIRValueUtil.asConstantValue(deltaValue).getJavaConstant().asLong();
+                    masm.add(size, scratch1, result, delta);
+                } else { // must be a register then
+                    masm.add(size, scratch1, result, asRegister(deltaValue));
+                }
+                try (ScratchRegister scratchRegister2 = masm.getScratchRegister()) {
+                    Register scratch2 = scratchRegister2.getRegister();
+                    masm.stlxr(size, scratch2, scratch1, address);
+                    // if scratch2 == 0 then write successful, else retry
+                    masm.cbnz(32, scratch2, retry);
+                }
+            }
+        }
+    }
+
+    /**
+     * Load (Read) and Add instruction. Does the following atomically: <code>
+     *  ATOMIC_READ_AND_ADD(addend, result, address):
+     *    result = *address
+     *    *address = result + addend
+     *    return result
+     * </code>
+     *
+     * The LSE version has different properties with regards to the register allocator. To define
+     * these differences, we have to create a separate LIR instruction class.
+     *
+     * The difference to {@linkplain AtomicReadAndAddOp} is:
+     * <li>{@linkplain #deltaValue} must be a register (@Use({REG}) instead @Alive({REG,CONST}))
+     * <li>{@linkplain #resultValue} may be an alias for the input registers (@Use instead
+     * of @Alive)
+     */
+    @Opcode("ATOMIC_READ_AND_ADD")
+    public static final class AtomicReadAndAddLSEOp extends AArch64LIRInstruction {
+        public static final LIRInstructionClass<AtomicReadAndAddLSEOp> TYPE = LIRInstructionClass.create(AtomicReadAndAddLSEOp.class);
+
+        private final AArch64Kind accessKind;
+
+        @Def({REG}) protected AllocatableValue resultValue;
+        @Use({REG}) protected AllocatableValue addressValue;
+        @Use({REG}) protected AllocatableValue deltaValue;
+
+        public AtomicReadAndAddLSEOp(AArch64Kind kind, AllocatableValue result, AllocatableValue address, AllocatableValue delta) {
+            super(TYPE);
+            this.accessKind = kind;
+            this.resultValue = result;
+            this.addressValue = address;
+            this.deltaValue = delta;
         }
 
         @Override
@@ -137,19 +199,57 @@
             Register address = asRegister(addressValue);
             Register delta = asRegister(deltaValue);
             Register result = asRegister(resultValue);
+            masm.ldadd(size, delta, result, address, true, true);
+        }
+    }
 
-            if (AArch64LIRFlagsVersioned.useLSE(masm)) {
-                masm.ldadd(size, delta, result, address, true, true);
+    /**
+     * Load (Read) and Write instruction. Does the following atomically: <code>
+     *  ATOMIC_READ_AND_WRITE(newValue, result, address):
+     *    result = *address
+     *    *address = newValue
+     *    return result
+     * </code>
+     */
+    @Opcode("ATOMIC_READ_AND_WRITE")
+    public static final class AtomicReadAndWriteOp extends AArch64LIRInstruction {
+        public static final LIRInstructionClass<AtomicReadAndWriteOp> TYPE = LIRInstructionClass.create(AtomicReadAndWriteOp.class);
+
+        private final AArch64Kind accessKind;
+
+        @Def protected AllocatableValue resultValue;
+        @Alive protected AllocatableValue addressValue;
+        @Alive protected AllocatableValue newValue;
+        @Temp protected AllocatableValue scratchValue;
+
+        public AtomicReadAndWriteOp(AArch64Kind kind, AllocatableValue result, AllocatableValue address, AllocatableValue newValue, AllocatableValue scratch) {
+            super(TYPE);
+            this.accessKind = kind;
+            this.resultValue = result;
+            this.addressValue = address;
+            this.newValue = newValue;
+            this.scratchValue = scratch;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AArch64MacroAssembler masm) {
+            assert accessKind.isInteger();
+            final int size = accessKind.getSizeInBytes() * Byte.SIZE;
+
+            Register address = asRegister(addressValue);
+            Register value = asRegister(newValue);
+            Register result = asRegister(resultValue);
+
+            if (AArch64LIRFlagsVersioned.useLSE(masm.target.arch)) {
+                masm.swp(size, value, result, address, true, true);
             } else {
-                Register scratch1 = asRegister(scratchValue1);
-                Register scratch2 = asRegister(scratchValue2);
+                Register scratch = asRegister(scratchValue);
                 Label retry = new Label();
                 masm.bind(retry);
                 masm.ldaxr(size, result, address);
-                masm.add(size, scratch1, result, delta, ShiftType.LSL, 0);
-                masm.stlxr(size, scratch2, scratch1, address);
-                // if scratch2 == 0 then write successful, else retry
-                masm.cbnz(32, scratch2, retry);
+                masm.stlxr(size, scratch, value, address);
+                // if scratch == 0 then write successful, else retry
+                masm.cbnz(32, scratch, retry);
             }
         }
     }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64LIRFlagsVersioned.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64LIRFlagsVersioned.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,13 +22,14 @@
  */
 package org.graalvm.compiler.lir.aarch64;
 
-import org.graalvm.compiler.asm.aarch64.AArch64MacroAssembler;
-
+import jdk.vm.ci.aarch64.AArch64;
 import jdk.vm.ci.aarch64.AArch64.CPUFeature;
 import jdk.vm.ci.aarch64.AArch64.Flag;
+import jdk.vm.ci.code.Architecture;
 
 public class AArch64LIRFlagsVersioned {
-    public static boolean useLSE(AArch64MacroAssembler masm) {
-        return masm.supports(CPUFeature.LSE) || masm.isFlagSet(Flag.UseLSE);
+    public static boolean useLSE(Architecture arch) {
+        AArch64 aarch64 = (AArch64) arch;
+        return aarch64.getFeatures().contains(CPUFeature.LSE) || aarch64.getFlags().contains(Flag.UseLSE);
     }
-}
+}
\ No newline at end of file
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/AMD64ArrayCompareToOp.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/AMD64ArrayCompareToOp.java	Tue Jun 19 16:33:07 2018 +0100
@@ -32,7 +32,6 @@
 
 import java.lang.reflect.Array;
 import java.lang.reflect.Field;
-import java.util.EnumSet;
 
 import org.graalvm.compiler.asm.Label;
 import org.graalvm.compiler.asm.amd64.AMD64Address;
@@ -125,10 +124,9 @@
         return arch.getFeatures().contains(CPUFeature.AVX2);
     }
 
-    private static boolean supportsAVX512VLBW(TargetDescription target) {
-        AMD64 arch = (AMD64) target.arch;
-        EnumSet<CPUFeature> features = arch.getFeatures();
-        return features.contains(CPUFeature.AVX512BW) && features.contains(CPUFeature.AVX512VL);
+    private static boolean supportsAVX512VLBW(@SuppressWarnings("unused") TargetDescription target) {
+        // TODO Add EVEX encoder in our assembler.
+        return false;
     }
 
     @Override
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorBinary.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import jdk.vm.ci.meta.AllocatableValue;
+import org.graalvm.compiler.asm.amd64.AMD64Address;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AVXKind;
+import org.graalvm.compiler.lir.LIRFrameState;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.Opcode;
+import org.graalvm.compiler.lir.amd64.AMD64AddressValue;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static jdk.vm.ci.code.ValueUtil.isRegister;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.COMPOSITE;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.STACK;
+
+public class AMD64VectorBinary {
+
+    public static final class AVXBinaryOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXBinaryOp> TYPE = LIRInstructionClass.create(AVXBinaryOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRVMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue x;
+        @Use({REG, STACK}) protected AllocatableValue y;
+
+        public AVXBinaryOp(AMD64VectorAssembler.VexRVMOp opcode, AVXKind.AVXSize size, AllocatableValue result, AllocatableValue x, AllocatableValue y) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.x = x;
+            this.y = y;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(y)) {
+                opcode.emit(vasm, size, asRegister(result), asRegister(x), asRegister(y));
+            } else {
+                opcode.emit(vasm, size, asRegister(result), asRegister(x), (AMD64Address) crb.asAddress(y));
+            }
+        }
+    }
+
+    public static final class AVXBinaryConstOp extends AMD64VectorLIRInstruction {
+
+        public static final LIRInstructionClass<AVXBinaryConstOp> TYPE = LIRInstructionClass.create(AVXBinaryConstOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRRIOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue x;
+        protected int y;
+
+        public AVXBinaryConstOp(AMD64VectorAssembler.VexRRIOp opcode, AVXKind.AVXSize size, AllocatableValue result, AllocatableValue x, int y) {
+            super(TYPE);
+            assert (y & 0xFF) == y;
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.x = x;
+            this.y = y;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            opcode.emit(vasm, size, asRegister(result), asRegister(x), y);
+        }
+    }
+
+    public static final class AVXBinaryMemoryOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXBinaryMemoryOp> TYPE = LIRInstructionClass.create(AVXBinaryMemoryOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRVMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue x;
+        @Use({COMPOSITE}) protected AMD64AddressValue y;
+        @State protected LIRFrameState state;
+
+        public AVXBinaryMemoryOp(AMD64VectorAssembler.VexRVMOp opcode, AVXKind.AVXSize size, AllocatableValue result, AllocatableValue x, AMD64AddressValue y, LIRFrameState state) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.x = x;
+            this.y = y;
+            this.state = state;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (state != null) {
+                crb.recordImplicitException(vasm.position(), state);
+            }
+            opcode.emit(vasm, size, asRegister(result), asRegister(x), y.toAddress());
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorClearOp.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMOp.VPXOR;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMOp.VXORPD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMOp.VXORPS;
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.XMM;
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+
+import org.graalvm.compiler.lir.LIRInstruction;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AVXKind;
+
+import jdk.vm.ci.amd64.AMD64Kind;
+import jdk.vm.ci.code.Register;
+import jdk.vm.ci.meta.AllocatableValue;
+
+public class AMD64VectorClearOp extends AMD64VectorLIRInstruction {
+    public static final LIRInstructionClass<AMD64VectorClearOp> TYPE = LIRInstructionClass.create(AMD64VectorClearOp.class);
+
+    protected @LIRInstruction.Def({REG}) AllocatableValue result;
+
+    public AMD64VectorClearOp(AllocatableValue result) {
+        this(TYPE, result);
+    }
+
+    protected AMD64VectorClearOp(LIRInstructionClass<? extends AMD64VectorClearOp> c, AllocatableValue result) {
+        super(c);
+        this.result = result;
+    }
+
+    @Override
+    public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+        AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+        Register register = asRegister(result);
+
+        switch (kind.getScalar()) {
+            case SINGLE:
+                VXORPS.emit(vasm, AVXKind.getRegisterSize(kind), register, register, register);
+                break;
+
+            case DOUBLE:
+                VXORPD.emit(vasm, AVXKind.getRegisterSize(kind), register, register, register);
+                break;
+
+            default:
+                // on AVX1, YMM VPXOR is not supported - still it is possible to clear the whole YMM
+                // register as the upper 128-bit are implicitly cleared by the AVX1 instruction.
+                VPXOR.emit(vasm, XMM, register, register, register);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorCompareOp.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.STACK;
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static jdk.vm.ci.code.ValueUtil.isRegister;
+import jdk.vm.ci.meta.AllocatableValue;
+
+import org.graalvm.compiler.asm.amd64.AMD64Address;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRMOp;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.Opcode;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+import org.graalvm.compiler.asm.amd64.AVXKind.AVXSize;
+
+public final class AMD64VectorCompareOp extends AMD64VectorLIRInstruction {
+    public static final LIRInstructionClass<AMD64VectorCompareOp> TYPE = LIRInstructionClass.create(AMD64VectorCompareOp.class);
+
+    @Opcode private final VexRMOp opcode;
+    @Use({REG}) protected AllocatableValue x;
+    @Use({REG, STACK}) protected AllocatableValue y;
+
+    public AMD64VectorCompareOp(VexRMOp opcode, AllocatableValue x, AllocatableValue y) {
+        super(TYPE);
+        this.opcode = opcode;
+        this.x = x;
+        this.y = y;
+    }
+
+    @Override
+    public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+        if (isRegister(y)) {
+            opcode.emit(vasm, AVXSize.XMM, asRegister(x), asRegister(y));
+        } else {
+            opcode.emit(vasm, AVXSize.XMM, asRegister(x), (AMD64Address) crb.asAddress(y));
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorLIRInstruction.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.amd64.AMD64LIRInstruction;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+public abstract class AMD64VectorLIRInstruction extends AMD64LIRInstruction {
+    public static final LIRInstructionClass<AMD64VectorLIRInstruction> TYPE = LIRInstructionClass.create(AMD64VectorLIRInstruction.class);
+
+    protected AMD64VectorLIRInstruction(LIRInstructionClass<? extends AMD64LIRInstruction> c) {
+        super(c);
+    }
+
+    @Override
+    public final void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) {
+        emitCode(crb, (AMD64VectorAssembler) masm);
+    }
+
+    public abstract void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorMove.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,434 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static jdk.vm.ci.code.ValueUtil.isRegister;
+import static jdk.vm.ci.code.ValueUtil.isStackSlot;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVDQU;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVQ;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVSD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVSS;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVUPD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVUPS;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMOp.VXORPD;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.COMPOSITE;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.HINT;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.STACK;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.UNINITIALIZED;
+
+import org.graalvm.compiler.asm.amd64.AMD64Address;
+import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp;
+import org.graalvm.compiler.asm.amd64.AVXKind;
+import org.graalvm.compiler.asm.amd64.AVXKind.AVXSize;
+import org.graalvm.compiler.debug.GraalError;
+import org.graalvm.compiler.lir.LIRFrameState;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.Opcode;
+import org.graalvm.compiler.lir.StandardOp.LoadConstantOp;
+import org.graalvm.compiler.lir.StandardOp.ValueMoveOp;
+import org.graalvm.compiler.lir.amd64.AMD64AddressValue;
+import org.graalvm.compiler.lir.amd64.AMD64Move;
+import org.graalvm.compiler.lir.amd64.AMD64RestoreRegistersOp;
+import org.graalvm.compiler.lir.amd64.AMD64SaveRegistersOp;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+import jdk.vm.ci.amd64.AMD64Kind;
+import jdk.vm.ci.code.Register;
+import jdk.vm.ci.code.RegisterValue;
+import jdk.vm.ci.code.StackSlot;
+import jdk.vm.ci.meta.AllocatableValue;
+import jdk.vm.ci.meta.Constant;
+import jdk.vm.ci.meta.JavaConstant;
+import jdk.vm.ci.meta.Value;
+
+public class AMD64VectorMove {
+
+    @Opcode("VMOVE")
+    public static final class MoveToRegOp extends AMD64VectorLIRInstruction implements ValueMoveOp {
+        public static final LIRInstructionClass<MoveToRegOp> TYPE = LIRInstructionClass.create(MoveToRegOp.class);
+
+        @Def({REG, HINT}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue input;
+
+        public MoveToRegOp(AllocatableValue result, AllocatableValue input) {
+            super(TYPE);
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            move(crb, vasm, result, input);
+        }
+
+        @Override
+        public AllocatableValue getInput() {
+            return input;
+        }
+
+        @Override
+        public AllocatableValue getResult() {
+            return result;
+        }
+    }
+
+    @Opcode("VMOVE")
+    public static final class MoveFromRegOp extends AMD64VectorLIRInstruction implements ValueMoveOp {
+        public static final LIRInstructionClass<MoveFromRegOp> TYPE = LIRInstructionClass.create(MoveFromRegOp.class);
+
+        @Def({REG, STACK}) protected AllocatableValue result;
+        @Use({REG, HINT}) protected AllocatableValue input;
+
+        public MoveFromRegOp(AllocatableValue result, AllocatableValue input) {
+            super(TYPE);
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            move(crb, vasm, result, input);
+        }
+
+        @Override
+        public AllocatableValue getInput() {
+            return input;
+        }
+
+        @Override
+        public AllocatableValue getResult() {
+            return result;
+        }
+    }
+
+    @Opcode("VMOVE")
+    public static class MoveFromConstOp extends AMD64VectorLIRInstruction implements LoadConstantOp {
+        public static final LIRInstructionClass<MoveFromConstOp> TYPE = LIRInstructionClass.create(MoveFromConstOp.class);
+
+        @Def({REG, STACK}) protected AllocatableValue result;
+        private final JavaConstant input;
+
+        public MoveFromConstOp(AllocatableValue result, JavaConstant input) {
+            super(TYPE);
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(result)) {
+                const2reg(crb, vasm, (RegisterValue) result, input);
+            } else {
+                assert isStackSlot(result);
+                AMD64Move.const2stack(crb, vasm, result, input);
+            }
+        }
+
+        @Override
+        public Constant getConstant() {
+            return input;
+        }
+
+        @Override
+        public AllocatableValue getResult() {
+            return result;
+        }
+    }
+
+    @Opcode("VSTACKMOVE")
+    public static final class StackMoveOp extends AMD64VectorLIRInstruction implements ValueMoveOp {
+        public static final LIRInstructionClass<StackMoveOp> TYPE = LIRInstructionClass.create(StackMoveOp.class);
+
+        @Def({STACK}) protected AllocatableValue result;
+        @Use({STACK, HINT}) protected AllocatableValue input;
+        @Alive({STACK, UNINITIALIZED}) private AllocatableValue backupSlot;
+
+        private Register scratch;
+
+        public StackMoveOp(AllocatableValue result, AllocatableValue input, Register scratch, AllocatableValue backupSlot) {
+            super(TYPE);
+            this.result = result;
+            this.input = input;
+            this.backupSlot = backupSlot;
+            this.scratch = scratch;
+        }
+
+        @Override
+        public AllocatableValue getInput() {
+            return input;
+        }
+
+        @Override
+        public AllocatableValue getResult() {
+            return result;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler masm) {
+            // backup scratch register
+            move(crb, masm, backupSlot, scratch.asValue(backupSlot.getValueKind()));
+            // move stack slot
+            move(crb, masm, scratch.asValue(getInput().getValueKind()), getInput());
+            move(crb, masm, getResult(), scratch.asValue(getResult().getValueKind()));
+            // restore scratch register
+            move(crb, masm, scratch.asValue(backupSlot.getValueKind()), backupSlot);
+
+        }
+    }
+
+    public abstract static class VectorMemOp extends AMD64VectorLIRInstruction {
+
+        protected final AVXSize size;
+        protected final VexMoveOp op;
+
+        @Use({COMPOSITE}) protected AMD64AddressValue address;
+        @State protected LIRFrameState state;
+
+        protected VectorMemOp(LIRInstructionClass<? extends VectorMemOp> c, AVXSize size, VexMoveOp op, AMD64AddressValue address, LIRFrameState state) {
+            super(c);
+            this.size = size;
+            this.op = op;
+            this.address = address;
+            this.state = state;
+        }
+
+        protected abstract void emitMemAccess(AMD64VectorAssembler vasm);
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (state != null) {
+                crb.recordImplicitException(vasm.position(), state);
+            }
+            emitMemAccess(vasm);
+        }
+    }
+
+    public static final class VectorLoadOp extends VectorMemOp {
+        public static final LIRInstructionClass<VectorLoadOp> TYPE = LIRInstructionClass.create(VectorLoadOp.class);
+
+        @Def({REG}) protected AllocatableValue result;
+
+        public VectorLoadOp(AVXSize size, VexMoveOp op, AllocatableValue result, AMD64AddressValue address, LIRFrameState state) {
+            super(TYPE, size, op, address, state);
+            this.result = result;
+        }
+
+        @Override
+        public void emitMemAccess(AMD64VectorAssembler vasm) {
+            op.emit(vasm, size, asRegister(result), address.toAddress());
+        }
+    }
+
+    public static class VectorStoreOp extends VectorMemOp {
+        public static final LIRInstructionClass<VectorStoreOp> TYPE = LIRInstructionClass.create(VectorStoreOp.class);
+
+        @Use({REG}) protected AllocatableValue input;
+
+        public VectorStoreOp(AVXSize size, VexMoveOp op, AMD64AddressValue address, AllocatableValue input, LIRFrameState state) {
+            super(TYPE, size, op, address, state);
+            this.input = input;
+        }
+
+        @Override
+        public void emitMemAccess(AMD64VectorAssembler vasm) {
+            op.emit(vasm, size, address.toAddress(), asRegister(input));
+        }
+    }
+
+    @Opcode("SAVE_REGISTER")
+    public static class SaveRegistersOp extends AMD64SaveRegistersOp {
+        public static final LIRInstructionClass<SaveRegistersOp> TYPE = LIRInstructionClass.create(SaveRegistersOp.class);
+
+        public SaveRegistersOp(Register[] savedRegisters, AllocatableValue[] slots, boolean supportsRemove) {
+            super(TYPE, savedRegisters, slots, supportsRemove);
+        }
+
+        @Override
+        protected void saveRegister(CompilationResultBuilder crb, AMD64MacroAssembler masm, StackSlot result, Register register) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+            if (kind.isXMM()) {
+                VexMoveOp op;
+                if (kind.getVectorLength() > 1) {
+                    op = getVectorMoveOp(kind.getScalar());
+                } else {
+                    op = getScalarMoveOp(kind);
+                }
+
+                AMD64Address addr = (AMD64Address) crb.asAddress(result);
+                op.emit((AMD64VectorAssembler) masm, AVXKind.getRegisterSize(kind), addr, register);
+            } else {
+                super.saveRegister(crb, masm, result, register);
+            }
+        }
+    }
+
+    @Opcode("RESTORE_REGISTER")
+    public static final class RestoreRegistersOp extends AMD64RestoreRegistersOp {
+        public static final LIRInstructionClass<RestoreRegistersOp> TYPE = LIRInstructionClass.create(RestoreRegistersOp.class);
+
+        public RestoreRegistersOp(AllocatableValue[] source, AMD64SaveRegistersOp save) {
+            super(TYPE, source, save);
+        }
+
+        @Override
+        protected void restoreRegister(CompilationResultBuilder crb, AMD64MacroAssembler masm, Register register, StackSlot input) {
+            AMD64Kind kind = (AMD64Kind) input.getPlatformKind();
+            if (kind.isXMM()) {
+                VexMoveOp op;
+                if (kind.getVectorLength() > 1) {
+                    op = getVectorMoveOp(kind.getScalar());
+                } else {
+                    op = getScalarMoveOp(kind);
+                }
+
+                AMD64Address addr = (AMD64Address) crb.asAddress(input);
+                op.emit((AMD64VectorAssembler) masm, AVXKind.getRegisterSize(kind), register, addr);
+            } else {
+                super.restoreRegister(crb, masm, register, input);
+            }
+        }
+    }
+
+    private static VexMoveOp getScalarMoveOp(AMD64Kind kind) {
+        switch (kind) {
+            case SINGLE:
+                return VMOVSS;
+            case DOUBLE:
+                return VMOVSD;
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+    }
+
+    private static VexMoveOp getVectorMoveOp(AMD64Kind kind) {
+        switch (kind) {
+            case SINGLE:
+                return VMOVUPS;
+            case DOUBLE:
+                return VMOVUPD;
+            default:
+                return VMOVDQU;
+        }
+    }
+
+    private static VexMoveOp getVectorMemMoveOp(AMD64Kind kind) {
+        switch (AVXKind.getDataSize(kind)) {
+            case DWORD:
+                return VMOVD;
+            case QWORD:
+                return VMOVQ;
+            default:
+                return getVectorMoveOp(kind.getScalar());
+        }
+    }
+
+    private static void move(CompilationResultBuilder crb, AMD64VectorAssembler vasm, AllocatableValue result, Value input) {
+        VexMoveOp op;
+        AVXSize size;
+        AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+        if (kind.getVectorLength() > 1) {
+            size = AVXKind.getRegisterSize(kind);
+            if (isRegister(input) && isRegister(result)) {
+                op = getVectorMoveOp(kind.getScalar());
+            } else {
+                op = getVectorMemMoveOp(kind);
+            }
+        } else {
+            size = AVXSize.XMM;
+            if (isRegister(input) && isRegister(result)) {
+                op = getVectorMoveOp(kind);
+            } else {
+                op = getScalarMoveOp(kind);
+            }
+        }
+
+        if (isRegister(input)) {
+            if (isRegister(result)) {
+                if (!asRegister(input).equals(asRegister(result))) {
+                    op.emit(vasm, size, asRegister(result), asRegister(input));
+                }
+            } else {
+                assert isStackSlot(result);
+                op.emit(vasm, size, (AMD64Address) crb.asAddress(result), asRegister(input));
+            }
+        } else {
+            assert isStackSlot(input) && isRegister(result);
+            op.emit(vasm, size, asRegister(result), (AMD64Address) crb.asAddress(input));
+        }
+    }
+
+    private static void const2reg(CompilationResultBuilder crb, AMD64VectorAssembler vasm, RegisterValue result, JavaConstant input) {
+        if (input.isDefaultForKind()) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+            Register register = result.getRegister();
+            VXORPD.emit(vasm, AVXKind.getRegisterSize(kind), register, register, register);
+            return;
+        }
+
+        AMD64Address address;
+        switch (input.getJavaKind()) {
+            case Float:
+                address = (AMD64Address) crb.asFloatConstRef(input);
+                break;
+
+            case Double:
+                address = (AMD64Address) crb.asDoubleConstRef(input);
+                break;
+
+            default:
+                throw GraalError.shouldNotReachHere();
+        }
+        VexMoveOp op = getScalarMoveOp((AMD64Kind) result.getPlatformKind());
+        op.emit(vasm, AVXSize.XMM, asRegister(result), address);
+    }
+
+    public static final class AVXMoveToIntOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXMoveToIntOp> TYPE = LIRInstructionClass.create(AVXMoveToIntOp.class);
+
+        @Opcode private final VexMoveOp opcode;
+
+        @Def({REG, STACK}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue input;
+
+        public AVXMoveToIntOp(VexMoveOp opcode, AllocatableValue result, AllocatableValue input) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(result)) {
+                opcode.emitReverse(vasm, AVXSize.XMM, asRegister(result), asRegister(input));
+            } else {
+                opcode.emit(vasm, AVXSize.XMM, (AMD64Address) crb.asAddress(result), asRegister(input));
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorShuffle.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static jdk.vm.ci.code.ValueUtil.isRegister;
+import static jdk.vm.ci.code.ValueUtil.isStackSlot;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VEXTRACTF128;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VEXTRACTI128;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VPEXTRB;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VPEXTRD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VPEXTRQ;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp.VPEXTRW;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMoveOp.VMOVQ;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMIOp.VINSERTF128;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMIOp.VINSERTI128;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMIOp.VSHUFPD;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMIOp.VSHUFPS;
+import static org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMOp.VPSHUFB;
+import static org.graalvm.compiler.asm.amd64.AVXKind.AVXSize.XMM;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.STACK;
+
+import org.graalvm.compiler.asm.amd64.AMD64Address;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexMRIOp;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRMIOp;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler.VexRVMIOp;
+import org.graalvm.compiler.asm.amd64.AVXKind;
+import org.graalvm.compiler.debug.GraalError;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+import jdk.vm.ci.amd64.AMD64;
+import jdk.vm.ci.amd64.AMD64.CPUFeature;
+import jdk.vm.ci.amd64.AMD64Kind;
+import jdk.vm.ci.meta.AllocatableValue;
+
+public class AMD64VectorShuffle {
+
+    public static final class IntToVectorOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<IntToVectorOp> TYPE = LIRInstructionClass.create(IntToVectorOp.class);
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue value;
+
+        public IntToVectorOp(AllocatableValue result, AllocatableValue value) {
+            super(TYPE);
+            assert ((AMD64Kind) result.getPlatformKind()).getScalar().isInteger() : result.getPlatformKind();
+            this.result = result;
+            this.value = value;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(value)) {
+                VMOVD.emit(vasm, XMM, asRegister(result), asRegister(value));
+            } else {
+                assert isStackSlot(value);
+                VMOVD.emit(vasm, XMM, asRegister(result), (AMD64Address) crb.asAddress(value));
+            }
+        }
+    }
+
+    public static final class LongToVectorOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<LongToVectorOp> TYPE = LIRInstructionClass.create(LongToVectorOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue value;
+
+        public LongToVectorOp(AllocatableValue result, AllocatableValue value) {
+            super(TYPE);
+            assert result.getPlatformKind() == AMD64Kind.V128_QWORD || result.getPlatformKind() == AMD64Kind.V256_QWORD;
+            this.result = result;
+            this.value = value;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(value)) {
+                VMOVQ.emit(vasm, XMM, asRegister(result), asRegister(value));
+            } else {
+                assert isStackSlot(value);
+                VMOVQ.emit(vasm, XMM, asRegister(result), (AMD64Address) crb.asAddress(value));
+            }
+        }
+    }
+
+    public static final class ShuffleBytesOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ShuffleBytesOp> TYPE = LIRInstructionClass.create(ShuffleBytesOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue source;
+        @Use({REG, STACK}) protected AllocatableValue selector;
+
+        public ShuffleBytesOp(AllocatableValue result, AllocatableValue source, AllocatableValue selector) {
+            super(TYPE);
+            this.result = result;
+            this.source = source;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+            if (isRegister(selector)) {
+                VPSHUFB.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source), asRegister(selector));
+            } else {
+                assert isStackSlot(selector);
+                VPSHUFB.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source), (AMD64Address) crb.asAddress(selector));
+            }
+        }
+    }
+
+    public static final class ConstShuffleBytesOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ConstShuffleBytesOp> TYPE = LIRInstructionClass.create(ConstShuffleBytesOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue source;
+        private final byte[] selector;
+
+        public ConstShuffleBytesOp(AllocatableValue result, AllocatableValue source, byte... selector) {
+            super(TYPE);
+            assert AVXKind.getRegisterSize(((AMD64Kind) result.getPlatformKind())).getBytes() == selector.length;
+            this.result = result;
+            this.source = source;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+            AMD64Address address = (AMD64Address) crb.recordDataReferenceInCode(selector, selector.length);
+            VPSHUFB.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source), address);
+        }
+    }
+
+    public static class ShuffleWordOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ShuffleWordOp> TYPE = LIRInstructionClass.create(ShuffleWordOp.class);
+        private final VexRMIOp op;
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue source;
+        private final int selector;
+
+        public ShuffleWordOp(VexRMIOp op, AllocatableValue result, AllocatableValue source, int selector) {
+            super(TYPE);
+            this.op = op;
+            this.result = result;
+            this.source = source;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) source.getPlatformKind();
+            if (isRegister(source)) {
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source), selector);
+            } else {
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), (AMD64Address) crb.asAddress(source), selector);
+            }
+        }
+    }
+
+    public static class ShuffleFloatOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ShuffleFloatOp> TYPE = LIRInstructionClass.create(ShuffleFloatOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue source1;
+        @Use({REG, STACK}) protected AllocatableValue source2;
+        private final int selector;
+
+        public ShuffleFloatOp(AllocatableValue result, AllocatableValue source1, AllocatableValue source2, int selector) {
+            super(TYPE);
+            this.result = result;
+            this.source1 = source1;
+            this.source2 = source2;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+
+            VexRVMIOp op;
+            switch (kind.getScalar()) {
+                case SINGLE:
+                    op = VSHUFPS;
+                    break;
+                case DOUBLE:
+                    op = VSHUFPD;
+                    break;
+                default:
+                    throw GraalError.shouldNotReachHere();
+            }
+
+            if (isRegister(source2)) {
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source1), asRegister(source2), selector);
+            } else {
+                assert isStackSlot(source2);
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source1), (AMD64Address) crb.asAddress(source2), selector);
+            }
+        }
+    }
+
+    public static final class Extract128Op extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<Extract128Op> TYPE = LIRInstructionClass.create(Extract128Op.class);
+        @Def({REG, STACK}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue source;
+        private final int selector;
+
+        public Extract128Op(AllocatableValue result, AllocatableValue source, int selector) {
+            super(TYPE);
+            this.result = result;
+            this.source = source;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) source.getPlatformKind();
+
+            VexMRIOp op;
+            switch (kind.getScalar()) {
+                case SINGLE:
+                case DOUBLE:
+                    op = VEXTRACTF128;
+                    break;
+                default:
+                    AMD64 arch = (AMD64) crb.target.arch;
+                    // if supported we want VEXTRACTI128
+                    // on AVX1, we have to use VEXTRACTF128
+                    op = arch.getFeatures().contains(CPUFeature.AVX2) ? VEXTRACTI128 : VEXTRACTF128;
+                    break;
+            }
+
+            if (isRegister(result)) {
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source), selector);
+            } else {
+                assert isStackSlot(result);
+                op.emit(vasm, AVXKind.getRegisterSize(kind), (AMD64Address) crb.asAddress(result), asRegister(source), selector);
+            }
+        }
+    }
+
+    public static final class Insert128Op extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<Insert128Op> TYPE = LIRInstructionClass.create(Insert128Op.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue source1;
+        @Use({REG, STACK}) protected AllocatableValue source2;
+        private final int selector;
+
+        public Insert128Op(AllocatableValue result, AllocatableValue source1, AllocatableValue source2, int selector) {
+            super(TYPE);
+            this.result = result;
+            this.source1 = source1;
+            this.source2 = source2;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            AMD64Kind kind = (AMD64Kind) result.getPlatformKind();
+
+            VexRVMIOp op;
+            switch (kind.getScalar()) {
+                case SINGLE:
+                case DOUBLE:
+                    op = VINSERTF128;
+                    break;
+                default:
+                    AMD64 arch = (AMD64) crb.target.arch;
+                    // if supported we want VINSERTI128 - on AVX1, we have to use VINSERTF128.
+                    // using instructions with an incorrect data type is possible but typically
+                    // results in an additional overhead whenever the value is being accessed.
+                    op = arch.getFeatures().contains(CPUFeature.AVX2) ? VINSERTI128 : VINSERTF128;
+                    break;
+            }
+
+            if (isRegister(source2)) {
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source1), asRegister(source2), selector);
+            } else {
+                assert isStackSlot(source2);
+                op.emit(vasm, AVXKind.getRegisterSize(kind), asRegister(result), asRegister(source1), (AMD64Address) crb.asAddress(source2), selector);
+            }
+        }
+    }
+
+    public static final class ExtractByteOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ExtractByteOp> TYPE = LIRInstructionClass.create(ExtractByteOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue vector;
+        private final int selector;
+
+        public ExtractByteOp(AllocatableValue result, AllocatableValue vector, int selector) {
+            super(TYPE);
+            assert result.getPlatformKind() == AMD64Kind.DWORD;
+            assert ((AMD64Kind) vector.getPlatformKind()).getScalar() == AMD64Kind.BYTE;
+            this.result = result;
+            this.vector = vector;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            VPEXTRB.emit(vasm, XMM, asRegister(result), asRegister(vector), selector);
+        }
+    }
+
+    public static final class ExtractShortOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ExtractShortOp> TYPE = LIRInstructionClass.create(ExtractShortOp.class);
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue vector;
+        private final int selector;
+
+        public ExtractShortOp(AllocatableValue result, AllocatableValue vector, int selector) {
+            super(TYPE);
+            assert result.getPlatformKind() == AMD64Kind.DWORD;
+            assert ((AMD64Kind) vector.getPlatformKind()).getScalar() == AMD64Kind.WORD;
+            this.result = result;
+            this.vector = vector;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            VPEXTRW.emit(vasm, XMM, asRegister(result), asRegister(vector), selector);
+        }
+    }
+
+    public static final class ExtractIntOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ExtractIntOp> TYPE = LIRInstructionClass.create(ExtractIntOp.class);
+        @Def({REG, STACK}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue vector;
+        private final int selector;
+
+        public ExtractIntOp(AllocatableValue result, AllocatableValue vector, int selector) {
+            super(TYPE);
+            assert result.getPlatformKind() == AMD64Kind.DWORD;
+            assert ((AMD64Kind) vector.getPlatformKind()).getScalar() == AMD64Kind.DWORD;
+            this.result = result;
+            this.vector = vector;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(result)) {
+                if (selector == 0) {
+                    VMOVD.emitReverse(vasm, XMM, asRegister(result), asRegister(vector));
+                } else {
+                    VPEXTRD.emit(vasm, XMM, asRegister(result), asRegister(vector), selector);
+                }
+            } else {
+                assert isStackSlot(result);
+                if (selector == 0) {
+                    VMOVD.emit(vasm, XMM, (AMD64Address) crb.asAddress(result), asRegister(vector));
+                } else {
+                    VPEXTRD.emit(vasm, XMM, (AMD64Address) crb.asAddress(result), asRegister(vector), selector);
+                }
+            }
+        }
+    }
+
+    public static final class ExtractLongOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<ExtractLongOp> TYPE = LIRInstructionClass.create(ExtractLongOp.class);
+        @Def({REG, STACK}) protected AllocatableValue result;
+        @Use({REG}) protected AllocatableValue vector;
+        private final int selector;
+
+        public ExtractLongOp(AllocatableValue result, AllocatableValue vector, int selector) {
+            super(TYPE);
+            assert result.getPlatformKind() == AMD64Kind.QWORD;
+            assert ((AMD64Kind) vector.getPlatformKind()).getScalar() == AMD64Kind.QWORD;
+            this.result = result;
+            this.vector = vector;
+            this.selector = selector;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(result)) {
+                if (selector == 0) {
+                    VMOVQ.emitReverse(vasm, XMM, asRegister(result), asRegister(vector));
+                } else {
+                    VPEXTRQ.emit(vasm, XMM, asRegister(result), asRegister(vector), selector);
+                }
+            } else {
+                assert isStackSlot(result);
+                if (selector == 0) {
+                    VMOVQ.emit(vasm, XMM, (AMD64Address) crb.asAddress(result), asRegister(vector));
+                } else {
+                    VPEXTRQ.emit(vasm, XMM, (AMD64Address) crb.asAddress(result), asRegister(vector), selector);
+                }
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.amd64/src/org/graalvm/compiler/lir/amd64/vector/AMD64VectorUnary.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.lir.amd64.vector;
+
+import jdk.vm.ci.meta.AllocatableValue;
+import jdk.vm.ci.meta.Value;
+import org.graalvm.compiler.asm.amd64.AMD64Address;
+import org.graalvm.compiler.asm.amd64.AMD64VectorAssembler;
+import org.graalvm.compiler.asm.amd64.AVXKind;
+import org.graalvm.compiler.lir.LIRFrameState;
+import org.graalvm.compiler.lir.LIRInstructionClass;
+import org.graalvm.compiler.lir.Opcode;
+import org.graalvm.compiler.lir.amd64.AMD64AddressValue;
+import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
+
+import static jdk.vm.ci.code.ValueUtil.asRegister;
+import static jdk.vm.ci.code.ValueUtil.isRegister;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.COMPOSITE;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.CONST;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG;
+import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.STACK;
+import static org.graalvm.compiler.lir.LIRValueUtil.asConstant;
+import static org.graalvm.compiler.lir.LIRValueUtil.isConstantValue;
+
+public class AMD64VectorUnary {
+
+    public static final class AVXUnaryOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXUnaryOp> TYPE = LIRInstructionClass.create(AVXUnaryOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue input;
+
+        public AVXUnaryOp(AMD64VectorAssembler.VexRMOp opcode, AVXKind.AVXSize size, AllocatableValue result, AllocatableValue input) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(input)) {
+                opcode.emit(vasm, size, asRegister(result), asRegister(input));
+            } else {
+                opcode.emit(vasm, size, asRegister(result), (AMD64Address) crb.asAddress(input));
+            }
+        }
+    }
+
+    public static final class AVXUnaryMemoryOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXUnaryMemoryOp> TYPE = LIRInstructionClass.create(AVXUnaryMemoryOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({COMPOSITE}) protected AMD64AddressValue input;
+        @State protected LIRFrameState state;
+
+        public AVXUnaryMemoryOp(AMD64VectorAssembler.VexRMOp opcode, AVXKind.AVXSize size, AllocatableValue result, AMD64AddressValue input, LIRFrameState state) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.input = input;
+            this.state = state;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (state != null) {
+                crb.recordImplicitException(vasm.position(), state);
+            }
+            opcode.emit(vasm, size, asRegister(result), input.toAddress());
+        }
+    }
+
+    public static final class AVXBroadcastOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXBroadcastOp> TYPE = LIRInstructionClass.create(AVXBroadcastOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK, CONST}) protected Value input;
+
+        public AVXBroadcastOp(AMD64VectorAssembler.VexRMOp opcode, AVXKind.AVXSize size, AllocatableValue result, Value input) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(input)) {
+                opcode.emit(vasm, size, asRegister(result), asRegister(input));
+            } else if (isConstantValue(input)) {
+                int align = input.getPlatformKind().getSizeInBytes();
+                AMD64Address address = (AMD64Address) crb.recordDataReferenceInCode(asConstant(input), align);
+                opcode.emit(vasm, size, asRegister(result), address);
+            } else {
+                opcode.emit(vasm, size, asRegister(result), (AMD64Address) crb.asAddress(input));
+            }
+        }
+    }
+
+    public static final class AVXConvertMemoryOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXConvertMemoryOp> TYPE = LIRInstructionClass.create(AVXConvertMemoryOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRVMOp opcode;
+        private final AVXKind.AVXSize size;
+
+        @Def({REG}) protected AllocatableValue result;
+        @Use({COMPOSITE}) protected AMD64AddressValue input;
+        @State protected LIRFrameState state;
+
+        public AVXConvertMemoryOp(AMD64VectorAssembler.VexRVMOp opcode, AVXKind.AVXSize size, AllocatableValue result, AMD64AddressValue input, LIRFrameState state) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.size = size;
+            this.result = result;
+            this.input = input;
+            this.state = state;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (state != null) {
+                crb.recordImplicitException(vasm.position(), state);
+            }
+            opcode.emit(vasm, size, asRegister(result), asRegister(result), input.toAddress());
+        }
+    }
+
+    public static final class AVXConvertOp extends AMD64VectorLIRInstruction {
+        public static final LIRInstructionClass<AVXConvertOp> TYPE = LIRInstructionClass.create(AVXConvertOp.class);
+
+        @Opcode private final AMD64VectorAssembler.VexRVMOp opcode;
+        @Def({REG}) protected AllocatableValue result;
+        @Use({REG, STACK}) protected AllocatableValue input;
+
+        public AVXConvertOp(AMD64VectorAssembler.VexRVMOp opcode, AllocatableValue result, AllocatableValue input) {
+            super(TYPE);
+            this.opcode = opcode;
+            this.result = result;
+            this.input = input;
+        }
+
+        @Override
+        public void emitCode(CompilationResultBuilder crb, AMD64VectorAssembler vasm) {
+            if (isRegister(input)) {
+                if (!asRegister(input).equals(asRegister(result))) {
+                    // clear result register to avoid unnecessary dependency
+                    AMD64VectorAssembler.VexRVMOp.VXORPD.emit(vasm, AVXKind.AVXSize.XMM, asRegister(result), asRegister(result), asRegister(result));
+                }
+                opcode.emit(vasm, AVXKind.AVXSize.XMM, asRegister(result), asRegister(result), asRegister(input));
+            } else {
+                AMD64VectorAssembler.VexRVMOp.VXORPD.emit(vasm, AVXKind.AVXSize.XMM, asRegister(result), asRegister(result), asRegister(result));
+                opcode.emit(vasm, AVXKind.AVXSize.XMM, asRegister(result), asRegister(result), (AMD64Address) crb.asAddress(input));
+            }
+        }
+    }
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes.test/src/org/graalvm/compiler/nodes/test/ShortCircuitOrNodeTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes.test/src/org/graalvm/compiler/nodes/test/ShortCircuitOrNodeTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,24 +24,27 @@
 
 import java.util.function.Function;
 
-import org.junit.Assert;
-import org.junit.Test;
-
 import org.graalvm.compiler.core.test.GraalCompilerTest;
 import org.graalvm.compiler.nodes.ConstantNode;
 import org.graalvm.compiler.nodes.LogicNode;
 import org.graalvm.compiler.nodes.ShortCircuitOrNode;
 import org.graalvm.compiler.nodes.StructuredGraph;
+import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
 import org.graalvm.compiler.nodes.ValueNode;
-import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
 import org.graalvm.compiler.nodes.calc.ConditionalNode;
 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode;
 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
+import org.graalvm.compiler.nodes.spi.LoweringTool;
 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
+import org.graalvm.compiler.phases.common.FloatingReadPhase;
+import org.graalvm.compiler.phases.common.IncrementalCanonicalizerPhase;
+import org.graalvm.compiler.phases.common.LoweringPhase;
 import org.graalvm.compiler.phases.tiers.PhaseContext;
+import org.junit.Assert;
+import org.junit.Test;
 
 import jdk.vm.ci.meta.JavaKind;
 import jdk.vm.ci.meta.ResolvedJavaMethod;
@@ -101,7 +104,7 @@
         return trueCount;
     }
 
-    public boolean testSimpleSnippet(boolean a, boolean b) {
+    public boolean testSimpleSnippet(Boolean a, Boolean b) {
         return shortCircuitOr(a, b);
     }
 
@@ -110,259 +113,260 @@
         testInputCombinations("testSimpleSnippet");
     }
 
-    public static boolean testCascadeSnippet1(boolean a, boolean b) {
+    // We cannot trust subword inputs. Parameter declared as boolean will have a stamp of int32.
+    public static boolean testCascadeSnippet1(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(a, b), a);
     }
 
-    public static boolean testCascadeSnippet2(boolean a, boolean b) {
+    public static boolean testCascadeSnippet2(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(b, a), a);
     }
 
-    public static boolean testCascadeSnippet3(boolean a, boolean b) {
+    public static boolean testCascadeSnippet3(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(a, b));
     }
 
-    public static boolean testCascadeSnippet4(boolean a, boolean b) {
+    public static boolean testCascadeSnippet4(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(b, a));
     }
 
-    public static boolean testCascadeSnippet5(boolean a, boolean b) {
+    public static boolean testCascadeSnippet5(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(a, b), a);
     }
 
-    public static boolean testCascadeSnippet6(boolean a, boolean b) {
+    public static boolean testCascadeSnippet6(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(b, a), a);
     }
 
-    public static boolean testCascadeSnippet7(boolean a, boolean b) {
+    public static boolean testCascadeSnippet7(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(a, b));
     }
 
-    public static boolean testCascadeSnippet8(boolean a, boolean b) {
+    public static boolean testCascadeSnippet8(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(b, a));
     }
 
-    public static boolean testCascadeSnippet9(boolean a, boolean b) {
+    public static boolean testCascadeSnippet9(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!a, b), a);
     }
 
-    public static boolean testCascadeSnippet10(boolean a, boolean b) {
+    public static boolean testCascadeSnippet10(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!b, a), a);
     }
 
-    public static boolean testCascadeSnippet11(boolean a, boolean b) {
+    public static boolean testCascadeSnippet11(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(a, b));
     }
 
-    public static boolean testCascadeSnippet12(boolean a, boolean b) {
+    public static boolean testCascadeSnippet12(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(b, a));
     }
 
-    public static boolean testCascadeSnippet13(boolean a, boolean b) {
+    public static boolean testCascadeSnippet13(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!a, b), a);
     }
 
-    public static boolean testCascadeSnippet14(boolean a, boolean b) {
+    public static boolean testCascadeSnippet14(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!b, a), a);
     }
 
-    public static boolean testCascadeSnippet15(boolean a, boolean b) {
+    public static boolean testCascadeSnippet15(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(a, b));
     }
 
-    public static boolean testCascadeSnippet16(boolean a, boolean b) {
+    public static boolean testCascadeSnippet16(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!b, a));
     }
 
-    public static boolean testCascadeSnippet17(boolean a, boolean b) {
+    public static boolean testCascadeSnippet17(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(a, !b), a);
     }
 
-    public static boolean testCascadeSnippet18(boolean a, boolean b) {
+    public static boolean testCascadeSnippet18(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(b, !a), a);
     }
 
-    public static boolean testCascadeSnippet19(boolean a, boolean b) {
+    public static boolean testCascadeSnippet19(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(!a, b));
     }
 
-    public static boolean testCascadeSnippet20(boolean a, boolean b) {
+    public static boolean testCascadeSnippet20(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(!b, a));
     }
 
-    public static boolean testCascadeSnippet21(boolean a, boolean b) {
+    public static boolean testCascadeSnippet21(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(a, !b), a);
     }
 
-    public static boolean testCascadeSnippet22(boolean a, boolean b) {
+    public static boolean testCascadeSnippet22(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(b, !a), a);
     }
 
-    public static boolean testCascadeSnippet23(boolean a, boolean b) {
+    public static boolean testCascadeSnippet23(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(!a, b));
     }
 
-    public static boolean testCascadeSnippet24(boolean a, boolean b) {
+    public static boolean testCascadeSnippet24(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(!b, a));
     }
 
-    public static boolean testCascadeSnippet25(boolean a, boolean b) {
+    public static boolean testCascadeSnippet25(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!a, !b), a);
     }
 
-    public static boolean testCascadeSnippet26(boolean a, boolean b) {
+    public static boolean testCascadeSnippet26(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!b, !a), a);
     }
 
-    public static boolean testCascadeSnippet27(boolean a, boolean b) {
+    public static boolean testCascadeSnippet27(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(!a, b));
     }
 
-    public static boolean testCascadeSnippet28(boolean a, boolean b) {
+    public static boolean testCascadeSnippet28(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(!b, a));
     }
 
-    public static boolean testCascadeSnippet29(boolean a, boolean b) {
+    public static boolean testCascadeSnippet29(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!a, !b), a);
     }
 
-    public static boolean testCascadeSnippet30(boolean a, boolean b) {
+    public static boolean testCascadeSnippet30(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!b, !a), a);
     }
 
-    public static boolean testCascadeSnippet31(boolean a, boolean b) {
+    public static boolean testCascadeSnippet31(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!a, b));
     }
 
-    public static boolean testCascadeSnippet32(boolean a, boolean b) {
+    public static boolean testCascadeSnippet32(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!b, a));
     }
 
-    public static boolean testCascadeSnippet33(boolean a, boolean b) {
+    public static boolean testCascadeSnippet33(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(a, b), !a);
     }
 
-    public static boolean testCascadeSnippet34(boolean a, boolean b) {
+    public static boolean testCascadeSnippet34(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(b, a), !a);
     }
 
-    public static boolean testCascadeSnippet35(boolean a, boolean b) {
+    public static boolean testCascadeSnippet35(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(a, !b));
     }
 
-    public static boolean testCascadeSnippet36(boolean a, boolean b) {
+    public static boolean testCascadeSnippet36(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(b, !a));
     }
 
-    public static boolean testCascadeSnippet37(boolean a, boolean b) {
+    public static boolean testCascadeSnippet37(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(a, b), !a);
     }
 
-    public static boolean testCascadeSnippet38(boolean a, boolean b) {
+    public static boolean testCascadeSnippet38(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(b, a), !a);
     }
 
-    public static boolean testCascadeSnippet39(boolean a, boolean b) {
+    public static boolean testCascadeSnippet39(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(a, !b));
     }
 
-    public static boolean testCascadeSnippet40(boolean a, boolean b) {
+    public static boolean testCascadeSnippet40(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(b, !a));
     }
 
-    public static boolean testCascadeSnippet41(boolean a, boolean b) {
+    public static boolean testCascadeSnippet41(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!a, b), !a);
     }
 
-    public static boolean testCascadeSnippet42(boolean a, boolean b) {
+    public static boolean testCascadeSnippet42(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!b, a), !a);
     }
 
-    public static boolean testCascadeSnippet43(boolean a, boolean b) {
+    public static boolean testCascadeSnippet43(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(a, !b));
     }
 
-    public static boolean testCascadeSnippet44(boolean a, boolean b) {
+    public static boolean testCascadeSnippet44(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(b, !a));
     }
 
-    public static boolean testCascadeSnippet45(boolean a, boolean b) {
+    public static boolean testCascadeSnippet45(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!a, b), !a);
     }
 
-    public static boolean testCascadeSnippet46(boolean a, boolean b) {
+    public static boolean testCascadeSnippet46(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!b, a), !a);
     }
 
-    public static boolean testCascadeSnippet47(boolean a, boolean b) {
+    public static boolean testCascadeSnippet47(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(a, !b));
     }
 
-    public static boolean testCascadeSnippet48(boolean a, boolean b) {
+    public static boolean testCascadeSnippet48(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!b, !a));
     }
 
-    public static boolean testCascadeSnippet49(boolean a, boolean b) {
+    public static boolean testCascadeSnippet49(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(a, !b), !a);
     }
 
-    public static boolean testCascadeSnippet50(boolean a, boolean b) {
+    public static boolean testCascadeSnippet50(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(b, !a), !a);
     }
 
-    public static boolean testCascadeSnippet51(boolean a, boolean b) {
+    public static boolean testCascadeSnippet51(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(!a, !b));
     }
 
-    public static boolean testCascadeSnippet52(boolean a, boolean b) {
+    public static boolean testCascadeSnippet52(Boolean a, Boolean b) {
         return shortCircuitOr(a, shortCircuitOr(!b, !a));
     }
 
-    public static boolean testCascadeSnippet53(boolean a, boolean b) {
+    public static boolean testCascadeSnippet53(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(a, !b), !a);
     }
 
-    public static boolean testCascadeSnippet54(boolean a, boolean b) {
+    public static boolean testCascadeSnippet54(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(b, !a), !a);
     }
 
-    public static boolean testCascadeSnippet55(boolean a, boolean b) {
+    public static boolean testCascadeSnippet55(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(!a, !b));
     }
 
-    public static boolean testCascadeSnippet56(boolean a, boolean b) {
+    public static boolean testCascadeSnippet56(Boolean a, Boolean b) {
         return shortCircuitOr(!a, shortCircuitOr(!b, !a));
     }
 
-    public static boolean testCascadeSnippet57(boolean a, boolean b) {
+    public static boolean testCascadeSnippet57(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!a, !b), !a);
     }
 
-    public static boolean testCascadeSnippet58(boolean a, boolean b) {
+    public static boolean testCascadeSnippet58(Boolean a, Boolean b) {
         return shortCircuitOr(shortCircuitOr(!b, !a), !a);
     }
 
-    public static boolean testCascadeSnippet59(boolean a, boolean b) {
+    public static boolean testCascadeSnippet59(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(!a, !b));
     }
 
-    public static boolean testCascadeSnippet60(boolean a, boolean b) {
+    public static boolean testCascadeSnippet60(Boolean a, Boolean b) {
         return shortCircuitOr(a, !shortCircuitOr(!b, !a));
     }
 
-    public static boolean testCascadeSnippet61(boolean a, boolean b) {
+    public static boolean testCascadeSnippet61(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!a, !b), !a);
     }
 
-    public static boolean testCascadeSnippet62(boolean a, boolean b) {
+    public static boolean testCascadeSnippet62(Boolean a, Boolean b) {
         return shortCircuitOr(!shortCircuitOr(!b, !a), !a);
     }
 
-    public static boolean testCascadeSnippet63(boolean a, boolean b) {
+    public static boolean testCascadeSnippet63(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!a, !b));
     }
 
-    public static boolean testCascadeSnippet64(boolean a, boolean b) {
+    public static boolean testCascadeSnippet64(Boolean a, Boolean b) {
         return shortCircuitOr(!a, !shortCircuitOr(!b, !a));
     }
 
@@ -374,6 +378,8 @@
             PhaseContext context = new PhaseContext(getProviders());
             CanonicalizerPhase canonicalizer = new CanonicalizerPhase();
             canonicalizer.apply(graph, context);
+            new LoweringPhase(canonicalizer, LoweringTool.StandardLoweringStage.HIGH_TIER).apply(graph, context);
+            new IncrementalCanonicalizerPhase<>(canonicalizer, new FloatingReadPhase()).apply(graph, context);
             int shortCircuitCount = graph.getNodes(ShortCircuitOrNode.TYPE).count();
 
             int trueCount = testInputCombinations(snippet);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes.test/src/org/graalvm/compiler/nodes/test/StructuredGraphTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2018, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.nodes.test;
+
+import org.graalvm.compiler.core.test.GraalCompilerTest;
+import org.graalvm.compiler.debug.DebugContext;
+import org.graalvm.compiler.debug.DebugHandlersFactory;
+import org.graalvm.compiler.nodes.StructuredGraph;
+import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
+import org.graalvm.compiler.options.OptionValues;
+import org.junit.Assert;
+import org.junit.Test;
+
+import jdk.vm.ci.meta.ResolvedJavaMethod;
+
+public class StructuredGraphTest extends GraalCompilerTest {
+
+    @Test
+    public void testGetBytecodeSize() {
+        OptionValues options = getInitialOptions();
+        DebugContext debug = DebugContext.create(options, DebugHandlersFactory.LOADER);
+        ResolvedJavaMethod rootMethod = getResolvedJavaMethod("testGetBytecodeSize");
+
+        // Test graph with root method and inlined methods
+        StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(rootMethod).build();
+        ResolvedJavaMethod otherMethod = getResolvedJavaMethod(GraalCompilerTest.class, "createSuites");
+        int expectedBytecodeSize = rootMethod.getCodeSize();
+        for (int i = 0; i < 10; i++) {
+            graph.recordMethod(otherMethod);
+            expectedBytecodeSize += otherMethod.getCodeSize();
+        }
+        Assert.assertEquals(expectedBytecodeSize, graph.getBytecodeSize());
+
+        // Test graph with only root method, no inlined methods
+        graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(rootMethod).build();
+        expectedBytecodeSize = rootMethod.getCodeSize();
+        Assert.assertEquals(expectedBytecodeSize, graph.getBytecodeSize());
+
+        // Test graph with no root method, only inlined methods
+        graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).build();
+        expectedBytecodeSize = 0;
+        for (int i = 0; i < 10; i++) {
+            graph.recordMethod(otherMethod);
+            expectedBytecodeSize += otherMethod.getCodeSize();
+        }
+        Assert.assertEquals(expectedBytecodeSize, graph.getBytecodeSize());
+
+        // Test graph with no root method, no inlined methods
+        graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).build();
+        expectedBytecodeSize = 0;
+        Assert.assertEquals(expectedBytecodeSize, graph.getBytecodeSize());
+    }
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/GraphDecoder.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/GraphDecoder.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1400,6 +1400,15 @@
         DebugContext debug = graph.getDebug();
         debug.dump(DebugContext.DETAILED_LEVEL, graph, "Before loop detection");
 
+        if (methodScope.loopExplosionHead == null) {
+            /*
+             * The to-be-exploded loop was not reached during partial evaluation (e.g., because
+             * there was a deoptimization beforehand), or the method might not even contain a loop.
+             * This is an uncommon case, but not an error.
+             */
+            return;
+        }
+
         List<Loop> orderedLoops = findLoops();
         assert orderedLoops.get(orderedLoops.size() - 1) == irreducibleLoopHandler : "outermost loop must be the last element in the list";
 
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/StructuredGraph.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/StructuredGraph.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,10 +25,14 @@
 import static org.graalvm.compiler.graph.Graph.SourcePositionTracking.Default;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.Consumer;
+import java.util.stream.Collectors;
 
 import jdk.internal.vm.compiler.collections.EconomicMap;
 import jdk.internal.vm.compiler.collections.EconomicSet;
@@ -40,6 +44,7 @@
 import org.graalvm.compiler.core.common.cfg.BlockMap;
 import org.graalvm.compiler.core.common.type.Stamp;
 import org.graalvm.compiler.debug.DebugContext;
+import org.graalvm.compiler.debug.GraalError;
 import org.graalvm.compiler.debug.JavaMethodContext;
 import org.graalvm.compiler.debug.TTY;
 import org.graalvm.compiler.graph.Graph;
@@ -54,6 +59,7 @@
 import org.graalvm.compiler.nodes.util.GraphUtil;
 import org.graalvm.compiler.options.OptionValues;
 
+import jdk.vm.ci.code.BytecodeFrame;
 import jdk.vm.ci.meta.Assumptions;
 import jdk.vm.ci.meta.Assumptions.Assumption;
 import jdk.vm.ci.meta.DefaultProfilingInfo;
@@ -170,6 +176,7 @@
         private CompilationIdentifier compilationId = CompilationIdentifier.INVALID_COMPILATION_ID;
         private int entryBCI = JVMCICompiler.INVOCATION_ENTRY_BCI;
         private boolean useProfilingInfo = true;
+        private boolean recordInlinedMethods = true;
         private SourcePositionTracking trackNodeSourcePosition = Default;
         private final OptionValues options;
         private Cancellable cancellable = null;
@@ -263,6 +270,15 @@
             return this;
         }
 
+        public boolean getRecordInlinedMethods() {
+            return recordInlinedMethods;
+        }
+
+        public Builder recordInlinedMethods(boolean flag) {
+            this.recordInlinedMethods = flag;
+            return this;
+        }
+
         public Builder trackNodeSourcePosition(SourcePositionTracking tracking) {
             this.trackNodeSourcePosition = tracking;
             return this;
@@ -281,7 +297,9 @@
         }
 
         public StructuredGraph build() {
-            return new StructuredGraph(name, rootMethod, entryBCI, assumptions, speculationLog, useProfilingInfo, trackNodeSourcePosition, compilationId, options, debug, cancellable, callerContext);
+            List<ResolvedJavaMethod> inlinedMethods = recordInlinedMethods ? new ArrayList<>() : null;
+            return new StructuredGraph(name, rootMethod, entryBCI, assumptions, speculationLog, useProfilingInfo, inlinedMethods,
+                            trackNodeSourcePosition, compilationId, options, debug, cancellable, callerContext);
         }
     }
 
@@ -318,14 +336,14 @@
 
     /**
      * Records the methods that were used while constructing this graph, one entry for each time a
-     * specific method is used.
+     * specific method is used. This will be {@code null} if recording of inlined methods is
+     * disabled for the graph.
      */
-    private final List<ResolvedJavaMethod> methods = new ArrayList<>();
+    private final List<ResolvedJavaMethod> methods;
 
     /**
      * Records the fields that were accessed while constructing this graph.
      */
-
     private EconomicSet<ResolvedJavaField> fields = null;
 
     private enum UnsafeAccessState {
@@ -346,6 +364,7 @@
                     Assumptions assumptions,
                     SpeculationLog speculationLog,
                     boolean useProfilingInfo,
+                    List<ResolvedJavaMethod> methods,
                     SourcePositionTracking trackNodeSourcePosition,
                     CompilationIdentifier compilationId,
                     OptionValues options,
@@ -359,6 +378,7 @@
         this.compilationId = compilationId;
         this.entryBCI = entryBCI;
         this.assumptions = assumptions;
+        this.methods = methods;
         if (speculationLog != null && !(speculationLog instanceof GraphSpeculationLog)) {
             this.speculationLog = new GraphSpeculationLog(speculationLog);
         } else {
@@ -514,6 +534,7 @@
                         assumptions == null ? null : new Assumptions(),
                         speculationLog,
                         useProfilingInfo,
+                        methods != null ? new ArrayList<>(methods) : null,
                         trackNodeSourcePosition,
                         newCompilationId,
                         getOptions(), debugForCopy, null, callerContext);
@@ -526,6 +547,9 @@
         copy.hasValueProxies = hasValueProxies;
         copy.isAfterExpandLogic = isAfterExpandLogic;
         copy.trackNodeSourcePosition = trackNodeSourcePosition;
+        if (fields != null) {
+            copy.fields = createFieldSet(fields);
+        }
         EconomicMap<Node, Node> replacements = EconomicMap.create(Equivalence.IDENTITY);
         replacements.put(start, copy.start);
         UnmodifiableEconomicMap<Node, Node> duplicates;
@@ -862,16 +886,55 @@
     }
 
     /**
-     * Gets the methods that were inlined while constructing this graph.
+     * Checks that any method referenced from a {@link FrameState} is also in the set of methods
+     * parsed while building this graph.
+     */
+    private boolean checkFrameStatesAgainstInlinedMethods() {
+        for (FrameState fs : getNodes(FrameState.TYPE)) {
+            if (!BytecodeFrame.isPlaceholderBci(fs.bci)) {
+                ResolvedJavaMethod m = fs.code.getMethod();
+                if (!m.equals(rootMethod) && !methods.contains(m)) {
+                    SortedSet<String> haystack = new TreeSet<>();
+                    if (!methods.contains(rootMethod)) {
+                        haystack.add(rootMethod.format("%H.%n(%p)"));
+                    }
+                    for (ResolvedJavaMethod e : methods) {
+                        haystack.add(e.format("%H.%n(%p)"));
+                    }
+                    throw new AssertionError(String.format("Could not find %s from %s in set(%s)", m.format("%H.%n(%p)"), fs, haystack.stream().collect(Collectors.joining(System.lineSeparator()))));
+                }
+            }
+        }
+        return true;
+    }
+
+    private static EconomicSet<ResolvedJavaField> createFieldSet(EconomicSet<ResolvedJavaField> init) {
+        // Multiple ResolvedJavaField objects can represent the same field so they
+        // need to be compared with equals().
+        if (init != null) {
+            return EconomicSet.create(Equivalence.DEFAULT, init);
+        }
+        return EconomicSet.create(Equivalence.DEFAULT);
+    }
+
+    /**
+     * Gets an unmodifiable view of the methods that were inlined while constructing this graph.
      */
     public List<ResolvedJavaMethod> getMethods() {
-        return methods;
+        if (methods != null) {
+            assert checkFrameStatesAgainstInlinedMethods();
+            return Collections.unmodifiableList(methods);
+        }
+        return Collections.emptyList();
     }
 
     /**
      * Records that {@code method} was used to build this graph.
      */
     public void recordMethod(ResolvedJavaMethod method) {
+        if (methods == null) {
+            throw new GraalError("inlined method recording not enabled for %s", this);
+        }
         methods.add(method);
     }
 
@@ -880,12 +943,21 @@
      * to build another graph.
      */
     public void updateMethods(StructuredGraph other) {
-        assert this != other;
-        this.methods.addAll(other.methods);
+        if (methods == null) {
+            throw new GraalError("inlined method recording not enabled for %s", this);
+        }
+        if (other.rootMethod != null) {
+            methods.add(other.rootMethod);
+        }
+        for (ResolvedJavaMethod m : other.methods) {
+            methods.add(m);
+        }
     }
 
     /**
-     * Gets the fields that were accessed while constructing this graph.
+     * Gets an unmodifiable view of the fields that were accessed while constructing this graph.
+     *
+     * @return {@code null} if no field accesses were recorded
      */
     public EconomicSet<ResolvedJavaField> getFields() {
         return fields;
@@ -897,7 +969,7 @@
     public void recordField(ResolvedJavaField field) {
         assert GraalOptions.GeneratePIC.getValue(getOptions());
         if (this.fields == null) {
-            this.fields = EconomicSet.create(Equivalence.IDENTITY);
+            this.fields = createFieldSet(null);
         }
         fields.add(field);
     }
@@ -911,7 +983,7 @@
         assert GraalOptions.GeneratePIC.getValue(getOptions());
         if (other.fields != null) {
             if (this.fields == null) {
-                this.fields = EconomicSet.create(Equivalence.IDENTITY);
+                this.fields = createFieldSet(null);
             }
             this.fields.addAll(other.fields);
         }
@@ -925,8 +997,13 @@
      */
     public int getBytecodeSize() {
         int res = 0;
-        for (ResolvedJavaMethod e : methods) {
-            res += e.getCodeSize();
+        if (rootMethod != null) {
+            res += rootMethod.getCodeSize();
+        }
+        if (methods != null) {
+            for (ResolvedJavaMethod e : methods) {
+                res += e.getCodeSize();
+            }
         }
         return res;
     }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/calc/SignExtendNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/calc/SignExtendNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -24,12 +24,14 @@
 
 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_1;
 
+import jdk.vm.ci.code.CodeUtil;
 import org.graalvm.compiler.core.common.type.ArithmeticOpTable;
 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.IntegerConvertOp;
 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.IntegerConvertOp.Narrow;
 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.IntegerConvertOp.SignExtend;
 import org.graalvm.compiler.core.common.type.IntegerStamp;
 import org.graalvm.compiler.core.common.type.PrimitiveStamp;
+import org.graalvm.compiler.core.common.type.Stamp;
 import org.graalvm.compiler.graph.NodeClass;
 import org.graalvm.compiler.graph.spi.CanonicalizerTool;
 import org.graalvm.compiler.lir.gen.ArithmeticLIRGeneratorTool;
@@ -107,7 +109,28 @@
                 return ZeroExtendNode.create(forValue, inputBits, resultBits, view, true);
             }
         }
-
+        if (forValue instanceof NarrowNode) {
+            NarrowNode narrow = (NarrowNode) forValue;
+            Stamp inputStamp = narrow.getValue().stamp(view);
+            if (inputStamp instanceof IntegerStamp) {
+                IntegerStamp istamp = (IntegerStamp) inputStamp;
+                long mask = CodeUtil.mask(PrimitiveStamp.getBits(narrow.stamp(view)) - 1);
+                if (~mask <= istamp.lowerBound() && istamp.upperBound() <= mask) {
+                    // The original value cannot change because of the narrow and sign extend.
+                    if (istamp.getBits() < resultBits) {
+                        // Need to keep the sign extend, skip the narrow.
+                        return create(narrow.getValue(), resultBits, view);
+                    } else if (istamp.getBits() > resultBits) {
+                        // Need to keep the narrow, skip the sign extend.
+                        return NarrowNode.create(narrow.getValue(), resultBits, view);
+                    } else {
+                        assert istamp.getBits() == resultBits;
+                        // Just return the original value.
+                        return narrow.getValue();
+                    }
+                }
+            }
+        }
         return self != null ? self : new SignExtendNode(forValue, inputBits, resultBits);
     }
 
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/BranchProbabilityNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/BranchProbabilityNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,10 @@
 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_0;
 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_0;
 
+import jdk.vm.ci.meta.JavaKind;
 import org.graalvm.compiler.core.common.calc.CanonicalCondition;
+import org.graalvm.compiler.core.common.type.IntegerStamp;
+import org.graalvm.compiler.core.common.type.StampFactory;
 import org.graalvm.compiler.debug.GraalError;
 import org.graalvm.compiler.graph.NodeClass;
 import org.graalvm.compiler.graph.iterators.NodePredicates;
@@ -40,6 +43,8 @@
 import org.graalvm.compiler.nodes.calc.ConditionalNode;
 import org.graalvm.compiler.nodes.calc.FloatingNode;
 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode;
+import org.graalvm.compiler.nodes.calc.NarrowNode;
+import org.graalvm.compiler.nodes.calc.ZeroExtendNode;
 import org.graalvm.compiler.nodes.spi.Lowerable;
 import org.graalvm.compiler.nodes.spi.LoweringTool;
 
@@ -68,7 +73,7 @@
     @Input ValueNode condition;
 
     public BranchProbabilityNode(ValueNode probability, ValueNode condition) {
-        super(TYPE, condition.stamp(NodeView.DEFAULT));
+        super(TYPE, StampFactory.forKind(JavaKind.Boolean));
         this.probability = probability;
         this.condition = condition;
     }
@@ -122,6 +127,11 @@
             }
             if (usageFound) {
                 ValueNode currentCondition = condition;
+                IntegerStamp currentStamp = (IntegerStamp) currentCondition.stamp(NodeView.DEFAULT);
+                if (currentStamp.lowerBound() < 0 || 1 < currentStamp.upperBound()) {
+                    ValueNode narrow = graph().maybeAddOrUnique(NarrowNode.create(currentCondition, 1, NodeView.DEFAULT));
+                    currentCondition = graph().maybeAddOrUnique(ZeroExtendNode.create(narrow, 32, NodeView.DEFAULT));
+                }
                 replaceAndDelete(currentCondition);
                 if (tool != null) {
                     tool.addToWorkList(currentCondition.usages());
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/RawLoadNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/RawLoadNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -158,8 +158,8 @@
     }
 
     @Override
-    protected ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field) {
-        return LoadFieldNode.create(assumptions, object(), field);
+    protected ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field, boolean volatileAccess) {
+        return LoadFieldNode.create(assumptions, object(), field, volatileAccess);
     }
 
     @Override
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/RawStoreNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/RawStoreNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -128,8 +128,8 @@
     }
 
     @Override
-    protected ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field) {
-        return new StoreFieldNode(object(), field, value(), stateAfter());
+    protected ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field, boolean volatileAccess) {
+        return new StoreFieldNode(object(), field, value(), stateAfter(), volatileAccess);
     }
 
     @Override
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/UnsafeAccessNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/extended/UnsafeAccessNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -99,7 +99,11 @@
                     // never a valid access of an arbitrary address.
                     if (field != null && field.getJavaKind() == this.accessKind()) {
                         assert !graph().isAfterFloatingReadPhase() : "cannot add more precise memory location after floating read phase";
-                        return cloneAsFieldAccess(graph().getAssumptions(), field);
+                        // Unsafe accesses never have volatile semantics.
+                        // Memory barriers are placed around such an unsafe access at construction
+                        // time if necessary, unlike AccessFieldNodes which encapsulate their
+                        // potential volatile semantics.
+                        return cloneAsFieldAccess(graph().getAssumptions(), field, false);
                     }
                 }
             }
@@ -115,7 +119,11 @@
         return this;
     }
 
-    protected abstract ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field);
+    protected ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field) {
+        return cloneAsFieldAccess(assumptions, field, field.isVolatile());
+    }
+
+    protected abstract ValueNode cloneAsFieldAccess(Assumptions assumptions, ResolvedJavaField field, boolean volatileAccess);
 
     protected abstract ValueNode cloneAsArrayAccess(ValueNode location, LocationIdentity identity);
 }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/GraphBuilderContext.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/GraphBuilderContext.java	Tue Jun 19 16:33:07 2018 +0100
@@ -43,6 +43,9 @@
 import org.graalvm.compiler.nodes.StateSplit;
 import org.graalvm.compiler.nodes.ValueNode;
 import org.graalvm.compiler.nodes.calc.IsNullNode;
+import org.graalvm.compiler.nodes.calc.NarrowNode;
+import org.graalvm.compiler.nodes.calc.SignExtendNode;
+import org.graalvm.compiler.nodes.calc.ZeroExtendNode;
 import org.graalvm.compiler.nodes.type.StampTool;
 
 import jdk.vm.ci.code.BailoutException;
@@ -312,4 +315,25 @@
         return null;
     }
 
+    /**
+     * Adds masking to a given subword value according to a given {@Link JavaKind}, such that the
+     * masked value falls in the range of the given kind. In the cases where the given kind is not a
+     * subword kind, the input value is returned immediately.
+     *
+     * @param value the value to be masked
+     * @param kind the kind that specifies the range of the masked value
+     * @return the masked value
+     */
+    default ValueNode maskSubWordValue(ValueNode value, JavaKind kind) {
+        if (kind == kind.getStackKind()) {
+            return value;
+        }
+        // Subword value
+        ValueNode narrow = append(NarrowNode.create(value, kind.getBitCount(), NodeView.DEFAULT));
+        if (kind.isUnsigned()) {
+            return append(ZeroExtendNode.create(narrow, 32, NodeView.DEFAULT));
+        } else {
+            return append(SignExtendNode.create(narrow, 32, NodeView.DEFAULT));
+        }
+    }
 }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/InvocationPlugins.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/InvocationPlugins.java	Tue Jun 19 16:33:07 2018 +0100
@@ -948,11 +948,11 @@
      *            non-static. Upon returning, element 0 will have been rewritten to
      *            {@code declaringClass}
      */
-    public void register(InvocationPlugin plugin, Type declaringClass, String name, Type... argumentTypes) {
+    public final void register(InvocationPlugin plugin, Type declaringClass, String name, Type... argumentTypes) {
         register(plugin, false, false, declaringClass, name, argumentTypes);
     }
 
-    public void register(InvocationPlugin plugin, String declaringClass, String name, Type... argumentTypes) {
+    public final void register(InvocationPlugin plugin, String declaringClass, String name, Type... argumentTypes) {
         register(plugin, false, false, new OptionalLazySymbol(declaringClass), name, argumentTypes);
     }
 
@@ -965,7 +965,7 @@
      *            non-static. Upon returning, element 0 will have been rewritten to
      *            {@code declaringClass}
      */
-    public void registerOptional(InvocationPlugin plugin, Type declaringClass, String name, Type... argumentTypes) {
+    public final void registerOptional(InvocationPlugin plugin, Type declaringClass, String name, Type... argumentTypes) {
         register(plugin, true, false, declaringClass, name, argumentTypes);
     }
 
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/AccessFieldNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/AccessFieldNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -48,6 +48,7 @@
     @OptionalInput ValueNode object;
 
     protected final ResolvedJavaField field;
+    protected final boolean volatileAccess;
 
     public ValueNode object() {
         return object;
@@ -58,11 +59,24 @@
      *
      * @param object the instruction producing the receiver object
      * @param field the compiler interface representation of the field
+     * @param volatileAccess specifies if the access is volatile or not, this overrides the field
+     *            volatile modifier.
      */
-    public AccessFieldNode(NodeClass<? extends AccessFieldNode> c, Stamp stamp, ValueNode object, ResolvedJavaField field) {
+    public AccessFieldNode(NodeClass<? extends AccessFieldNode> c, Stamp stamp, ValueNode object, ResolvedJavaField field, boolean volatileAccess) {
         super(c, stamp);
         this.object = object;
         this.field = field;
+        this.volatileAccess = volatileAccess;
+    }
+
+    /**
+     * Constructs a new access field object.
+     *
+     * @param object the instruction producing the receiver object
+     * @param field the compiler interface representation of the field
+     */
+    public AccessFieldNode(NodeClass<? extends AccessFieldNode> c, Stamp stamp, ValueNode object, ResolvedJavaField field) {
+        this(c, stamp, object, field, field.isVolatile());
     }
 
     /**
@@ -84,12 +98,13 @@
     }
 
     /**
-     * Checks whether this field is declared volatile.
+     * Checks whether this access has volatile semantics.
      *
-     * @return {@code true} if the field is resolved and declared volatile
+     * The field access semantics are coupled to the access and not to the field. e.g. it's possible
+     * to access volatile fields using non-volatile semantics via VarHandles.
      */
     public boolean isVolatile() {
-        return field.isVolatile();
+        return volatileAccess;
     }
 
     @Override
@@ -114,7 +129,7 @@
 
     @Override
     public NodeSize estimatedNodeSize() {
-        if (field.isVolatile()) {
+        if (isVolatile()) {
             return SIZE_2;
         }
         return super.estimatedNodeSize();
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/LoadFieldNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/LoadFieldNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -69,12 +69,20 @@
     private final Stamp uncheckedStamp;
 
     protected LoadFieldNode(StampPair stamp, ValueNode object, ResolvedJavaField field) {
-        super(TYPE, stamp.getTrustedStamp(), object, field);
+        this(stamp, object, field, field.isVolatile());
+    }
+
+    protected LoadFieldNode(StampPair stamp, ValueNode object, ResolvedJavaField field, boolean volatileAccess) {
+        super(TYPE, stamp.getTrustedStamp(), object, field, volatileAccess);
         this.uncheckedStamp = stamp.getUncheckedStamp();
     }
 
     public static LoadFieldNode create(Assumptions assumptions, ValueNode object, ResolvedJavaField field) {
-        return new LoadFieldNode(StampFactory.forDeclaredType(assumptions, field.getType(), false), object, field);
+        return create(assumptions, object, field, field.isVolatile());
+    }
+
+    public static LoadFieldNode create(Assumptions assumptions, ValueNode object, ResolvedJavaField field, boolean volatileAccess) {
+        return new LoadFieldNode(StampFactory.forDeclaredType(assumptions, field.getType(), false), object, field, volatileAccess);
     }
 
     public static ValueNode create(ConstantFieldProvider constantFields, ConstantReflectionProvider constantReflection, MetaAccessProvider metaAccess,
@@ -202,7 +210,7 @@
 
     @Override
     public NodeCycles estimatedNodeCycles() {
-        if (field.isVolatile()) {
+        if (isVolatile()) {
             return CYCLES_2;
         }
         return super.estimatedNodeCycles();
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/StoreFieldNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/StoreFieldNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -71,12 +71,16 @@
     }
 
     public StoreFieldNode(ValueNode object, ResolvedJavaField field, ValueNode value) {
-        super(TYPE, StampFactory.forVoid(), object, field);
+        this(object, field, value, field.isVolatile());
+    }
+
+    public StoreFieldNode(ValueNode object, ResolvedJavaField field, ValueNode value, boolean volatileAccess) {
+        super(TYPE, StampFactory.forVoid(), object, field, volatileAccess);
         this.value = value;
     }
 
-    public StoreFieldNode(ValueNode object, ResolvedJavaField field, ValueNode value, FrameState stateAfter) {
-        super(TYPE, StampFactory.forVoid(), object, field);
+    public StoreFieldNode(ValueNode object, ResolvedJavaField field, ValueNode value, FrameState stateAfter, boolean volatileAccess) {
+        super(TYPE, StampFactory.forVoid(), object, field, volatileAccess);
         this.value = value;
         this.stateAfter = stateAfter;
     }
@@ -100,7 +104,7 @@
 
     @Override
     public NodeCycles estimatedNodeCycles() {
-        if (field.isVolatile()) {
+        if (isVolatile()) {
             return CYCLES_8;
         }
         return super.estimatedNodeCycles();
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/UnsafeCompareAndExchangeNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/java/UnsafeCompareAndExchangeNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/inlining/info/elem/InlineableGraph.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/inlining/info/elem/InlineableGraph.java	Tue Jun 19 16:33:07 2018 +0100
@@ -67,27 +67,20 @@
     private FixedNodeProbabilityCache probabilites = new FixedNodeProbabilityCache();
 
     public InlineableGraph(final ResolvedJavaMethod method, final Invoke invoke, final HighTierContext context, CanonicalizerPhase canonicalizer, boolean trackNodeSourcePosition) {
-        StructuredGraph original = getOriginalGraph(method, context, canonicalizer, invoke.asNode().graph(), invoke.bci(), trackNodeSourcePosition);
-        // TODO copying the graph is only necessary if it is modified or if it contains any invokes
-        this.graph = (StructuredGraph) original.copy(invoke.asNode().getDebug());
+        StructuredGraph original = InliningUtil.getIntrinsicGraph(context.getReplacements(), method, invoke.bci(), trackNodeSourcePosition, null);
+        if (original == null) {
+            original = parseBytecodes(method, context, canonicalizer, invoke.asNode().graph(), trackNodeSourcePosition);
+        } else if (original.isFrozen()) {
+            // Graph may be modified by specializeGraphToArguments so defensively
+            // make a copy. We rely on the frozen state of a graph to denote
+            // whether it is shared.
+            original = (StructuredGraph) original.copy(invoke.asNode().getDebug());
+        }
+        this.graph = original;
         specializeGraphToArguments(invoke, context, canonicalizer);
     }
 
     /**
-     * This method looks up in a cache the graph for the argument, if not found bytecode is parsed.
-     * The graph thus obtained is returned, ie the caller is responsible for cloning before
-     * modification.
-     */
-    private static StructuredGraph getOriginalGraph(final ResolvedJavaMethod method, final HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller, int callerBci,
-                    boolean trackNodeSourcePosition) {
-        StructuredGraph result = InliningUtil.getIntrinsicGraph(context.getReplacements(), method, callerBci, trackNodeSourcePosition, null);
-        if (result != null) {
-            return result;
-        }
-        return parseBytecodes(method, context, canonicalizer, caller, trackNodeSourcePosition);
-    }
-
-    /**
      * @return true iff one or more parameters <code>newGraph</code> were specialized to account for
      *         a constant argument, or an argument with a more specific stamp.
      */
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.processor/src/org/graalvm/compiler/processor/AbstractProcessor.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.processor/src/org/graalvm/compiler/processor/AbstractProcessor.java	Tue Jun 19 16:33:07 2018 +0100
@@ -74,7 +74,7 @@
     /**
      * Gets the {@link TypeMirror} for a given class name.
      *
-     * @rturn {@code null} if the class cannot be resolved
+     * @return {@code null} if the class cannot be resolved
      */
     public TypeMirror getTypeOrNull(String className) {
         TypeElement element = getTypeElementOrNull(className);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.aarch64/src/org/graalvm/compiler/replacements/aarch64/AArch64GraphBuilderPlugins.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.aarch64/src/org/graalvm/compiler/replacements/aarch64/AArch64GraphBuilderPlugins.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,6 +41,7 @@
 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
 import org.graalvm.compiler.nodes.java.AtomicReadAndAddNode;
+import org.graalvm.compiler.nodes.java.AtomicReadAndWriteNode;
 import org.graalvm.compiler.nodes.memory.address.AddressNode;
 import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode;
 import org.graalvm.compiler.replacements.StandardGraphBuilderPlugins;
@@ -65,7 +66,7 @@
                 registerMathPlugins(invocationPlugins);
                 registerStringLatin1Plugins(invocationPlugins, bytecodeProvider);
                 registerStringUTF16Plugins(invocationPlugins, bytecodeProvider);
-                registerUnsafeReadAndAddPlugins(invocationPlugins, bytecodeProvider);
+                registerUnsafePlugins(invocationPlugins, bytecodeProvider);
                 // This is temporarily disabled until we implement correct emitting of the CAS
                 // instructions of the proper width.
                 StandardGraphBuilderPlugins.registerPlatformSpecificUnsafePlugins(invocationPlugins, bytecodeProvider,
@@ -163,18 +164,32 @@
         }
     }
 
-    private static void registerUnsafeReadAndAddPlugins(InvocationPlugins plugins, BytecodeProvider replacementsBytecodeProvider) {
+    private static void registerUnsafePlugins(InvocationPlugins plugins, BytecodeProvider replacementsBytecodeProvider) {
         Registration r;
+        JavaKind[] unsafeJavaKinds;
         if (Java8OrEarlier) {
             r = new Registration(plugins, Unsafe.class);
+            unsafeJavaKinds = new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object};
         } else {
             r = new Registration(plugins, "jdk.internal.misc.Unsafe", replacementsBytecodeProvider);
+            unsafeJavaKinds = new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object};
         }
 
-        for (JavaKind kind : new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object}) {
+        for (JavaKind kind : unsafeJavaKinds) {
             Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 
-            if (kind != JavaKind.Object) {
+            r.register4("getAndSet" + kind.name(), Receiver.class, Object.class, long.class, javaClass, new InvocationPlugin() {
+                @Override
+                public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode value) {
+                    // Emits a null-check for the otherwise unused receiver
+                    unsafe.get();
+                    b.addPush(kind, new AtomicReadAndWriteNode(object, offset, value, kind, LocationIdentity.any()));
+                    b.getGraph().markUnsafeAccess();
+                    return true;
+                }
+            });
+
+            if (kind != JavaKind.Boolean && kind.isNumericInteger()) {
                 r.register4("getAndAdd" + kind.name(), Receiver.class, Object.class, long.class, javaClass, new InvocationPlugin() {
                     @Override
                     public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode delta) {
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.amd64/src/org/graalvm/compiler/replacements/amd64/AMD64FloatConvertNode.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.amd64/src/org/graalvm/compiler/replacements/amd64/AMD64FloatConvertNode.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,8 +25,12 @@
 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_8;
 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
 
+import jdk.vm.ci.meta.JavaConstant;
 import org.graalvm.compiler.core.common.calc.FloatConvert;
 import org.graalvm.compiler.core.common.type.ArithmeticOpTable.FloatConvertOp;
+import org.graalvm.compiler.core.common.type.IntegerStamp;
+import org.graalvm.compiler.core.common.type.Stamp;
+import org.graalvm.compiler.core.common.type.StampFactory;
 import org.graalvm.compiler.graph.NodeClass;
 import org.graalvm.compiler.graph.spi.CanonicalizerTool;
 import org.graalvm.compiler.lir.gen.ArithmeticLIRGeneratorTool;
@@ -41,6 +45,9 @@
  * This node has the semantics of the AMD64 floating point conversions. It is used in the lowering
  * of the {@link FloatConvertNode} which, on AMD64 needs a {@link AMD64FloatConvertNode} plus some
  * fixup code that handles the corner cases that differ between AMD64 and Java.
+ *
+ * Since this node evaluates to a special value if the conversion is inexact, its stamp must be
+ * modified to avoid optimizing away {@link AMD64ConvertSnippets}.
  */
 @NodeInfo(cycles = CYCLES_8, size = SIZE_1)
 public final class AMD64FloatConvertNode extends UnaryArithmeticNode<FloatConvertOp> implements ArithmeticLIRLowerable {
@@ -51,6 +58,7 @@
     public AMD64FloatConvertNode(FloatConvert op, ValueNode value) {
         super(TYPE, table -> table.getFloatConvert(op), value);
         this.op = op;
+        this.stamp = this.stamp.meet(createInexactCaseStamp());
     }
 
     @Override
@@ -60,6 +68,20 @@
     }
 
     @Override
+    public Stamp foldStamp(Stamp newStamp) {
+        // The semantics of the x64 CVTTSS2SI instruction allow returning 0x8000000 in the special
+        // cases.
+        Stamp foldedStamp = super.foldStamp(newStamp);
+        return foldedStamp.meet(createInexactCaseStamp());
+    }
+
+    private Stamp createInexactCaseStamp() {
+        IntegerStamp intStamp = (IntegerStamp) this.stamp;
+        long inexactValue = intStamp.getBits() <= 32 ? 0x8000_0000L : 0x8000_0000_0000_0000L;
+        return StampFactory.forConstant(JavaConstant.forPrimitiveInt(intStamp.getBits(), inexactValue));
+    }
+
+    @Override
     public void generate(NodeLIRBuilderTool nodeValueMap, ArithmeticLIRGeneratorTool gen) {
         nodeValueMap.setResult(this, gen.emitFloatConvert(op, nodeValueMap.operand(getValue())));
     }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.amd64/src/org/graalvm/compiler/replacements/amd64/AMD64GraphBuilderPlugins.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.amd64/src/org/graalvm/compiler/replacements/amd64/AMD64GraphBuilderPlugins.java	Tue Jun 19 16:33:07 2018 +0100
@@ -220,16 +220,14 @@
     }
 
     private static void registerUnsafePlugins(InvocationPlugins plugins, BytecodeProvider replacementsBytecodeProvider) {
-        Registration r;
-        JavaKind[] unsafeJavaKinds;
-        if (Java8OrEarlier) {
-            r = new Registration(plugins, Unsafe.class);
-            unsafeJavaKinds = new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object};
-        } else {
-            r = new Registration(plugins, "jdk.internal.misc.Unsafe", replacementsBytecodeProvider);
-            unsafeJavaKinds = new JavaKind[]{JavaKind.Boolean, JavaKind.Byte, JavaKind.Char, JavaKind.Short, JavaKind.Int, JavaKind.Long, JavaKind.Object};
+        registerUnsafePlugins(new Registration(plugins, Unsafe.class), new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object});
+        if (!Java8OrEarlier) {
+            registerUnsafePlugins(new Registration(plugins, "jdk.internal.misc.Unsafe", replacementsBytecodeProvider),
+                            new JavaKind[]{JavaKind.Boolean, JavaKind.Byte, JavaKind.Char, JavaKind.Short, JavaKind.Int, JavaKind.Long, JavaKind.Object});
         }
+    }
 
+    private static void registerUnsafePlugins(Registration r, JavaKind[] unsafeJavaKinds) {
         for (JavaKind kind : unsafeJavaKinds) {
             Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 
@@ -260,8 +258,8 @@
 
         for (JavaKind kind : new JavaKind[]{JavaKind.Char, JavaKind.Short, JavaKind.Int, JavaKind.Long}) {
             Class<?> javaClass = kind.toJavaClass();
-            r.registerOptional3("get" + kind.name() + "Unaligned", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, false));
-            r.registerOptional4("put" + kind.name() + "Unaligned", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, false));
+            r.registerOptional3("get" + kind.name() + "Unaligned", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind));
+            r.registerOptional4("put" + kind.name() + "Unaligned", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind));
         }
     }
 
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.jdk9.test/src/org/graalvm/compiler/replacements/jdk9/UnsafeReplacementsTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.jdk9.test/src/org/graalvm/compiler/replacements/jdk9/UnsafeReplacementsTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,9 +22,9 @@
  */
 package org.graalvm.compiler.replacements.jdk9;
 
+import jdk.vm.ci.aarch64.AArch64;
 import jdk.vm.ci.amd64.AMD64;
 import jdk.vm.ci.code.TargetDescription;
-import jdk.vm.ci.meta.ResolvedJavaMethod;
 import org.graalvm.compiler.api.test.Graal;
 import org.graalvm.compiler.core.phases.HighTier;
 import org.graalvm.compiler.options.OptionValues;
@@ -38,9 +38,6 @@
 @AddExports("java.base/jdk.internal.misc")
 public class UnsafeReplacementsTest extends MethodSubstitutionTest {
 
-    // See GR-9819.
-    @SuppressWarnings("unused") ResolvedJavaMethod method = null;
-
     static class Container {
         public volatile boolean booleanField;
         public volatile byte byteField = 17;
@@ -247,6 +244,8 @@
             testGraph("unsafeGetAndAddByte");
             testGraph("unsafeGetAndAddChar");
             testGraph("unsafeGetAndAddShort");
+        }
+        if (target.arch instanceof AMD64 || target.arch instanceof AArch64) {
             testGraph("unsafeGetAndAddInt");
             testGraph("unsafeGetAndAddLong");
         }
@@ -302,6 +301,8 @@
             testGraph("unsafeGetAndSetByte");
             testGraph("unsafeGetAndSetChar");
             testGraph("unsafeGetAndSetShort");
+        }
+        if (target.arch instanceof AMD64 || target.arch instanceof AArch64) {
             testGraph("unsafeGetAndSetInt");
             testGraph("unsafeGetAndSetLong");
             testGraph("unsafeGetAndSetObject");
@@ -342,6 +343,12 @@
         test(new OptionValues(getInitialOptions(), HighTier.Options.Inline, false), "fieldStatic");
     }
 
+    public static void assertEquals(Object seen, Object expected, String message) {
+        if (seen != expected) {
+            throw new AssertionError(message + " - seen: " + seen + ", expected: " + expected);
+        }
+    }
+
     public static class JdkInternalMiscUnsafeAccessTestBoolean {
         static final int ITERATIONS = 100000;
 
@@ -405,12 +412,6 @@
             }
         }
 
-        public static void assertEquals(Object seen, Object expected, String message) {
-            if (seen != expected) {
-                throw new AssertionError(message + " - seen: " + seen + ", expected: " + expected);
-            }
-        }
-
         // Checkstyle: stop
         @BytecodeParserForceInline
         public static void testAccess(Object base, long offset) {
@@ -510,4 +511,312 @@
         }
         // Checkstyle: resume
     }
+
+    public static boolean unsafeGetPutBoolean() {
+        Container container = new Container();
+        unsafe.putBoolean(container, booleanOffset, true);
+        return unsafe.getBoolean(container, booleanOffset);
+    }
+
+    public static byte unsafeGetPutByte() {
+        Container container = new Container();
+        unsafe.putByte(container, byteOffset, (byte) 0x12);
+        return unsafe.getByte(container, byteOffset);
+    }
+
+    public static short unsafeGetPutShort() {
+        Container container = new Container();
+        unsafe.putShort(container, shortOffset, (short) 0x1234);
+        return unsafe.getShort(container, shortOffset);
+    }
+
+    public static char unsafeGetPutChar() {
+        Container container = new Container();
+        unsafe.putChar(container, charOffset, 'x');
+        return unsafe.getChar(container, charOffset);
+    }
+
+    public static int unsafeGetPutInt() {
+        Container container = new Container();
+        unsafe.putInt(container, intOffset, 0x01234567);
+        return unsafe.getInt(container, intOffset);
+    }
+
+    public static long unsafeGetPutLong() {
+        Container container = new Container();
+        unsafe.putLong(container, longOffset, 0x01234567890ABCDEFL);
+        return unsafe.getLong(container, longOffset);
+    }
+
+    public static float unsafeGetPutFloat() {
+        Container container = new Container();
+        unsafe.putFloat(container, floatOffset, 1.234F);
+        return unsafe.getFloat(container, floatOffset);
+    }
+
+    public static double unsafeGetPutDouble() {
+        Container container = new Container();
+        unsafe.putDouble(container, doubleOffset, 1.23456789);
+        return unsafe.getDouble(container, doubleOffset);
+    }
+
+    public static Object unsafeGetPutObject() {
+        Container container = new Container();
+        unsafe.putObject(container, objectOffset, "Hello there");
+        return unsafe.getObject(container, objectOffset);
+    }
+
+    public static boolean unsafeGetPutBooleanOpaque() {
+        Container container = new Container();
+        unsafe.putBooleanOpaque(container, booleanOffset, true);
+        return unsafe.getBooleanOpaque(container, booleanOffset);
+    }
+
+    public static byte unsafeGetPutByteOpaque() {
+        Container container = new Container();
+        unsafe.putByteOpaque(container, byteOffset, (byte) 0x12);
+        return unsafe.getByteOpaque(container, byteOffset);
+    }
+
+    public static short unsafeGetPutShortOpaque() {
+        Container container = new Container();
+        unsafe.putShortOpaque(container, shortOffset, (short) 0x1234);
+        return unsafe.getShortOpaque(container, shortOffset);
+    }
+
+    public static char unsafeGetPutCharOpaque() {
+        Container container = new Container();
+        unsafe.putCharOpaque(container, charOffset, 'x');
+        return unsafe.getCharOpaque(container, charOffset);
+    }
+
+    public static int unsafeGetPutIntOpaque() {
+        Container container = new Container();
+        unsafe.putIntOpaque(container, intOffset, 0x01234567);
+        return unsafe.getIntOpaque(container, intOffset);
+    }
+
+    public static long unsafeGetPutLongOpaque() {
+        Container container = new Container();
+        unsafe.putLongOpaque(container, longOffset, 0x01234567890ABCDEFL);
+        return unsafe.getLongOpaque(container, longOffset);
+    }
+
+    public static float unsafeGetPutFloatOpaque() {
+        Container container = new Container();
+        unsafe.putFloatOpaque(container, floatOffset, 1.234F);
+        return unsafe.getFloatOpaque(container, floatOffset);
+    }
+
+    public static double unsafeGetPutDoubleOpaque() {
+        Container container = new Container();
+        unsafe.putDoubleOpaque(container, doubleOffset, 1.23456789);
+        return unsafe.getDoubleOpaque(container, doubleOffset);
+    }
+
+    public static Object unsafeGetPutObjectOpaque() {
+        Container container = new Container();
+        unsafe.putObjectOpaque(container, objectOffset, "Hello there");
+        return unsafe.getObjectOpaque(container, objectOffset);
+    }
+
+    public static boolean unsafeGetPutBooleanRA() {
+        Container container = new Container();
+        unsafe.putBooleanRelease(container, booleanOffset, true);
+        return unsafe.getBooleanAcquire(container, booleanOffset);
+    }
+
+    public static byte unsafeGetPutByteRA() {
+        Container container = new Container();
+        unsafe.putByteRelease(container, byteOffset, (byte) 0x12);
+        return unsafe.getByteAcquire(container, byteOffset);
+    }
+
+    public static short unsafeGetPutShortRA() {
+        Container container = new Container();
+        unsafe.putShortRelease(container, shortOffset, (short) 0x1234);
+        return unsafe.getShortAcquire(container, shortOffset);
+    }
+
+    public static char unsafeGetPutCharRA() {
+        Container container = new Container();
+        unsafe.putCharRelease(container, charOffset, 'x');
+        return unsafe.getCharAcquire(container, charOffset);
+    }
+
+    public static int unsafeGetPutIntRA() {
+        Container container = new Container();
+        unsafe.putIntRelease(container, intOffset, 0x01234567);
+        return unsafe.getIntAcquire(container, intOffset);
+    }
+
+    public static long unsafeGetPutLongRA() {
+        Container container = new Container();
+        unsafe.putLongRelease(container, longOffset, 0x01234567890ABCDEFL);
+        return unsafe.getLongAcquire(container, longOffset);
+    }
+
+    public static float unsafeGetPutFloatRA() {
+        Container container = new Container();
+        unsafe.putFloatRelease(container, floatOffset, 1.234F);
+        return unsafe.getFloatAcquire(container, floatOffset);
+    }
+
+    public static double unsafeGetPutDoubleRA() {
+        Container container = new Container();
+        unsafe.putDoubleRelease(container, doubleOffset, 1.23456789);
+        return unsafe.getDoubleAcquire(container, doubleOffset);
+    }
+
+    public static Object unsafeGetPutObjectRA() {
+        Container container = new Container();
+        unsafe.putObjectRelease(container, objectOffset, "Hello there");
+        return unsafe.getObjectAcquire(container, objectOffset);
+    }
+
+    public static boolean unsafeGetPutBooleanVolatile() {
+        Container container = new Container();
+        unsafe.putBooleanVolatile(container, booleanOffset, true);
+        return unsafe.getBooleanVolatile(container, booleanOffset);
+    }
+
+    public static byte unsafeGetPutByteVolatile() {
+        Container container = new Container();
+        unsafe.putByteVolatile(container, byteOffset, (byte) 0x12);
+        return unsafe.getByteVolatile(container, byteOffset);
+    }
+
+    public static short unsafeGetPutShortVolatile() {
+        Container container = new Container();
+        unsafe.putShortVolatile(container, shortOffset, (short) 0x1234);
+        return unsafe.getShortVolatile(container, shortOffset);
+    }
+
+    public static char unsafeGetPutCharVolatile() {
+        Container container = new Container();
+        unsafe.putCharVolatile(container, charOffset, 'x');
+        return unsafe.getCharVolatile(container, charOffset);
+    }
+
+    public static int unsafeGetPutIntVolatile() {
+        Container container = new Container();
+        unsafe.putIntVolatile(container, intOffset, 0x01234567);
+        return unsafe.getIntVolatile(container, intOffset);
+    }
+
+    public static long unsafeGetPutLongVolatile() {
+        Container container = new Container();
+        unsafe.putLongVolatile(container, longOffset, 0x01234567890ABCDEFL);
+        return unsafe.getLongVolatile(container, longOffset);
+    }
+
+    public static float unsafeGetPutFloatVolatile() {
+        Container container = new Container();
+        unsafe.putFloatVolatile(container, floatOffset, 1.234F);
+        return unsafe.getFloatVolatile(container, floatOffset);
+    }
+
+    public static double unsafeGetPutDoubleVolatile() {
+        Container container = new Container();
+        unsafe.putDoubleVolatile(container, doubleOffset, 1.23456789);
+        return unsafe.getDoubleVolatile(container, doubleOffset);
+    }
+
+    public static Object unsafeGetPutObjectVolatile() {
+        Container container = new Container();
+        unsafe.putObjectVolatile(container, objectOffset, "Hello there");
+        return unsafe.getObjectVolatile(container, objectOffset);
+    }
+
+    @Test
+    public void testUnsafeGetPutPlain() {
+        testGraph("unsafeGetPutBoolean");
+        testGraph("unsafeGetPutByte");
+        testGraph("unsafeGetPutShort");
+        testGraph("unsafeGetPutChar");
+        testGraph("unsafeGetPutInt");
+        testGraph("unsafeGetPutLong");
+        testGraph("unsafeGetPutFloat");
+        testGraph("unsafeGetPutDouble");
+        testGraph("unsafeGetPutObject");
+
+        test("unsafeGetPutBoolean");
+        test("unsafeGetPutByte");
+        test("unsafeGetPutShort");
+        test("unsafeGetPutChar");
+        test("unsafeGetPutInt");
+        test("unsafeGetPutLong");
+        test("unsafeGetPutFloat");
+        test("unsafeGetPutDouble");
+        test("unsafeGetPutObject");
+    }
+
+    @Test
+    public void testUnsafeGetPutOpaque() {
+        testGraph("unsafeGetPutBooleanOpaque");
+        testGraph("unsafeGetPutByteOpaque");
+        testGraph("unsafeGetPutShortOpaque");
+        testGraph("unsafeGetPutCharOpaque");
+        testGraph("unsafeGetPutIntOpaque");
+        testGraph("unsafeGetPutLongOpaque");
+        testGraph("unsafeGetPutFloatOpaque");
+        testGraph("unsafeGetPutDoubleOpaque");
+        testGraph("unsafeGetPutObjectOpaque");
+
+        test("unsafeGetPutBooleanOpaque");
+        test("unsafeGetPutByteOpaque");
+        test("unsafeGetPutShortOpaque");
+        test("unsafeGetPutCharOpaque");
+        test("unsafeGetPutIntOpaque");
+        test("unsafeGetPutLongOpaque");
+        test("unsafeGetPutFloatOpaque");
+        test("unsafeGetPutDoubleOpaque");
+        test("unsafeGetPutObjectOpaque");
+    }
+
+    @Test
+    public void testUnsafeGetPutReleaseAcquire() {
+        testGraph("unsafeGetPutBooleanRA");
+        testGraph("unsafeGetPutByteRA");
+        testGraph("unsafeGetPutShortRA");
+        testGraph("unsafeGetPutCharRA");
+        testGraph("unsafeGetPutIntRA");
+        testGraph("unsafeGetPutLongRA");
+        testGraph("unsafeGetPutFloatRA");
+        testGraph("unsafeGetPutDoubleRA");
+        testGraph("unsafeGetPutObjectRA");
+
+        test("unsafeGetPutBooleanRA");
+        test("unsafeGetPutByteRA");
+        test("unsafeGetPutShortRA");
+        test("unsafeGetPutCharRA");
+        test("unsafeGetPutIntRA");
+        test("unsafeGetPutLongRA");
+        test("unsafeGetPutFloatRA");
+        test("unsafeGetPutDoubleRA");
+        test("unsafeGetPutObjectRA");
+    }
+
+    @Test
+    public void testUnsafeGetPutVolatile() {
+        testGraph("unsafeGetPutBooleanVolatile");
+        testGraph("unsafeGetPutByteVolatile");
+        testGraph("unsafeGetPutShortVolatile");
+        testGraph("unsafeGetPutCharVolatile");
+        testGraph("unsafeGetPutIntVolatile");
+        testGraph("unsafeGetPutLongVolatile");
+        testGraph("unsafeGetPutFloatVolatile");
+        testGraph("unsafeGetPutDoubleVolatile");
+        testGraph("unsafeGetPutObjectVolatile");
+
+        test("unsafeGetPutBooleanVolatile");
+        test("unsafeGetPutByteVolatile");
+        test("unsafeGetPutShortVolatile");
+        test("unsafeGetPutCharVolatile");
+        test("unsafeGetPutIntVolatile");
+        test("unsafeGetPutLongVolatile");
+        test("unsafeGetPutFloatVolatile");
+        test("unsafeGetPutDoubleVolatile");
+        test("unsafeGetPutObjectVolatile");
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.jdk9.test/src/org/graalvm/compiler/replacements/jdk9/VarHandleTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.graalvm.compiler.replacements.jdk9;
+
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.VarHandle;
+
+import org.graalvm.compiler.core.test.GraalCompilerTest;
+import org.graalvm.compiler.debug.GraalError;
+import org.graalvm.compiler.graph.Node;
+import org.graalvm.compiler.nodes.StartNode;
+import org.graalvm.compiler.nodes.StructuredGraph;
+import org.graalvm.compiler.nodes.extended.MembarNode;
+import org.graalvm.compiler.nodes.memory.MemoryCheckpoint;
+import org.graalvm.compiler.nodes.memory.ReadNode;
+import org.graalvm.compiler.nodes.memory.WriteNode;
+import jdk.internal.vm.compiler.word.LocationIdentity;
+import org.junit.Assert;
+import org.junit.Test;
+
+import jdk.vm.ci.meta.ResolvedJavaMethod;
+
+public class VarHandleTest extends GraalCompilerTest {
+
+    static class Holder {
+        /* Field is declared volatile, but accessed with non-volatile semantics in the tests. */
+        volatile int volatileField = 42;
+
+        /* Field is declared non-volatile, but accessed with volatile semantics in the tests. */
+        int field = 2018;
+
+        static final VarHandle VOLATILE_FIELD;
+        static final VarHandle FIELD;
+
+        static {
+            try {
+                VOLATILE_FIELD = MethodHandles.lookup().findVarHandle(Holder.class, "volatileField", int.class);
+                FIELD = MethodHandles.lookup().findVarHandle(Holder.class, "field", int.class);
+            } catch (ReflectiveOperationException ex) {
+                throw GraalError.shouldNotReachHere(ex);
+            }
+        }
+    }
+
+    public static int testRead1Snippet(Holder h) {
+        /* Explicitly access the volatile field with non-volatile access semantics. */
+        return (int) Holder.VOLATILE_FIELD.get(h);
+    }
+
+    public static int testRead2Snippet(Holder h) {
+        /* Explicitly access the volatile field with volatile access semantics. */
+        return (int) Holder.VOLATILE_FIELD.getVolatile(h);
+    }
+
+    public static int testRead3Snippet(Holder h) {
+        /* Explicitly access the non-volatile field with non-volatile access semantics. */
+        return (int) Holder.FIELD.get(h);
+    }
+
+    public static int testRead4Snippet(Holder h) {
+        /* Explicitly access the non-volatile field with volatile access semantics. */
+        return (int) Holder.FIELD.getVolatile(h);
+    }
+
+    public static void testWrite1Snippet(Holder h) {
+        /* Explicitly access the volatile field with non-volatile access semantics. */
+        Holder.VOLATILE_FIELD.set(h, 123);
+    }
+
+    public static void testWrite2Snippet(Holder h) {
+        /* Explicitly access the volatile field with volatile access semantics. */
+        Holder.VOLATILE_FIELD.setVolatile(h, 123);
+    }
+
+    public static void testWrite3Snippet(Holder h) {
+        /* Explicitly access the non-volatile field with non-volatile access semantics. */
+        Holder.FIELD.set(h, 123);
+    }
+
+    public static void testWrite4Snippet(Holder h) {
+        /* Explicitly access the non-volatile field with volatile access semantics. */
+        Holder.FIELD.setVolatile(h, 123);
+    }
+
+    void testAccess(String name, int expectedReads, int expectedWrites, int expectedMembars, int expectedAnyKill) {
+        ResolvedJavaMethod method = getResolvedJavaMethod(name);
+        StructuredGraph graph = parseForCompile(method);
+        compile(method, graph);
+        Assert.assertEquals(expectedReads, graph.getNodes().filter(ReadNode.class).count());
+        Assert.assertEquals(expectedWrites, graph.getNodes().filter(WriteNode.class).count());
+        Assert.assertEquals(expectedMembars, graph.getNodes().filter(MembarNode.class).count());
+        Assert.assertEquals(expectedAnyKill, countAnyKill(graph));
+    }
+
+    @Test
+    public void testRead1() {
+        testAccess("testRead1Snippet", 1, 0, 0, 0);
+    }
+
+    @Test
+    public void testRead2() {
+        testAccess("testRead2Snippet", 1, 0, 2, 2);
+    }
+
+    @Test
+    public void testRead3() {
+        testAccess("testRead3Snippet", 1, 0, 0, 0);
+    }
+
+    @Test
+    public void testRead4() {
+        testAccess("testRead4Snippet", 1, 0, 2, 2);
+    }
+
+    @Test
+    public void testWrite1() {
+        testAccess("testWrite1Snippet", 0, 1, 0, 0);
+    }
+
+    @Test
+    public void testWrite2() {
+        testAccess("testWrite2Snippet", 0, 1, 2, 2);
+    }
+
+    @Test
+    public void testWrite3() {
+        testAccess("testWrite3Snippet", 0, 1, 0, 0);
+    }
+
+    @Test
+    public void testWrite4() {
+        testAccess("testWrite4Snippet", 0, 1, 2, 2);
+    }
+
+    private static int countAnyKill(StructuredGraph graph) {
+        int anyKillCount = 0;
+        int startNodes = 0;
+        for (Node n : graph.getNodes()) {
+            if (n instanceof StartNode) {
+                startNodes++;
+            } else if (n instanceof MemoryCheckpoint.Single) {
+                MemoryCheckpoint.Single single = (MemoryCheckpoint.Single) n;
+                if (single.getLocationIdentity().isAny()) {
+                    anyKillCount++;
+                }
+            } else if (n instanceof MemoryCheckpoint.Multi) {
+                MemoryCheckpoint.Multi multi = (MemoryCheckpoint.Multi) n;
+                for (LocationIdentity loc : multi.getLocationIdentities()) {
+                    if (loc.isAny()) {
+                        anyKillCount++;
+                        break;
+                    }
+                }
+            }
+        }
+        // Ignore single StartNode.
+        Assert.assertEquals(1, startNodes);
+        return anyKillCount;
+    }
+}
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/BitOpNodesTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/BitOpNodesTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -38,6 +38,7 @@
 import org.graalvm.compiler.phases.tiers.HighTierContext;
 import org.graalvm.compiler.replacements.nodes.BitScanReverseNode;
 
+import jdk.vm.ci.aarch64.AArch64;
 import jdk.vm.ci.amd64.AMD64;
 import jdk.vm.ci.code.Architecture;
 import jdk.vm.ci.meta.JavaKind;
@@ -59,6 +60,47 @@
      * Tests for BitCountNode canonicalizations.
      */
 
+    /**
+     * Determines if the current VM context supports intrinsics for the {@code bitCount} methods in
+     * {@link Integer} and {@link Long}.
+     */
+    public static boolean isBitCountIntrinsicSupported(Architecture arch) {
+        if (arch instanceof AMD64) {
+            AMD64 amd64 = (AMD64) arch;
+            return amd64.getFeatures().contains(AMD64.CPUFeature.POPCNT);
+        } else {
+            // Even though there are AArch64 intrinsics for bitCount, they do
+            // not use BitCountNode.
+            return arch instanceof SPARC;
+        }
+    }
+
+    /**
+     * Determines if the current VM context supports intrinsics for the {@code numberOfLeadingZeros}
+     * methods in {@link Integer} and {@link Long}.
+     */
+    public static boolean isNumberLeadingZerosIntrinsicSupported(Architecture arch) {
+        if (arch instanceof AMD64) {
+            AMD64 amd64 = (AMD64) arch;
+            return amd64.getFeatures().contains(AMD64.CPUFeature.LZCNT) && amd64.getFlags().contains(AMD64.Flag.UseCountLeadingZerosInstruction);
+        } else {
+            return arch instanceof SPARC || arch instanceof AArch64;
+        }
+    }
+
+    /**
+     * Determines if the current VM context supports intrinsics for the
+     * {@code numberOfTrailingZeros} methods in {@link Integer} and {@link Long}.
+     */
+    public static boolean isNumberTrailingZerosIntrinsicSupported(Architecture arch) {
+        if (arch instanceof AMD64) {
+            AMD64 amd64 = (AMD64) arch;
+            return amd64.getFeatures().contains(AMD64.CPUFeature.BMI1) && amd64.getFlags().contains(AMD64.Flag.UseCountTrailingZerosInstruction);
+        } else {
+            return arch instanceof SPARC || arch instanceof AArch64;
+        }
+    }
+
     public static int bitCountIntConstantSnippet() {
         return Integer.bitCount(INT_CONSTANT_1) + Integer.bitCount(INT_CONSTANT_2) + Integer.bitCount(INT_CONSTANT_3);
     }
@@ -79,10 +121,7 @@
 
     @Test
     public void testBitCountInt() {
-        Architecture arch = getBackend().getTarget().arch;
-        boolean isAmd64WithPopCount = arch instanceof AMD64 && ((AMD64) arch).getFeatures().contains(AMD64.CPUFeature.POPCNT);
-        boolean isSparc = arch instanceof SPARC;
-        Assume.assumeTrue("Only works on hardware with popcnt at the moment", isAmd64WithPopCount || isSparc);
+        Assume.assumeTrue(isBitCountIntrinsicSupported(getBackend().getTarget().arch));
         ValueNode result = parseAndInline("bitCountIntSnippet");
         Assert.assertEquals(StampFactory.forInteger(JavaKind.Int, 8, 24), result.stamp(NodeView.DEFAULT));
     }
@@ -93,10 +132,7 @@
 
     @Test
     public void testBitCountIntEmpty() {
-        Architecture arch = getBackend().getTarget().arch;
-        boolean isAmd64WithPopCount = arch instanceof AMD64 && ((AMD64) arch).getFeatures().contains(AMD64.CPUFeature.POPCNT);
-        boolean isSparc = arch instanceof SPARC;
-        Assume.assumeTrue("Only works on hardware with popcnt at the moment", isAmd64WithPopCount || isSparc);
+        Assume.assumeTrue(isBitCountIntrinsicSupported(getBackend().getTarget().arch));
         ValueNode result = parseAndInline("bitCountIntEmptySnippet");
         Assert.assertEquals(StampFactory.forInteger(JavaKind.Int, 0, 24), result.stamp(NodeView.DEFAULT));
     }
@@ -113,10 +149,7 @@
 
     @Test
     public void testBitCountLong() {
-        Architecture arch = getBackend().getTarget().arch;
-        boolean isAmd64WithPopCount = arch instanceof AMD64 && ((AMD64) arch).getFeatures().contains(AMD64.CPUFeature.POPCNT);
-        boolean isSparc = arch instanceof SPARC;
-        Assume.assumeTrue("Only works on hardware with popcnt at the moment", isAmd64WithPopCount || isSparc);
+        Assume.assumeTrue(isBitCountIntrinsicSupported(getBackend().getTarget().arch));
         ValueNode result = parseAndInline("bitCountLongSnippet");
         Assert.assertEquals(StampFactory.forInteger(JavaKind.Int, 8, 40), result.stamp(NodeView.DEFAULT));
     }
@@ -127,10 +160,7 @@
 
     @Test
     public void testBitCountLongEmpty() {
-        Architecture arch = getBackend().getTarget().arch;
-        boolean isAmd64WithPopCount = arch instanceof AMD64 && ((AMD64) arch).getFeatures().contains(AMD64.CPUFeature.POPCNT);
-        boolean isSparc = arch instanceof SPARC;
-        Assume.assumeTrue("Only works on hardware with popcnt at the moment", isAmd64WithPopCount || isSparc);
+        Assume.assumeTrue(isBitCountIntrinsicSupported(getBackend().getTarget().arch));
         ValueNode result = parseAndInline("bitCountLongEmptySnippet");
         Assert.assertEquals(StampFactory.forInteger(JavaKind.Int, 0, 40), result.stamp(NodeView.DEFAULT));
     }
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/ObjectAccessTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/ObjectAccessTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,6 +28,8 @@
 import org.graalvm.compiler.nodes.ReturnNode;
 import org.graalvm.compiler.nodes.StructuredGraph;
 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
+import org.graalvm.compiler.nodes.ValueNode;
+import org.graalvm.compiler.nodes.calc.ConvertNode;
 import org.graalvm.compiler.nodes.calc.SignExtendNode;
 import org.graalvm.compiler.nodes.extended.JavaReadNode;
 import org.graalvm.compiler.nodes.extended.JavaWriteNode;
@@ -74,21 +76,21 @@
     @Test
     public void testWrite1() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "1", AllowAssumptions.YES), true, ID);
+            assertWrite(parseEager("write" + kind.name() + "1", AllowAssumptions.YES), kind, true, ID);
         }
     }
 
     @Test
     public void testWrite2() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "2", AllowAssumptions.YES), true, ID);
+            assertWrite(parseEager("write" + kind.name() + "2", AllowAssumptions.YES), kind, true, ID);
         }
     }
 
     @Test
     public void testWrite3() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "3", AllowAssumptions.YES), true, LocationIdentity.any());
+            assertWrite(parseEager("write" + kind.name() + "3", AllowAssumptions.YES), kind, true, LocationIdentity.any());
         }
     }
 
@@ -113,10 +115,15 @@
         Assert.assertEquals(read, ret.result());
     }
 
-    private static void assertWrite(StructuredGraph graph, boolean indexConvert, LocationIdentity locationIdentity) {
+    private static void assertWrite(StructuredGraph graph, JavaKind kind, boolean indexConvert, LocationIdentity locationIdentity) {
         JavaWriteNode write = (JavaWriteNode) graph.start().next();
-        Assert.assertEquals(graph.getParameter(2), write.value());
-
+        ValueNode valueNode = write.value();
+        if (kind != kind.getStackKind()) {
+            while (valueNode instanceof ConvertNode) {
+                valueNode = ((ConvertNode) valueNode).getValue();
+            }
+        }
+        Assert.assertEquals(graph.getParameter(2), valueNode);
         OffsetAddressNode address = (OffsetAddressNode) write.getAddress();
         Assert.assertEquals(graph.getParameter(0), address.getBase());
         Assert.assertEquals(BytecodeFrame.AFTER_BCI, write.stateAfter().bci);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/PointerTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/PointerTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,6 +28,8 @@
 import org.graalvm.compiler.nodes.ReturnNode;
 import org.graalvm.compiler.nodes.StructuredGraph;
 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
+import org.graalvm.compiler.nodes.ValueNode;
+import org.graalvm.compiler.nodes.calc.ConvertNode;
 import org.graalvm.compiler.nodes.calc.SignExtendNode;
 import org.graalvm.compiler.nodes.extended.JavaReadNode;
 import org.graalvm.compiler.nodes.extended.JavaWriteNode;
@@ -84,21 +86,21 @@
     @Test
     public void testWrite1() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "1", AllowAssumptions.YES), true, ID);
+            assertWrite(parseEager("write" + kind.name() + "1", AllowAssumptions.YES), kind, true, ID);
         }
     }
 
     @Test
     public void testWrite2() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "2", AllowAssumptions.YES), true, ID);
+            assertWrite(parseEager("write" + kind.name() + "2", AllowAssumptions.YES), kind, true, ID);
         }
     }
 
     @Test
     public void testWrite3() {
         for (JavaKind kind : KINDS) {
-            assertWrite(parseEager("write" + kind.name() + "3", AllowAssumptions.YES), true, LocationIdentity.any());
+            assertWrite(parseEager("write" + kind.name() + "3", AllowAssumptions.YES), kind, true, LocationIdentity.any());
         }
     }
 
@@ -128,11 +130,17 @@
         Assert.assertEquals(read, ret.result());
     }
 
-    private void assertWrite(StructuredGraph graph, boolean indexConvert, LocationIdentity locationIdentity) {
+    private void assertWrite(StructuredGraph graph, JavaKind kind, boolean indexConvert, LocationIdentity locationIdentity) {
         WordCastNode cast = (WordCastNode) graph.start().next();
 
         JavaWriteNode write = (JavaWriteNode) cast.next();
-        Assert.assertEquals(graph.getParameter(2), write.value());
+        ValueNode valueNode = write.value();
+        if (kind != kind.getStackKind()) {
+            while (valueNode instanceof ConvertNode) {
+                valueNode = ((ConvertNode) valueNode).getValue();
+            }
+        }
+        Assert.assertEquals(graph.getParameter(2), valueNode);
         Assert.assertEquals(BytecodeFrame.AFTER_BCI, write.stateAfter().bci);
 
         OffsetAddressNode address = (OffsetAddressNode) write.getAddress();
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/Log.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/Log.java	Tue Jun 19 16:33:07 2018 +0100
@@ -40,7 +40,7 @@
 
     public static final ForeignCallDescriptor LOG_PRIMITIVE = new ForeignCallDescriptor("logPrimitive", void.class, int.class, long.class, boolean.class);
     public static final ForeignCallDescriptor LOG_OBJECT = new ForeignCallDescriptor("logObject", void.class, Object.class, boolean.class, boolean.class);
-    public static final ForeignCallDescriptor LOG_PRINTF = new ForeignCallDescriptor("logPrintf", void.class, Object.class, long.class, long.class, long.class);
+    public static final ForeignCallDescriptor LOG_PRINTF = new ForeignCallDescriptor("logPrintf", void.class, String.class, long.class, long.class, long.class);
 
     @NodeIntrinsic(ForeignCallNode.class)
     private static native void log(@ConstantNodeParameter ForeignCallDescriptor logObject, Object object, boolean asString, boolean newline);
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/PEGraphDecoder.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/PEGraphDecoder.java	Tue Jun 19 16:33:07 2018 +0100
@@ -846,7 +846,9 @@
         // Copy inlined methods from inlinee to caller
         List<ResolvedJavaMethod> inlinedMethods = graphToInline.getInlinedMethods();
         if (inlinedMethods != null) {
-            graph.getMethods().addAll(inlinedMethods);
+            for (ResolvedJavaMethod other : inlinedMethods) {
+                graph.recordMethod(other);
+            }
         }
 
         if (graphToInline.getFields() != null) {
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/StandardGraphBuilderPlugins.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/StandardGraphBuilderPlugins.java	Tue Jun 19 16:33:07 2018 +0100
@@ -267,14 +267,15 @@
     private static UnsafeCompareAndExchangePluginsRegistrar unsafeCompareAndExchangePluginsRegistrar = new UnsafeCompareAndExchangePluginsRegistrar();
 
     public static void registerPlatformSpecificUnsafePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider, JavaKind[] supportedCasKinds) {
-        Registration r;
-        if (Java8OrEarlier) {
-            r = new Registration(plugins, Unsafe.class);
-        } else {
-            r = new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider);
+        registerPlatformSpecificUnsafePlugins(supportedCasKinds, new Registration(plugins, Unsafe.class), true);
+        if (!Java8OrEarlier) {
+            registerPlatformSpecificUnsafePlugins(supportedCasKinds, new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider), false);
         }
 
-        if (Java8OrEarlier) {
+    }
+
+    private static void registerPlatformSpecificUnsafePlugins(JavaKind[] supportedCasKinds, Registration r, boolean java8OrEarlier) {
+        if (java8OrEarlier) {
             unsafeCompareAndSwapPluginsRegistrar.register(r, "compareAndSwap", new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object});
         } else {
             unsafeCompareAndSwapPluginsRegistrar.register(r, "compareAndSet", supportedCasKinds);
@@ -283,13 +284,13 @@
     }
 
     private static void registerUnsafePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
-        Registration r;
-        if (Java8OrEarlier) {
-            r = new Registration(plugins, Unsafe.class);
-        } else {
-            r = new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider);
+        registerUnsafePlugins(new Registration(plugins, Unsafe.class), true);
+        if (!Java8OrEarlier) {
+            registerUnsafePlugins(new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider), false);
         }
+    }
 
+    private static void registerUnsafePlugins(Registration r, boolean java8OrEarlier) {
         for (JavaKind kind : JavaKind.values()) {
             if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) {
                 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
@@ -297,30 +298,33 @@
                 String getName = "get" + kindName;
                 String putName = "put" + kindName;
                 // Object-based accesses
-                r.register3(getName, Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, false));
-                r.register4(putName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, false));
+                r.register3(getName, Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind));
+                r.register4(putName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind));
                 // Volatile object-based accesses
-                r.register3(getName + "Volatile", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, true));
-                r.register4(putName + "Volatile", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, true));
+                r.register3(getName + "Volatile", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.VOLATILE));
+                r.register4(putName + "Volatile", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.VOLATILE));
                 // Ordered object-based accesses
-                if (Java8OrEarlier) {
+                if (java8OrEarlier) {
                     if (kind == JavaKind.Int || kind == JavaKind.Long || kind == JavaKind.Object) {
-                        r.register4("putOrdered" + kindName, Receiver.class, Object.class, long.class, javaClass, UnsafePutPlugin.putOrdered(kind));
+                        r.register4("putOrdered" + kindName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.RELEASE_ACQUIRE));
                     }
                 } else {
-                    r.register4("put" + kindName + "Release", Receiver.class, Object.class, long.class, javaClass, UnsafePutPlugin.putOrdered(kind));
+                    r.register4("put" + kindName + "Release", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.RELEASE_ACQUIRE));
+                    r.register3("get" + kindName + "Acquire", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.RELEASE_ACQUIRE));
+                    r.register4("put" + kindName + "Opaque", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.OPAQUE));
+                    r.register3("get" + kindName + "Opaque", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.OPAQUE));
                 }
                 if (kind != JavaKind.Boolean && kind != JavaKind.Object) {
                     // Raw accesses to memory addresses
-                    r.register2(getName, Receiver.class, long.class, new UnsafeGetPlugin(kind, false));
-                    r.register3(putName, Receiver.class, long.class, kind.toJavaClass(), new UnsafePutPlugin(kind, false));
+                    r.register2(getName, Receiver.class, long.class, new UnsafeGetPlugin(kind));
+                    r.register3(putName, Receiver.class, long.class, kind.toJavaClass(), new UnsafePutPlugin(kind));
                 }
             }
         }
 
         // Accesses to native memory addresses.
-        r.register2("getAddress", Receiver.class, long.class, new UnsafeGetPlugin(JavaKind.Long, false));
-        r.register3("putAddress", Receiver.class, long.class, long.class, new UnsafePutPlugin(JavaKind.Long, false));
+        r.register2("getAddress", Receiver.class, long.class, new UnsafeGetPlugin(JavaKind.Long));
+        r.register3("putAddress", Receiver.class, long.class, long.class, new UnsafePutPlugin(JavaKind.Long));
 
         r.register2("allocateInstance", Receiver.class, Class.class, new InvocationPlugin() {
 
@@ -726,14 +730,52 @@
         }
     }
 
+    /**
+     * The new memory order modes (JDK9+) are defined with cumulative effect, from weakest to
+     * strongest: Plain, Opaque, Release/Acquire, and Volatile. The existing Plain and Volatile
+     * modes are defined compatibly with their pre-JDK 9 forms. Any guaranteed property of a weaker
+     * mode, plus more, holds for a stronger mode. (Conversely, implementations are allowed to use a
+     * stronger mode than requested for any access.) In JDK 9, these are provided without a full
+     * formal specification.
+     */
+    enum AccessKind {
+        PLAIN(0, 0, 0, 0, false),
+        /**
+         * Opaque accesses are wrapped by dummy membars to avoid floating/hoisting, this is stronger
+         * than required since Opaque mode does not directly impose any ordering constraints with
+         * respect to other variables beyond Plain mode.
+         */
+        OPAQUE(0, 0, 0, 0, true),
+        RELEASE_ACQUIRE(0, LOAD_LOAD | LOAD_STORE, LOAD_STORE | STORE_STORE, 0, true),
+        VOLATILE(JMM_PRE_VOLATILE_READ, JMM_POST_VOLATILE_READ, JMM_PRE_VOLATILE_WRITE, JMM_POST_VOLATILE_WRITE, true);
+
+        public final boolean emitBarriers;
+        public final int preReadBarriers;
+        public final int postReadBarriers;
+        public final int preWriteBarriers;
+        public final int postWriteBarriers;
+
+        AccessKind(int preReadBarriers, int postReadBarriers, int preWriteBarriers, int postWriteBarriers, boolean emitBarriers) {
+            this.emitBarriers = emitBarriers;
+            this.preReadBarriers = preReadBarriers;
+            this.postReadBarriers = postReadBarriers;
+            this.preWriteBarriers = preWriteBarriers;
+            this.postWriteBarriers = postWriteBarriers;
+        }
+    }
+
     public static class UnsafeGetPlugin implements InvocationPlugin {
 
         private final JavaKind returnKind;
-        private final boolean isVolatile;
+        private final AccessKind accessKind;
 
-        public UnsafeGetPlugin(JavaKind returnKind, boolean isVolatile) {
+        public UnsafeGetPlugin(JavaKind returnKind) {
+            this(returnKind, AccessKind.PLAIN);
+        }
+
+        public UnsafeGetPlugin(JavaKind returnKind, AccessKind accessKind) {
             this.returnKind = returnKind;
-            this.isVolatile = isVolatile;
+            this.accessKind = accessKind;
         }
 
         @Override
@@ -749,13 +791,13 @@
         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset) {
             // Emits a null-check for the otherwise unused receiver
             unsafe.get();
-            if (isVolatile) {
-                b.add(new MembarNode(JMM_PRE_VOLATILE_READ));
+            if (accessKind.emitBarriers) {
+                b.add(new MembarNode(accessKind.preReadBarriers));
             }
             LocationIdentity locationIdentity = object.isNullConstant() ? OFF_HEAP_LOCATION : LocationIdentity.any();
             b.addPush(returnKind, new RawLoadNode(object, offset, returnKind, locationIdentity));
-            if (isVolatile) {
-                b.add(new MembarNode(JMM_POST_VOLATILE_READ));
+            if (accessKind.emitBarriers) {
+                b.add(new MembarNode(accessKind.postReadBarriers));
             }
             b.getGraph().markUnsafeAccess();
             return true;
@@ -763,31 +805,22 @@
     }
 
     public static class UnsafePutPlugin implements InvocationPlugin {
+        private final JavaKind kind;
+        private final AccessKind accessKind;
 
-        private final JavaKind kind;
-        private final boolean hasBarrier;
-        private final int preWrite;
-        private final int postWrite;
-
-        public UnsafePutPlugin(JavaKind kind, boolean isVolatile) {
-            this(kind, isVolatile, JMM_PRE_VOLATILE_WRITE, JMM_POST_VOLATILE_WRITE);
+        public UnsafePutPlugin(JavaKind kind) {
+            this(kind, AccessKind.PLAIN);
         }
 
-        private UnsafePutPlugin(JavaKind kind, boolean hasBarrier, int preWrite, int postWrite) {
+        private UnsafePutPlugin(JavaKind kind, AccessKind accessKind) {
             super();
             this.kind = kind;
-            this.hasBarrier = hasBarrier;
-            this.preWrite = preWrite;
-            this.postWrite = postWrite;
-        }
-
-        public static UnsafePutPlugin putOrdered(JavaKind kind) {
-            return new UnsafePutPlugin(kind, true, LOAD_STORE | STORE_STORE, 0);
+            this.accessKind = accessKind;
         }
 
         @Override
         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode address, ValueNode value) {
-            assert !hasBarrier : "Barriers for address based Unsafe put is not supported.";
+            assert !accessKind.emitBarriers : "Barriers for address based Unsafe put is not supported.";
             // Emits a null-check for the otherwise unused receiver
             unsafe.get();
             b.add(new UnsafeMemoryStoreNode(address, value, kind, OFF_HEAP_LOCATION));
@@ -799,13 +832,13 @@
         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode value) {
             // Emits a null-check for the otherwise unused receiver
             unsafe.get();
-            if (hasBarrier) {
-                b.add(new MembarNode(preWrite));
+            if (accessKind.emitBarriers) {
+                b.add(new MembarNode(accessKind.preWriteBarriers));
             }
             LocationIdentity locationIdentity = object.isNullConstant() ? OFF_HEAP_LOCATION : LocationIdentity.any();
-            b.add(new RawStoreNode(object, offset, value, kind, locationIdentity));
-            if (hasBarrier) {
-                b.add(new MembarNode(postWrite));
+            b.add(new RawStoreNode(object, offset, b.maskSubWordValue(value, kind), kind, locationIdentity));
+            if (accessKind.emitBarriers) {
+                b.add(new MembarNode(accessKind.postWriteBarriers));
             }
             b.getGraph().markUnsafeAccess();
             return true;
--- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.virtual/src/org/graalvm/compiler/virtual/phases/ea/PEReadEliminationClosure.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.virtual/src/org/graalvm/compiler/virtual/phases/ea/PEReadEliminationClosure.java	Tue Jun 19 16:33:07 2018 +0100
@@ -244,29 +244,9 @@
         return processLoad(load, load.object(), new FieldLocationIdentity(load.field()), -1, load.field().getJavaKind(), state, effects);
     }
 
-    private static JavaKind getElementKindFromStamp(ValueNode array) {
-        ResolvedJavaType type = StampTool.typeOrNull(array);
-        if (type != null && type.isArray()) {
-            return type.getComponentType().getJavaKind();
-        } else {
-            // It is likely an OSRLocal without valid stamp
-            return JavaKind.Illegal;
-        }
-    }
-
     private boolean processStoreIndexed(StoreIndexedNode store, PEReadEliminationBlockState state, GraphEffectList effects) {
         int index = store.index().isConstant() ? ((JavaConstant) store.index().asConstant()).asInt() : -1;
-        // BASTORE (with elementKind being Byte) can be used to store values in boolean arrays.
         JavaKind elementKind = store.elementKind();
-        if (elementKind == JavaKind.Byte) {
-            elementKind = getElementKindFromStamp(store.array());
-            if (elementKind == JavaKind.Illegal) {
-                // Could not determine the actual access kind from stamp. Hence kill both.
-                state.killReadCache(NamedLocationIdentity.getArrayLocation(JavaKind.Boolean), index);
-                state.killReadCache(NamedLocationIdentity.getArrayLocation(JavaKind.Byte), index);
-                return false;
-            }
-        }
         LocationIdentity arrayLocation = NamedLocationIdentity.getArrayLocation(elementKind);
         if (index != -1) {
             return processStore(store, store.array(), arrayLocation, index, elementKind, false, store.value(), state, effects);
@@ -279,15 +259,7 @@
     private boolean processLoadIndexed(LoadIndexedNode load, PEReadEliminationBlockState state, GraphEffectList effects) {
         if (load.index().isConstant()) {
             int index = ((JavaConstant) load.index().asConstant()).asInt();
-            // BALOAD (with elementKind being Byte) can be used to retrieve values from boolean
-            // arrays.
             JavaKind elementKind = load.elementKind();
-            if (elementKind == JavaKind.Byte) {
-                elementKind = getElementKindFromStamp(load.array());
-                if (elementKind == JavaKind.Illegal) {
-                    return false;
-                }
-            }
             LocationIdentity arrayLocation = NamedLocationIdentity.getArrayLocation(elementKind);
             return processLoad(load, load.array(), arrayLocation, index, elementKind, state, effects);
         }
--- a/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Tue Jun 19 16:33:07 2018 +0100
@@ -26,15 +26,12 @@
 package sun.tools.jar;
 
 import java.io.File;
-import java.io.PrintStream;
 import java.io.PrintWriter;
-import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleDescriptor.Version;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
-
 import jdk.internal.module.ModulePath;
 import jdk.internal.module.ModuleResolution;
 
@@ -292,6 +289,10 @@
                 break;
 
             String name = args[count];
+            if (name.equals("-XDsuppress-tool-removal-message")) {
+                jartool.suppressDeprecateMsg = true;
+                continue;
+            }
             Option option = getOption(name);
             String param = null;
             if (option.hasArg) {
--- a/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,33 +31,34 @@
 import java.lang.module.InvalidModuleDescriptorException;
 import java.lang.module.ModuleDescriptor;
 import java.lang.module.ModuleDescriptor.Exports;
+import java.lang.module.ModuleDescriptor.Opens;
 import java.lang.module.ModuleDescriptor.Provides;
-import java.lang.module.ModuleDescriptor.Opens;
-import java.lang.module.ModuleDescriptor.Requires;
 import java.lang.module.ModuleDescriptor.Version;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReader;
 import java.lang.module.ModuleReference;
-import java.lang.module.ResolutionException;
 import java.lang.module.ResolvedModule;
 import java.net.URI;
 import java.nio.ByteBuffer;
+import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.nio.file.StandardCopyOption;
+import java.text.MessageFormat;
 import java.util.*;
 import java.util.function.Consumer;
-import java.util.function.Supplier;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
-import java.util.zip.*;
-import java.util.jar.*;
-import java.util.jar.Pack200.*;
-import java.util.jar.Manifest;
-import java.text.MessageFormat;
-
+import java.util.zip.CRC32;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
 import jdk.internal.module.Checks;
 import jdk.internal.module.ModuleHashes;
 import jdk.internal.module.ModuleHashesBuilder;
@@ -67,10 +68,10 @@
 import jdk.internal.module.ModuleTarget;
 import jdk.internal.util.jar.JarIndex;
 
-import static jdk.internal.util.jar.JarIndex.INDEX_NAME;
+import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
 import static java.util.jar.JarFile.MANIFEST_NAME;
 import static java.util.stream.Collectors.joining;
-import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
+import static jdk.internal.util.jar.JarIndex.INDEX_NAME;
 
 /**
  * This class implements a simple utility for creating files in the JAR
@@ -151,6 +152,8 @@
      */
     boolean cflag, uflag, xflag, tflag, vflag, flag0, Mflag, iflag, nflag, pflag, dflag;
 
+    boolean suppressDeprecateMsg = false;
+
     /* To support additional GNU Style informational options */
     Consumer<PrintWriter> info;
 
@@ -238,6 +241,7 @@
     /**
      * Starts main program with the specified arguments.
      */
+    @SuppressWarnings({"removal"})
     public synchronized boolean run(String args[]) {
         ok = true;
         if (!parseArgs(args)) {
@@ -315,11 +319,14 @@
                     create(new BufferedOutputStream(out, 4096), manifest);
                 }
                 if (nflag) {
+                    if (!suppressDeprecateMsg) {
+                        warn(formatMsg("warn.flag.is.deprecated", "-n"));
+                    }
                     File packFile = createTemporaryFile(tmpbase, ".pack");
                     try {
-                        Packer packer = Pack200.newPacker();
+                        java.util.jar.Pack200.Packer packer = java.util.jar.Pack200.newPacker();
                         Map<String, String> p = packer.properties();
-                        p.put(Packer.EFFORT, "1"); // Minimal effort to conserve CPU
+                        p.put(java.util.jar.Pack200.Packer.EFFORT, "1"); // Minimal effort to conserve CPU
                         try (JarFile jarFile = new JarFile(tmpFile.getCanonicalPath());
                              OutputStream pack = new FileOutputStream(packFile))
                         {
@@ -332,7 +339,7 @@
                         try (OutputStream out = new FileOutputStream(tmpFile);
                              JarOutputStream jos = new JarOutputStream(out))
                         {
-                            Unpacker unpacker = Pack200.newUnpacker();
+                            java.util.jar.Pack200.Unpacker unpacker = java.util.jar.Pack200.newUnpacker();
                             unpacker.unpack(packFile, jos);
                         }
                     } finally {
--- a/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Tue Jun 19 16:33:07 2018 +0100
@@ -131,6 +131,8 @@
         in incompatible public interfaces
 warn.release.unexpected.versioned.entry=\
         unexpected versioned entry {0}
+warn.flag.is.deprecated=\
+        Warning: The {0} option is deprecated, and is planned for removal in a future JDK release\n
 out.added.manifest=\
         added manifest
 out.added.module-info=\
@@ -170,7 +172,8 @@
 \ \   -v  generate verbose output on standard output\n\
 \ \   -f  specify archive file name\n\
 \ \   -m  include manifest information from specified manifest file\n\
-\ \   -n  perform Pack200 normalization after creating a new archive\n\
+\ \   -n  perform Pack200 normalization after creating a new archive,\n\
+\ \       this option is deprecated, and is planned for removal in a future JDK release\n\
 \ \   -e  specify application entry point for stand-alone application \n\
 \ \       bundled into an executable jar file\n\
 \ \   -0  store only; use no ZIP compression\n\
@@ -250,7 +253,8 @@
 \ Operation modifiers valid only in create mode:\n
 main.help.opt.create.normalize=\
 \  -n, --normalize            Normalize information in the new jar archive\n\
-\                             after creation
+\                             after creation. This option is deprecated, and is\n\
+\                             planned for removal in a future JDK release
 main.help.opt.create.update=\
 \ Operation modifiers valid only in create and update mode:\n
 main.help.opt.create.update.main-class=\
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java	Tue Jun 19 16:33:07 2018 +0100
@@ -176,8 +176,6 @@
 
     HtmlTree fixedNavDiv = new HtmlTree(HtmlTag.DIV);
 
-    final static Pattern IMPROPER_HTML_CHARS = Pattern.compile(".*[&<>].*");
-
     /**
      * The window title of this file.
      */
@@ -910,15 +908,7 @@
      */
     public Content getDocLink(LinkInfoImpl.Kind context, TypeElement typeElement, Element element,
             CharSequence label, boolean strong, boolean isProperty) {
-        return getDocLink(context, typeElement, element, new StringContent(check(label)), strong, isProperty);
-    }
-
-    CharSequence check(CharSequence s) {
-        Matcher m = IMPROPER_HTML_CHARS.matcher(s);
-        if (m.matches()) {
-            throw new IllegalArgumentException(s.toString());
-        }
-        return s;
+        return getDocLink(context, typeElement, element, new StringContent(label), strong, isProperty);
     }
 
     public Content getDocLink(LinkInfoImpl.Kind context, TypeElement typeElement, Element element,
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java	Tue Jun 19 16:33:07 2018 +0100
@@ -406,9 +406,9 @@
      * {@inheritDoc}
      */
     public Content valueTagOutput(VariableElement field, String constantVal, boolean includeLink) {
-        return includeLink ?
-            htmlWriter.getDocLink(LinkInfoImpl.Kind.VALUE_TAG, field,
-                constantVal, false) : new RawHtml(constantVal);
+        return includeLink
+                ? htmlWriter.getDocLink(LinkInfoImpl.Kind.VALUE_TAG, field, constantVal, false)
+                : new StringContent(constantVal);
     }
 
     /**
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/jquery/jquery-migrate-3.0.1.js	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/jquery/jquery-migrate-3.0.1.js	Tue Jun 19 16:33:07 2018 +0100
@@ -23,6 +23,8 @@
 
 jQuery.migrateVersion = "3.0.1";
 
+jQuery.migrateMute = true;
+
 /* exported migrateWarn, migrateWarnFunc, migrateWarnProp */
 
 ( function() {
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,6 +36,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.IllformedLocaleException;
 import java.util.List;
 import java.util.Locale;
 import java.util.MissingResourceException;
@@ -853,46 +854,17 @@
      * then return default locale.
      */
     private Locale getLocale(String localeName) throws ToolException {
-        Locale userlocale = null;
-        if (localeName == null || localeName.isEmpty()) {
-            return Locale.getDefault();
-        }
-        int firstuscore = localeName.indexOf('_');
-        int seconduscore = -1;
-        String language = null;
-        String country = null;
-        String variant = null;
-        if (firstuscore == 2) {
-            language = localeName.substring(0, firstuscore);
-            seconduscore = localeName.indexOf('_', firstuscore + 1);
-            if (seconduscore > 0) {
-                if (seconduscore != firstuscore + 3
-                        || localeName.length() <= seconduscore + 1) {
-                    String text = messager.getText("main.malformed_locale_name", localeName);
-                    throw new ToolException(CMDERR, text);
-                }
-                country = localeName.substring(firstuscore + 1,
-                        seconduscore);
-                variant = localeName.substring(seconduscore + 1);
-            } else if (localeName.length() == firstuscore + 3) {
-                country = localeName.substring(firstuscore + 1);
-            } else {
-                String text = messager.getText("main.malformed_locale_name", localeName);
-                throw new ToolException(CMDERR, text);
-            }
-        } else if (firstuscore == -1 && localeName.length() == 2) {
-            language = localeName;
-        } else {
+        try {
+            // Tolerate, at least for a while, the older syntax accepted by javadoc,
+            // using _ as the separator
+            localeName = localeName.replace("_", "-");
+            Locale l =  new Locale.Builder().setLanguageTag(localeName).build();
+            // Ensure that a non-empty language is available for the <HTML lang=...> element
+            return (l.getLanguage().isEmpty()) ? Locale.ENGLISH : l;
+        } catch (IllformedLocaleException e) {
             String text = messager.getText("main.malformed_locale_name", localeName);
             throw new ToolException(CMDERR, text);
         }
-        userlocale = searchLocale(language, country, variant);
-        if (userlocale == null) {
-            String text = messager.getText("main.illegal_locale_name", localeName);
-            throw new ToolException(CMDERR, text);
-        } else {
-            return userlocale;
-        }
     }
 
     /**
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/resources/javadoc.properties	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/resources/javadoc.properties	Tue Jun 19 16:33:07 2018 +0100
@@ -285,7 +285,6 @@
 main.doclet_no_classloader_found=Could not obtain classloader to load {0}
 main.could_not_instantiate_class=Could not instantiate class {0}
 main.doclet_class_not_found=Cannot find doclet class {0}
-main.illegal_locale_name=Locale not available: {0}
 main.malformed_locale_name=Malformed locale name: {0}
 main.file_not_found=File not found: "{0}"
 main.illegal_class_name=Illegal class name: "{0}"
--- a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Tue Jun 19 16:33:07 2018 +0100
@@ -347,7 +347,7 @@
                 this.root = null;
                 this.systemModules = Collections.emptyMap();
             } else {
-                if (Files.isRegularFile(Paths.get(javaHome, "lib", "modules")))
+                if (!Files.isRegularFile(Paths.get(javaHome, "lib", "modules")))
                     throw new IllegalArgumentException("Invalid java.home: " + javaHome);
 
                 // alternate java.home
--- a/src/jdk.pack/share/classes/module-info.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.pack/share/classes/module-info.java	Tue Jun 19 16:33:07 2018 +0100
@@ -36,7 +36,10 @@
  * </dl>
  *
  * @moduleGraph
+ * @deprecated This module is deprecated, and is planned for removal in a
+ *             future release.
  * @since 9
  */
+@Deprecated(since="11", forRemoval=true)
 module jdk.pack {
 }
--- a/src/jdk.pack/share/native/common-unpack/defines.h	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.pack/share/native/common-unpack/defines.h	Tue Jun 19 16:33:07 2018 +0100
@@ -118,6 +118,7 @@
 #define tempname        _tempname
 #define sleep           Sleep
 #define snprintf        _snprintf
+#define PATH_SEPARATOR '\\'
 #else
 typedef signed char byte;
 #ifdef _LP64
@@ -128,6 +129,7 @@
 typedef long long unsigned julong;
 #endif
 #define MKDIR(dir) mkdir(dir, 0777);
+#define PATH_SEPARATOR '/'
 #endif
 
 #ifdef OLDCC
--- a/src/jdk.pack/share/native/unpack200/main.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/src/jdk.pack/share/native/unpack200/main.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -139,7 +139,7 @@
 }
 
 static const char* nbasename(const char* progname) {
-  const char* slash = strrchr(progname, '/');
+  const char* slash = strrchr(progname, PATH_SEPARATOR);
   if (slash != null)  progname = ++slash;
   return progname;
 }
@@ -161,6 +161,13 @@
     "Exit Status:\n" \
     "  0 if successful, >0 if an error occurred\n"
 
+#define DEPRECATE_WARNING \
+    "\nWarning: The %s tool is deprecated, and is planned for removal in a future JDK release.\n\n"
+
+#define SUPPRESS_DEPRECATE_MSG "-XDsuppress-tool-removal-message"
+
+static bool suppress_warning = false;
+
 static void usage(unpacker* u, const char* progname, bool full = false) {
   // WinMain does not set argv[0] to the progrname
   progname = (progname != null) ? nbasename(progname) : "unpack200";
@@ -182,7 +189,11 @@
     char* buf = (char*) strdup(env);
     const char* delim = "\n\t ";
     for (char* p = strtok(buf, delim); p != null; p = strtok(null, delim)) {
-      envargs.add(p);
+      if (!strcmp(p, SUPPRESS_DEPRECATE_MSG)) {
+        suppress_warning = true;
+      } else {
+        envargs.add(p);
+      }
     }
   }
   // allocate extra margin at both head and tail
@@ -194,7 +205,11 @@
   }
   for (i = 1; i < argc; i++) {
     // note: skip argv[0] (program name)
-    *argp++ = (char*) strdup(argv[i]);  // make a scratch copy
+    if (!strcmp(argv[i], SUPPRESS_DEPRECATE_MSG)) {
+      suppress_warning = true;
+    } else {
+      *argp++ = (char*) strdup(argv[i]);  // make a scratch copy
+    }
   }
   *argp = null; // sentinel
   envargc = envargs.length();  // report this count to next_arg
@@ -293,6 +308,10 @@
   int verbose = 0;
   char* logfile = null;
 
+  if (!suppress_warning) {
+      fprintf(u.errstrm, DEPRECATE_WARNING, nbasename(argv[0]));
+  }
+
   for (;;) {
     const char* arg = (*argp == null)? "": u.saveStr(*argp);
     bool isenvarg = (argp < arg0);
--- a/test/hotspot/gtest/jfr/test_threadCpuLoad.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/gtest/jfr/test_threadCpuLoad.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -32,42 +32,15 @@
 // with the ones that should pick up the mocks removed. Those should be included
 // later after the mocks have been defined.
 
-#include "jvm.h"
-#include "classfile/classLoaderStats.hpp"
-#include "classfile/javaClasses.hpp"
-#include "code/codeCache.hpp"
-#include "compiler/compileBroker.hpp"
-#include "gc/g1/g1HeapRegionEventSender.hpp"
-#include "gc/shared/gcConfiguration.hpp"
-#include "gc/shared/gcTrace.hpp"
-#include "gc/shared/objectCountEventSender.hpp"
-#include "gc/shared/vmGCOperations.hpp"
+#include "logging/log.hpp"
 #include "jfr/jfrEvents.hpp"
-#include "jfr/periodic/jfrModuleEvent.hpp"
-#include "jfr/periodic/jfrOSInterface.hpp"
-#include "jfr/periodic/jfrThreadCPULoadEvent.hpp"
-#include "jfr/periodic/jfrThreadDumpEvent.hpp"
-#include "jfr/recorder/jfrRecorder.hpp"
 #include "jfr/support/jfrThreadId.hpp"
+#include "jfr/support/jfrThreadLocal.hpp"
 #include "jfr/utilities/jfrTime.hpp"
-#include "logging/log.hpp"
-#include "memory/heapInspection.hpp"
-#include "memory/resourceArea.hpp"
-#include "oops/oop.inline.hpp"
-#include "runtime/arguments.hpp"
-#include "runtime/flags/jvmFlag.hpp"
-#include "runtime/globals.hpp"
+#include "utilities/globalDefinitions.hpp"
 #include "runtime/os.hpp"
-#include "runtime/os_perf.hpp"
 #include "runtime/thread.inline.hpp"
-#include "runtime/threadSMR.hpp"
-#include "runtime/sweeper.hpp"
-#include "runtime/vmThread.hpp"
-#include "services/classLoadingService.hpp"
-#include "services/management.hpp"
-#include "services/threadService.hpp"
-#include "utilities/exceptions.hpp"
-#include "utilities/globalDefinitions.hpp"
+#include "runtime/threadSMR.inline.hpp"
 
 #include "unittest.hpp"
 
@@ -103,6 +76,18 @@
   jlong MockOs::user_cpu_time;
   jlong MockOs::system_cpu_time;
 
+  class MockJavaThread : public ::JavaThread {
+  public:
+    MockJavaThread() : ::JavaThread() {}
+  };
+
+  class MockJavaThreadIteratorWithHandle
+  {
+  public:
+    MockJavaThread* next() { return NULL; }
+    int length() { return 0; }
+  };
+
 // Reincluding source files in the anonymous namespace unfortunately seems to
 // behave strangely with precompiled headers (only when using gcc though)
 #ifndef DONT_USE_PRECOMPILED_HEADER
@@ -111,23 +96,27 @@
 
 #define os MockOs
 #define EventThreadCPULoad MockEventThreadCPULoad
+#define JavaThread MockJavaThread
+#define JavaThreadIteratorWithHandle MockJavaThreadIteratorWithHandle
 
-#include "jfrfiles/jfrPeriodic.hpp"
-#include "jfr/periodic/jfrPeriodic.cpp"
+#include "jfr/periodic/jfrThreadCPULoadEvent.hpp"
+#include "jfr/periodic/jfrThreadCPULoadEvent.cpp"
 
 #undef os
 #undef EventThreadCPULoad
+#undef JavaThread
+#undef JavaThreadIteratorWithHandle
 
 } // anonymous namespace
 
 class JfrTestThreadCPULoadSingle : public ::testing::Test {
 protected:
-  JavaThread* thread;
+  MockJavaThread* thread;
   JfrThreadLocal* thread_data;
   MockEventThreadCPULoad event;
 
   void SetUp() {
-    thread = new JavaThread();
+    thread = new MockJavaThread();
     thread_data = thread->jfr_thread_local();
     thread_data->set_wallclock_time(0);
     thread_data->set_user_time(0);
@@ -137,9 +126,15 @@
   void TearDown() {
     delete thread;
   }
+
+  // Fix for gcc compilation warning about unused functions
+  bool TouchUnused() {
+    return (&JfrThreadCPULoadEvent::send_events &&
+            &JfrThreadCPULoadEvent::send_event_for_thread);
+  }
 };
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_SingleCpu) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, SingleCpu) {
   MockOs::user_cpu_time = 100 * NANOSECS_PER_MILLISEC;
   MockOs::system_cpu_time = 100 * NANOSECS_PER_MILLISEC;
   EXPECT_TRUE(JfrThreadCPULoadEvent::update_event(event, thread, 400 * NANOSECS_PER_MILLISEC, 1));
@@ -147,7 +142,7 @@
   EXPECT_FLOAT_EQ(0.25, event.system);
 }
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_MultipleCpus) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, MultipleCpus) {
   MockOs::user_cpu_time = 100 * NANOSECS_PER_MILLISEC;
   MockOs::system_cpu_time = 100 * NANOSECS_PER_MILLISEC;
   EXPECT_TRUE(JfrThreadCPULoadEvent::update_event(event, thread, 400 * NANOSECS_PER_MILLISEC, 2));
@@ -155,13 +150,13 @@
   EXPECT_FLOAT_EQ(0.125, event.system);
 }
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_BelowThreshold) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, BelowThreshold) {
   MockOs::user_cpu_time = 100;
   MockOs::system_cpu_time = 100;
   EXPECT_FALSE(JfrThreadCPULoadEvent::update_event(event, thread, 400 * NANOSECS_PER_MILLISEC, 2));
 }
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_UserAboveMaximum) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, UserAboveMaximum) {
 
   // First call will not report above 100%
   MockOs::user_cpu_time = 200 * NANOSECS_PER_MILLISEC;
@@ -176,7 +171,7 @@
   EXPECT_FLOAT_EQ(0, event.system);
 }
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_SystemAboveMaximum) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, SystemAboveMaximum) {
 
   // First call will not report above 100%
   MockOs::user_cpu_time = 100 * NANOSECS_PER_MILLISEC;
@@ -191,7 +186,7 @@
   EXPECT_FLOAT_EQ(0.25, event.system);
 }
 
-TEST_VM_F(JfrTestThreadCPULoadSingle, DISABLED_SystemTimeDecreasing) {
+TEST_VM_F(JfrTestThreadCPULoadSingle, SystemTimeDecreasing) {
 
   // As seen in an actual run - caused by different resolution for total and user time
   // Total time    User time    (Calculated system time)
--- a/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/gtest/utilities/test_concurrentHashtable.cpp	Tue Jun 19 16:33:07 2018 +0100
@@ -211,7 +211,7 @@
   // Removes all odd values.
   SimpleTestTable::BulkDeleteTask bdt(cht);
   if (bdt.prepare(thr)) {
-    while(bdt.doTask(thr, getinsert_bulkdelete_eval, getinsert_bulkdelete_del)) {
+    while(bdt.do_task(thr, getinsert_bulkdelete_eval, getinsert_bulkdelete_del)) {
       bdt.pause(thr);
       EXPECT_TRUE(bdt.cont(thr)) << "Uncontended continue should work.";
     }
@@ -362,7 +362,7 @@
 
   SimpleTestTable::GrowTask gt(cht);
   EXPECT_TRUE(gt.prepare(thr)) << "Growing uncontended should not fail.";
-  while(gt.doTask(thr)) { /* grow */  }
+  while(gt.do_task(thr)) { /* grow */  }
   gt.done(thr);
 
   EXPECT_TRUE(cht->get_copy(thr, stl) == val) << "Getting an item after grow failed.";
@@ -953,3 +953,73 @@
   GI_BD_InserterThread::_shrink = false;
   mt_test_doer<RunnerGI_BD_InserterThread>();
 }
+
+//#############################################################################################
+
+class MT_BD_Thread : public JavaTestThread {
+  TestTable::BulkDeleteTask* _bd;
+  public:
+  MT_BD_Thread(Semaphore* post, TestTable::BulkDeleteTask* bd)
+    : JavaTestThread(post), _bd(bd){}
+  virtual ~MT_BD_Thread() {}
+  void main_run() {
+    MyDel del;
+    while(_bd->do_task(this, *this, del));
+  }
+
+  bool operator()(uintptr_t* val) {
+    return true;
+  }
+
+  struct MyDel {
+    void operator()(uintptr_t* val) {
+    }
+  };
+};
+
+class Driver_BD_Thread : public JavaTestThread {
+public:
+  Semaphore _done;
+  Driver_BD_Thread(Semaphore* post) : JavaTestThread(post) {
+  };
+  virtual ~Driver_BD_Thread(){}
+
+  void main_run() {
+    Semaphore done(0);
+    TestTable* cht = new TestTable(16, 16, 2);
+    for (uintptr_t v = 1; v < 99999; v++ ) {
+      TestLookup tl(v);
+      EXPECT_TRUE(cht->insert(this, tl, v)) << "Inserting an unique value should work.";
+    }
+    TestTable::BulkDeleteTask bdt(cht, true /* mt */ );
+    EXPECT_TRUE(bdt.prepare(this)) << "Uncontended prepare must work.";
+
+    MT_BD_Thread* tt[4];
+    for (int i = 0; i < 4; i++) {
+      tt[i] = new MT_BD_Thread(&done, &bdt);
+      tt[i]->doit();
+    }
+
+    for (uintptr_t v = 1; v < 99999; v++ ) {
+      TestLookup tl(v);
+      cht->get_copy(this, tl);
+    }
+
+    for (int i = 0; i < 4; i++) {
+      done.wait();
+    }
+
+    bdt.done(this);
+
+    cht->do_scan(this, *this);
+  }
+
+  bool operator()(uintptr_t* val) {
+    EXPECT_TRUE(false) << "No items should left";
+    return true;
+  }
+};
+
+TEST_VM(ConcurrentHashTable, concurrent_mt_bulk_delete) {
+  mt_test_doer<Driver_BD_Thread>();
+}
--- a/test/hotspot/jtreg/ProblemList.txt	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/ProblemList.txt	Tue Jun 19 16:33:07 2018 +0100
@@ -52,7 +52,7 @@
 compiler/c2/Test8007294.java 8192992 generic-all
 
 applications/ctw/modules/java_desktop.java 8189604 windows-all
-applications/ctw/modules/java_desktop_2.java 8189604 windows-all
+applications/ctw/modules/java_desktop_2.java 8189604,8204842 generic-all
 applications/ctw/modules/jdk_jconsole.java 8189604 windows-all
 
 #############################################################################
--- a/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -125,7 +125,7 @@
             "interpreted mode"
         },
         {
-            "intx CompileThreshold                         = 0                                      {pd product} {command line, ergonomic}",
+            "intx CompileThreshold                         = 0                                      {pd product} {command line}",
             "double CompileThresholdScaling                  = 0.750000                                  {product} {command line}",
             "interpreted mode"
         }
--- a/test/hotspot/jtreg/compiler/jsr292/InvokerSignatureMismatch.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/compiler/jsr292/InvokerSignatureMismatch.java	Tue Jun 19 16:33:07 2018 +0100
@@ -39,7 +39,7 @@
 
     static void mainLink(int i) throws Throwable {
         Object name = MethodHandleHelper.internalMemberName(INT_MH);
-        MethodHandleHelper.linkToStatic(INT_MH, (float) i, name);
+        MethodHandleHelper.linkToStatic((float) i, name);
     }
 
     static void mainInvoke(int i) throws Throwable {
--- a/test/hotspot/jtreg/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Tue Jun 19 16:33:07 2018 +0100
@@ -49,8 +49,8 @@
     }
 
     @ForceInline
-    public static void linkToStatic(MethodHandle mh, float arg, Object name) throws Throwable {
-        MethodHandle.linkToStatic(mh, arg, name);
+    public static void linkToStatic(float arg, Object name) throws Throwable {
+        MethodHandle.linkToStatic(arg, name);
     }
 
     @ForceInline
--- a/test/hotspot/jtreg/compiler/loopopts/IterationSplitPredicateInconsistency.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/compiler/loopopts/IterationSplitPredicateInconsistency.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,11 +23,12 @@
 
 /**
  * @test
- * @bug 8193130
+ * @bug 8193130 8203915
  * @summary Bad graph when unrolled loop bounds conflicts with range checks
  *
  * @run main/othervm IterationSplitPredicateInconsistency
  * @run main/othervm -XX:-UseLoopPredicate IterationSplitPredicateInconsistency
+ * @run main/othervm -XX:LoopStripMiningIter=0 IterationSplitPredicateInconsistency
  *
  */
 
--- a/test/hotspot/jtreg/compiler/loopopts/TestOverunrolling.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/compiler/loopopts/TestOverunrolling.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,11 +23,12 @@
 
 /*
  * @test
- * @bug 8159016 8202949
+ * @bug 8159016 8202949 8203915
  * @summary Tests correct dominator information after over-unrolling a loop.
  * @requires vm.gc == "Parallel" | vm.gc == "null"
  * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockExperimentalVMOptions
  *                   -Xcomp -XX:-TieredCompilation -XX:-UseSwitchProfiling
+ *                   -XX:-UseCountedLoopSafepoints -XX:LoopUnrollLimit=250
  *                   -XX:-UseG1GC -XX:+UseParallelGC compiler.loopopts.TestOverunrolling
  */
 
@@ -81,11 +82,74 @@
         }
     }
 
+    // Similar to test2 but we cannot statically determine the upper bound of
+    // the inner for loop and can therefore not prevent over-unrolling.
+    public static void test3(int[] array) {
+        int[] iArr = new int[8];
+        for (int i = 0; i < array.length; i++) {
+            for (int j = 5; j < i; j++) {
+                int k = 1;
+                do {
+                    iArr[j] = 0;
+                    switch (k) {
+                    case 1:
+                        lFld = 0;
+                        break;
+                    case 10:
+                        dFld = 0;
+                        break;
+                    }
+                } while (++k < 1);
+            }
+        }
+    }
+
+    // Similar to test3 but with negative stride and constant outer loop limit
+    public static void test4(int[] array, boolean store) {
+        int[] iArr = new int[8];
+        for (int i = -8; i < 8; i++) {
+            for (int j = 5; j > i; j--) {
+                int k = 1;
+                do {
+                    if (store) {
+                        iArr[j] = 0;
+                    }
+                    switch (k) {
+                    case 1:
+                        lFld = 0;
+                        break;
+                    case 10:
+                        dFld = 0;
+                        break;
+                    }
+                } while (++k < 1);
+            }
+        }
+    }
+
+    // The inner for-loop is over-unrolled and vectorized resulting in
+    // a crash in the matcher because the memory input to a vector is top.
+    public static int test5(int[] array) {
+        int result = 0;
+        int[] iArr = new int[8];
+        for (int i = 0; i < array.length; i++) {
+            for (int j = 5; j < i; j++) {
+                iArr[j] += array[j];
+                result += array[j];
+            }
+        }
+        return result;
+    }
+
     public static void main(String args[]) {
         for (int i = 0; i < 42; ++i) {
             test1(i);
         }
         test2();
+        int[] array = new int[8];
+        test3(array);
+        test4(array, false);
+        test5(array);
     }
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestNegBaseOffset.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8202948
+ * @summary Test skipping vector packs with negative base offset.
+ * @comment Test fails only with -Xcomp when profiling data is not present.
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockExperimentalVMOptions
+ *                   -Xcomp -XX:-TieredCompilation -XX:CICompilerCount=1
+ *                   -XX:CompileOnly=compiler/loopopts/superword/TestNegBaseOffset
+ *                   compiler.loopopts.superword.TestNegBaseOffset
+ */
+
+package compiler.loopopts.superword;
+
+public class TestNegBaseOffset {
+    public static final int N = 400;
+    public static int iFld=10;
+    public static int iArr[]=new int[N];
+
+    public static void mainTest() {
+        int i0=1, i2;
+        while (++i0 < 339) {
+            if ((i0 % 2) == 0) {
+                for (i2 = 2; i2 > i0; i2 -= 3) {
+                    iArr[i2 - 1] &= iFld;
+                }
+            }
+        }
+    }
+
+    public static void main(String[] strArr) {
+        for (int i = 0; i < 10; i++) {
+            mainTest();
+        }
+    }
+}
+
--- a/test/hotspot/jtreg/gc/TestMemoryMXBeansAndPoolsPresence.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/gc/TestMemoryMXBeansAndPoolsPresence.java	Tue Jun 19 16:33:07 2018 +0100
@@ -86,7 +86,7 @@
     public static void main(String[] args) {
         switch (args[0]) {
             case "G1":
-                test(new GCBeanDescription("G1 Young Generation", new String[] {"G1 Eden Space", "G1 Survivor Space"}),
+                test(new GCBeanDescription("G1 Young Generation", new String[] {"G1 Eden Space", "G1 Survivor Space", "G1 Old Gen"}),
                      new GCBeanDescription("G1 Old Generation",   new String[] {"G1 Eden Space", "G1 Survivor Space", "G1 Old Gen"}));
                 break;
             case "CMS":
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/arguments/TestParallelRefProc.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 TestParallelRefProc
+ * @key gc
+ * @summary Test defaults processing for -XX:+ParallelRefProcEnabled.
+ * @library /test/lib
+ * @run driver TestParallelRefProc
+ */
+
+import java.util.Arrays;
+import java.util.ArrayList;
+
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class TestParallelRefProc {
+
+    public static void main(String args[]) throws Exception {
+        testFlag(new String[] { "-XX:+UseSerialGC" }, false);
+        testFlag(new String[] { "-XX:+UseConcMarkSweepGC" }, false);
+        testFlag(new String[] { "-XX:+UseParallelGC" }, false);
+        testFlag(new String[] { "-XX:+UseG1GC", "-XX:ParallelGCThreads=1" }, false);
+        testFlag(new String[] { "-XX:+UseG1GC", "-XX:ParallelGCThreads=2" }, true);
+        testFlag(new String[] { "-XX:+UseG1GC", "-XX:-ParallelRefProcEnabled", "-XX:ParallelGCThreads=2" }, false);
+    }
+
+    private static final String parallelRefProcEnabledPattern =
+        " *bool +ParallelRefProcEnabled *= *true +\\{product\\}";
+
+    private static final String parallelRefProcDisabledPattern =
+        " *bool +ParallelRefProcEnabled *= *false +\\{product\\}";
+
+    private static void testFlag(String[] args, boolean expectedTrue) throws Exception {
+        ArrayList<String> result = new ArrayList<String>();
+        result.addAll(Arrays.asList(args));
+        result.add("-XX:+PrintFlagsFinal");
+        result.add("-version");
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(result.toArray(new String[0]));
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        output.shouldHaveExitValue(0);
+
+        final String expectedPattern = expectedTrue ? parallelRefProcEnabledPattern : parallelRefProcDisabledPattern;
+
+        String value = output.firstMatch(expectedPattern);
+        if (value == null) {
+            throw new RuntimeException(
+                Arrays.toString(args) + " didn't set ParallelRefProcEnabled to " + expectedTrue + " as expected");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/g1/mixedgc/TestOldGenCollectionUsage.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 TestOldGenCollectionUsage.java
+ * @bug 8195115
+ * @summary G1 Old Gen's CollectionUsage.used is zero after mixed GC which is incorrect
+ * @key gc
+ * @requires vm.gc.G1
+ * @requires vm.opt.MaxGCPauseMillis == "null"
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.management
+ * @build sun.hotspot.WhiteBox
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UseG1GC -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -verbose:gc -XX:SurvivorRatio=1 -Xmx12m -Xms12m -XX:MaxTenuringThreshold=1 -XX:InitiatingHeapOccupancyPercent=100 -XX:-G1UseAdaptiveIHOP -XX:G1MixedGCCountTarget=4 -XX:MaxGCPauseMillis=30000 -XX:G1HeapRegionSize=1m -XX:G1HeapWastePercent=0 -XX:G1MixedGCLiveThresholdPercent=100 TestOldGenCollectionUsage
+ */
+
+import jdk.test.lib.Asserts;
+import sun.hotspot.WhiteBox;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Collections;
+
+import java.lang.management.*;
+
+// 8195115 says that for the "G1 Old Gen" MemoryPool, CollectionUsage.used
+// is zero for G1 after a mixed collection, which is incorrect.
+
+public class TestOldGenCollectionUsage {
+
+    private String poolName = "G1 Old Gen";
+    private String collectorName = "G1 Young Generation";
+
+    public static void main(String [] args) throws Exception {
+        TestOldGenCollectionUsage t = new TestOldGenCollectionUsage();
+        t.run();
+    }
+
+    public TestOldGenCollectionUsage() {
+        System.out.println("Monitor G1 Old Gen pool with G1 Young Generation collector.");
+    }
+
+    public void run() {
+        // Find memory pool and collector
+        List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
+        MemoryPoolMXBean pool = null;
+        boolean foundPool = false;
+        for (int i = 0; i < pools.size(); i++) {
+            pool = pools.get(i);
+            String name = pool.getName();
+            if (name.contains(poolName)) {
+                System.out.println("Found pool: " + name);
+                foundPool = true;
+                break;
+            }
+        }
+        if (!foundPool) {
+            throw new RuntimeException(poolName + " not found, test with -XX:+UseG1GC");
+        }
+
+        List<GarbageCollectorMXBean> collectors = ManagementFactory.getGarbageCollectorMXBeans();
+        GarbageCollectorMXBean collector = null;
+        boolean foundCollector = false;
+        for (int i = 0; i < collectors.size(); i++) {
+            collector = collectors.get(i);
+            String name = collector.getName();
+            if (name.contains(collectorName)) {
+                System.out.println("Found collector: " + name);
+                foundCollector = true;
+                break;
+            }
+        }
+        if (!foundCollector) {
+            throw new RuntimeException(collectorName + " not found, test with -XX:+UseG1GC");
+        }
+
+        MixedGCProvoker gcProvoker = new MixedGCProvoker();
+        gcProvoker.allocateOldObjects();
+
+        // Verify no non-zero result was stored
+        long usage = pool.getCollectionUsage().getUsed();
+        System.out.println(poolName + ": usage after GC = " + usage);
+        if (usage > 0) {
+            throw new RuntimeException("Premature mixed collections(s)");
+        }
+
+        // Verify that collections were done
+        long collectionCount = collector.getCollectionCount();
+        System.out.println(collectorName + ": collection count = "
+                           + collectionCount);
+        long collectionTime = collector.getCollectionTime();
+        System.out.println(collectorName + ": collection time  = "
+                           + collectionTime);
+        if (collectionCount <= 0) {
+            throw new RuntimeException("Collection count <= 0");
+        }
+        if (collectionTime <= 0) {
+            throw new RuntimeException("Collector has not run");
+        }
+
+        gcProvoker.provokeMixedGC();
+
+        usage = pool.getCollectionUsage().getUsed();
+        System.out.println(poolName + ": usage after GC = " + usage);
+        if (usage <= 0) {
+            throw new RuntimeException(poolName + " found with zero usage");
+        }
+
+        long newCollectionCount = collector.getCollectionCount();
+        System.out.println(collectorName + ": collection count = "
+                           + newCollectionCount);
+        long newCollectionTime = collector.getCollectionTime();
+        System.out.println(collectorName + ": collection time  = "
+                           + newCollectionTime);
+        if (newCollectionCount <= collectionCount) {
+            throw new RuntimeException("No new collection");
+        }
+        if (newCollectionTime <= collectionTime) {
+            throw new RuntimeException("Collector has not run some more");
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    /**
+     * Utility class to guarantee a mixed GC. The class allocates several arrays and
+     * promotes them to the oldgen. After that it tries to provoke mixed GC by
+     * allocating new objects.
+     *
+     * The necessary condition for guaranteed mixed GC is running MixedGCProvoker is
+     * running in VM with the following flags: -XX:MaxTenuringThreshold=1 -Xms12M
+     * -Xmx12M -XX:G1MixedGCLiveThresholdPercent=100 -XX:G1HeapWastePercent=0
+     * -XX:G1HeapRegionSize=1m
+     */
+    public class MixedGCProvoker {
+        private final WhiteBox WB = WhiteBox.getWhiteBox();
+        private final List<byte[]> liveOldObjects = new ArrayList<>();
+        private final List<byte[]> newObjects = new ArrayList<>();
+
+        public static final int ALLOCATION_SIZE = 20000;
+        public static final int ALLOCATION_COUNT = 15;
+
+        public void allocateOldObjects() {
+            List<byte[]> deadOldObjects = new ArrayList<>();
+            // Allocates buffer and promotes it to the old gen. Mix live and dead old
+            // objects
+            for (int i = 0; i < ALLOCATION_COUNT; ++i) {
+                liveOldObjects.add(new byte[ALLOCATION_SIZE * 5]);
+                deadOldObjects.add(new byte[ALLOCATION_SIZE * 5]);
+            }
+
+            // Do two young collections, MaxTenuringThreshold=1 will force promotion.
+            // G1HeapRegionSize=1m guarantees that old gen regions will be filled.
+            WB.youngGC();
+            WB.youngGC();
+            // Check it is promoted & keep alive
+            Asserts.assertTrue(WB.isObjectInOldGen(liveOldObjects),
+                               "List of the objects is suppose to be in OldGen");
+            Asserts.assertTrue(WB.isObjectInOldGen(deadOldObjects),
+                               "List of the objects is suppose to be in OldGen");
+        }
+
+        /**
+         * Waits until Concurent Mark Cycle finishes
+         * @param wb  Whitebox instance
+         * @param sleepTime sleep time
+         */
+        private void waitTillCMCFinished(int sleepTime) {
+            while (WB.g1InConcurrentMark()) {
+                if (sleepTime > -1) {
+                    try {
+                        Thread.sleep(sleepTime);
+                    } catch (InterruptedException e) {
+                        System.out.println("Got InterruptedException while waiting for ConcMarkCycle to finish");
+                    }
+                }
+            }
+        }
+
+        public void provokeMixedGC() {
+            waitTillCMCFinished(0);
+            WB.g1StartConcMarkCycle();
+            waitTillCMCFinished(0);
+            WB.youngGC();
+
+            System.out.println("Allocating new objects to provoke mixed GC");
+            // Provoke a mixed collection. G1MixedGCLiveThresholdPercent=100
+            // guarantees that full old gen regions will be included.
+            for (int i = 0; i < (ALLOCATION_COUNT * 20); i++) {
+                newObjects.add(new byte[ALLOCATION_SIZE]);
+            }
+            // check that liveOldObjects still alive
+            Asserts.assertTrue(WB.isObjectInOldGen(liveOldObjects),
+                               "List of the objects is suppose to be in OldGen");
+        }
+
+    }
+
+}
--- a/test/hotspot/jtreg/gc/logging/TestPrintReferences.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/gc/logging/TestPrintReferences.java	Tue Jun 19 16:33:07 2018 +0100
@@ -41,183 +41,209 @@
 import java.util.regex.Matcher;
 
 public class TestPrintReferences {
-  static String output;
-  static final String doubleRegex = "[0-9]+[.,][0-9]+";
-  static final String referenceProcessing = "Reference Processing";
-  static final String softReference = "SoftReference";
-  static final String weakReference = "WeakReference";
-  static final String finalReference = "FinalReference";
-  static final String phantomReference = "PhantomReference";
-  static final String phase1 = "Phase1";
-  static final String phase2 = "Phase2";
-  static final String phase3 = "Phase3";
-  static final String gcLogTimeRegex = ".* GC\\([0-9]+\\) ";
+    static String output;
+    static final String doubleRegex = "[0-9]+[.,][0-9]+";
+    static final String referenceProcessing = "Reference Processing";
+    static final String softReference = "SoftReference";
+    static final String weakReference = "WeakReference";
+    static final String finalReference = "FinalReference";
+    static final String phantomReference = "PhantomReference";
 
-  public static void main(String[] args) throws Exception {
-    test(true);
-    test(false);
-  }
+    static final String phaseReconsiderSoftReferences = "Reconsider SoftReferences";
+    static final String phaseNotifySoftWeakReferences = "Notify Soft/WeakReferences";
+    static final String phaseNotifyKeepAliveFinalizer = "Notify and keep alive finalizable";
+    static final String phaseNotifyPhantomReferences  = "Notify PhantomReferences";
+
+    static final String phase1 = "Phase1";
+    static final String phase2 = "Phase2";
+    static final String phase3 = "Phase3";
+    static final String gcLogTimeRegex = ".* GC\\([0-9]+\\) ";
 
-  static String indent(int count) {
-    return " {" + count + "}";
-  }
+    public static void main(String[] args) throws Exception {
+        testPhases(true);
+        testPhases(false);
+        testRefs();
+    }
+
+    static String indent(int count) {
+        return " {" + count + "}";
+    }
 
-  public static void test(boolean parallelRefProcEnabled) throws Exception {
-    ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+phases+ref=debug",
-                                                                      "-XX:+UseG1GC",
-                                                                      "-Xmx32M",
-                                                                      // Explicit thread setting is required to avoid using only 1 thread
-                                                                      "-XX:" + (parallelRefProcEnabled ? "+" : "-") + "ParallelRefProcEnabled",
-                                                                      "-XX:ParallelGCThreads=2",
-                                                                      GCTest.class.getName());
-    OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start());
+    public static void testRefs() throws Exception {
+        ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+ref+phases=debug",
+                                                                          "-XX:+UseG1GC",
+                                                                          "-Xmx32M",
+                                                                          GCTest.class.getName());
+        OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start());
 
-    checkLogFormat(output, parallelRefProcEnabled);
-    checkLogValue(output);
+        checkRefsLogFormat(output);
 
-    output.shouldHaveExitValue(0);
-  }
+        output.shouldHaveExitValue(0);
+    }
 
-  // Find the first Reference Processing log and check its format.
-  public static void checkLogFormat(OutputAnalyzer output, boolean parallelRefProcEnabled) {
-    String countRegex = "[0-9]+";
-    String timeRegex = doubleRegex + "ms";
-    String totalRegex = gcLogTimeRegex + indent(4) + referenceProcessing + ": " + timeRegex + "\n";
-    String balanceRegex = parallelRefProcEnabled ? gcLogTimeRegex + indent(8) + "Balance queues: " + timeRegex + "\n" : "";
-    String softRefRegex = gcLogTimeRegex + indent(6) + softReference + ": " + timeRegex + "\n";
-    String weakRefRegex = gcLogTimeRegex + indent(6) + weakReference + ": " + timeRegex + "\n";
-    String finalRefRegex = gcLogTimeRegex + indent(6) + finalReference + ": " + timeRegex + "\n";
-    String phantomRefRegex = gcLogTimeRegex + indent(6) + phantomReference + ": " + timeRegex + "\n";
-    String refDetailRegex = gcLogTimeRegex + indent(8) + phase2 + ": " + timeRegex + "\n" +
-                            gcLogTimeRegex + indent(8) + phase3 + ": " + timeRegex + "\n" +
-                            gcLogTimeRegex + indent(8) + "Discovered: " + countRegex + "\n" +
-                            gcLogTimeRegex + indent(8) + "Cleared: " + countRegex + "\n";
-    String softRefDetailRegex = gcLogTimeRegex + indent(8) + phase1 + ": " + timeRegex + "\n" + refDetailRegex;
+    private static String refRegex(String reftype) {
+        String countRegex = "[0-9]+";
+        return gcLogTimeRegex + indent(6) + reftype + ":\n" +
+               gcLogTimeRegex + indent(8) + "Discovered: " + countRegex + "\n" +
+               gcLogTimeRegex + indent(8) + "Cleared: " + countRegex + "\n";
+    }
+
+    private static void checkRefsLogFormat(OutputAnalyzer output) {
+        output.shouldMatch(refRegex("SoftReference") +
+                           refRegex("WeakReference") +
+                           refRegex("FinalReference") +
+                           refRegex("PhantomReference"));
+    }
 
-    output.shouldMatch(/* Total Reference processing time */
-                       totalRegex +
-                       /* SoftReference processing */
-                       softRefRegex + balanceRegex + softRefDetailRegex +
-                       /* WeakReference processing */
-                       weakRefRegex + balanceRegex + refDetailRegex +
-                       /* FinalReference processing */
-                       finalRefRegex + balanceRegex + refDetailRegex +
-                       /* PhantomReference processing */
-                       phantomRefRegex + balanceRegex + refDetailRegex
-                       );
-  }
+    public static void testPhases(boolean parallelRefProcEnabled) throws Exception {
+        ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+phases+ref=debug",
+                                                                          "-XX:+UseG1GC",
+                                                                          "-Xmx32M",
+                                                                          "-XX:" + (parallelRefProcEnabled ? "+" : "-") + "ParallelRefProcEnabled",
+                                                                          "-XX:-UseDynamicNumberOfGCThreads",
+                                                                          "-XX:ParallelGCThreads=2",
+                                                                          GCTest.class.getName());
+        OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start());
+
+        checkLogFormat(output, parallelRefProcEnabled);
+        checkLogValue(output);
+
+        output.shouldHaveExitValue(0);
+    }
 
-  // After getting time value, update 'output' for next use.
-  public static BigDecimal getTimeValue(String name, int indentCount) {
-    // Pattern of 'name', 'value' and some extra strings.
-    String patternString = gcLogTimeRegex + indent(indentCount) + name + ": " + "(" + doubleRegex + ")";
-    Matcher m = Pattern.compile(patternString).matcher(output);
-     if (!m.find()) {
-      throw new RuntimeException("Could not find time log for " + patternString);
-     }
+    private static String phaseRegex(String phaseName) {
+        final String timeRegex = doubleRegex + "ms";
+        return indent(6) + phaseName + ": " + timeRegex + "\n";
+    }
 
-    String match = m.group();
-    String value = m.group(1);
-
-    double result = Double.parseDouble(value);
-
-    int index = output.indexOf(match);
-    if (index != -1) {
-      output = output.substring(index, output.length());
+    private static String subphaseRegex(String subphaseName, boolean parallelRefProcEnabled) {
+        final String timeRegex = "\\s+" + doubleRegex;
+        if (parallelRefProcEnabled) {
+            final String timeInParRegex = timeRegex +",\\s";
+            return gcLogTimeRegex + indent(8) + subphaseName +
+                   " \\(ms\\):\\s+(Min:" + timeInParRegex + "Avg:" + timeInParRegex + "Max:" + timeInParRegex + "Diff:" + timeInParRegex + "Sum:" + timeInParRegex +
+                   "Workers: [0-9]+|skipped)" + "\n";
+        } else {
+            return gcLogTimeRegex + indent(8) + subphaseName + ":(" + timeRegex + "ms|\\s+skipped)\n";
+        }
     }
 
-    // Convert to BigDecimal to control the precision of floating point arithmetic.
-    return BigDecimal.valueOf(result);
-  }
+    // Find the first Reference Processing log and check its format.
+    private static void checkLogFormat(OutputAnalyzer output, boolean parallelRefProcEnabled) {
+        String countRegex = "[0-9]+";
+        String timeRegex = doubleRegex + "ms";
 
-  // Reference log is printing 1 decimal place of elapsed time.
-  // So sum of each sub-phases could be slightly larger than the enclosing phase in some cases.
-  // e.g. If there are 3 sub-phases:
-  //      Actual value:  SoftReference(5.55) = phase1(1.85) + phase2(1.85) + phase3(1.85)
-  //      Log value:     SoftReference(5.6) = phase1(1.9) + phase2(1.9) + phase3(1.9)
-  //      When checked:  5.6 < 5.7 (sum of phase1~3)
-  // Because of this we need method to verify that our measurements and calculations are valid.
-  public static boolean greaterThanOrApproximatelyEqual(BigDecimal phaseTime, BigDecimal sumOfSubPhasesTime, BigDecimal tolerance) {
-    if (phaseTime.compareTo(sumOfSubPhasesTime) >= 0) {
-      // phaseTime is greater than or equal.
-      return true;
-    }
+        /* Total Reference processing time */
+        String totalRegex = gcLogTimeRegex + indent(4) + referenceProcessing + ": " + timeRegex + "\n";
+
+        String balanceRegex = parallelRefProcEnabled ? "(" + gcLogTimeRegex + indent(8) + "Balance queues: " + timeRegex + "\n)??" : "";
+
+        final boolean p = parallelRefProcEnabled;
 
-    BigDecimal diff = sumOfSubPhasesTime.subtract(phaseTime);
-    if (diff.compareTo(tolerance) <= 0) {
-      // Difference is within tolerance, so approximately equal.
-      return true;
-    }
-
-    // sumOfSubPhasesTime is greater than phaseTime and not within tolerance.
-    return false;
-  }
+        String phase1Regex = gcLogTimeRegex + phaseRegex(phaseReconsiderSoftReferences) + balanceRegex + subphaseRegex("SoftRef", p);
+        String phase2Regex = gcLogTimeRegex + phaseRegex(phaseNotifySoftWeakReferences) +
+                             balanceRegex +
+                             subphaseRegex("SoftRef", p) +
+                             subphaseRegex("WeakRef", p) +
+                             subphaseRegex("FinalRef", p) +
+                             subphaseRegex("Total", p);
+        String phase3Regex = gcLogTimeRegex + phaseRegex(phaseNotifyKeepAliveFinalizer) + balanceRegex + subphaseRegex("FinalRef", p);
+        String phase4Regex = gcLogTimeRegex + phaseRegex(phaseNotifyPhantomReferences) + balanceRegex + subphaseRegex("PhantomRef", p);
 
-  public static BigDecimal checkPhaseTime(String refType) {
-    BigDecimal phaseTime = getTimeValue(refType, 2);
-    BigDecimal sumOfSubPhasesTime = BigDecimal.valueOf(0.0);
-
-    if (softReference.equals(refType)) {
-      sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phase1, 4));
-    }
-    sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phase2, 4));
-    sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phase3, 4));
-
-    // If there are 3 sub-phases, we should allow 0.1 tolerance.
-    final BigDecimal toleranceFor3SubPhases = BigDecimal.valueOf(0.1);
-    if (!greaterThanOrApproximatelyEqual(phaseTime, sumOfSubPhasesTime, toleranceFor3SubPhases)) {
-      throw new RuntimeException(refType +" time(" + phaseTime +
-                                 "ms) is less than the sum(" + sumOfSubPhasesTime + "ms) of each phases");
+        output.shouldMatch(totalRegex +
+                           phase1Regex +
+                           phase2Regex +
+                           phase3Regex +
+                           phase4Regex);
     }
 
-    return phaseTime;
-  }
+    // After getting time value, update 'output' for next use.
+    private static BigDecimal getTimeValue(String name, int indentCount) {
+        // Pattern of 'name', 'value' and some extra strings.
+        String patternString = gcLogTimeRegex + indent(indentCount) + name + ": " + "(" + doubleRegex + ")";
+        Matcher m = Pattern.compile(patternString).matcher(output);
+        if (!m.find()) {
+            throw new RuntimeException("Could not find time log for " + patternString);
+        }
 
-  // Find the first concurrent Reference Processing log and compare phase time vs. sum of sub-phases.
-  public static void checkLogValue(OutputAnalyzer out) {
-    output = out.getStdout();
+        String match = m.group();
+        String value = m.group(1);
+
+        double result = Double.parseDouble(value);
+
+        int index = output.indexOf(match);
+        if (index != -1) {
+            output = output.substring(index, output.length());
+        }
 
-    String patternString = gcLogTimeRegex + indent(0) +
-                           referenceProcessing + ": " + "[0-9]+[.,][0-9]+";
-    Matcher m = Pattern.compile(patternString).matcher(output);
-    if (m.find()) {
-        int start = m.start();
-        int end = output.length();
-        // If there's another concurrent Reference Processing log, ignore it.
-        if (m.find()) {
-            end = m.start();
+        // Convert to BigDecimal to control the precision of floating point arithmetic.
+        return BigDecimal.valueOf(result);
+   }
+
+    // Reference log is printing 1 decimal place of elapsed time.
+    // So sum of each sub-phases could be slightly larger than the enclosing phase in some cases.
+    // Because of this we need method to verify that our measurements and calculations are valid.
+    private static boolean greaterThanOrApproximatelyEqual(BigDecimal phaseTime, BigDecimal sumOfSubPhasesTime, BigDecimal tolerance) {
+        if (phaseTime.compareTo(sumOfSubPhasesTime) >= 0) {
+            // phaseTime is greater than or equal.
+            return true;
         }
-        if (start != -1) {
-            output = output.substring(start, end);
-            checkTrimmedLogValue();
+
+        BigDecimal diff = sumOfSubPhasesTime.subtract(phaseTime);
+        if (diff.compareTo(tolerance) <= 0) {
+            // Difference is within tolerance, so approximately equal.
+            return true;
         }
-     }
-  }
+
+        // sumOfSubPhasesTime is greater than phaseTime and not within tolerance.
+        return false;
+    }
 
-  public static void checkTrimmedLogValue() {
-    BigDecimal refProcTime = getTimeValue(referenceProcessing, 0);
+    // Find the first concurrent Reference Processing log and compare phase time vs. sum of sub-phases.
+    public static void checkLogValue(OutputAnalyzer out) {
+        output = out.getStdout();
 
-    BigDecimal sumOfSubPhasesTime = checkPhaseTime(softReference);
-    sumOfSubPhasesTime = sumOfSubPhasesTime.add(checkPhaseTime(weakReference));
-    sumOfSubPhasesTime = sumOfSubPhasesTime.add(checkPhaseTime(finalReference));
-    sumOfSubPhasesTime = sumOfSubPhasesTime.add(checkPhaseTime(phantomReference));
-
-    // If there are 4 sub-phases, we should allow 0.2 tolerance.
-    final BigDecimal toleranceFor4SubPhases = BigDecimal.valueOf(0.2);
-    if (!greaterThanOrApproximatelyEqual(refProcTime, sumOfSubPhasesTime, toleranceFor4SubPhases)) {
-      throw new RuntimeException("Reference Processing time(" + refProcTime + "ms) is less than the sum("
-                                 + sumOfSubPhasesTime + "ms) of each phases");
+        String patternString = gcLogTimeRegex + indent(0) +
+                               referenceProcessing + ": " + "[0-9]+[.,][0-9]+";
+        Matcher m = Pattern.compile(patternString).matcher(output);
+        if (m.find()) {
+            int start = m.start();
+            int end = output.length();
+            // If there's another concurrent Reference Processing log, ignore it.
+            if (m.find()) {
+                end = m.start();
+            }
+            if (start != -1) {
+                output = output.substring(start, end);
+                checkTrimmedLogValue();
+            }
+        }
     }
-  }
+
+    private static void checkTrimmedLogValue() {
+        BigDecimal refProcTime = getTimeValue(referenceProcessing, 0);
 
-  static class GCTest {
-    static final int SIZE = 512 * 1024;
-    static Object[] dummy = new Object[SIZE];
+        BigDecimal sumOfSubPhasesTime = getTimeValue(phaseReconsiderSoftReferences, 2);
+        sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phaseNotifySoftWeakReferences, 2));
+        sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phaseNotifyKeepAliveFinalizer, 2));
+        sumOfSubPhasesTime = sumOfSubPhasesTime.add(getTimeValue(phaseNotifyPhantomReferences, 2));
 
-    public static void main(String [] args) {
-      for (int i = 0; i < SIZE; i++) {
-        dummy[i] = new SoftReference<>(new Object());
-      }
+        // If there are 4 phases, we should allow 0.2 tolerance.
+        final BigDecimal toleranceFor4SubPhases = BigDecimal.valueOf(0.2);
+        if (!greaterThanOrApproximatelyEqual(refProcTime, sumOfSubPhasesTime, toleranceFor4SubPhases)) {
+            throw new RuntimeException("Reference Processing time(" + refProcTime + "ms) is less than the sum("
+                                       + sumOfSubPhasesTime + "ms) of each phases");
+        }
     }
-  }
+
+    static class GCTest {
+        static final int SIZE = 512 * 1024;
+        static Object[] dummy = new Object[SIZE];
+
+        public static void main(String [] args) {
+             for (int i = 0; i < SIZE; i++) {
+                  dummy[i] = new SoftReference<>(new Object());
+             }
+        }
+    }
 }
--- a/test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithZ.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithZ.java	Tue Jun 19 16:33:07 2018 +0100
@@ -28,7 +28,7 @@
  * @test TestGCBasherWithZ
  * @key gc stress
  * @requires vm.gc.Z
- * @requires vm.flavor == "server" & !vm.emulatedClient
+ * @requires vm.flavor == "server" & !vm.emulatedClient & !vm.graal.enabled
  * @summary Stress ZGC
  * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx384m -server -XX:+UnlockExperimentalVMOptions -XX:+UseZGC TestGCBasherWithZ 120000
  */
--- a/test/hotspot/jtreg/gc/stress/gcold/TestGCOldWithZ.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/gc/stress/gcold/TestGCOldWithZ.java	Tue Jun 19 16:33:07 2018 +0100
@@ -25,7 +25,7 @@
 /*
  * @test TestGCOldWithZ
  * @key gc
- * @requires vm.gc.Z
+ * @requires vm.gc.Z & !vm.graal.enabled
  * @summary Stress the Z
  * @run main/othervm -Xmx384M -XX:+UnlockExperimentalVMOptions -XX:+UseZGC TestGCOldWithZ 50 1 20 10 10000
  * @run main/othervm -Xmx256m -XX:+UnlockExperimentalVMOptions -XX:+UseZGC TestGCOldWithZ 50 5 20 1 5000
--- a/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,21 +1,3 @@
-import static java.io.File.createTempFile;
-import static java.lang.Long.parseLong;
-import static java.lang.System.getProperty;
-import static java.nio.file.Files.readAllBytes;
-import static java.util.Arrays.stream;
-import static java.util.stream.Collectors.joining;
-import static java.util.stream.Collectors.toList;
-import static jdk.test.lib.process.ProcessTools.createJavaProcessBuilder;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.Collection;
-import java.util.stream.Stream;
-
 /*
  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -39,6 +21,26 @@
  * questions.
  */
 
+import static java.io.File.createTempFile;
+import static java.lang.Long.parseLong;
+import static java.lang.System.getProperty;
+import static java.nio.file.Files.readAllBytes;
+import static java.util.Arrays.stream;
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toList;
+import static jdk.test.lib.process.ProcessTools.createJavaProcessBuilder;
+import static jdk.test.lib.Platform.isWindows;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Collection;
+import java.util.Optional;
+import java.util.stream.Stream;
+
 /*
  * @test TestInheritFD
  * @bug 8176717 8176809
@@ -78,6 +80,12 @@
         String logPath = createTempFile("logging", LOG_SUFFIX).getName();
         File commFile = createTempFile("communication", ".txt");
 
+        if (!isWindows() && !lsofCommand().isPresent()) {
+            System.out.println("Could not find lsof like command");
+            System.out.println("Exit test case as successful though it could not verify anything");
+            return;
+        }
+
         ProcessBuilder pb = createJavaProcessBuilder(
             "-Xlog:gc:\"" + logPath + "\"",
             "-Dtest.jdk=" + getProperty("test.jdk"),
@@ -113,7 +121,7 @@
             pb.inheritIO(); // in future, redirect information from third VM to first VM
             pb.start();
 
-            if (getProperty("os.name").toLowerCase().contains("win") == false) {
+            if (!isWindows()) {
                 System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames().stream().collect(joining("\n")));
             }
         }
@@ -127,7 +135,7 @@
                 long parentPid = parseLong(args[1]);
                 fakeLeakyJVM(false); // for debugging of test case
 
-                if (getProperty("os.name").toLowerCase().contains("win")) {
+                if (isWindows()) {
                     windows(logFile, parentPid);
                 } else {
                     Collection<String> output = outputContainingFilenames();
@@ -161,19 +169,24 @@
         }
     }
 
+    static Optional<String[]> lsofCommandCache = stream(new String[][]{
+            {"/usr/bin/lsof", "-p"},
+            {"/usr/sbin/lsof", "-p"},
+            {"/bin/lsof", "-p"},
+            {"/sbin/lsof", "-p"},
+            {"/usr/local/bin/lsof", "-p"},
+            {"/usr/bin/pfiles", "-F"}}) // Solaris
+        .filter(args -> new File(args[0]).exists())
+        .findFirst();
+
+    static Optional<String[]> lsofCommand() {
+        return lsofCommandCache;
+    }
+
     static Collection<String> outputContainingFilenames() {
         long pid = ProcessHandle.current().pid();
-        String[] command = stream(new String[][]{
-                {"/usr/bin/lsof", "-p"},
-                {"/usr/sbin/lsof", "-p"},
-                {"/bin/lsof", "-p"},
-                {"/sbin/lsof", "-p"},
-                {"/usr/local/bin/lsof", "-p"},
-                {"/usr/bin/pfiles", "-F"}}) // Solaris
-            .filter(args -> new File(args[0]).exists())
-            .findFirst()
-            .orElseThrow(() -> new RuntimeException("could not find lsof-like command"));
 
+        String[] command = lsofCommand().orElseThrow(() -> new RuntimeException("lsof like command not found"));
         System.out.println("using command: " + command[0] + " " + command[1]);
         return run(command[0], command[1], "" + pid).collect(toList());
     }
@@ -191,4 +204,5 @@
         System.out.println("trying to rename file to the same name: " + f);
         System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD); // this parts communicates a closed file descriptor by printing "VM RESULT => RETAINS FD"
     }
-}
\ No newline at end of file
+}
+
--- a/test/hotspot/jtreg/runtime/LoaderConstraints/differentLE/Test.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/LoaderConstraints/differentLE/Test.java	Tue Jun 19 16:33:07 2018 +0100
@@ -75,11 +75,13 @@
     // Then it loads the D2 variant of D from the current working directory and it's
     // superclass C. This fails as D1 is already loaded with the same superclass.
 
-    static String expectedErrorMessage =
-        "loader constraint violation: loader \"<unnamed>\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) wants to load " +
+    // Break the expectedErrorMessage into 2 pieces since the loader name will include
+    // its identity hash and can not be compared against.
+    static String expectedErrorMessage_part1 = "loader constraint violation: loader PreemptingClassLoader @";
+    static String expectedErrorMessage_part2 = " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) wants to load " +
         "class test.D_ambgs. A different class with the same name was previously loaded " +
-        "by \"app\" (instance of jdk.internal.loader.ClassLoaders$AppClassLoader).";
+        "by 'app' (instance of jdk.internal.loader.ClassLoaders$AppClassLoader).";
 
     public static void test_access() throws Exception {
         try {
@@ -101,8 +103,9 @@
             throw new RuntimeException("Expected LinkageError was not thrown.");
         } catch (LinkageError jle) {
             String errorMsg = jle.getMessage();
-            if (!errorMsg.equals(expectedErrorMessage)) {
-                System.out.println("Expected: " + expectedErrorMessage + "\n" +
+            if (!errorMsg.contains(expectedErrorMessage_part1) ||
+                !errorMsg.contains(expectedErrorMessage_part2)) {
+                System.out.println("Expected: " + expectedErrorMessage_part1 + "<id>" + expectedErrorMessage_part2 + "\n" +
                                    "but got:  " + errorMsg);
                 throw new RuntimeException("Wrong error message of LinkageError.");
             } else {
--- a/test/hotspot/jtreg/runtime/LoaderConstraints/duplicateLE/Test.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/LoaderConstraints/duplicateLE/Test.java	Tue Jun 19 16:33:07 2018 +0100
@@ -37,23 +37,28 @@
 
     // Check that all names have external formatting ('.' and not '/' in package names).
     // Check for parent of class loader.
-    static String expectedErrorMessage1 =
-        "loader \"<unnamed>\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+    // Break each expectedErrorMessage into 2 parts due to the class loader name containing
+    // the unique @<id> identity hash which cannot be compared against.
+    static String expectedErrorMessage1_part1 = "loader PreemptingClassLoader @";
+    static String expectedErrorMessage1_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "attempted duplicate class definition for test.Foo.";
 
     // Check that all names have external formatting ('.' and not '/' in package names).
     // Check for name and parent of class loader.
-    static String expectedErrorMessage2 =
-        "loader \"DuplicateLE_Test_Loader\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+    static String expectedErrorMessage2_part1 = "loader 'DuplicateLE_Test_Loader' @";
+    static String expectedErrorMessage2_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "attempted duplicate class definition for test.Foo.";
 
     // Check that all names have external formatting ('.' and not '/' in package names).
     // Check for name and parent of class loader. Type should be mentioned as 'interface'.
-    static String expectedErrorMessage3 =
-        "loader \"DuplicateLE_Test_Loader_IF\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+    static String expectedErrorMessage3_part1 = "loader 'DuplicateLE_Test_Loader_IF' @";
+    static String expectedErrorMessage3_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "attempted duplicate interface definition for test.J.";
 
     // Test that the error message is correct when a loader constraint error is
@@ -63,7 +68,8 @@
     // overrides "J.m()LFoo;".  But, Task's class Foo and super type J's class Foo
     // are different.  So, a LinkageError exception should be thrown because the
     // loader constraint check will fail.
-    public static void test(String loaderName, String expectedErrorMessage, String testType) throws Exception {
+    public static void test(String loaderName, String expectedErrorMessage_part1,
+                            String expectedErrorMessage_part2, String testType) throws Exception {
         String[] classNames = {testType};
         ClassLoader l = new PreemptingClassLoader(loaderName, classNames, false);
         l.loadClass(testType);
@@ -72,8 +78,9 @@
             throw new RuntimeException("Expected LinkageError exception not thrown");
         } catch (LinkageError e) {
             String errorMsg = e.getMessage();
-            if (!errorMsg.equals(expectedErrorMessage)) {
-                System.out.println("Expected: " + expectedErrorMessage + "\n" +
+            if (!errorMsg.contains(expectedErrorMessage_part1) ||
+                !errorMsg.contains(expectedErrorMessage_part2)) {
+                System.out.println("Expected: " + expectedErrorMessage_part1 + "<id>" + expectedErrorMessage_part2 + "\n" +
                                    "but got:  " + errorMsg);
                 throw new RuntimeException("Wrong LinkageError exception thrown: " + errorMsg);
             }
@@ -82,9 +89,9 @@
     }
 
     public static void main(String args[]) throws Exception {
-        test(null, expectedErrorMessage1, "test.Foo");
-        test("DuplicateLE_Test_Loader", expectedErrorMessage2, "test.Foo");
-        test("DuplicateLE_Test_Loader_IF", expectedErrorMessage3, "test.J");
+        test(null, expectedErrorMessage1_part1, expectedErrorMessage1_part2, "test.Foo");
+        test("DuplicateLE_Test_Loader", expectedErrorMessage2_part1, expectedErrorMessage2_part2, "test.Foo");
+        test("DuplicateLE_Test_Loader_IF", expectedErrorMessage3_part1, expectedErrorMessage3_part2, "test.J");
     }
 }
 
--- a/test/hotspot/jtreg/runtime/LoaderConstraints/itableLdrConstraint/Test.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/LoaderConstraints/itableLdrConstraint/Test.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,22 +35,28 @@
 
 public class Test {
 
-    static String expectedErrorMessage1 =
+    // Break expected error messages into 2 parts since the loader name includes its identity
+    // hash which is unique and can't be compared against.
+    static String expectedErrorMessage1_part1 =
         "loader constraint violation in interface itable initialization for class test.C: " +
         "when selecting method test.I.m()Ltest/Foo; " +
-        "the class loader \"<unnamed>\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
-        "for super interface test.I, and the class loader \"app\" " +
+        "the class loader PreemptingClassLoader @";
+    static String expectedErrorMessage1_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "for super interface test.I, and the class loader 'app' " +
         "(instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "of the selected method's type, test.J have different Class objects " +
         "for the type test.Foo used in the signature";
 
-    static String expectedErrorMessage2 =
+    static String expectedErrorMessage2_part1 =
         "loader constraint violation in interface itable initialization for class test.C: " +
         "when selecting method test.I.m()Ltest/Foo; " +
-        "the class loader \"ItableLdrCnstrnt_Test_Loader\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
-        "for super interface test.I, and the class loader \"app\" " +
+        "the class loader 'ItableLdrCnstrnt_Test_Loader' @";
+    static String expectedErrorMessage2_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "for super interface test.I, and the class loader 'app' " +
         "(instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "of the selected method's type, test.J have different Class objects " +
         "for the type test.Foo used in the signature";
@@ -63,7 +69,9 @@
     // type super interface J.  The selected method is not an overpass method nor
     // otherwise excluded from loader constraint checking.  So, a LinkageError
     // exception should be thrown because the loader constraint check will fail.
-    public static void test(String loaderName, String expectedErrorMessage) throws Exception {
+    public static void test(String loaderName,
+                            String expectedErrorMessage_part1,
+                            String expectedErrorMessage_part2) throws Exception {
         Class<?> c = test.Foo.class; // Forces standard class loader to load Foo.
         String[] classNames = {"test.Task", "test.Foo", "test.C", "test.I"};
         ClassLoader l = new PreemptingClassLoader(loaderName, classNames);
@@ -73,8 +81,9 @@
             throw new RuntimeException("Expected LinkageError exception not thrown");
         } catch (LinkageError e) {
             String errorMsg = e.getMessage();
-            if (!errorMsg.equals(expectedErrorMessage)) {
-                System.out.println("Expected: " + expectedErrorMessage + "\n" +
+            if (!errorMsg.contains(expectedErrorMessage_part1) ||
+                !errorMsg.contains(expectedErrorMessage_part2)) {
+                System.out.println("Expected: " + expectedErrorMessage_part1 + "<id>" + expectedErrorMessage_part2 + "\n" +
                                    "but got:  " + errorMsg);
                 throw new RuntimeException("Wrong LinkageError exception thrown: " + errorMsg);
             }
@@ -83,7 +92,7 @@
     }
 
     public static void main(String... args) throws Exception {
-        test(null, expectedErrorMessage1);
-        test("ItableLdrCnstrnt_Test_Loader", expectedErrorMessage2);
+        test(null, expectedErrorMessage1_part1, expectedErrorMessage1_part2);
+        test("ItableLdrCnstrnt_Test_Loader", expectedErrorMessage2_part1, expectedErrorMessage2_part2);
     }
 }
--- a/test/hotspot/jtreg/runtime/LoaderConstraints/vtableLdrConstraint/Test.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/LoaderConstraints/vtableLdrConstraint/Test.java	Tue Jun 19 16:33:07 2018 +0100
@@ -35,23 +35,29 @@
 
 public class Test {
 
-    static String expectedErrorMessage1 =
+    // Break expected error messages into 2 parts since the loader name includes its identity
+    // hash which is unique and can't be compared against.
+    static String expectedErrorMessage1_part1 =
         "loader constraint violation for class test.Task: " +
         "when selecting overriding method test.Task.m()Ltest/Foo; " +
-        "the class loader \"<unnamed>\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "the class loader PreemptingClassLoader @";
+    static String expectedErrorMessage1_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "of the selected method's type test.Task, " +
-        "and the class loader \"app\" (instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "and the class loader 'app' (instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "for its super type test.J " +
         "have different Class objects for the type test.Foo used in the signature";
 
-    static String expectedErrorMessage2 =
+    static String expectedErrorMessage2_part1 =
         "loader constraint violation for class test.Task: " +
         "when selecting overriding method test.Task.m()Ltest/Foo; " +
-        "the class loader \"VtableLdrCnstrnt_Test_Loader\" (instance of PreemptingClassLoader, " +
-        "child of \"app\" jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "the class loader 'VtableLdrCnstrnt_Test_Loader' @";
+    static String expectedErrorMessage2_part2 =
+        " (instance of PreemptingClassLoader, " +
+        "child of 'app' jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "of the selected method's type test.Task, " +
-        "and the class loader \"app\" (instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
+        "and the class loader 'app' (instance of jdk.internal.loader.ClassLoaders$AppClassLoader) " +
         "for its super type test.J " +
         "have different Class objects for the type test.Foo used in the signature";
 
@@ -62,7 +68,9 @@
     // overrides "J.m()LFoo;".  But, Task's class Foo and super type J's class Foo
     // are different.  So, a LinkageError exception should be thrown because the
     // loader constraint check will fail.
-    public static void test(String loaderName, String expectedErrorMessage) throws Exception {
+    public static void test(String loaderName,
+                            String expectedErrorMessage_part1,
+                            String expectedErrorMessage_part2) throws Exception {
         Class<?> c = test.Foo.class; // Forces standard class loader to load Foo.
         String[] classNames = {"test.Task", "test.Foo", "test.I"};
         ClassLoader l = new PreemptingClassLoader(loaderName, classNames);
@@ -72,8 +80,9 @@
             throw new RuntimeException("Expected LinkageError exception not thrown");
         } catch (LinkageError e) {
             String errorMsg = e.getMessage();
-            if (!errorMsg.equals(expectedErrorMessage)) {
-                System.out.println("Expected: " + expectedErrorMessage + "\n" +
+            if (!errorMsg.contains(expectedErrorMessage_part1) ||
+                !errorMsg.contains(expectedErrorMessage_part2)) {
+                System.out.println("Expected: " + expectedErrorMessage_part1 + "<id>" + expectedErrorMessage_part2 + "\n" +
                                    "but got:  " + errorMsg);
                 throw new RuntimeException("Wrong LinkageError exception thrown: " + errorMsg);
             }
@@ -82,8 +91,8 @@
     }
 
     public static void main(String args[]) throws Exception {
-        test(null, expectedErrorMessage1);
-        test("VtableLdrCnstrnt_Test_Loader", expectedErrorMessage2);
+        test(null, expectedErrorMessage1_part1, expectedErrorMessage1_part2);
+        test("VtableLdrCnstrnt_Test_Loader", expectedErrorMessage2_part1, expectedErrorMessage2_part2);
     }
 }
 
--- a/test/hotspot/jtreg/runtime/SharedArchiveFile/DumpSymbolAndStringTable.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/SharedArchiveFile/DumpSymbolAndStringTable.java	Tue Jun 19 16:33:07 2018 +0100
@@ -60,7 +60,7 @@
         pb.command(new String[] {JDKToolFinder.getJDKTool("jcmd"), pid, "VM.systemdictionary"});
         output = CDSTestUtils.executeAndLog(pb, "jcmd-systemdictionary");
         try {
-            output.shouldContain("System Dictionary for jdk/internal/loader/ClassLoaders$AppClassLoader statistics:");
+            output.shouldContain("System Dictionary for 'app' class loader statistics:");
             output.shouldContain("Number of buckets");
             output.shouldContain("Number of entries");
             output.shouldContain("Maximum bucket size");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/ArrayStoreException/ArrayStoreExceptionTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018 SAP SE. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @summary Test ArrayStoreException message. The message lists
+ *   information about the array types involved.
+ * @library /test/lib
+ * @run main ArrayStoreExceptionTest
+ */
+
+import java.util.Date;
+import jdk.test.lib.Asserts;
+
+/**
+ * Tests the detailed messages of the ArrayStoreException.
+ */
+public class ArrayStoreExceptionTest {
+
+    static {
+        System.loadLibrary("ArrayStoreExceptionTest");
+    }
+
+    static void testASMessages(Object from, Object to, String message) throws Exception {
+        try {
+            System.arraycopy(from, 1, to, 3, 2);
+            Asserts.fail("Expected ArrayStoreException not thrown");
+        } catch (ArrayStoreException e) {
+            Asserts.assertEquals(e.getMessage(), message);
+        }
+    }
+
+    static native void doNativeArrayStore(Object[] src, Object dst, int index);
+
+    static void testNativeASMessages(Object[] array, Object elem, int index, String message)
+        throws Exception {
+        try {
+            doNativeArrayStore(array, elem, index);
+            Asserts.fail("Expected ArrayStoreException not thrown");
+        } catch (ArrayStoreException e) {
+            Asserts.assertEquals(e.getMessage(), message);
+        }
+    }
+
+    static native void doNativeArrayStore2(Object src, Object dst, int index);
+
+    static void testNativeASMessages2(Object array, Object elem, int index, String message)
+        throws Exception {
+        try {
+            doNativeArrayStore2(array, elem, index);
+            Asserts.fail("Expected ArrayStoreException not thrown");
+        } catch (ArrayIndexOutOfBoundsException e) {
+            Asserts.assertEquals(e.getMessage(), message);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        try {
+            boolean[]    za1 = new boolean[3];
+            byte[]       ba1 = new byte[3];
+            short[]      sa1 = new short[3];
+            char[]       ca1 = new char[3];
+            int[]        ia1 = new int[3];
+            long[]       la1 = new long[3];
+            float[]      fa1 = new float[3];
+            double[]     da1 = new double[3];
+            Object[]     oa1 = new Object[3];
+
+            boolean[]    za2 = new boolean[9];
+            byte[]       ba2 = new byte[9];
+            short[]      sa2 = new short[9];
+            char[]       ca2 = new char[9];
+            int[]        ia2 = new int[9];
+            long[]       la2 = new long[9];
+            float[]      fa2 = new float[9];
+            double[]     da2 = new double[9];
+            Object[]     oa2 = new Object[9];
+
+            boolean[][]  za3 = new boolean[9][9];
+            byte[][]     ba3 = new byte[9][9];
+            short[][]    sa3 = new short[9][9];
+            char[][]     ca3 = new char[9][9];
+            int[][]      ia3 = new int[9][9];
+            long[][]     la3 = new long[9][9];
+            float[][]    fa3 = new float[9][9];
+            double[][]   da3 = new double[9][9];
+            Object[][]   oa3 = new Object[9][9];
+
+            int[][][]    ia4 = new int[9][9][9];
+            Object[][][] oa4 = new Object[9][9][9];
+
+
+            testASMessages(za1, ba2, "arraycopy: type mismatch: can not copy boolean[] into byte[]");
+            testASMessages(ba1, sa2, "arraycopy: type mismatch: can not copy byte[] into short[]");
+            testASMessages(sa1, ca2, "arraycopy: type mismatch: can not copy short[] into char[]");
+            testASMessages(ca1, ia2, "arraycopy: type mismatch: can not copy char[] into int[]");
+            testASMessages(ia1, la2, "arraycopy: type mismatch: can not copy int[] into long[]");
+            testASMessages(la1, fa2, "arraycopy: type mismatch: can not copy long[] into float[]");
+            testASMessages(fa1, da2, "arraycopy: type mismatch: can not copy float[] into double[]");
+            testASMessages(da1, oa2, "arraycopy: type mismatch: can not copy double[] into object array[]");
+            testASMessages(oa1, za2, "arraycopy: type mismatch: can not copy object array[] into boolean[]");
+
+            testASMessages(za1, oa2, "arraycopy: type mismatch: can not copy boolean[] into object array[]");
+            testASMessages(ba1, za2, "arraycopy: type mismatch: can not copy byte[] into boolean[]");
+            testASMessages(sa1, ba2, "arraycopy: type mismatch: can not copy short[] into byte[]");
+            testASMessages(ca1, sa2, "arraycopy: type mismatch: can not copy char[] into short[]");
+            testASMessages(ia1, ca2, "arraycopy: type mismatch: can not copy int[] into char[]");
+            testASMessages(la1, ia2, "arraycopy: type mismatch: can not copy long[] into int[]");
+            testASMessages(fa1, la2, "arraycopy: type mismatch: can not copy float[] into long[]");
+            testASMessages(da1, fa2, "arraycopy: type mismatch: can not copy double[] into float[]");
+            testASMessages(oa1, da2, "arraycopy: type mismatch: can not copy object array[] into double[]");
+
+            testASMessages(za3, ba2, "arraycopy: type mismatch: can not copy object array[] into byte[]");
+            testASMessages(ba3, sa2, "arraycopy: type mismatch: can not copy object array[] into short[]");
+            testASMessages(sa3, ca2, "arraycopy: type mismatch: can not copy object array[] into char[]");
+            testASMessages(ca3, ia2, "arraycopy: type mismatch: can not copy object array[] into int[]");
+            testASMessages(ia3, la2, "arraycopy: type mismatch: can not copy object array[] into long[]");
+            testASMessages(la3, fa2, "arraycopy: type mismatch: can not copy object array[] into float[]");
+            testASMessages(fa3, da2, "arraycopy: type mismatch: can not copy object array[] into double[]");
+            testASMessages(oa3, za2, "arraycopy: type mismatch: can not copy object array[] into boolean[]");
+
+            testASMessages(za1, oa3, "arraycopy: type mismatch: can not copy boolean[] into object array[]");
+            testASMessages(ba1, za3, "arraycopy: type mismatch: can not copy byte[] into object array[]");
+            testASMessages(sa1, ba3, "arraycopy: type mismatch: can not copy short[] into object array[]");
+            testASMessages(ca1, sa3, "arraycopy: type mismatch: can not copy char[] into object array[]");
+            testASMessages(ia1, ca3, "arraycopy: type mismatch: can not copy int[] into object array[]");
+            testASMessages(la1, ia3, "arraycopy: type mismatch: can not copy long[] into object array[]");
+            testASMessages(fa1, la3, "arraycopy: type mismatch: can not copy float[] into object array[]");
+            testASMessages(da1, fa3, "arraycopy: type mismatch: can not copy double[] into object array[]");
+
+            //testASMessages(null, ba2,  "arraycopy: type mismatch: can not copy boolean[] into byte[]"); NPE
+            //testASMessages(za1,  null, "arraycopy: type mismatch: can not copy boolean[] into byte[]"); NPE
+            testASMessages("This is not an array", ia2, "arraycopy: source type java.lang.String is not an array");
+            testASMessages(la1, "This is not an array", "arraycopy: destination type java.lang.String is not an array");
+
+            //testASMessages(null, oa2,  "arraycopy: type mismatch: can not copy boolean[] into byte[]"); NPE
+            //testASMessages(oa1,  null, "arraycopy: type mismatch: can not copy boolean[] into byte[]"); NPE
+            testASMessages("This is not an array", oa2, "arraycopy: source type java.lang.String is not an array");
+            testASMessages(oa1, "This is not an array", "arraycopy: destination type java.lang.String is not an array");
+
+            String[] Sa1 = new String[3];
+            Date[]   Da1 = new Date[3];
+            String[] Sa2 = new String[9];
+            Date[]   Da2 = new Date[9];
+
+            for (int i = 0; i < 3; i++) {
+                Sa1[i] = "" + i;
+                oa1[i] = "" + i;
+            }
+            testASMessages(Sa1, Da2,
+                           "arraycopy: type mismatch: can not copy java.lang.String[] " +
+                           "into java.util.Date[]");
+            testASMessages(oa1, Da2,
+                           "arraycopy: element type mismatch: can not cast one of the " +
+                           "elements of java.lang.Object[] to the type of the destination " +
+                           "array, java.util.Date");
+
+            // These should succeed.
+            doNativeArrayStore(Sa1, "This is a string", 0);
+            doNativeArrayStore(oa1, "This is a string", 2);
+
+            testNativeASMessages(Da1, "This is not a date", 0,
+                                 "type mismatch: can not store java.lang.String to java.util.Date[0]");
+            testNativeASMessages(Da1, "This is not a date", 2,
+                                 "type mismatch: can not store java.lang.String to java.util.Date[2]");
+            testNativeASMessages(oa3, "This is not a date", 2,
+                                 "type mismatch: can not store java.lang.String to java.lang.Object[2][]");
+            testNativeASMessages(oa4, "This is not a date", 1,
+                                 "type mismatch: can not store java.lang.String to java.lang.Object[1][][]");
+            testNativeASMessages(ia3, "This is not a date", 1,
+                                 "type mismatch: can not store java.lang.String to int[1][]");
+            testNativeASMessages(ia4, "This is not a date", 2,
+                                 "type mismatch: can not store java.lang.String to int[2][][]");
+
+            testNativeASMessages2("This is not an array", "This is not a date", 2, "2");
+
+        } catch (java.lang.RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            e.printStackTrace();
+            Asserts.fail("Wrong exception thrown: " + e);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/ArrayStoreException/libArrayStoreExceptionTest.c	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018 SAP SE. All rights reserved.
+ * 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.
+ */
+
+#include <jni.h>
+
+JNIEXPORT void JNICALL
+  Java_ArrayStoreExceptionTest_doNativeArrayStore(JNIEnv *env, jclass klass,
+                                                  jobjectArray array, jobject element, jint index) {
+  (*env)->SetObjectArrayElement(env, array, index, element);
+}
+
+JNIEXPORT void JNICALL
+  Java_ArrayStoreExceptionTest_doNativeArrayStore2(JNIEnv *env, jclass klass,
+                                                   jobject array, jobject element, jint index) {
+  (*env)->SetObjectArrayElement(env, (jobjectArray)array, index, element);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ICC2_B.jasm	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018 SAP SE. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test;
+
+class ICC2_B implements ICC2_iA {
+
+    public Method "<init>":"()V"
+        stack 1 locals 1
+    {
+        aload_0;
+        invokespecial Method java/lang/Object."<init>":"()V";
+        return;
+    }
+
+  public Method a:"()V"
+        stack 2 locals 1
+    {
+        getstatic     Field java/lang/System.out:"Ljava/io/PrintStream;";
+        ldc           String "test.B.a()";
+        invokevirtual Method java/io/PrintStream.print:"(Ljava/lang/String;)V";
+        return;
+    }
+
+  public Method b:"()V"
+        stack 2 locals 1
+    {
+        getstatic     Field java/lang/System.out:"Ljava/io/PrintStream;";
+        ldc           String "test.B.b()";
+        invokevirtual Method java/io/PrintStream.print:"(Ljava/lang/String;)V";
+        return;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ICC3_B.jasm	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018 SAP SE. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test;
+
+// Erroneous class: ICC3_A is not an interface but a class.
+class ICC3_B implements ICC3_A {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ICC4_B.jasm	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018 SAP SE. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package test;
+
+// Erroneous class: ICC3_iA is not a class but an interface.
+class ICC4_B extends ICC4_iA {
+}
--- a/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ICC_B.jasm	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2018 SAP SE. All rights reserved.
- * 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.
- */
-
-class ICC_B implements ICC_iA {
-
-    public Method "<init>":"()V"
-        stack 1 locals 1
-    {
-        aload_0;
-        invokespecial Method java/lang/Object."<init>":"()V";
-        return;
-    }
-
-  public Method a:"()V"
-        stack 2 locals 1
-    {
-        getstatic     Field java/lang/System.out:"Ljava/io/PrintStream;";
-        ldc           String "B.a()";
-        invokevirtual Method java/io/PrintStream.print:"(Ljava/lang/String;)V";
-        return;
-    }
-
-  public Method b:"()V"
-        stack 2 locals 1
-    {
-        getstatic     Field java/lang/System.out:"Ljava/io/PrintStream;";
-        ldc           String "B.b()";
-        invokevirtual Method java/io/PrintStream.print:"(Ljava/lang/String;)V";
-        return;
-    }
-}
--- a/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ImplementsSomeInterfaces.jasm	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/ImplementsSomeInterfaces.jasm	Tue Jun 19 16:33:07 2018 +0100
@@ -22,9 +22,7 @@
  * questions.
  */
 
-
-
-
+package test;
 
 class ImplementsSomeInterfaces extends AbstractICCE0 {
 
@@ -32,7 +30,7 @@
         stack 1 locals 1
     {
         aload_0;
-        invokespecial Method AbstractICCE0."<init>":"()V";
+        invokespecial Method test/AbstractICCE0."<init>":"()V";
         return;
     }
 
--- a/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/IncompatibleClassChangeErrorTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/exceptionMsgs/IncompatibleClassChangeError/IncompatibleClassChangeErrorTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -31,18 +31,20 @@
  * @build sun.hotspot.WhiteBox
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
  * @compile IncompatibleClassChangeErrorTest.java
- * @compile ImplementsSomeInterfaces.jasm ICC_B.jasm
+ * @compile ImplementsSomeInterfaces.jasm ICC2_B.jasm ICC3_B.jasm ICC4_B.jasm
  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  *                   -XX:CompileThreshold=1000 -XX:-BackgroundCompilation -XX:-Inline
- *                   -XX:CompileCommand=exclude,IncompatibleClassChangeErrorTest::test_iccInt
- *                   IncompatibleClassChangeErrorTest
+ *                   -XX:CompileCommand=exclude,test.IncompatibleClassChangeErrorTest::test_iccInt
+ *                   test.IncompatibleClassChangeErrorTest
  */
 
+package test;
+
 import sun.hotspot.WhiteBox;
 import compiler.whitebox.CompilerWhiteBoxTest;
 import java.lang.reflect.Method;
 
-// This test assembles an errorneous installation of classes.
+// This test assembles an erroneous installation of classes.
 // First, compile the test by @compile. This results in a legal set
 // of classes.
 // Then, with jasm, generate incompatible classes that overwrite
@@ -56,10 +58,10 @@
     private static boolean enableChecks = true;
 
     private static String expectedErrorMessageInterpreted =
-        "Class ImplementsSomeInterfaces " +
-        "does not implement the requested interface InterfaceICCE1";
+        "Class test.ImplementsSomeInterfaces " +
+        "does not implement the requested interface test.InterfaceICCE1";
     private static String expectedErrorMessageCompiled =
-        "Class ICC_B does not implement the requested interface ICC_iB";
+        "Class test.ICC2_B does not implement the requested interface test.ICC2_iB";
         // old message: "vtable stub"
 
 
@@ -93,9 +95,9 @@
 
         // Compile
         if (!compile(IncompatibleClassChangeErrorTest.class, "test_icc_compiled_itable_stub") ||
-            !compile(ICC_C.class, "b") ||
-            !compile(ICC_D.class, "b") ||
-            !compile(ICC_E.class, "b")) {
+            !compile(ICC2_C.class, "b") ||
+            !compile(ICC2_D.class, "b") ||
+            !compile(ICC2_E.class, "b")) {
           return false;
         }
 
@@ -119,6 +121,9 @@
                                    "but got:  " + errorMsg);
                 throw new RuntimeException("Wrong error message of IncompatibleClassChangeError.");
             }
+            if (enableChecks) {
+                System.out.println("Test 1 passed with message: " + errorMsg);
+            }
             caught_icc = true;
         } catch (Throwable e) {
             throw new RuntimeException("Caught unexpected exception: " + e);
@@ -142,10 +147,10 @@
     public static void test_icc_compiled_itable_stub() {
         // Allocated the objects we need and call a valid method.
         boolean caught_icc = false;
-        ICC_B b = new ICC_B();
-        ICC_C c = new ICC_C();
-        ICC_D d = new ICC_D();
-        ICC_E e = new ICC_E();
+        ICC2_B b = new ICC2_B();
+        ICC2_C c = new ICC2_C();
+        ICC2_D d = new ICC2_D();
+        ICC2_E e = new ICC2_E();
         b.a();
         c.a();
         d.a();
@@ -155,7 +160,7 @@
             final int iterations = 10;
             // Test: calls b.b() in the last iteration.
             for (int i = 0; i < iterations; i++) {
-                ICC_iB a = b;
+                ICC2_iB a = b;
                 if (i % 3 == 0 && i < iterations - 1) {
                     a = c;
                 }
@@ -194,7 +199,7 @@
                 throw new RuntimeException("Wrong error message of IncompatibleClassChangeError.");
             }
             if (enableChecks) {
-                System.out.println("Passed with message: " + errorMsg);
+                System.out.println("Test 2 passed with message: " + errorMsg);
             }
         } catch (Throwable exc) {
             throw exc; // new RuntimeException("Caught unexpected exception: " + exc);
@@ -206,12 +211,54 @@
         }
     }
 
+    private static String expectedErrorMessage3 =
+        "Class test.ICC3_B can not implement test.ICC3_A, because it is not an interface";
+
+    public static void test3_implementsClass() throws Exception {
+        try {
+            new ICC3_B();
+            throw new RuntimeException("Expected IncompatibleClassChangeError was not thrown.");
+        } catch (IncompatibleClassChangeError e) {
+            String errorMsg = e.getMessage();
+            if (!errorMsg.equals(expectedErrorMessage3)) {
+                System.out.println("Expected: " + expectedErrorMessage3 + "\n" +
+                                   "but got:  " + errorMsg);
+                throw new RuntimeException("Wrong error message of IncompatibleClassChangeError.");
+            }
+            System.out.println("Test 3 passed with message: " + errorMsg);
+        } catch (Throwable e) {
+            throw new RuntimeException("Caught unexpected exception: " + e);
+        }
+    }
+
+    private static String expectedErrorMessage4 =
+        "class test.ICC4_B has interface test.ICC4_iA as super class";
+
+    public static void test4_extendsInterface() throws Exception {
+        try {
+            new ICC4_B();
+            throw new RuntimeException("Expected IncompatibleClassChangeError was not thrown.");
+        } catch (IncompatibleClassChangeError e) {
+            String errorMsg = e.getMessage();
+            if (!errorMsg.equals(expectedErrorMessage4)) {
+                System.out.println("Expected: " + expectedErrorMessage4 + "\n" +
+                                   "but got:  " + errorMsg);
+                throw new RuntimeException("Wrong error message of IncompatibleClassChangeError.");
+            }
+            System.out.println("Test 4 passed with message: " + errorMsg);
+        } catch (Throwable e) {
+            throw new RuntimeException("Caught unexpected exception: " + e);
+        }
+    }
+
     public static void main(String[] args) throws Exception {
         if (!setup_test()) {
             return;
         }
         test_iccInt();
         test_icc_compiled_itable_stub();
+        test3_implementsClass();
+        test4_extendsInterface();
     }
 }
 
@@ -305,20 +352,20 @@
 //         C D E \
 //                B (bad class, missing interface implementation)
 
-interface ICC_iA {
+interface ICC2_iA {
     public void a();
 }
 
-interface ICC_iB {
+interface ICC2_iB {
     public void b();
 }
 
-// This is the errorneous class. A variant of it not
-// implementing ICC_iB is copied into the test before
+// This is the erroneous class. A variant of it not
+// implementing ICC2_iB is copied into the test before
 // it is run.
-class ICC_B implements ICC_iA,
+class ICC2_B implements ICC2_iA,
                        // This interface is missing in the .jasm implementation.
-                       ICC_iB {
+                       ICC2_iB {
     public void a() {
         System.out.print("B.a() ");
     }
@@ -328,7 +375,7 @@
     }
 }
 
-class ICC_C implements ICC_iA, ICC_iB {
+class ICC2_C implements ICC2_iA, ICC2_iB {
     public void a() {
         System.out.print("C.a() ");
     }
@@ -338,7 +385,7 @@
     }
 }
 
-class ICC_D implements ICC_iA, ICC_iB {
+class ICC2_D implements ICC2_iA, ICC2_iB {
     public void a() {
         System.out.print("D.a() ");
     }
@@ -348,7 +395,7 @@
     }
 }
 
-class ICC_E implements ICC_iA, ICC_iB {
+class ICC2_E implements ICC2_iA, ICC2_iB {
     public void a() {
         System.out.print("E.a() ");
     }
@@ -357,3 +404,31 @@
         System.out.print("E.b() ");
     }
 }
+
+// Helper classes to test error where class appears in implements statement.
+//
+// Class hierachy:
+//
+//       A  Some Class.
+//       |
+//       B  erroneous class. Correct B extends A, incorrect B (from jasm) implements A.
+
+class ICC3_A {
+}
+
+class ICC3_B extends ICC3_A {
+}
+
+// Helper classes to test error where interface appears in extends statement.
+//
+// Class hierachy:
+//
+//       A  Some Interface.
+//       |
+//       B  erroneous class. Correct B implements A, incorrect B (from jasm) extends A.
+
+interface ICC4_iA {
+}
+
+class ICC4_B implements ICC4_iA {
+}
--- a/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -67,12 +67,12 @@
         pb = exec("-XX:+TraceLoaderConstraints");
         out = new OutputAnalyzer(pb.start());
         out.getOutput();
-        out.shouldContain("[class,loader,constraints] adding new constraint for name: java/lang/Class, loader[0]: jdk/internal/loader/ClassLoaders$AppClassLoader, loader[1]: <bootloader>");
+        out.shouldContain("[class,loader,constraints] adding new constraint for name: java/lang/Class, loader[0]: 'app', loader[1]: 'bootstrap'");
 
         // -Xlog:class+loader+constraints=info
         pb = exec("-Xlog:class+loader+constraints=info");
         out = new OutputAnalyzer(pb.start());
-        out.shouldContain("[class,loader,constraints] adding new constraint for name: java/lang/Class, loader[0]: jdk/internal/loader/ClassLoaders$AppClassLoader, loader[1]: <bootloader>");
+        out.shouldContain("[class,loader,constraints] adding new constraint for name: java/lang/Class, loader[0]: 'app', loader[1]: 'bootstrap'");
 
         // -XX:-TraceLoaderConstraints
         pb = exec("-XX:-TraceLoaderConstraints");
--- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c	Tue Jun 19 16:33:07 2018 +0100
@@ -52,7 +52,7 @@
 
 typedef struct _ObjectTrace{
   jweak object;
-  size_t size;
+  jlong size;
   jvmtiFrameInfo* frames;
   size_t frame_count;
   jthread thread;
--- a/test/hotspot/jtreg/serviceability/sa/TestUniverse.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/serviceability/sa/TestUniverse.java	Tue Jun 19 16:33:07 2018 +0100
@@ -163,8 +163,8 @@
                 if (args[0].equals("withZ")) {
                     test("-XX:+UseZGC");
                 }
+                test("-XX:+UseEpsilonGC");
             }
-            test("-XX:+UseEpsilonGC");
         } catch (Exception e) {
             throw new Error("Test failed with " + e);
         }
--- a/test/hotspot/jtreg/vmTestbase/ExecDriver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/ExecDriver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -102,22 +102,29 @@
         // adding jvm.so to library path
         if (launcher) {
             Path dir = Paths.get(Utils.TEST_JDK);
+            String value;
             String name;
             if (Platform.isWindows()) {
-                dir = dir.resolve("bin")
-                         .resolve(variant())
-                         .toAbsolutePath();
+                value = dir.resolve("bin")
+                           .resolve(variant())
+                           .toAbsolutePath()
+                           .toString();
+                value += File.pathSeparator;
+                value += dir.resolve("bin")
+                            .toAbsolutePath()
+                            .toString();
                 name = "PATH";
             } else {
-                dir = dir.resolve("lib")
-                         .resolve(variant())
-                         .toAbsolutePath();
+                value = dir.resolve("lib")
+                           .resolve(variant())
+                           .toAbsolutePath()
+                           .toString();
                 name = Platform.isOSX() ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH";
             }
 
             System.out.println("  with " + name + " = " +
                     pb.environment()
-                      .merge(name, dir.toString(), (x, y) -> y + File.pathSeparator + x));
+                      .merge(name, value, (x, y) -> y + File.pathSeparator + x));
             System.out.println("  with CLASSPATH = " +
                     pb.environment()
                       .put("CLASSPATH", Utils.TEST_CLASS_PATH));
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/general_functions/GF08/gf08t001/TestDriver.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/general_functions/GF08/gf08t001/TestDriver.java	Tue Jun 19 16:33:07 2018 +0100
@@ -63,6 +63,8 @@
  *      TestDriver
  */
 
+import sun.hotspot.code.Compiler;
+
 public class TestDriver {
     public static void main(String[] args) throws Exception {
         sun.hotspot.WhiteBox wb = sun.hotspot.WhiteBox.getWhiteBox();
@@ -70,6 +72,12 @@
         Boolean isUseG1GCon = wb.getBooleanVMFlag("UseG1GC");
         Boolean isUseConcMarkSweepGCon = wb.getBooleanVMFlag("UseConcMarkSweepGC");
         Boolean isUseZGCon = wb.getBooleanVMFlag("UseZGC");
+        Boolean isUseEpsilonGCon = wb.getBooleanVMFlag("UseEpsilonGC");
+
+        if (Compiler.isGraalEnabled() &&
+            (isUseConcMarkSweepGCon || isUseZGCon || isUseEpsilonGCon)) {
+            return; // Graal does not support these GCs
+        }
 
         String keyPhrase;
         if ((isExplicitGCInvokesConcurrentOn && (isUseG1GCon || isUseConcMarkSweepGCon)) || isUseZGCon) {
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/unit/heapref/heapref.c	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/unit/heapref/heapref.c	Tue Jun 19 16:33:07 2018 +0100
@@ -132,7 +132,7 @@
   obj_class = (*env)->GetObjectClass(env, obj);
 
   err = (*jvmti)->GetTag(jvmti, obj_class, &haba);
-  class_tag = (MyTag*)haba;
+  class_tag = (MyTag*)(intptr_t)haba;
   if (err != JVMTI_ERROR_NONE) {
     printf("Error (GetTag): %s (%d)\n", TranslateError(err), err);
     result = STATUS_FAILED;
@@ -144,7 +144,7 @@
 
   new_tag = newTag(kind, class_tag, size, name);
 
-  err = (*jvmti)->SetTag(jvmti, obj, (jlong)new_tag);
+  err = (*jvmti)->SetTag(jvmti, obj, (intptr_t)new_tag);
   if (err != JVMTI_ERROR_NONE) {
     printf("Error (SetTag): %s (%d)\n", TranslateError(err), err);
     result = STATUS_FAILED;
@@ -295,8 +295,8 @@
 
 jvmtiIterationControl JNICALL
 heapMarkCallback(jlong class_tag, jlong size, jlong* tag_ptr, void* user_data) {
-  const MyTag* const tag = newTag(rmark, (const MyTag*)class_tag, size, NULL);
-  *tag_ptr = (jlong)tag;
+  const MyTag* const tag = newTag(rmark, (const MyTag*)(intptr_t)class_tag, size, NULL);
+  *tag_ptr = (intptr_t)tag;
 
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
     user_data_error_flag = JNI_TRUE;
@@ -314,12 +314,12 @@
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, tag);
-    *tag_ptr = (jlong)tag;
+    *tag_ptr = (intptr_t)tag;
   } else {
     /* existing tag */
-    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)*tag_ptr);
+    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)(intptr_t)*tag_ptr);
   }
 
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
@@ -340,12 +340,12 @@
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, tag);
-    *tag_ptr = (jlong)tag;
+    *tag_ptr = (intptr_t)tag;
   } else {
     /* existing tag */
-    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)*tag_ptr);
+    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)(intptr_t)*tag_ptr);
   }
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
     user_data_error_flag = JNI_TRUE;
@@ -366,17 +366,17 @@
   if (0 == referrer_tag) {
     referrer = missed;
   } else {
-    referrer = (MyTag *)referrer_tag;
+    referrer = (MyTag *)(intptr_t)referrer_tag;
   }
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(referrer, reference_kind, tag);
-    *tag_ptr = (jlong) tag;
+    *tag_ptr = (intptr_t) tag;
   } else {
     /* existing tag */
-    MyTag* tag = (MyTag*)*tag_ptr;
+    MyTag* tag = (MyTag*)(intptr_t)*tag_ptr;
     addRef(referrer, reference_kind, tag);
   }
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/unit/refignore/refignore.c	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/unit/refignore/refignore.c	Tue Jun 19 16:33:07 2018 +0100
@@ -132,7 +132,7 @@
   obj_class = (*env)->GetObjectClass(env, obj);
 
   err = (*jvmti)->GetTag(jvmti, obj_class, &haba);
-  class_tag = (MyTag*)haba;
+  class_tag = (MyTag*)(intptr_t)haba;
   if (err != JVMTI_ERROR_NONE) {
     printf("Error (GetTag): %s (%d)\n", TranslateError(err), err);
     result = STATUS_FAILED;
@@ -144,7 +144,7 @@
 
   new_tag = newTag(kind, class_tag, size, name);
 
-  err = (*jvmti)->SetTag(jvmti, obj, (jlong)new_tag);
+  err = (*jvmti)->SetTag(jvmti, obj, (intptr_t)new_tag);
   if (err != JVMTI_ERROR_NONE) {
     printf("Error (SetTag): %s (%d)\n", TranslateError(err), err);
     result = STATUS_FAILED;
@@ -293,8 +293,8 @@
 
 jvmtiIterationControl JNICALL
 heapMarkCallback(jlong class_tag, jlong size, jlong* tag_ptr, void* user_data) {
-  const MyTag* const tag = newTag(rmark, (const MyTag*)class_tag, size, NULL);
-  *tag_ptr = (jlong)tag;
+  const MyTag* const tag = newTag(rmark, (const MyTag*)(intptr_t)class_tag, size, NULL);
+  *tag_ptr = (intptr_t)tag;
 
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
     user_data_error_flag = JNI_TRUE;
@@ -312,12 +312,12 @@
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, tag);
-    *tag_ptr = (jlong)tag;
+    *tag_ptr = (intptr_t)tag;
   } else {
     /* existing tag */
-    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)*tag_ptr);
+    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)(intptr_t)*tag_ptr);
   }
 
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
@@ -338,12 +338,12 @@
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, tag);
-    *tag_ptr = (jlong)tag;
+    *tag_ptr = (intptr_t)tag;
   } else {
     /* existing tag */
-    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)*tag_ptr);
+    addRef(fakeRoot, HEAP_ROOT_REF_KIND_BASE+root_kind, (MyTag*)(intptr_t)*tag_ptr);
   }
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
     user_data_error_flag = JNI_TRUE;
@@ -364,17 +364,17 @@
   if (0 == referrer_tag) {
     referrer = missed;
   } else {
-    referrer = (MyTag *)referrer_tag;
+    referrer = (MyTag *)(intptr_t)referrer_tag;
   }
 
   if (0 == *tag_ptr) {
     /* new tag */
-    MyTag* tag = newTag(kind, (MyTag*)class_tag, size, NULL);
+    MyTag* tag = newTag(kind, (MyTag*)(intptr_t)class_tag, size, NULL);
     addRef(referrer, reference_kind, tag);
-    *tag_ptr = (jlong) tag;
+    *tag_ptr = (intptr_t) tag;
   } else {
     /* existing tag */
-    MyTag* tag = (MyTag*)*tag_ptr;
+    MyTag* tag = (MyTag*)(intptr_t)*tag_ptr;
     addRef(referrer, reference_kind, tag);
   }
   if (user_data != &dummy_user_data && user_data_error_flag == JNI_FALSE) {
--- a/test/jdk/ProblemList.txt	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/ProblemList.txt	Tue Jun 19 16:33:07 2018 +0100
@@ -889,4 +889,3 @@
 jdk/jfr/event/io/TestInstrumentation.java                       8202142    generic-all
 jdk/jfr/event/sampling/TestNative.java                          8202142    generic-all
 jdk/jfr/event/os/TestSystemProcess.java                         8202835    linux-all
-jdk/jfr/event/runtime/TestBiasedLockRevocationEvents.java       8203237    generic-all
--- a/test/jdk/TEST.ROOT	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/TEST.ROOT	Tue Jun 19 16:33:07 2018 +0100
@@ -40,7 +40,8 @@
     vm.gc.Z \
     vm.graal.enabled \
     vm.cds \
-    docker.support
+    docker.support \
+    release.implementor
 
 # Minimum jtreg version
 requiredVersion=4.2 b12
--- a/test/jdk/TEST.groups	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/TEST.groups	Tue Jun 19 16:33:07 2018 +0100
@@ -39,7 +39,6 @@
     -java/util/Arrays/TimSortStackSize2.java
 
 tier1_part3 = \
-    :build_sanity \
     :jdk_math \
     :jdk_svc_sanity \
     java/nio/Buffer \
@@ -76,6 +75,7 @@
     :jdk_net
 
 tier3 = \
+    :build \
     :jdk_rmi \
     :jdk_beans \
     :jdk_imageio \
@@ -88,8 +88,8 @@
 #
 
 # Build source checking
-build_sanity = \
-    sanity/releaseFile
+build = \
+    build
 
 # java.lang package and VM runtime support
 jdk_lang = \
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/build/releaseFile/CheckSource.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,120 @@
+
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8193660
+ * @summary Check SOURCE line in "release" file for closedjdk
+ * @run main CheckSource
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+public class CheckSource {
+
+    CheckSource(String dataFile, boolean isOpenJDK) {
+        // Read data files
+        readFile(dataFile, isOpenJDK);
+    }
+
+    private void readFile(String fileName, boolean isOpenJDK) {
+        String fishForSOURCE = null;
+
+        File file = new File(fileName);
+
+        // open the stream to read in for Entries
+        try (BufferedReader buffRead =
+            new BufferedReader(new FileReader(fileName))) {
+
+            // this is the string read
+            String readIn;
+
+            // let's read some strings!
+            while ((readIn = buffRead.readLine()) != null) {
+                readIn = readIn.trim();
+
+                // throw out blank lines
+                if (readIn.length() == 0)
+                    continue;
+
+                // grab SOURCE line
+                if (readIn.startsWith("SOURCE=")) {
+                    fishForSOURCE = readIn;
+                    break;
+                }
+            }
+        } catch (FileNotFoundException fileExcept) {
+            throw new RuntimeException("File " + fileName +
+                                       " not found reading data!", fileExcept);
+        } catch (IOException ioExcept) {
+            throw new RuntimeException("Unexpected problem reading data!",
+                                       ioExcept);
+        }
+
+        // was SOURCE even found?
+        if (fishForSOURCE == null) {
+            throw new RuntimeException("SOURCE line was not found!");
+        } else {
+            // OK it was found, did it have correct sources?
+            System.out.println("The source string found: " + fishForSOURCE);
+
+            // First it MUST have .: regardless of closed or openJDK
+            if (!fishForSOURCE.contains(".:")) {
+                throw new RuntimeException("The test failed, .: not found!");
+            }
+            // take out the .: source path
+            fishForSOURCE = fishForSOURCE.replace(".:", "");
+
+            // if its closedJDK it MUST have open:
+            if (!isOpenJDK && !fishForSOURCE.contains("open:")) {
+                throw new RuntimeException("The test failed, open: not found!");
+            }
+            // take out the open: source path
+            fishForSOURCE = fishForSOURCE.replace("open:", "");
+
+            // if any other source exists, that's an error
+            if (fishForSOURCE.contains(":")) {
+                throw new RuntimeException("The test failed, additional sources found!");
+            }
+        }
+
+        // Everything was fine
+        System.out.println("The test passed!");
+    }
+
+    public static void main(String args[]) {
+        String jdkPath = System.getProperty("test.jdk");
+        String runtime = System.getProperty("java.runtime.name");
+
+        System.out.println("JDK Path : " + jdkPath);
+        System.out.println("Runtime Name : " + runtime);
+
+        new CheckSource(jdkPath + "/release",
+                              runtime.contains("OpenJDK"));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/build/translations/VerifyTranslations.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.BufferedInputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+/**
+ * @test
+ * @requires release.implementor == "Oracle Corporation"
+ * @modules jdk.jlink/jdk.tools.jimage
+ * @summary Oracle builds of OpenJDK should only contain english, chinese and
+ *          japanese translations
+ */
+public class VerifyTranslations {
+
+    /**
+     * The set of translations we want to see in an Oracle built image
+     */
+    private static final Set<String> VALID_TRANSLATION_SUFFIXES = Set.of(
+            "_en", "_en_US", "_en_US_POSIX", "_ja", "_zh_CN", "_zh_TW", "_zh_HK"
+    );
+
+    /**
+     * This regexp will not match locales with 3 letter lang strings because
+     * doing so would trigger a ton of false positives all over the source
+     * tree. This is ok for now but is a potential future flaw in the test.
+     */
+    private static final String BASE_LOCALE_REGEXP
+            = "(_[a-z]{2}(_[A-Z][a-z]{3})?(_([A-Z]{2})|([0-9]{3}))?(_[a-zA-Z]+)?)";
+
+    public static void main(String[] args) {
+        String jdkPath = System.getProperty("test.jdk");
+        String modulesFile = jdkPath + "/lib/modules";
+
+        // Run jimage tool to extract list of all classes and resources in the jdk
+        StringWriter output = new StringWriter();
+        jdk.tools.jimage.Main.run(new String[] { "list", modulesFile }, new PrintWriter(output));
+
+        Pattern classesLocalePattern = Pattern.compile(BASE_LOCALE_REGEXP + "\\.(class|properties)");
+
+        boolean failed = false;
+        String module = "";
+        for (String line : output.toString().split("\n")) {
+            if (line.startsWith("Module: ")) {
+                module = line.substring(8).trim();
+            }
+            // We do not filter resources in jdk.localedata
+            if (!module.equals("jdk.localedata")) {
+                Matcher matcher = classesLocalePattern.matcher(line);
+                if (matcher.find()) {
+                    if (!VALID_TRANSLATION_SUFFIXES.contains(matcher.group(1))) {
+                        System.out.println("Unsupported translation found in lib/modules: "
+                                + module + "/" + line.trim());
+                        failed = true;
+                    }
+                }
+            }
+        }
+
+        // Check all files in src.zip
+        Pattern sourceLocalePattern = Pattern.compile(BASE_LOCALE_REGEXP + "\\.java");
+        String srcZip = jdkPath + "/lib/src.zip";
+        try (ZipInputStream srcZipInput = new ZipInputStream(
+                new BufferedInputStream(new FileInputStream(srcZip)))) {
+            ZipEntry entry;
+            while ((entry = srcZipInput.getNextEntry()) != null) {
+                String name = entry.getName();
+                if (!name.startsWith("jdk.localedata")) {
+                    Matcher matcher = sourceLocalePattern.matcher(name);
+                    if (matcher.find()) {
+                        if (!VALID_TRANSLATION_SUFFIXES.contains(matcher.group(1))) {
+                            System.out.println("Unsupported translation found in lib/src.zip: " + name);
+                            failed = true;
+                        }
+                    }
+                }
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        if (failed) {
+            throw new RuntimeException("lib/modules contains unsupported translations");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/EnumToCompileAgainst.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * 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.
+ */
+
+/**
+ * The enum that will be seen at compile-time.
+ *
+ * <p>The filename deliberately does not match, since we need to declare two versions of the enum
+ * for compile-time and runtime.
+ */
+enum Enum {
+    ONE,
+    TWO,
+    THREE
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/EnumToRunAgainst.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * 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.
+ */
+
+/**
+ * The enum that will be seen at runtime.
+ *
+ * <p>The filename deliberately does not match, since we need to declare two versions of the enum
+ * for compile-time and runtime.
+ */
+enum Enum {
+    ONE
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingAnnotation.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+
+/** An annotation that will be missing at runtime. */
+@Retention(RUNTIME)
+public @interface MissingAnnotation {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingAnnotationArrayElementTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+/*
+ * @test
+ * @bug 7183985
+ * @summary getAnnotation() should throw NoClassDefFoundError when an annotation class is not
+ *          present at runtime
+ * @compile MissingAnnotationArrayElementTest.java MissingAnnotation.java
+ * @clean MissingAnnotation
+ * @run main MissingAnnotationArrayElementTest
+ */
+public class MissingAnnotationArrayElementTest {
+
+    @Retention(RUNTIME)
+    @interface AnnotationAnnotation {
+        MissingAnnotation[] value();
+    }
+
+    @AnnotationAnnotation({@MissingAnnotation, @MissingAnnotation})
+    static class Test {
+        void f(@AnnotationAnnotation({@MissingAnnotation, @MissingAnnotation}) int x) {}
+
+        Test(@AnnotationAnnotation({@MissingAnnotation, @MissingAnnotation}) int x) {}
+    }
+
+    public static void main(String[] args) throws Exception {
+        // MissingAnnotation will be absent from the runtime classpath, causing a
+        // NoClassDefFoundError when AnnotationAnnotation is read (since the type of its value array
+        // references cannot be completed).
+        assertThrowsNoClassDefFoundError(
+                () -> Test.class.getAnnotation(AnnotationAnnotation.class));
+        Method method = Test.class.getDeclaredMethod("f", int.class);
+        assertThrowsNoClassDefFoundError(method::getParameterAnnotations);
+        Constructor constructor = Test.class.getDeclaredConstructor(int.class);
+        assertThrowsNoClassDefFoundError(constructor::getParameterAnnotations);
+    }
+
+    interface ThrowingRunnable {
+        void run() throws Exception;
+    }
+
+    static void assertThrowsNoClassDefFoundError(ThrowingRunnable throwingRunnable)
+            throws Exception {
+        try {
+            throwingRunnable.run();
+            throw new AssertionError("expected exception");
+        } catch (NoClassDefFoundError expected) {
+            if (!expected.getMessage().contains("MissingAnnotation")) {
+                throw expected;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingClass.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * 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.
+ */
+
+/** A class that will be missing at runtime. */
+public class MissingClass {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingClass2.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * 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.
+ */
+
+/** A class that will be missing at runtime. */
+public class MissingClass2 {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingClassArrayElementTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.util.Arrays;
+
+/*
+ * @test
+ * @bug 7183985
+ * @summary getAnnotation() throws an ArrayStoreException when the annotation class not present
+ * @compile MissingClassArrayElementTest.java MissingClass.java MissingClass2.java
+ * @clean MissingClass MissingClass2
+ * @run main MissingClassArrayElementTest
+ */
+public class MissingClassArrayElementTest {
+
+    @Retention(RUNTIME)
+    @interface AnnotationAnnotation {
+        ClassArrayAnnotation[] value();
+    }
+
+    @Retention(RUNTIME)
+    @interface ClassArrayAnnotation {
+        Class<?>[] value();
+    }
+
+    @AnnotationAnnotation({
+        @ClassArrayAnnotation({MissingClass.class}),
+        @ClassArrayAnnotation({MissingClass.class, String.class}),
+        @ClassArrayAnnotation({String.class, MissingClass.class}),
+        @ClassArrayAnnotation({MissingClass.class, MissingClass2.class}),
+        @ClassArrayAnnotation({String.class})
+    })
+    static class Test {
+        void f(
+                @AnnotationAnnotation({
+                            @ClassArrayAnnotation({MissingClass.class, MissingClass.class}),
+                            @ClassArrayAnnotation({Float.class})
+                        })
+                        int x,
+                @AnnotationAnnotation({@ClassArrayAnnotation({Double.class})}) int y) {}
+
+        Test(
+                @AnnotationAnnotation({
+                            @ClassArrayAnnotation({MissingClass.class, MissingClass.class}),
+                            @ClassArrayAnnotation({Short.class}),
+                        })
+                        int x,
+                @AnnotationAnnotation({@ClassArrayAnnotation({Character.class})}) int y) {}
+    }
+
+    public static void main(String[] args) throws Exception {
+        classAnnotationTest();
+        methodParameterAnnotationsTest();
+        constructorParameterAnnotationsTest();
+    }
+
+    static void classAnnotationTest() throws Exception {
+        ClassArrayAnnotation[] outer = Test.class.getAnnotation(AnnotationAnnotation.class).value();
+        assertMissing(outer[0]);
+        assertMissing(outer[1]);
+        assertMissing(outer[2]);
+        assertMissing(outer[3]);
+        assertArrayEquals(outer[4].value(), new Class<?>[] {String.class});
+    }
+
+    static void methodParameterAnnotationsTest() throws Exception {
+        AnnotationAnnotation[] methodParameterAnnotations =
+                Arrays.stream(
+                                Test.class
+                                        .getDeclaredMethod("f", int.class, int.class)
+                                        .getParameterAnnotations())
+                        .map(x -> ((AnnotationAnnotation) x[0]))
+                        .toArray(AnnotationAnnotation[]::new);
+        // The first parameter's annotation contains some well-formed values, and the second
+        // parameter's
+        // annotation is well-formed
+        assertArrayEquals(
+                methodParameterAnnotations[0].value()[1].value(), new Class<?>[] {Float.class});
+        assertArrayEquals(
+                methodParameterAnnotations[1].value()[0].value(), new Class<?>[] {Double.class});
+        // The first parameter's annotation contains a missing value
+        assertMissing(methodParameterAnnotations[0].value()[0]);
+    }
+
+    static void constructorParameterAnnotationsTest() throws Exception {
+        AnnotationAnnotation[] constructorParameterAnnotations =
+                Arrays.stream(
+                                Test.class
+                                        .getDeclaredConstructor(int.class, int.class)
+                                        .getParameterAnnotations())
+                        .map(x -> ((AnnotationAnnotation) x[0]))
+                        .toArray(AnnotationAnnotation[]::new);
+        // The first parameter's annotation contains some well-formed values, and the second
+        // parameter's
+        // annotation is well-formed
+        assertArrayEquals(
+                constructorParameterAnnotations[0].value()[1].value(),
+                new Class<?>[] {Short.class});
+        assertArrayEquals(
+                constructorParameterAnnotations[1].value()[0].value(),
+                new Class<?>[] {Character.class});
+        // The first parameter's annotation contains a missing value
+        assertMissing(constructorParameterAnnotations[0].value()[0]);
+    }
+
+    static void assertArrayEquals(Object[] actual, Object[] expected) {
+        if (!Arrays.equals(actual, expected)) {
+            throw new AssertionError(
+                    "expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actual));
+        }
+    }
+
+    static void assertMissing(ClassArrayAnnotation missing) {
+        try {
+            missing.value();
+            throw new AssertionError("expected exception");
+        } catch (TypeNotPresentException expected) {
+            if (!expected.typeName().equals("MissingClass")) {
+                throw new AssertionError(
+                        "expected TypeNotPresentException: MissingClass", expected);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/annotation/Missing/MissingArrayElement/MissingEnumArrayElementTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2018, Google Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.util.Arrays;
+
+/*
+ * @test
+ * @bug 7183985
+ * @summary getAnnotation() throws an ArrayStoreException when the annotation class not present
+ * @compile MissingEnumArrayElementTest.java EnumToCompileAgainst.java
+ * @clean Enum
+ * @compile EnumToRunAgainst.java
+ * @run main MissingEnumArrayElementTest
+ */
+public class MissingEnumArrayElementTest {
+
+    @Retention(RUNTIME)
+    @interface AnnotationAnnotation {
+        EnumArrayAnnotation[] value();
+    }
+
+    @Retention(RUNTIME)
+    @interface EnumArrayAnnotation {
+        Enum[] value();
+    }
+
+    @AnnotationAnnotation({
+        @EnumArrayAnnotation({Enum.TWO}),
+        @EnumArrayAnnotation({Enum.ONE, Enum.TWO}),
+        @EnumArrayAnnotation({Enum.TWO, Enum.ONE}),
+        @EnumArrayAnnotation({Enum.TWO, Enum.THREE}),
+        @EnumArrayAnnotation({Enum.ONE}),
+    })
+    static class Test {
+        void f(
+                @AnnotationAnnotation({
+                            @EnumArrayAnnotation({Enum.TWO, Enum.ONE}),
+                            @EnumArrayAnnotation({Enum.ONE})
+                        })
+                        int x,
+                @AnnotationAnnotation({@EnumArrayAnnotation({Enum.ONE})}) int y) {}
+
+        Test(
+                @AnnotationAnnotation({
+                            @EnumArrayAnnotation({Enum.TWO, Enum.ONE}),
+                            @EnumArrayAnnotation({Enum.ONE})
+                        })
+                        int x,
+                @AnnotationAnnotation({@EnumArrayAnnotation({Enum.ONE})}) int y) {}
+    }
+
+    public static void main(String[] args) throws Exception {
+        classAnnotationTest();
+        methodParameterAnnotationsTest();
+        constructorParameterAnnotationsTest();
+    }
+
+    static void classAnnotationTest() throws Exception {
+        EnumArrayAnnotation[] outer = Test.class.getAnnotation(AnnotationAnnotation.class).value();
+        assertMissing(outer[0]);
+        assertMissing(outer[1]);
+        assertMissing(outer[2]);
+        assertMissing(outer[3]);
+        assertArrayEquals(outer[4].value(), new Enum[] {Enum.ONE});
+    }
+
+    static void methodParameterAnnotationsTest() throws Exception {
+        AnnotationAnnotation[] methodParameterAnnotations =
+                Arrays.stream(
+                                Test.class
+                                        .getDeclaredMethod("f", int.class, int.class)
+                                        .getParameterAnnotations())
+                        .map(x -> ((AnnotationAnnotation) x[0]))
+                        .toArray(AnnotationAnnotation[]::new);
+        // The first parameter's annotation contains some well-formed values, and the second
+        // parameter's
+        // annotation is well-formed
+        assertArrayEquals(methodParameterAnnotations[0].value()[1].value(), new Enum[] {Enum.ONE});
+        assertArrayEquals(methodParameterAnnotations[1].value()[0].value(), new Enum[] {Enum.ONE});
+        // The first parameter's annotation contains a missing value
+        assertMissing(methodParameterAnnotations[0].value()[0]);
+    }
+
+    static void constructorParameterAnnotationsTest() throws Exception {
+        AnnotationAnnotation[] constructorParameterAnnotations =
+                Arrays.stream(
+                                Test.class
+                                        .getDeclaredConstructor(int.class, int.class)
+                                        .getParameterAnnotations())
+                        .map(x -> ((AnnotationAnnotation) x[0]))
+                        .toArray(AnnotationAnnotation[]::new);
+        // The first parameter's annotation contains some well-formed values, and the second
+        // parameter's
+        // annotation is well-formed
+        assertArrayEquals(constructorParameterAnnotations[0].value()[1].value(), new Enum[] {Enum.ONE});
+        assertArrayEquals(constructorParameterAnnotations[1].value()[0].value(), new Enum[] {Enum.ONE});
+        // The first parameter's annotation contains a missing value
+        assertMissing(constructorParameterAnnotations[0].value()[0]);
+    }
+
+    static void assertArrayEquals(Object[] actual, Object[] expected) {
+        if (!Arrays.equals(actual, expected)) {
+            throw new AssertionError(
+                    "expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actual));
+        }
+    }
+
+    static void assertMissing(EnumArrayAnnotation annotation) throws Exception {
+        try {
+            annotation.value();
+            throw new AssertionError("expected exception");
+        } catch (EnumConstantNotPresentException expected) {
+            if (!expected.getMessage().equals("Enum.TWO")) {
+                throw new AssertionError(
+                        "expected EnumConstantNotPresentException for Enum.TWO", expected);
+            }
+        }
+    }
+}
--- a/test/jdk/java/nio/Buffer/EqualsCompareTest.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/java/nio/Buffer/EqualsCompareTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -86,6 +86,7 @@
 
         final MethodHandle eq;
         final MethodHandle cmp;
+        final MethodHandle mismtch;
 
         final MethodHandle getter;
         final MethodHandle setter;
@@ -99,6 +100,7 @@
             try {
                 eq = lookup.findVirtual(bufferType, "equals", MethodType.methodType(boolean.class, Object.class));
                 cmp = lookup.findVirtual(bufferType, "compareTo", MethodType.methodType(int.class, bufferType));
+                mismtch = lookup.findVirtual(bufferType, "mismatch", MethodType.methodType(int.class, bufferType));
 
                 getter = lookup.findVirtual(bufferType, "get", MethodType.methodType(elementType, int.class));
                 setter = lookup.findVirtual(bufferType, "put", MethodType.methodType(bufferType, int.class, elementType));
@@ -186,6 +188,18 @@
             return true;
         }
 
+        int mismatch(T a, T b) {
+            try {
+                return (int) mismtch.invoke(a, b);
+            }
+            catch (RuntimeException | Error e) {
+                throw e;
+            }
+            catch (Throwable t) {
+              throw new Error(t);
+            }
+        }
+
         static class Bytes extends BufferType<ByteBuffer, Byte> {
             Bytes(BufferKind k) {
                 super(k, ByteBuffer.class, byte.class);
@@ -423,7 +437,6 @@
         }
     }
 
-
     static Object[][] bufferTypes;
 
     @DataProvider
@@ -635,12 +648,21 @@
                                 if (eq) {
                                     Assert.assertEquals(bt.compare(as, bs), 0);
                                     Assert.assertEquals(bt.compare(bs, as), 0);
+
+                                    // If buffers are equal, there shall be no mismatch
+                                    Assert.assertEquals(bt.mismatch(as, bs), -1);
+                                    Assert.assertEquals(bt.mismatch(bs, as), -1);
                                 }
                                 else {
                                     int aCb = bt.compare(as, bs);
                                     int bCa = bt.compare(bs, as);
                                     int v = Integer.signum(aCb) * Integer.signum(bCa);
                                     Assert.assertTrue(v == -1);
+
+                                    int aMs = bt.mismatch(as, bs);
+                                    int bMs = bt.mismatch(bs, as);
+                                    Assert.assertNotEquals(aMs, -1);
+                                    Assert.assertEquals(aMs, bMs);
                                 }
                             }
                         }
@@ -661,6 +683,11 @@
                                 int aCc = bt.compare(as, cs);
                                 int v = Integer.signum(cCa) * Integer.signum(aCc);
                                 Assert.assertTrue(v == -1);
+
+                                int cMa = bt.mismatch(cs, as);
+                                int aMc = bt.mismatch(as, cs);
+                                Assert.assertEquals(cMa, aMc);
+                                Assert.assertEquals(cMa, i - aFrom);
                             }
                         }
                     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/nio/channels/Selector/SelectWithConsumer.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,755 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8199433
+ * @run testng SelectWithConsumer
+ * @summary Unit test for Selector select(Consumer), select(Consumer,long) and
+ *          selectNow(Consumer)
+ */
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.Pipe;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import static java.util.concurrent.TimeUnit.*;
+
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+@Test
+public class SelectWithConsumer {
+
+    /**
+     * Invoke the select methods that take an action and check that the
+     * accumulated ready ops notified to the action matches the expected ops.
+     */
+    void testActionInvoked(SelectionKey key, int expectedOps) throws Exception {
+        var callerThread = Thread.currentThread();
+        var sel = key.selector();
+        var interestOps = key.interestOps();
+        var notifiedOps = new AtomicInteger();
+
+        // select(Consumer)
+        if (expectedOps == 0)
+            sel.wakeup(); // ensure select does not block
+        notifiedOps.set(0);
+        int n = sel.select(k -> {
+            assertTrue(Thread.currentThread() == callerThread);
+            assertTrue(k == key);
+            int readyOps = key.readyOps();
+            assertTrue((readyOps & interestOps) != 0);
+            assertTrue((readyOps & notifiedOps.get()) == 0);
+            notifiedOps.set(notifiedOps.get() | readyOps);
+        });
+        assertTrue((n == 1) ^ (expectedOps == 0));
+        assertTrue(notifiedOps.get() == expectedOps);
+
+        // select(Consumer, timeout)
+        notifiedOps.set(0);
+        n = sel.select(k -> {
+            assertTrue(Thread.currentThread() == callerThread);
+            assertTrue(k == key);
+            int readyOps = key.readyOps();
+            assertTrue((readyOps & interestOps) != 0);
+            assertTrue((readyOps & notifiedOps.get()) == 0);
+            notifiedOps.set(notifiedOps.get() | readyOps);
+        }, 1000);
+        assertTrue((n == 1) ^ (expectedOps == 0));
+        assertTrue(notifiedOps.get() == expectedOps);
+
+        // selectNow(Consumer)
+        notifiedOps.set(0);
+        n = sel.selectNow(k -> {
+            assertTrue(Thread.currentThread() == callerThread);
+            assertTrue(k == key);
+            int readyOps = key.readyOps();
+            assertTrue((readyOps & interestOps) != 0);
+            assertTrue((readyOps & notifiedOps.get()) == 0);
+            notifiedOps.set(notifiedOps.get() | readyOps);
+        });
+        assertTrue((n == 1) ^ (expectedOps == 0));
+        assertTrue(notifiedOps.get() == expectedOps);
+    }
+
+    /**
+     * Test that an action is performed when a channel is ready for reading.
+     */
+    public void testReadable() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+            source.configureBlocking(false);
+            SelectionKey key = source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure source is readable
+            scheduleWrite(sink, messageBuffer(), 100, MILLISECONDS);
+
+            // test that action is invoked
+            testActionInvoked(key, SelectionKey.OP_READ);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test that an action is performed when a channel is ready for writing.
+     */
+    public void testWritable() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            sink.configureBlocking(false);
+            SelectionKey key = sink.register(sel, SelectionKey.OP_WRITE);
+
+            // test that action is invoked
+            testActionInvoked(key, SelectionKey.OP_WRITE);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test that an action is performed when a channel is ready for both
+     * reading and writing.
+     */
+    public void testReadableAndWriteable() throws Exception {
+        ServerSocketChannel ssc = null;
+        SocketChannel sc = null;
+        SocketChannel peer = null;
+        try (Selector sel = Selector.open()) {
+            ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));
+            sc = SocketChannel.open(ssc.getLocalAddress());
+            sc.configureBlocking(false);
+            SelectionKey key = sc.register(sel, (SelectionKey.OP_READ |
+                                                 SelectionKey.OP_WRITE));
+
+            // accept connection and write data so the source is readable
+            peer = ssc.accept();
+            peer.write(messageBuffer());
+
+            // test that action is invoked
+            testActionInvoked(key, (SelectionKey.OP_READ | SelectionKey.OP_WRITE));
+        } finally {
+            if (ssc != null) ssc.close();
+            if (sc != null) sc.close();
+            if (peer != null) peer.close();
+        }
+    }
+
+    /**
+     * Test that the action is called for two selected channels
+     */
+    public void testTwoChannels() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            sink.configureBlocking(false);
+            SelectionKey key1 = source.register(sel, SelectionKey.OP_READ);
+            SelectionKey key2 = sink.register(sel, SelectionKey.OP_WRITE);
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            var counter = new AtomicInteger();
+
+            // select(Consumer)
+            counter.set(0);
+            int n = sel.select(k -> {
+                counter.incrementAndGet();
+                if (k == key1) {
+                    assertTrue(k.isReadable());
+                } else if (k == key2) {
+                    assertTrue(k.isWritable());
+                } else {
+                    assertTrue(false);
+                }
+            });
+            assertTrue(n == 2);
+            assertTrue(counter.get() == 2);
+
+            // select(Consumer, timeout)
+            counter.set(0);
+            n = sel.select(k -> {
+                counter.incrementAndGet();
+                if (k == key1) {
+                    assertTrue(k.isReadable());
+                } else if (k == key2) {
+                    assertTrue(k.isWritable());
+                } else {
+                    assertTrue(false);
+                }
+            }, 1000);
+            assertTrue(n == 2);
+            assertTrue(counter.get() == 2);
+
+            // selectNow(Consumer)
+            counter.set(0);
+            n = sel.selectNow(k -> {
+                counter.incrementAndGet();
+                if (k == key1) {
+                    assertTrue(k.isReadable());
+                } else if (k == key2) {
+                    assertTrue(k.isWritable());
+                } else {
+                    assertTrue(false);
+                }
+            });
+            assertTrue(n == 2);
+            assertTrue(counter.get() == 2);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test calling select twice, the action should be invoked each time
+     */
+    public void testRepeatedSelect1() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            SelectionKey key = source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            // test that action is invoked
+            testActionInvoked(key, SelectionKey.OP_READ);
+            testActionInvoked(key, SelectionKey.OP_READ);
+
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test calling select twice. An I/O operation is performed after the
+     * first select so the channel will not be selected by the second select.
+     */
+    public void testRepeatedSelect2() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            SelectionKey key = source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            // test that action is invoked
+            testActionInvoked(key, SelectionKey.OP_READ);
+
+            // read all bytes
+            int n;
+            ByteBuffer bb = ByteBuffer.allocate(100);
+            do {
+                n = source.read(bb);
+                bb.clear();
+            } while (n > 0);
+
+            // test that action is not invoked
+            testActionInvoked(key, 0);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test timeout
+     */
+    public void testTimeout() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            source.register(sel, SelectionKey.OP_READ);
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 1000L);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration > 500, "select took " + duration + " ms");
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test wakeup prior to select
+     */
+    public void testWakeupBeforeSelect() throws Exception {
+        // select(Consumer)
+        try (Selector sel = Selector.open()) {
+            sel.wakeup();
+            int n = sel.select(k -> assertTrue(false));
+            assertTrue(n == 0);
+        }
+
+        // select(Consumer, timeout)
+        try (Selector sel = Selector.open()) {
+            sel.wakeup();
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 60*1000);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration < 5000, "select took " + duration + " ms");
+        }
+    }
+
+    /**
+     * Test wakeup during select
+     */
+    public void testWakeupDuringSelect() throws Exception {
+        // select(Consumer)
+        try (Selector sel = Selector.open()) {
+            scheduleWakeup(sel, 1, SECONDS);
+            int n = sel.select(k -> assertTrue(false));
+            assertTrue(n == 0);
+        }
+
+        // select(Consumer, timeout)
+        try (Selector sel = Selector.open()) {
+            scheduleWakeup(sel, 1, SECONDS);
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 60*1000);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration > 500 && duration < 10*1000,
+                    "select took " + duration + " ms");
+        }
+    }
+
+    /**
+     * Test invoking select with interrupt status set
+     */
+    public void testInterruptBeforeSelect() throws Exception {
+        // select(Consumer)
+        try (Selector sel = Selector.open()) {
+            Thread.currentThread().interrupt();
+            int n = sel.select(k -> assertTrue(false));
+            assertTrue(n == 0);
+            assertTrue(Thread.currentThread().isInterrupted());
+            assertTrue(sel.isOpen());
+        } finally {
+            Thread.currentThread().interrupted();  // clear interrupt status
+        }
+
+        // select(Consumer, timeout)
+        try (Selector sel = Selector.open()) {
+            Thread.currentThread().interrupt();
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 60*1000);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration < 5000, "select took " + duration + " ms");
+            assertTrue(Thread.currentThread().isInterrupted());
+            assertTrue(sel.isOpen());
+        } finally {
+            Thread.currentThread().interrupted();  // clear interrupt status
+        }
+    }
+
+    /**
+     * Test interrupt thread during select
+     */
+    public void testInterruptDuringSelect() throws Exception {
+        // select(Consumer)
+        try (Selector sel = Selector.open()) {
+            scheduleInterrupt(Thread.currentThread(), 1, SECONDS);
+            int n = sel.select(k -> assertTrue(false));
+            assertTrue(n == 0);
+            assertTrue(Thread.currentThread().isInterrupted());
+            assertTrue(sel.isOpen());
+        } finally {
+            Thread.currentThread().interrupted();  // clear interrupt status
+        }
+
+        // select(Consumer, timeout)
+        try (Selector sel = Selector.open()) {
+            scheduleInterrupt(Thread.currentThread(), 1, SECONDS);
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 60*1000);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration > 500 && duration < 5000,
+                    "select took " + duration + " ms");
+            assertTrue(Thread.currentThread().isInterrupted());
+            assertTrue(sel.isOpen());
+        } finally {
+            Thread.currentThread().interrupted();  // clear interrupt status
+        }
+    }
+
+    /**
+     * Test invoking select on a closed selector
+     */
+    @Test(expectedExceptions = ClosedSelectorException.class)
+    public void testClosedSelector1() throws Exception {
+        Selector sel = Selector.open();
+        sel.close();
+        sel.select(k -> assertTrue(false));
+    }
+    @Test(expectedExceptions = ClosedSelectorException.class)
+    public void testClosedSelector2() throws Exception {
+        Selector sel = Selector.open();
+        sel.close();
+        sel.select(k -> assertTrue(false), 1000);
+    }
+    @Test(expectedExceptions = ClosedSelectorException.class)
+    public void testClosedSelector3() throws Exception {
+        Selector sel = Selector.open();
+        sel.close();
+        sel.selectNow(k -> assertTrue(false));
+    }
+
+    /**
+     * Test closing selector while in a selection operation
+     */
+    public void testCloseDuringSelect() throws Exception {
+        // select(Consumer)
+        try (Selector sel = Selector.open()) {
+            scheduleClose(sel, 3, SECONDS);
+            int n = sel.select(k -> assertTrue(false));
+            assertTrue(n == 0);
+            assertFalse(sel.isOpen());
+        }
+
+        // select(Consumer, timeout)
+        try (Selector sel = Selector.open()) {
+            scheduleClose(sel, 3, SECONDS);
+            long start = System.currentTimeMillis();
+            int n = sel.select(k -> assertTrue(false), 60*1000);
+            long duration = System.currentTimeMillis() - start;
+            assertTrue(n == 0);
+            assertTrue(duration > 2000 && duration < 10*1000,
+                    "select took " + duration + " ms");
+            assertFalse(sel.isOpen());
+        }
+    }
+
+    /**
+     * Test action closing selector
+     */
+    @Test(expectedExceptions = ClosedSelectorException.class)
+    public void testActionClosingSelector() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            SelectionKey key = source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            // should relay ClosedSelectorException
+            sel.select(k -> {
+                assertTrue(k == key);
+                try {
+                    sel.close();
+                } catch (IOException ioe) { }
+            });
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test that the action is invoked while synchronized on the selector and
+     * its selected-key set.
+     */
+    public void testLocks() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SourceChannel source = p.source();
+            Pipe.SinkChannel sink = p.sink();
+            source.configureBlocking(false);
+            SelectionKey key = source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            // select(Consumer)
+            sel.select(k -> {
+                assertTrue(k == key);
+                assertTrue(Thread.holdsLock(sel));
+                assertFalse(Thread.holdsLock(sel.keys()));
+                assertTrue(Thread.holdsLock(sel.selectedKeys()));
+            });
+
+            // select(Consumer, timeout)
+            sel.select(k -> {
+                assertTrue(k == key);
+                assertTrue(Thread.holdsLock(sel));
+                assertFalse(Thread.holdsLock(sel.keys()));
+                assertTrue(Thread.holdsLock(sel.selectedKeys()));
+            }, 1000L);
+
+            // selectNow(Consumer)
+            sel.selectNow(k -> {
+                assertTrue(k == key);
+                assertTrue(Thread.holdsLock(sel));
+                assertFalse(Thread.holdsLock(sel.keys()));
+                assertTrue(Thread.holdsLock(sel.selectedKeys()));
+            });
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test that selection operations remove cancelled keys from the selector's
+     * key and selected-key sets.
+     */
+    public void testCancel() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+
+            // write to sink to ensure that the source is readable
+            sink.write(messageBuffer());
+
+            sink.configureBlocking(false);
+            source.configureBlocking(false);
+            SelectionKey key1 = sink.register(sel, SelectionKey.OP_WRITE);
+            SelectionKey key2 = source.register(sel, SelectionKey.OP_READ);
+
+            sel.selectNow();
+            assertTrue(sel.keys().contains(key1));
+            assertTrue(sel.keys().contains(key2));
+            assertTrue(sel.selectedKeys().contains(key1));
+            assertTrue(sel.selectedKeys().contains(key2));
+
+            // cancel key1
+            key1.cancel();
+            int n = sel.selectNow(k -> assertTrue(k == key2));
+            assertTrue(n == 1);
+            assertFalse(sel.keys().contains(key1));
+            assertTrue(sel.keys().contains(key2));
+            assertFalse(sel.selectedKeys().contains(key1));
+            assertTrue(sel.selectedKeys().contains(key2));
+
+            // cancel key2
+            key2.cancel();
+            n = sel.selectNow(k -> assertTrue(false));
+            assertTrue(n == 0);
+            assertFalse(sel.keys().contains(key1));
+            assertFalse(sel.keys().contains(key2));
+            assertFalse(sel.selectedKeys().contains(key1));
+            assertFalse(sel.selectedKeys().contains(key2));
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test an action invoking select()
+     */
+    public void testReentrantSelect1() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+            source.configureBlocking(false);
+            source.register(sel, SelectionKey.OP_READ);
+
+            // write to sink to ensure that the source is readable
+            scheduleWrite(sink, messageBuffer(), 100, MILLISECONDS);
+
+            int n = sel.select(k -> {
+                try {
+                    sel.select();
+                    assertTrue(false);
+                } catch (IOException ioe) {
+                    throw new RuntimeException(ioe);
+                } catch (IllegalStateException expected) {
+                }
+            });
+            assertTrue(n == 1);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test an action invoking selectNow()
+     */
+    public void testReentrantSelect2() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+
+            // write to sink to ensure that the source is readable
+            scheduleWrite(sink, messageBuffer(), 100, MILLISECONDS);
+
+            source.configureBlocking(false);
+            source.register(sel, SelectionKey.OP_READ);
+            int n = sel.select(k -> {
+                try {
+                    sel.selectNow();
+                    assertTrue(false);
+                } catch (IOException ioe) {
+                    throw new RuntimeException(ioe);
+                } catch (IllegalStateException expected) {
+                }
+            });
+            assertTrue(n == 1);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Test an action invoking select(Consumer)
+     */
+    public void testReentrantSelect3() throws Exception {
+        Pipe p = Pipe.open();
+        try (Selector sel = Selector.open()) {
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+
+            // write to sink to ensure that the source is readable
+            scheduleWrite(sink, messageBuffer(), 100, MILLISECONDS);
+
+            source.configureBlocking(false);
+            source.register(sel, SelectionKey.OP_READ);
+            int n = sel.select(k -> {
+                try {
+                    sel.select(x -> assertTrue(false));
+                    assertTrue(false);
+                } catch (IOException ioe) {
+                    throw new RuntimeException(ioe);
+                } catch (IllegalStateException expected) {
+                }
+            });
+            assertTrue(n == 1);
+        } finally {
+            closePipe(p);
+        }
+    }
+
+    /**
+     * Negative timeout
+     */
+    @Test(expectedExceptions = IllegalArgumentException.class)
+    public void testNegativeTimeout() throws Exception {
+        try (Selector sel = Selector.open()) {
+            sel.select(k -> { }, -1L);
+        }
+    }
+
+    /**
+     * Null action
+     */
+    @Test(expectedExceptions = NullPointerException.class)
+    public void testNull1() throws Exception {
+        try (Selector sel = Selector.open()) {
+            sel.select(null);
+        }
+    }
+    @Test(expectedExceptions = NullPointerException.class)
+    public void testNull2() throws Exception {
+        try (Selector sel = Selector.open()) {
+            sel.select(null, 1000);
+        }
+    }
+    @Test(expectedExceptions = NullPointerException.class)
+    public void testNull3() throws Exception {
+        try (Selector sel = Selector.open()) {
+            sel.selectNow(null);
+        }
+    }
+
+
+    // -- support methods ---
+
+    private final ScheduledExecutorService POOL = Executors.newScheduledThreadPool(1);
+
+    @AfterTest
+    void shutdownThreadPool() {
+        POOL.shutdown();
+    }
+
+    void scheduleWakeup(Selector sel, long delay, TimeUnit unit) {
+        POOL.schedule(() -> sel.wakeup(), delay, unit);
+    }
+
+    void scheduleInterrupt(Thread t, long delay, TimeUnit unit) {
+        POOL.schedule(() -> t.interrupt(), delay, unit);
+    }
+
+    void scheduleClose(Closeable c, long delay, TimeUnit unit) {
+        POOL.schedule(() -> {
+            try {
+                c.close();
+            } catch (IOException ioe) {
+                ioe.printStackTrace();
+            }
+        }, delay, unit);
+    }
+
+    void scheduleWrite(WritableByteChannel sink, ByteBuffer buf, long delay, TimeUnit unit) {
+        POOL.schedule(() -> {
+            try {
+                sink.write(buf);
+            } catch (IOException ioe) {
+                ioe.printStackTrace();
+            }
+        }, delay, unit);
+    }
+
+    static void closePipe(Pipe p) {
+        try { p.sink().close(); } catch (IOException ignore) { }
+        try { p.source().close(); } catch (IOException ignore) { }
+    }
+
+    static ByteBuffer messageBuffer() {
+        try {
+            return ByteBuffer.wrap("message".getBytes("UTF-8"));
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
--- a/test/jdk/java/nio/file/Files/CopyAndMove.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/java/nio/file/Files/CopyAndMove.java	Tue Jun 19 16:33:07 2018 +0100
@@ -53,7 +53,9 @@
         try {
 
             // Same directory
-            testPosixAttributes = getFileStore(dir1).supportsFileAttributeView("posix");
+            FileStore fileStore1 = getFileStore(dir1);
+            printDirInfo("dir1", dir1, fileStore1);
+            testPosixAttributes = fileStore1.supportsFileAttributeView("posix");
             testCopyFileToFile(dir1, dir1, TestUtil.supportsLinks(dir1));
             testMove(dir1, dir1, TestUtil.supportsLinks(dir1));
 
@@ -64,8 +66,10 @@
             try {
                 boolean testSymbolicLinks =
                     TestUtil.supportsLinks(dir1) && TestUtil.supportsLinks(dir2);
-                testPosixAttributes = getFileStore(dir1).supportsFileAttributeView("posix") &&
-                                      getFileStore(dir2).supportsFileAttributeView("posix");
+                FileStore fileStore2 = getFileStore(dir2);
+                printDirInfo("dir2", dir2, fileStore2);
+                testPosixAttributes = fileStore1.supportsFileAttributeView("posix") &&
+                                      fileStore2.supportsFileAttributeView("posix");
                 testCopyFileToFile(dir1, dir2, testSymbolicLinks);
                 testMove(dir1, dir2, testSymbolicLinks);
             } finally {
@@ -74,8 +78,10 @@
 
             // Target is location associated with custom provider
             Path dir3 = PassThroughFileSystem.create().getPath(dir1.toString());
-            testPosixAttributes = getFileStore(dir1).supportsFileAttributeView("posix") &&
-                                  getFileStore(dir3).supportsFileAttributeView("posix");
+            FileStore fileStore3 = getFileStore(dir3);
+            printDirInfo("dir3", dir3, fileStore3);
+            testPosixAttributes = fileStore1.supportsFileAttributeView("posix") &&
+                                  fileStore3.supportsFileAttributeView("posix");
             testCopyFileToFile(dir1, dir3, false);
             testMove(dir1, dir3, false);
 
@@ -88,16 +94,9 @@
         }
     }
 
-    static void printDirInfo(String name, Path dir) throws IOException {
-        System.err.format("%s: %s (%s)%n", name, dir,
-            Files.getFileStore(dir).type());
-    }
-
-    static void printDirInfo(String label, Path dir1, Path dir2)
+    static void printDirInfo(String name, Path dir, FileStore store)
         throws IOException {
-        System.err.format("--- %s ---%n", label);
-        printDirInfo("dir1", dir1);
-        printDirInfo("dir2", dir2);
+        System.err.format("%s: %s (%s)%n", name, dir, store.type());
     }
 
     static void checkBasicAttributes(BasicFileAttributes attrs1,
@@ -129,44 +128,25 @@
     static void checkPosixAttributes(PosixFileAttributes attrs1,
                                      PosixFileAttributes attrs2)
     {
-        try {
-            assertTrue(attrs1.permissions().equals(attrs2.permissions()));
-            assertTrue(attrs1.owner().equals(attrs2.owner()));
-            assertTrue(attrs1.group().equals(attrs2.group()));
-        } catch (Exception e) {
-            if (!attrs1.permissions().equals(attrs2.permissions()))
-                System.err.format("permissions%n1 (%d): %s%n2 (%d): %s%n%n",
-                    attrs1.permissions().size(), attrs1.permissions(),
-                    attrs2.permissions().size(), attrs2.permissions());
-            if (!attrs1.owner().equals(attrs2.owner()))
-                System.err.format("owner%n1: %s%n2: %s%n%n",
-                    attrs1.owner(), attrs2.owner());
-            if (!attrs1.group().equals(attrs2.group()))
-                System.err.format("group%n1: %s%n2: %s%n%n",
-                    attrs1.group(), attrs2.group());
-            throw e;
-        }
+        assertTrue(attrs1.permissions().equals(attrs2.permissions()),
+            "permissions%n1 (%d): %s%n2 (%d): %s%n%n",
+             attrs1.permissions().size(), attrs1.permissions(),
+             attrs2.permissions().size(), attrs2.permissions());
+        assertTrue(attrs1.owner().equals(attrs2.owner()),
+             "owner%n1: %s%n2: %s%n%n", attrs1.owner(), attrs2.owner());
+        assertTrue(attrs1.group().equals(attrs2.group()),
+             "group%n1: %s%n2: %s%n%n", attrs1.group(), attrs2.group());
     }
 
     static void checkDosAttributes(DosFileAttributes attrs1,
                                    DosFileAttributes attrs2)
     {
-        try {
-            assertTrue(attrs1.isReadOnly() == attrs2.isReadOnly());
-            assertTrue(attrs1.isHidden() == attrs2.isHidden());
-            assertTrue(attrs1.isSystem() == attrs2.isSystem());
-        } catch (Exception e) {
-            if(attrs1.isReadOnly() != attrs2.isReadOnly())
-                System.err.format("isReadOnly%n1: %s%n2: %s%n%n",
-                    attrs1.isReadOnly(), attrs2.isReadOnly());
-            if(attrs1.isHidden() != attrs2.isHidden())
-                System.err.format("isHidden%n1: %s%n2: %s%n%n",
-                    attrs1.isHidden(), attrs2.isHidden());
-            if(attrs1.isSystem() != attrs2.isSystem())
-                System.err.format("isSystem%n1: %s%n2: %s%n%n",
-                    attrs1.isSystem(), attrs2.isSystem());
-            throw e;
-        }
+        assertTrue(attrs1.isReadOnly() == attrs2.isReadOnly(),
+            "isReadOnly%n1: %s%n2: %s%n%n", attrs1.isReadOnly(), attrs2.isReadOnly());
+        assertTrue(attrs1.isHidden() == attrs2.isHidden(),
+            "isHidden%n1: %s%n2: %s%n%n", attrs1.isHidden(), attrs2.isHidden());
+        assertTrue(attrs1.isSystem() == attrs2.isSystem(),
+            "isSystem%n1: %s%n2: %s%n%n", attrs1.isSystem(), attrs2.isSystem());
     }
 
     static void checkUserDefinedFileAttributes(Map<String,ByteBuffer> attrs1,
@@ -292,8 +272,6 @@
     static void testMove(Path dir1, Path dir2, boolean supportsLinks)
         throws IOException
     {
-        printDirInfo("testMove", dir1, dir2);
-
         Path source, target, entry;
 
         boolean sameDevice = getFileStore(dir1).equals(getFileStore(dir2));
@@ -729,8 +707,6 @@
     static void testCopyFileToFile(Path dir1, Path dir2, boolean supportsLinks)
         throws IOException
     {
-        printDirInfo("testCopyFileToFile", dir1, dir2);
-
         Path source, target, link, entry;
 
         // -- regular file --
@@ -1156,6 +1132,13 @@
             throw new RuntimeException("Assertion failed");
     }
 
+    static void assertTrue(boolean value, String format, Object... args) {
+        if (!value) {
+            System.err.format(format, args);
+            throw new RuntimeException("Assertion failed");
+        }
+    }
+
     // computes simple hash of the given file
     static int computeHash(Path file) throws IOException {
         int h = 0;
--- a/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/java/time/test/java/time/format/TestDateTimeFormatterBuilderWithLocale.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,17 +64,23 @@
  */
 package test.java.time.format;
 
+import java.time.chrono.ChronoLocalDate;
 import java.time.chrono.Chronology;
 import java.time.chrono.IsoChronology;
 import java.time.chrono.JapaneseChronology;
+import java.time.chrono.JapaneseEra;
 import java.time.chrono.MinguoChronology;
+import java.time.chrono.ThaiBuddhistChronology;
 import java.time.format.DateTimeFormatter;
 import java.time.format.DateTimeFormatterBuilder;
 import java.time.format.FormatStyle;
 import java.time.LocalDate;
+import java.time.temporal.ChronoField;
 import java.time.temporal.Temporal;
 
+import java.util.HashMap;
 import java.util.Locale;
+import java.util.Map;
 
 import static org.testng.Assert.assertEquals;
 
@@ -115,6 +121,29 @@
     }
 
     //-----------------------------------------------------------------------
+    @DataProvider(name="mapTextLookup")
+    Object[][] data_mapTextLookup() {
+        return new Object[][] {
+            {IsoChronology.INSTANCE.date(1, 1, 1), Locale.ENGLISH},
+            {JapaneseChronology.INSTANCE.date(JapaneseEra.HEISEI, 1, 1, 8), Locale.ENGLISH},
+            {MinguoChronology.INSTANCE.date(1, 1, 1), Locale.ENGLISH},
+            {ThaiBuddhistChronology.INSTANCE.date(1, 1, 1), Locale.ENGLISH},
+        };
+    }
+
+    @Test(dataProvider="mapTextLookup")
+    public void test_appendText_mapTextLookup(ChronoLocalDate date, Locale locale) {
+        final String new1st = "1st";
+        Map<Long, String> yearMap = new HashMap<>();
+        yearMap.put(1L, new1st);
+        builder.appendText(ChronoField.YEAR_OF_ERA, yearMap);
+
+        String actual = date.format(builder.toFormatter(locale));
+        assertEquals(actual, new1st);
+    }
+
+
+    //-----------------------------------------------------------------------
     @DataProvider(name="localePatterns")
     Object[][] localizedDateTimePatterns() {
         return new Object[][] {
--- a/test/jdk/java/util/logging/LocalizedLevelName.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/java/util/logging/LocalizedLevelName.java	Tue Jun 19 16:33:07 2018 +0100
@@ -34,19 +34,19 @@
 
 public class LocalizedLevelName {
     private static Object[] namesMap = {
-        "SEVERE",  Locale.ENGLISH, "Severe",        Level.SEVERE,
-        "WARNING", Locale.FRENCH,  "Avertissement", Level.WARNING,
-        "INFO",    Locale.ITALIAN, "Informazioni",  Level.INFO,
-        "SEVERE",  Locale.FRENCH,  "Grave",         Level.SEVERE,
-        "CONFIG",  Locale.GERMAN,  "Konfiguration", Level.CONFIG,
-        "ALL",     Locale.ROOT,    "All",           Level.ALL,
-        "SEVERE",  Locale.ROOT,    "Severe",        Level.SEVERE,
-        "WARNING", Locale.ROOT,    "Warning",       Level.WARNING,
-        "CONFIG",  Locale.ROOT,    "Config",        Level.CONFIG,
-        "INFO",    Locale.ROOT,    "Info",          Level.INFO,
-        "FINE",    Locale.ROOT,    "Fine",          Level.FINE,
-        "FINER",   Locale.ROOT,    "Finer",         Level.FINER,
-        "FINEST",  Locale.ROOT,    "Finest",        Level.FINEST
+        "SEVERE",  Locale.ENGLISH,                 "Severe",       Level.SEVERE,
+        "WARNING", Locale.JAPANESE,                "\u8B66\u544A", Level.WARNING,
+        "INFO",    Locale.SIMPLIFIED_CHINESE,      "\u4FE1\u606F", Level.INFO,
+        "SEVERE",  Locale.TRADITIONAL_CHINESE,     "\u56B4\u91CD", Level.SEVERE,
+        "CONFIG",  Locale.forLanguageTag("zh-HK"), "\u7D44\u614B", Level.CONFIG,
+        "ALL",     Locale.ROOT,                    "All",          Level.ALL,
+        "SEVERE",  Locale.ROOT,                    "Severe",       Level.SEVERE,
+        "WARNING", Locale.ROOT,                    "Warning",      Level.WARNING,
+        "CONFIG",  Locale.ROOT,                    "Config",       Level.CONFIG,
+        "INFO",    Locale.ROOT,                    "Info",         Level.INFO,
+        "FINE",    Locale.ROOT,                    "Fine",         Level.FINE,
+        "FINER",   Locale.ROOT,                    "Finer",        Level.FINER,
+        "FINEST",  Locale.ROOT,                    "Finest",       Level.FINEST
     };
 
     public static void main(String args[]) throws Exception {
--- a/test/jdk/javax/xml/crypto/dsig/GenerationTests.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/javax/xml/crypto/dsig/GenerationTests.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 /**
  * @test
  * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8046949
- *      8046724 8079693
+ *      8046724 8079693 8177334
  * @summary Basic unit tests for generating XML Signatures with JSR 105
  * @modules java.base/sun.security.util
  *          java.base/sun.security.x509
@@ -32,7 +32,7 @@
  *          jdk.httpserver/com.sun.net.httpserver
  * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
  *     X509KeySelector.java GenerationTests.java
- * @run main/othervm GenerationTests
+ * @run main/othervm/timeout=300 GenerationTests
  * @author Sean Mullan
  */
 
@@ -40,6 +40,7 @@
 import com.sun.net.httpserver.HttpHandler;
 import com.sun.net.httpserver.HttpServer;
 import java.io.*;
+import java.lang.reflect.Modifier;
 import java.math.BigInteger;
 import java.net.InetSocketAddress;
 import java.security.Key;
@@ -67,6 +68,7 @@
 import java.security.spec.RSAPrivateKeySpec;
 import java.security.spec.RSAPublicKeySpec;
 import java.util.*;
+import java.util.stream.Stream;
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 import javax.xml.XMLConstants;
@@ -91,8 +93,8 @@
 import org.w3c.dom.*;
 
 /**
- * Test that recreates merlin-xmldsig-twenty-three test vectors but with
- * different keys and X.509 data.
+ * Test that recreates merlin-xmldsig-twenty-three test vectors (and more)
+ * but with different keys and X.509 data.
  */
 public class GenerationTests {
 
@@ -100,11 +102,14 @@
     private static KeyInfoFactory kifac;
     private static DocumentBuilder db;
     private static CanonicalizationMethod withoutComments;
-    private static SignatureMethod dsaSha1, dsaSha256, rsaSha1,
-                                   rsaSha256, rsaSha384, rsaSha512,
-                                   ecdsaSha1;
-    private static DigestMethod sha1, sha256, sha384, sha512;
-    private static KeyInfo dsa1024, dsa2048, rsa, rsa1024,
+    private static SignatureMethod dsaSha1, dsaSha256,
+            rsaSha1, rsaSha224, rsaSha256, rsaSha384, rsaSha512,
+            ecdsaSha1, ecdsaSha224, ecdsaSha256, ecdsaSha384, ecdsaSha512,
+            hmacSha1, hmacSha224, hmacSha256, hmacSha384, hmacSha512,
+            rsaSha1mgf1, rsaSha224mgf1, rsaSha256mgf1, rsaSha384mgf1, rsaSha512mgf1;
+    private static DigestMethod sha1, sha224, sha256, sha384, sha512,
+                                sha3_224, sha3_256, sha3_384, sha3_512;
+    private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, rsa2048,
                            p256ki, p384ki, p521ki;
     private static KeySelector kvks = new KeySelectors.KeyValueKeySelector();
     private static KeySelector sks;
@@ -183,11 +188,67 @@
         null, Transform.BASE64
     };
 
-    private static final String[] signatureMethods = new String[] {
-        SignatureMethod.DSA_SHA1,
-        SignatureMethod.RSA_SHA1,
-        SignatureMethod.HMAC_SHA1
-    };
+    // It will be too time consuming to test all combinations of
+    // all digest methods and signature methods. So we pick some
+    // majors one and only test a combination when a major method
+    // (either digest or signature) is included.
+    //
+    //              *  *  *
+    //              *  *  *
+    //              *  *  *
+    //     *  *  *  *  *  *  *  *  *
+    //     *  *  *  *  *  *  *  *  *
+    //     *  *  *  *  *  *  *  *  *
+    //              *  *  *
+    //              *  *  *
+    //              *  *  *
+
+    private static List<String> majorSignatureMethods = List.of(
+            SignatureMethod.DSA_SHA256,
+            SignatureMethod.RSA_SHA256,
+            SignatureMethod.ECDSA_SHA256,
+            SignatureMethod.HMAC_SHA256,
+            SignatureMethod.SHA256_RSA_MGF1);
+
+    private static final String[] allSignatureMethods
+            = Stream.of(SignatureMethod.class.getDeclaredFields())
+                .filter(f -> Modifier.isStatic(f.getModifiers()))
+                .map(f -> {
+                    try {
+                        return (String)f.get(null);
+                    } catch (Exception e) {
+                        throw new Error("should not happen");
+                    }
+                })
+                .toArray(String[]::new);
+
+    private static final List<String> majorDigestMethods = List.of(
+            DigestMethod.SHA1,
+            DigestMethod.SHA256,
+            DigestMethod.SHA3_256);
+
+    private static final String[] allDigestMethods
+            = Stream.of(DigestMethod.class.getDeclaredFields())
+                .filter(f -> Modifier.isStatic(f.getModifiers())
+                                && !f.getName().equals("RIPEMD160"))
+                .map(f -> {
+                    try {
+                        return (String)f.get(null);
+                    } catch (Exception e) {
+                        throw new Error("should not happen");
+                    }
+                })
+                .toArray(String[]::new);
+
+    // As of JDK 11, the number of defined algorithms are...
+    static {
+        if (allSignatureMethods.length != 22
+                || allDigestMethods.length != 9) {
+            System.out.println(Arrays.toString(allSignatureMethods));
+            System.out.println(Arrays.toString(allDigestMethods));
+            throw new AssertionError("Not all methods are counted");
+        }
+    }
 
     private static enum Content {
         Xml, Text, Base64, NotExisitng
@@ -207,10 +268,15 @@
         test_create_signature_enveloping_dsa();
         test_create_signature_enveloping_hmac_sha1_40();
         test_create_signature_enveloping_hmac_sha256();
+        test_create_signature_enveloping_hmac_sha224();
         test_create_signature_enveloping_hmac_sha384();
         test_create_signature_enveloping_hmac_sha512();
         test_create_signature_enveloping_rsa();
         test_create_signature_enveloping_p256_sha1();
+        test_create_signature_enveloping_p256_sha224();
+        test_create_signature_enveloping_p256_sha256();
+        test_create_signature_enveloping_p256_sha384();
+        test_create_signature_enveloping_p256_sha512();
         test_create_signature_enveloping_p384_sha1();
         test_create_signature_enveloping_p521_sha1();
         test_create_signature_external_b64_dsa();
@@ -227,8 +293,19 @@
         test_create_sign_spec();
         test_create_signature_enveloping_sha256_dsa();
         test_create_signature_enveloping_sha384_rsa_sha256();
+        test_create_signature_enveloping_sha224_rsa_sha256();
+        test_create_signature_enveloping_sha3_224_rsa_sha256();
+        test_create_signature_enveloping_sha3_256_rsa_sha256();
+        test_create_signature_enveloping_sha3_384_rsa_sha256();
+        test_create_signature_enveloping_sha3_512_rsa_sha256();
         test_create_signature_enveloping_sha512_rsa_sha384();
+        test_create_signature_enveloping_sha512_rsa_sha224();
         test_create_signature_enveloping_sha512_rsa_sha512();
+        test_create_signature_enveloping_sha512_rsa_sha1_mgf1();
+        test_create_signature_enveloping_sha512_rsa_sha224_mgf1();
+        test_create_signature_enveloping_sha512_rsa_sha256_mgf1();
+        test_create_signature_enveloping_sha512_rsa_sha384_mgf1();
+        test_create_signature_enveloping_sha512_rsa_sha512_mgf1();
         test_create_signature_reference_dependency();
         test_create_signature_with_attr_in_no_namespace();
         test_create_signature_with_empty_id();
@@ -239,30 +316,39 @@
 
             // 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);
-                        }))));
+                Arrays.stream(allSignatureMethods).forEach(s ->
+                    Arrays.stream(allDigestMethods).forEach(d ->
+                        Arrays.stream(xml_transforms).forEach(t ->
+                            Arrays.stream(KeyInfoType.values()).forEach(k -> {
+                                if (isMajor(s, d)) {
+                                    test_create_detached_signature(c, s, d, 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);
-                    })));
+                Arrays.stream(allSignatureMethods).forEach(s ->
+                    Arrays.stream(allDigestMethods).forEach(d ->
+                        Arrays.stream(KeyInfoType.values()).forEach(k -> {
+                            if (isMajor(s, d)) {
+                                test_create_detached_signature(c, s, d, 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);
-                        }))));
+                Arrays.stream(allSignatureMethods).forEach(s ->
+                    Arrays.stream(allDigestMethods).forEach(d ->
+                        Arrays.stream(non_xml_transforms).forEach(t ->
+                            Arrays.stream(KeyInfoType.values()).forEach(k -> {
+                                if (isMajor(s, d)) {
+                                    test_create_detached_signature(c, s, d, t, k,
+                                            Content.Base64, server.getPort(),
+                                            false, null);
+                                }
+                        })))));
 
             // negative tests
 
@@ -270,6 +356,7 @@
             test_create_detached_signature(
                     CanonicalizationMethod.EXCLUSIVE + BOGUS,
                     SignatureMethod.DSA_SHA1,
+                    DigestMethod.SHA1,
                     CanonicalizationMethod.INCLUSIVE,
                     KeyInfoType.KeyName,
                     Content.Xml,
@@ -281,6 +368,18 @@
             test_create_detached_signature(
                     CanonicalizationMethod.EXCLUSIVE,
                     SignatureMethod.DSA_SHA1 + BOGUS,
+                    DigestMethod.SHA1,
+                    CanonicalizationMethod.INCLUSIVE,
+                    KeyInfoType.KeyName, Content.Xml,
+                    server.getPort(),
+                    true,
+                    NoSuchAlgorithmException.class);
+
+            // unknown DigestMethod
+            test_create_detached_signature(
+                    CanonicalizationMethod.EXCLUSIVE,
+                    SignatureMethod.DSA_SHA1,
+                    DigestMethod.SHA1 + BOGUS,
                     CanonicalizationMethod.INCLUSIVE,
                     KeyInfoType.KeyName, Content.Xml,
                     server.getPort(),
@@ -291,6 +390,7 @@
             test_create_detached_signature(
                     CanonicalizationMethod.EXCLUSIVE,
                     SignatureMethod.DSA_SHA1,
+                    DigestMethod.SHA1,
                     CanonicalizationMethod.INCLUSIVE + BOGUS,
                     KeyInfoType.KeyName, Content.Xml,
                     server.getPort(),
@@ -301,6 +401,7 @@
             test_create_detached_signature(
                     CanonicalizationMethod.EXCLUSIVE,
                     SignatureMethod.DSA_SHA1,
+                    DigestMethod.SHA1,
                     CanonicalizationMethod.INCLUSIVE,
                     KeyInfoType.KeyName,
                     Content.NotExisitng,
@@ -312,6 +413,7 @@
             test_create_detached_signature(
                     CanonicalizationMethod.EXCLUSIVE,
                     SignatureMethod.DSA_SHA1,
+                    DigestMethod.SHA1,
                     CanonicalizationMethod.INCLUSIVE,
                     KeyInfoType.KeyName,
                     Content.Text,
@@ -325,6 +427,12 @@
         }
     }
 
+    // Do not test on all combinations.
+    private static boolean isMajor(String signatureMethod, String digestMethod) {
+        return majorDigestMethods.contains(digestMethod)
+                || majorSignatureMethods.contains(signatureMethod);
+    }
+
     private static void setup() throws Exception {
         fac = XMLSignatureFactory.getInstance();
         kifac = fac.getKeyInfoFactory();
@@ -345,11 +453,17 @@
             (CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null);
         dsaSha1 = fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
         dsaSha256 = fac.newSignatureMethod(DSA_SHA256, null);
+
         sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
+        sha224 = fac.newDigestMethod(DigestMethod.SHA224, null);
         sha256 = fac.newDigestMethod(DigestMethod.SHA256, null);
-        sha384 = fac.newDigestMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#sha384", null);
+        sha384 = fac.newDigestMethod(DigestMethod.SHA384, null);
         sha512 = fac.newDigestMethod(DigestMethod.SHA512, null);
+        sha3_224 = fac.newDigestMethod(DigestMethod.SHA3_224, null);
+        sha3_256 = fac.newDigestMethod(DigestMethod.SHA3_256, null);
+        sha3_384 = fac.newDigestMethod(DigestMethod.SHA3_384, null);
+        sha3_512 = fac.newDigestMethod(DigestMethod.SHA3_512, null);
+
         dsa1024 = kifac.newKeyInfo(Collections.singletonList
             (kifac.newKeyValue(validatingKey)));
         dsa2048 = kifac.newKeyInfo(Collections.singletonList
@@ -358,21 +472,39 @@
             (kifac.newKeyValue(getPublicKey("RSA", 512))));
         rsa1024 = kifac.newKeyInfo(Collections.singletonList
             (kifac.newKeyValue(getPublicKey("RSA", 1024))));
+        rsa2048 = kifac.newKeyInfo(Collections.singletonList
+                (kifac.newKeyValue(getPublicKey("RSA", 2048))));
         p256ki = kifac.newKeyInfo(Collections.singletonList
             (kifac.newKeyValue(getECPublicKey("P256"))));
         p384ki = kifac.newKeyInfo(Collections.singletonList
             (kifac.newKeyValue(getECPublicKey("P384"))));
         p521ki = kifac.newKeyInfo(Collections.singletonList
             (kifac.newKeyValue(getECPublicKey("P521"))));
+
         rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
-        rsaSha256 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
-        rsaSha384 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", null);
-        rsaSha512 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", null);
-        ecdsaSha1 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", null);
+        rsaSha224 = fac.newSignatureMethod(SignatureMethod.RSA_SHA224, null);
+        rsaSha256 = fac.newSignatureMethod(SignatureMethod.RSA_SHA256, null);
+        rsaSha384 = fac.newSignatureMethod(SignatureMethod.RSA_SHA384, null);
+        rsaSha512 = fac.newSignatureMethod(SignatureMethod.RSA_SHA512, null);
+
+        rsaSha1mgf1 = fac.newSignatureMethod(SignatureMethod.SHA1_RSA_MGF1, null);
+        rsaSha224mgf1 = fac.newSignatureMethod(SignatureMethod.SHA224_RSA_MGF1, null);
+        rsaSha256mgf1 = fac.newSignatureMethod(SignatureMethod.SHA256_RSA_MGF1, null);
+        rsaSha384mgf1 = fac.newSignatureMethod(SignatureMethod.SHA384_RSA_MGF1, null);
+        rsaSha512mgf1 = fac.newSignatureMethod(SignatureMethod.SHA512_RSA_MGF1, null);
+
+        ecdsaSha1 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA1, null);
+        ecdsaSha224 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA224, null);
+        ecdsaSha256 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA256, null);
+        ecdsaSha384 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA384, null);
+        ecdsaSha512 = fac.newSignatureMethod(SignatureMethod.ECDSA_SHA512, null);
+
+        hmacSha1 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA1, null);
+        hmacSha224 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA224, null);
+        hmacSha256 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA256, null);
+        hmacSha384 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA384, null);
+        hmacSha512 = fac.newSignatureMethod(SignatureMethod.HMAC_SHA512, null);
+
         sks = new KeySelectors.SecretKeySelector("secret".getBytes("ASCII"));
 
         httpUd = new HttpURIDereferencer();
@@ -459,8 +591,6 @@
     static void test_create_signature_enveloping_hmac_sha1_40()
         throws Exception {
         System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml");
-        SignatureMethod hmacSha1 = fac.newSignatureMethod
-            (SignatureMethod.HMAC_SHA1, new HMACParameterSpec(40));
         try {
             test_create_signature_enveloping(sha1, hmacSha1, null,
                 getSecretKey("secret".getBytes("ASCII")), sks, false);
@@ -475,18 +605,22 @@
     static void test_create_signature_enveloping_hmac_sha256()
         throws Exception {
         System.out.println("* Generating signature-enveloping-hmac-sha256.xml");
-        SignatureMethod hmacSha256 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null);
         test_create_signature_enveloping(sha1, hmacSha256, null,
             getSecretKey("secret".getBytes("ASCII")), sks, false);
         System.out.println();
     }
 
+    static void test_create_signature_enveloping_hmac_sha224()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-hmac-sha224.xml");
+        test_create_signature_enveloping(sha1, hmacSha224, null,
+                getSecretKey("secret".getBytes("ASCII")), sks, false);
+        System.out.println();
+    }
+
     static void test_create_signature_enveloping_hmac_sha384()
         throws Exception {
         System.out.println("* Generating signature-enveloping-hmac-sha384.xml");
-        SignatureMethod hmacSha384 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null);
         test_create_signature_enveloping(sha1, hmacSha384, null,
             getSecretKey("secret".getBytes("ASCII")), sks, false);
         System.out.println();
@@ -495,8 +629,6 @@
     static void test_create_signature_enveloping_hmac_sha512()
         throws Exception {
         System.out.println("* Generating signature-enveloping-hmac-sha512.xml");
-        SignatureMethod hmacSha512 = fac.newSignatureMethod
-            ("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null);
         test_create_signature_enveloping(sha1, hmacSha512, null,
             getSecretKey("secret".getBytes("ASCII")), sks, false);
         System.out.println();
@@ -517,6 +649,46 @@
         System.out.println();
     }
 
+    static void test_create_signature_enveloping_sha224_rsa_sha256()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha224-rsa_sha256.xml");
+        test_create_signature_enveloping(sha224, rsaSha256, rsa,
+                getPrivateKey("RSA", 512), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha3_224_rsa_sha256()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha3_224-rsa_sha256.xml");
+        test_create_signature_enveloping(sha3_224, rsaSha256, rsa,
+                getPrivateKey("RSA", 512), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha3_256_rsa_sha256()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha3_256-rsa_sha256.xml");
+        test_create_signature_enveloping(sha3_256, rsaSha256, rsa,
+                getPrivateKey("RSA", 512), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha3_384_rsa_sha256()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha3_384-rsa_sha256.xml");
+        test_create_signature_enveloping(sha3_384, rsaSha256, rsa,
+                getPrivateKey("RSA", 512), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha3_512_rsa_sha256()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha3_512-rsa_sha256.xml");
+        test_create_signature_enveloping(sha3_512, rsaSha256, rsa,
+                getPrivateKey("RSA", 512), kvks, false);
+        System.out.println();
+    }
+
     static void test_create_signature_enveloping_sha512_rsa_sha384()
         throws Exception {
         System.out.println("* Generating signature-enveloping-sha512-rsa_sha384.xml");
@@ -525,6 +697,14 @@
         System.out.println();
     }
 
+    static void test_create_signature_enveloping_sha512_rsa_sha224()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha224.xml");
+        test_create_signature_enveloping(sha512, rsaSha224, rsa1024,
+                getPrivateKey("RSA", 1024), kvks, false);
+        System.out.println();
+    }
+
     static void test_create_signature_enveloping_sha512_rsa_sha512()
         throws Exception {
         System.out.println("* Generating signature-enveloping-sha512-rsa_sha512.xml");
@@ -533,6 +713,46 @@
         System.out.println();
     }
 
+    static void test_create_signature_enveloping_sha512_rsa_sha1_mgf1()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha1_mgf1.xml");
+        test_create_signature_enveloping(sha512, rsaSha1mgf1, rsa1024,
+                getPrivateKey("RSA", 1024), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha512_rsa_sha224_mgf1()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha224_mgf1.xml");
+        test_create_signature_enveloping(sha512, rsaSha224mgf1, rsa1024,
+                getPrivateKey("RSA", 1024), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha512_rsa_sha256_mgf1()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha256_mgf1.xml");
+        test_create_signature_enveloping(sha512, rsaSha256mgf1, rsa1024,
+                getPrivateKey("RSA", 1024), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha512_rsa_sha384_mgf1()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha384_mgf1.xml");
+        test_create_signature_enveloping(sha512, rsaSha384mgf1, rsa1024,
+                getPrivateKey("RSA", 1024), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_sha512_rsa_sha512_mgf1()
+            throws Exception {
+        System.out.println("* Generating signature-enveloping-sha512-rsa_sha512_mgf1.xml");
+        test_create_signature_enveloping(sha512, rsaSha512mgf1, rsa2048,
+                getPrivateKey("RSA", 2048), kvks, false);
+        System.out.println();
+    }
+
     static void test_create_signature_enveloping_p256_sha1() throws Exception {
         System.out.println("* Generating signature-enveloping-p256-sha1.xml");
         test_create_signature_enveloping(sha1, ecdsaSha1, p256ki,
@@ -540,6 +760,34 @@
         System.out.println();
     }
 
+    static void test_create_signature_enveloping_p256_sha224() throws Exception {
+        System.out.println("* Generating signature-enveloping-p256-sha224.xml");
+        test_create_signature_enveloping(sha1, ecdsaSha224, p256ki,
+                getECPrivateKey("P256"), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_p256_sha256() throws Exception {
+        System.out.println("* Generating signature-enveloping-p256-sha256.xml");
+        test_create_signature_enveloping(sha1, ecdsaSha256, p256ki,
+                getECPrivateKey("P256"), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_p256_sha384() throws Exception {
+        System.out.println("* Generating signature-enveloping-p256-sha384.xml");
+        test_create_signature_enveloping(sha1, ecdsaSha384, p256ki,
+                getECPrivateKey("P256"), kvks, false);
+        System.out.println();
+    }
+
+    static void test_create_signature_enveloping_p256_sha512() throws Exception {
+        System.out.println("* Generating signature-enveloping-p256-sha512.xml");
+        test_create_signature_enveloping(sha1, ecdsaSha512, p256ki,
+                getECPrivateKey("P256"), kvks, false);
+        System.out.println();
+    }
+
     static void test_create_signature_enveloping_p384_sha1() throws Exception {
         System.out.println("* Generating signature-enveloping-p384-sha1.xml");
         test_create_signature_enveloping(sha1, ecdsaSha1, p384ki,
@@ -1119,8 +1367,7 @@
 
         // create reference 1
         refs.add(fac.newReference
-            ("#xpointer(id('to-be-signed'))",
-             fac.newDigestMethod(DigestMethod.SHA1, null),
+            ("#xpointer(id('to-be-signed'))", sha1,
              Collections.singletonList
                 (fac.newTransform(CanonicalizationMethod.EXCLUSIVE,
                  (TransformParameterSpec) null)),
@@ -1132,16 +1379,14 @@
         prefixList.add("#default");
         ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
         refs.add(fac.newReference
-            ("#xpointer(id('to-be-signed'))",
-             fac.newDigestMethod(DigestMethod.SHA1, null),
+            ("#xpointer(id('to-be-signed'))", sha1,
              Collections.singletonList
                 (fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),
              null, null));
 
         // create reference 3
         refs.add(fac.newReference
-            ("#xpointer(id('to-be-signed'))",
-             fac.newDigestMethod(DigestMethod.SHA1, null),
+            ("#xpointer(id('to-be-signed'))", sha1,
              Collections.singletonList(fac.newTransform
                 (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                  (TransformParameterSpec) null)),
@@ -1153,8 +1398,7 @@
         prefixList.add("#default");
         params = new ExcC14NParameterSpec(prefixList);
         refs.add(fac.newReference
-            ("#xpointer(id('to-be-signed'))",
-             fac.newDigestMethod(DigestMethod.SHA1, null),
+            ("#xpointer(id('to-be-signed'))", sha1,
              Collections.singletonList(fac.newTransform
                 (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)),
              null, null));
@@ -1164,7 +1408,7 @@
             fac.newCanonicalizationMethod
                 (CanonicalizationMethod.EXCLUSIVE,
                  (C14NMethodParameterSpec) null),
-            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
+                    dsaSha1, refs);
 
         // create KeyInfo
         List<XMLStructure> kits = new ArrayList<>(2);
@@ -1222,8 +1466,7 @@
         types.add(new XPathType(" //ReallyToBeSigned ",
             XPathType.Filter.UNION));
         XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
-        refs.add(fac.newReference
-            ("", fac.newDigestMethod(DigestMethod.SHA1, null),
+        refs.add(fac.newReference("", sha1,
              Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)),
              null, null));
 
@@ -1235,15 +1478,14 @@
             (Collections.singletonList
                 (new XPathType(" / ", XPathType.Filter.UNION)));
         trans2.add(fac.newTransform(Transform.XPATH2, xp2));
-        refs.add(fac.newReference("#signature-value",
-            fac.newDigestMethod(DigestMethod.SHA1, null), trans2, null, null));
+        refs.add(fac.newReference("#signature-value", sha1, trans2, null, null));
 
         // create SignedInfo
         SignedInfo si = fac.newSignedInfo(
             fac.newCanonicalizationMethod
                 (CanonicalizationMethod.INCLUSIVE,
                  (C14NMethodParameterSpec) null),
-            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
+                    dsaSha1, refs);
 
         // create KeyInfo
         List<XMLStructure> kits = new ArrayList<>(2);
@@ -1306,28 +1548,26 @@
         System.out.println();
     }
 
-    static void test_create_detached_signature(String canonicalizationMethod,
-            String signatureMethod, String transform, KeyInfoType keyInfo,
+    // Only print if there is an error.
+    static void test_create_detached_signature(
+            String canonicalizationMethod, String signatureMethod,
+            String digestMethod, 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()));
+        String title = "\nTest detached signature:"
+                + "\n    Canonicalization method: " + canonicalizationMethod
+                + "\n    Signature method: " + signatureMethod
+                + "\n    Transform: " + transform
+                + "\n    Digest method: " + digestMethod
+                + "\n    KeyInfoType: " + keyInfo
+                + "\n    Content type: " + contentType
+                + "\n    Expected failure: " + (expectedFailure ? "yes" : "no")
+                + "\n    Expected exception: " + (expectedException == null ?
+                            "no" : expectedException.getName());
 
         try {
-            boolean success = test_create_detached_signature(
+            boolean success = test_create_detached_signature0(
                     canonicalizationMethod,
                     signatureMethod,
                     digestMethod,
@@ -1337,12 +1577,15 @@
                     port);
 
             if (success && expectedFailure) {
+                System.out.println(title);
                 System.out.println("Signature validation unexpectedly passed");
                 result = false;
             } else if (!success && !expectedFailure) {
+                System.out.println(title);
                 System.out.println("Signature validation unexpectedly failed");
                 result = false;
             } else if (expectedException != null) {
+                System.out.println(title);
                 System.out.println("Expected " + expectedException
                         + " not thrown");
                 result = false;
@@ -1350,23 +1593,21 @@
         } catch (Exception e) {
             if (expectedException == null
                     || !e.getClass().isAssignableFrom(expectedException)) {
+                System.out.println(title);
                 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,
+    // Print out as little as possible. This method will be called many times.
+    static boolean test_create_detached_signature0(String canonicalizationMethod,
             String signatureMethod, String digestMethod, String transform,
             KeyInfoType keyInfo, Content contentType, int port)
             throws Exception {
 
-        System.out.print("Sign ...");
+        System.out.print("-S");
 
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
@@ -1410,20 +1651,34 @@
 
         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:
+        if (signatureMethod.contains("#hmac-")) {
+            // http://...#hmac-sha1 -> hmac-sha1 -> hmacsha1
+            String algName = signatureMethod
+                    .substring(signatureMethod.indexOf('#') + 1)
+                    .replace("-", "");
+            KeyGenerator kg = KeyGenerator.getInstance(algName);
+            signingKey = kg.generateKey();
+            validationKey = signingKey;
+        } else {
+            KeyPairGenerator kpg;
+            SecureRandom random = new SecureRandom();
+            if (signatureMethod.contains("#rsa-")
+                    || signatureMethod.contains("-rsa-MGF1")) {
+                kpg = KeyPairGenerator.getInstance("RSA");
+                kpg.initialize(signatureMethod.contains("#sha512-rsa-MGF1")
+                        ? 2048 : 1024, random);
+            } else if (signatureMethod.contains("#dsa-")) {
+                kpg = KeyPairGenerator.getInstance("DSA");
+                kpg.initialize(1024, random);
+            } else if (signatureMethod.contains("#ecdsa-")) {
+                kpg = KeyPairGenerator.getInstance("EC");
+                kpg.initialize(256, random);
+            } else {
                 throw new RuntimeException("Unsupported signature algorithm");
+            }
+            KeyPair kp = kpg.generateKeyPair();
+            validationKey = kp.getPublic();
+            signingKey = kp.getPrivate();
         }
 
         SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
@@ -1464,7 +1719,7 @@
             signatureString = writer.toString();
         }
 
-        System.out.print("Validate ... ");
+        System.out.print("V");
         try (ByteArrayInputStream bis = new ByteArrayInputStream(
                 signatureString.getBytes())) {
             doc = dbf.newDocumentBuilder().parse(bis);
@@ -1487,13 +1742,13 @@
 
         boolean success = signature.validate(vc);
         if (!success) {
-            System.out.println("Core signature validation failed");
+            System.out.print("x");
             return false;
         }
 
         success = signature.getSignatureValue().validate(vc);
         if (!success) {
-            System.out.println("Cryptographic validation of signature failed");
+            System.out.print("X");
             return false;
         }
 
@@ -1547,6 +1802,26 @@
         "237008997971129772408397621801631622129297063463868593083106979716" +
         "204903524890556839550490384015324575598723478554854070823335021842" +
         "210112348400928769";
+    private static final String RSA_2048_MOD = "243987087691547796017401146540"
+        + "9844666035826535295137885613771811531602666348704672255163984907599"
+        + "4298308997053582963763109207465354916871136820987101812436158377530"
+        + "6117270010853232249007544652859474372258057062943608962079402484091"
+        + "8121307687901225514249308620012025884376216406019656605767311580224"
+        + "4715304950770504195751384382230005665573033547124060755957932161045"
+        + "7288008201789401237690181537646952377591671113513382933711547044631"
+        + "6055957820531234310030119265612054594720774653570278810236807313332"
+        + "5293876225940483622056721445101719346295263740434720907474414905706"
+        + "086605825077661246082956613711071075569880930102141";
+    private static final String RSA_2048_PRIV = "12265063405401593206575340300"
+        + "5824698296458954796982342251774894076489082263237675553422307220014"
+        + "4395010131540855227949365446755185799985229111139387016816011165826"
+        + "5498929552020323994756478872375078784799489891112924298115119573429"
+        + "3677627114115546751555523555375278381312502020990154549150867571006"
+        + "4470674155961982582802981649643127000520693025433874996570667724459"
+        + "3395670697152709457274026580106078581585077146782827694403672461289"
+        + "9143004401242754355097671446183871158504602884373174300123820136505"
+        + "6449932139773607305129273545117363975014750743804523418307647791195"
+        + "6408859873123458434820062206102268853256685162004893";
     private static final String EC_P256_X =
         "335863644451761614592446380116804721648611739647823420286081723541" +
         "6166183710";
@@ -1632,6 +1907,9 @@
             } else if (keysize == 1024) {
                 kspec = new RSAPublicKeySpec(new BigInteger(RSA_1024_MOD),
                                              new BigInteger(RSA_PUB));
+            } else if (keysize == 2048) {
+                kspec = new RSAPublicKeySpec(new BigInteger(RSA_2048_MOD),
+                                             new BigInteger(RSA_PUB));
             } else throw new RuntimeException("Unsupported keysize:" + keysize);
         } else throw new RuntimeException("Unsupported key algorithm " + algo);
         return kf.generatePublic(kspec);
@@ -1684,10 +1962,13 @@
             if (keysize == 512) {
                 kspec = new RSAPrivateKeySpec
                     (new BigInteger(RSA_MOD), new BigInteger(RSA_PRIV));
-            } else {
+            } else if (keysize == 1024) {
                 kspec = new RSAPrivateKeySpec(new BigInteger(RSA_1024_MOD),
-                                              new BigInteger(RSA_1024_PRIV));
-            }
+                        new BigInteger(RSA_1024_PRIV));
+            } else if (keysize == 2048) {
+                kspec = new RSAPrivateKeySpec(new BigInteger(RSA_2048_MOD),
+                        new BigInteger(RSA_2048_PRIV));
+            } else throw new RuntimeException("Unsupported key algorithm " + algo);
         } else throw new RuntimeException("Unsupported key algorithm " + algo);
         return kf.generatePrivate(kspec);
     }
@@ -1724,25 +2005,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.
--- a/test/jdk/javax/xml/crypto/dsig/KeySelectors.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/javax/xml/crypto/dsig/KeySelectors.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,14 +30,7 @@
 import javax.crypto.SecretKey;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.*;
 import javax.xml.crypto.dsig.keyinfo.*;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.DocumentBuilder;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.Element;
-import org.w3c.dom.traversal.*;
 import sun.security.util.DerValue;
 import sun.security.x509.X500Name;
 
@@ -167,26 +160,11 @@
         }
 
         static boolean algEquals(String algURI, String algName) {
-            if (algName.equalsIgnoreCase("DSA") &&
-                algURI.equals(SignatureMethod.DSA_SHA1) ||
-                algURI.equals("http://www.w3.org/2009/xmldsig11#dsa-sha256")) {
-                return true;
-            } else if (algName.equalsIgnoreCase("RSA") &&
-                (algURI.equals(SignatureMethod.RSA_SHA1) ||
-                 algURI.equals
-                    ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") ||
-                 algURI.equals
-                    ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384") ||
-                 algURI.equals
-                    ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"))) {
-                return true;
-            } else if (algName.equalsIgnoreCase("EC") &&
-                (algURI.equals
-                    ("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"))) {
-                return true;
-            } else {
-                return false;
-            }
+            algName = algName.toUpperCase(Locale.ROOT);
+            return algName.equals("DSA") && algURI.contains("#dsa-")
+                    || algName.equals("RSA")
+                            && (algURI.contains("#rsa-") || algURI.contains("-rsa-MGF1"))
+                    || algName.equals("EC") && algURI.contains("#ecdsa-");
         }
     }
 
--- a/test/jdk/jdk/jfr/event/runtime/TestClassLoadEvent.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/jdk/jfr/event/runtime/TestClassLoadEvent.java	Tue Jun 19 16:33:07 2018 +0100
@@ -47,7 +47,7 @@
 public final class TestClassLoadEvent {
 
     private final static String TEST_CLASS_NAME = "jdk.jfr.event.runtime.TestClasses";
-    private final static String BOOT_CLASS_LOADER_NAME = "boot";
+    private final static String BOOT_CLASS_LOADER_NAME = "bootstrap";
     private final static String SEARCH_CLASS_NAME = "java.lang.Object";
     private final static String SEARCH_PACKAGE_NAME = "java/lang";
     private final static String SEARCH_MODULE_NAME = "java.base";
--- a/test/jdk/jdk/modules/etc/UpgradeableModules.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/jdk/modules/etc/UpgradeableModules.java	Tue Jun 19 16:33:07 2018 +0100
@@ -44,14 +44,9 @@
 public class UpgradeableModules {
     private static final List<String> UPGRADEABLE_MODULES =
         List.of("java.compiler",
-                "java.jnlp",
+                "jdk.aot",
                 "jdk.internal.vm.compiler",
-                "jdk.internal.vm.compiler.management",
-                "jdk.deploy",
-                "jdk.javaws",
-                "jdk.plugin",
-                "jdk.plugin.dom"
-                );
+                "jdk.internal.vm.compiler.management");
 
     public static void main(String... args) {
         Set<String> hashedModules = hashedModules();
--- a/test/jdk/sanity/releaseFile/CheckSource.java	Tue Jun 19 16:08:39 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,120 +0,0 @@
-
-/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * 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 8193660
- * @summary Check SOURCE line in "release" file for closedjdk
- * @run main CheckSource
- */
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-public class CheckSource {
-
-    CheckSource(String dataFile, boolean isOpenJDK) {
-        // Read data files
-        readFile(dataFile, isOpenJDK);
-    }
-
-    private void readFile(String fileName, boolean isOpenJDK) {
-        String fishForSOURCE = null;
-
-        File file = new File(fileName);
-
-        // open the stream to read in for Entries
-        try (BufferedReader buffRead =
-            new BufferedReader(new FileReader(fileName))) {
-
-            // this is the string read
-            String readIn;
-
-            // let's read some strings!
-            while ((readIn = buffRead.readLine()) != null) {
-                readIn = readIn.trim();
-
-                // throw out blank lines
-                if (readIn.length() == 0)
-                    continue;
-
-                // grab SOURCE line
-                if (readIn.startsWith("SOURCE=")) {
-                    fishForSOURCE = readIn;
-                    break;
-                }
-            }
-        } catch (FileNotFoundException fileExcept) {
-            throw new RuntimeException("File " + fileName +
-                                       " not found reading data!", fileExcept);
-        } catch (IOException ioExcept) {
-            throw new RuntimeException("Unexpected problem reading data!",
-                                       ioExcept);
-        }
-
-        // was SOURCE even found?
-        if (fishForSOURCE == null) {
-            throw new RuntimeException("SOURCE line was not found!");
-        } else {
-            // OK it was found, did it have correct sources?
-            System.out.println("The source string found: " + fishForSOURCE);
-
-            // First it MUST have .: regardless of closed or openJDK
-            if (!fishForSOURCE.contains(".:")) {
-                throw new RuntimeException("The test failed, .: not found!");
-            }
-            // take out the .: source path
-            fishForSOURCE = fishForSOURCE.replace(".:", "");
-
-            // if its closedJDK it MUST have open:
-            if (!isOpenJDK && !fishForSOURCE.contains("open:")) {
-                throw new RuntimeException("The test failed, open: not found!");
-            }
-            // take out the open: source path
-            fishForSOURCE = fishForSOURCE.replace("open:", "");
-
-            // if any other source exists, that's an error
-            if (fishForSOURCE.contains(":")) {
-                throw new RuntimeException("The test failed, additional sources found!");
-            }
-        }
-
-        // Everything was fine
-        System.out.println("The test passed!");
-    }
-
-    public static void main(String args[]) {
-        String jdkPath = System.getProperty("test.jdk");
-        String runtime = System.getProperty("java.runtime.name");
-
-        System.out.println("JDK Path : " + jdkPath);
-        System.out.println("Runtime Name : " + runtime);
-
-        new CheckSource(jdkPath + "/release",
-                              runtime.contains("OpenJDK"));
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/tools/jar/DeprecateOptionN.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8199871
+ * @modules jdk.jartool
+ * @summary jar -n should print out deprecation warning
+ * @run testng DeprecateOptionN
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.spi.ToolProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+public class DeprecateOptionN {
+    private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar")
+            .orElseThrow(() ->
+                    new RuntimeException("jar tool not found")
+            );
+
+    protected static String jar(String... options) {
+        StringWriter writer = new StringWriter();
+        PrintWriter pw = new PrintWriter(writer);
+
+        JAR_TOOL.run(pw, pw, options);
+        String output = writer.toString();
+        System.err.println(output);
+        return output;
+    }
+
+    @Test
+    public void helpCompatWithWarning() {
+        String output = jar("--help:compat");
+        assertTrue(output.contains("this option is deprecated, and is planned for removal in a future JDK release"));
+    }
+
+    @Test
+    public void helpExtraWithWarning() {
+        String output = jar("--help-extra");
+        assertTrue(output.contains("This option is deprecated, and is"));
+        assertTrue(output.contains("planned for removal in a future JDK release"));
+    }
+
+    @Test
+    public void normalizeWithWarning() throws IOException {
+        File tmp = File.createTempFile("test", null);
+        String output = jar("cnf", "test.jar", tmp.getAbsolutePath());
+        tmp.delete();
+        assertTrue(output.contains("Warning: The -n option is deprecated, and is planned for removal in a future JDK release"));
+    }
+
+    @Test
+    public void NoWarningWithoutN() throws IOException {
+        File tmp = File.createTempFile("test", null);
+        String output = jar("cf", "test.jar", tmp.getAbsolutePath());
+        tmp.delete();
+        assertFalse(output.contains("Warning: The -n option is deprecated, and is planned for removal in a future JDK release"));
+    }
+
+
+    @Test
+    public void SuppressWarning() throws IOException {
+        File tmp = File.createTempFile("test", null);
+        String output = jar("-c", "-n", "-XDsuppress-tool-removal-message",
+                "-f", "test.jar", tmp.getAbsolutePath());
+        tmp.delete();
+        assertFalse(output.contains("Warning: The -n option is deprecated, and is planned for removal in a future JDK release"));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/tools/pack200/DeprecatePack200.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 8199871
+ * @summary pack200 and unpack200 should print out deprecate warning
+ * @modules jdk.pack
+ * @compile -XDignore.symbol.file Utils.java
+ * @run testng DeprecatePack200
+ */
+
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+public class DeprecatePack200 {
+    final static String PACK200_CMD = Utils.getPack200Cmd();
+    final static String UNPACK200_CMD = Utils.getUnpack200Cmd();
+    final static Predicate<String> PACK200_MSG = Pattern.compile(
+            "Warning: The pack200(\\.exe)?? tool is deprecated, and is planned for removal in a future JDK release.")
+            .asMatchPredicate();
+    final static Predicate<String> UNPACK200_MSG = Pattern.compile(
+            "Warning: The unpack200(\\.exe)?? tool is deprecated, and is planned for removal in a future JDK release.")
+            .asMatchPredicate();
+
+    @DataProvider(name="tools")
+    public static final Object[][] provide() { return cases; }
+
+    private static final Object[][] cases = {
+        { PACK200_MSG, 1, List.of(PACK200_CMD) },
+        { PACK200_MSG, 1, List.of(PACK200_CMD, "-V") },
+        { PACK200_MSG, 2, List.of(PACK200_CMD, "--help") },
+        { PACK200_MSG, 0, List.of(PACK200_CMD, "-XDsuppress-tool-removal-message") },
+        { PACK200_MSG, 0, List.of(PACK200_CMD, "--version", "-XDsuppress-tool-removal-message") },
+        { PACK200_MSG, 0, List.of(PACK200_CMD, "-h", "-XDsuppress-tool-removal-message") },
+
+        { UNPACK200_MSG, 1, List.of(UNPACK200_CMD) },
+        { UNPACK200_MSG, 1, List.of(UNPACK200_CMD, "-V") },
+        { UNPACK200_MSG, 1, List.of(UNPACK200_CMD, "--help") },
+        { UNPACK200_MSG, 0, List.of(UNPACK200_CMD, "-XDsuppress-tool-removal-message") },
+        { UNPACK200_MSG, 0, List.of(UNPACK200_CMD, "--version", "-XDsuppress-tool-removal-message") },
+        { UNPACK200_MSG, 0, List.of(UNPACK200_CMD, "-h", "-XDsuppress-tool-removal-message") }
+    };
+
+    @Test(dataProvider = "tools")
+    public void CheckWarnings(Predicate<String> msg, long count, List<String> cmd) {
+        List<String> output = Utils.runExec(cmd, null, true);
+        assertEquals(output.stream().filter(msg).count(), count);
+    }
+}
--- a/test/jdk/tools/pack200/Utils.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jdk/tools/pack200/Utils.java	Tue Jun 19 16:33:07 2018 +0100
@@ -497,6 +497,10 @@
     }
 
     static List<String> runExec(List<String> cmdsList, Map<String, String> penv) {
+        return runExec(cmdsList, penv, false);
+    }
+
+    static List<String> runExec(List<String> cmdsList, Map<String, String> penv, boolean ignoreReturnValue) {
         ArrayList<String> alist = new ArrayList<String>();
         ProcessBuilder pb =
                 new ProcessBuilder(cmdsList);
@@ -529,7 +533,7 @@
                 in = rd.readLine();
             }
             retval = p.waitFor();
-            if (retval != 0) {
+            if (!ignoreReturnValue && retval != 0) {
                 throw new RuntimeException("process failed with non-zero exit");
             }
         } catch (Exception ex) {
--- a/test/jtreg-ext/requires/VMProps.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/jtreg-ext/requires/VMProps.java	Tue Jun 19 16:33:07 2018 +0100
@@ -22,7 +22,10 @@
  */
 package requires;
 
+import java.io.BufferedInputStream;
+import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
@@ -31,6 +34,7 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Properties;
 import java.util.concurrent.Callable;
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
@@ -80,6 +84,7 @@
         // vm.graal.enabled is true if Graal is used as JIT
         map.put("vm.graal.enabled", isGraalEnabled());
         map.put("docker.support", dockerSupport());
+        map.put("release.implementor", implementor());
         vmGC(map); // vm.gc.X = true/false
         vmOptFinalFlags(map);
 
@@ -396,6 +401,18 @@
     }
 
 
+    private String implementor() {
+        try (InputStream in = new BufferedInputStream(new FileInputStream(
+                System.getProperty("java.home") + "/release"))) {
+            Properties properties = new Properties();
+            properties.load(in);
+            return properties.getProperty("IMPLEMENTOR").replace("\"", "");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
 
     /**
      * Dumps the map to the file if the file name is given as the property.
--- a/test/langtools/ProblemList.txt	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/langtools/ProblemList.txt	Tue Jun 19 16:33:07 2018 +0100
@@ -26,7 +26,6 @@
 ###########################################################################
 #
 # javadoc
-jdk/javadoc/tool/VerifyLocale.java                                              8149565    generic-all    -locale option issues
 jdk/javadoc/tool/enum/docComments/Main.java                                     8152313    generic-all    convert to doclet test framework
 jdk/javadoc/tool/enum/enumType/Main.java                                        8152313    generic-all    convert to doclet test framework
 jdk/javadoc/tool/varArgs/Main.java                                              8152313    generic-all    convert to doclet test framework
--- a/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java	Tue Jun 19 16:33:07 2018 +0100
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug      4764045 8004825 8026567 8191030
+ * @bug      4764045 8004825 8026567 8191030 8204330
  * @summary  This test ensures that the value tag works in all
  *           use cases, the tests are explained below.
  * @author   jamieh
@@ -33,6 +33,12 @@
  * @run main TestValueTag
  */
 
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
 public class TestValueTag extends JavadocTester {
 
     public static void main(String... args) throws Exception {
@@ -110,7 +116,7 @@
         checkForException();
     }
 
-    @Test()
+    @Test
     void test2() {
         javadoc("-Xdoclint:none",
                 "-d", "out2",
@@ -133,7 +139,7 @@
         checkForException();
     }
 
-    @Test()
+    @Test
     void test3() {
         javadoc("-d", "out3",
                 "-sourcepath", testSrc,
@@ -146,10 +152,37 @@
                 "The value2 is <a href=\"#CONSTANT\">\"constant\"</a>.",
                 "The value3 is <a href=\"../pkg2/Class3.html#TEST_12_PASSES\">"
                 + "\"Test 12 passes\"</a>.");
+        checkForException();
+    }
+
+    @Test
+    void test4() throws IOException {
+        Path base = Paths.get("test4");
+        Path src = base.resolve("src");
+        Files.createDirectories(src.resolve("p"));
+        Files.write(src.resolve("p").resolve("C.java"), List.of(
+                "package p;",
+                "/** This class defines specialChars: {@value C#specialChars}. */",
+                "public class C {",
+                "    /** The value is {@value}. */",
+                "    public static final String specialChars = \"abc < def & ghi > jkl\";",
+                "}"));
+
+        javadoc("-d", base.resolve("out").toString(),
+                "-sourcepath", src.toString(),
+                "p");
+        checkExit(Exit.OK);
+        checkOutput("p/C.html", false,
+                "The value is \"abc < def & ghi > jkl\".");
+        checkOutput("p/C.html", true,
+                "The value is \"abc &lt; def &amp; ghi &gt; jkl\".");
+
+        checkForException();
     }
 
 
     void checkForException() {
         checkOutput(Output.STDERR, false, "DocletAbortException");
+        checkOutput(Output.STDERR, false, "IllegalArgumentException");
     }
 }
--- a/test/langtools/jdk/javadoc/tool/VerifyLocale.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/langtools/jdk/javadoc/tool/VerifyLocale.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,18 +23,24 @@
 
 /*
  * @test
- * @bug 8035473
+ * @bug 8035473 8149565
  * @summary Verify that init method works correctly.
  * @modules jdk.javadoc/jdk.javadoc.internal.tool
- * @ignore 8149565
  */
 
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.Collections;
+import java.util.List;
 import java.util.Locale;
 import java.util.Set;
 
 import javax.lang.model.SourceVersion;
 import javax.tools.Diagnostic.Kind;
+import javax.tools.DocumentationTool;
+import javax.tools.DocumentationTool.DocumentationTask;
+import javax.tools.JavaFileObject;
+import javax.tools.ToolProvider;
 
 import jdk.javadoc.doclet.Doclet;
 import jdk.javadoc.doclet.Reporter;
@@ -49,30 +55,54 @@
     Reporter reporter;
 
     public static void main(String[] args) {
-        String thisFile = "" +
-            new java.io.File(System.getProperty("test.src", "."),
-                             "VerifyLocale.java");
+        DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
+        Path thisFile =
+            Paths.get(System.getProperty("test.src", ".")).resolve("VerifyLocale.java");
+        JavaFileObject fo = tool.getStandardFileManager(null, null, null)
+                .getJavaFileObjects(thisFile).iterator().next();
+
+        int skipCount = 0;
+        int testCount = 0;
 
         for (Locale loc : Locale.getAvailableLocales()) {
+
             language = loc.getLanguage();
             country = loc.getCountry();
             variant = loc.getVariant();
+            System.err.printf("test locale: %s [%s,%s,%s] %s%n",
+                loc, language, country, variant, loc.toLanguageTag());
+
+            // skip locales for which the round-trip fails
+            if (!loc.equals(Locale.forLanguageTag(loc.toLanguageTag()))) {
+                System.err.println("skipped " + loc + "!");
+                System.err.println();
+                skipCount++;
+                continue;
+            }
+
             if (!language.equals("")) {
-                String[] command_line = {
-                    // jumble the options in some weird order
-                    "-doclet", "VerifyLocale",
-                    "-locale", language + (country.equals("") ? "" : ("_" + country + (variant.equals("") ? "" : "_" + variant))),
-                    "-docletpath", System.getProperty("test.classes", "."),
-                    thisFile
-                };
-                if (jdk.javadoc.internal.tool.Main.execute(command_line) != 0)
+                List<String> options = List.of("-locale", loc.toLanguageTag());
+                System.err.println("test options: " + options);
+                DocumentationTask t = tool.getTask(null, null, null,
+                        VerifyLocale.class, options, List.of(fo));
+                if (!t.call())
                     throw new Error("Javadoc encountered warnings or errors.");
+                testCount++;
             }
+            System.err.println();
         }
+        System.err.println("Skipped " + skipCount + " locales");
+        System.err.println("Tested " + testCount + " locales");
     }
 
     public boolean run(DocletEnvironment root) {
-        reporter.print(Kind.NOTE, "just a test: Locale is: " + locale.getDisplayName());
+        reporter.print(Kind.NOTE, String.format("doclet locale is: %s [%s,%s,%s] %s (%s)",
+                locale,
+                locale.getLanguage(),
+                locale.getCountry(),
+                locale.getVariant(),
+                locale.toLanguageTag(),
+                locale.getDisplayName()));
         return language.equals(locale.getLanguage())
                && country.equals(locale.getCountry())
                && variant.equals(locale.getVariant());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/T8203338/CheckWellFormednessIntersectionTypesTest.java	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,32 @@
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 8203338
+ * @summary Unboxing in return from lambda miscompiled to throw ClassCastException
+ * @compile/fail/ref=CheckWellFormednessIntersectionTypesTest.out -XDrawDiagnostics CheckWellFormednessIntersectionTypesTest.java
+ */
+
+public class CheckWellFormednessIntersectionTypesTest {
+    class U1 {}
+    class U3 {}
+
+    class X1 extends U1 {}
+    class X3 extends U3 {}
+
+    interface SAM<P1 extends X1, P2 extends P1, P3 extends X3> {
+        P3 m(P1 p1, P2 p2);
+    }
+
+    interface I<T> {}
+
+    @SuppressWarnings("unchecked")
+    class Tester {
+        public X3 foo(X1 x1, Object x2) { return new X3(); }
+        Object method(SAM<?, ?, ?> sam) {
+            return sam.m(null, null);
+        }
+
+        Object foo() {
+            return method((SAM<?, ?, ?> & I<?>) this::foo);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/T8203338/CheckWellFormednessIntersectionTypesTest.out	Tue Jun 19 16:33:07 2018 +0100
@@ -0,0 +1,2 @@
+CheckWellFormednessIntersectionTypesTest.java:29:49: compiler.err.prob.found.req: (compiler.misc.no.suitable.functional.intf.inst: java.lang.Object&CheckWellFormednessIntersectionTypesTest.SAM<CheckWellFormednessIntersectionTypesTest.X1,java.lang.Object,CheckWellFormednessIntersectionTypesTest.X3>&CheckWellFormednessIntersectionTypesTest.I<java.lang.Object>)
+1 error
--- a/test/langtools/tools/jdeps/Options.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/langtools/tools/jdeps/Options.java	Tue Jun 19 16:33:07 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8168386
+ * @bug 8168386 8205116
  * @summary Test option validation
  * @modules jdk.jdeps
  * @library lib
@@ -89,4 +89,18 @@
         assertTrue(jdeps.run(true) != 0);
         return jdeps;
     }
+
+    @Test
+    public void testSystemOption() {
+        JdepsRunner jdeps;
+
+        // valid path
+        jdeps = new JdepsRunner("--check", "java.base", "--system", System.getProperty("java.home"));
+        assertTrue(jdeps.run(true) == 0);
+
+        // invalid path
+        jdeps = new JdepsRunner("--check", "java.base", "--system", "bad");
+        assertTrue(jdeps.run(true) != 0);
+        jdeps.outputContains("invalid path: bad");
+    }
 }
--- a/test/lib/jdk/test/lib/Platform.java	Tue Jun 19 16:08:39 2018 +0100
+++ b/test/lib/jdk/test/lib/Platform.java	Tue Jun 19 16:33:07 2018 +0100
@@ -344,8 +344,7 @@
         boolean isLinux = Platform.isLinux();
         boolean is64 = Platform.is64bit();
         boolean isSolaris = Platform.isSolaris();
-        boolean isAix = Platform.isAix();
 
-        return (is64 && (isLinux || isSolaris || isAix));
+        return (is64 && (isLinux || isSolaris));
     }
 }