--- a/.hgtags Sat Apr 13 07:22:55 2019 +0100
+++ b/.hgtags Sat Apr 13 07:23:18 2019 +0100
@@ -553,3 +553,4 @@
83cace4142c8563b6a921787db02388e1bc48d01 jdk-13+13
46cf212cdccaf4fb064d913b12004007d3322b67 jdk-13+14
f855ec13aa2501ae184c8b3e0626a8cec9966116 jdk-13+15
+9d0ae9508d5337b0dc7cc4684be42888c4023755 jdk-13+16
--- a/doc/testing.html Sat Apr 13 07:22:55 2019 +0100
+++ b/doc/testing.html Sat Apr 13 07:23:18 2019 +0100
@@ -1,19 +1,24 @@
<!DOCTYPE html>
-<html>
+<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
- <meta charset="utf-8">
- <meta name="generator" content="pandoc">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
+ <meta charset="utf-8" />
+ <meta name="generator" content="pandoc" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>Testing the JDK</title>
- <style type="text/css">code{white-space: pre;}</style>
- <link rel="stylesheet" href="../make/data/docs-resources/resources/jdk-default.css">
+ <style type="text/css">
+ code{white-space: pre-wrap;}
+ span.smallcaps{font-variant: small-caps;}
+ span.underline{text-decoration: underline;}
+ div.column{display: inline-block; vertical-align: top; width: 50%;}
+ </style>
+ <link rel="stylesheet" href="../make/data/docs-resources/resources/jdk-default.css" />
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<style type="text/css">pre, code, tt { color: #1d6ae5; }</style>
</head>
<body>
-<header>
+<header id="title-block-header">
<h1 class="title">Testing the JDK</h1>
</header>
<nav id="TOC">
@@ -34,6 +39,9 @@
<li><a href="#gtest-keywords">Gtest keywords</a></li>
<li><a href="#microbenchmark-keywords">Microbenchmark keywords</a></li>
</ul></li>
+<li><a href="#notes-for-specific-tests">Notes for Specific Tests</a><ul>
+<li><a href="#docker-tests">Docker Tests</a></li>
+</ul></li>
</ul>
</nav>
<h2 id="using-make-test-the-run-test-framework">Using "make test" (the run-test framework)</h2>
@@ -180,5 +188,11 @@
<p>Additional VM arguments to provide to forked off VMs. Same as <code>-jvmArgs <args></code></p>
<h4 id="options-2">OPTIONS</h4>
<p>Additional arguments to send to JMH.</p>
+<h2 id="notes-for-specific-tests">Notes for Specific Tests</h2>
+<h3 id="docker-tests">Docker Tests</h3>
+<p>Docker tests with default parameters may fail on systems with glibc versions not compatible with the one used in the default docker image (e.g., Oracle Linux 7.6 for x86). For example, they pass on Ubuntu 16.04 but fail on Ubuntu 18.04 if run like this on x86:</p>
+<pre><code>$ make test TEST="jtreg:test/hotspot/jtreg/containers/docker"</code></pre>
+<p>To run these tests correctly, additional parameters for the correct docker image are required on Ubuntu 18.04 by using <code>JAVA_OPTIONS</code>.</p>
+<pre><code>$ make test TEST="jtreg:test/hotspot/jtreg/containers/docker" JTREG="JAVA_OPTIONS=-Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest"</code></pre>
</body>
</html>
--- a/doc/testing.md Sat Apr 13 07:22:55 2019 +0100
+++ b/doc/testing.md Sat Apr 13 07:23:18 2019 +0100
@@ -373,6 +373,21 @@
#### OPTIONS
Additional arguments to send to JMH.
+## Notes for Specific Tests
+
+### Docker Tests
+
+Docker tests with default parameters may fail on systems with glibc versions not
+compatible with the one used in the default docker image (e.g., Oracle Linux 7.6 for x86).
+For example, they pass on Ubuntu 16.04 but fail on Ubuntu 18.04 if run like this on x86:
+
+ $ make test TEST="jtreg:test/hotspot/jtreg/containers/docker"
+
+To run these tests correctly, additional parameters for the correct docker image are
+required on Ubuntu 18.04 by using `JAVA_OPTIONS`.
+
+ $ make test TEST="jtreg:test/hotspot/jtreg/containers/docker" JTREG="JAVA_OPTIONS=-Djdk.test.docker.image.name=ubuntu -Djdk.test.docker.image.version=latest"
+
---
# Override some definitions in the global css file that are not optimal for
# this document.
--- a/make/Coverage.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/Coverage.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -49,6 +49,7 @@
-exclude 'java.lang.Object' \
-exclude 'jdk.internal.org.objectweb.**' \
-exclude jdk.test.Main -exclude '**\$Proxy*' \
+ $(JCOV_FILTERS) \
$(JCOV_TEMP)/$(JCOV_IMAGE_SUBDIR)
$(MV) $(JCOV_TEMP)/$(JCOV_IMAGE_SUBDIR) $(JCOV_IMAGE_DIR)
$(RMDIR) $(JCOV_TEMP)
--- a/make/RunTests.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/RunTests.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -1194,10 +1194,18 @@
$(call LogWarn, Stopping JCov Grabber...)
$(JAVA) -jar $(JCOV_HOME)/lib/jcov.jar GrabberManager -stop -stoptimeout 3600
+ JCOV_REPORT_TITLE := JDK code coverage report<br/>
+ ifneq ($(JCOV_FILTERS), )
+ JCOV_REPORT_TITLE += Code filters: $(JCOV_FILTERS)<br>
+ endif
+ JCOV_REPORT_TITLE += Tests: $(TEST)
+
jcov-gen-report: jcov-stop-grabber
$(call LogWarn, Generating JCov report ...)
$(JAVA) -Xmx4g -jar $(JCOV_HOME)/lib/jcov.jar RepGen -sourcepath \
`$(ECHO) $(TOPDIR)/src/*/share/classes/ | $(TR) ' ' ':'` -fmt html \
+ $(JCOV_FILTERS) \
+ -mainReportTitle "$(JCOV_REPORT_TITLE)" \
-o $(JCOV_REPORT) $(JCOV_RESULT_FILE)
TARGETS += jcov-do-start-grabber jcov-start-grabber jcov-stop-grabber \
--- a/make/autoconf/basics.m4 Sat Apr 13 07:22:55 2019 +0100
+++ b/make/autoconf/basics.m4 Sat Apr 13 07:23:18 2019 +0100
@@ -883,10 +883,11 @@
fi
if test "x$CUSTOM_ROOT" != x; then
- OUTPUTDIR="${CUSTOM_ROOT}/build/${CONF_NAME}"
+ WORKSPACE_ROOT="${CUSTOM_ROOT}"
else
- OUTPUTDIR="${TOPDIR}/build/${CONF_NAME}"
+ WORKSPACE_ROOT="${TOPDIR}"
fi
+ OUTPUTDIR="${WORKSPACE_ROOT}/build/${CONF_NAME}"
$MKDIR -p "$OUTPUTDIR"
if test ! -d "$OUTPUTDIR"; then
AC_MSG_ERROR([Could not create build directory $OUTPUTDIR])
@@ -942,6 +943,7 @@
AC_SUBST(SPEC)
AC_SUBST(CONF_NAME)
AC_SUBST(OUTPUTDIR)
+ AC_SUBST(WORKSPACE_ROOT)
AC_SUBST(CONFIGURESUPPORT_OUTPUTDIR)
# The spec.gmk file contains all variables for the make system.
--- a/make/autoconf/flags-cflags.m4 Sat Apr 13 07:22:55 2019 +0100
+++ b/make/autoconf/flags-cflags.m4 Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -799,15 +799,29 @@
$1_WARNING_CFLAGS_JVM="-Wno-format-zero-length -Wtype-limits -Wuninitialized"
fi
+ if test "x$TOOLCHAIN_TYPE" = xgcc || test "x$TOOLCHAIN_TYPE" = xclang; then
+ # Check if compiler supports -fmacro-prefix-map. If so, use that to make
+ # the __FILE__ macro resolve to paths relative to the workspace root.
+ workspace_root_trailing_slash="${WORKSPACE_ROOT%/}/"
+ FILE_MACRO_CFLAGS="-fmacro-prefix-map=${workspace_root_trailing_slash}="
+ FLAGS_COMPILER_CHECK_ARGUMENTS(ARGUMENT: [${FILE_MACRO_CFLAGS}],
+ PREFIX: $3,
+ IF_FALSE: [
+ FILE_MACRO_CFLAGS=
+ ]
+ )
+ fi
+
# EXPORT to API
CFLAGS_JVM_COMMON="$ALWAYS_CFLAGS_JVM $ALWAYS_DEFINES_JVM \
$TOOLCHAIN_CFLAGS_JVM ${$1_TOOLCHAIN_CFLAGS_JVM} \
$OS_CFLAGS $OS_CFLAGS_JVM $CFLAGS_OS_DEF_JVM $DEBUG_CFLAGS_JVM \
- $WARNING_CFLAGS $WARNING_CFLAGS_JVM $JVM_PICFLAG"
+ $WARNING_CFLAGS $WARNING_CFLAGS_JVM $JVM_PICFLAG $FILE_MACRO_CFLAGS"
CFLAGS_JDK_COMMON="$ALWAYS_CFLAGS_JDK $ALWAYS_DEFINES_JDK $TOOLCHAIN_CFLAGS_JDK \
$OS_CFLAGS $CFLAGS_OS_DEF_JDK $DEBUG_CFLAGS_JDK $DEBUG_OPTIONS_FLAGS_JDK \
- $WARNING_CFLAGS $WARNING_CFLAGS_JDK $DEBUG_SYMBOLS_CFLAGS_JDK"
+ $WARNING_CFLAGS $WARNING_CFLAGS_JDK $DEBUG_SYMBOLS_CFLAGS_JDK \
+ $FILE_MACRO_CFLAGS"
# Use ${$2EXTRA_CFLAGS} to block EXTRA_CFLAGS to be added to build flags.
# (Currently we don't have any OPENJDK_BUILD_EXTRA_CFLAGS, but that might
--- a/make/autoconf/flags-other.m4 Sat Apr 13 07:22:55 2019 +0100
+++ b/make/autoconf/flags-other.m4 Sat Apr 13 07:23:18 2019 +0100
@@ -81,21 +81,21 @@
RC_FLAGS="$RC_FLAGS \
-D\"JDK_VERSION_STRING=\$(VERSION_STRING)\" \
-D\"JDK_COMPANY=\$(COMPANY_NAME)\" \
- -D\"JDK_COMPONENT=\$(JDK_RC_NAME) binary\" \
+ -D\"JDK_FILEDESC=\$(JDK_RC_NAME) binary\" \
-D\"JDK_VER=\$(VERSION_NUMBER)\" \
-D\"JDK_COPYRIGHT=Copyright \xA9 $COPYRIGHT_YEAR\" \
-D\"JDK_NAME=\$(JDK_RC_NAME) \$(VERSION_FEATURE)\" \
-D\"JDK_FVER=\$(subst .,\$(COMMA),\$(VERSION_NUMBER_FOUR_POSITIONS))\""
JVM_RCFLAGS="$JVM_RCFLAGS \
- -D\"HS_BUILD_ID=\$(VERSION_STRING)\" \
+ -D\"HS_VERSION_STRING=\$(VERSION_STRING)\" \
-D\"HS_COMPANY=\$(COMPANY_NAME)\" \
- -D\"JDK_DOTVER=\$(VERSION_NUMBER_FOUR_POSITIONS)\" \
+ -D\"HS_VER=\$(VERSION_NUMBER_FOUR_POSITIONS)\" \
+ -D\"HS_INTERNAL_NAME=jvm\" \
-D\"HS_COPYRIGHT=Copyright $COPYRIGHT_YEAR\" \
+ -D\"HS_FNAME=jvm.dll\" \
-D\"HS_NAME=\$(PRODUCT_NAME) \$(VERSION_SHORT)\" \
- -D\"JDK_VER=\$(subst .,\$(COMMA),\$(VERSION_NUMBER_FOUR_POSITIONS))\" \
- -D\"HS_FNAME=jvm.dll\" \
- -D\"HS_INTERNAL_NAME=jvm\""
+ -D\"HS_FVER=\$(subst .,\$(COMMA),\$(VERSION_NUMBER_FOUR_POSITIONS))\""
fi
AC_SUBST(RC_FLAGS)
AC_SUBST(JVM_RCFLAGS)
--- a/make/autoconf/jdk-options.m4 Sat Apr 13 07:22:55 2019 +0100
+++ b/make/autoconf/jdk-options.m4 Sat Apr 13 07:23:18 2019 +0100
@@ -404,9 +404,12 @@
[jcov library location])])
AC_ARG_WITH(jcov-input-jdk, [AS_HELP_STRING([--with-jcov-input-jdk],
[jdk image to instrument])])
+ AC_ARG_WITH(jcov-filters, [AS_HELP_STRING([--with-jcov-filters],
+ [filters to limit code for jcov instrumentation and report generation])])
JCOV_HOME=
JCOV_INPUT_JDK=
JCOV_ENABLED=
+ JCOV_FILTERS=
if test "x$with_jcov" = "x" ; then
JCOV_ENABLED="false"
else
@@ -425,10 +428,14 @@
fi
BASIC_FIXUP_PATH(JCOV_INPUT_JDK)
fi
+ if test "x$with_jcov_filters" != "x" ; then
+ JCOV_FILTERS="$with_jcov_filters"
+ fi
fi
AC_SUBST(JCOV_ENABLED)
AC_SUBST(JCOV_HOME)
AC_SUBST(JCOV_INPUT_JDK)
+ AC_SUBST(JCOV_FILTERS)
])
###############################################################################
--- a/make/autoconf/spec.gmk.in Sat Apr 13 07:22:55 2019 +0100
+++ b/make/autoconf/spec.gmk.in Sat Apr 13 07:23:18 2019 +0100
@@ -140,7 +140,9 @@
# The top-level directory of the source repository
TOPDIR:=@TOPDIR@
-
+# Usually the top level directory, but could be something else if a custom
+# root is defined.
+WORKSPACE_ROOT:=@WORKSPACE_ROOT@
IMPORT_MODULES_CLASSES:=@IMPORT_MODULES_CLASSES@
IMPORT_MODULES_CMDS:=@IMPORT_MODULES_CMDS@
IMPORT_MODULES_LIBS:=@IMPORT_MODULES_LIBS@
@@ -387,6 +389,7 @@
JCOV_ENABLED=@JCOV_ENABLED@
JCOV_HOME=@JCOV_HOME@
JCOV_INPUT_JDK=@JCOV_INPUT_JDK@
+JCOV_FILTERS=@JCOV_FILTERS@
# AddressSanitizer
export ASAN_ENABLED:=@ASAN_ENABLED@
--- a/make/common/NativeCompilation.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/common/NativeCompilation.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -236,8 +236,10 @@
# This is the definite source file to use for $1_FILENAME.
$1_SRC_FILE := $$($1_FILE)
- ifneq ($$($1_DISABLE_THIS_FILE_DEFINE), true)
- $1_THIS_FILE = -DTHIS_FILE='"$$($1_FILENAME)"'
+ ifneq ($$($1_DEFINE_THIS_FILE), false)
+ ifneq ($$($$($1_BASE)_DEFINE_THIS_FILE), false)
+ $1_THIS_FILE = -DTHIS_FILE='"$$($1_FILENAME)"'
+ endif
endif
ifeq ($$($1_OPTIMIZATION), )
@@ -370,6 +372,7 @@
$(ECHO) $$@: \\ > $$($1_DEPS_FILE) ; \
$(SED) $(WINDOWS_SHOWINCLUDE_SED_PATTERN) $$($1_OBJ).log \
| $(SORT) -u >> $$($1_DEPS_FILE) ; \
+ $(ECHO) >> $$($1_DEPS_FILE) ; \
$(SED) $(DEPENDENCY_TARGET_SED_PATTERN) $$($1_DEPS_FILE) > $$($1_DEPS_TARGETS_FILE)
endif
endif
@@ -426,6 +429,7 @@
# STRIPFLAGS Optionally change the flags given to the strip command
# PRECOMPILED_HEADER Header file to use as precompiled header
# PRECOMPILED_HEADER_EXCLUDE List of source files that should not use PCH
+# DEFINE_THIS_FILE Set to false to not set the THIS_FILE preprocessor macro
#
# After being called, some variables are exported from this macro, all prefixed
# with parameter 1 followed by a '_':
@@ -703,7 +707,7 @@
FILE := $$($1_GENERATED_PCH_SRC), \
BASE := $1, \
EXTRA_CXXFLAGS := -Fp$$($1_PCH_FILE) -Yc$$(notdir $$($1_PRECOMPILED_HEADER)), \
- DISABLE_THIS_FILE_DEFINE := true, \
+ DEFINE_THIS_FILE := false, \
))
$1_USE_PCH_FLAGS := \
@@ -840,6 +844,7 @@
$(ECHO) $$($1_RES): \\ > $$($1_RES_DEPS_FILE) ; \
$(SED) $(WINDOWS_SHOWINCLUDE_SED_PATTERN) $$($1_RES_DEPS_FILE).obj.log \
>> $$($1_RES_DEPS_FILE) ; \
+ $(ECHO) >> $$($1_RES_DEPS_FILE) ;\
$(SED) $(DEPENDENCY_TARGET_SED_PATTERN) $$($1_RES_DEPS_FILE) \
> $$($1_RES_DEPS_TARGETS_FILE)
endif
--- a/make/hotspot/gensrc/GensrcAdlc.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/hotspot/gensrc/GensrcAdlc.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -76,6 +76,7 @@
DEBUG_SYMBOLS := false, \
DISABLED_WARNINGS_clang := tautological-compare, \
DISABLED_WARNINGS_solstudio := notemsource, \
+ DEFINE_THIS_FILE := false, \
))
ADLC_TOOL := $(BUILD_ADLC_TARGET)
--- a/make/hotspot/gensrc/GensrcDtrace.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/hotspot/gensrc/GensrcDtrace.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -80,6 +80,7 @@
EXTRA_DEPS := $(JVMTI_H) $(JFR_FILES), \
OBJECT_DIR := $(JVM_VARIANT_OUTPUTDIR)/tools/dtrace-gen-offsets/objs, \
OUTPUT_DIR := $(JVM_VARIANT_OUTPUTDIR)/tools/dtrace-gen-offsets, \
+ DEFINE_THIS_FILE := false, \
))
DTRACE_GEN_OFFSETS_TOOL := $(BUILD_DTRACE_GEN_OFFSETS_TARGET)
--- a/make/hotspot/lib/CompileDtraceLibraries.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/hotspot/lib/CompileDtraceLibraries.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -42,6 +42,7 @@
LDFLAGS := -m64 -mt -xnolib $(SHARED_LIBRARY_FLAGS), \
LIBS := $(LIBDL) -lthread -ldoor, \
OBJECT_DIR := $(LIBJVM_DTRACE_OUTPUTDIR)/objs, \
+ DEFINE_THIS_FILE := false, \
))
# Note that libjvm_db.c has tests for COMPILER2, but this was never set by
@@ -54,6 +55,7 @@
CFLAGS := -I$(DTRACE_GENSRC_DIR) $(JNI_INCLUDE_FLAGS) -m64 -G -mt -KPIC -xldscope=hidden, \
LDFLAGS := -m64 -mt -xnolib $(SHARED_LIBRARY_FLAGS), \
OBJECT_DIR := $(LIBJVM_DB_OUTPUTDIR)/objs, \
+ DEFINE_THIS_FILE := false, \
))
TARGETS += $(BUILD_LIBJVM_DTRACE) $(BUILD_LIBJVM_DB)
--- a/make/hotspot/lib/CompileGtest.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/hotspot/lib/CompileGtest.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -92,6 +92,7 @@
STRIP_SYMBOLS := false, \
PRECOMPILED_HEADER := $(JVM_PRECOMPILED_HEADER), \
PRECOMPILED_HEADER_EXCLUDE := gtest-all.cc gtestMain.cpp, \
+ DEFINE_THIS_FILE := false, \
))
TARGETS += $(BUILD_GTEST_LIBJVM)
@@ -115,6 +116,7 @@
LIBS_windows := $(JVM_OUTPUTDIR)/gtest/objs/jvm.lib, \
COPY_DEBUG_SYMBOLS := $(GTEST_COPY_DEBUG_SYMBOLS), \
ZIP_EXTERNAL_DEBUG_SYMBOLS := false, \
+ DEFINE_THIS_FILE := false, \
))
$(BUILD_GTEST_LAUNCHER): $(BUILD_GTEST_LIBJVM)
--- a/make/hotspot/lib/CompileJvm.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/hotspot/lib/CompileJvm.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -202,6 +202,7 @@
VERSIONINFO_RESOURCE := $(TOPDIR)/src/hotspot/os/windows/version.rc, \
PRECOMPILED_HEADER := $(JVM_PRECOMPILED_HEADER), \
PRECOMPILED_HEADER_EXCLUDE := $(JVM_PRECOMPILED_HEADER_EXCLUDE), \
+ DEFINE_THIS_FILE := false, \
))
# Always recompile vm_version.cpp if libjvm needs to be relinked. This ensures
--- a/make/launcher/Launcher-jdk.accessibility.gmk Sat Apr 13 07:22:55 2019 +0100
+++ b/make/launcher/Launcher-jdk.accessibility.gmk Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,7 @@
DISABLED_WARNINGS_microsoft := 4267 4996, \
LDFLAGS := $(LDFLAGS_JDKEXE), \
LIBS := advapi32.lib version.lib user32.lib, \
- VERSIONINFO_RESOURCE := $(ACCESSBRIDGE_SRC)/AccessBridgeStatusWindow.RC, \
+ VERSIONINFO_RESOURCE := $(ACCESSBRIDGE_SRC)/AccessBridgeStatusWindow.rc, \
MANIFEST := $(JABSWITCH_SRC)/jabswitch.manifest, \
MANIFEST_VERSION := $(VERSION_NUMBER_FOUR_POSITIONS), \
))
--- a/src/hotspot/cpu/aarch64/aarch64.ad Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/aarch64/aarch64.ad Sat Apr 13 07:23:18 2019 +0100
@@ -3932,7 +3932,8 @@
operand immL_bitmask()
%{
- predicate(((n->get_long() & 0xc000000000000000l) == 0)
+ predicate((n->get_long() != 0)
+ && ((n->get_long() & 0xc000000000000000l) == 0)
&& is_power_of_2(n->get_long() + 1));
match(ConL);
@@ -3943,7 +3944,8 @@
operand immI_bitmask()
%{
- predicate(((n->get_int() & 0xc0000000) == 0)
+ predicate((n->get_int() != 0)
+ && ((n->get_int() & 0xc0000000) == 0)
&& is_power_of_2(n->get_int() + 1));
match(ConI);
@@ -11432,11 +11434,13 @@
instruct ubfxwI(iRegINoSp dst, iRegIorL2I src, immI rshift, immI_bitmask mask)
%{
match(Set dst (AndI (URShiftI src rshift) mask));
+ // Make sure we are not going to exceed what ubfxw can do.
+ predicate((exact_log2(n->in(2)->get_int() + 1) + (n->in(1)->in(2)->get_int() & 31)) <= (31 + 1));
ins_cost(INSN_COST);
format %{ "ubfxw $dst, $src, $rshift, $mask" %}
ins_encode %{
- int rshift = $rshift$$constant;
+ int rshift = $rshift$$constant & 31;
long mask = $mask$$constant;
int width = exact_log2(mask+1);
__ ubfxw(as_Register($dst$$reg),
@@ -11447,13 +11451,15 @@
instruct ubfxL(iRegLNoSp dst, iRegL src, immI rshift, immL_bitmask mask)
%{
match(Set dst (AndL (URShiftL src rshift) mask));
+ // Make sure we are not going to exceed what ubfx can do.
+ predicate((exact_log2_long(n->in(2)->get_long() + 1) + (n->in(1)->in(2)->get_int() & 63)) <= (63 + 1));
ins_cost(INSN_COST);
format %{ "ubfx $dst, $src, $rshift, $mask" %}
ins_encode %{
- int rshift = $rshift$$constant;
+ int rshift = $rshift$$constant & 63;
long mask = $mask$$constant;
- int width = exact_log2(mask+1);
+ int width = exact_log2_long(mask+1);
__ ubfx(as_Register($dst$$reg),
as_Register($src$$reg), rshift, width);
%}
@@ -11465,11 +11471,13 @@
instruct ubfxIConvI2L(iRegLNoSp dst, iRegIorL2I src, immI rshift, immI_bitmask mask)
%{
match(Set dst (ConvI2L (AndI (URShiftI src rshift) mask)));
+ // Make sure we are not going to exceed what ubfxw can do.
+ predicate((exact_log2(n->in(1)->in(2)->get_int() + 1) + (n->in(1)->in(1)->in(2)->get_int() & 31)) <= (31 + 1));
ins_cost(INSN_COST * 2);
format %{ "ubfx $dst, $src, $rshift, $mask" %}
ins_encode %{
- int rshift = $rshift$$constant;
+ int rshift = $rshift$$constant & 31;
long mask = $mask$$constant;
int width = exact_log2(mask+1);
__ ubfx(as_Register($dst$$reg),
@@ -11510,7 +11518,7 @@
ins_encode %{
int lshift = $lshift$$constant;
long mask = $mask$$constant;
- int width = exact_log2(mask+1);
+ int width = exact_log2_long(mask+1);
__ ubfiz(as_Register($dst$$reg),
as_Register($src$$reg), lshift, width);
%}
--- a/src/hotspot/cpu/aarch64/aarch64_ad.m4 Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/aarch64/aarch64_ad.m4 Sat Apr 13 07:23:18 2019 +0100
@@ -181,31 +181,35 @@
`instruct $3$1(iReg$1NoSp dst, iReg$1`'ORL2I($1) src, immI rshift, imm$1_bitmask mask)
%{
match(Set dst (And$1 ($2$1 src rshift) mask));
+ // Make sure we are not going to exceed what $3 can do.
+ predicate((exact_log2$6(n->in(2)->get_$5() + 1) + (n->in(1)->in(2)->get_int() & $4)) <= ($4 + 1));
ins_cost(INSN_COST);
format %{ "$3 $dst, $src, $rshift, $mask" %}
ins_encode %{
- int rshift = $rshift$$constant;
+ int rshift = $rshift$$constant & $4;
long mask = $mask$$constant;
- int width = exact_log2(mask+1);
+ int width = exact_log2$6(mask+1);
__ $3(as_Register($dst$$reg),
as_Register($src$$reg), rshift, width);
%}
ins_pipe(ialu_reg_shift);
%}')
-BFX_INSN(I,URShift,ubfxw)
-BFX_INSN(L,URShift,ubfx)
+BFX_INSN(I, URShift, ubfxw, 31, int)
+BFX_INSN(L, URShift, ubfx, 63, long, _long)
// We can use ubfx when extending an And with a mask when we know mask
// is positive. We know that because immI_bitmask guarantees it.
instruct ubfxIConvI2L(iRegLNoSp dst, iRegIorL2I src, immI rshift, immI_bitmask mask)
%{
match(Set dst (ConvI2L (AndI (URShiftI src rshift) mask)));
+ // Make sure we are not going to exceed what ubfxw can do.
+ predicate((exact_log2(n->in(1)->in(2)->get_int() + 1) + (n->in(1)->in(1)->in(2)->get_int() & 31)) <= (31 + 1));
ins_cost(INSN_COST * 2);
format %{ "ubfx $dst, $src, $rshift, $mask" %}
ins_encode %{
- int rshift = $rshift$$constant;
+ int rshift = $rshift$$constant & 31;
long mask = $mask$$constant;
int width = exact_log2(mask+1);
__ ubfx(as_Register($dst$$reg),
@@ -228,7 +232,7 @@
ins_encode %{
int lshift = $lshift$$constant;
long mask = $mask$$constant;
- int width = exact_log2(mask+1);
+ int width = exact_log2$5(mask+1);
__ $2(as_Register($dst$$reg),
as_Register($src$$reg), lshift, width);
%}
--- a/src/hotspot/cpu/aarch64/interpreterRT_aarch64.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/aarch64/interpreterRT_aarch64.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -418,7 +418,7 @@
};
-IRT_ENTRY(address,
+JRT_ENTRY(address,
InterpreterRuntime::slow_signature_handler(JavaThread* thread,
Method* method,
intptr_t* from,
@@ -435,4 +435,4 @@
// return result handler
return Interpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/arm/interpreterRT_arm.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/arm/interpreterRT_arm.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -369,9 +369,9 @@
}
};
-IRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(JavaThread* thread, Method* method, intptr_t* from, intptr_t* to))
+JRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(JavaThread* thread, Method* method, intptr_t* from, intptr_t* to))
methodHandle m(thread, (Method*)method);
assert(m->is_native(), "sanity check");
SlowSignatureHandler(m, (address)from, to).iterate(UCONST64(-1));
return Interpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/ppc/interpreterRT_ppc.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/ppc/interpreterRT_ppc.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2013 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -148,15 +148,15 @@
// Access function to get the signature.
-IRT_ENTRY(address, InterpreterRuntime::get_signature(JavaThread* thread, Method* method))
+JRT_ENTRY(address, InterpreterRuntime::get_signature(JavaThread* thread, Method* method))
methodHandle m(thread, method);
assert(m->is_native(), "sanity check");
Symbol *s = m->signature();
return (address) s->base();
-IRT_END
+JRT_END
-IRT_ENTRY(address, InterpreterRuntime::get_result_handler(JavaThread* thread, Method* method))
+JRT_ENTRY(address, InterpreterRuntime::get_result_handler(JavaThread* thread, Method* method))
methodHandle m(thread, method);
assert(m->is_native(), "sanity check");
return AbstractInterpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/ppc/vm_version_ppc.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/ppc/vm_version_ppc.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -381,6 +381,27 @@
}
}
+void VM_Version::print_platform_virtualization_info(outputStream* st) {
+ const char* info_file = "/proc/ppc64/lparcfg";
+ const char* kw[] = { "system_type=", // qemu indicates PowerKVM
+ "partition_entitled_capacity=", // entitled processor capacity percentage
+ "partition_max_entitled_capacity=",
+ "capacity_weight=", // partition CPU weight
+ "partition_active_processors=",
+ "partition_potential_processors=",
+ "entitled_proc_capacity_available=",
+ "capped=", // 0 - uncapped, 1 - vcpus capped at entitled processor capacity percentage
+ "shared_processor_mode=", // (non)dedicated partition
+ "system_potential_processors=",
+ "pool=", // CPU-pool number
+ "pool_capacity=",
+ "NumLpars=", // on non-KVM machines, NumLpars is not found for full partition mode machines
+ NULL };
+ if (!print_matching_lines_from_file(info_file, st, kw)) {
+ st->print_cr(" <%s Not Available>", info_file);
+ }
+}
+
bool VM_Version::use_biased_locking() {
#if INCLUDE_RTM_OPT
// RTM locking is most useful when there is high lock contention and
--- a/src/hotspot/cpu/ppc/vm_version_ppc.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/ppc/vm_version_ppc.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -89,6 +89,9 @@
static void initialize();
// Override Abstract_VM_Version implementation
+ static void print_platform_virtualization_info(outputStream*);
+
+ // Override Abstract_VM_Version implementation
static bool use_biased_locking();
static bool is_determine_features_test_running() { return _is_determine_features_test_running; }
--- a/src/hotspot/cpu/s390/interpreterRT_s390.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/s390/interpreterRT_s390.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -151,15 +151,15 @@
void SignatureHandlerLibrary::pd_set_handler(address handler) {}
-IRT_ENTRY(address, InterpreterRuntime::get_signature(JavaThread* thread, Method* method))
+JRT_ENTRY(address, InterpreterRuntime::get_signature(JavaThread* thread, Method* method))
methodHandle m(thread, method);
assert(m->is_native(), "sanity check");
Symbol *s = m->signature();
return (address) s->base();
-IRT_END
+JRT_END
-IRT_ENTRY(address, InterpreterRuntime::get_result_handler(JavaThread* thread, Method* method))
+JRT_ENTRY(address, InterpreterRuntime::get_result_handler(JavaThread* thread, Method* method))
methodHandle m(thread, method);
assert(m->is_native(), "sanity check");
return AbstractInterpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/s390/vm_version_s390.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/s390/vm_version_s390.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -516,6 +516,19 @@
}
}
+void VM_Version::print_platform_virtualization_info(outputStream* st) {
+ // /proc/sysinfo contains interesting information about
+ // - LPAR
+ // - whole "Box" (CPUs )
+ // - z/VM / KVM (VM<nn>); this is not available in an LPAR-only setup
+ const char* kw[] = { "LPAR", "CPUs", "VM", NULL };
+ const char* info_file = "/proc/sysinfo";
+
+ if (!print_matching_lines_from_file(info_file, st, kw)) {
+ st->print_cr(" <%s Not Available>", info_file);
+ }
+}
+
void VM_Version::print_features() {
print_features_internal("Version:");
}
--- a/src/hotspot/cpu/s390/vm_version_s390.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/s390/vm_version_s390.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -346,6 +346,9 @@
static void print_features();
static bool is_determine_features_test_running() { return _is_determine_features_test_running; }
+ // Override Abstract_VM_Version implementation
+ static void print_platform_virtualization_info(outputStream*);
+
// CPU feature query functions
static const char* get_model_string() { return _model_string; }
static bool has_StoreFacilityListExtended() { return (_features[0] & StoreFacilityListExtendedMask) == StoreFacilityListExtendedMask; }
--- a/src/hotspot/cpu/sparc/interpreterRT_sparc.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/sparc/interpreterRT_sparc.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -191,7 +191,7 @@
};
-IRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(
+JRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(
JavaThread* thread,
Method* method,
intptr_t* from,
@@ -204,4 +204,4 @@
SlowSignatureHandler(m, (address)from, m->is_static() ? to+2 : to+1, to).iterate((uint64_t)CONST64(-1));
// return result handler
return Interpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/x86/assembler_x86.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/assembler_x86.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -3099,7 +3099,7 @@
}
return;
}
- if (UseAddressNop && VM_Version::is_amd()) {
+ if (UseAddressNop && VM_Version::is_amd_family()) {
//
// Using multi-bytes nops "0x0F 0x1F [address]" for AMD.
// 1: 0x90
--- a/src/hotspot/cpu/x86/interpreterRT_x86_32.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/interpreterRT_x86_32.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -147,11 +147,11 @@
}
};
-IRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(JavaThread* thread, Method* method, intptr_t* from, intptr_t* to))
+JRT_ENTRY(address, InterpreterRuntime::slow_signature_handler(JavaThread* thread, Method* method, intptr_t* from, intptr_t* to))
methodHandle m(thread, (Method*)method);
assert(m->is_native(), "sanity check");
// handle arguments
SlowSignatureHandler(m, (address)from, to + 1).iterate((uint64_t)CONST64(-1));
// return result handler
return Interpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/x86/interpreterRT_x86_64.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/interpreterRT_x86_64.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -496,7 +496,7 @@
#endif
-IRT_ENTRY(address,
+JRT_ENTRY(address,
InterpreterRuntime::slow_signature_handler(JavaThread* thread,
Method* method,
intptr_t* from,
@@ -509,4 +509,4 @@
// return result handler
return Interpreter::result_handler(m->result_type());
-IRT_END
+JRT_END
--- a/src/hotspot/cpu/x86/vm_version_ext_x86.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/vm_version_ext_x86.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -340,6 +340,10 @@
return !is_amd_Barcelona();
}
+ if (is_hygon()) {
+ return true;
+ }
+
return false;
}
@@ -407,6 +411,10 @@
}
return _family_id_intel[cpu_family_id];
}
+ if (is_hygon()) {
+ return "Dhyana";
+ }
+
return "Unknown x86";
}
@@ -423,6 +431,9 @@
} else if (is_amd()) {
cpu_type = "AMD";
x64 = cpu_is_em64t() ? " AMD64" : "";
+ } else if (is_hygon()) {
+ cpu_type = "Hygon";
+ x64 = cpu_is_em64t() ? " AMD64" : "";
} else {
cpu_type = "Unknown x86";
x64 = cpu_is_em64t() ? " x86_64" : "";
--- a/src/hotspot/cpu/x86/vm_version_x86.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/vm_version_x86.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -680,7 +680,7 @@
_features &= ~CPU_HT;
}
- if( is_intel() ) { // Intel cpus specific settings
+ if (is_intel()) { // Intel cpus specific settings
if (is_knights_family()) {
_features &= ~CPU_VZEROUPPER;
}
@@ -781,7 +781,7 @@
FLAG_SET_DEFAULT(UseAESCTRIntrinsics, false);
}
} else {
- if(supports_sse4_1()) {
+ if (supports_sse4_1()) {
if (FLAG_IS_DEFAULT(UseAESCTRIntrinsics)) {
FLAG_SET_DEFAULT(UseAESCTRIntrinsics, true);
}
@@ -1001,7 +1001,7 @@
} else if (UseAVX == 1 || UseAVX == 2) {
// 32 bytes vectors (in YMM) are only supported with AVX+
max_vector_size = 32;
- } else if (UseAVX > 2 ) {
+ } else if (UseAVX > 2) {
// 64 bytes vectors (in ZMM) are only supported with AVX 3
max_vector_size = 64;
}
@@ -1165,38 +1165,38 @@
}
}
- if( is_amd() ) { // AMD cpus specific settings
- if( supports_sse2() && FLAG_IS_DEFAULT(UseAddressNop) ) {
+ if (is_amd_family()) { // AMD cpus specific settings
+ if (supports_sse2() && FLAG_IS_DEFAULT(UseAddressNop)) {
// Use it on new AMD cpus starting from Opteron.
UseAddressNop = true;
}
- if( supports_sse2() && FLAG_IS_DEFAULT(UseNewLongLShift) ) {
+ if (supports_sse2() && FLAG_IS_DEFAULT(UseNewLongLShift)) {
// Use it on new AMD cpus starting from Opteron.
UseNewLongLShift = true;
}
- if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
+ if (FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper)) {
if (supports_sse4a()) {
UseXmmLoadAndClearUpper = true; // use movsd only on '10h' Opteron
} else {
UseXmmLoadAndClearUpper = false;
}
}
- if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
- if( supports_sse4a() ) {
+ if (FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll)) {
+ if (supports_sse4a()) {
UseXmmRegToRegMoveAll = true; // use movaps, movapd only on '10h'
} else {
UseXmmRegToRegMoveAll = false;
}
}
- if( FLAG_IS_DEFAULT(UseXmmI2F) ) {
- if( supports_sse4a() ) {
+ if (FLAG_IS_DEFAULT(UseXmmI2F)) {
+ if (supports_sse4a()) {
UseXmmI2F = true;
} else {
UseXmmI2F = false;
}
}
- if( FLAG_IS_DEFAULT(UseXmmI2D) ) {
- if( supports_sse4a() ) {
+ if (FLAG_IS_DEFAULT(UseXmmI2D)) {
+ if (supports_sse4a()) {
UseXmmI2D = true;
} else {
UseXmmI2D = false;
@@ -1214,7 +1214,7 @@
}
// some defaults for AMD family 15h
- if ( cpu_family() == 0x15 ) {
+ if (cpu_family() == 0x15) {
// On family 15h processors default is no sw prefetch
if (FLAG_IS_DEFAULT(AllocatePrefetchStyle)) {
FLAG_SET_DEFAULT(AllocatePrefetchStyle, 0);
@@ -1239,8 +1239,8 @@
}
#endif // COMPILER2
- // Some defaults for AMD family 17h
- if ( cpu_family() == 0x17 ) {
+ // Some defaults for AMD family 17h || Hygon family 18h
+ if (cpu_family() == 0x17 || cpu_family() == 0x18) {
// On family 17h processors use XMM and UnalignedLoadStores for Array Copy
if (supports_sse2() && FLAG_IS_DEFAULT(UseXMMForArrayCopy)) {
FLAG_SET_DEFAULT(UseXMMForArrayCopy, true);
@@ -1256,29 +1256,29 @@
}
}
- if( is_intel() ) { // Intel cpus specific settings
- if( FLAG_IS_DEFAULT(UseStoreImmI16) ) {
+ if (is_intel()) { // Intel cpus specific settings
+ if (FLAG_IS_DEFAULT(UseStoreImmI16)) {
UseStoreImmI16 = false; // don't use it on Intel cpus
}
- if( cpu_family() == 6 || cpu_family() == 15 ) {
- if( FLAG_IS_DEFAULT(UseAddressNop) ) {
+ if (cpu_family() == 6 || cpu_family() == 15) {
+ if (FLAG_IS_DEFAULT(UseAddressNop)) {
// Use it on all Intel cpus starting from PentiumPro
UseAddressNop = true;
}
}
- if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
+ if (FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper)) {
UseXmmLoadAndClearUpper = true; // use movsd on all Intel cpus
}
- if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
- if( supports_sse3() ) {
+ if (FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll)) {
+ if (supports_sse3()) {
UseXmmRegToRegMoveAll = true; // use movaps, movapd on new Intel cpus
} else {
UseXmmRegToRegMoveAll = false;
}
}
- if( cpu_family() == 6 && supports_sse3() ) { // New Intel cpus
+ if (cpu_family() == 6 && supports_sse3()) { // New Intel cpus
#ifdef COMPILER2
- if( FLAG_IS_DEFAULT(MaxLoopPad) ) {
+ if (FLAG_IS_DEFAULT(MaxLoopPad)) {
// For new Intel cpus do the next optimization:
// don't align the beginning of a loop if there are enough instructions
// left (NumberOfLoopInstrToAlign defined in c2_globals.hpp)
@@ -1324,7 +1324,7 @@
FLAG_SET_DEFAULT(UseIncDec, false);
}
}
- if(FLAG_IS_DEFAULT(AllocatePrefetchInstr) && supports_3dnow_prefetch()) {
+ if (FLAG_IS_DEFAULT(AllocatePrefetchInstr) && supports_3dnow_prefetch()) {
FLAG_SET_DEFAULT(AllocatePrefetchInstr, 3);
}
}
@@ -1573,6 +1573,65 @@
#endif // !PRODUCT
}
+void VM_Version::print_platform_virtualization_info(outputStream* st) {
+ VirtualizationType vrt = VM_Version::get_detected_virtualization();
+ if (vrt == XenHVM) {
+ st->print_cr("Xen hardware-assisted virtualization detected");
+ } else if (vrt == KVM) {
+ st->print_cr("KVM virtualization detected");
+ } else if (vrt == VMWare) {
+ st->print_cr("VMWare virtualization detected");
+ } else if (vrt == HyperV) {
+ st->print_cr("HyperV virtualization detected");
+ }
+}
+
+void VM_Version::check_virt_cpuid(uint32_t idx, uint32_t *regs) {
+// TODO support 32 bit
+#if defined(_LP64)
+#if defined(_MSC_VER)
+ // Allocate space for the code
+ const int code_size = 100;
+ ResourceMark rm;
+ CodeBuffer cb("detect_virt", code_size, 0);
+ MacroAssembler* a = new MacroAssembler(&cb);
+ address code = a->pc();
+ void (*test)(uint32_t idx, uint32_t *regs) = (void(*)(uint32_t idx, uint32_t *regs))code;
+
+ a->movq(r9, rbx); // save nonvolatile register
+
+ // next line would not work on 32-bit
+ a->movq(rax, c_rarg0 /* rcx */);
+ a->movq(r8, c_rarg1 /* rdx */);
+ a->cpuid();
+ a->movl(Address(r8, 0), rax);
+ a->movl(Address(r8, 4), rbx);
+ a->movl(Address(r8, 8), rcx);
+ a->movl(Address(r8, 12), rdx);
+
+ a->movq(rbx, r9); // restore nonvolatile register
+ a->ret(0);
+
+ uint32_t *code_end = (uint32_t *)a->pc();
+ a->flush();
+
+ // execute code
+ (*test)(idx, regs);
+#elif defined(__GNUC__)
+ __asm__ volatile (
+ " cpuid;"
+ " mov %%eax,(%1);"
+ " mov %%ebx,4(%1);"
+ " mov %%ecx,8(%1);"
+ " mov %%edx,12(%1);"
+ : "+a" (idx)
+ : "S" (regs)
+ : "ebx", "ecx", "edx", "memory" );
+#endif
+#endif
+}
+
+
bool VM_Version::use_biased_locking() {
#if INCLUDE_RTM_OPT
// RTM locking is most useful when there is high lock contention and
@@ -1594,6 +1653,54 @@
return UseBiasedLocking;
}
+// On Xen, the cpuid instruction returns
+// eax / registers[0]: Version of Xen
+// ebx / registers[1]: chars 'XenV'
+// ecx / registers[2]: chars 'MMXe'
+// edx / registers[3]: chars 'nVMM'
+//
+// On KVM / VMWare / MS Hyper-V, the cpuid instruction returns
+// ebx / registers[1]: chars 'KVMK' / 'VMwa' / 'Micr'
+// ecx / registers[2]: chars 'VMKV' / 'reVM' / 'osof'
+// edx / registers[3]: chars 'M' / 'ware' / 't Hv'
+//
+// more information :
+// https://kb.vmware.com/s/article/1009458
+//
+void VM_Version::check_virtualizations() {
+#if defined(_LP64)
+ uint32_t registers[4];
+ char signature[13];
+ uint32_t base;
+ signature[12] = '\0';
+ memset((void*)registers, 0, 4*sizeof(uint32_t));
+
+ for (base = 0x40000000; base < 0x40010000; base += 0x100) {
+ check_virt_cpuid(base, registers);
+
+ *(uint32_t *)(signature + 0) = registers[1];
+ *(uint32_t *)(signature + 4) = registers[2];
+ *(uint32_t *)(signature + 8) = registers[3];
+
+ if (strncmp("VMwareVMware", signature, 12) == 0) {
+ Abstract_VM_Version::_detected_virtualization = VMWare;
+ }
+
+ if (strncmp("Microsoft Hv", signature, 12) == 0) {
+ Abstract_VM_Version::_detected_virtualization = HyperV;
+ }
+
+ if (strncmp("KVMKVMKVM", signature, 9) == 0) {
+ Abstract_VM_Version::_detected_virtualization = KVM;
+ }
+
+ if (strncmp("XenVMMXenVMM", signature, 12) == 0) {
+ Abstract_VM_Version::_detected_virtualization = XenHVM;
+ }
+ }
+#endif
+}
+
void VM_Version::initialize() {
ResourceMark rm;
// Making this stub must be FIRST use of assembler
@@ -1608,4 +1715,7 @@
g.generate_get_cpu_info());
get_processor_features();
+ if (cpu_family() > 4) { // it supports CPUID
+ check_virtualizations();
+ }
}
--- a/src/hotspot/cpu/x86/vm_version_x86.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/x86/vm_version_x86.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -495,13 +495,13 @@
result |= CPU_CX8;
if (_cpuid_info.std_cpuid1_edx.bits.cmov != 0)
result |= CPU_CMOV;
- if (_cpuid_info.std_cpuid1_edx.bits.fxsr != 0 || (is_amd() &&
+ if (_cpuid_info.std_cpuid1_edx.bits.fxsr != 0 || (is_amd_family() &&
_cpuid_info.ext_cpuid1_edx.bits.fxsr != 0))
result |= CPU_FXSR;
// HT flag is set for multi-core processors also.
if (threads_per_core() > 1)
result |= CPU_HT;
- if (_cpuid_info.std_cpuid1_edx.bits.mmx != 0 || (is_amd() &&
+ if (_cpuid_info.std_cpuid1_edx.bits.mmx != 0 || (is_amd_family() &&
_cpuid_info.ext_cpuid1_edx.bits.mmx != 0))
result |= CPU_MMX;
if (_cpuid_info.std_cpuid1_edx.bits.sse != 0)
@@ -553,7 +553,7 @@
result |= CPU_VNNI;
}
}
- if(_cpuid_info.sef_cpuid7_ebx.bits.bmi1 != 0)
+ if (_cpuid_info.sef_cpuid7_ebx.bits.bmi1 != 0)
result |= CPU_BMI1;
if (_cpuid_info.std_cpuid1_edx.bits.tsc != 0)
result |= CPU_TSC;
@@ -567,17 +567,17 @@
result |= CPU_CLMUL;
if (_cpuid_info.sef_cpuid7_ebx.bits.rtm != 0)
result |= CPU_RTM;
- if(_cpuid_info.sef_cpuid7_ebx.bits.adx != 0)
+ if (_cpuid_info.sef_cpuid7_ebx.bits.adx != 0)
result |= CPU_ADX;
- if(_cpuid_info.sef_cpuid7_ebx.bits.bmi2 != 0)
+ if (_cpuid_info.sef_cpuid7_ebx.bits.bmi2 != 0)
result |= CPU_BMI2;
if (_cpuid_info.sef_cpuid7_ebx.bits.sha != 0)
result |= CPU_SHA;
if (_cpuid_info.std_cpuid1_ecx.bits.fma != 0)
result |= CPU_FMA;
- // AMD features.
- if (is_amd()) {
+ // AMD|Hygon features.
+ if (is_amd_family()) {
if ((_cpuid_info.ext_cpuid1_edx.bits.tdnow != 0) ||
(_cpuid_info.ext_cpuid1_ecx.bits.prefetchw != 0))
result |= CPU_3DNOW_PREFETCH;
@@ -587,8 +587,8 @@
result |= CPU_SSE4A;
}
// Intel features.
- if(is_intel()) {
- if(_cpuid_info.ext_cpuid1_ecx.bits.lzcnt_intel != 0)
+ if (is_intel()) {
+ if (_cpuid_info.ext_cpuid1_ecx.bits.lzcnt_intel != 0)
result |= CPU_LZCNT;
// for Intel, ecx.bits.misalignsse bit (bit 8) indicates support for prefetchw
if (_cpuid_info.ext_cpuid1_ecx.bits.misalignsse != 0) {
@@ -686,6 +686,9 @@
static void initialize();
// Override Abstract_VM_Version implementation
+ static void print_platform_virtualization_info(outputStream*);
+
+ // Override Abstract_VM_Version implementation
static bool use_biased_locking();
// Asserts
@@ -711,6 +714,8 @@
static int cpu_family() { return _cpu;}
static bool is_P6() { return cpu_family() >= 6; }
static bool is_amd() { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x68747541; } // 'htuA'
+ static bool is_hygon() { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x6F677948; } // 'ogyH'
+ static bool is_amd_family() { return is_amd() || is_hygon(); }
static bool is_intel() { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x756e6547; } // 'uneG'
static bool is_zx() { assert_is_initialized(); return (_cpuid_info.std_vendor_name_0 == 0x746e6543) || (_cpuid_info.std_vendor_name_0 == 0x68532020); } // 'tneC'||'hS '
static bool is_atom_family() { return ((cpu_family() == 0x06) && ((extended_cpu_model() == 0x36) || (extended_cpu_model() == 0x37) || (extended_cpu_model() == 0x4D))); } //Silvermont and Centerton
@@ -734,7 +739,7 @@
if (!supports_topology || result == 0) {
result = (_cpuid_info.dcp_cpuid4_eax.bits.cores_per_cpu + 1);
}
- } else if (is_amd()) {
+ } else if (is_amd_family()) {
result = (_cpuid_info.ext_cpuid8_ecx.bits.cores_per_cpu + 1);
} else if (is_zx()) {
bool supports_topology = supports_processor_topology();
@@ -770,7 +775,7 @@
intx result = 0;
if (is_intel()) {
result = (_cpuid_info.dcp_cpuid4_ebx.bits.L1_line_size + 1);
- } else if (is_amd()) {
+ } else if (is_amd_family()) {
result = _cpuid_info.ext_cpuid5_ecx.bits.L1_line_size;
} else if (is_zx()) {
result = (_cpuid_info.dcp_cpuid4_ebx.bits.L1_line_size + 1);
@@ -857,7 +862,7 @@
// AMD features
static bool supports_3dnow_prefetch() { return (_features & CPU_3DNOW_PREFETCH) != 0; }
- static bool supports_mmx_ext() { return is_amd() && _cpuid_info.ext_cpuid1_edx.bits.mmx_amd != 0; }
+ static bool supports_mmx_ext() { return is_amd_family() && _cpuid_info.ext_cpuid1_edx.bits.mmx_amd != 0; }
static bool supports_lzcnt() { return (_features & CPU_LZCNT) != 0; }
static bool supports_sse4a() { return (_features & CPU_SSE4A) != 0; }
@@ -870,8 +875,8 @@
}
static bool supports_tscinv() {
return supports_tscinv_bit() &&
- ( (is_amd() && !is_amd_Barcelona()) ||
- is_intel_tsc_synched_at_init() );
+ ((is_amd_family() && !is_amd_Barcelona()) ||
+ is_intel_tsc_synched_at_init());
}
// Intel Core and newer cpus have fast IDIV instruction (excluding Atom).
@@ -896,7 +901,7 @@
// Core - 256 / prefetchnta
// It will be used only when AllocatePrefetchStyle > 0
- if (is_amd()) { // AMD
+ if (is_amd_family()) { // AMD | Hygon
if (supports_sse2()) {
return 256; // Opteron
} else {
@@ -930,6 +935,11 @@
// that can be used for efficient implementation of
// the intrinsic for java.lang.Thread.onSpinWait()
static bool supports_on_spin_wait() { return supports_sse2(); }
+
+ // support functions for virtualization detection
+ private:
+ static void check_virt_cpuid(uint32_t idx, uint32_t *regs);
+ static void check_virtualizations();
};
#endif // CPU_X86_VM_VERSION_X86_HPP
--- a/src/hotspot/cpu/zero/cppInterpreter_zero.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/zero/cppInterpreter_zero.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -371,14 +371,12 @@
intptr_t result[4 - LogBytesPerWord];
ffi_call(handler->cif(), (void (*)()) function, result, arguments);
- // Change the thread state back to _thread_in_Java.
+ // Change the thread state back to _thread_in_Java and ensure it
+ // is seen by the GC thread.
// ThreadStateTransition::transition_from_native() cannot be used
// here because it does not check for asynchronous exceptions.
// We have to manage the transition ourself.
- thread->set_thread_state(_thread_in_native_trans);
-
- // Make sure new state is visible in the GC thread
- InterfaceSupport::serialize_thread_state(thread);
+ thread->set_thread_state_fence(_thread_in_native_trans);
// Handle safepoint operations, pending suspend requests,
// and pending asynchronous exceptions.
@@ -701,11 +699,11 @@
return stack->sp() + argument_slots;
}
-IRT_ENTRY(void, CppInterpreter::throw_exception(JavaThread* thread,
+JRT_ENTRY(void, CppInterpreter::throw_exception(JavaThread* thread,
Symbol* name,
char* message))
THROW_MSG(name, message);
-IRT_END
+JRT_END
InterpreterFrame *InterpreterFrame::build(Method* const method, TRAPS) {
JavaThread *thread = (JavaThread *) THREAD;
--- a/src/hotspot/cpu/zero/interpreterRT_zero.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/cpu/zero/interpreterRT_zero.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright 2007, 2008, 2010 Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@@ -141,7 +141,7 @@
assert(status == FFI_OK, "should be");
}
-IRT_ENTRY(address,
+JRT_ENTRY(address,
InterpreterRuntime::slow_signature_handler(JavaThread* thread,
Method* method,
intptr_t* unused1,
@@ -162,7 +162,7 @@
handler->finalize();
return (address) handler;
-IRT_END
+JRT_END
void SignatureHandlerLibrary::pd_set_handler(address handlerAddr) {
InterpreterRuntime::SignatureHandler *handler =
--- a/src/hotspot/os/aix/os_perf_aix.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/os/aix/os_perf_aix.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -273,98 +273,12 @@
return n;
}
-static FILE* open_statfile(void) {
- FILE *f;
-
- if ((f = fopen("/proc/stat", "r")) == NULL) {
- static int haveWarned = 0;
- if (!haveWarned) {
- haveWarned = 1;
- }
- }
- return f;
-}
-
-static void
-next_line(FILE *f) {
- int c;
- do {
- c = fgetc(f);
- } while (c != '\n' && c != EOF);
-}
-
/**
- * Return the total number of ticks since the system was booted.
- * If the usedTicks parameter is not NULL, it will be filled with
- * the number of ticks spent on actual processes (user, system or
- * nice processes) since system boot. Note that this is the total number
- * of "executed" ticks on _all_ CPU:s, that is on a n-way system it is
- * n times the number of ticks that has passed in clock time.
- *
- * Returns a negative value if the reading of the ticks failed.
+ * on Linux we got the ticks related information from /proc/stat
+ * this does not work on AIX, libperfstat might be an alternative
*/
static OSReturn get_total_ticks(int which_logical_cpu, CPUPerfTicks* pticks) {
- FILE* fh;
- uint64_t userTicks, niceTicks, systemTicks, idleTicks;
- uint64_t iowTicks = 0, irqTicks = 0, sirqTicks= 0;
- int logical_cpu = -1;
- const int expected_assign_count = (-1 == which_logical_cpu) ? 4 : 5;
- int n;
-
- if ((fh = open_statfile()) == NULL) {
- return OS_ERR;
- }
- if (-1 == which_logical_cpu) {
- n = fscanf(fh, "cpu " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
- UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT,
- &userTicks, &niceTicks, &systemTicks, &idleTicks,
- &iowTicks, &irqTicks, &sirqTicks);
- } else {
- // Move to next line
- next_line(fh);
-
- // find the line for requested cpu faster to just iterate linefeeds?
- for (int i = 0; i < which_logical_cpu; i++) {
- next_line(fh);
- }
-
- n = fscanf(fh, "cpu%u " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
- UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT,
- &logical_cpu, &userTicks, &niceTicks,
- &systemTicks, &idleTicks, &iowTicks, &irqTicks, &sirqTicks);
- }
-
- fclose(fh);
- if (n < expected_assign_count || logical_cpu != which_logical_cpu) {
- return OS_ERR;
- }
- pticks->used = userTicks + niceTicks;
- pticks->usedKernel = systemTicks + irqTicks + sirqTicks;
- pticks->total = userTicks + niceTicks + systemTicks + idleTicks +
- iowTicks + irqTicks + sirqTicks;
-
- return OS_OK;
-}
-
-
-static int get_systemtype(void) {
- static int procEntriesType = UNDETECTED;
- DIR *taskDir;
-
- if (procEntriesType != UNDETECTED) {
- return procEntriesType;
- }
-
- // Check whether we have a task subdirectory
- if ((taskDir = opendir("/proc/self/task")) == NULL) {
- procEntriesType = UNDETECTABLE;
- } else {
- // The task subdirectory exists; we're on a Linux >= 2.6 system
- closedir(taskDir);
- procEntriesType = LINUX26_NPTL;
- }
-
- return procEntriesType;
+ return OS_ERR;
}
/** read user and system ticks from a named procfile, assumed to be in 'stat' format then. */
@@ -378,26 +292,7 @@
* to the JVM on any CPU.
*/
static OSReturn get_jvm_ticks(CPUPerfTicks* pticks) {
- uint64_t userTicks;
- uint64_t systemTicks;
-
- if (get_systemtype() != LINUX26_NPTL) {
- return OS_ERR;
- }
-
- if (read_ticks("/proc/self/stat", &userTicks, &systemTicks) != 2) {
- return OS_ERR;
- }
-
- // get the total
- if (get_total_ticks(-1, pticks) != OS_OK) {
- return OS_ERR;
- }
-
- pticks->used = userTicks;
- pticks->usedKernel = systemTicks;
-
- return OS_OK;
+ return OS_ERR;
}
/**
@@ -461,29 +356,7 @@
}
static int SCANF_ARGS(1, 2) parse_stat(_SCANFMT_ const char* fmt, ...) {
- FILE *f;
- va_list args;
-
- va_start(args, fmt);
-
- if ((f = open_statfile()) == NULL) {
- va_end(args);
- return OS_ERR;
- }
- for (;;) {
- char line[80];
- if (fgets(line, sizeof(line), f) != NULL) {
- if (vsscanf(line, fmt, args) == 1) {
- fclose(f);
- va_end(args);
- return OS_OK;
- }
- } else {
- fclose(f);
- va_end(args);
- return OS_ERR;
- }
- }
+ return OS_ERR;
}
static int get_noof_context_switches(uint64_t* switches) {
--- a/src/hotspot/os/linux/os_linux.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/os/linux/os_linux.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -63,6 +63,7 @@
#include "runtime/threadCritical.hpp"
#include "runtime/threadSMR.hpp"
#include "runtime/timer.hpp"
+#include "runtime/vm_version.hpp"
#include "semaphore_posix.hpp"
#include "services/attachListener.hpp"
#include "services/memTracker.hpp"
@@ -1939,35 +1940,6 @@
return true;
}
-#if defined(S390) || defined(PPC64)
-// keywords_to_match - NULL terminated array of keywords
-static bool print_matching_lines_from_file(const char* filename, outputStream* st, const char* keywords_to_match[]) {
- char* line = NULL;
- size_t length = 0;
- FILE* fp = fopen(filename, "r");
- if (fp == NULL) {
- return false;
- }
-
- st->print_cr("Virtualization information:");
- while (getline(&line, &length, fp) != -1) {
- int i = 0;
- while (keywords_to_match[i] != NULL) {
- if (strncmp(line, keywords_to_match[i], strlen(keywords_to_match[i])) == 0) {
- st->print("%s", line);
- break;
- }
- i++;
- }
- }
-
- free(line);
- fclose(fp);
-
- return true;
-}
-#endif
-
void os::print_dll_info(outputStream *st) {
st->print_cr("Dynamic libraries:");
@@ -2052,7 +2024,7 @@
os::Linux::print_container_info(st);
- os::Linux::print_virtualization_info(st);
+ VM_Version::print_platform_virtualization_info(st);
os::Linux::print_steal_info(st);
}
@@ -2309,40 +2281,6 @@
st->cr();
}
-void os::Linux::print_virtualization_info(outputStream* st) {
-#if defined(S390)
- // /proc/sysinfo contains interesting information about
- // - LPAR
- // - whole "Box" (CPUs )
- // - z/VM / KVM (VM<nn>); this is not available in an LPAR-only setup
- const char* kw[] = { "LPAR", "CPUs", "VM", NULL };
- const char* info_file = "/proc/sysinfo";
-
- if (!print_matching_lines_from_file(info_file, st, kw)) {
- st->print_cr(" <%s Not Available>", info_file);
- }
-#elif defined(PPC64)
- const char* info_file = "/proc/ppc64/lparcfg";
- const char* kw[] = { "system_type=", // qemu indicates PowerKVM
- "partition_entitled_capacity=", // entitled processor capacity percentage
- "partition_max_entitled_capacity=",
- "capacity_weight=", // partition CPU weight
- "partition_active_processors=",
- "partition_potential_processors=",
- "entitled_proc_capacity_available=",
- "capped=", // 0 - uncapped, 1 - vcpus capped at entitled processor capacity percentage
- "shared_processor_mode=", // (non)dedicated partition
- "system_potential_processors=",
- "pool=", // CPU-pool number
- "pool_capacity=",
- "NumLpars=", // on non-KVM machines, NumLpars is not found for full partition mode machines
- NULL };
- if (!print_matching_lines_from_file(info_file, st, kw)) {
- st->print_cr(" <%s Not Available>", info_file);
- }
-#endif
-}
-
void os::Linux::print_steal_info(outputStream* st) {
if (has_initial_tick_info) {
CPUPerfTicks pticks;
--- a/src/hotspot/os/linux/os_linux.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/os/linux/os_linux.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -108,7 +108,6 @@
static void print_full_memory_info(outputStream* st);
static void print_container_info(outputStream* st);
- static void print_virtualization_info(outputStream* st);
static void print_steal_info(outputStream* st);
static void print_distro_info(outputStream* st);
static void print_libversion_info(outputStream* st);
--- a/src/hotspot/os/windows/os_windows.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/os/windows/os_windows.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1601,6 +1601,10 @@
#endif
st->print("OS:");
os::win32::print_windows_version(st);
+
+#ifdef _LP64
+ VM_Version::print_platform_virtualization_info(st);
+#endif
}
void os::win32::print_windows_version(outputStream* st) {
--- a/src/hotspot/os/windows/version.rc Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/os/windows/version.rc Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
//
-// Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 2004, 2019, Oracle and/or its affiliates. All rights reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
//
// This code is free software; you can redistribute it and/or modify it
@@ -36,8 +36,8 @@
//
VS_VERSION_INFO VERSIONINFO
- FILEVERSION JDK_VER
- PRODUCTVERSION JDK_VER
+ FILEVERSION HS_FVER
+ PRODUCTVERSION HS_FVER
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@@ -54,15 +54,15 @@
BEGIN
BLOCK "000004b0"
BEGIN
- VALUE "CompanyName", XSTR(HS_COMPANY) "\0"
- VALUE "FileDescription", XSTR(HS_FILEDESC) "\0"
- VALUE "FileVersion", XSTR(JDK_DOTVER) "\0"
- VALUE "Full Version", XSTR(HS_BUILD_ID) "\0"
- VALUE "InternalName", XSTR(HS_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(HS_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(HS_FNAME) "\0"
- VALUE "ProductName", XSTR(HS_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_DOTVER) "\0"
+ VALUE "CompanyName", XSTR(HS_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(HS_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(HS_VER) "\0"
+ VALUE "Full Version", XSTR(HS_VERSION_STRING) "\0"
+ VALUE "InternalName", XSTR(HS_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(HS_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(HS_FNAME) "\0"
+ VALUE "ProductName", XSTR(HS_NAME) "\0"
+ VALUE "ProductVersion", XSTR(HS_VER) "\0"
END
END
BLOCK "VarFileInfo"
--- a/src/hotspot/share/classfile/javaClasses.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/classfile/javaClasses.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -160,6 +160,7 @@
int java_lang_String::value_offset = 0;
int java_lang_String::hash_offset = 0;
+int java_lang_String::hashIsZero_offset = 0;
int java_lang_String::coder_offset = 0;
bool java_lang_String::initialized = false;
@@ -179,7 +180,8 @@
#define STRING_FIELDS_DO(macro) \
macro(value_offset, k, vmSymbols::value_name(), byte_array_signature, false); \
macro(hash_offset, k, "hash", int_signature, false); \
- macro(coder_offset, k, "coder", byte_signature, false)
+ macro(hashIsZero_offset, k, "hashIsZero", bool_signature, false); \
+ macro(coder_offset, k, "coder", byte_signature, false);
void java_lang_String::compute_offsets() {
if (initialized) {
@@ -507,18 +509,38 @@
}
unsigned int java_lang_String::hash_code(oop java_string) {
- typeArrayOop value = java_lang_String::value(java_string);
- int length = java_lang_String::length(java_string, value);
- // Zero length string will hash to zero with String.hashCode() function.
- if (length == 0) return 0;
-
- bool is_latin1 = java_lang_String::is_latin1(java_string);
-
- if (is_latin1) {
- return java_lang_String::hash_code(value->byte_at_addr(0), length);
+ // The hash and hashIsZero fields are subject to a benign data race,
+ // making it crucial to ensure that any observable result of the
+ // calculation in this method stays correct under any possible read of
+ // these fields. Necessary restrictions to allow this to be correct
+ // without explicit memory fences or similar concurrency primitives is
+ // that we can ever only write to one of these two fields for a given
+ // String instance, and that the computation is idempotent and derived
+ // from immutable state
+ assert(initialized && (hash_offset > 0) && (hashIsZero_offset > 0), "Must be initialized");
+ if (java_lang_String::hash_is_set(java_string)) {
+ return java_string->int_field(hash_offset);
+ }
+
+ typeArrayOop value = java_lang_String::value(java_string);
+ int length = java_lang_String::length(java_string, value);
+ bool is_latin1 = java_lang_String::is_latin1(java_string);
+
+ unsigned int hash = 0;
+ if (length > 0) {
+ if (is_latin1) {
+ hash = java_lang_String::hash_code(value->byte_at_addr(0), length);
+ } else {
+ hash = java_lang_String::hash_code(value->char_at_addr(0), length);
+ }
+ }
+
+ if (hash != 0) {
+ java_string->int_field_put(hash_offset, hash);
} else {
- return java_lang_String::hash_code(value->char_at_addr(0), length);
+ java_string->bool_field_put(hashIsZero_offset, true);
}
+ return hash;
}
char* java_lang_String::as_quoted_ascii(oop java_string) {
@@ -3613,23 +3635,48 @@
resolved_method->address_field_put(_vmtarget_offset, (address)m);
}
+void java_lang_invoke_ResolvedMethodName::set_vmholder(oop resolved_method, oop holder) {
+ assert(is_instance(resolved_method), "wrong type");
+ resolved_method->obj_field_put(_vmholder_offset, holder);
+}
+
oop java_lang_invoke_ResolvedMethodName::find_resolved_method(const methodHandle& m, TRAPS) {
+ const Method* method = m();
+
// lookup ResolvedMethod oop in the table, or create a new one and intern it
- oop resolved_method = ResolvedMethodTable::find_method(m());
- if (resolved_method == NULL) {
- InstanceKlass* k = SystemDictionary::ResolvedMethodName_klass();
- if (!k->is_initialized()) {
- k->initialize(CHECK_NULL);
- }
- oop new_resolved_method = k->allocate_instance(CHECK_NULL);
- new_resolved_method->address_field_put(_vmtarget_offset, (address)m());
- // Add a reference to the loader (actually mirror because unsafe anonymous classes will not have
- // distinct loaders) to ensure the metadata is kept alive.
- // This mirror may be different than the one in clazz field.
- new_resolved_method->obj_field_put(_vmholder_offset, m->method_holder()->java_mirror());
- resolved_method = ResolvedMethodTable::add_method(m, Handle(THREAD, new_resolved_method));
+ oop resolved_method = ResolvedMethodTable::find_method(method);
+ if (resolved_method != NULL) {
+ return resolved_method;
+ }
+
+ InstanceKlass* k = SystemDictionary::ResolvedMethodName_klass();
+ if (!k->is_initialized()) {
+ k->initialize(CHECK_NULL);
}
- return resolved_method;
+
+ oop new_resolved_method = k->allocate_instance(CHECK_NULL);
+
+ NoSafepointVerifier nsv;
+
+ if (method->is_old()) {
+ method = (method->is_deleted()) ? Universe::throw_no_such_method_error() :
+ method->get_new_method();
+ }
+
+ InstanceKlass* holder = method->method_holder();
+
+ set_vmtarget(new_resolved_method, const_cast<Method*>(method));
+ // Add a reference to the loader (actually mirror because unsafe anonymous classes will not have
+ // distinct loaders) to ensure the metadata is kept alive.
+ // This mirror may be different than the one in clazz field.
+ set_vmholder(new_resolved_method, holder->java_mirror());
+
+ // Set flag in class to indicate this InstanceKlass has entries in the table
+ // to avoid walking table during redefinition if none of the redefined classes
+ // have any membernames in the table.
+ holder->set_has_resolved_methods();
+
+ return ResolvedMethodTable::add_method(method, Handle(THREAD, new_resolved_method));
}
oop java_lang_invoke_LambdaForm::vmentry(oop lform) {
--- a/src/hotspot/share/classfile/javaClasses.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/classfile/javaClasses.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -94,6 +94,7 @@
private:
static int value_offset;
static int hash_offset;
+ static int hashIsZero_offset;
static int coder_offset;
static bool initialized;
@@ -132,6 +133,10 @@
assert(initialized && (hash_offset > 0), "Must be initialized");
return hash_offset;
}
+ static int hashIsZero_offset_in_bytes() {
+ assert(initialized && (hashIsZero_offset > 0), "Must be initialized");
+ return hashIsZero_offset;
+ }
static int coder_offset_in_bytes() {
assert(initialized && (coder_offset > 0), "Must be initialized");
return coder_offset;
@@ -139,12 +144,11 @@
static inline void set_value_raw(oop string, typeArrayOop buffer);
static inline void set_value(oop string, typeArrayOop buffer);
- static inline void set_hash(oop string, unsigned int hash);
// Accessors
static inline typeArrayOop value(oop java_string);
static inline typeArrayOop value_no_keepalive(oop java_string);
- static inline unsigned int hash(oop java_string);
+ static inline bool hash_is_set(oop string);
static inline bool is_latin1(oop java_string);
static inline int length(oop java_string);
static inline int length(oop java_string, typeArrayOop string_value);
@@ -1059,6 +1063,8 @@
static Method* vmtarget(oop resolved_method);
static void set_vmtarget(oop resolved_method, Method* method);
+ static void set_vmholder(oop resolved_method, oop holder);
+
// find or create resolved member name
static oop find_resolved_method(const methodHandle& m, TRAPS);
--- a/src/hotspot/share/classfile/javaClasses.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/classfile/javaClasses.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -45,9 +45,9 @@
string->obj_field_put(value_offset, (oop)buffer);
}
-void java_lang_String::set_hash(oop string, unsigned int hash) {
- assert(initialized && (hash_offset > 0), "Must be initialized");
- string->int_field_put(hash_offset, hash);
+bool java_lang_String::hash_is_set(oop java_string) {
+ assert(initialized && (hash_offset > 0) && (hashIsZero_offset > 0), "Must be initialized");
+ return java_string->int_field(hash_offset) != 0 || java_string->bool_field(hashIsZero_offset) != 0;
}
// Accessors
@@ -71,12 +71,6 @@
return (typeArrayOop) java_string->obj_field_access<AS_NO_KEEPALIVE>(value_offset);
}
-unsigned int java_lang_String::hash(oop java_string) {
- assert(initialized && (hash_offset > 0), "Must be initialized");
- assert(is_instance(java_string), "must be java_string");
- return java_string->int_field(hash_offset);
-}
-
bool java_lang_String::is_latin1(oop java_string) {
assert(initialized && (coder_offset > 0), "Must be initialized");
assert(is_instance(java_string), "must be java_string");
--- a/src/hotspot/share/classfile/stringTable.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/classfile/stringTable.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -761,8 +761,6 @@
return true;
}
unsigned int hash = java_lang_String::hash_code(s);
-
- java_lang_String::set_hash(s, hash);
oop new_s = StringTable::create_archived_string(s, Thread::current());
if (new_s == NULL) {
return true;
--- a/src/hotspot/share/classfile/systemDictionary.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/classfile/systemDictionary.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -68,7 +68,6 @@
#include "oops/symbol.hpp"
#include "oops/typeArrayKlass.hpp"
#include "prims/jvmtiExport.hpp"
-#include "prims/resolvedMethodTable.hpp"
#include "prims/methodHandles.hpp"
#include "runtime/arguments.hpp"
#include "runtime/biasedLocking.hpp"
@@ -1836,8 +1835,6 @@
}
GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
- // Trigger cleaning the ResolvedMethodTable even if no unloading occurred.
- ResolvedMethodTable::trigger_cleanup();
if (unloading_occurred) {
SymbolTable::trigger_cleanup();
--- a/src/hotspot/share/compiler/compileBroker.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/compiler/compileBroker.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -135,11 +135,6 @@
volatile jint CompileBroker::_compilation_id = 0;
volatile jint CompileBroker::_osr_compilation_id = 0;
-// Debugging information
-int CompileBroker::_last_compile_type = no_compile;
-int CompileBroker::_last_compile_level = CompLevel_none;
-char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
-
// Performance counters
PerfCounter* CompileBroker::_perf_total_compilation = NULL;
PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
@@ -577,8 +572,6 @@
//
// Initialize the Compilation object
void CompileBroker::compilation_init_phase1(TRAPS) {
- _last_method_compiled[0] = '\0';
-
// No need to initialize compilation system if we do not use it.
if (!UseCompiler) {
return;
@@ -2032,8 +2025,10 @@
// Look up matching directives
directive = DirectivesStack::getMatchingDirective(method, comp);
- // Save information about this method in case of failure.
- set_last_compile(thread, method, is_osr, task_level);
+ // Update compile information when using perfdata.
+ if (UsePerfData) {
+ update_compile_perf_data(thread, method, is_osr);
+ }
DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
}
@@ -2264,58 +2259,49 @@
}
// ------------------------------------------------------------------
-// CompileBroker::set_last_compile
+// CompileBroker::update_compile_perf_data
//
// Record this compilation for debugging purposes.
-void CompileBroker::set_last_compile(CompilerThread* thread, const methodHandle& method, bool is_osr, int comp_level) {
+void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
ResourceMark rm;
char* method_name = method->name()->as_C_string();
- strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
- _last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated
char current_method[CompilerCounters::cmname_buffer_length];
size_t maxLen = CompilerCounters::cmname_buffer_length;
- if (UsePerfData) {
- const char* class_name = method->method_holder()->name()->as_C_string();
-
- size_t s1len = strlen(class_name);
- size_t s2len = strlen(method_name);
+ const char* class_name = method->method_holder()->name()->as_C_string();
- // check if we need to truncate the string
- if (s1len + s2len + 2 > maxLen) {
+ size_t s1len = strlen(class_name);
+ size_t s2len = strlen(method_name);
- // the strategy is to lop off the leading characters of the
- // class name and the trailing characters of the method name.
+ // check if we need to truncate the string
+ if (s1len + s2len + 2 > maxLen) {
- if (s2len + 2 > maxLen) {
- // lop of the entire class name string, let snprintf handle
- // truncation of the method name.
- class_name += s1len; // null string
- }
- else {
- // lop off the extra characters from the front of the class name
- class_name += ((s1len + s2len + 2) - maxLen);
- }
+ // the strategy is to lop off the leading characters of the
+ // class name and the trailing characters of the method name.
+
+ if (s2len + 2 > maxLen) {
+ // lop of the entire class name string, let snprintf handle
+ // truncation of the method name.
+ class_name += s1len; // null string
}
-
- jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
+ else {
+ // lop off the extra characters from the front of the class name
+ class_name += ((s1len + s2len + 2) - maxLen);
+ }
}
- if (CICountOSR && is_osr) {
- _last_compile_type = osr_compile;
- } else {
- _last_compile_type = normal_compile;
- }
- _last_compile_level = comp_level;
+ jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
- if (UsePerfData) {
- CompilerCounters* counters = thread->counters();
- counters->set_current_method(current_method);
- counters->set_compile_type((jlong)_last_compile_type);
+ int last_compile_type = normal_compile;
+ if (CICountOSR && is_osr) {
+ last_compile_type = osr_compile;
}
+
+ CompilerCounters* counters = thread->counters();
+ counters->set_current_method(current_method);
+ counters->set_compile_type((jlong) last_compile_type);
}
-
// ------------------------------------------------------------------
// CompileBroker::push_jni_handle_block
//
@@ -2618,21 +2604,6 @@
tty->print_cr(" nmethod total size : %8d bytes", nmethods_size);
}
-// Debugging output for failure
-void CompileBroker::print_last_compile() {
- if (_last_compile_level != CompLevel_none &&
- compiler(_last_compile_level) != NULL &&
- _last_compile_type != no_compile) {
- if (_last_compile_type == osr_compile) {
- tty->print_cr("Last parse: [osr]%d+++(%d) %s",
- _osr_compilation_id, _last_compile_level, _last_method_compiled);
- } else {
- tty->print_cr("Last parse: %d+++(%d) %s",
- _compilation_id, _last_compile_level, _last_method_compiled);
- }
- }
-}
-
// Print general/accumulated JIT information.
void CompileBroker::print_info(outputStream *out) {
if (out == NULL) out = tty;
--- a/src/hotspot/share/compiler/compileBroker.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/compiler/compileBroker.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -173,10 +173,6 @@
static volatile jint _compilation_id;
static volatile jint _osr_compilation_id;
- static int _last_compile_type;
- static int _last_compile_level;
- static char _last_method_compiled[name_buffer_length];
-
static CompileQueue* _c2_compile_queue;
static CompileQueue* _c1_compile_queue;
@@ -254,7 +250,8 @@
static void invoke_compiler_on_method(CompileTask* task);
static void post_compile(CompilerThread* thread, CompileTask* task, bool success, ciEnv* ci_env,
int compilable, const char* failure_reason);
- static void set_last_compile(CompilerThread *thread, const methodHandle& method, bool is_osr, int comp_level);
+ static void update_compile_perf_data(CompilerThread *thread, const methodHandle& method, bool is_osr);
+
static void push_jni_handle_block();
static void pop_jni_handle_block();
static void collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task);
@@ -382,9 +379,6 @@
// Print a detailed accounting of compilation time
static void print_times(bool per_compiler = true, bool aggregate = true);
- // Debugging output for failure
- static void print_last_compile();
-
// compiler name for debugging
static const char* compiler_name(int comp_level);
--- a/src/hotspot/share/gc/shared/stringdedup/stringDedupTable.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shared/stringdedup/stringDedupTable.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -351,19 +351,14 @@
unsigned int hash = 0;
if (use_java_hash()) {
- // Get hash code from cache
- hash = java_lang_String::hash(java_string);
- }
-
- if (hash == 0) {
+ if (!java_lang_String::hash_is_set(java_string)) {
+ stat->inc_hashed();
+ }
+ hash = java_lang_String::hash_code(java_string);
+ } else {
// Compute hash
hash = hash_code(value, latin1);
stat->inc_hashed();
-
- if (use_java_hash() && hash != 0) {
- // Store hash code in cache
- java_lang_String::set_hash(java_string, hash);
- }
}
typeArrayOop existing_value = lookup_or_add(value, latin1, hash);
--- a/src/hotspot/share/gc/shared/weakProcessor.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shared/weakProcessor.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -31,22 +31,33 @@
#include "gc/shared/weakProcessorPhaseTimes.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/iterator.hpp"
+#include "prims/resolvedMethodTable.hpp"
#include "runtime/globals.hpp"
#include "utilities/macros.hpp"
+template <typename Container>
+class OopsDoAndReportCounts {
+public:
+ void operator()(BoolObjectClosure* is_alive, OopClosure* keep_alive, WeakProcessorPhase phase) {
+ Container::reset_dead_counter();
+
+ CountingSkippedIsAliveClosure<BoolObjectClosure, OopClosure> cl(is_alive, keep_alive);
+ WeakProcessorPhases::oop_storage(phase)->oops_do(&cl);
+
+ Container::inc_dead_counter(cl.num_dead() + cl.num_skipped());
+ Container::finish_dead_counter();
+ }
+};
+
void WeakProcessor::weak_oops_do(BoolObjectClosure* is_alive, OopClosure* keep_alive) {
FOR_EACH_WEAK_PROCESSOR_PHASE(phase) {
if (WeakProcessorPhases::is_serial(phase)) {
WeakProcessorPhases::processor(phase)(is_alive, keep_alive);
} else {
if (WeakProcessorPhases::is_stringtable(phase)) {
- StringTable::reset_dead_counter();
-
- CountingSkippedIsAliveClosure<BoolObjectClosure, OopClosure> cl(is_alive, keep_alive);
- WeakProcessorPhases::oop_storage(phase)->oops_do(&cl);
-
- StringTable::inc_dead_counter(cl.num_dead() + cl.num_skipped());
- StringTable::finish_dead_counter();
+ OopsDoAndReportCounts<StringTable>()(is_alive, keep_alive, phase);
+ } else if (WeakProcessorPhases::is_resolved_method_table(phase)){
+ OopsDoAndReportCounts<ResolvedMethodTable>()(is_alive, keep_alive, phase);
} else {
WeakProcessorPhases::oop_storage(phase)->weak_oops_do(is_alive, keep_alive);
}
@@ -104,6 +115,7 @@
new (states++) StorageState(storage, _nworkers);
}
StringTable::reset_dead_counter();
+ ResolvedMethodTable::reset_dead_counter();
}
WeakProcessor::Task::Task(uint nworkers) :
@@ -134,6 +146,7 @@
FREE_C_HEAP_ARRAY(StorageState, _storage_states);
}
StringTable::finish_dead_counter();
+ ResolvedMethodTable::finish_dead_counter();
}
void WeakProcessor::GangTask::work(uint worker_id) {
--- a/src/hotspot/share/gc/shared/weakProcessor.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shared/weakProcessor.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -32,6 +32,7 @@
#include "gc/shared/weakProcessorPhases.hpp"
#include "gc/shared/weakProcessorPhaseTimes.hpp"
#include "gc/shared/workgroup.hpp"
+#include "prims/resolvedMethodTable.hpp"
#include "utilities/debug.hpp"
class BoolObjectClosure;
@@ -115,6 +116,9 @@
if (WeakProcessorPhases::is_stringtable(phase)) {
StringTable::inc_dead_counter(cl.num_dead() + cl.num_skipped());
}
+ if (WeakProcessorPhases::is_resolved_method_table(phase)) {
+ ResolvedMethodTable::inc_dead_counter(cl.num_dead() + cl.num_skipped());
+ }
}
}
--- a/src/hotspot/share/gc/shared/weakProcessorPhases.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shared/weakProcessorPhases.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -26,6 +26,7 @@
#include "classfile/stringTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "gc/shared/weakProcessorPhases.hpp"
+#include "prims/resolvedMethodTable.hpp"
#include "runtime/jniHandles.hpp"
#include "utilities/debug.hpp"
#include "utilities/macros.hpp"
@@ -80,6 +81,7 @@
JFR_ONLY(case jfr: return "JFR weak processing";)
case jni: return "JNI weak processing";
case stringtable: return "StringTable weak processing";
+ case resolved_method_table: return "ResolvedMethodTable weak processing";
case vm: return "VM weak processing";
default:
ShouldNotReachHere();
@@ -101,6 +103,7 @@
switch (phase) {
case jni: return JNIHandles::weak_global_handles();
case stringtable: return StringTable::weak_storage();
+ case resolved_method_table: return ResolvedMethodTable::weak_storage();
case vm: return SystemDictionary::vm_weak_oop_storage();
default:
ShouldNotReachHere();
@@ -111,3 +114,7 @@
bool WeakProcessorPhases::is_stringtable(Phase phase) {
return phase == stringtable;
}
+
+bool WeakProcessorPhases::is_resolved_method_table(Phase phase) {
+ return phase == resolved_method_table;
+}
--- a/src/hotspot/share/gc/shared/weakProcessorPhases.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shared/weakProcessorPhases.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -45,6 +45,7 @@
// OopStorage phases.
jni,
stringtable,
+ resolved_method_table,
vm
};
@@ -68,6 +69,7 @@
static OopStorage* oop_storage(Phase phase); // Precondition: is_oop_storage(phase)
static bool is_stringtable(Phase phase);
+ static bool is_resolved_method_table(Phase phase);
};
typedef WeakProcessorPhases::Phase WeakProcessorPhase;
--- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -72,7 +72,7 @@
// we hit max_cset. When max_cset is hit, we terminate the cset selection. Note that in this scheme,
// ShenandoahGarbageThreshold is the soft threshold which would be ignored until min_garbage is hit.
- size_t capacity = ShenandoahHeap::heap()->capacity();
+ size_t capacity = ShenandoahHeap::heap()->max_capacity();
size_t free_target = ShenandoahMinFreeThreshold * capacity / 100;
size_t min_garbage = free_target > actual_free ? (free_target - actual_free) : 0;
size_t max_cset = (size_t)(1.0 * ShenandoahEvacReserve * capacity / 100 / ShenandoahEvacWaste);
@@ -123,12 +123,12 @@
bool ShenandoahAdaptiveHeuristics::should_start_normal_gc() const {
ShenandoahHeap* heap = ShenandoahHeap::heap();
- size_t capacity = heap->capacity();
+ size_t capacity = heap->max_capacity();
size_t available = heap->free_set()->available();
// Check if we are falling below the worst limit, time to trigger the GC, regardless of
// anything else.
- size_t min_threshold = ShenandoahMinFreeThreshold * heap->capacity() / 100;
+ size_t min_threshold = ShenandoahMinFreeThreshold * heap->max_capacity() / 100;
if (available < min_threshold) {
log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
available / M, min_threshold / M);
@@ -138,7 +138,7 @@
// Check if are need to learn a bit about the application
const size_t max_learn = ShenandoahLearningSteps;
if (_gc_times_learned < max_learn) {
- size_t init_threshold = ShenandoahInitFreeThreshold * heap->capacity() / 100;
+ size_t init_threshold = ShenandoahInitFreeThreshold * heap->max_capacity() / 100;
if (available < init_threshold) {
log_info(gc)("Trigger: Learning " SIZE_FORMAT " of " SIZE_FORMAT ". Free (" SIZE_FORMAT "M) is below initial threshold (" SIZE_FORMAT "M)",
_gc_times_learned + 1, max_learn, available / M, init_threshold / M);
--- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahCompactHeuristics.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahCompactHeuristics.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -53,8 +53,8 @@
ShenandoahHeap* heap = ShenandoahHeap::heap();
size_t available = heap->free_set()->available();
- size_t threshold_bytes_allocated = heap->capacity() * ShenandoahAllocationThreshold / 100;
- size_t min_threshold = ShenandoahMinFreeThreshold * heap->capacity() / 100;
+ size_t threshold_bytes_allocated = heap->max_capacity() * ShenandoahAllocationThreshold / 100;
+ size_t min_threshold = ShenandoahMinFreeThreshold * heap->max_capacity() / 100;
if (available < min_threshold) {
log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
--- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahPassiveHeuristics.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahPassiveHeuristics.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -81,7 +81,7 @@
// Do not select too large CSet that would overflow the available free space.
// Take at least the entire evacuation reserve, and be free to overflow to free space.
- size_t capacity = ShenandoahHeap::heap()->capacity();
+ size_t capacity = ShenandoahHeap::heap()->max_capacity();
size_t available = MAX2(ShenandoahEvacReserve * capacity / 100, actual_free);
size_t max_cset = (size_t)(available / ShenandoahEvacWaste);
--- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahStaticHeuristics.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahStaticHeuristics.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -52,7 +52,7 @@
bool ShenandoahStaticHeuristics::should_start_normal_gc() const {
ShenandoahHeap* heap = ShenandoahHeap::heap();
- size_t capacity = heap->capacity();
+ size_t capacity = heap->max_capacity();
size_t available = heap->free_set()->available();
size_t threshold_available = (capacity * ShenandoahFreeThreshold) / 100;
--- a/src/hotspot/share/gc/shenandoah/heuristics/shenandoahTraversalHeuristics.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/heuristics/shenandoahTraversalHeuristics.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -41,13 +41,6 @@
FLAG_SET_DEFAULT(ShenandoahKeepAliveBarrier, false);
FLAG_SET_DEFAULT(ShenandoahAllowMixedAllocs, false);
- SHENANDOAH_ERGO_OVERRIDE_DEFAULT(ShenandoahRefProcFrequency, 1);
-
- // Adjust class unloading settings only if globally enabled.
- if (ClassUnloadingWithConcurrentMark) {
- SHENANDOAH_ERGO_OVERRIDE_DEFAULT(ShenandoahUnloadClassesFrequency, 1);
- }
-
SHENANDOAH_ERGO_ENABLE_FLAG(ExplicitGCInvokesConcurrent);
SHENANDOAH_ERGO_ENABLE_FLAG(ShenandoahImplicitGCInvokesConcurrent);
@@ -124,7 +117,7 @@
// The significant complication is that liveness data was collected at the previous cycle, and only
// for those regions that were allocated before previous cycle started.
- size_t capacity = heap->capacity();
+ size_t capacity = heap->max_capacity();
size_t actual_free = heap->free_set()->available();
size_t free_target = ShenandoahMinFreeThreshold * capacity / 100;
size_t min_garbage = free_target > actual_free ? (free_target - actual_free) : 0;
@@ -213,12 +206,12 @@
ShenandoahHeap* heap = ShenandoahHeap::heap();
assert(!heap->has_forwarded_objects(), "no forwarded objects here");
- size_t capacity = heap->capacity();
+ size_t capacity = heap->max_capacity();
size_t available = heap->free_set()->available();
// Check if we are falling below the worst limit, time to trigger the GC, regardless of
// anything else.
- size_t min_threshold = ShenandoahMinFreeThreshold * heap->capacity() / 100;
+ size_t min_threshold = ShenandoahMinFreeThreshold * heap->max_capacity() / 100;
if (available < min_threshold) {
log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
available / M, min_threshold / M);
@@ -228,7 +221,7 @@
// Check if are need to learn a bit about the application
const size_t max_learn = ShenandoahLearningSteps;
if (_gc_times_learned < max_learn) {
- size_t init_threshold = ShenandoahInitFreeThreshold * heap->capacity() / 100;
+ size_t init_threshold = ShenandoahInitFreeThreshold * heap->max_capacity() / 100;
if (available < init_threshold) {
log_info(gc)("Trigger: Learning " SIZE_FORMAT " of " SIZE_FORMAT ". Free (" SIZE_FORMAT "M) is below initial threshold (" SIZE_FORMAT "M)",
_gc_times_learned + 1, max_learn, available / M, init_threshold / M);
--- a/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahArguments.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -139,6 +139,11 @@
FLAG_SET_DEFAULT(ShenandoahUncommit, false);
}
+ if ((InitialHeapSize == MaxHeapSize) && ShenandoahUncommit) {
+ log_info(gc)("Min heap equals to max heap, disabling ShenandoahUncommit");
+ FLAG_SET_DEFAULT(ShenandoahUncommit, false);
+ }
+
// If class unloading is disabled, no unloading for concurrent cycles as well.
// If class unloading is enabled, users should opt-in for unloading during
// concurrent cycles.
--- a/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahControlThread.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -462,9 +462,11 @@
void ShenandoahControlThread::service_uncommit(double shrink_before) {
ShenandoahHeap* heap = ShenandoahHeap::heap();
- // Scan through the heap and determine if there is work to do. This avoids taking
- // heap lock if there is no work available, avoids spamming logs with superfluous
- // logging messages, and minimises the amount of work while locks are taken.
+ // Determine if there is work to do. This avoids taking heap lock if there is
+ // no work available, avoids spamming logs with superfluous logging messages,
+ // and minimises the amount of work while locks are taken.
+
+ if (heap->committed() <= heap->min_capacity()) return;
bool has_work = false;
for (size_t i = 0; i < heap->num_regions(); i++) {
--- a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -430,7 +430,7 @@
}
// Evac reserve: reserve trailing space for evacuations
- size_t to_reserve = ShenandoahEvacReserve * _heap->capacity() / 100;
+ size_t to_reserve = ShenandoahEvacReserve * _heap->max_capacity() / 100;
size_t reserved = 0;
for (size_t idx = _heap->num_regions() - 1; idx > 0; idx--) {
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -141,6 +141,7 @@
//
size_t init_byte_size = collector_policy()->initial_heap_byte_size();
+ size_t min_byte_size = collector_policy()->min_heap_byte_size();
size_t max_byte_size = collector_policy()->max_heap_byte_size();
size_t heap_alignment = collector_policy()->heap_alignment();
@@ -159,8 +160,13 @@
size_t num_committed_regions = init_byte_size / reg_size_bytes;
num_committed_regions = MIN2(num_committed_regions, _num_regions);
assert(num_committed_regions <= _num_regions, "sanity");
-
_initial_size = num_committed_regions * reg_size_bytes;
+
+ size_t num_min_regions = min_byte_size / reg_size_bytes;
+ num_min_regions = MIN2(num_min_regions, _num_regions);
+ assert(num_min_regions <= _num_regions, "sanity");
+ _minimum_size = num_min_regions * reg_size_bytes;
+
_committed = _initial_size;
size_t heap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
@@ -351,8 +357,11 @@
_control_thread = new ShenandoahControlThread();
- log_info(gc, init)("Initialize Shenandoah heap with initial size " SIZE_FORMAT "%s",
- byte_size_in_proper_unit(_initial_size), proper_unit_for_byte_size(_initial_size));
+ log_info(gc, init)("Initialize Shenandoah heap: " SIZE_FORMAT "%s initial, " SIZE_FORMAT "%s min, " SIZE_FORMAT "%s max",
+ byte_size_in_proper_unit(_initial_size), proper_unit_for_byte_size(_initial_size),
+ byte_size_in_proper_unit(_minimum_size), proper_unit_for_byte_size(_minimum_size),
+ byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity())
+ );
log_info(gc, init)("Safepointing mechanism: %s",
SafepointMechanism::uses_thread_local_poll() ? "thread-local poll" :
@@ -450,8 +459,8 @@
_max_workers = MAX2(_max_workers, 1U);
_workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
- /* are_GC_task_threads */true,
- /* are_ConcurrentGC_threads */false);
+ /* are_GC_task_threads */ true,
+ /* are_ConcurrentGC_threads */ true);
if (_workers == NULL) {
vm_exit_during_initialization("Failed necessary allocation.");
} else {
@@ -461,7 +470,8 @@
if (ShenandoahParallelSafepointThreads > 1) {
_safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
ShenandoahParallelSafepointThreads,
- false, false);
+ /* are_GC_task_threads */ false,
+ /* are_ConcurrentGC_threads */ false);
_safepoint_workers->initialize_workers();
}
}
@@ -502,7 +512,7 @@
void ShenandoahHeap::print_on(outputStream* st) const {
st->print_cr("Shenandoah Heap");
st->print_cr(" " SIZE_FORMAT "K total, " SIZE_FORMAT "K committed, " SIZE_FORMAT "K used",
- capacity() / K, committed() / K, used() / K);
+ max_capacity() / K, committed() / K, used() / K);
st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"K regions",
num_regions(), ShenandoahHeapRegion::region_size_bytes() / K);
@@ -615,13 +625,17 @@
}
size_t ShenandoahHeap::capacity() const {
- return num_regions() * ShenandoahHeapRegion::region_size_bytes();
+ return committed();
}
size_t ShenandoahHeap::max_capacity() const {
return _num_regions * ShenandoahHeapRegion::region_size_bytes();
}
+size_t ShenandoahHeap::min_capacity() const {
+ return _minimum_size;
+}
+
size_t ShenandoahHeap::initial_capacity() const {
return _initial_size;
}
@@ -635,12 +649,22 @@
void ShenandoahHeap::op_uncommit(double shrink_before) {
assert (ShenandoahUncommit, "should be enabled");
+ // Application allocates from the beginning of the heap, and GC allocates at
+ // the end of it. It is more efficient to uncommit from the end, so that applications
+ // could enjoy the near committed regions. GC allocations are much less frequent,
+ // and therefore can accept the committing costs.
+
size_t count = 0;
- for (size_t i = 0; i < num_regions(); i++) {
- ShenandoahHeapRegion* r = get_region(i);
+ for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
+ ShenandoahHeapRegion* r = get_region(i - 1);
if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
ShenandoahHeapLocker locker(lock());
if (r->is_empty_committed()) {
+ // Do not uncommit below minimal capacity
+ if (committed() < min_capacity() + ShenandoahHeapRegion::region_size_bytes()) {
+ break;
+ }
+
r->make_uncommitted();
count++;
}
@@ -649,8 +673,6 @@
}
if (count > 0) {
- log_info(gc)("Uncommitted " SIZE_FORMAT "M. Heap: " SIZE_FORMAT "M reserved, " SIZE_FORMAT "M committed, " SIZE_FORMAT "M used",
- count * ShenandoahHeapRegion::region_size_bytes() / M, capacity() / M, committed() / M, used() / M);
control_thread()->notify_heap_changed();
}
}
--- a/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -115,11 +115,6 @@
};
#endif
-class ShenandoahAlwaysTrueClosure : public BoolObjectClosure {
-public:
- bool do_object_b(oop p) { return true; }
-};
-
class ShenandoahForwardedIsAliveClosure: public BoolObjectClosure {
private:
ShenandoahMarkingContext* const _mark_context;
@@ -198,6 +193,7 @@
//
private:
size_t _initial_size;
+ size_t _minimum_size;
DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile size_t));
volatile size_t _used;
volatile size_t _committed;
@@ -216,6 +212,7 @@
size_t bytes_allocated_since_gc_start();
void reset_bytes_allocated_since_gc_start();
+ size_t min_capacity() const;
size_t max_capacity() const;
size_t initial_capacity() const;
size_t capacity() const;
--- a/src/hotspot/share/gc/shenandoah/shenandoahMonitoringSupport.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahMonitoringSupport.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -46,12 +46,12 @@
ShenandoahHeap* _heap;
public:
ShenandoahGenerationCounters(ShenandoahHeap* heap) :
- GenerationCounters("Heap", 1, 1, heap->initial_capacity(), heap->max_capacity(), heap->committed()),
+ GenerationCounters("Heap", 1, 1, heap->initial_capacity(), heap->max_capacity(), heap->capacity()),
_heap(heap)
{};
virtual void update_all() {
- _current_size->set_value(_heap->committed());
+ _current_size->set_value(_heap->capacity());
}
};
@@ -94,7 +94,7 @@
if (UsePerfData) {
ShenandoahHeap* heap = ShenandoahHeap::heap();
size_t used = heap->used();
- size_t capacity = heap->capacity();
+ size_t capacity = heap->max_capacity();
_heap_counters->update_all();
_space_counters->update_all(capacity, used);
_heap_region_counters->update();
--- a/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -153,7 +153,7 @@
void ShenandoahPacer::setup_for_idle() {
assert(ShenandoahPacing, "Only be here when pacing is enabled");
- size_t initial = _heap->capacity() * ShenandoahPacingIdleSlack / 100;
+ size_t initial = _heap->max_capacity() * ShenandoahPacingIdleSlack / 100;
double tax = 1;
restart_with(initial, tax);
@@ -166,7 +166,7 @@
if (_progress == -1) {
// First initialization, report some prior
Atomic::store((intptr_t)PACING_PROGRESS_ZERO, &_progress);
- return (size_t) (_heap->capacity() * 0.1);
+ return (size_t) (_heap->max_capacity() * 0.1);
} else {
// Record history, and reply historical data
_progress_history->add(_progress);
--- a/src/hotspot/share/gc/shenandoah/shenandoahPhaseTimings.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahPhaseTimings.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -51,6 +51,7 @@
f(scan_jfr_weak_roots, " S: JFR Weak Roots") \
f(scan_jni_weak_roots, " S: JNI Weak Roots") \
f(scan_stringtable_roots, " S: String Table Roots") \
+ f(scan_resolved_method_table_roots, " S: Resolved Table Roots") \
f(scan_vm_weak_roots, " S: VM Weak Roots") \
f(scan_synchronizer_roots, " S: Synchronizer Roots") \
f(scan_management_roots, " S: Management Roots") \
@@ -76,6 +77,7 @@
f(update_jfr_weak_roots, " U: JFR Weak Roots") \
f(update_jni_weak_roots, " U: JNI Weak Roots") \
f(update_stringtable_roots, " U: String Table Roots") \
+ f(update_resolved_method_table_roots, " U: Resolved Table Roots") \
f(update_vm_weak_roots, " U: VM Weak Roots") \
f(update_synchronizer_roots, " U: Synchronizer Roots") \
f(update_management_roots, " U: Management Roots") \
@@ -109,6 +111,7 @@
f(evac_jfr_weak_roots, " E: JFR Weak Roots") \
f(evac_jni_weak_roots, " E: JNI Weak Roots") \
f(evac_stringtable_roots, " E: String Table Roots") \
+ f(evac_resolved_method_table_roots, " E: Resolved Table Roots") \
f(evac_vm_weak_roots, " E: VM Weak Roots") \
f(evac_synchronizer_roots, " E: Synchronizer Roots") \
f(evac_management_roots, " E: Management Roots") \
@@ -139,6 +142,7 @@
f(final_update_jfr_weak_roots, " UR: JFR Weak Roots") \
f(final_update_jni_weak_roots, " UR: JNI Weak Roots") \
f(final_update_stringtable_roots, " UR: String Table Roots") \
+ f(final_update_resolved_method_table_roots, " UR: Resolved Table Roots") \
f(final_update_vm_weak_roots, " UR: VM Weak Roots") \
f(final_update_refs_synchronizer_roots, " UR: Synchronizer Roots") \
f(final_update_refs_management_roots, " UR: Management Roots") \
@@ -164,6 +168,7 @@
f(degen_gc_update_jfr_weak_roots, " DU: JFR Weak Roots") \
f(degen_gc_update_jni_weak_roots, " DU: JNI Weak Roots") \
f(degen_gc_update_stringtable_roots, " DU: String Table Roots") \
+ f(degen_gc_update_resolved_method_table_roots, " DU: Resolved Table Roots") \
f(degen_gc_update_vm_weak_roots, " DU: VM Weak Roots") \
f(degen_gc_update_synchronizer_roots, " DU: Synchronizer Roots") \
f(degen_gc_update_management_roots, " DU: Management Roots") \
@@ -190,6 +195,7 @@
f(init_traversal_gc_jfr_weak_roots, " TI: JFR Weak Roots") \
f(init_traversal_gc_jni_weak_roots, " TI: JNI Weak Roots") \
f(init_traversal_gc_stringtable_roots, " TI: String Table Roots") \
+ f(init_traversal_gc_resolved_method_table_roots, " TI: Resolved Table Roots") \
f(init_traversal_gc_vm_weak_roots, " TI: VM Weak Roots") \
f(init_traversal_gc_synchronizer_roots, " TI: Synchronizer Roots") \
f(init_traversal_gc_management_roots, " TI: Management Roots") \
@@ -213,6 +219,7 @@
f(final_traversal_gc_jfr_weak_roots, " TF: JFR Weak Roots") \
f(final_traversal_gc_jni_weak_roots, " TF: JNI Weak Roots") \
f(final_traversal_gc_stringtable_roots, " TF: String Table Roots") \
+ f(final_traversal_gc_resolved_method_table_roots, " TF: Resolved Table Roots") \
f(final_traversal_gc_vm_weak_roots, " TF: VM Weak Roots") \
f(final_traversal_gc_synchronizer_roots, " TF: Synchronizer Roots") \
f(final_traversal_gc_management_roots, " TF: Management Roots") \
@@ -225,24 +232,25 @@
f(final_traversal_gc_termination, " TF: Termination") \
\
/* Per-thread timer block, should have "roots" counters in consistent order */ \
- f(final_traversal_update_roots, " Update Roots") \
- f(final_traversal_update_thread_roots, " TU: Thread Roots") \
- f(final_traversal_update_code_roots, " TU: Code Cache Roots") \
- f(final_traversal_update_universe_roots, " TU: Universe Roots") \
- f(final_traversal_update_jni_roots, " TU: JNI Roots") \
- f(final_traversal_update_jvmti_weak_roots, " TU: JVMTI Weak Roots") \
- f(final_traversal_update_jfr_weak_roots, " TU: JFR Weak Roots") \
- f(final_traversal_update_jni_weak_roots, " TU: JNI Weak Roots") \
- f(final_traversal_update_stringtable_roots, " TU: String Table Roots") \
- f(final_traversal_update_vm_weak_roots, " TU: VM Weak Roots") \
- f(final_traversal_update_synchronizer_roots, " TU: Synchronizer Roots") \
- f(final_traversal_update_management_roots, " TU: Management Roots") \
- f(final_traversal_update_system_dict_roots, " TU: System Dict Roots") \
- f(final_traversal_update_cldg_roots, " TU: CLDG Roots") \
- f(final_traversal_update_jvmti_roots, " TU: JVMTI Roots") \
- f(final_traversal_update_string_dedup_table_roots, " TU: Dedup Table Roots") \
- f(final_traversal_update_string_dedup_queue_roots, " TU: Dedup Queue Roots") \
- f(final_traversal_update_finish_queues, " TU: Finish Queues") \
+ f(final_traversal_update_roots, " Update Roots") \
+ f(final_traversal_update_thread_roots, " TU: Thread Roots") \
+ f(final_traversal_update_code_roots, " TU: Code Cache Roots") \
+ f(final_traversal_update_universe_roots, " TU: Universe Roots") \
+ f(final_traversal_update_jni_roots, " TU: JNI Roots") \
+ f(final_traversal_update_jvmti_weak_roots, " TU: JVMTI Weak Roots") \
+ f(final_traversal_update_jfr_weak_roots, " TU: JFR Weak Roots") \
+ f(final_traversal_update_jni_weak_roots, " TU: JNI Weak Roots") \
+ f(final_traversal_update_stringtable_roots, " TU: String Table Roots") \
+ f(final_traversal_update_resolved_method_table_roots, " TU: Resolved Table Roots") \
+ f(final_traversal_update_vm_weak_roots, " TU: VM Weak Roots") \
+ f(final_traversal_update_synchronizer_roots, " TU: Synchronizer Roots") \
+ f(final_traversal_update_management_roots, " TU: Management Roots") \
+ f(final_traversal_update_system_dict_roots, " TU: System Dict Roots") \
+ f(final_traversal_update_cldg_roots, " TU: CLDG Roots") \
+ f(final_traversal_update_jvmti_roots, " TU: JVMTI Roots") \
+ f(final_traversal_update_string_dedup_table_roots, " TU: Dedup Table Roots") \
+ f(final_traversal_update_string_dedup_queue_roots, " TU: Dedup Queue Roots") \
+ f(final_traversal_update_finish_queues, " TU: Finish Queues") \
\
f(traversal_gc_cleanup, " Cleanup") \
\
@@ -261,6 +269,7 @@
f(full_gc_jfr_weak_roots, " F: JFR Weak Roots") \
f(full_gc_jni_weak_roots, " F: JNI Weak Roots") \
f(full_gc_stringtable_roots, " F: String Table Roots") \
+ f(full_gc_resolved_method_table_roots, " F: Resolved Table Roots") \
f(full_gc_vm_weak_roots, " F: VM Weak Roots") \
f(full_gc_synchronizer_roots, " F: Synchronizer Roots") \
f(full_gc_management_roots, " F: Management Roots") \
@@ -311,23 +320,24 @@
// end
#define SHENANDOAH_GC_PAR_PHASE_DO(f) \
- f(ThreadRoots, "Thread Roots (ms):") \
- f(CodeCacheRoots, "CodeCache Roots (ms):") \
- f(UniverseRoots, "Universe Roots (ms):") \
- f(JNIRoots, "JNI Handles Roots (ms):") \
- f(JVMTIWeakRoots, "JVMTI Weak Roots (ms):") \
- f(JFRWeakRoots, "JFR Weak Roots (ms):") \
- f(JNIWeakRoots, "JNI Weak Roots (ms):") \
- f(StringTableRoots, "StringTable Roots(ms):") \
- f(VMWeakRoots, "VM Weak Roots(ms)") \
- f(ObjectSynchronizerRoots, "ObjectSynchronizer Roots (ms):") \
- f(ManagementRoots, "Management Roots (ms):") \
- f(SystemDictionaryRoots, "SystemDictionary Roots (ms):") \
- f(CLDGRoots, "CLDG Roots (ms):") \
- f(JVMTIRoots, "JVMTI Roots (ms):") \
- f(StringDedupTableRoots, "String Dedup Table Roots (ms):") \
- f(StringDedupQueueRoots, "String Dedup Queue Roots (ms):") \
- f(FinishQueues, "Finish Queues (ms):") \
+ f(ThreadRoots, "Thread Roots (ms):") \
+ f(CodeCacheRoots, "CodeCache Roots (ms):") \
+ f(UniverseRoots, "Universe Roots (ms):") \
+ f(JNIRoots, "JNI Handles Roots (ms):") \
+ f(JVMTIWeakRoots, "JVMTI Weak Roots (ms):") \
+ f(JFRWeakRoots, "JFR Weak Roots (ms):") \
+ f(JNIWeakRoots, "JNI Weak Roots (ms):") \
+ f(StringTableRoots, "StringTable Roots(ms):") \
+ f(ResolvedMethodTableRoots, "Resolved Table Roots(ms):") \
+ f(VMWeakRoots, "VM Weak Roots(ms)") \
+ f(ObjectSynchronizerRoots, "ObjectSynchronizer Roots (ms):") \
+ f(ManagementRoots, "Management Roots (ms):") \
+ f(SystemDictionaryRoots, "SystemDictionary Roots (ms):") \
+ f(CLDGRoots, "CLDG Roots (ms):") \
+ f(JVMTIRoots, "JVMTI Roots (ms):") \
+ f(StringDedupTableRoots, "String Dedup Table Roots (ms):") \
+ f(StringDedupQueueRoots, "String Dedup Queue Roots (ms):") \
+ f(FinishQueues, "Finish Queues (ms):") \
// end
class ShenandoahPhaseTimings : public CHeapObj<mtGC> {
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -48,14 +48,15 @@
static const struct PhaseMap phase_mapping[] = {
#if INCLUDE_JVMTI
- {WeakProcessorPhases::jvmti, ShenandoahPhaseTimings::JVMTIWeakRoots},
+ {WeakProcessorPhases::jvmti, ShenandoahPhaseTimings::JVMTIWeakRoots},
#endif
#if INCLUDE_JFR
- {WeakProcessorPhases::jfr, ShenandoahPhaseTimings::JFRWeakRoots},
+ {WeakProcessorPhases::jfr, ShenandoahPhaseTimings::JFRWeakRoots},
#endif
- {WeakProcessorPhases::jni, ShenandoahPhaseTimings::JNIWeakRoots},
- {WeakProcessorPhases::stringtable, ShenandoahPhaseTimings::StringTableRoots},
- {WeakProcessorPhases::vm, ShenandoahPhaseTimings::VMWeakRoots}
+ {WeakProcessorPhases::jni, ShenandoahPhaseTimings::JNIWeakRoots},
+ {WeakProcessorPhases::stringtable, ShenandoahPhaseTimings::StringTableRoots},
+ {WeakProcessorPhases::resolved_method_table, ShenandoahPhaseTimings::ResolvedMethodTableRoots},
+ {WeakProcessorPhases::vm, ShenandoahPhaseTimings::VMWeakRoots}
};
STATIC_ASSERT(sizeof(phase_mapping) / sizeof(PhaseMap) == WeakProcessorPhases::phase_count);
@@ -64,7 +65,6 @@
ShenandoahPhaseTimings::Phase phase) :
_process_strong_tasks(new SubTasksDone(SHENANDOAH_RP_PS_NumElements)),
_srs(n_workers),
- _par_state_string(StringTable::weak_storage()),
_phase(phase),
_coderoots_all_iterator(ShenandoahCodeRoots::iterator()),
_weak_processor_timings(n_workers),
--- a/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahRootProcessor.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -56,7 +56,6 @@
class ShenandoahRootProcessor : public StackObj {
SubTasksDone* _process_strong_tasks;
StrongRootsScope _srs;
- OopStorage::ParState<false, false> _par_state_string;
ShenandoahPhaseTimings::Phase _phase;
ParallelCLDRootIterator _cld_iterator;
ShenandoahAllCodeRootsIterator _coderoots_all_iterator;
--- a/src/hotspot/share/gc/shenandoah/shenandoahStringDedup.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahStringDedup.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -92,7 +92,7 @@
void ShenandoahStringDedup::oops_do_slow(OopClosure* cl) {
assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
assert(is_enabled(), "String deduplication not enabled");
- ShenandoahAlwaysTrueClosure always_true;
+ AlwaysTrueClosure always_true;
StringDedupUnlinkOrOopsDoClosure sd_cl(&always_true, cl);
StringDedupQueue::unlink_or_oops_do(&sd_cl);
StringDedupTable::unlink_or_oops_do(&sd_cl, 0);
--- a/src/hotspot/share/gc/shenandoah/shenandoahTimingTracker.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahTimingTracker.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -76,8 +76,11 @@
phase == ShenandoahPhaseTimings::full_gc_weakrefs_termination,
"Only these phases");
- assert(Thread::current()->is_VM_thread() || Thread::current()->is_ConcurrentGC_thread(),
- "Called from wrong thread");
+ assert(!Thread::current()->is_Worker_thread() &&
+ (Thread::current()->is_VM_thread() ||
+ Thread::current()->is_ConcurrentGC_thread()),
+ "Called from wrong thread");
+
_current_termination_phase = phase;
ShenandoahHeap::heap()->phase_timings()->termination_times()->reset();
}
--- a/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -196,6 +196,10 @@
} else {
_rp->process_all_roots(&roots_cl, &cld_cl, &code_cl, NULL, worker_id);
}
+ if (ShenandoahStringDedup::is_enabled()) {
+ AlwaysTrueClosure is_alive;
+ ShenandoahStringDedup::parallel_oops_do(&is_alive, &roots_cl, worker_id);
+ }
}
}
};
@@ -595,11 +599,10 @@
}
if (!_heap->cancelled_gc()) {
+ fixup_roots();
if (_heap->unload_classes()) {
_heap->unload_classes_and_cleanup_tables(false);
}
-
- fixup_roots();
}
if (!_heap->cancelled_gc()) {
@@ -769,29 +772,6 @@
void do_oop(oop* p) { do_oop_work(p); }
};
-class ShenandoahTraversalWeakUpdateClosure : public OopClosure {
-private:
- template <class T>
- inline void do_oop_work(T* p) {
- // Cannot call maybe_update_with_forwarded, because on traversal-degen
- // path the collection set is already dropped. Instead, do the unguarded store.
- // TODO: This can be fixed after degen-traversal stops dropping cset.
- T o = RawAccess<>::oop_load(p);
- if (!CompressedOops::is_null(o)) {
- oop obj = CompressedOops::decode_not_null(o);
- obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
- shenandoah_assert_marked(p, obj);
- RawAccess<IS_NOT_NULL>::oop_store(p, obj);
- }
- }
-
-public:
- ShenandoahTraversalWeakUpdateClosure() {}
-
- void do_oop(narrowOop* p) { do_oop_work(p); }
- void do_oop(oop* p) { do_oop_work(p); }
-};
-
class ShenandoahTraversalKeepAliveUpdateDegenClosure : public OopClosure {
private:
ShenandoahObjToScanQueue* _queue;
@@ -1104,16 +1084,6 @@
&pt);
}
- {
- ShenandoahGCPhase phase(phase_process);
- ShenandoahTerminationTracker termination(ShenandoahPhaseTimings::weakrefs_termination);
-
- // Process leftover weak oops (using parallel version)
- ShenandoahTraversalWeakUpdateClosure cl;
- WeakProcessor::weak_oops_do(workers, &is_alive, &cl, 1);
-
- pt.print_all_references();
-
- assert(task_queues()->is_empty() || _heap->cancelled_gc(), "Should be empty");
- }
+ pt.print_all_references();
+ assert(task_queues()->is_empty() || _heap->cancelled_gc(), "Should be empty");
}
--- a/src/hotspot/share/gc/shenandoah/shenandoahUtils.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/shenandoah/shenandoahUtils.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -100,9 +100,10 @@
ShenandoahGCPhase::ShenandoahGCPhase(const ShenandoahPhaseTimings::Phase phase) :
_heap(ShenandoahHeap::heap()), _phase(phase) {
- assert(Thread::current()->is_VM_thread() ||
- Thread::current()->is_ConcurrentGC_thread(),
- "Must be set by these threads");
+ assert(!Thread::current()->is_Worker_thread() &&
+ (Thread::current()->is_VM_thread() ||
+ Thread::current()->is_ConcurrentGC_thread()),
+ "Must be set by these threads");
_parent_phase = _current_phase;
_current_phase = phase;
--- a/src/hotspot/share/gc/z/zBarrier.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zBarrier.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -123,7 +123,7 @@
}
void ZBarrier::load_barrier_on_oop_fields(oop o) {
- assert(ZOop::is_good(o), "Should be good");
+ assert(ZAddress::is_good(ZOop::to_address(o)), "Should be good");
ZLoadBarrierOopClosure cl;
o->oop_iterate(&cl);
}
--- a/src/hotspot/share/gc/z/zBarrier.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zBarrier.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -37,7 +37,7 @@
retry:
// Fast path
if (fast_path(addr)) {
- return ZOop::to_oop(addr);
+ return ZOop::from_address(addr);
}
// Slow path
@@ -56,7 +56,7 @@
}
}
- return ZOop::to_oop(good_addr);
+ return ZOop::from_address(good_addr);
}
template <ZBarrierFastPath fast_path, ZBarrierSlowPath slow_path>
@@ -67,7 +67,7 @@
if (fast_path(addr)) {
// Return the good address instead of the weak good address
// to ensure that the currently active heap view is used.
- return ZOop::to_oop(ZAddress::good_or_null(addr));
+ return ZOop::from_address(ZAddress::good_or_null(addr));
}
// Slow path
@@ -95,7 +95,7 @@
}
}
- return ZOop::to_oop(good_addr);
+ return ZOop::from_address(good_addr);
}
template <ZBarrierFastPath fast_path, ZBarrierSlowPath slow_path>
@@ -117,7 +117,7 @@
// to heal the same root if it is aligned, since they would always heal
// the root in the same way and it does not matter in which order it
// happens. For misaligned oops, there needs to be mutual exclusion.
- *p = ZOop::to_oop(good_addr);
+ *p = ZOop::from_address(good_addr);
}
inline bool ZBarrier::is_null_fast_path(uintptr_t addr) {
--- a/src/hotspot/share/gc/z/zForwarding.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zForwarding.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -69,6 +69,11 @@
// Check for duplicates
for (ZForwardingCursor j = i + 1; j < _entries.length(); j++) {
const ZForwardingEntry other = at(&j);
+ if (!other.populated()) {
+ // Skip empty entries
+ continue;
+ }
+
guarantee(entry.from_index() != other.from_index(), "Duplicate from");
guarantee(entry.to_offset() != other.to_offset(), "Duplicate to");
}
--- a/src/hotspot/share/gc/z/zHeap.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zHeap.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -135,7 +135,7 @@
}
inline bool ZHeap::is_oop(oop object) const {
- return ZOop::is_good(object);
+ return ZAddress::is_good(ZOop::to_address(object));
}
#endif // SHARE_GC_Z_ZHEAP_INLINE_HPP
--- a/src/hotspot/share/gc/z/zLiveMap.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zLiveMap.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -144,7 +144,7 @@
const uintptr_t addr = page_start + ((index / 2) << page_object_alignment_shift);
// Apply closure
- cl->do_object(ZOop::to_oop(addr));
+ cl->do_object(ZOop::from_address(addr));
// Find next bit after this object
const size_t size = ZUtils::object_size(addr);
--- a/src/hotspot/share/gc/z/zMark.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zMark.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -200,7 +200,7 @@
}
bool ZMark::is_array(uintptr_t addr) const {
- return ZOop::to_oop(addr)->is_objArray();
+ return ZOop::from_address(addr)->is_objArray();
}
void ZMark::push_partial_array(uintptr_t addr, size_t size, bool finalizable) {
@@ -347,9 +347,9 @@
}
if (is_array(addr)) {
- follow_array_object(objArrayOop(ZOop::to_oop(addr)), finalizable);
+ follow_array_object(objArrayOop(ZOop::from_address(addr)), finalizable);
} else {
- follow_object(ZOop::to_oop(addr), finalizable);
+ follow_object(ZOop::from_address(addr), finalizable);
}
}
--- a/src/hotspot/share/gc/z/zOop.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zOop.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,13 +29,8 @@
class ZOop : public AllStatic {
public:
- static oop to_oop(uintptr_t value);
+ static oop from_address(uintptr_t addr);
static uintptr_t to_address(oop o);
-
- static bool is_good(oop o);
- static bool is_finalizable_good(oop o);
-
- static oop good(oop);
};
#endif // SHARE_GC_Z_ZOOP_HPP
--- a/src/hotspot/share/gc/z/zOop.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zOop.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
* 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,28 +24,14 @@
#ifndef SHARE_GC_Z_ZOOP_INLINE_HPP
#define SHARE_GC_Z_ZOOP_INLINE_HPP
-#include "gc/z/zAddress.inline.hpp"
#include "gc/z/zOop.hpp"
-#include "oops/oopsHierarchy.hpp"
-inline oop ZOop::to_oop(uintptr_t value) {
- return cast_to_oop(value);
+inline oop ZOop::from_address(uintptr_t addr) {
+ return cast_to_oop(addr);
}
inline uintptr_t ZOop::to_address(oop o) {
return cast_from_oop<uintptr_t>(o);
}
-inline bool ZOop::is_good(oop o) {
- return ZAddress::is_good(to_address(o));
-}
-
-inline bool ZOop::is_finalizable_good(oop o) {
- return ZAddress::is_finalizable_good(to_address(o));
-}
-
-inline oop ZOop::good(oop o) {
- return to_oop(ZAddress::good(to_address(o)));
-}
-
#endif // SHARE_GC_Z_ZOOP_INLINE_HPP
--- a/src/hotspot/share/gc/z/zOopClosures.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zOopClosures.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -39,12 +39,14 @@
const oop o = RawAccess<>::oop_load(p);
if (o != NULL) {
- guarantee(ZOop::is_good(o) || ZOop::is_finalizable_good(o),
+ const uintptr_t addr = ZOop::to_address(o);
+ const uintptr_t good_addr = ZAddress::good(addr);
+ guarantee(ZAddress::is_good(addr) || ZAddress::is_finalizable_good(addr),
"Bad oop " PTR_FORMAT " found at " PTR_FORMAT ", expected " PTR_FORMAT,
- p2i(o), p2i(p), p2i(ZOop::good(o)));
- guarantee(oopDesc::is_oop(ZOop::good(o)),
+ addr, p2i(p), good_addr);
+ guarantee(oopDesc::is_oop(ZOop::from_address(good_addr)),
"Bad object " PTR_FORMAT " found at " PTR_FORMAT,
- p2i(o), p2i(p));
+ addr, p2i(p));
}
}
--- a/src/hotspot/share/gc/z/zRootsIterator.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zRootsIterator.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -41,6 +41,7 @@
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "prims/jvmtiExport.hpp"
+#include "prims/resolvedMethodTable.hpp"
#include "runtime/atomic.hpp"
#include "runtime/jniHandles.hpp"
#include "runtime/thread.hpp"
@@ -80,6 +81,7 @@
static const ZStatSubPhase ZSubPhaseConcurrentWeakRootsVMWeakHandles("Concurrent Weak Roots VMWeakHandles");
static const ZStatSubPhase ZSubPhaseConcurrentWeakRootsJNIWeakHandles("Concurrent Weak Roots JNIWeakHandles");
static const ZStatSubPhase ZSubPhaseConcurrentWeakRootsStringTable("Concurrent Weak Roots StringTable");
+static const ZStatSubPhase ZSubPhaseConcurrentWeakRootsResolvedMethodTable("Concurrent Weak Roots ResolvedMethodTable");
template <typename T, void (T::*F)(ZRootsIteratorClosure*)>
ZSerialOopsDo<T, F>::ZSerialOopsDo(T* iter) :
@@ -341,14 +343,18 @@
_vm_weak_handles_iter(SystemDictionary::vm_weak_oop_storage()),
_jni_weak_handles_iter(JNIHandles::weak_global_handles()),
_string_table_iter(StringTable::weak_storage()),
+ _resolved_method_table_iter(ResolvedMethodTable::weak_storage()),
_vm_weak_handles(this),
_jni_weak_handles(this),
- _string_table(this) {
+ _string_table(this),
+ _resolved_method_table(this) {
StringTable::reset_dead_counter();
+ ResolvedMethodTable::reset_dead_counter();
}
ZConcurrentWeakRootsIterator::~ZConcurrentWeakRootsIterator() {
StringTable::finish_dead_counter();
+ ResolvedMethodTable::finish_dead_counter();
}
void ZConcurrentWeakRootsIterator::do_vm_weak_handles(ZRootsIteratorClosure* cl) {
@@ -361,18 +367,19 @@
_jni_weak_handles_iter.oops_do(cl);
}
-class ZStringTableDeadCounterClosure : public ZRootsIteratorClosure {
+template <class Container>
+class ZDeadCounterClosure : public ZRootsIteratorClosure {
private:
ZRootsIteratorClosure* const _cl;
size_t _ndead;
public:
- ZStringTableDeadCounterClosure(ZRootsIteratorClosure* cl) :
+ ZDeadCounterClosure(ZRootsIteratorClosure* cl) :
_cl(cl),
_ndead(0) {}
- ~ZStringTableDeadCounterClosure() {
- StringTable::inc_dead_counter(_ndead);
+ ~ZDeadCounterClosure() {
+ Container::inc_dead_counter(_ndead);
}
virtual void do_oop(oop* p) {
@@ -389,15 +396,22 @@
void ZConcurrentWeakRootsIterator::do_string_table(ZRootsIteratorClosure* cl) {
ZStatTimer timer(ZSubPhaseConcurrentWeakRootsStringTable);
- ZStringTableDeadCounterClosure counter_cl(cl);
+ ZDeadCounterClosure<StringTable> counter_cl(cl);
_string_table_iter.oops_do(&counter_cl);
}
+void ZConcurrentWeakRootsIterator::do_resolved_method_table(ZRootsIteratorClosure* cl) {
+ ZStatTimer timer(ZSubPhaseConcurrentWeakRootsResolvedMethodTable);
+ ZDeadCounterClosure<ResolvedMethodTable> counter_cl(cl);
+ _resolved_method_table_iter.oops_do(&counter_cl);
+}
+
void ZConcurrentWeakRootsIterator::oops_do(ZRootsIteratorClosure* cl) {
ZStatTimer timer(ZSubPhaseConcurrentWeakRoots);
_vm_weak_handles.oops_do(cl);
_jni_weak_handles.oops_do(cl);
_string_table.oops_do(cl);
+ _resolved_method_table.oops_do(cl);
}
ZThreadRootsIterator::ZThreadRootsIterator() :
--- a/src/hotspot/share/gc/z/zRootsIterator.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zRootsIterator.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -149,14 +149,17 @@
ZOopStorageIterator _vm_weak_handles_iter;
ZOopStorageIterator _jni_weak_handles_iter;
ZOopStorageIterator _string_table_iter;
+ ZOopStorageIterator _resolved_method_table_iter;
void do_vm_weak_handles(ZRootsIteratorClosure* cl);
void do_jni_weak_handles(ZRootsIteratorClosure* cl);
void do_string_table(ZRootsIteratorClosure* cl);
+ void do_resolved_method_table(ZRootsIteratorClosure* cl);
- ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_vm_weak_handles> _vm_weak_handles;
- ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_jni_weak_handles> _jni_weak_handles;
- ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_string_table> _string_table;
+ ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_vm_weak_handles> _vm_weak_handles;
+ ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_jni_weak_handles> _jni_weak_handles;
+ ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_string_table> _string_table;
+ ZParallelOopsDo<ZConcurrentWeakRootsIterator, &ZConcurrentWeakRootsIterator::do_resolved_method_table> _resolved_method_table;
public:
ZConcurrentWeakRootsIterator();
--- a/src/hotspot/share/gc/z/zUtils.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/gc/z/zUtils.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -57,7 +57,7 @@
}
inline size_t ZUtils::object_size(uintptr_t addr) {
- return words_to_bytes(ZOop::to_oop(addr)->size());
+ return words_to_bytes(ZOop::from_address(addr)->size());
}
inline void ZUtils::object_copy(uintptr_t from, uintptr_t to, size_t size) {
--- a/src/hotspot/share/interpreter/interpreterRuntime.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/interpreter/interpreterRuntime.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -156,7 +156,7 @@
// Constants
-IRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
+JRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
// access constant pool
LastFrameAccessor last_frame(thread);
ConstantPool* pool = last_frame.method()->constants();
@@ -167,9 +167,9 @@
Klass* klass = pool->klass_at(index, CHECK);
oop java_class = klass->java_mirror();
thread->set_vm_result(java_class);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* thread, Bytecodes::Code bytecode)) {
+JRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* thread, Bytecodes::Code bytecode)) {
assert(bytecode == Bytecodes::_ldc ||
bytecode == Bytecodes::_ldc_w ||
bytecode == Bytecodes::_ldc2_w ||
@@ -219,13 +219,13 @@
thread->set_vm_result_2((Metadata*)flags);
}
}
-IRT_END
+JRT_END
//------------------------------------------------------------------------------------------------------------------------
// Allocation
-IRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* thread, ConstantPool* pool, int index))
+JRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* thread, ConstantPool* pool, int index))
Klass* k = pool->klass_at(index, CHECK);
InstanceKlass* klass = InstanceKlass::cast(k);
@@ -251,23 +251,23 @@
// because the _breakpoint bytecode would be lost.
oop obj = klass->allocate_instance(CHECK);
thread->set_vm_result(obj);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* thread, BasicType type, jint size))
+JRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* thread, BasicType type, jint size))
oop obj = oopFactory::new_typeArray(type, size, CHECK);
thread->set_vm_result(obj);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* thread, ConstantPool* pool, int index, jint size))
+JRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* thread, ConstantPool* pool, int index, jint size))
Klass* klass = pool->klass_at(index, CHECK);
objArrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
thread->set_vm_result(obj);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* thread, jint* first_size_address))
+JRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* thread, jint* first_size_address))
// We may want to pass in more arguments - could make this slightly faster
LastFrameAccessor last_frame(thread);
ConstantPool* constants = last_frame.method()->constants();
@@ -292,18 +292,18 @@
}
oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
thread->set_vm_result(obj);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
+JRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
assert(oopDesc::is_oop(obj), "must be a valid oop");
assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
-IRT_END
+JRT_END
// Quicken instance-of and check-cast bytecodes
-IRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* thread))
// Force resolving; quicken the bytecode
LastFrameAccessor last_frame(thread);
int which = last_frame.get_index_u2(Bytecodes::_checkcast);
@@ -314,7 +314,7 @@
// assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
Klass* klass = cpool->klass_at(which, CHECK);
thread->set_vm_result_2(klass);
-IRT_END
+JRT_END
//------------------------------------------------------------------------------------------------------------------------
@@ -354,10 +354,10 @@
#ifdef CC_INTERP
// As legacy note_trap, but we have more arguments.
-IRT_ENTRY(void, InterpreterRuntime::note_trap(JavaThread* thread, int reason, Method *method, int trap_bci))
+JRT_ENTRY(void, InterpreterRuntime::note_trap(JavaThread* thread, int reason, Method *method, int trap_bci))
methodHandle trap_method(method);
note_trap_inner(thread, reason, trap_method, trap_bci, THREAD);
-IRT_END
+JRT_END
// Class Deoptimization is not visible in BytecodeInterpreter, so we need a wrapper
// for each exception.
@@ -394,16 +394,16 @@
// space left we use the pre-allocated & pre-initialized StackOverflowError
// klass to create an stack overflow error instance. We do not call its
// constructor for the same reason (it is empty, anyway).
-IRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
Handle exception = get_preinitialized_exception(
SystemDictionary::StackOverflowError_klass(),
CHECK);
// Increment counter for hs_err file reporting
Atomic::inc(&Exceptions::_stack_overflow_errors);
THROW_HANDLE(exception);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* thread))
Handle exception = get_preinitialized_exception(
SystemDictionary::StackOverflowError_klass(),
CHECK);
@@ -412,9 +412,9 @@
// Increment counter for hs_err file reporting
Atomic::inc(&Exceptions::_stack_overflow_errors);
THROW_HANDLE(exception);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
+JRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
// lookup exception klass
TempNewSymbol s = SymbolTable::new_symbol(name, CHECK);
if (ProfileTraps) {
@@ -427,10 +427,10 @@
// create exception
Handle exception = Exceptions::new_exception(thread, s, message);
thread->set_vm_result(exception());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
+JRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
// Produce the error message first because note_trap can safepoint
ResourceMark rm(thread);
const char* klass_name = obj->klass()->external_name();
@@ -442,9 +442,9 @@
// create exception, with klass name as detail message
Handle exception = Exceptions::new_exception(thread, s, klass_name);
thread->set_vm_result(exception());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, arrayOopDesc* a, jint index))
+JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, arrayOopDesc* a, jint index))
// Produce the error message first because note_trap can safepoint
ResourceMark rm(thread);
stringStream ss;
@@ -455,9 +455,9 @@
}
THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
+JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
JavaThread* thread, oopDesc* obj))
// Produce the error message first because note_trap can safepoint
@@ -471,7 +471,7 @@
// create exception
THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
-IRT_END
+JRT_END
// exception_handler_for_exception(...) returns the continuation address,
// the exception oop (via TLS) and sets the bci/bcp for the continuation.
@@ -481,7 +481,7 @@
// bci where the exception happened. If the exception was propagated back
// from a call, the expression stack contains the values for the bci at the
// invoke w/o arguments (i.e., as if one were inside the call).
-IRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
+JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
LastFrameAccessor last_frame(thread);
Handle h_exception(thread, exception);
@@ -622,18 +622,18 @@
thread->set_vm_result(h_exception());
return continuation;
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
// nothing to do - eventually we should remove this code entirely (see comments @ call sites)
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
THROW(vmSymbols::java_lang_AbstractMethodError());
-IRT_END
+JRT_END
// This method is called from the "abstract_entry" of the interpreter.
// At that point, the arguments have already been removed from the stack
@@ -641,28 +641,28 @@
// on some platforms the receiver still resides in a register...). Thus,
// we have no choice but print an error message not containing the receiver
// type.
-IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* thread,
+JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* thread,
Method* missingMethod))
ResourceMark rm(thread);
assert(missingMethod != NULL, "sanity");
methodHandle m(thread, missingMethod);
LinkResolver::throw_abstract_method_error(m, THREAD);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* thread,
+JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* thread,
Klass* recvKlass,
Method* missingMethod))
ResourceMark rm(thread);
methodHandle mh = methodHandle(thread, missingMethod);
LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* thread,
+JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* thread,
Klass* recvKlass,
Klass* interfaceKlass))
ResourceMark rm(thread);
@@ -673,7 +673,7 @@
recvKlass ? recvKlass->external_name() : "NULL",
interfaceKlass ? interfaceKlass->external_name() : "NULL");
THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
-IRT_END
+JRT_END
//------------------------------------------------------------------------------------------------------------------------
// Fields
@@ -760,7 +760,7 @@
//%note synchronization_3
//%note monitor_1
-IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
+JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
#ifdef ASSERT
thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
@@ -781,11 +781,11 @@
#ifdef ASSERT
thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
-IRT_END
+JRT_END
//%note monitor_1
-IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
+JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
#ifdef ASSERT
thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
@@ -802,15 +802,15 @@
#ifdef ASSERT
thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
THROW(vmSymbols::java_lang_IllegalMonitorStateException());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
// Returns an illegal exception to install into the current thread. The
// pending_exception flag is cleared so normal exception handling does not
// trigger. Any current installed exception will be overwritten. This
@@ -826,23 +826,23 @@
CATCH);
}
thread->set_vm_result(exception());
-IRT_END
+JRT_END
//------------------------------------------------------------------------------------------------------------------------
// Invokes
-IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
+JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
return method->orig_bytecode_at(method->bci_from(bcp));
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
+JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
+JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
JvmtiExport::post_raw_breakpoint(thread, method, bcp);
-IRT_END
+JRT_END
void InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode) {
Thread* THREAD = thread;
@@ -998,7 +998,7 @@
// This function is the interface to the assembly code. It returns the resolved
// cpCache entry. This doesn't safepoint, but the helper routines safepoint.
// This function will check for redefinition!
-IRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* thread, Bytecodes::Code bytecode)) {
+JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* thread, Bytecodes::Code bytecode)) {
switch (bytecode) {
case Bytecodes::_getstatic:
case Bytecodes::_putstatic:
@@ -1023,7 +1023,7 @@
break;
}
}
-IRT_END
+JRT_END
//------------------------------------------------------------------------------------------------------------------------
// Miscellaneous
@@ -1069,7 +1069,7 @@
return nm;
}
-IRT_ENTRY(nmethod*,
+JRT_ENTRY(nmethod*,
InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
// use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
// flag, in case this method triggers classloading which will call into Java.
@@ -1113,17 +1113,17 @@
}
}
return osr_nm;
-IRT_END
+JRT_END
-IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
+JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
assert(ProfileInterpreter, "must be profiling interpreter");
int bci = method->bci_from(cur_bcp);
MethodData* mdo = method->method_data();
if (mdo == NULL) return 0;
return mdo->bci_to_di(bci);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
// use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
// flag, in case this method triggers classloading which will call into Java.
UnlockFlagSaver fs(thread);
@@ -1138,11 +1138,11 @@
CLEAR_PENDING_EXCEPTION;
// and fall through...
}
-IRT_END
+JRT_END
#ifdef ASSERT
-IRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
+JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
assert(ProfileInterpreter, "must be profiling interpreter");
MethodData* mdo = method->method_data();
@@ -1169,10 +1169,10 @@
method->print_codes();
}
assert(mdp == mdp2, "wrong mdp");
-IRT_END
+JRT_END
#endif // ASSERT
-IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
+JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
assert(ProfileInterpreter, "must be profiling interpreter");
ResourceMark rm(thread);
HandleMark hm(thread);
@@ -1191,24 +1191,24 @@
RetData* rdata = data->as_RetData();
address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
last_frame.set_mdp(new_mdp);
-IRT_END
+JRT_END
-IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
+JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
MethodCounters* mcs = Method::build_method_counters(m, thread);
if (HAS_PENDING_EXCEPTION) {
assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
CLEAR_PENDING_EXCEPTION;
}
return mcs;
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
+JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
// We used to need an explict preserve_arguments here for invoke bytecodes. However,
// stack traversal automatically takes care of preserving arguments for invoke, so
// this is no longer needed.
- // IRT_END does an implicit safepoint check, hence we are guaranteed to block
+ // JRT_END does an implicit safepoint check, hence we are guaranteed to block
// if this is called during a safepoint
if (JvmtiExport::should_post_single_step()) {
@@ -1218,9 +1218,9 @@
LastFrameAccessor last_frame(thread);
JvmtiExport::at_single_stepping_point(thread, last_frame.method(), last_frame.bcp());
}
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
+JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
ConstantPoolCacheEntry *cp_entry))
// check the access_flags for the field in the klass
@@ -1241,9 +1241,9 @@
jfieldID fid = jfieldIDWorkaround::to_jfieldID(cp_entry_f1, cp_entry->f2_as_index(), is_static);
LastFrameAccessor last_frame(thread);
JvmtiExport::post_field_access(thread, last_frame.method(), last_frame.bcp(), cp_entry_f1, h_obj, fid);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
+JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
Klass* k = cp_entry->f1_as_klass();
@@ -1298,24 +1298,24 @@
LastFrameAccessor last_frame(thread);
JvmtiExport::post_raw_field_modification(thread, last_frame.method(), last_frame.bcp(), ik, h_obj,
fid, sig_type, &fvalue);
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
+JRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
LastFrameAccessor last_frame(thread);
JvmtiExport::post_method_entry(thread, last_frame.method(), last_frame.get_frame());
-IRT_END
+JRT_END
-IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
+JRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
LastFrameAccessor last_frame(thread);
JvmtiExport::post_method_exit(thread, last_frame.method(), last_frame.get_frame());
-IRT_END
+JRT_END
-IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
+JRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
{
return (Interpreter::contains(pc) ? 1 : 0);
}
-IRT_END
+JRT_END
// Implementation of SignatureHandlerLibrary
@@ -1508,7 +1508,7 @@
address SignatureHandlerLibrary::_buffer = NULL;
-IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
+JRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
methodHandle m(thread, method);
assert(m->is_native(), "sanity check");
// lookup native function entry point if it doesn't exist
@@ -1522,10 +1522,10 @@
// before trying to fetch the native entry point and klass mirror.
// We must set the signature handler last, so that multiple processors
// preparing the same method will be sure to see non-null entry & mirror.
-IRT_END
+JRT_END
#if defined(IA32) || defined(AMD64) || defined(ARM)
-IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
+JRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
if (src_address == dest_address) {
return;
}
@@ -1541,7 +1541,7 @@
int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
Copy::conjoint_jbytes(src_address, dest_address,
size_of_arguments * Interpreter::stackElementSize);
-IRT_END
+JRT_END
#endif
#if INCLUDE_JVMTI
@@ -1551,7 +1551,7 @@
// The member_name argument is a saved reference (in local#0) to the member_name.
// For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
// FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
-IRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
+JRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
Method* method, address bcp))
Bytecodes::Code code = Bytecodes::code_at(method, bcp);
if (code != Bytecodes::_invokestatic) {
@@ -1572,19 +1572,19 @@
} else {
thread->set_vm_result(NULL);
}
-IRT_END
+JRT_END
#endif // INCLUDE_JVMTI
#ifndef PRODUCT
-// This must be a IRT_LEAF function because the interpreter must save registers on x86 to
+// This must be a JRT_LEAF function because the interpreter must save registers on x86 to
// call this, which changes rsp and makes the interpreter's expression stack not walkable.
// The generated code still uses call_VM because that will set up the frame pointer for
// bcp and method.
-IRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
+JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
LastFrameAccessor last_frame(thread);
assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
methodHandle mh(thread, last_frame.method());
BytecodeTracer::trace(mh, last_frame.bcp(), tos, tos2);
return preserve_this_value;
-IRT_END
+JRT_END
#endif // !PRODUCT
--- a/src/hotspot/share/oops/weakHandle.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/oops/weakHandle.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -29,6 +29,7 @@
#include "oops/access.inline.hpp"
#include "oops/oop.hpp"
#include "oops/weakHandle.inline.hpp"
+#include "prims/resolvedMethodTable.hpp"
#include "utilities/debug.hpp"
#include "utilities/ostream.hpp"
@@ -40,6 +41,10 @@
return StringTable::weak_storage();
}
+template <> OopStorage* WeakHandle<vm_resolved_method_table_data>::get_storage() {
+ return ResolvedMethodTable::weak_storage();
+}
+
template <WeakHandleType T>
WeakHandle<T> WeakHandle<T>::create(Handle obj) {
assert(obj() != NULL, "no need to create weak null oop");
@@ -74,4 +79,4 @@
// Provide instantiation.
template class WeakHandle<vm_class_loader_data>;
template class WeakHandle<vm_string_table_data>;
-
+template class WeakHandle<vm_resolved_method_table_data>;
--- a/src/hotspot/share/oops/weakHandle.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/oops/weakHandle.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -39,7 +39,7 @@
// This is the vm version of jweak but has different GC lifetimes and policies,
// depending on the type.
-enum WeakHandleType { vm_class_loader_data, vm_string_table_data };
+enum WeakHandleType { vm_class_loader_data, vm_string_table_data, vm_resolved_method_table_data };
template <WeakHandleType T>
class WeakHandle {
@@ -64,6 +64,4 @@
void print_on(outputStream* st) const;
};
-typedef WeakHandle<vm_class_loader_data> ClassLoaderWeakHandle;
-
#endif // SHARE_OOPS_WEAKHANDLE_HPP
--- a/src/hotspot/share/prims/jni.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/jni.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -3971,7 +3971,7 @@
#endif
// Since this is not a JVM_ENTRY we have to set the thread state manually before leaving.
- ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
+ ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
} else {
// If create_vm exits because of a pending exception, exit with that
// exception. In the future when we figure out how to reclaim memory,
@@ -4073,7 +4073,7 @@
res = JNI_OK;
return res;
} else {
- ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
+ ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
res = JNI_ERR;
return res;
}
@@ -4195,7 +4195,7 @@
// using ThreadStateTransition::transition, we do a callback to the safepoint code if
// needed.
- ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
+ ThreadStateTransition::transition(thread, _thread_in_vm, _thread_in_native);
// Perform any platform dependent FPU setup
os::setup_fpu();
--- a/src/hotspot/share/prims/jvmtiCodeBlobEvents.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/jvmtiCodeBlobEvents.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -236,7 +236,7 @@
// Don't hold the lock over the notify or jmethodID creation
MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
current->get_and_cache_jmethod_id();
- JvmtiExport::post_compiled_method_load(current);
+ JvmtiExport::post_compiled_method_load(env, current);
}
return JVMTI_ERROR_NONE;
}
--- a/src/hotspot/share/prims/jvmtiExport.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/jvmtiExport.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -2170,61 +2170,37 @@
JvmtiEnvIterator it;
for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
- if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
- if (env->phase() == JVMTI_PHASE_PRIMORDIAL) {
- continue;
- }
- EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
- ("[%s] class compile method load event sent %s.%s ",
- JvmtiTrace::safe_get_thread_name(thread),
- (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
- (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
- ResourceMark rm(thread);
- HandleMark hm(thread);
-
- // Add inlining information
- jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
- // Pass inlining information through the void pointer
- JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
- JvmtiJavaThreadEventTransition jet(thread);
- jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
- if (callback != NULL) {
- (*callback)(env->jvmti_external(), jem.jni_methodID(),
- jem.code_size(), jem.code_data(), jem.map_length(),
- jem.map(), jem.compile_info());
- }
- }
+ post_compiled_method_load(env, nm);
}
}
-
// post a COMPILED_METHOD_LOAD event for a given environment
-void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, const jmethodID method, const jint length,
- const void *code_begin, const jint map_length,
- const jvmtiAddrLocationMap* map)
-{
- if (env->phase() <= JVMTI_PHASE_PRIMORDIAL) {
+void JvmtiExport::post_compiled_method_load(JvmtiEnv* env, nmethod *nm) {
+ if (env->phase() == JVMTI_PHASE_PRIMORDIAL || !env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
+ return;
+ }
+ jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
+ if (callback == NULL) {
return;
}
JavaThread* thread = JavaThread::current();
- EVT_TRIG_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
- ("[%s] method compile load event triggered (by GenerateEvents)",
- JvmtiTrace::safe_get_thread_name(thread)));
- if (env->is_enabled(JVMTI_EVENT_COMPILED_METHOD_LOAD)) {
-
- EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
- ("[%s] class compile method load event sent (by GenerateEvents), jmethodID=" PTR_FORMAT,
- JvmtiTrace::safe_get_thread_name(thread), p2i(method)));
-
- JvmtiEventMark jem(thread);
- JvmtiJavaThreadEventTransition jet(thread);
- jvmtiEventCompiledMethodLoad callback = env->callbacks()->CompiledMethodLoad;
- if (callback != NULL) {
- (*callback)(env->jvmti_external(), method,
- length, code_begin, map_length,
- map, NULL);
- }
- }
+
+ EVT_TRACE(JVMTI_EVENT_COMPILED_METHOD_LOAD,
+ ("[%s] method compile load event sent %s.%s ",
+ JvmtiTrace::safe_get_thread_name(thread),
+ (nm->method() == NULL) ? "NULL" : nm->method()->klass_name()->as_C_string(),
+ (nm->method() == NULL) ? "NULL" : nm->method()->name()->as_C_string()));
+ ResourceMark rm(thread);
+ HandleMark hm(thread);
+
+ // Add inlining information
+ jvmtiCompiledMethodLoadInlineRecord* inlinerecord = create_inline_record(nm);
+ // Pass inlining information through the void pointer
+ JvmtiCompiledMethodLoadEventMark jem(thread, nm, inlinerecord);
+ JvmtiJavaThreadEventTransition jet(thread);
+ (*callback)(env->jvmti_external(), jem.jni_methodID(),
+ jem.code_size(), jem.code_data(), jem.map_length(),
+ jem.map(), jem.compile_info());
}
void JvmtiExport::post_dynamic_code_generated_internal(const char *name, const void *code_begin, const void *code_end) {
--- a/src/hotspot/share/prims/jvmtiExport.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/jvmtiExport.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -165,9 +165,7 @@
// DynamicCodeGenerated events for a given environment.
friend class JvmtiCodeBlobEvents;
- static void post_compiled_method_load(JvmtiEnv* env, const jmethodID method, const jint length,
- const void *code_begin, const jint map_length,
- const jvmtiAddrLocationMap* map) NOT_JVMTI_RETURN;
+ static void post_compiled_method_load(JvmtiEnv* env, nmethod *nm) NOT_JVMTI_RETURN;
static void post_dynamic_code_generated(JvmtiEnv* env, const char *name, const void *code_begin,
const void *code_end) NOT_JVMTI_RETURN;
--- a/src/hotspot/share/prims/resolvedMethodTable.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/resolvedMethodTable.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -24,223 +24,422 @@
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
+#include "gc/shared/oopStorage.inline.hpp"
#include "logging/log.hpp"
#include "memory/allocation.hpp"
#include "memory/resourceArea.hpp"
#include "oops/access.inline.hpp"
#include "oops/oop.inline.hpp"
#include "oops/method.hpp"
-#include "oops/symbol.hpp"
#include "oops/weakHandle.inline.hpp"
#include "prims/resolvedMethodTable.hpp"
#include "runtime/handles.inline.hpp"
+#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/safepointVerifiers.hpp"
-#include "utilities/hashtable.inline.hpp"
+#include "runtime/timerTrace.hpp"
+#include "utilities/concurrentHashTable.inline.hpp"
+#include "utilities/concurrentHashTableTasks.inline.hpp"
#include "utilities/macros.hpp"
-
-oop ResolvedMethodEntry::object() {
- return literal().resolve();
-}
-
-oop ResolvedMethodEntry::object_no_keepalive() {
- // The AS_NO_KEEPALIVE peeks at the oop without keeping it alive.
- // This is dangerous in general but is okay if the loaded oop does
- // not leak out past a thread transition where a safepoint can happen.
- // A subsequent oop_load without AS_NO_KEEPALIVE (the object() accessor)
- // keeps the oop alive before doing so.
- return literal().peek();
-}
-
-ResolvedMethodTable::ResolvedMethodTable()
- : Hashtable<ClassLoaderWeakHandle, mtClass>(_table_size, sizeof(ResolvedMethodEntry)) { }
+// 2^24 is max size
+static const size_t END_SIZE = 24;
+// If a chain gets to 32 something might be wrong
+static const size_t GROW_HINT = 32;
-oop ResolvedMethodTable::lookup(int index, unsigned int hash, Method* method) {
- assert_locked_or_safepoint(ResolvedMethodTable_lock);
- for (ResolvedMethodEntry* p = bucket(index); p != NULL; p = p->next()) {
- if (p->hash() == hash) {
-
- // Peek the object to check if it is the right target.
- oop target = p->object_no_keepalive();
+static const size_t ResolvedMethodTableSizeLog = 10;
- // The method is in the table as a target already
- if (target != NULL && java_lang_invoke_ResolvedMethodName::vmtarget(target) == method) {
- ResourceMark rm;
- log_debug(membername, table) ("ResolvedMethod entry found for %s index %d",
- method->name_and_sig_as_C_string(), index);
- // The object() accessor makes sure the target object is kept alive before
- // leaking out.
- return p->object();
- }
- }
- }
- return NULL;
-}
-
-unsigned int ResolvedMethodTable::compute_hash(Method* method) {
+unsigned int method_hash(const Method* method) {
unsigned int name_hash = method->name()->identity_hash();
unsigned int signature_hash = method->signature()->identity_hash();
return name_hash ^ signature_hash;
}
+class ResolvedMethodTableConfig : public ResolvedMethodTableHash::BaseConfig {
+ private:
+ public:
+ static uintx get_hash(WeakHandle<vm_resolved_method_table_data> const& value,
+ bool* is_dead) {
+ EXCEPTION_MARK;
+ oop val_oop = value.peek();
+ if (val_oop == NULL) {
+ *is_dead = true;
+ return 0;
+ }
+ *is_dead = false;
+ Method* method = java_lang_invoke_ResolvedMethodName::vmtarget(val_oop);
+ return method_hash(method);
+ }
-oop ResolvedMethodTable::lookup(Method* method) {
- unsigned int hash = compute_hash(method);
- int index = hash_to_index(hash);
- return lookup(index, hash, method);
+ // We use default allocation/deallocation but counted
+ static void* allocate_node(size_t size, WeakHandle<vm_resolved_method_table_data> const& value) {
+ ResolvedMethodTable::item_added();
+ return ResolvedMethodTableHash::BaseConfig::allocate_node(size, value);
+ }
+ static void free_node(void* memory, WeakHandle<vm_resolved_method_table_data> const& value) {
+ value.release();
+ ResolvedMethodTableHash::BaseConfig::free_node(memory, value);
+ ResolvedMethodTable::item_removed();
+ }
+};
+
+ResolvedMethodTableHash* ResolvedMethodTable::_local_table = NULL;
+size_t ResolvedMethodTable::_current_size = (size_t)1 << ResolvedMethodTableSizeLog;
+
+OopStorage* ResolvedMethodTable::_weak_handles = NULL;
+
+volatile bool ResolvedMethodTable::_has_work = false;
+volatile size_t ResolvedMethodTable::_items_count = 0;
+volatile size_t ResolvedMethodTable::_uncleaned_items_count = 0;
+
+void ResolvedMethodTable::create_table() {
+ _local_table = new ResolvedMethodTableHash(ResolvedMethodTableSizeLog, END_SIZE, GROW_HINT);
+ _weak_handles = new OopStorage("ResolvedMethodTable weak",
+ ResolvedMethodTableWeakAlloc_lock,
+ ResolvedMethodTableWeakActive_lock);
+ log_trace(membername, table)("Start size: " SIZE_FORMAT " (" SIZE_FORMAT ")",
+ _current_size, ResolvedMethodTableSizeLog);
+}
+
+size_t ResolvedMethodTable::table_size() {
+ return (size_t)1 << _local_table->get_size_log2(Thread::current());
}
-oop ResolvedMethodTable::basic_add(Method* method, Handle rmethod_name) {
- assert_locked_or_safepoint(ResolvedMethodTable_lock);
+class ResolvedMethodTableLookup : StackObj {
+ private:
+ Thread* _thread;
+ uintx _hash;
+ const Method* _method;
+ Handle _found;
+
+ public:
+ ResolvedMethodTableLookup(Thread* thread, uintx hash, const Method* key)
+ : _thread(thread), _hash(hash), _method(key) {
+ }
+ uintx get_hash() const {
+ return _hash;
+ }
+ bool equals(WeakHandle<vm_resolved_method_table_data>* value, bool* is_dead) {
+ oop val_oop = value->peek();
+ if (val_oop == NULL) {
+ // dead oop, mark this hash dead for cleaning
+ *is_dead = true;
+ return false;
+ }
+ bool equals = _method == java_lang_invoke_ResolvedMethodName::vmtarget(val_oop);
+ if (!equals) {
+ return false;
+ }
+ // Need to resolve weak handle and Handleize through possible safepoint.
+ _found = Handle(_thread, value->resolve());
+ return true;
+ }
+};
+
- unsigned int hash = compute_hash(method);
- int index = hash_to_index(hash);
+class ResolvedMethodGet : public StackObj {
+ Thread* _thread;
+ const Method* _method;
+ Handle _return;
+public:
+ ResolvedMethodGet(Thread* thread, const Method* method) : _thread(thread), _method(method) {}
+ void operator()(WeakHandle<vm_resolved_method_table_data>* val) {
+ oop result = val->resolve();
+ assert(result != NULL, "Result should be reachable");
+ _return = Handle(_thread, result);
+ log_get();
+ }
+ oop get_res_oop() {
+ return _return();
+ }
+ void log_get() {
+ LogTarget(Trace, membername, table) log;
+ if (log.is_enabled()) {
+ ResourceMark rm;
+ log.print("ResolvedMethod entry found for %s",
+ _method->name_and_sig_as_C_string());
+ }
+ }
+};
+
+oop ResolvedMethodTable::find_method(const Method* method) {
+ Thread* thread = Thread::current();
- // One was added while aquiring the lock
- oop entry = lookup(index, hash, method);
- if (entry != NULL) {
- return entry;
+ ResolvedMethodTableLookup lookup(thread, method_hash(method), method);
+ ResolvedMethodGet rmg(thread, method);
+ _local_table->get(thread, lookup, rmg);
+
+ return rmg.get_res_oop();
+}
+
+static void log_insert(const Method* method) {
+ LogTarget(Debug, membername, table) log;
+ if (log.is_enabled()) {
+ ResourceMark rm;
+ log_debug(membername, table) ("ResolvedMethod entry added for %s",
+ method->name_and_sig_as_C_string());
+ }
+}
+
+oop ResolvedMethodTable::add_method(const Method* method, Handle rmethod_name) {
+ Thread* thread = Thread::current();
+
+ ResolvedMethodTableLookup lookup(thread, method_hash(method), method);
+ ResolvedMethodGet rmg(thread, method);
+
+ while (true) {
+ if (_local_table->get(thread, lookup, rmg)) {
+ return rmg.get_res_oop();
+ }
+ WeakHandle<vm_resolved_method_table_data> wh = WeakHandle<vm_resolved_method_table_data>::create(rmethod_name);
+ // The hash table takes ownership of the WeakHandle, even if it's not inserted.
+ if (_local_table->insert(thread, lookup, wh)) {
+ log_insert(method);
+ return wh.resolve();
+ }
}
- ClassLoaderWeakHandle w = ClassLoaderWeakHandle::create(rmethod_name);
- ResolvedMethodEntry* p = (ResolvedMethodEntry*) Hashtable<ClassLoaderWeakHandle, mtClass>::new_entry(hash, w);
- Hashtable<ClassLoaderWeakHandle, mtClass>::add_entry(index, p);
- ResourceMark rm;
- log_debug(membername, table) ("ResolvedMethod entry added for %s index %d",
- method->name_and_sig_as_C_string(), index);
return rmethod_name();
}
-ResolvedMethodTable* ResolvedMethodTable::_the_table = NULL;
+void ResolvedMethodTable::item_added() {
+ Atomic::inc(&_items_count);
+}
+
+void ResolvedMethodTable::item_removed() {
+ Atomic::dec(&_items_count);
+ log_trace(membername, table) ("ResolvedMethod entry removed");
+}
-oop ResolvedMethodTable::find_method(Method* method) {
- MutexLocker ml(ResolvedMethodTable_lock);
- oop entry = _the_table->lookup(method);
- return entry;
+bool ResolvedMethodTable::has_work() {
+ return _has_work;
+}
+
+OopStorage* ResolvedMethodTable::weak_storage() {
+ return _weak_handles;
+}
+
+double ResolvedMethodTable::get_load_factor() {
+ return (double)_items_count/_current_size;
+}
+
+double ResolvedMethodTable::get_dead_factor() {
+ return (double)_uncleaned_items_count/_current_size;
}
-oop ResolvedMethodTable::add_method(const methodHandle& m, Handle resolved_method_name) {
- MutexLocker ml(ResolvedMethodTable_lock);
- DEBUG_ONLY(NoSafepointVerifier nsv);
+static const double PREF_AVG_LIST_LEN = 2.0;
+// If we have as many dead items as 50% of the number of bucket
+static const double CLEAN_DEAD_HIGH_WATER_MARK = 0.5;
- Method* method = m();
- // Check if method has been redefined while taking out ResolvedMethodTable_lock, if so
- // use new method in the ResolvedMethodName. The old method won't be deallocated
- // yet because it's passed in as a Handle.
- if (method->is_old()) {
- method = (method->is_deleted()) ? Universe::throw_no_such_method_error() :
- method->get_new_method();
- java_lang_invoke_ResolvedMethodName::set_vmtarget(resolved_method_name(), method);
+void ResolvedMethodTable::check_concurrent_work() {
+ if (_has_work) {
+ return;
}
- // Set flag in class to indicate this InstanceKlass has entries in the table
- // to avoid walking table during redefinition if none of the redefined classes
- // have any membernames in the table.
- method->method_holder()->set_has_resolved_methods();
-
- return _the_table->basic_add(method, resolved_method_name);
+ double load_factor = get_load_factor();
+ double dead_factor = get_dead_factor();
+ // We should clean/resize if we have more dead than alive,
+ // more items than preferred load factor or
+ // more dead items than water mark.
+ if ((dead_factor > load_factor) ||
+ (load_factor > PREF_AVG_LIST_LEN) ||
+ (dead_factor > CLEAN_DEAD_HIGH_WATER_MARK)) {
+ log_debug(membername, table)("Concurrent work triggered, live factor: %g dead factor: %g",
+ load_factor, dead_factor);
+ trigger_concurrent_work();
+ }
}
-// Removing entries
-int ResolvedMethodTable::_total_oops_removed = 0;
-
-// There are no dead entries at start
-bool ResolvedMethodTable::_dead_entries = false;
-
-void ResolvedMethodTable::trigger_cleanup() {
+void ResolvedMethodTable::trigger_concurrent_work() {
MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
- _dead_entries = true;
+ _has_work = true;
Service_lock->notify_all();
}
-// Serially invoke removed unused oops from the table.
-// This is done by the ServiceThread after being notified on class unloading
-void ResolvedMethodTable::unlink() {
- MutexLocker ml(ResolvedMethodTable_lock);
- int _oops_removed = 0;
- int _oops_counted = 0;
- for (int i = 0; i < _the_table->table_size(); ++i) {
- ResolvedMethodEntry** p = _the_table->bucket_addr(i);
- ResolvedMethodEntry* entry = _the_table->bucket(i);
- while (entry != NULL) {
- _oops_counted++;
- oop l = entry->object_no_keepalive();
- if (l != NULL) {
- p = entry->next_addr();
- } else {
- // Entry has been removed.
- _oops_removed++;
- if (log_is_enabled(Debug, membername, table)) {
- log_debug(membername, table) ("ResolvedMethod entry removed for index %d", i);
- }
- entry->literal().release();
- *p = entry->next();
- _the_table->free_entry(entry);
+void ResolvedMethodTable::do_concurrent_work(JavaThread* jt) {
+ _has_work = false;
+ double load_factor = get_load_factor();
+ log_debug(membername, table)("Concurrent work, live factor: %g", load_factor);
+ // We prefer growing, since that also removes dead items
+ if (load_factor > PREF_AVG_LIST_LEN && !_local_table->is_max_size_reached()) {
+ grow(jt);
+ } else {
+ clean_dead_entries(jt);
+ }
+}
+
+void ResolvedMethodTable::grow(JavaThread* jt) {
+ ResolvedMethodTableHash::GrowTask gt(_local_table);
+ if (!gt.prepare(jt)) {
+ return;
+ }
+ log_trace(membername, table)("Started to grow");
+ {
+ TraceTime timer("Grow", TRACETIME_LOG(Debug, membername, table, perf));
+ while (gt.do_task(jt)) {
+ gt.pause(jt);
+ {
+ ThreadBlockInVM tbivm(jt);
}
- // get next entry
- entry = (ResolvedMethodEntry*)HashtableEntry<ClassLoaderWeakHandle, mtClass>::make_ptr(*p);
+ gt.cont(jt);
+ }
+ }
+ gt.done(jt);
+ _current_size = table_size();
+ log_info(membername, table)("Grown to size:" SIZE_FORMAT, _current_size);
+}
+
+struct ResolvedMethodTableDoDelete : StackObj {
+ void operator()(WeakHandle<vm_resolved_method_table_data>* val) {
+ /* do nothing */
+ }
+};
+
+struct ResolvedMethodTableDeleteCheck : StackObj {
+ long _count;
+ long _item;
+ ResolvedMethodTableDeleteCheck() : _count(0), _item(0) {}
+ bool operator()(WeakHandle<vm_resolved_method_table_data>* val) {
+ ++_item;
+ oop tmp = val->peek();
+ if (tmp == NULL) {
+ ++_count;
+ return true;
+ } else {
+ return false;
}
}
- log_debug(membername, table) ("ResolvedMethod entries counted %d removed %d",
- _oops_counted, _oops_removed);
- _total_oops_removed += _oops_removed;
- _dead_entries = false;
+};
+
+void ResolvedMethodTable::clean_dead_entries(JavaThread* jt) {
+ ResolvedMethodTableHash::BulkDeleteTask bdt(_local_table);
+ if (!bdt.prepare(jt)) {
+ return;
+ }
+ ResolvedMethodTableDeleteCheck stdc;
+ ResolvedMethodTableDoDelete stdd;
+ {
+ TraceTime timer("Clean", TRACETIME_LOG(Debug, membername, table, perf));
+ while(bdt.do_task(jt, stdc, stdd)) {
+ bdt.pause(jt);
+ {
+ ThreadBlockInVM tbivm(jt);
+ }
+ bdt.cont(jt);
+ }
+ bdt.done(jt);
+ }
+ log_info(membername, table)("Cleaned %ld of %ld", stdc._count, stdc._item);
+}
+void ResolvedMethodTable::reset_dead_counter() {
+ _uncleaned_items_count = 0;
+}
+
+void ResolvedMethodTable::inc_dead_counter(size_t ndead) {
+ size_t total = Atomic::add(ndead, &_uncleaned_items_count);
+ log_trace(membername, table)(
+ "Uncleaned items:" SIZE_FORMAT " added: " SIZE_FORMAT " total:" SIZE_FORMAT,
+ _uncleaned_items_count, ndead, total);
}
-#ifndef PRODUCT
-void ResolvedMethodTable::print() {
- MutexLocker ml(ResolvedMethodTable_lock);
- for (int i = 0; i < table_size(); ++i) {
- ResolvedMethodEntry* entry = bucket(i);
- while (entry != NULL) {
- tty->print("%d : ", i);
- oop rmethod_name = entry->object_no_keepalive();
- if (rmethod_name != NULL) {
- rmethod_name->print();
- Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(rmethod_name);
- m->print();
- }
- entry = entry->next();
+// After the parallel walk this method must be called to trigger
+// cleaning. Note it might trigger a resize instead.
+void ResolvedMethodTable::finish_dead_counter() {
+ check_concurrent_work();
+
+#ifdef ASSERT
+ if (SafepointSynchronize::is_at_safepoint()) {
+ size_t fail_cnt = verify_and_compare_entries();
+ if (fail_cnt != 0) {
+ tty->print_cr("ERROR: fail_cnt=" SIZE_FORMAT, fail_cnt);
+ guarantee(fail_cnt == 0, "unexpected ResolvedMethodTable verification failures");
}
}
+#endif // ASSERT
}
-#endif // PRODUCT
#if INCLUDE_JVMTI
+class AdjustMethodEntries : public StackObj {
+ bool* _trace_name_printed;
+public:
+ AdjustMethodEntries(bool* trace_name_printed) : _trace_name_printed(trace_name_printed) {};
+ bool operator()(WeakHandle<vm_resolved_method_table_data>* entry) {
+ oop mem_name = entry->peek();
+ if (mem_name == NULL) {
+ // Removed
+ return true;
+ }
+
+ Method* old_method = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(mem_name);
+
+ if (old_method->is_old()) {
+
+ Method* new_method = (old_method->is_deleted()) ?
+ Universe::throw_no_such_method_error() :
+ old_method->get_new_method();
+ java_lang_invoke_ResolvedMethodName::set_vmtarget(mem_name, new_method);
+
+ ResourceMark rm;
+ if (!(*_trace_name_printed)) {
+ log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
+ *_trace_name_printed = true;
+ }
+ log_debug(redefine, class, update, constantpool)
+ ("ResolvedMethod method update: %s(%s)",
+ new_method->name()->as_C_string(), new_method->signature()->as_C_string());
+ }
+
+ return true;
+ }
+};
+
// It is called at safepoint only for RedefineClasses
void ResolvedMethodTable::adjust_method_entries(bool * trace_name_printed) {
assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
// For each entry in RMT, change to new method
- for (int i = 0; i < _the_table->table_size(); ++i) {
- for (ResolvedMethodEntry* entry = _the_table->bucket(i);
- entry != NULL;
- entry = entry->next()) {
-
- oop mem_name = entry->object_no_keepalive();
- // except ones removed
- if (mem_name == NULL) {
- continue;
- }
- Method* old_method = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(mem_name);
-
- if (old_method->is_old()) {
+ AdjustMethodEntries adjust(trace_name_printed);
+ _local_table->do_safepoint_scan(adjust);
+}
+#endif // INCLUDE_JVMTI
- Method* new_method = (old_method->is_deleted()) ?
- Universe::throw_no_such_method_error() :
- old_method->get_new_method();
- java_lang_invoke_ResolvedMethodName::set_vmtarget(mem_name, new_method);
-
- ResourceMark rm;
- if (!(*trace_name_printed)) {
- log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
- *trace_name_printed = true;
- }
- log_debug(redefine, class, update, constantpool)
- ("ResolvedMethod method update: %s(%s)",
- new_method->name()->as_C_string(), new_method->signature()->as_C_string());
+// Verification and comp
+class VerifyCompResolvedMethod : StackObj {
+ GrowableArray<oop>* _oops;
+ public:
+ size_t _errors;
+ VerifyCompResolvedMethod(GrowableArray<oop>* oops) : _oops(oops), _errors(0) {}
+ bool operator()(WeakHandle<vm_resolved_method_table_data>* val) {
+ oop s = val->peek();
+ if (s == NULL) {
+ return true;
+ }
+ int len = _oops->length();
+ for (int i = 0; i < len; i++) {
+ bool eq = s == _oops->at(i);
+ assert(!eq, "Duplicate entries");
+ if (eq) {
+ _errors++;
}
}
- }
+ _oops->push(s);
+ return true;
+ };
+};
+
+size_t ResolvedMethodTable::items_count() {
+ return _items_count;
}
-#endif // INCLUDE_JVMTI
+
+size_t ResolvedMethodTable::verify_and_compare_entries() {
+ Thread* thr = Thread::current();
+ GrowableArray<oop>* oops =
+ new (ResourceObj::C_HEAP, mtInternal)
+ GrowableArray<oop>((int)_current_size, true);
+
+ VerifyCompResolvedMethod vcs(oops);
+ if (!_local_table->try_scan(thr, vcs)) {
+ log_info(membername, table)("verify unavailable at this moment");
+ }
+ delete oops;
+ return vcs._errors;
+}
--- a/src/hotspot/share/prims/resolvedMethodTable.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/resolvedMethodTable.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -25,89 +25,78 @@
#ifndef SHARE_PRIMS_RESOLVEDMETHODTABLE_HPP
#define SHARE_PRIMS_RESOLVEDMETHODTABLE_HPP
+#include "gc/shared/oopStorage.hpp"
+#include "gc/shared/oopStorageParState.hpp"
+#include "memory/allocation.hpp"
#include "oops/symbol.hpp"
#include "oops/weakHandle.hpp"
+#include "utilities/concurrentHashTable.hpp"
#include "utilities/hashtable.hpp"
-// Hashtable to record Method* used in ResolvedMethods, via. ResolvedMethod oops.
-// This is needed for redefinition to replace Method* with redefined versions.
-
-// Entry in a ResolvedMethodTable, mapping a ClassLoaderWeakHandle for a single oop of
-// java_lang_invoke_ResolvedMethodName which holds JVM Method* in vmtarget.
-
-class ResolvedMethodEntry : public HashtableEntry<ClassLoaderWeakHandle, mtClass> {
- public:
- ResolvedMethodEntry* next() const {
- return (ResolvedMethodEntry*)HashtableEntry<ClassLoaderWeakHandle, mtClass>::next();
- }
-
- ResolvedMethodEntry** next_addr() {
- return (ResolvedMethodEntry**)HashtableEntry<ClassLoaderWeakHandle, mtClass>::next_addr();
- }
-
- oop object();
- oop object_no_keepalive();
-
- void print_on(outputStream* st) const;
-};
+class ResolvedMethodTable;
+class ResolvedMethodTableConfig;
+typedef ConcurrentHashTable<WeakHandle<vm_resolved_method_table_data>, ResolvedMethodTableConfig, mtClass> ResolvedMethodTableHash;
-class ResolvedMethodTable : public Hashtable<ClassLoaderWeakHandle, mtClass> {
- enum Constants {
- _table_size = 1007
- };
-
- static int _total_oops_removed;
-
- static bool _dead_entries;
+class ResolvedMethodTable : public AllStatic {
+ static ResolvedMethodTableHash* _local_table;
+ static size_t _current_size;
- static ResolvedMethodTable* _the_table;
-private:
- ResolvedMethodEntry* bucket(int i) {
- return (ResolvedMethodEntry*) Hashtable<ClassLoaderWeakHandle, mtClass>::bucket(i);
- }
+ static OopStorage* _weak_handles;
- ResolvedMethodEntry** bucket_addr(int i) {
- return (ResolvedMethodEntry**) Hashtable<ClassLoaderWeakHandle, mtClass>::bucket_addr(i);
- }
-
- unsigned int compute_hash(Method* method);
+ static volatile bool _has_work;
- // need not be locked; no state change
- oop lookup(int index, unsigned int hash, Method* method);
- oop lookup(Method* method);
-
- // must be done under ResolvedMethodTable_lock
- oop basic_add(Method* method, Handle rmethod_name);
+ static volatile size_t _items_count;
+ static volatile size_t _uncleaned_items_count;
public:
- ResolvedMethodTable();
+ // Initialization
+ static void create_table();
- static void create_table() {
- assert(_the_table == NULL, "One symbol table allowed.");
- _the_table = new ResolvedMethodTable();
- }
+ static size_t table_size();
+
+ // Lookup and inserts
+ static oop find_method(const Method* method);
+ static oop add_method(const Method* method, Handle rmethod_name);
- // Called from java_lang_invoke_ResolvedMethodName
- static oop find_method(Method* method);
- static oop add_method(const methodHandle& method, Handle rmethod_name);
+ // Callbacks
+ static void item_added();
+ static void item_removed();
+
+ // Cleaning
+ static bool has_work();
- static bool has_work() { return _dead_entries; }
- static void trigger_cleanup();
+ // GC Support - Backing storage for the oop*s
+ static OopStorage* weak_storage();
+
+ // Cleaning and table management
+
+ static double get_load_factor();
+ static double get_dead_factor();
- static int removed_entries_count() { return _total_oops_removed; };
+ static void check_concurrent_work();
+ static void trigger_concurrent_work();
+ static void do_concurrent_work(JavaThread* jt);
-#if INCLUDE_JVMTI
- // It is called at safepoint only for RedefineClasses
- static void adjust_method_entries(bool * trace_name_printed);
-#endif // INCLUDE_JVMTI
+ static void grow(JavaThread* jt);
+ static void clean_dead_entries(JavaThread* jt);
+
+ // GC Notification
- // Cleanup cleared entries
- static void unlink();
+ // Must be called before a parallel walk where objects might die.
+ static void reset_dead_counter();
+ // After the parallel walk this method must be called to trigger
+ // cleaning. Note it might trigger a resize instead.
+ static void finish_dead_counter();
+ // If GC uses ParState directly it should add the number of cleared
+ // entries to this method.
+ static void inc_dead_counter(size_t ndead);
-#ifndef PRODUCT
- void print();
-#endif
- void verify();
+ // JVMTI Support - It is called at safepoint only for RedefineClasses
+ JVMTI_ONLY(static void adjust_method_entries(bool * trace_name_printed);)
+
+ // Debugging
+ static size_t items_count();
+ static size_t verify_and_compare_entries();
};
#endif // SHARE_PRIMS_RESOLVEDMETHODTABLE_HPP
--- a/src/hotspot/share/prims/whitebox.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/prims/whitebox.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -2092,8 +2092,8 @@
#endif
WB_END
-WB_ENTRY(jint, WB_ResolvedMethodRemovedCount(JNIEnv* env, jobject o))
- return (jint) ResolvedMethodTable::removed_entries_count();
+WB_ENTRY(jlong, WB_ResolvedMethodItemsCount(JNIEnv* env, jobject o))
+ return (jlong) ResolvedMethodTable::items_count();
WB_END
WB_ENTRY(jint, WB_ProtectionDomainRemovedCount(JNIEnv* env, jobject o))
@@ -2337,7 +2337,7 @@
{CC"isContainerized", CC"()Z", (void*)&WB_IsContainerized },
{CC"printOsInfo", CC"()V", (void*)&WB_PrintOsInfo },
{CC"disableElfSectionCache", CC"()V", (void*)&WB_DisableElfSectionCache },
- {CC"resolvedMethodRemovedCount", CC"()I", (void*)&WB_ResolvedMethodRemovedCount },
+ {CC"resolvedMethodItemsCount", CC"()J", (void*)&WB_ResolvedMethodItemsCount },
{CC"protectionDomainRemovedCount", CC"()I", (void*)&WB_ProtectionDomainRemovedCount },
{CC"aotLibrariesCount", CC"()I", (void*)&WB_AotLibrariesCount },
};
--- a/src/hotspot/share/runtime/interfaceSupport.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/interfaceSupport.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -66,22 +66,6 @@
static void verify_stack();
static void verify_last_frame();
# endif
-
- public:
- static void serialize_thread_state_with_handler(JavaThread* thread) {
- serialize_thread_state_internal(thread, true);
- }
-
- // Should only call this if we know that we have a proper SEH set up.
- static void serialize_thread_state(JavaThread* thread) {
- serialize_thread_state_internal(thread, false);
- }
-
- private:
- static void serialize_thread_state_internal(JavaThread* thread, bool needs_exception_handler) {
- // Make sure new state is seen by VM thread
- OrderAccess::fence();
- }
};
@@ -103,28 +87,8 @@
assert(from != _thread_in_native, "use transition_from_native");
assert((from & 1) == 0 && (to & 1) == 0, "odd numbers are transitions states");
assert(thread->thread_state() == from, "coming from wrong thread state");
- // Change to transition state
- thread->set_thread_state((JavaThreadState)(from + 1));
-
- InterfaceSupport::serialize_thread_state(thread);
-
- SafepointMechanism::block_if_requested(thread);
- thread->set_thread_state(to);
-
- CHECK_UNHANDLED_OOPS_ONLY(thread->clear_unhandled_oops();)
- }
-
- // transition_and_fence must be used on any thread state transition
- // where there might not be a Java call stub on the stack, in
- // particular on Windows where the Structured Exception Handler is
- // set up in the call stub.
- static inline void transition_and_fence(JavaThread *thread, JavaThreadState from, JavaThreadState to) {
- assert(thread->thread_state() == from, "coming from wrong thread state");
- assert((from & 1) == 0 && (to & 1) == 0, "odd numbers are transitions states");
- // Change to transition state
- thread->set_thread_state((JavaThreadState)(from + 1));
-
- InterfaceSupport::serialize_thread_state_with_handler(thread);
+ // Change to transition state and ensure it is seen by the VM thread.
+ thread->set_thread_state_fence((JavaThreadState)(from + 1));
SafepointMechanism::block_if_requested(thread);
thread->set_thread_state(to);
@@ -143,19 +107,14 @@
static inline void transition_from_native(JavaThread *thread, JavaThreadState to) {
assert((to & 1) == 0, "odd numbers are transitions states");
assert(thread->thread_state() == _thread_in_native, "coming from wrong thread state");
- // Change to transition state
- thread->set_thread_state(_thread_in_native_trans);
-
- InterfaceSupport::serialize_thread_state_with_handler(thread);
+ // Change to transition state and ensure it is seen by the VM thread.
+ thread->set_thread_state_fence(_thread_in_native_trans);
// We never install asynchronous exceptions when coming (back) in
// to the runtime from native code because the runtime is not set
// up to handle exceptions floating around at arbitrary points.
if (SafepointMechanism::should_block(thread) || thread->is_suspend_after_native()) {
JavaThread::check_safepoint_and_suspend_for_native_trans(thread);
-
- // Clear unhandled oops anywhere where we could block, even if we don't.
- CHECK_UNHANDLED_OOPS_ONLY(thread->clear_unhandled_oops();)
}
thread->set_thread_state(to);
@@ -164,7 +123,6 @@
void trans(JavaThreadState from, JavaThreadState to) { transition(_thread, from, to); }
void trans_from_java(JavaThreadState to) { transition_from_java(_thread, to); }
void trans_from_native(JavaThreadState to) { transition_from_native(_thread, to); }
- void trans_and_fence(JavaThreadState from, JavaThreadState to) { transition_and_fence(_thread, from, to); }
};
class ThreadInVMForHandshake : public ThreadStateTransition {
@@ -173,9 +131,8 @@
void transition_back() {
// This can be invoked from transition states and must return to the original state properly
assert(_thread->thread_state() == _thread_in_vm, "should only call when leaving VM after handshake");
- _thread->set_thread_state(_thread_in_vm_trans);
-
- InterfaceSupport::serialize_thread_state(_thread);
+ // Change to transition state and ensure it is seen by the VM thread.
+ _thread->set_thread_state_fence(_thread_in_vm_trans);
SafepointMechanism::block_if_requested(_thread);
@@ -217,7 +174,6 @@
class ThreadInVMfromUnknown {
- private:
JavaThread* _thread;
public:
ThreadInVMfromUnknown() : _thread(NULL) {
@@ -236,7 +192,7 @@
}
~ThreadInVMfromUnknown() {
if (_thread) {
- ThreadStateTransition::transition_and_fence(_thread, _thread_in_vm, _thread_in_native);
+ ThreadStateTransition::transition(_thread, _thread_in_vm, _thread_in_native);
}
}
};
@@ -248,7 +204,7 @@
trans_from_native(_thread_in_vm);
}
~ThreadInVMfromNative() {
- trans_and_fence(_thread_in_vm, _thread_in_native);
+ trans(_thread_in_vm, _thread_in_native);
}
};
@@ -260,7 +216,7 @@
// Block, if we are in the middle of a safepoint synchronization.
assert(!thread->owns_locks(), "must release all locks when leaving VM");
thread->frame_anchor()->make_walkable(thread);
- trans_and_fence(_thread_in_vm, _thread_in_native);
+ trans(_thread_in_vm, _thread_in_native);
// Check for pending. async. exceptions or suspends.
if (_thread->has_special_runtime_exit_condition()) _thread->handle_special_runtime_exit_condition(false);
}
@@ -279,10 +235,10 @@
: ThreadStateTransition(thread) {
// Once we are blocked vm expects stack to be walkable
thread->frame_anchor()->make_walkable(thread);
- trans_and_fence(_thread_in_vm, _thread_blocked);
+ trans(_thread_in_vm, _thread_blocked);
}
~ThreadBlockInVM() {
- trans_and_fence(_thread_blocked, _thread_in_vm);
+ trans(_thread_blocked, _thread_in_vm);
OrderAccess::cross_modify_fence();
// We don't need to clear_walkable because it will happen automagically when we return to java
}
@@ -322,14 +278,10 @@
OrderAccess::storestore();
thread->set_thread_state(_thread_blocked);
-
- CHECK_UNHANDLED_OOPS_ONLY(_thread->clear_unhandled_oops();)
}
~ThreadBlockInVMWithDeadlockCheck() {
- // Change to transition state
- _thread->set_thread_state((JavaThreadState)(_thread_blocked_trans));
-
- InterfaceSupport::serialize_thread_state_with_handler(_thread);
+ // Change to transition state and ensure it is seen by the VM thread.
+ _thread->set_thread_state_fence((JavaThreadState)(_thread_blocked_trans));
if (SafepointMechanism::should_block(_thread)) {
release_monitor();
@@ -337,8 +289,6 @@
}
_thread->set_thread_state(_thread_in_vm);
- CHECK_UNHANDLED_OOPS_ONLY(_thread->clear_unhandled_oops();)
-
OrderAccess::cross_modify_fence();
}
};
@@ -472,30 +422,6 @@
/* begin of body */
-// Definitions for IRT (Interpreter Runtime)
-// (thread is an argument passed in to all these routines)
-
-#define IRT_ENTRY(result_type, header) \
- result_type header { \
- ThreadInVMfromJava __tiv(thread); \
- VM_ENTRY_BASE(result_type, header, thread) \
- debug_only(VMEntryWrapper __vew;)
-
-
-#define IRT_LEAF(result_type, header) \
- result_type header { \
- VM_LEAF_BASE(result_type, header) \
- debug_only(NoSafepointVerifier __nspv(true);)
-
-
-#define IRT_ENTRY_NO_ASYNC(result_type, header) \
- result_type header { \
- ThreadInVMfromJavaNoAsyncException __tiv(thread); \
- VM_ENTRY_BASE(result_type, header, thread) \
- debug_only(VMEntryWrapper __vew;)
-
-#define IRT_END }
-
#define JRT_ENTRY(result_type, header) \
result_type header { \
ThreadInVMfromJava __tiv(thread); \
--- a/src/hotspot/share/runtime/mutex.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/mutex.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -159,7 +159,7 @@
// !no_safepoint_check logically implies java_thread
guarantee(no_safepoint_check || self->is_Java_thread(), "invariant");
- #ifdef ASSERT
+#ifdef ASSERT
Monitor * least = get_least_ranked_lock_besides_this(self->owned_locks());
assert(least != this, "Specification of get_least_... call above");
if (least != NULL && least->rank() <= special) {
@@ -168,7 +168,14 @@
name(), rank(), least->name(), least->rank());
assert(false, "Shouldn't block(wait) while holding a lock of rank special");
}
- #endif // ASSERT
+#endif // ASSERT
+
+#ifdef CHECK_UNHANDLED_OOPS
+ // Clear unhandled oops in JavaThreads so we get a crash right away.
+ if (self->is_Java_thread() && !no_safepoint_check) {
+ self->clear_unhandled_oops();
+ }
+#endif // CHECK_UNHANDLED_OOPS
int wait_status;
// conceptually set the owner to NULL in anticipation of
--- a/src/hotspot/share/runtime/mutexLocker.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/mutexLocker.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -54,7 +54,8 @@
Mutex* JNIHandleBlockFreeList_lock = NULL;
Mutex* VMWeakAlloc_lock = NULL;
Mutex* VMWeakActive_lock = NULL;
-Mutex* ResolvedMethodTable_lock = NULL;
+Mutex* ResolvedMethodTableWeakAlloc_lock = NULL;
+Mutex* ResolvedMethodTableWeakActive_lock = NULL;
Mutex* JmethodIdCreation_lock = NULL;
Mutex* JfieldIdCreation_lock = NULL;
Monitor* JNICritical_lock = NULL;
@@ -212,6 +213,9 @@
def(StringTableWeakAlloc_lock , PaddedMutex , vmweak, true, Monitor::_safepoint_check_never);
def(StringTableWeakActive_lock , PaddedMutex , vmweak-1, true, Monitor::_safepoint_check_never);
+ def(ResolvedMethodTableWeakAlloc_lock , PaddedMutex , vmweak, true, Monitor::_safepoint_check_never);
+ def(ResolvedMethodTableWeakActive_lock , PaddedMutex , vmweak-1, true, Monitor::_safepoint_check_never);
+
if (UseConcMarkSweepGC || UseG1GC) {
def(FullGCCount_lock , PaddedMonitor, leaf, true, Monitor::_safepoint_check_never); // in support of ExplicitGCInvokesConcurrent
}
@@ -298,7 +302,6 @@
def(Heap_lock , PaddedMonitor, nonleaf+1, false, Monitor::_safepoint_check_sometimes);
def(JfieldIdCreation_lock , PaddedMutex , nonleaf+1, true, Monitor::_safepoint_check_always); // jfieldID, Used in VM_Operation
- def(ResolvedMethodTable_lock , PaddedMutex , nonleaf+1, false, Monitor::_safepoint_check_always); // Used to protect ResolvedMethodTable
def(CompiledIC_lock , PaddedMutex , nonleaf+2, false, Monitor::_safepoint_check_never); // locks VtableStubs_lock, InlineCacheBuffer_lock
def(CompileTaskAlloc_lock , PaddedMutex , nonleaf+2, true, Monitor::_safepoint_check_always);
--- a/src/hotspot/share/runtime/mutexLocker.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/mutexLocker.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -48,7 +48,8 @@
extern Mutex* JNIHandleBlockFreeList_lock; // a lock on the JNI handle block free list
extern Mutex* VMWeakAlloc_lock; // VM Weak Handles storage allocate list lock
extern Mutex* VMWeakActive_lock; // VM Weak Handles storage active list lock
-extern Mutex* ResolvedMethodTable_lock; // a lock on the ResolvedMethodTable updates
+extern Mutex* ResolvedMethodTableWeakAlloc_lock; // ResolvedMethodTable weak storage allocate list
+extern Mutex* ResolvedMethodTableWeakActive_lock; // ResolvedMethodTable weak storage active list
extern Mutex* JmethodIdCreation_lock; // a lock on creating JNI method identifiers
extern Mutex* JfieldIdCreation_lock; // a lock on creating JNI static field identifiers
extern Monitor* JNICritical_lock; // a lock used while entering and exiting JNI critical regions, allows GC to sometimes get in
--- a/src/hotspot/share/runtime/safepoint.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/safepoint.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -805,9 +805,9 @@
// This part we can skip if we notice we miss or are in a future safepoint.
OrderAccess::storestore();
- thread->set_thread_state(_thread_blocked);
+ // Load in wait barrier should not float up
+ thread->set_thread_state_fence(_thread_blocked);
- OrderAccess::fence(); // Load in wait barrier should not float up
_wait_barrier->wait(static_cast<int>(safepoint_id));
assert(_state != _synchronized, "Can't be");
--- a/src/hotspot/share/runtime/serviceThread.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/serviceThread.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -190,7 +190,7 @@
}
if (resolved_method_table_work) {
- ResolvedMethodTable::unlink();
+ ResolvedMethodTable::do_concurrent_work(jt);
}
if (protection_domain_table_work) {
--- a/src/hotspot/share/runtime/sharedRuntime.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/sharedRuntime.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1918,7 +1918,7 @@
// where we went int -> i2c -> c2i and so the caller could in fact be
// interpreted. If the caller is compiled we attempt to patch the caller
// so he no longer calls into the interpreter.
-IRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
+JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
Method* moop(method);
address entry_point = moop->from_compiled_entry_no_trampoline();
@@ -1987,7 +1987,7 @@
}
}
}
-IRT_END
+JRT_END
// same as JVM_Arraycopy, but called directly from compiled code
--- a/src/hotspot/share/runtime/thread.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/thread.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1837,7 +1837,7 @@
// Thread is now sufficiently initialized to be handled by the safepoint code as being
// in the VM. Change thread state from _thread_new to _thread_in_vm
- ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
+ ThreadStateTransition::transition(this, _thread_new, _thread_in_vm);
// Before a thread is on the threads list it is always safe, so after leaving the
// _thread_new we should emit a instruction barrier. The distance to modified code
// from here is probably far enough, but this is consistent and safe.
@@ -2475,11 +2475,10 @@
JavaThreadState state = thread_state();
set_thread_state(_thread_blocked);
java_suspend_self();
- set_thread_state(state);
+ set_thread_state_fence(state);
// Since we are not using a regular thread-state transition helper here,
// we must manually emit the instruction barrier after leaving a safe state.
OrderAccess::cross_modify_fence();
- InterfaceSupport::serialize_thread_state_with_handler(this);
if (state != _thread_in_native) {
SafepointMechanism::block_if_requested(this);
}
--- a/src/hotspot/share/runtime/thread.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/thread.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -1288,6 +1288,7 @@
// Safepoint support
inline JavaThreadState thread_state() const;
inline void set_thread_state(JavaThreadState s);
+ inline void set_thread_state_fence(JavaThreadState s); // fence after setting thread state
inline ThreadSafepointState* safepoint_state() const;
inline void set_safepoint_state(ThreadSafepointState* state);
inline bool is_at_poll_safepoint();
--- a/src/hotspot/share/runtime/thread.inline.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/thread.inline.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -141,6 +141,11 @@
#endif
}
+inline void JavaThread::set_thread_state_fence(JavaThreadState s) {
+ set_thread_state(s);
+ OrderAccess::fence();
+}
+
ThreadSafepointState* JavaThread::safepoint_state() const {
return _safepoint_state;
}
--- a/src/hotspot/share/runtime/threadSMR.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/threadSMR.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -590,12 +590,9 @@
}
void ThreadsList::dec_nested_handle_cnt() {
- // The decrement needs to be MO_ACQ_REL. At the moment, the Atomic::dec
- // backend on PPC does not yet conform to these requirements. Therefore
- // the decrement is simulated with an Atomic::sub(1, &addr).
- // Without this MO_ACQ_REL Atomic::dec simulation, the nested SMR mechanism
- // is not generally safe to use.
- Atomic::sub(1, &_nested_handle_cnt);
+ // The decrement only needs to be MO_ACQ_REL since the reference
+ // counter is volatile (and the hazard ptr is already NULL).
+ Atomic::dec(&_nested_handle_cnt);
}
int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
@@ -626,19 +623,9 @@
}
void ThreadsList::inc_nested_handle_cnt() {
- // The increment needs to be MO_SEQ_CST. At the moment, the Atomic::inc
- // backend on PPC does not yet conform to these requirements. Therefore
- // the increment is simulated with a load phi; cas phi + 1; loop.
- // Without this MO_SEQ_CST Atomic::inc simulation, the nested SMR mechanism
- // is not generally safe to use.
- intx sample = OrderAccess::load_acquire(&_nested_handle_cnt);
- for (;;) {
- if (Atomic::cmpxchg(sample + 1, &_nested_handle_cnt, sample) == sample) {
- return;
- } else {
- sample = OrderAccess::load_acquire(&_nested_handle_cnt);
- }
- }
+ // The increment needs to be MO_SEQ_CST so that the reference counter
+ // update is seen before the subsequent hazard ptr update.
+ Atomic::inc(&_nested_handle_cnt);
}
bool ThreadsList::includes(const JavaThread * const p) const {
--- a/src/hotspot/share/runtime/vm_version.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/vm_version.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -44,6 +44,8 @@
unsigned int Abstract_VM_Version::_logical_processors_per_package = 1U;
unsigned int Abstract_VM_Version::_L1_data_cache_line_size = 0;
+VirtualizationType Abstract_VM_Version::_detected_virtualization = NoDetectedVirtualization;
+
#ifndef HOTSPOT_VERSION_STRING
#error HOTSPOT_VERSION_STRING must be defined
#endif
@@ -295,7 +297,6 @@
(Abstract_VM_Version::vm_build_number() & 0xFF);
}
-
void VM_Version_init() {
VM_Version::initialize();
@@ -306,3 +307,27 @@
os::print_cpu_info(&ls, buf, sizeof(buf));
}
}
+
+bool Abstract_VM_Version::print_matching_lines_from_file(const char* filename, outputStream* st, const char* keywords_to_match[]) {
+ char line[500];
+ FILE* fp = fopen(filename, "r");
+ if (fp == NULL) {
+ return false;
+ }
+
+ st->print_cr("Virtualization information:");
+ while (fgets(line, sizeof(line), fp) != NULL) {
+ int i = 0;
+ while (keywords_to_match[i] != NULL) {
+ if (strncmp(line, keywords_to_match[i], strlen(keywords_to_match[i])) == 0) {
+ st->print("%s", line);
+ break;
+ }
+ i++;
+ }
+ }
+ fclose(fp);
+ return true;
+}
+
+
--- a/src/hotspot/share/runtime/vm_version.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/runtime/vm_version.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -29,6 +29,14 @@
#include "utilities/ostream.hpp"
#include "utilities/macros.hpp"
+typedef enum {
+ NoDetectedVirtualization,
+ XenHVM,
+ KVM,
+ VMWare,
+ HyperV
+} VirtualizationType;
+
// VM_Version provides information about the VM.
class Abstract_VM_Version: AllStatic {
@@ -57,6 +65,8 @@
static int _vm_patch_version;
static int _vm_build_number;
+ static VirtualizationType _detected_virtualization;
+
public:
// Called as part of the runtime services initialization which is
// called from the management module initialization (via init_globals())
@@ -111,6 +121,14 @@
return _features_string;
}
+ static VirtualizationType get_detected_virtualization() {
+ return _detected_virtualization;
+ }
+
+ // platforms that need to specialize this
+ // define VM_Version::print_platform_virtualization_info()
+ static void print_platform_virtualization_info(outputStream*) { }
+
// does HW support an 8-byte compare-exchange operation?
static bool supports_cx8() {
#ifdef SUPPORTS_NATIVE_CX8
@@ -149,6 +167,8 @@
// Does this CPU support spin wait instruction?
static bool supports_on_spin_wait() { return false; }
+
+ static bool print_matching_lines_from_file(const char* filename, outputStream* st, const char* keywords_to_match[]);
};
#include CPU_HEADER(vm_version)
--- a/src/hotspot/share/utilities/exceptions.hpp Sat Apr 13 07:22:55 2019 +0100
+++ b/src/hotspot/share/utilities/exceptions.hpp Sat Apr 13 07:23:18 2019 +0100
@@ -237,11 +237,7 @@
// visible within the scope containing the THROW. Usually this is achieved by declaring the function
// with a TRAPS argument.
-#ifdef THIS_FILE
-#define THREAD_AND_LOCATION THREAD, THIS_FILE, __LINE__
-#else
#define THREAD_AND_LOCATION THREAD, __FILE__, __LINE__
-#endif
#define THROW_OOP(e) \
{ Exceptions::_throw_oop(THREAD_AND_LOCATION, e); return; }
--- a/src/java.base/share/classes/java/lang/AbstractStringBuilder.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/AbstractStringBuilder.java Sat Apr 13 07:23:18 2019 +0100
@@ -92,19 +92,57 @@
}
/**
- * Creates an AbstractStringBuilder with the specified coder and with
- * the initial capacity equal to the smaller of (length + addition)
- * and Integer.MAX_VALUE.
+ * Constructs an AbstractStringBuilder that contains the same characters
+ * as the specified {@code String}. The initial capacity of
+ * the string builder is {@code 16} plus the length of the
+ * {@code String} argument.
+ *
+ * @param str the string to copy.
*/
- AbstractStringBuilder(byte coder, int length, int addition) {
+ AbstractStringBuilder(String str) {
+ int length = str.length();
+ int capacity = (length < Integer.MAX_VALUE - 16)
+ ? length + 16 : Integer.MAX_VALUE;
+ final byte initCoder = str.coder();
+ coder = initCoder;
+ value = (initCoder == LATIN1)
+ ? new byte[capacity] : StringUTF16.newBytesFor(capacity);
+ append(str);
+ }
+
+ /**
+ * Constructs an AbstractStringBuilder that contains the same characters
+ * as the specified {@code CharSequence}. The initial capacity of
+ * the string builder is {@code 16} plus the length of the
+ * {@code CharSequence} argument.
+ *
+ * @param seq the sequence to copy.
+ */
+ AbstractStringBuilder(CharSequence seq) {
+ int length = seq.length();
if (length < 0) {
throw new NegativeArraySizeException("Negative length: " + length);
}
- this.coder = coder;
- int capacity = (length < Integer.MAX_VALUE - addition)
- ? length + addition : Integer.MAX_VALUE;
- value = (coder == LATIN1)
+ int capacity = (length < Integer.MAX_VALUE - 16)
+ ? length + 16 : Integer.MAX_VALUE;
+
+ final byte initCoder;
+ if (COMPACT_STRINGS) {
+ if (seq instanceof AbstractStringBuilder) {
+ initCoder = ((AbstractStringBuilder)seq).getCoder();
+ } else if (seq instanceof String) {
+ initCoder = ((String)seq).coder();
+ } else {
+ initCoder = LATIN1;
+ }
+ } else {
+ initCoder = UTF16;
+ }
+
+ coder = initCoder;
+ value = (initCoder == LATIN1)
? new byte[capacity] : StringUTF16.newBytesFor(capacity);
+ append(seq);
}
/**
--- a/src/java.base/share/classes/java/lang/Class.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/Class.java Sat Apr 13 07:23:18 2019 +0100
@@ -277,8 +277,7 @@
.collect(Collectors.joining(",", "<", ">")));
}
- for (int i = 0; i < arrayDepth; i++)
- sb.append("[]");
+ if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
return sb.toString();
}
@@ -1589,12 +1588,7 @@
dimensions++;
cl = cl.getComponentType();
} while (cl.isArray());
- StringBuilder sb = new StringBuilder();
- sb.append(cl.getName());
- for (int i = 0; i < dimensions; i++) {
- sb.append("[]");
- }
- return sb.toString();
+ return cl.getName() + "[]".repeat(dimensions);
} catch (Throwable e) { /*FALLTHRU*/ }
}
return getName();
@@ -3418,15 +3412,12 @@
* Helper method to get the method name from arguments.
*/
private String methodToString(String name, Class<?>[] argTypes) {
- StringBuilder sb = new StringBuilder();
- sb.append(getName() + "." + name + "(");
- if (argTypes != null) {
- sb.append(Arrays.stream(argTypes)
- .map(c -> (c == null) ? "null" : c.getName())
- .collect(Collectors.joining(",")));
- }
- sb.append(")");
- return sb.toString();
+ return getName() + '.' + name +
+ ((argTypes == null || argTypes.length == 0) ?
+ "()" :
+ Arrays.stream(argTypes)
+ .map(c -> c == null ? "null" : c.getName())
+ .collect(Collectors.joining(",", "(", ")")));
}
/** use serialVersionUID from JDK 1.1 for interoperability */
--- a/src/java.base/share/classes/java/lang/Math.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/Math.java Sat Apr 13 07:23:18 2019 +0100
@@ -1274,7 +1274,12 @@
* @since 1.8
*/
public static int floorMod(int x, int y) {
- return x - floorDiv(x, y) * y;
+ int mod = x % y;
+ // if the signs are different and modulo not zero, adjust result
+ if ((mod ^ y) < 0 && mod != 0) {
+ mod += y;
+ }
+ return mod;
}
/**
@@ -1301,7 +1306,7 @@
*/
public static int floorMod(long x, int y) {
// Result cannot overflow the range of int.
- return (int)(x - floorDiv(x, y) * y);
+ return (int)floorMod(x, (long)y);
}
/**
@@ -1327,7 +1332,12 @@
* @since 1.8
*/
public static long floorMod(long x, long y) {
- return x - floorDiv(x, y) * y;
+ long mod = x % y;
+ // if the signs are different and modulo not zero, adjust result
+ if ((x ^ y) < 0 && mod != 0) {
+ mod += y;
+ }
+ return mod;
}
/**
--- a/src/java.base/share/classes/java/lang/String.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/String.java Sat Apr 13 07:23:18 2019 +0100
@@ -164,6 +164,12 @@
/** Cache the hash code for the string */
private int hash; // Default to 0
+ /**
+ * Cache if the hash has been calculated as actually being zero, enabling
+ * us to avoid recalculating this.
+ */
+ private boolean hashIsZero; // Default to false;
+
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
@@ -1508,14 +1514,21 @@
* @return a hash code value for this object.
*/
public int hashCode() {
+ // The hash or hashIsZero fields are subject to a benign data race,
+ // making it crucial to ensure that any observable result of the
+ // calculation in this method stays correct under any possible read of
+ // these fields. Necessary restrictions to allow this to be correct
+ // without explicit memory fences or similar concurrency primitives is
+ // that we can ever only write to one of these two fields for a given
+ // String instance, and that the computation is idempotent and derived
+ // from immutable state
int h = hash;
- if (h == 0 && value.length > 0) {
+ if (h == 0 && !hashIsZero) {
h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
- // Avoid issuing a store if the calculated value is also zero:
- // in addition to a minor performance benefit, this allows storing
- // Strings with zero hash code in read-only memory.
- if (h != 0) {
+ if (h == 0) {
+ hashIsZero = true;
+ } else {
hash = h;
}
}
--- a/src/java.base/share/classes/java/lang/StringBuffer.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/StringBuffer.java Sat Apr 13 07:23:18 2019 +0100
@@ -148,8 +148,7 @@
*/
@HotSpotIntrinsicCandidate
public StringBuffer(String str) {
- super(str.coder(), str.length(), 16);
- append(str);
+ super(str);
}
/**
@@ -162,8 +161,7 @@
* @since 1.5
*/
public StringBuffer(CharSequence seq) {
- super(String.LATIN1, seq.length(), 16);
- append(seq);
+ super(seq);
}
/**
--- a/src/java.base/share/classes/java/lang/StringBuilder.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/lang/StringBuilder.java Sat Apr 13 07:23:18 2019 +0100
@@ -121,8 +121,7 @@
*/
@HotSpotIntrinsicCandidate
public StringBuilder(String str) {
- super(str.coder(), str.length(), 16);
- append(str);
+ super(str);
}
/**
@@ -134,8 +133,7 @@
* @param seq the sequence to copy.
*/
public StringBuilder(CharSequence seq) {
- super(String.LATIN1, seq.length(), 16);
- append(seq);
+ super(seq);
}
/**
--- a/src/java.base/share/classes/java/security/Permissions.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/security/Permissions.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* 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,21 +25,20 @@
package java.security;
+import java.io.InvalidObjectException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.Hashtable;
-import java.util.NoSuchElementException;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.List;
import java.util.Iterator;
-import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
-import java.io.Serializable;
-import java.io.ObjectStreamField;
-import java.io.ObjectOutputStream;
-import java.io.ObjectInputStream;
-import java.io.IOException;
-
/**
* This class represents a heterogeneous collection of Permissions. That is,
@@ -392,6 +391,22 @@
permsMap = new ConcurrentHashMap<>(perms.size()*2);
permsMap.putAll(perms);
+ // Check that Class is mapped to PermissionCollection containing
+ // Permissions of the same class
+ for (Map.Entry<Class<?>, PermissionCollection> e : perms.entrySet()) {
+ Class<?> k = e.getKey();
+ PermissionCollection v = e.getValue();
+ Enumeration<Permission> en = v.elements();
+ while (en.hasMoreElements()) {
+ Permission p = en.nextElement();
+ if (!k.equals(p.getClass())) {
+ throw new InvalidObjectException("Permission with class " +
+ k + " incorrectly mapped to PermissionCollection " +
+ "containing Permission with " + p.getClass());
+ }
+ }
+ }
+
// Set hasUnresolved
UnresolvedPermissionCollection uc =
(UnresolvedPermissionCollection) permsMap.get(UnresolvedPermission.class);
@@ -584,5 +599,15 @@
(Hashtable<Permission, Permission>)gfields.get("perms", null);
permsMap = new ConcurrentHashMap<>(perms.size()*2);
permsMap.putAll(perms);
+
+ // check that the Permission key and value are the same object
+ for (Map.Entry<Permission, Permission> e : perms.entrySet()) {
+ Permission k = e.getKey();
+ Permission v = e.getValue();
+ if (k != v) {
+ throw new InvalidObjectException("Permission (" + k +
+ ") incorrectly mapped to Permission (" + v + ")");
+ }
+ }
}
}
--- a/src/java.base/share/classes/java/security/Signature.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/security/Signature.java Sat Apr 13 07:23:18 2019 +0100
@@ -40,6 +40,8 @@
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import javax.crypto.NoSuchPaddingException;
+import jdk.internal.access.JavaSecuritySignatureAccess;
+import jdk.internal.access.SharedSecrets;
import sun.security.util.Debug;
import sun.security.jca.*;
@@ -118,6 +120,34 @@
public abstract class Signature extends SignatureSpi {
+ static {
+ SharedSecrets.setJavaSecuritySignatureAccess(
+ new JavaSecuritySignatureAccess() {
+ @Override
+ public void initVerify(Signature s, PublicKey publicKey,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException,
+ InvalidAlgorithmParameterException {
+ s.initVerify(publicKey, params);
+ }
+ @Override
+ public void initVerify(Signature s,
+ java.security.cert.Certificate certificate,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException,
+ InvalidAlgorithmParameterException {
+ s.initVerify(certificate, params);
+ }
+ @Override
+ public void initSign(Signature s, PrivateKey privateKey,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException,
+ InvalidAlgorithmParameterException {
+ s.initSign(privateKey, params, random);
+ }
+ });
+ }
+
private static final Debug debug =
Debug.getInstance("jca", "Signature");
@@ -482,6 +512,53 @@
}
/**
+ * Initialize this object for verification. If this method is called
+ * again with different arguments, it negates the effect
+ * of this call.
+ *
+ * @param publicKey the public key of the identity whose signature is
+ * going to be verified.
+ * @param params the parameters used for verifying this signature.
+ *
+ * @exception InvalidKeyException if the key is invalid.
+ * @exception InvalidAlgorithmParameterException if the params is invalid.
+ */
+ final void initVerify(PublicKey publicKey, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ engineInitVerify(publicKey, params);
+ state = VERIFY;
+
+ if (!skipDebug && pdebug != null) {
+ pdebug.println("Signature." + algorithm +
+ " verification algorithm from: " + getProviderName());
+ }
+ }
+
+ private static PublicKey getPublicKeyFromCert(Certificate cert)
+ throws InvalidKeyException {
+ // If the certificate is of type X509Certificate,
+ // we should check whether it has a Key Usage
+ // extension marked as critical.
+ //if (cert instanceof java.security.cert.X509Certificate) {
+ if (cert instanceof X509Certificate) {
+ // Check whether the cert has a key usage extension
+ // marked as a critical extension.
+ // The OID for KeyUsage extension is 2.5.29.15.
+ X509Certificate c = (X509Certificate)cert;
+ Set<String> critSet = c.getCriticalExtensionOIDs();
+
+ if (critSet != null && !critSet.isEmpty()
+ && critSet.contains("2.5.29.15")) {
+ boolean[] keyUsageInfo = c.getKeyUsage();
+ // keyUsageInfo[0] is for digitalSignature.
+ if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
+ throw new InvalidKeyException("Wrong key usage");
+ }
+ }
+ return cert.getPublicKey();
+ }
+
+ /**
* Initializes this object for verification, using the public key from
* the given certificate.
* <p>If the certificate is of type X.509 and has a <i>key usage</i>
@@ -501,27 +578,40 @@
*/
public final void initVerify(Certificate certificate)
throws InvalidKeyException {
- // If the certificate is of type X509Certificate,
- // we should check whether it has a Key Usage
- // extension marked as critical.
- if (certificate instanceof java.security.cert.X509Certificate) {
- // Check whether the cert has a key usage extension
- // marked as a critical extension.
- // The OID for KeyUsage extension is 2.5.29.15.
- X509Certificate cert = (X509Certificate)certificate;
- Set<String> critSet = cert.getCriticalExtensionOIDs();
+ engineInitVerify(getPublicKeyFromCert(certificate));
+ state = VERIFY;
+
+ if (!skipDebug && pdebug != null) {
+ pdebug.println("Signature." + algorithm +
+ " verification algorithm from: " + getProviderName());
+ }
+ }
- if (critSet != null && !critSet.isEmpty()
- && critSet.contains("2.5.29.15")) {
- boolean[] keyUsageInfo = cert.getKeyUsage();
- // keyUsageInfo[0] is for digitalSignature.
- if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
- throw new InvalidKeyException("Wrong key usage");
- }
- }
-
- PublicKey publicKey = certificate.getPublicKey();
- engineInitVerify(publicKey);
+ /**
+ * Initializes this object for verification, using the public key from
+ * the given certificate.
+ * <p>If the certificate is of type X.509 and has a <i>key usage</i>
+ * extension field marked as critical, and the value of the <i>key usage</i>
+ * extension field implies that the public key in
+ * the certificate and its corresponding private key are not
+ * supposed to be used for digital signatures, an
+ * {@code InvalidKeyException} is thrown.
+ *
+ * @param certificate the certificate of the identity whose signature is
+ * going to be verified.
+ * @param params the parameters used for verifying this signature.
+ *
+ * @exception InvalidKeyException if the public key in the certificate
+ * is not encoded properly or does not include required parameter
+ * information or cannot be used for digital signature purposes.
+ * @exception InvalidAlgorithmParameterException if the params is invalid.
+ *
+ * @since 13
+ */
+ final void initVerify(Certificate certificate,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ engineInitVerify(getPublicKeyFromCert(certificate), params);
state = VERIFY;
if (!skipDebug && pdebug != null) {
@@ -575,6 +665,31 @@
}
/**
+ * Initialize this object for signing. If this method is called
+ * again with different arguments, it negates the effect
+ * of this call.
+ *
+ * @param privateKey the private key of the identity whose signature
+ * is going to be generated.
+ * @param params the parameters used for generating signature.
+ * @param random the source of randomness for this signature.
+ *
+ * @exception InvalidKeyException if the key is invalid.
+ * @exception InvalidAlgorithmParameterException if the params is invalid
+ */
+ final void initSign(PrivateKey privateKey,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ engineInitSign(privateKey, params, random);
+ state = SIGN;
+
+ if (!skipDebug && pdebug != null) {
+ pdebug.println("Signature." + algorithm +
+ " signing algorithm from: " + getProviderName());
+ }
+ }
+
+ /**
* Returns the signature bytes of all the data updated.
* The format of the signature depends on the underlying
* signature scheme.
@@ -1110,11 +1225,13 @@
}
}
- private void chooseProvider(int type, Key key, SecureRandom random)
- throws InvalidKeyException {
+ // Used by engineSetParameter/engineInitSign/engineInitVerify() to
+ // find the right provider with the supplied key, parameters, random source
+ private void chooseProvider(int type, Key key,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
synchronized (lock) {
if (sigSpi != null) {
- init(sigSpi, type, key, random);
return;
}
Exception lastException = null;
@@ -1127,7 +1244,7 @@
s = serviceIterator.next();
}
// if provider says it does not support this key, ignore it
- if (s.supportsParameter(key) == false) {
+ if (key != null && s.supportsParameter(key) == false) {
continue;
}
// if instance is not a SignatureSpi, ignore it
@@ -1136,7 +1253,7 @@
}
try {
SignatureSpi spi = newInstance(s);
- init(spi, type, key, random);
+ tryOperation(spi, type, key, params, random);
provider = s.getProvider();
sigSpi = spi;
firstService = null;
@@ -1158,6 +1275,10 @@
if (lastException instanceof RuntimeException) {
throw (RuntimeException)lastException;
}
+ if (lastException instanceof InvalidAlgorithmParameterException) {
+ throw (InvalidAlgorithmParameterException)lastException;
+ }
+
String k = (key != null) ? key.getClass().getName() : "(null)";
throw new InvalidKeyException
("No installed provider supports this key: "
@@ -1165,22 +1286,35 @@
}
}
- private static final int I_PUB = 1;
- private static final int I_PRIV = 2;
- private static final int I_PRIV_SR = 3;
+ private static final int I_PUB = 1;
+ private static final int I_PRIV = 2;
+ private static final int I_PRIV_SR = 3;
+ private static final int I_PUB_PARAM = 4;
+ private static final int I_PRIV_PARAM_SR = 5;
+ private static final int S_PARAM = 6;
- private void init(SignatureSpi spi, int type, Key key,
- SecureRandom random) throws InvalidKeyException {
+ private void tryOperation(SignatureSpi spi, int type, Key key,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
switch (type) {
case I_PUB:
spi.engineInitVerify((PublicKey)key);
break;
+ case I_PUB_PARAM:
+ spi.engineInitVerify((PublicKey)key, params);
+ break;
case I_PRIV:
spi.engineInitSign((PrivateKey)key);
break;
case I_PRIV_SR:
spi.engineInitSign((PrivateKey)key, random);
break;
+ case I_PRIV_PARAM_SR:
+ spi.engineInitSign((PrivateKey)key, params, random);
+ break;
+ case S_PARAM:
+ spi.engineSetParameter(params);
+ break;
default:
throw new AssertionError("Internal error: " + type);
}
@@ -1191,7 +1325,22 @@
if (sigSpi != null) {
sigSpi.engineInitVerify(publicKey);
} else {
- chooseProvider(I_PUB, publicKey, null);
+ try {
+ chooseProvider(I_PUB, publicKey, null, null);
+ } catch (InvalidAlgorithmParameterException iape) {
+ // should not happen, re-throw as IKE just in case
+ throw new InvalidKeyException(iape);
+ }
+ }
+ }
+
+ void engineInitVerify(PublicKey publicKey,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ if (sigSpi != null) {
+ sigSpi.engineInitVerify(publicKey, params);
+ } else {
+ chooseProvider(I_PUB_PARAM, publicKey, params, null);
}
}
@@ -1200,7 +1349,12 @@
if (sigSpi != null) {
sigSpi.engineInitSign(privateKey);
} else {
- chooseProvider(I_PRIV, privateKey, null);
+ try {
+ chooseProvider(I_PRIV, privateKey, null, null);
+ } catch (InvalidAlgorithmParameterException iape) {
+ // should not happen, re-throw as IKE just in case
+ throw new InvalidKeyException(iape);
+ }
}
}
@@ -1209,7 +1363,22 @@
if (sigSpi != null) {
sigSpi.engineInitSign(privateKey, sr);
} else {
- chooseProvider(I_PRIV_SR, privateKey, sr);
+ try {
+ chooseProvider(I_PRIV_SR, privateKey, null, sr);
+ } catch (InvalidAlgorithmParameterException iape) {
+ // should not happen, re-throw as IKE just in case
+ throw new InvalidKeyException(iape);
+ }
+ }
+ }
+
+ void engineInitSign(PrivateKey privateKey,
+ AlgorithmParameterSpec params, SecureRandom sr)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ if (sigSpi != null) {
+ sigSpi.engineInitSign(privateKey, params, sr);
+ } else {
+ chooseProvider(I_PRIV_PARAM_SR, privateKey, params, sr);
}
}
@@ -1260,8 +1429,16 @@
protected void engineSetParameter(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
- chooseFirstProvider();
- sigSpi.engineSetParameter(params);
+ if (sigSpi != null) {
+ sigSpi.engineSetParameter(params);
+ } else {
+ try {
+ chooseProvider(S_PARAM, null, params, null);
+ } catch (InvalidKeyException ike) {
+ // should never happen, rethrow just in case
+ throw new InvalidAlgorithmParameterException(ike);
+ }
+ }
}
protected Object engineGetParameter(String param)
--- a/src/java.base/share/classes/java/security/SignatureSpi.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/security/SignatureSpi.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -72,6 +72,33 @@
/**
* Initializes this signature object with the specified
+ * public key for verification operations.
+ *
+ * @param publicKey the public key of the identity whose signature is
+ * going to be verified.
+ * @param params the parameters for generating this signature
+ *
+ * @exception InvalidKeyException if the key is improperly
+ * encoded, does not work with the given parameters, and so on.
+ * @exception InvalidAlgorithmParameterException if the given parameters
+ * is invalid.
+ */
+ void engineInitVerify(PublicKey publicKey,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ if (params != null) {
+ try {
+ engineSetParameter(params);
+ } catch (UnsupportedOperationException usoe) {
+ // error out if not overrridden
+ throw new InvalidAlgorithmParameterException(usoe);
+ }
+ }
+ engineInitVerify(publicKey);
+ }
+
+ /**
+ * Initializes this signature object with the specified
* private key for signing operations.
*
* @param privateKey the private key of the identity whose signature
@@ -98,10 +125,41 @@
* encoded, parameters are missing, and so on.
*/
protected void engineInitSign(PrivateKey privateKey,
- SecureRandom random)
- throws InvalidKeyException {
- this.appRandom = random;
- engineInitSign(privateKey);
+ SecureRandom random)
+ throws InvalidKeyException {
+ this.appRandom = random;
+ engineInitSign(privateKey);
+ }
+
+ /**
+ * Initializes this signature object with the specified
+ * private key and source of randomness for signing operations.
+ *
+ * <p>This concrete method has been added to this previously-defined
+ * abstract class. (For backwards compatibility, it cannot be abstract.)
+ *
+ * @param privateKey the private key of the identity whose signature
+ * will be generated.
+ * @param params the parameters for generating this signature
+ * @param random the source of randomness
+ *
+ * @exception InvalidKeyException if the key is improperly
+ * encoded, parameters are missing, and so on.
+ * @exception InvalidAlgorithmParameterException if the parameters is
+ * invalid.
+ */
+ void engineInitSign(PrivateKey privateKey,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
+ if (params != null) {
+ try {
+ engineSetParameter(params);
+ } catch (UnsupportedOperationException usoe) {
+ // error out if not overrridden
+ throw new InvalidAlgorithmParameterException(usoe);
+ }
+ }
+ engineInitSign(privateKey, random);
}
/**
@@ -127,7 +185,7 @@
* properly
*/
protected abstract void engineUpdate(byte[] b, int off, int len)
- throws SignatureException;
+ throws SignatureException;
/**
* Updates the data to be signed or verified using the specified
@@ -223,7 +281,7 @@
* @since 1.2
*/
protected int engineSign(byte[] outbuf, int offset, int len)
- throws SignatureException {
+ throws SignatureException {
byte[] sig = engineSign();
if (len < sig.length) {
throw new SignatureException
@@ -251,7 +309,7 @@
* process the input data provided, etc.
*/
protected abstract boolean engineVerify(byte[] sigBytes)
- throws SignatureException;
+ throws SignatureException;
/**
* Verifies the passed-in signature in the specified array
@@ -273,7 +331,7 @@
* @since 1.4
*/
protected boolean engineVerify(byte[] sigBytes, int offset, int length)
- throws SignatureException {
+ throws SignatureException {
byte[] sigBytesCopy = new byte[length];
System.arraycopy(sigBytes, offset, sigBytesCopy, 0, length);
return engineVerify(sigBytesCopy);
@@ -305,7 +363,7 @@
*/
@Deprecated
protected abstract void engineSetParameter(String param, Object value)
- throws InvalidParameterException;
+ throws InvalidParameterException;
/**
* <p>This method is overridden by providers to initialize
@@ -321,8 +379,8 @@
* are inappropriate for this signature engine
*/
protected void engineSetParameter(AlgorithmParameterSpec params)
- throws InvalidAlgorithmParameterException {
- throw new UnsupportedOperationException();
+ throws InvalidAlgorithmParameterException {
+ throw new UnsupportedOperationException();
}
/**
--- a/src/java.base/share/classes/java/security/cert/X509CRL.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/security/cert/X509CRL.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -239,16 +239,15 @@
public void verify(PublicKey key, Provider sigProvider)
throws CRLException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
+ String sigAlgName = getSigAlgName();
Signature sig = (sigProvider == null)
- ? Signature.getInstance(getSigAlgName())
- : Signature.getInstance(getSigAlgName(), sigProvider);
+ ? Signature.getInstance(sigAlgName)
+ : Signature.getInstance(sigAlgName, sigProvider);
- sig.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selections occur when key is set
try {
- SignatureUtil.specialSetParameter(sig, getSigAlgParams());
+ byte[] paramBytes = getSigAlgParams();
+ SignatureUtil.initVerifyWithParam(sig, key,
+ SignatureUtil.getParamSpec(sigAlgName, paramBytes));
} catch (ProviderException e) {
throw new CRLException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
--- a/src/java.base/share/classes/java/security/cert/X509Certificate.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/security/cert/X509Certificate.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -676,16 +676,14 @@
public void verify(PublicKey key, Provider sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
+ String sigName = getSigAlgName();
Signature sig = (sigProvider == null)
- ? Signature.getInstance(getSigAlgName())
- : Signature.getInstance(getSigAlgName(), sigProvider);
+ ? Signature.getInstance(sigName)
+ : Signature.getInstance(sigName, sigProvider);
- sig.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selections occur when key is set
try {
- SignatureUtil.specialSetParameter(sig, getSigAlgParams());
+ SignatureUtil.initVerifyWithParam(sig, key,
+ SignatureUtil.getParamSpec(sigName, getSigAlgParams()));
} catch (ProviderException e) {
throw new CertificateException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
--- a/src/java.base/share/classes/java/util/ImmutableCollections.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/java/util/ImmutableCollections.java Sat Apr 13 07:23:18 2019 +0100
@@ -882,6 +882,11 @@
}
@Override
+ public V get(Object o) {
+ return o.equals(k0) ? v0 : null; // implicit nullcheck of o
+ }
+
+ @Override
public boolean containsKey(Object o) {
return o.equals(k0); // implicit nullcheck of o
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/jdk/internal/access/JavaSecuritySignatureAccess.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.access;
+
+import java.security.*;
+import java.security.spec.AlgorithmParameterSpec;
+
+public interface JavaSecuritySignatureAccess {
+
+ void initVerify(Signature s, PublicKey publicKey, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException;
+
+ void initVerify(Signature s, java.security.cert.Certificate certificate,
+ AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException;
+
+ void initSign(Signature s, PrivateKey privateKey,
+ AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException;
+}
--- a/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java Sat Apr 13 07:23:18 2019 +0100
@@ -36,6 +36,7 @@
import java.io.ObjectInputStream;
import java.io.RandomAccessFile;
import java.security.ProtectionDomain;
+import java.security.Signature;
import jdk.internal.misc.Unsafe;
/** A repository of "shared secrets", which are a mechanism for
@@ -73,6 +74,7 @@
private static JavaObjectInputStreamAccess javaObjectInputStreamAccess;
private static JavaObjectInputFilterAccess javaObjectInputFilterAccess;
private static JavaIORandomAccessFileAccess javaIORandomAccessFileAccess;
+ private static JavaSecuritySignatureAccess javaSecuritySignatureAccess;
private static JavaxCryptoSealedObjectAccess javaxCryptoSealedObjectAccess;
public static JavaUtilJarAccess javaUtilJarAccess() {
@@ -327,6 +329,17 @@
return javaIORandomAccessFileAccess;
}
+ public static void setJavaSecuritySignatureAccess(JavaSecuritySignatureAccess jssa) {
+ javaSecuritySignatureAccess = jssa;
+ }
+
+ public static JavaSecuritySignatureAccess getJavaSecuritySignatureAccess() {
+ if (javaSecuritySignatureAccess == null) {
+ unsafe.ensureClassInitialized(Signature.class);
+ }
+ return javaSecuritySignatureAccess;
+ }
+
public static void setJavaxCryptoSealedObjectAccess(JavaxCryptoSealedObjectAccess jcsoa) {
javaxCryptoSealedObjectAccess = jcsoa;
}
--- a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -447,15 +447,13 @@
Signature sig = Signature.getInstance(algname);
- sig.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selections occur when key is set
AlgorithmParameters ap =
digestEncryptionAlgorithmId.getParameters();
try {
- SignatureUtil.specialSetParameter(sig, ap);
- } catch (ProviderException | InvalidAlgorithmParameterException e) {
+ SignatureUtil.initVerifyWithParam(sig, key,
+ SignatureUtil.getParamSpec(algname, ap));
+ } catch (ProviderException | InvalidAlgorithmParameterException |
+ InvalidKeyException e) {
throw new SignatureException(e.getMessage(), e);
}
@@ -466,8 +464,6 @@
} catch (IOException e) {
throw new SignatureException("IO error verifying signature:\n" +
e.getMessage());
- } catch (InvalidKeyException e) {
- throw new SignatureException("InvalidKey: " + e.getMessage());
}
return null;
}
--- a/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java Sat Apr 13 07:23:18 2019 +0100
@@ -167,12 +167,8 @@
try {
sigAlg = id.getName();
sig = Signature.getInstance(sigAlg);
-
- sig.initVerify(subjectPublicKeyInfo);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selections occur when key is set
- SignatureUtil.specialSetParameter(sig, id.getParameters());
+ SignatureUtil.initVerifyWithParam(sig, subjectPublicKeyInfo,
+ SignatureUtil.getParamSpec(sigAlg, id.getParameters()));
sig.update(data);
if (!sig.verify(sigData)) {
--- a/src/java.base/share/classes/sun/security/ssl/SignatureScheme.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/ssl/SignatureScheme.java Sat Apr 13 07:23:18 2019 +0100
@@ -43,6 +43,7 @@
import sun.security.ssl.SupportedGroupsExtension.NamedGroupType;
import sun.security.ssl.X509Authentication.X509Possession;
import sun.security.util.KeyUtil;
+import sun.security.util.SignatureUtil;
enum SignatureScheme {
// EdDSA algorithms
@@ -471,16 +472,11 @@
Signature signer = Signature.getInstance(algorithm);
if (key instanceof PublicKey) {
- signer.initVerify((PublicKey)(key));
+ SignatureUtil.initVerifyWithParam(signer, (PublicKey)key,
+ signAlgParameter);
} else {
- signer.initSign((PrivateKey)key);
- }
-
- // Important note: Please don't set the parameters before signature
- // or verification initialization, so that the crypto provider can
- // be selected properly.
- if (signAlgParameter != null) {
- signer.setParameter(signAlgParameter);
+ SignatureUtil.initSignWithParam(signer, (PrivateKey)key,
+ signAlgParameter, null);
}
return signer;
--- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java Sat Apr 13 07:23:18 2019 +0100
@@ -84,6 +84,7 @@
import sun.security.util.Password;
import sun.security.util.SecurityProperties;
import sun.security.util.SecurityProviderConstants;
+import sun.security.util.SignatureUtil;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
@@ -1441,11 +1442,12 @@
sigAlgName = getCompatibleSigAlgName(privateKey);
}
Signature signature = Signature.getInstance(sigAlgName);
- signature.initSign(privateKey);
+ AlgorithmParameterSpec params = AlgorithmId
+ .getDefaultAlgorithmParameterSpec(sigAlgName, privateKey);
+
+ SignatureUtil.initSignWithParam(signature, privateKey, params, null);
X509CertInfo info = new X509CertInfo();
- AlgorithmParameterSpec params = AlgorithmId
- .getDefaultAlgorithmParameterSpec(sigAlgName, privateKey);
AlgorithmId algID = AlgorithmId.getWithParameterSpec(sigAlgName, params);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER,
@@ -1599,12 +1601,9 @@
}
Signature signature = Signature.getInstance(sigAlgName);
- signature.initSign(privKey);
AlgorithmParameterSpec params = AlgorithmId
.getDefaultAlgorithmParameterSpec(sigAlgName, privKey);
- if (params != null) {
- signature.setParameter(params);
- }
+ SignatureUtil.initSignWithParam(signature, privKey, params, null);
X500Name subject = dname == null?
new X500Name(((X509Certificate)cert).getSubjectDN().toString()):
--- a/src/java.base/share/classes/sun/security/util/SignatureUtil.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/util/SignatureUtil.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
import java.security.*;
import java.security.spec.*;
import sun.security.rsa.RSAUtil;
+import jdk.internal.access.SharedSecrets;
/**
* Utility class for Signature related operations. Currently used by various
@@ -39,12 +40,25 @@
*/
public class SignatureUtil {
+ private static String checkName(String algName) throws ProviderException {
+ if (algName.indexOf(".") == -1) {
+ return algName;
+ }
+ // convert oid to String
+ try {
+ return Signature.getInstance(algName).getAlgorithm();
+ } catch (Exception e) {
+ throw new ProviderException("Error mapping algorithm name", e);
+ }
+ }
+
// Utility method of creating an AlgorithmParameters object with
// the specified algorithm name and encoding
private static AlgorithmParameters createAlgorithmParameters(String algName,
byte[] paramBytes) throws ProviderException {
try {
+ algName = checkName(algName);
AlgorithmParameters result =
AlgorithmParameters.getInstance(algName);
result.init(paramBytes);
@@ -54,52 +68,81 @@
}
}
- private static AlgorithmParameterSpec getParamSpec(String sigName,
+ // Utility method for converting the specified AlgorithmParameters object
+ // into an AlgorithmParameterSpec object.
+ public static AlgorithmParameterSpec getParamSpec(String sigName,
AlgorithmParameters params)
- throws InvalidAlgorithmParameterException, ProviderException {
+ throws ProviderException {
- if (params == null) return null;
-
- if (sigName.toUpperCase().indexOf("RSA") == -1) {
- throw new ProviderException
- ("Unrecognized algorithm for signature parameters " +
- sigName);
+ sigName = checkName(sigName);
+ AlgorithmParameterSpec paramSpec = null;
+ if (params != null) {
+ if (sigName.toUpperCase().indexOf("RSA") == -1) {
+ throw new ProviderException
+ ("Unrecognized algorithm for signature parameters " +
+ sigName);
+ }
+ // AlgorithmParameters.getAlgorithm() may returns oid if it's
+ // created during DER decoding. Convert to use the standard name
+ // before passing it to RSAUtil
+ if (params.getAlgorithm().indexOf(".") != -1) {
+ try {
+ params = createAlgorithmParameters(sigName,
+ params.getEncoded());
+ } catch (IOException e) {
+ throw new ProviderException(e);
+ }
+ }
+ paramSpec = RSAUtil.getParamSpec(params);
}
- // AlgorithmParameters.getAlgorithm() may returns oid if it's
- // created during DER decoding. Convert to use the standard name
- // before passing it to RSAUtil
- String alg = params.getAlgorithm();
- if (alg.equalsIgnoreCase(sigName) || alg.indexOf(".") != -1) {
- try {
- params = createAlgorithmParameters(sigName,
- params.getEncoded());
- } catch (IOException e) {
- throw new ProviderException(e);
- }
- }
- return RSAUtil.getParamSpec(params);
+ return paramSpec;
}
- // Special method for setting the specified parameter bytes into the
- // specified Signature object as signature parameters.
- public static void specialSetParameter(Signature sig, byte[] paramBytes)
- throws InvalidAlgorithmParameterException, ProviderException {
+ // Utility method for converting the specified parameter bytes into an
+ // AlgorithmParameterSpec object.
+ public static AlgorithmParameterSpec getParamSpec(String sigName,
+ byte[] paramBytes)
+ throws ProviderException {
+ sigName = checkName(sigName);
+ AlgorithmParameterSpec paramSpec = null;
if (paramBytes != null) {
- String sigName = sig.getAlgorithm();
+ if (sigName.toUpperCase().indexOf("RSA") == -1) {
+ throw new ProviderException
+ ("Unrecognized algorithm for signature parameters " +
+ sigName);
+ }
AlgorithmParameters params =
createAlgorithmParameters(sigName, paramBytes);
- specialSetParameter(sig, params);
+ paramSpec = RSAUtil.getParamSpec(params);
}
+ return paramSpec;
}
- // Special method for setting the specified AlgorithmParameter object
- // into the specified Signature object as signature parameters.
- public static void specialSetParameter(Signature sig,
- AlgorithmParameters params)
- throws InvalidAlgorithmParameterException, ProviderException {
- if (params != null) {
- String sigName = sig.getAlgorithm();
- sig.setParameter(getParamSpec(sigName, params));
- }
+ // Utility method for initializing the specified Signature object
+ // for verification with the specified key and params (may be null)
+ public static void initVerifyWithParam(Signature s, PublicKey key,
+ AlgorithmParameterSpec params)
+ throws ProviderException, InvalidAlgorithmParameterException,
+ InvalidKeyException {
+ SharedSecrets.getJavaSecuritySignatureAccess().initVerify(s, key, params);
+ }
+
+ // Utility method for initializing the specified Signature object
+ // for verification with the specified Certificate and params (may be null)
+ public static void initVerifyWithParam(Signature s,
+ java.security.cert.Certificate cert,
+ AlgorithmParameterSpec params)
+ throws ProviderException, InvalidAlgorithmParameterException,
+ InvalidKeyException {
+ SharedSecrets.getJavaSecuritySignatureAccess().initVerify(s, cert, params);
+ }
+
+ // Utility method for initializing the specified Signature object
+ // for signing with the specified key and params (may be null)
+ public static void initSignWithParam(Signature s, PrivateKey key,
+ AlgorithmParameterSpec params, SecureRandom sr)
+ throws ProviderException, InvalidAlgorithmParameterException,
+ InvalidKeyException {
+ SharedSecrets.getJavaSecuritySignatureAccess().initSign(s, key, params, sr);
}
}
--- a/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -370,18 +370,16 @@
throw new CRLException("Uninitialized CRL");
}
Signature sigVerf = null;
+ String sigName = sigAlgId.getName();
if (sigProvider.isEmpty()) {
- sigVerf = Signature.getInstance(sigAlgId.getName());
+ sigVerf = Signature.getInstance(sigName);
} else {
- sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
+ sigVerf = Signature.getInstance(sigName, sigProvider);
}
- sigVerf.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selection happens when key is set
try {
- SignatureUtil.specialSetParameter(sigVerf, getSigAlgParams());
+ SignatureUtil.initVerifyWithParam(sigVerf, key,
+ SignatureUtil.getParamSpec(sigName, getSigAlgParams()));
} catch (ProviderException e) {
throw new CRLException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
@@ -425,18 +423,16 @@
throw new CRLException("Uninitialized CRL");
}
Signature sigVerf = null;
+ String sigName = sigAlgId.getName();
if (sigProvider == null) {
- sigVerf = Signature.getInstance(sigAlgId.getName());
+ sigVerf = Signature.getInstance(sigName);
} else {
- sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
+ sigVerf = Signature.getInstance(sigName, sigProvider);
}
- sigVerf.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selection happens when key is set
try {
- SignatureUtil.specialSetParameter(sigVerf, getSigAlgParams());
+ SignatureUtil.initVerifyWithParam(sigVerf, key,
+ SignatureUtil.getParamSpec(sigName, getSigAlgParams()));
} catch (ProviderException e) {
throw new CRLException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
@@ -502,7 +498,7 @@
sigEngine.initSign(key);
- // in case the name is reset
+ // in case the name is reset
sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
infoSigAlgId = sigAlgId;
--- a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java Sat Apr 13 07:23:18 2019 +0100
@@ -422,18 +422,16 @@
}
// Verify the signature ...
Signature sigVerf = null;
+ String sigName = algId.getName();
if (sigProvider.isEmpty()) {
- sigVerf = Signature.getInstance(algId.getName());
+ sigVerf = Signature.getInstance(sigName);
} else {
- sigVerf = Signature.getInstance(algId.getName(), sigProvider);
+ sigVerf = Signature.getInstance(sigName, sigProvider);
}
- sigVerf.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selection happens when key is set
try {
- SignatureUtil.specialSetParameter(sigVerf, getSigAlgParams());
+ SignatureUtil.initVerifyWithParam(sigVerf, key,
+ SignatureUtil.getParamSpec(sigName, getSigAlgParams()));
} catch (ProviderException e) {
throw new CertificateException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
@@ -478,18 +476,16 @@
}
// Verify the signature ...
Signature sigVerf = null;
+ String sigName = algId.getName();
if (sigProvider == null) {
- sigVerf = Signature.getInstance(algId.getName());
+ sigVerf = Signature.getInstance(sigName);
} else {
- sigVerf = Signature.getInstance(algId.getName(), sigProvider);
+ sigVerf = Signature.getInstance(sigName, sigProvider);
}
- sigVerf.initVerify(key);
-
- // set parameters after Signature.initSign/initVerify call,
- // so the deferred provider selection happens when key is set
try {
- SignatureUtil.specialSetParameter(sigVerf, getSigAlgParams());
+ SignatureUtil.initVerifyWithParam(sigVerf, key,
+ SignatureUtil.getParamSpec(sigName, getSigAlgParams()));
} catch (ProviderException e) {
throw new CertificateException(e.getMessage(), e.getCause());
} catch (InvalidAlgorithmParameterException e) {
@@ -587,22 +583,19 @@
InvalidKeyException, InvalidAlgorithmParameterException,
NoSuchProviderException, SignatureException {
try {
- if (readOnly)
+ if (readOnly) {
throw new CertificateEncodingException(
- "cannot over-write existing certificate");
+ "cannot over-write existing certificate");
+ }
Signature sigEngine = null;
- if (provider == null || provider.isEmpty())
+ if (provider == null || provider.isEmpty()) {
sigEngine = Signature.getInstance(algorithm);
- else
+ } else {
sigEngine = Signature.getInstance(algorithm, provider);
-
- sigEngine.initSign(key);
+ }
- if (signingParams != null) {
- // set parameters after Signature.initSign/initVerify call, so
- // the deferred provider selection happens when the key is set
- sigEngine.setParameter(signingParams);
- }
+ SignatureUtil.initSignWithParam(sigEngine, key, signingParams,
+ null);
// in case the name is reset
if (signingParams != null) {
--- a/src/java.base/windows/classes/sun/nio/fs/WindowsConstants.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/windows/classes/sun/nio/fs/WindowsConstants.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -75,6 +75,7 @@
public static final int IO_REPARSE_TAG_SYMLINK = 0xA000000C;
public static final int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024;
public static final int SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1;
+ public static final int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x2;
// volume flags
public static final int FILE_CASE_SENSITIVE_SEARCH = 0x00000001;
@@ -104,6 +105,7 @@
public static final int ERROR_MORE_DATA = 234;
public static final int ERROR_DIRECTORY = 267;
public static final int ERROR_NOTIFY_ENUM_DIR = 1022;
+ public static final int ERROR_PRIVILEGE_NOT_HELD = 1314;
public static final int ERROR_NONE_MAPPED = 1332;
public static final int ERROR_NOT_A_REPARSE_POINT = 4390;
public static final int ERROR_INVALID_REPARSE_DATA = 4392;
--- a/src/java.base/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,8 @@
import java.security.PrivilegedAction;
import jdk.internal.misc.Unsafe;
+import static sun.nio.fs.WindowsConstants.*;
+
/**
* Win32 and library calls.
*/
@@ -920,6 +922,12 @@
* LPCWSTR lpTargetFileName,
* DWORD dwFlags
* )
+ *
+ * Creates a symbolic link, conditionally retrying with the addition of
+ * the flag SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE if the initial
+ * attempt fails with ERROR_PRIVILEGE_NOT_HELD. If the retry fails, throw
+ * the original exception due to ERROR_PRIVILEGE_NOT_HELD. The retry will
+ * succeed only on Windows build 14972 or later if Developer Mode is on.
*/
static void CreateSymbolicLink(String link, String target, int flags)
throws WindowsException
@@ -929,6 +937,19 @@
try {
CreateSymbolicLink0(linkBuffer.address(), targetBuffer.address(),
flags);
+ } catch (WindowsException x) {
+ if (x.lastError() == ERROR_PRIVILEGE_NOT_HELD) {
+ flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
+ try {
+ CreateSymbolicLink0(linkBuffer.address(),
+ targetBuffer.address(), flags);
+ return;
+ } catch (WindowsException ignored) {
+ // Will fail with ERROR_INVALID_PARAMETER for Windows
+ // builds older than 14972.
+ }
+ }
+ throw x;
} finally {
targetBuffer.release();
linkBuffer.release();
--- a/src/java.base/windows/native/common/version.rc Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/windows/native/common/version.rc Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
//
-// Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 2004, 2019, Oracle and/or its affiliates. All rights reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
//
// This code is free software; you can redistribute it and/or modify it
@@ -55,15 +55,15 @@
BEGIN
BLOCK "000004b0"
BEGIN
- VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
- VALUE "FileDescription", XSTR(JDK_COMPONENT) "\0"
- VALUE "FileVersion", XSTR(JDK_VER) "\0"
+ VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(JDK_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(JDK_VER) "\0"
VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
- VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
- VALUE "ProductName", XSTR(JDK_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_VER) "\0"
+ VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
+ VALUE "ProductName", XSTR(JDK_NAME) "\0"
+ VALUE "ProductVersion", XSTR(JDK_VER) "\0"
END
END
BLOCK "VarFileInfo"
--- a/src/java.base/windows/native/libnio/fs/WindowsNativeDispatcher.c Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.base/windows/native/libnio/fs/WindowsNativeDispatcher.c Sat Apr 13 07:23:18 2019 +0100
@@ -1063,17 +1063,7 @@
LPCWSTR link = jlong_to_ptr(linkAddress);
LPCWSTR target = jlong_to_ptr(targetAddress);
- // Allow creation of symbolic links when the process is not elevated.
- // Developer Mode must be enabled for this option to function, otherwise
- // it will be ignored. Check that symbol is available in current build SDK.
- DWORD dwFlags = (DWORD)flags;
-#ifdef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
- dwFlags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
-#endif
-
- // On Windows 64-bit this appears to succeed even when there are
- // insufficient privileges
- if (CreateSymbolicLinkW(link, target, dwFlags) == 0)
+ if (CreateSymbolicLinkW(link, target, (DWORD)flags) == 0)
throwWindowsException(env, GetLastError());
}
--- a/src/java.desktop/share/classes/com/sun/media/sound/FastSysexMessage.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/share/classes/com/sun/media/sound/FastSysexMessage.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -37,9 +37,7 @@
FastSysexMessage(byte[] data) throws InvalidMidiDataException {
super(data);
- if (data.length==0 || (((data[0] & 0xFF) != 0xF0) && ((data[0] & 0xFF) != 0xF7))) {
- super.setMessage(data, data.length); // will throw Exception
- }
+ MidiUtils.checkSysexStatus(data, data.length);
}
/**
@@ -54,9 +52,7 @@
// which is shared among all transmitters, cannot be modified
@Override
public void setMessage(byte[] data, int length) throws InvalidMidiDataException {
- if ((data.length == 0) || (((data[0] & 0xFF) != 0xF0) && ((data[0] & 0xFF) != 0xF7))) {
- super.setMessage(data, data.length); // will throw Exception
- }
+ MidiUtils.checkSysexStatus(data, length);
this.length = length;
this.data = new byte[this.length];
System.arraycopy(data, 0, this.data, 0, length);
--- a/src/java.desktop/share/classes/com/sun/media/sound/MidiUtils.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/share/classes/com/sun/media/sound/MidiUtils.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
import java.util.ArrayList;
+import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiEvent;
@@ -34,6 +35,9 @@
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;
+import static javax.sound.midi.SysexMessage.SPECIAL_SYSTEM_EXCLUSIVE;
+import static javax.sound.midi.SysexMessage.SYSTEM_EXCLUSIVE;
+
// TODO:
// - define and use a global symbolic constant for 60000000 (see convertTempo)
@@ -65,6 +69,37 @@
"MidiDevice %s not supported by this provider", info));
}
+ /**
+ * Checks the status byte for the system exclusive message.
+ *
+ * @param data the system exclusive message data
+ * @param length the length of the valid message data in the array
+ * @throws InvalidMidiDataException if the status byte is invalid for a
+ * system exclusive message
+ */
+ public static void checkSysexStatus(final byte[] data, final int length)
+ throws InvalidMidiDataException {
+ if (data.length == 0 || length == 0) {
+ throw new InvalidMidiDataException("Status byte is missing");
+ }
+ checkSysexStatus(data[0] & 0xFF);
+ }
+
+ /**
+ * Checks the status byte for the system exclusive message.
+ *
+ * @param status the status byte for the message (0xF0 or 0xF7)
+ * @throws InvalidMidiDataException if the status byte is invalid for a
+ * system exclusive message
+ */
+ public static void checkSysexStatus(final int status)
+ throws InvalidMidiDataException {
+ if (status != SYSTEM_EXCLUSIVE && status != SPECIAL_SYSTEM_EXCLUSIVE) {
+ throw new InvalidMidiDataException(String.format(
+ "Invalid status byte for sysex message: 0x%X", status));
+ }
+ }
+
/** return true if the passed message is Meta End Of Track */
public static boolean isMetaEndOfTrack(MidiMessage midiMsg) {
// first check if it is a META message at all
--- a/src/java.desktop/share/classes/javax/sound/midi/SysexMessage.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/share/classes/javax/sound/midi/SysexMessage.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
package javax.sound.midi;
+import com.sun.media.sound.MidiUtils;
+
/**
* A {@code SysexMessage} object represents a MIDI system exclusive message.
* <p>
@@ -183,10 +185,7 @@
*/
@Override
public void setMessage(byte[] data, int length) throws InvalidMidiDataException {
- int status = (data[0] & 0xFF);
- if ((status != 0xF0) && (status != 0xF7)) {
- throw new InvalidMidiDataException("Invalid status byte for sysex message: 0x" + Integer.toHexString(status));
- }
+ MidiUtils.checkSysexStatus(data, length);
super.setMessage(data, length);
}
@@ -200,9 +199,7 @@
* system exclusive message
*/
public void setMessage(int status, byte[] data, int length) throws InvalidMidiDataException {
- if ( (status != 0xF0) && (status != 0xF7) ) {
- throw new InvalidMidiDataException("Invalid status byte for sysex message: 0x" + Integer.toHexString(status));
- }
+ MidiUtils.checkSysexStatus(status);
if (length < 0 || length > data.length) {
throw new IndexOutOfBoundsException("length out of bounds: "+length);
}
--- a/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* 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,65 +25,58 @@
package javax.swing.text;
+import java.util.Enumeration;
import java.util.Stack;
-import java.util.Enumeration;
/**
+ * {@code ElementIterator}, as the name suggests, iterates over the
+ * {@code Element} tree. The constructor can be invoked with either
+ * {@code Document} or an {@code Element} as an argument. If the constructor is
+ * invoked with a {@code Document} as an argument then the root of the iteration
+ * is the return value of {@code document.getDefaultRootElement()}.
* <p>
- * ElementIterator, as the name suggests, iterates over the Element
- * tree. The constructor can be invoked with either Document or an Element
- * as an argument. If the constructor is invoked with a Document as an
- * argument then the root of the iteration is the return value of
- * document.getDefaultRootElement().
- *
- * The iteration happens in a depth-first manner. In terms of how
- * boundary conditions are handled:
- * a) if next() is called before first() or current(), the
- * root will be returned.
- * b) next() returns null to indicate the end of the list.
- * c) previous() returns null when the current element is the root
- * or next() has returned null.
- *
- * The ElementIterator does no locking of the Element tree. This means
- * that it does not track any changes. It is the responsibility of the
+ * The iteration happens in a depth-first manner. In terms of how boundary
+ * conditions are handled:
+ * <ul>
+ * <li>if {@link #next} is called before {@link #first} or {@link #current},
+ * the root will be returned
+ * <li>{@link #next} returns {@code null} to indicate the end of the list
+ * <li>{@link #previous} returns {@code null} when the current element is the
+ * root or {@link #next} has returned {@code null}
+ * </ul>
+ * <p>
+ * The {@code ElementIterator} does no locking of the {@code Element} tree. This
+ * means that it does not track any changes. It is the responsibility of the
* user of this class, to ensure that no changes happen during element
* iteration.
- *
+ * <p>
* Simple usage example:
- *
- * public void iterate() {
- * ElementIterator it = new ElementIterator(root);
- * Element elem;
- * while (true) {
- * if ((elem = next()) != null) {
- * // process element
- * System.out.println("elem: " + elem.getName());
- * } else {
- * break;
- * }
- * }
- * }
+ * <pre>{@code public void iterate() {
+ * ElementIterator it = new ElementIterator(root);
+ * Element elem;
+ * while (true) {
+ * if ((elem = it.next()) != null) {
+ * // process element
+ * System.out.println("elem: " + elem.getName());
+ * } else {
+ * break;
+ * }
+ * }
+ * }}</pre>
*
* @author Sunita Mani
- *
*/
-
public class ElementIterator implements Cloneable {
-
private Element root;
private Stack<StackItem> elementStack = null;
/**
- * The StackItem class stores the element
- * as well as a child index. If the
- * index is -1, then the element represented
- * on the stack is the element itself.
- * Otherwise, the index functions as an index
- * into the vector of children of the element.
- * In this case, the item on the stack
- * represents the "index"th child of the element
- *
+ * The {@code StackItem} class stores the element as well as a child index.
+ * If the index is -1, then the element represented on the stack is the
+ * element itself. Otherwise, the index functions as an index into the
+ * vector of children of the element. In this case, the item on the stack
+ * represents the "index"th child of the element.
*/
private class StackItem implements Cloneable {
Element item;
@@ -117,31 +110,28 @@
}
/**
- * Creates a new ElementIterator. The
- * root element is taken to get the
- * default root element of the document.
+ * Creates a new {@code ElementIterator}. The root element is taken to get
+ * the default root element of the document.
*
- * @param document a Document.
+ * @param document a {@code Document}
*/
public ElementIterator(Document document) {
root = document.getDefaultRootElement();
}
-
/**
- * Creates a new ElementIterator.
+ * Creates a new {@code ElementIterator}.
*
- * @param root the root Element.
+ * @param root the root {@code Element}
*/
public ElementIterator(Element root) {
this.root = root;
}
-
/**
- * Clones the ElementIterator.
+ * Clones the {@code ElementIterator}.
*
- * @return a cloned ElementIterator Object.
+ * @return a cloned {@code ElementIterator} Object
*/
public synchronized Object clone() {
@@ -161,11 +151,10 @@
}
}
-
/**
* Fetches the first element.
*
- * @return an Element.
+ * @return an {@code Element}
*/
public Element first() {
// just in case...
@@ -183,7 +172,7 @@
/**
* Fetches the current depth of element tree.
*
- * @return the depth.
+ * @return the depth
*/
public int depth() {
if (elementStack == null) {
@@ -192,12 +181,11 @@
return elementStack.size();
}
-
/**
- * Fetches the current Element.
+ * Fetches the current {@code Element}.
*
- * @return element on top of the stack or
- * <code>null</code> if the root element is <code>null</code>
+ * @return element on top of the stack or {@code null} if the root element
+ * is {@code null}
*/
public Element current() {
@@ -222,14 +210,11 @@
return null;
}
-
/**
- * Fetches the next Element. The strategy
- * used to locate the next element is
- * a depth-first search.
+ * Fetches the next {@code Element}. The strategy used to locate the next
+ * element is a depth-first search.
*
- * @return the next element or <code>null</code>
- * at the end of the list.
+ * @return the next element or {@code null} at the end of the list
*/
public Element next() {
@@ -282,14 +267,12 @@
return null;
}
-
/**
- * Fetches the previous Element. If however the current
- * element is the last element, or the current element
- * is null, then null is returned.
+ * Fetches the previous {@code Element}. If however the current element is
+ * the last element, or the current element is {@code null}, then
+ * {@code null} is returned.
*
- * @return previous <code>Element</code> if available
- *
+ * @return previous {@code Element} if available
*/
public Element previous() {
@@ -335,8 +318,8 @@
}
/**
- * Returns the last child of <code>parent</code> that is a leaf. If the
- * last child is a not a leaf, this method is called with the last child.
+ * Returns the last child of {@code parent} that is a leaf. If the last
+ * child is a not a leaf, this method is called with the last child.
*/
private Element getDeepestLeaf(Element parent) {
if (parent.isLeaf()) {
@@ -349,10 +332,10 @@
return getDeepestLeaf(parent.getElement(childCount - 1));
}
- /*
- Iterates through the element tree and prints
- out each element and its attributes.
- */
+ /**
+ * Iterates through the element tree and prints out each element and its
+ * attributes.
+ */
private void dumpTree() {
Element elem;
--- a/src/java.desktop/share/classes/javax/swing/text/View.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/share/classes/javax/swing/text/View.java Sat Apr 13 07:23:18 2019 +0100
@@ -229,7 +229,6 @@
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view
- * @see View#getPreferredSpan
*/
public abstract float getPreferredSpan(int axis);
--- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c Sat Apr 13 07:23:18 2019 +0100
@@ -1777,9 +1777,18 @@
(widget_type == CHECK_BOX || widget_type == RADIO_BUTTON)) {
return;
}
- GtkStyleContext* context = get_style(widget_type, detail);
+
+ GtkStyleContext* context = NULL;
if (widget_type == TOOL_TIP) {
+ context = get_style(widget_type, detail);
fp_gtk_style_context_add_class(context, "background");
+ } else {
+ gtk3_widget = gtk3_get_widget(widget_type);
+ context = fp_gtk_widget_get_style_context (gtk3_widget);
+ fp_gtk_style_context_save (context);
+ if (detail != 0) {
+ transform_detail_string(detail, context);
+ }
}
GtkStateFlags flags = get_gtk_flags(state_type);
@@ -1795,8 +1804,11 @@
}
fp_gtk_render_background (context, cr, x, y, width, height);
-
- disposeOrRestoreContext(context);
+ if (widget_type == TOOL_TIP) {
+ disposeOrRestoreContext(context);
+ } else {
+ fp_gtk_style_context_restore (context);
+ }
}
static void gtk3_paint_focus(WidgetType widget_type, GtkStateType state_type,
--- a/src/java.desktop/windows/native/libawt/windows/awt.rc Sat Apr 13 07:22:55 2019 +0100
+++ b/src/java.desktop/windows/native/libawt/windows/awt.rc Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
//
-// Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
//
// This code is free software; you can redistribute it and/or modify it
@@ -65,15 +65,15 @@
BEGIN
BLOCK "040904b0"
BEGIN
- VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
- VALUE "FileDescription", XSTR(JDK_COMPONENT) "\0"
- VALUE "FileVersion", XSTR(JDK_VER) "\0"
+ VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(JDK_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(JDK_VER) "\0"
VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
- VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
- VALUE "ProductName", XSTR(JDK_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_VER) "\0"
+ VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
+ VALUE "ProductName", XSTR(JDK_NAME) "\0"
+ VALUE "ProductVersion", XSTR(JDK_VER) "\0"
END
END
BLOCK "VarFileInfo"
--- a/src/jdk.accessibility/windows/native/common/AccessBridgeStatusWindow.RC Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,174 +0,0 @@
-//Microsoft Developer Studio generated resource script.
-//
-#include "resource.h"
-#include "accessBridgeResource.h"
-
-#define XSTR(x) STR(x)
-#define STR(x) #x
-
-#define APSTUDIO_READONLY_SYMBOLS
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 2 resource.
-//
-#define APSTUDIO_HIDDEN_SYMBOLS
-#include "windows.h"
-#undef APSTUDIO_HIDDEN_SYMBOLS
-
-/////////////////////////////////////////////////////////////////////////////
-#undef APSTUDIO_READONLY_SYMBOLS
-
-/////////////////////////////////////////////////////////////////////////////
-// English (U.S.) resources
-
-#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-#ifdef _WIN32
-LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
-#pragma code_page(1252)
-#endif //_WIN32
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Dialog
-//
-
-ACCESSBRIDGESTATUSWINDOW DIALOGEX 160, 78, 209, 163
-STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
-EXSTYLE WS_EX_CLIENTEDGE
-CAPTION "Access Bridge status"
-FONT 8, "MS Sans Serif", 0, 0, 0x1
-BEGIN
- EDITTEXT cVMID,67,23,121,13,ES_READONLY
- EDITTEXT cStatusText,40,147,162,13,ES_READONLY
- LTEXT "Java VM ID:",IDC_STATIC,23,25,40,8
- LTEXT "Status:",IDC_STATIC,11,149,23,8
- EDITTEXT cWindowsID,67,39,121,13,ES_READONLY
- LTEXT "Windows ID:",IDC_STATIC,21,41,42,8
- EDITTEXT cCallInfo,12,65,184,75,ES_MULTILINE | ES_AUTOVSCROLL |
- ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL
- GROUPBOX "Call info",IDC_STATIC,4,55,197,90
- EDITTEXT cInvokedByText,67,1,121,13,ES_READONLY
- LTEXT "Invoked by:",IDC_STATIC,25,3,38,8
-END
-
-IDD_DIALOG1 DIALOG DISCARDABLE 0, 0, 186, 95
-STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
-CAPTION "Dialog"
-FONT 8, "MS Sans Serif"
-BEGIN
- DEFPUSHBUTTON "OK",IDOK,129,7,50,14
- PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
-END
-
-
-#ifdef APSTUDIO_INVOKED
-/////////////////////////////////////////////////////////////////////////////
-//
-// TEXTINCLUDE
-//
-
-1 TEXTINCLUDE DISCARDABLE
-BEGIN
- "resource.h\0"
-END
-
-2 TEXTINCLUDE DISCARDABLE
-BEGIN
- "#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
- "#include ""windows.h""\r\n"
- "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
- "\0"
-END
-
-3 TEXTINCLUDE DISCARDABLE
-BEGIN
- "\r\n"
- "\0"
-END
-
-#endif // APSTUDIO_INVOKED
-
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// DESIGNINFO
-//
-
-#ifdef APSTUDIO_INVOKED
-GUIDELINES DESIGNINFO DISCARDABLE
-BEGIN
- "ACCESSBRIDGESTATUSWINDOW", DIALOG
- BEGIN
- LEFTMARGIN, 4
- RIGHTMARGIN, 202
- BOTTOMMARGIN, 160
- END
-
- "IDD_DIALOG1", DIALOG
- BEGIN
- LEFTMARGIN, 7
- RIGHTMARGIN, 179
- TOPMARGIN, 7
- BOTTOMMARGIN, 88
- END
-END
-#endif // APSTUDIO_INVOKED
-
-
-#ifndef _MAC
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO VERSIONINFO
- FILEVERSION JDK_FVER
- PRODUCTVERSION JDK_FVER
- FILEFLAGSMASK 0x3fL
-#ifdef DEBUG
- FILEFLAGS 0x1L
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS 0x40004L
- FILETYPE JDK_FTYPE
- FILESUBTYPE 0x0L
-BEGIN
- BLOCK "StringFileInfo"
- BEGIN
- BLOCK "040904b0"
- BEGIN
- VALUE "Comments", "Java Access Bridge\0"
- VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
- VALUE "FileDescription", XSTR(JDK_COMPONENT) "\0"
- VALUE "FileVersion", XSTR(JDK_VER) "\0"
- VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
- VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
- VALUE "ProductName", XSTR(JDK_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_VER) "\0"
- END
- END
- BLOCK "VarFileInfo"
- BEGIN
- VALUE "Translation", 0x409, 1200
- END
-END
-
-#endif // !_MAC
-
-#endif // English (U.S.) resources
-/////////////////////////////////////////////////////////////////////////////
-
-
-
-#ifndef APSTUDIO_INVOKED
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 3 resource.
-//
-
-
-/////////////////////////////////////////////////////////////////////////////
-#endif // not APSTUDIO_INVOKED
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.accessibility/windows/native/common/AccessBridgeStatusWindow.rc Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,174 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+#include "accessBridgeResource.h"
+
+#define XSTR(x) STR(x)
+#define STR(x) #x
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#define APSTUDIO_HIDDEN_SYMBOLS
+#include "windows.h"
+#undef APSTUDIO_HIDDEN_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// English (U.S.) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+ACCESSBRIDGESTATUSWINDOW DIALOGEX 160, 78, 209, 163
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_CLIENTEDGE
+CAPTION "Access Bridge status"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ EDITTEXT cVMID,67,23,121,13,ES_READONLY
+ EDITTEXT cStatusText,40,147,162,13,ES_READONLY
+ LTEXT "Java VM ID:",IDC_STATIC,23,25,40,8
+ LTEXT "Status:",IDC_STATIC,11,149,23,8
+ EDITTEXT cWindowsID,67,39,121,13,ES_READONLY
+ LTEXT "Windows ID:",IDC_STATIC,21,41,42,8
+ EDITTEXT cCallInfo,12,65,184,75,ES_MULTILINE | ES_AUTOVSCROLL |
+ ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL
+ GROUPBOX "Call info",IDC_STATIC,4,55,197,90
+ EDITTEXT cInvokedByText,67,1,121,13,ES_READONLY
+ LTEXT "Invoked by:",IDC_STATIC,25,3,38,8
+END
+
+IDD_DIALOG1 DIALOG DISCARDABLE 0, 0, 186, 95
+STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Dialog"
+FONT 8, "MS Sans Serif"
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,129,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
+END
+
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
+ "#include ""windows.h""\r\n"
+ "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO DISCARDABLE
+BEGIN
+ "ACCESSBRIDGESTATUSWINDOW", DIALOG
+ BEGIN
+ LEFTMARGIN, 4
+ RIGHTMARGIN, 202
+ BOTTOMMARGIN, 160
+ END
+
+ "IDD_DIALOG1", DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 88
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION JDK_FVER
+ PRODUCTVERSION JDK_FVER
+ FILEFLAGSMASK 0x3fL
+#ifdef DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE JDK_FTYPE
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "Comments", "Java Access Bridge" "\0"
+ VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(JDK_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(JDK_VER) "\0"
+ VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
+ VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
+ VALUE "ProductName", XSTR(JDK_NAME) "\0"
+ VALUE "ProductVersion", XSTR(JDK_VER) "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
+
+#endif // !_MAC
+
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
--- a/src/jdk.accessibility/windows/native/common/resource.h Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.accessibility/windows/native/common/resource.h Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* 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 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
-// Used by AccessBridgeStatusWindow.RC
+// Used by AccessBridgeStatusWindow.rc
//
//#define IDB_BITMAP1 102
--- a/src/jdk.accessibility/windows/native/jaccessinspector/jaccessinspectorWindow.rc Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.accessibility/windows/native/jaccessinspector/jaccessinspectorWindow.rc Sat Apr 13 07:23:18 2019 +0100
@@ -199,15 +199,15 @@
BEGIN
BLOCK "000004b0"
BEGIN
- VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
- VALUE "FileDescription", XSTR(JDK_COMPONENT) "\0"
- VALUE "FileVersion", XSTR(JDK_VER) "\0"
+ VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(JDK_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(JDK_VER) "\0"
VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
- VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
- VALUE "ProductName", XSTR(JDK_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_VER) "\0"
+ VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
+ VALUE "ProductName", XSTR(JDK_NAME) "\0"
+ VALUE "ProductVersion", XSTR(JDK_VER) "\0"
END
END
BLOCK "VarFileInfo"
--- a/src/jdk.accessibility/windows/native/jaccesswalker/jaccesswalkerWindow.rc Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.accessibility/windows/native/jaccesswalker/jaccesswalkerWindow.rc Sat Apr 13 07:23:18 2019 +0100
@@ -164,15 +164,15 @@
BEGIN
BLOCK "000004b0"
BEGIN
- VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
- VALUE "FileDescription", XSTR(JDK_COMPONENT) "\0"
- VALUE "FileVersion", XSTR(JDK_VER) "\0"
+ VALUE "CompanyName", XSTR(JDK_COMPANY) "\0"
+ VALUE "FileDescription", XSTR(JDK_FILEDESC) "\0"
+ VALUE "FileVersion", XSTR(JDK_VER) "\0"
VALUE "Full Version", XSTR(JDK_VERSION_STRING) "\0"
- VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
- VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
- VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
- VALUE "ProductName", XSTR(JDK_NAME) "\0"
- VALUE "ProductVersion", XSTR(JDK_VER) "\0"
+ VALUE "InternalName", XSTR(JDK_INTERNAL_NAME) "\0"
+ VALUE "LegalCopyright", XSTR(JDK_COPYRIGHT) "\0"
+ VALUE "OriginalFilename", XSTR(JDK_FNAME) "\0"
+ VALUE "ProductName", XSTR(JDK_NAME) "\0"
+ VALUE "ProductVersion", XSTR(JDK_VER) "\0"
END
END
BLOCK "VarFileInfo"
--- a/src/jdk.compiler/share/classes/com/sun/source/util/JavacTask.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/source/util/JavacTask.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
+import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
@@ -137,6 +138,27 @@
public abstract void removeTaskListener(TaskListener taskListener);
/**
+ * Sets the specified {@link ParameterNameProvider}. It may be used when
+ * {@link VariableElement#getSimpleName()} is called for a method parameter
+ * for which an authoritative name is not found. The given
+ * {@code ParameterNameProvider} may infer a user-friendly name
+ * for the method parameter.
+ *
+ * Setting a new {@code ParameterNameProvider} will clear any previously set
+ * {@code ParameterNameProvider}, which won't be queried any more.
+ *
+ * When no {@code ParameterNameProvider} is set, or when it returns null from
+ * {@link ParameterNameProvider#getParameterName(javax.lang.model.element.VariableElement)},
+ * an automatically synthesized name is returned from {@code VariableElement.getSimpleName()}.
+ *
+ * @implSpec The default implementation of this method does nothing.
+ *
+ * @param provider the provider.
+ * @since 13
+ */
+ public void setParameterNameProvider(ParameterNameProvider provider) {}
+
+ /**
* Returns a type mirror of the tree node determined by the specified path.
* This method has been superceded by methods on
* {@link com.sun.source.util.Trees Trees}.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.compiler/share/classes/com/sun/source/util/ParameterNameProvider.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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.source.util;
+
+import javax.lang.model.element.VariableElement;
+
+/**
+ * A provider for parameter names when the parameter names are not determined from
+ * a reliable source, like a classfile.
+ *
+ * @since 13
+ */
+public interface ParameterNameProvider {
+
+ /**
+ * Infer a parameter name for the given parameter. The implementations of this method
+ * should infer parameter names in such a way that the parameter names are distinct
+ * for any given owning method.
+ *
+ * If the implementation of this method returns null, an automatically synthesized name is used.
+ *
+ * @param parameter the parameter for which the name should be inferred.
+ * @return a user-friendly name for the parameter, or null if unknown
+ */
+ public CharSequence getParameterName(VariableElement parameter);
+
+}
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/BasicJavacTask.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/BasicJavacTask.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -43,9 +43,11 @@
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
+import com.sun.source.util.ParameterNameProvider;
import com.sun.source.util.Plugin;
import com.sun.source.util.TaskListener;
import com.sun.tools.doclint.DocLint;
+import com.sun.tools.javac.code.MissingInfoHandler;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.model.JavacTypes;
@@ -123,6 +125,11 @@
mtl.remove(taskListener);
}
+ @Override
+ public void setParameterNameProvider(ParameterNameProvider handler) {
+ MissingInfoHandler.instance(context).setDelegate(handler);
+ }
+
public Collection<TaskListener> getTaskListeners() {
MultiTaskListener mtl = MultiTaskListener.instance(context);
return mtl.getTaskListeners();
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Flags.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Flags.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -319,6 +319,11 @@
*/
public static final long BODY_ONLY_FINALIZE = 1L<<17; //blocks only
+ /**
+ * Flag to indicate the given ParamSymbol has a user-friendly name filled.
+ */
+ public static final long NAME_FILLED = 1L<<58; //ParamSymbols only
+
/** Modifier masks.
*/
public static final int
@@ -435,7 +440,8 @@
DEPRECATED_REMOVAL(Flags.DEPRECATED_REMOVAL),
HAS_RESOURCE(Flags.HAS_RESOURCE),
POTENTIALLY_AMBIGUOUS(Flags.POTENTIALLY_AMBIGUOUS),
- ANONCONSTR_BASED(Flags.ANONCONSTR_BASED);
+ ANONCONSTR_BASED(Flags.ANONCONSTR_BASED),
+ NAME_FILLED(Flags.NAME_FILLED);
Flag(long flag) {
this.value = flag;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/MissingInfoHandler.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.javac.code;
+
+import com.sun.source.util.ParameterNameProvider;
+import com.sun.tools.javac.code.Symbol.ParamSymbol;
+import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.util.Name;
+import com.sun.tools.javac.util.Names;
+
+/**
+ * A Context class, that can return additional useful information for Symbols, currently
+ * parameter names. It does so by calling user-supplied {@link ParameterNameProvider}.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own risk.
+ * This code and its internal interfaces are subject to change or
+ * deletion without notice.</b>
+ */
+public class MissingInfoHandler {
+ protected static final Context.Key<MissingInfoHandler> missingInfoHandlerWrapperKey = new Context.Key<>();
+
+ public static MissingInfoHandler instance(Context context) {
+ MissingInfoHandler instance = context.get(missingInfoHandlerWrapperKey);
+ if (instance == null)
+ instance = new MissingInfoHandler(context);
+ return instance;
+ }
+
+ private final Names names;
+ private ParameterNameProvider parameterNameProvider;
+
+ protected MissingInfoHandler(Context context) {
+ context.put(missingInfoHandlerWrapperKey, this);
+ names = Names.instance(context);
+ }
+
+ public Name getParameterName(ParamSymbol parameter) {
+ if (parameterNameProvider != null) {
+ CharSequence name = parameterNameProvider.getParameterName(parameter);
+ if (name != null) {
+ return names.fromString(name.toString());
+ }
+ }
+
+ return null;
+ }
+
+ public void setDelegate(ParameterNameProvider delegate) {
+ this.parameterNameProvider = delegate;
+ }
+}
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -65,9 +65,12 @@
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
+import com.sun.tools.javac.code.MissingInfoHandler;
import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
import com.sun.tools.javac.code.Scope.WriteableScope;
+import com.sun.tools.javac.code.Symbol;
import static com.sun.tools.javac.code.Symbol.OperatorSymbol.AccessCode.FIRSTASGOP;
+import com.sun.tools.javac.code.Type;
import static com.sun.tools.javac.code.TypeTag.CLASS;
import static com.sun.tools.javac.code.TypeTag.FORALL;
import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
@@ -76,6 +79,7 @@
import static com.sun.tools.javac.jvm.ByteCodes.lushrl;
import static com.sun.tools.javac.jvm.ByteCodes.lxor;
import static com.sun.tools.javac.jvm.ByteCodes.string_add;
+import com.sun.tools.javac.util.Name;
/** Root class for Java symbols. It contains subclasses
* for specific sorts of symbols, such as variables, methods and operators,
@@ -1189,6 +1193,16 @@
}
+ public static class RootPackageSymbol extends PackageSymbol {
+ public final MissingInfoHandler missingInfoHandler;
+
+ public RootPackageSymbol(Name name, Symbol owner, MissingInfoHandler missingInfoHandler) {
+ super(name, owner);
+ this.missingInfoHandler = missingInfoHandler;
+ }
+
+ }
+
/** A class for class symbols
*/
public static class ClassSymbol extends TypeSymbol implements TypeElement {
@@ -1634,6 +1648,32 @@
}
}
+ public static class ParamSymbol extends VarSymbol {
+ public ParamSymbol(long flags, Name name, Type type, Symbol owner) {
+ super(flags, name, type, owner);
+ }
+
+ @Override
+ public Name getSimpleName() {
+ if ((flags_field & NAME_FILLED) == 0) {
+ flags_field |= NAME_FILLED;
+ Symbol rootPack = this;
+ while (rootPack != null && !(rootPack instanceof RootPackageSymbol)) {
+ rootPack = rootPack.owner;
+ }
+ if (rootPack != null) {
+ Name inferredName =
+ ((RootPackageSymbol) rootPack).missingInfoHandler.getParameterName(this);
+ if (inferredName != null) {
+ this.name = inferredName;
+ }
+ }
+ }
+ return super.getSimpleName();
+ }
+
+ }
+
/** A class for method symbols.
*/
public static class MethodSymbol extends Symbol implements ExecutableElement {
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -42,6 +42,7 @@
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.ModuleSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
+import com.sun.tools.javac.code.Symbol.RootPackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type.BottomType;
@@ -382,7 +383,9 @@
messages = JavacMessages.instance(context);
- rootPackage = new PackageSymbol(names.empty, null);
+ MissingInfoHandler missingInfoHandler = MissingInfoHandler.instance(context);
+
+ rootPackage = new RootPackageSymbol(names.empty, null, missingInfoHandler);
// create the basic builtin symbols
unnamedModule = new ModuleSymbol(names.empty, null) {
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
@@ -366,9 +367,11 @@
for (Type t : minContext.inferencevars) {
//add listener that forwards notifications to original context
minContext.addFreeTypeListener(List.of(t), (inferenceContext) -> {
- ((UndetVar)asUndetVar(t)).setInst(inferenceContext.asInstType(t));
- infer.doIncorporation(inferenceContext, warn);
- solve(List.from(rv.minMap.get(t)), warn);
+ Type instType = inferenceContext.asInstType(t);
+ for (Type eq : rv.minMap.get(t)) {
+ ((UndetVar)asUndetVar(eq)).setInst(instType);
+ }
+ infer.doIncorporation(this, warn);
notifyChange();
});
}
@@ -385,9 +388,9 @@
class ReachabilityVisitor extends Types.UnaryVisitor<Void> {
- Set<Type> equiv = new HashSet<>();
- Set<Type> min = new HashSet<>();
- Map<Type, Set<Type>> minMap = new HashMap<>();
+ Set<Type> equiv = new LinkedHashSet<>();
+ Set<Type> min = new LinkedHashSet<>();
+ Map<Type, Set<Type>> minMap = new LinkedHashMap<>();
void scan(List<Type> roots) {
roots.stream().forEach(this::visit);
@@ -401,7 +404,7 @@
@Override
public Void visitUndetVar(UndetVar t, Void _unused) {
if (min.add(t.qtype)) {
- Set<Type> deps = minMap.getOrDefault(t.qtype, new HashSet<>(Collections.singleton(t.qtype)));
+ Set<Type> deps = minMap.getOrDefault(t.qtype, new LinkedHashSet<>(Collections.singleton(t.qtype)));
for (InferenceBound boundKind : InferenceBound.values()) {
for (Type b : t.getBounds(boundKind)) {
Type undet = asUndetVar(b);
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -1502,6 +1502,10 @@
// See java.lang.Class
private Name simpleBinaryName(Name self, Name enclosing) {
+ if (!self.startsWith(enclosing)) {
+ throw badClassFile("bad.enclosing.method", self);
+ }
+
String simpleBinaryName = self.toString().substring(enclosing.toString().length());
if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
throw badClassFile("bad.enclosing.method", self);
@@ -2553,14 +2557,12 @@
firstParam += skip;
}
}
- List<Name> paramNames = List.nil();
+ Set<Name> paramNames = new HashSet<>();
ListBuffer<VarSymbol> params = new ListBuffer<>();
int nameIndex = firstParam;
int annotationIndex = 0;
for (Type t: sym.type.getParameterTypes()) {
- Name name = parameterName(nameIndex, paramNames);
- paramNames = paramNames.prepend(name);
- VarSymbol param = new VarSymbol(PARAMETER, name, t, sym);
+ VarSymbol param = parameter(nameIndex, t, sym, paramNames);
params.append(param);
if (parameterAnnotations != null) {
ParameterAnnotations annotations = parameterAnnotations[annotationIndex];
@@ -2585,18 +2587,24 @@
// Returns the name for the parameter at position 'index', either using
// names read from the MethodParameters, or by synthesizing a name that
// is not on the 'exclude' list.
- private Name parameterName(int index, List<Name> exclude) {
+ private VarSymbol parameter(int index, Type t, MethodSymbol owner, Set<Name> exclude) {
+ long flags = PARAMETER;
+ Name argName;
if (parameterNameIndices != null && index < parameterNameIndices.length
&& parameterNameIndices[index] != 0) {
- return readName(parameterNameIndices[index]);
+ argName = readName(parameterNameIndices[index]);
+ flags |= NAME_FILLED;
+ } else {
+ String prefix = "arg";
+ while (true) {
+ argName = names.fromString(prefix + exclude.size());
+ if (!exclude.contains(argName))
+ break;
+ prefix += "$";
+ }
}
- String prefix = "arg";
- while (true) {
- Name argName = names.fromString(prefix + exclude.size());
- if (!exclude.contains(argName))
- return argName;
- prefix += "$";
- }
+ exclude.add(argName);
+ return new ParamSymbol(flags, argName, t, owner);
}
/**
--- a/src/jdk.rmic/share/classes/sun/tools/java/BinaryClass.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.rmic/share/classes/sun/tools/java/BinaryClass.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -122,6 +122,13 @@
sun.tools.javac.Main.getText(
"javac.err.version.too.old",
String.valueOf(version)));
+ } else if ((version >= JAVA_MIN_PREVIEW_MAJOR_VERSION)
+ && (minor_version == JAVA_PREVIEW_MINOR_VERSION)) {
+ // reject all class files that have preview features enabled
+ throw new ClassFormatError(
+ sun.tools.javac.Main.getText(
+ "javac.err.version.preview",
+ version+"."+minor_version));
} else if ((version > JAVA_MAX_SUPPORTED_VERSION)
|| (version == JAVA_MAX_SUPPORTED_VERSION
&& minor_version > JAVA_MAX_SUPPORTED_MINOR_VERSION)) {
--- a/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -69,6 +69,8 @@
int JAVA_MIN_SUPPORTED_VERSION = 45;
int JAVA_MAX_SUPPORTED_VERSION = 57;
int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0;
+ int JAVA_MIN_PREVIEW_MAJOR_VERSION = 55; // preview intro'd in JDK 11
+ int JAVA_PREVIEW_MINOR_VERSION = 0xffff;
/* Generate class file version for 1.1 by default */
int JAVA_DEFAULT_VERSION = 45;
--- a/src/jdk.rmic/share/classes/sun/tools/javac/resources/javac.properties Sat Apr 13 07:22:55 2019 +0100
+++ b/src/jdk.rmic/share/classes/sun/tools/javac/resources/javac.properties Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -579,6 +579,9 @@
javac.err.version.too.recent=\
The major.minor version ''{0}'' is too recent for this tool \
to understand.
+javac.err.version.preview=\
+ The major.minor version ''{0}'' indicates the class was compiled with \
+ preview features enabled, which this tool does not support.
#
benv.parsed_in=[parsed {0} in {1} ms]
benv.loaded_in=[loaded {0} in {1} ms]
--- a/test/hotspot/jtreg/ProblemList-graal.txt Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/ProblemList-graal.txt Sat Apr 13 07:23:18 2019 +0100
@@ -38,8 +38,6 @@
compiler/compilercontrol/mixed/RandomValidCommandsTest.java 8181753 generic-all
compiler/compilercontrol/mixed/RandomCommandsTest.java 8181753 generic-all
-compiler/graalunit/JttThreadsTest.java 8208066 generic-all
-
compiler/jvmci/SecurityRestrictionsTest.java 8181837 generic-all
compiler/unsafe/UnsafeGetConstantField.java 8181833 generic-all
@@ -218,6 +216,8 @@
vmTestbase/nsk/jdb/clear/clear003/clear003.java 8218701 generic-all
+compiler/jsr292/InvokerSignatureMismatch.java 8221577 generic-all
+
# Graal unit tests
org.graalvm.compiler.core.test.CheckGraalInvariants 8205081
org.graalvm.compiler.core.test.OptionsVerifierTest 8205081
@@ -228,4 +228,3 @@
org.graalvm.compiler.core.test.deopt.CompiledMethodTest 8202955
org.graalvm.compiler.hotspot.test.ReservedStackAccessTest 8213567 windows-all
-
--- a/test/hotspot/jtreg/ProblemList.txt Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/ProblemList.txt Sat Apr 13 07:23:18 2019 +0100
@@ -79,7 +79,7 @@
# :hotspot_runtime
runtime/SharedArchiveFile/SASymbolTableTest.java 8193639 solaris-all
-runtime/containers/docker/TestCPUSets.java 8220672 generic-all
+containers/docker/TestCPUSets.java 8220672 generic-all
runtime/jni/terminatedThread/TestTerminatedThread.java 8219652 aix-ppc64
#############################################################################
--- a/test/hotspot/jtreg/TEST.groups Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/TEST.groups Sat Apr 13 07:23:18 2019 +0100
@@ -43,6 +43,7 @@
gc \
-gc/nvdimm
+# By design this group should include ALL tests under runtime sub-directory
hotspot_runtime = \
runtime
@@ -65,6 +66,9 @@
hotspot_native_sanity = \
native_sanity
+hotspot_containers = \
+ containers
+
tier1_common = \
sanity/BasicVMTest.java \
gtest/GTestWrapper.java
@@ -296,7 +300,6 @@
-runtime/Thread/CancellableThreadTest.java \
-runtime/Thread/TestThreadDumpMonitorContention.java \
-runtime/Unsafe/RangeCheck.java \
- -runtime/containers/ \
sanity/ \
testlibrary_tests/TestMutuallyExclusivePlatformPredicates.java \
-:tier1_runtime_appcds_exclude \
@@ -365,7 +368,6 @@
-runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java \
-runtime/CompressedOops/UseCompressedOops.java \
-runtime/Thread/TestThreadDumpMonitorContention.java \
- -runtime/containers/ \
-:tier1_runtime \
-:tier1_serviceability \
-:hotspot_tier2_runtime_platform_agnostic \
@@ -379,7 +381,6 @@
hotspot_tier3_runtime = \
runtime/ \
serviceability/ \
- -runtime/containers/ \
-:tier1_runtime \
-:tier1_serviceability \
-:hotspot_tier2_runtime_platform_agnostic \
--- a/test/hotspot/jtreg/compiler/graalunit/common/GraalUnitTestLauncher.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/compiler/graalunit/common/GraalUnitTestLauncher.java Sat Apr 13 07:23:18 2019 +0100
@@ -241,7 +241,8 @@
javaFlags.add("-ea");
// Make sure exception message is never null
javaFlags.add("-XX:-OmitStackTraceInFastThrow");
-
+ // set timeout factor based on jtreg harness settings
+ javaFlags.add("-Dgraaltest.timeout.factor=" + System.getProperty("test.timeout.factor", "1.0"));
// generate class path
ArrayList<String> graalJars = new ArrayList<String>(Arrays.asList(GRAAL_EXTRA_JARS));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/cgroup/PlainRead.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2017, 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 PlainRead
+ * @requires os.family == "linux"
+ * @library /testlibrary /test/lib
+ * @build sun.hotspot.WhiteBox
+ * @run driver ClassFileInstaller sun.hotspot.WhiteBox
+ * sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI PlainRead
+ */
+
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.Platform;
+import sun.hotspot.WhiteBox;
+
+public class PlainRead {
+
+ static public void match(OutputAnalyzer oa, String what, String value) {
+ oa.shouldMatch("^.*" + what + " *" + value + ".*$");
+ }
+
+ static public void noMatch(OutputAnalyzer oa, String what, String value) {
+ oa.shouldNotMatch("^.*" + what + " *" + value + ".*$");
+ }
+
+ static final String good_value = "(\\d+|-1|Unlimited)";
+ static final String bad_value = "(failed)";
+
+ static final String[] variables = {"Memory Limit is:", "CPU Shares is:", "CPU Quota is:", "CPU Period is:", "active_processor_count:"};
+
+ static public void isContainer(OutputAnalyzer oa) {
+ for (String v: variables) {
+ match(oa, v, good_value);
+ }
+ for (String v: variables) {
+ noMatch(oa, v, bad_value);
+ }
+ }
+
+ static public void isNotContainer(OutputAnalyzer oa) {
+ oa.shouldMatch("^.*Can't open /proc/self/mountinfo.*$");
+ }
+
+ public static void main(String[] args) throws Exception {
+ WhiteBox wb = WhiteBox.getWhiteBox();
+ ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+container=trace", "-version");
+ OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+ if (wb.isContainerized()) {
+ System.out.println("Inside a cgroup, testing...");
+ isContainer(output);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/AttemptOOM.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class AttemptOOM {
+ private static MyObj[] data;
+
+ public static void main(String[] args) throws Exception {
+ System.out.println("Entering AttemptOOM main");
+
+ // each MyObj will allocate 1024 byte array
+ int sizeInMb = Integer.parseInt(args[0]);
+ data = new MyObj[sizeInMb*1024];
+
+ System.out.println("data.length = " + data.length);
+
+ for (int i=0; i < data.length; i++) {
+ data[i] = new MyObj(1024);
+ }
+
+ System.out.println("AttemptOOM allocation successful");
+ }
+
+ private static class MyObj {
+ private byte[] myData;
+ MyObj(int size) {
+ myData = new byte[size];
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/CheckContainerized.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.hotspot.WhiteBox;
+
+public class CheckContainerized {
+ public static String OUTSIDE_OF_CONTAINER =
+ "CheckContainerized: Running outside of a container";
+ public static String INSIDE_A_CONTAINER =
+ "CheckContainerized: Running inside a container";
+
+ public static void main(String[] args) {
+ System.out.println("CheckContainerized: Entering");
+ WhiteBox wb = WhiteBox.getWhiteBox();
+
+ if (wb.isContainerized()) {
+ System.out.println(INSIDE_A_CONTAINER);
+
+ } else {
+ System.out.println(OUTSIDE_OF_CONTAINER);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/DockerBasicTest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 Basic (sanity) test for JDK-under-test inside a docker image.
+ * @requires docker.support
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @build HelloDocker
+ * @run driver DockerBasicTest
+ */
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+import jdk.test.lib.Platform;
+import jdk.test.lib.Utils;
+
+
+public class DockerBasicTest {
+ private static final String imageNameAndTag = Common.imageName("basic");
+
+ public static void main(String[] args) throws Exception {
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ DockerTestUtils.buildJdkDockerImage(imageNameAndTag, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ testJavaVersion();
+ testHelloDocker();
+ } finally {
+ if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) {
+ DockerTestUtils.removeDockerImage(imageNameAndTag);
+ }
+ }
+ }
+
+
+ private static void testJavaVersion() throws Exception {
+ DockerRunOptions opts =
+ new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version");
+
+ DockerTestUtils.dockerRunJava(opts)
+ .shouldHaveExitValue(0)
+ .shouldContain(Platform.vmName);
+ }
+
+
+ private static void testHelloDocker() throws Exception {
+ DockerRunOptions opts =
+ new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "HelloDocker")
+ .addJavaOpts("-cp", "/test-classes/")
+ .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
+
+ DockerTestUtils.dockerRunJava(opts)
+ .shouldHaveExitValue(0)
+ .shouldContain("Hello Docker");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/HelloDocker.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class HelloDocker {
+ public static void main(String args[]) {
+ System.out.println("Hello Docker");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/JfrReporter.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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.
+ */
+
+import java.nio.file.Paths;
+import jdk.jfr.Recording;
+import jdk.jfr.consumer.RecordedEvent;
+import jdk.jfr.consumer.RecordingFile;
+
+
+// This class is intended to run inside a container
+public class JfrReporter {
+ public static final String TEST_REPORTED_CORES="TEST_REPORTED_CORES";
+ public static final String TEST_REPORTED_MEMORY="TEST_REPORTED_MEMORY";
+ public static final String TEST_REPORTED_PID="TEST_REPORTED_PID";
+ public static final String TESTCASE_CPU="cpu";
+ public static final String TESTCASE_MEMORY="memory";
+ public static final String TESTCASE_PROCESS="process";
+
+ public static void main(String[] args) throws Exception {
+ String testCase = args[0];
+ System.out.println("Testcase: " + testCase);
+ switch (testCase) {
+ case TESTCASE_CPU:
+ RecordedEvent event = testEvent("jdk.CPUInformation", "cpu.jfr");
+ System.out.println(TEST_REPORTED_CORES + "=" + event.getInt("cores"));
+ break;
+ case TESTCASE_MEMORY:
+ event = testEvent("jdk.PhysicalMemory", "memory.jfr");
+ System.out.println(TEST_REPORTED_MEMORY + "=" + event.getLong("totalSize"));
+ break;
+ case TESTCASE_PROCESS:
+ event = testEvent("jdk.SystemProcess", "process.jfr");
+ System.out.println(TEST_REPORTED_PID + "=" + event.getString("pid"));
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid test case");
+ }
+ }
+
+ private static RecordedEvent testEvent(String event, String recordingPath) throws Exception {
+ System.out.println("========= Testing event: " + event);
+ Recording r = new Recording();
+ r.enable(event);
+ r.setDestination(Paths.get("tmp", recordingPath));
+ r.start();
+ r.stop();
+
+ RecordedEvent recordedEvent = RecordingFile.readAllEvents(r.getDestination()).get(0);
+ System.out.println("RecordedEvent: " + recordedEvent);
+ return recordedEvent;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/PrintContainerInfo.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.hotspot.WhiteBox;
+
+public class PrintContainerInfo {
+
+ public static void main(String[] args) {
+ System.out.println("PrintContainerInfo: Entering");
+ WhiteBox wb = WhiteBox.getWhiteBox();
+
+ wb.printOsInfo();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TEST.properties Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,1 @@
+exclusiveAccess.dirs=.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TestCPUAwareness.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 JVM's CPU resource awareness when running inside docker container
+ * @requires docker.support
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @run driver TestCPUAwareness
+ */
+import java.util.List;
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+import jdk.test.lib.containers.cgroup.CPUSetsReader;
+
+public class TestCPUAwareness {
+ private static final String imageName = Common.imageName("cpu");
+ private static final int availableCPUs = Runtime.getRuntime().availableProcessors();
+
+ public static void main(String[] args) throws Exception {
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ System.out.println("Test Environment: detected availableCPUs = " + availableCPUs);
+ DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ // cpuset, period, shares, expected Active Processor Count
+ testComboWithCpuSets();
+
+ // cpu shares - it should be safe to use CPU shares exceeding available CPUs
+ testCpuShares(256, 1);
+ testCpuShares(2048, 2);
+ testCpuShares(4096, 4);
+
+ // leave one CPU for system and tools, otherwise this test may be unstable
+ int maxNrOfAvailableCpus = availableCPUs - 1;
+ for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) {
+ testCpus(i, i);
+ }
+
+ // If ActiveProcessorCount is set, the VM should use it, regardless of other
+ // container settings, host settings or available CPUs on the host.
+ testActiveProcessorCount(1, 1);
+ testActiveProcessorCount(2, 2);
+
+ // cpu quota and period
+ testCpuQuotaAndPeriod(50*1000, 100*1000);
+ testCpuQuotaAndPeriod(100*1000, 100*1000);
+ testCpuQuotaAndPeriod(150*1000, 100*1000);
+ testCpuQuotaAndPeriod(400*1000, 100*1000);
+
+ } finally {
+ DockerTestUtils.removeDockerImage(imageName);
+ }
+ }
+
+
+ private static void testComboWithCpuSets() throws Exception {
+ String cpuSetStr = CPUSetsReader.readFromProcStatus("Cpus_allowed_list");
+ System.out.println("cpuSetStr = " + cpuSetStr);
+
+ if (cpuSetStr == null) {
+ System.out.printf("The cpuset test cases are skipped");
+ } else {
+ List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
+
+ // Test subset of cpuset with one element
+ if (cpuSet.size() >= 1) {
+ String testCpuSet = CPUSetsReader.listToString(cpuSet, 1);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 4*1024, true, 1);
+ }
+
+ // Test subset of cpuset with two elements
+ if (cpuSet.size() >= 2) {
+ String testCpuSet = CPUSetsReader.listToString(cpuSet, 2);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 4*1024, true, 2);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, true, 2);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, false, 1);
+ }
+
+ // Test subset of cpuset with three elements
+ if (cpuSet.size() >= 3) {
+ String testCpuSet = CPUSetsReader.listToString(cpuSet, 3);
+ testAPCCombo(testCpuSet, 100*1000, 100*1000, 2*1024, true, 1);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, true, 2);
+ testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, false, 1);
+ }
+ }
+ }
+
+
+ private static void testActiveProcessorCount(int valueToSet, int expectedValue) throws Exception {
+ Common.logNewTestCase("Test ActiveProcessorCount: valueToSet = " + valueToSet);
+
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addJavaOpts("-XX:ActiveProcessorCount=" + valueToSet, "-Xlog:os=trace");
+ Common.run(opts)
+ .shouldMatch("active processor count set by user.*" + expectedValue);
+ }
+
+
+ private static void testCpus(int valueToSet, int expectedTraceValue) throws Exception {
+ Common.logNewTestCase("test cpus: " + valueToSet);
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addDockerOpts("--cpu-period=" + 10000)
+ .addDockerOpts("--cpu-quota=" + valueToSet * 10000);
+ Common.run(opts)
+ .shouldMatch("active_processor_count.*" + expectedTraceValue);
+ }
+
+
+ // Expected active processor count can not exceed available CPU count
+ private static int adjustExpectedAPCForAvailableCPUs(int expectedAPC) {
+ if (expectedAPC > availableCPUs) {
+ expectedAPC = availableCPUs;
+ System.out.println("Adjusted expectedAPC = " + expectedAPC);
+ }
+ return expectedAPC;
+ }
+
+
+ private static void testCpuQuotaAndPeriod(int quota, int period)
+ throws Exception {
+ Common.logNewTestCase("test cpu quota and period: ");
+ System.out.println("quota = " + quota);
+ System.out.println("period = " + period);
+
+ int expectedAPC = (int) Math.ceil((float) quota / (float) period);
+ System.out.println("expectedAPC = " + expectedAPC);
+ expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addDockerOpts("--cpu-period=" + period)
+ .addDockerOpts("--cpu-quota=" + quota);
+
+ Common.run(opts)
+ .shouldMatch("CPU Period is.*" + period)
+ .shouldMatch("CPU Quota is.*" + quota)
+ .shouldMatch("active_processor_count.*" + expectedAPC);
+ }
+
+
+ // Test correctess of automatically selected active processor cound
+ private static void testAPCCombo(String cpuset, int quota, int period, int shares,
+ boolean usePreferContainerQuotaForCPUCount,
+ int expectedAPC) throws Exception {
+ Common.logNewTestCase("test APC Combo");
+ System.out.println("cpuset = " + cpuset);
+ System.out.println("quota = " + quota);
+ System.out.println("period = " + period);
+ System.out.println("shares = " + shares);
+ System.out.println("usePreferContainerQuotaForCPUCount = " + usePreferContainerQuotaForCPUCount);
+ System.out.println("expectedAPC = " + expectedAPC);
+
+ expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addDockerOpts("--cpuset-cpus", "" + cpuset)
+ .addDockerOpts("--cpu-period=" + period)
+ .addDockerOpts("--cpu-quota=" + quota)
+ .addDockerOpts("--cpu-shares=" + shares);
+
+ if (!usePreferContainerQuotaForCPUCount) opts.addJavaOpts("-XX:-PreferContainerQuotaForCPUCount");
+
+ Common.run(opts)
+ .shouldMatch("active_processor_count.*" + expectedAPC);
+ }
+
+
+ private static void testCpuShares(int shares, int expectedAPC) throws Exception {
+ Common.logNewTestCase("test cpu shares, shares = " + shares);
+ System.out.println("expectedAPC = " + expectedAPC);
+
+ expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
+
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addDockerOpts("--cpu-shares=" + shares);
+ Common.run(opts)
+ .shouldMatch("CPU Shares is.*" + shares)
+ .shouldMatch("active_processor_count.*" + expectedAPC);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TestCPUSets.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+/*
+ * @test
+ * @summary Test JVM's awareness of cpu sets (cpus and mems)
+ * @requires docker.support
+ * @requires (os.arch != "s390x")
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @build AttemptOOM sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestCPUSets
+ */
+import java.util.List;
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+import jdk.test.lib.containers.cgroup.CPUSetsReader;
+import jdk.test.lib.Asserts;
+import jdk.test.lib.Platform;
+import jdk.test.lib.Utils;
+import jdk.test.lib.process.OutputAnalyzer;
+
+
+public class TestCPUSets {
+ private static final String imageName = Common.imageName("cpusets");
+
+ public static void main(String[] args) throws Exception {
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ Common.prepareWhiteBox();
+ DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ // Sanity test the cpu sets reader and parser
+ CPUSetsReader.test();
+ testTheSet("Cpus_allowed_list");
+ testTheSet("Mems_allowed_list");
+ } finally {
+ DockerTestUtils.removeDockerImage(imageName);
+ }
+ }
+
+
+ private static void testTheSet(String setType) throws Exception {
+ String cpuSetStr = CPUSetsReader.readFromProcStatus(setType);
+
+ if (cpuSetStr == null) {
+ System.out.printf("The %s test is skipped %n", setType);
+ } else {
+ List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
+
+ // Test subset of one, full subset, and half of the subset
+ testCpuSet(CPUSetsReader.listToString(cpuSet, 1));
+ if (cpuSet.size() > 1) {
+ testCpuSet(CPUSetsReader.listToString(cpuSet));
+ }
+ if (cpuSet.size() > 2) {
+ testCpuSet(CPUSetsReader.listToString(cpuSet, cpuSet.size()/2 ));
+ }
+ }
+ }
+
+
+ private static DockerRunOptions commonOpts() {
+ DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java",
+ "PrintContainerInfo");
+ opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
+ opts.addJavaOpts("-Xlog:os+container=trace", "-cp", "/test-classes/");
+ Common.addWhiteBoxOpts(opts);
+ return opts;
+ }
+
+
+ private static void checkResult(List<String> lines, String lineMarker, String value) {
+ boolean lineMarkerFound = false;
+
+ for (String line : lines) {
+ if (line.contains(lineMarker)) {
+ lineMarkerFound = true;
+ String[] parts = line.split(":");
+ System.out.println("DEBUG: line = " + line);
+ System.out.println("DEBUG: parts.length = " + parts.length);
+
+ Asserts.assertEquals(parts.length, 2);
+ String set = parts[1].replaceAll("\\s","");
+ String actual = CPUSetsReader.listToString(CPUSetsReader.parseCpuSet(set));
+ Asserts.assertEquals(actual, value);
+ break;
+ }
+ }
+ Asserts.assertTrue(lineMarkerFound);
+ }
+
+
+ private static void testCpuSet(String value) throws Exception {
+ Common.logNewTestCase("cpusets.cpus, value = " + value);
+
+ DockerRunOptions opts = commonOpts();
+ opts.addDockerOpts("--cpuset-cpus=" + value);
+
+ List<String> lines = Common.run(opts).asLines();
+ checkResult(lines, "cpuset.cpus is:", value);
+ }
+
+ private static void testMemSet(String value) throws Exception {
+ Common.logNewTestCase("cpusets.mems, value = " + value);
+
+ DockerRunOptions opts = commonOpts();
+ opts.addDockerOpts("--cpuset-mems=" + value);
+
+ List<String> lines = Common.run(opts).asLines();
+ checkResult(lines, "cpuset.mems is:", value);
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TestJFREvents.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 Ensure that certain JFR events return correct results for resource values
+ * when run inside Docker container, such as available CPU and memory.
+ * Also make sure that PIDs are based on value provided by container,
+ * not by the host system.
+ * @requires (docker.support & os.maxMemory >= 2g)
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @build JfrReporter
+ * @run driver TestJFREvents
+ */
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+import jdk.test.lib.Utils;
+
+
+public class TestJFREvents {
+ private static final String imageName = Common.imageName("jfr-events");
+ private static final int availableCPUs = Runtime.getRuntime().availableProcessors();
+
+ public static void main(String[] args) throws Exception {
+ System.out.println("Test Environment: detected availableCPUs = " + availableCPUs);
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ // leave one CPU for system and tools, otherwise this test may be unstable
+ int maxNrOfAvailableCpus = availableCPUs - 1;
+ for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) {
+ testCPUInfo(i, i);
+ }
+
+ long MB = 1024*1024;
+ testMemory("200m", "" + 200*MB);
+ testMemory("500m", "" + 500*MB);
+ testMemory("1g", "" + 1024*MB);
+
+ testProcessInfo();
+
+ } finally {
+ DockerTestUtils.removeDockerImage(imageName);
+ }
+ }
+
+
+ private static void testCPUInfo(int valueToSet, int expectedValue) throws Exception {
+ Common.logNewTestCase("CPUInfo: --cpus = " + valueToSet);
+ DockerTestUtils.dockerRunJava(
+ commonDockerOpts()
+ .addDockerOpts("--cpus=" + valueToSet)
+ .addClassOptions(JfrReporter.TESTCASE_CPU))
+ .shouldHaveExitValue(0)
+ .shouldContain(JfrReporter.TEST_REPORTED_CORES);
+
+ // The following assertion is currently disabled due to JFR reporting incorrect values.
+ // JFR reports values for the host system as opposed to values for the container.
+ // @ignore 8219999
+ // .shouldContain(JfrReporter.TEST_REPORTED_CORES + "=" + expectedValue);
+ }
+
+
+ private static void testMemory(String valueToSet, String expectedValue) throws Exception {
+ Common.logNewTestCase("Memory: --memory = " + valueToSet);
+ DockerTestUtils.dockerRunJava(
+ commonDockerOpts()
+ .addDockerOpts("--memory=" + valueToSet)
+ .addClassOptions(JfrReporter.TESTCASE_MEMORY))
+ .shouldHaveExitValue(0)
+ .shouldContain(JfrReporter.TEST_REPORTED_MEMORY + "=" + expectedValue);
+ }
+
+
+ private static void testProcessInfo() throws Exception {
+ Common.logNewTestCase("ProcessInfo");
+ DockerTestUtils.dockerRunJava(
+ commonDockerOpts()
+ .addClassOptions(JfrReporter.TESTCASE_PROCESS))
+ .shouldHaveExitValue(0)
+ .shouldContain(JfrReporter.TEST_REPORTED_PID + "=1");
+
+ }
+
+
+ private static DockerRunOptions commonDockerOpts() {
+ return new DockerRunOptions(imageName, "/jdk/bin/java", "JfrReporter")
+ .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/")
+ .addJavaOpts("-cp", "/test-classes/");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TestMemoryAwareness.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2017, 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
+ * @summary Test JVM's memory resource awareness when running inside docker container
+ * @requires docker.support
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @build AttemptOOM sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestMemoryAwareness
+ */
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+
+
+public class TestMemoryAwareness {
+ private static final String imageName = Common.imageName("memory");
+
+ public static void main(String[] args) throws Exception {
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ Common.prepareWhiteBox();
+ DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ testMemoryLimit("100m", "104857600");
+ testMemoryLimit("500m", "524288000");
+ testMemoryLimit("1g", "1073741824");
+ testMemoryLimit("4g", "4294967296");
+
+ testMemorySoftLimit("500m", "524288000");
+ testMemorySoftLimit("1g", "1073741824");
+
+ // Add extra 10 Mb to allocator limit, to be sure to cause OOM
+ testOOM("256m", 256 + 10);
+
+ } finally {
+ DockerTestUtils.removeDockerImage(imageName);
+ }
+ }
+
+
+ private static void testMemoryLimit(String valueToSet, String expectedTraceValue)
+ throws Exception {
+
+ Common.logNewTestCase("memory limit: " + valueToSet);
+
+ DockerRunOptions opts = Common.newOpts(imageName)
+ .addDockerOpts("--memory", valueToSet);
+
+ Common.run(opts)
+ .shouldMatch("Memory Limit is:.*" + expectedTraceValue);
+ }
+
+
+ private static void testMemorySoftLimit(String valueToSet, String expectedTraceValue)
+ throws Exception {
+ Common.logNewTestCase("memory soft limit: " + valueToSet);
+
+ DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
+ Common.addWhiteBoxOpts(opts);
+ opts.addDockerOpts("--memory-reservation=" + valueToSet);
+
+ Common.run(opts)
+ .shouldMatch("Memory Soft Limit.*" + expectedTraceValue);
+ }
+
+
+ // provoke OOM inside the container, see how VM reacts
+ private static void testOOM(String dockerMemLimit, int sizeToAllocInMb) throws Exception {
+ Common.logNewTestCase("OOM");
+
+ DockerRunOptions opts = Common.newOpts(imageName, "AttemptOOM")
+ .addDockerOpts("--memory", dockerMemLimit, "--memory-swap", dockerMemLimit);
+ opts.classParams.add("" + sizeToAllocInMb);
+
+ DockerTestUtils.dockerRunJava(opts)
+ .shouldHaveExitValue(1)
+ .shouldContain("Entering AttemptOOM main")
+ .shouldNotContain("AttemptOOM allocation successful")
+ .shouldContain("java.lang.OutOfMemoryError");
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/containers/docker/TestMisc.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2017, 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
+ * @summary Test miscellanous functionality related to JVM running in docker container
+ * @requires docker.support
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * java.management
+ * jdk.jartool/sun.tools.jar
+ * @build CheckContainerized sun.hotspot.WhiteBox PrintContainerInfo
+ * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
+ * @run driver TestMisc
+ */
+import jdk.test.lib.containers.docker.Common;
+import jdk.test.lib.containers.docker.DockerTestUtils;
+import jdk.test.lib.containers.docker.DockerRunOptions;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+
+public class TestMisc {
+ private static final String imageName = Common.imageName("misc");
+
+ public static void main(String[] args) throws Exception {
+ if (!DockerTestUtils.canTestDocker()) {
+ return;
+ }
+
+ Common.prepareWhiteBox();
+ DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
+
+ try {
+ testMinusContainerSupport();
+ testIsContainerized();
+ testPrintContainerInfo();
+ } finally {
+ DockerTestUtils.removeDockerImage(imageName);
+ }
+ }
+
+
+ private static void testMinusContainerSupport() throws Exception {
+ Common.logNewTestCase("Test related flags: '-UseContainerSupport'");
+ DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "-version");
+ opts.addJavaOpts("-XX:-UseContainerSupport", "-Xlog:os+container=trace");
+
+ Common.run(opts)
+ .shouldContain("Container Support not enabled");
+ }
+
+
+ private static void testIsContainerized() throws Exception {
+ Common.logNewTestCase("Test is_containerized() inside a docker container");
+
+ DockerRunOptions opts = Common.newOpts(imageName, "CheckContainerized");
+ Common.addWhiteBoxOpts(opts);
+
+ Common.run(opts)
+ .shouldContain(CheckContainerized.INSIDE_A_CONTAINER);
+ }
+
+
+ private static void testPrintContainerInfo() throws Exception {
+ Common.logNewTestCase("Test print_container_info()");
+
+ DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
+ Common.addWhiteBoxOpts(opts);
+
+ checkContainerInfo(Common.run(opts));
+ }
+
+
+ private static void checkContainerInfo(OutputAnalyzer out) throws Exception {
+ String[] expectedToContain = new String[] {
+ "cpuset.cpus",
+ "cpuset.mems",
+ "CPU Shares",
+ "CPU Quota",
+ "CPU Period",
+ "OSContainer::active_processor_count",
+ "Memory Limit",
+ "Memory Soft Limit",
+ "Memory Usage",
+ "Maximum Memory Usage",
+ "memory_max_usage_in_bytes"
+ };
+
+ for (String s : expectedToContain) {
+ out.shouldContain(s);
+ }
+ }
+
+}
--- a/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestMemoryMXBeans.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/gc/shenandoah/mxbeans/TestMemoryMXBeans.java Sat Apr 13 07:23:18 2019 +0100
@@ -31,6 +31,8 @@
* @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xmx1g TestMemoryMXBeans -1 1024
* @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms1g -Xmx1g TestMemoryMXBeans 1024 1024
* @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms128m -Xmx1g TestMemoryMXBeans 128 1024
+ * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms1g -Xmx1g -XX:ShenandoahUncommitDelay=0 TestMemoryMXBeans 1024 1024
+ * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -Xms128m -Xmx1g -XX:ShenandoahUncommitDelay=0 TestMemoryMXBeans 128 1024
*/
import java.lang.management.*;
@@ -46,6 +48,9 @@
long initSize = 1L * Integer.parseInt(args[0]) * 1024 * 1024;
long maxSize = 1L * Integer.parseInt(args[1]) * 1024 * 1024;
+ // wait for GC to uncommit
+ Thread.sleep(1000);
+
testMemoryBean(initSize, maxSize);
}
@@ -65,7 +70,15 @@
throw new IllegalStateException("Max heap size is wrong: " + heapMax + " vs " + maxSize);
}
if (initSize > 0 && maxSize > 0 && initSize != maxSize && heapCommitted == heapMax) {
- throw new IllegalStateException("Init committed heap size is wrong: " + heapCommitted +
+ throw new IllegalStateException("Committed heap size is max: " + heapCommitted +
+ " (init: " + initSize + ", max: " + maxSize + ")");
+ }
+ if (initSize > 0 && maxSize > 0 && initSize == maxSize && heapCommitted != heapMax) {
+ throw new IllegalStateException("Committed heap size is not max: " + heapCommitted +
+ " (init: " + initSize + ", max: " + maxSize + ")");
+ }
+ if (initSize > 0 && heapCommitted < initSize) {
+ throw new IllegalStateException("Committed heap size is below min: " + heapCommitted +
" (init: " + initSize + ", max: " + maxSize + ")");
}
}
--- a/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java Sat Apr 13 07:23:18 2019 +0100
@@ -25,14 +25,16 @@
* @test
* @bug 8174749 8213307
* @summary MemberNameTable should reuse entries
- * @requires vm.gc == "null"
- * @library /test/lib
+ * @library /test/lib /runtime/testlibrary
+ * @modules java.base/jdk.internal.misc
+ * @modules java.compiler
* @build sun.hotspot.WhiteBox
* @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
* @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. MemberNameLeak
*/
import java.lang.invoke.*;
+import java.lang.reflect.*;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import sun.hotspot.WhiteBox;
@@ -40,6 +42,12 @@
import sun.hotspot.gc.GC;
public class MemberNameLeak {
+ private static String className = "MemberNameLeakTestClass";
+ private static String methodPrefix = "method";
+ // The size of the ResolvedMethodTable is 1024. 2000 entries
+ // is enough to trigger a grow/cleaning of the table after a GC.
+ private static int methodCount = 2000;
+
static class Leak {
public void callMe() {
}
@@ -47,15 +55,31 @@
public static void main(String[] args) throws Throwable {
Leak leak = new Leak();
WhiteBox wb = WhiteBox.getWhiteBox();
- int removedCountOrig = wb.resolvedMethodRemovedCount();
- int removedCount;
+
+ ClassWithManyMethodsClassLoader classLoader = new ClassWithManyMethodsClassLoader();
+ Class<?> clazz = classLoader.create(className, methodPrefix, methodCount);
+
+ long before = wb.resolvedMethodItemsCount();
+
+ Object o = clazz.newInstance();
+ MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(clazz, MethodHandles.lookup());
- for (int i = 0; i < 10; i++) {
- MethodHandles.Lookup lookup = MethodHandles.lookup();
- MethodType mt = MethodType.fromMethodDescriptorString("()V", Leak.class.getClassLoader());
+ for (int i = 0; i < methodCount; i++) {
+ MethodType mt = MethodType.fromMethodDescriptorString("()V", classLoader);
+ String methodName = methodPrefix + i;
// findSpecial leaks some native mem
- MethodHandle mh = lookup.findSpecial(Leak.class, "callMe", mt, Leak.class);
- mh.invokeExact(leak);
+ // Add entry to ResolvedMethodTable.
+ MethodHandle mh0 = lookup.findSpecial(clazz, methodName, mt, clazz);
+ // Find entry in ResolvedMethodTable.
+ MethodHandle mh1 = lookup.findSpecial(clazz, methodName, mt, clazz);
+
+ mh1.invoke(o);
+ }
+
+ long after = wb.resolvedMethodItemsCount();
+
+ if (after == before) {
+ throw new RuntimeException("Too few resolved methods");
}
// Wait until ServiceThread cleans ResolvedMethod table
@@ -64,16 +88,19 @@
if (cnt++ % 30 == 0) {
System.gc(); // make mh unused
}
- removedCount = wb.resolvedMethodRemovedCount();
- if (removedCountOrig != removedCount) {
+
+ if (after != wb.resolvedMethodItemsCount()) {
+ // Entries have been removed.
break;
}
+
Thread.sleep(100);
}
}
}
- public static void test(String gc, boolean doConcurrent) throws Throwable {
+ public static void test(GC gc, boolean doConcurrent) throws Throwable {
+ System.err.println("test(" + gc + ", " + doConcurrent + ")");
// Run this Leak class with logging
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
"-Xlog:membername+table=trace",
@@ -84,27 +111,35 @@
doConcurrent ? "-XX:+ExplicitGCInvokesConcurrent" : "-XX:-ExplicitGCInvokesConcurrent",
"-XX:+ClassUnloading",
"-XX:+ClassUnloadingWithConcurrentMark",
- gc, Leak.class.getName());
+ "-XX:+Use" + gc + "GC",
+ Leak.class.getName());
OutputAnalyzer output = new OutputAnalyzer(pb.start());
- output.shouldContain("ResolvedMethod entry added for MemberNameLeak$Leak.callMe()V");
- output.shouldContain("ResolvedMethod entry found for MemberNameLeak$Leak.callMe()V");
+ // Hardcoded names for classes generated by GeneratedClassLoader
+ String descriptor = className + "." + methodPrefix + "0()V";
+ output.shouldContain("ResolvedMethod entry added for " + descriptor);
+ output.shouldContain("ResolvedMethod entry found for " + descriptor);
output.shouldContain("ResolvedMethod entry removed");
output.shouldHaveExitValue(0);
}
- public static void main(java.lang.String[] unused) throws Throwable {
- test("-XX:+UseG1GC", false);
- test("-XX:+UseG1GC", true);
+ private static boolean supportsSTW(GC gc) {
+ return !(gc == GC.Epsilon);
+ }
- test("-XX:+UseParallelGC", false);
- test("-XX:+UseSerialGC", false);
- if (!Compiler.isGraalEnabled()) { // Graal does not support CMS
- test("-XX:+UseConcMarkSweepGC", false);
- test("-XX:+UseConcMarkSweepGC", true);
- if (GC.Shenandoah.isSupported()) {
- test("-XX:+UseShenandoahGC", true);
- test("-XX:+UseShenandoahGC", false);
- }
+ private static boolean supportsConcurrent(GC gc) {
+ return !(gc == GC.Epsilon || gc == GC.Serial || gc == GC.Parallel);
+ }
+
+ private static void test(GC gc) throws Throwable {
+ if (supportsSTW(gc)) {
+ test(gc, false);
+ }
+ if (supportsConcurrent(gc)) {
+ test(gc, true);
}
}
+
+ public static void main(java.lang.String[] unused) throws Throwable {
+ test(GC.selected());
+ }
}
--- a/test/hotspot/jtreg/runtime/containers/cgroup/PlainRead.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2017, 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 PlainRead
- * @requires os.family == "linux"
- * @library /testlibrary /test/lib
- * @build sun.hotspot.WhiteBox
- * @run driver ClassFileInstaller sun.hotspot.WhiteBox
- * sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI PlainRead
- */
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-import jdk.test.lib.Platform;
-import sun.hotspot.WhiteBox;
-
-public class PlainRead {
-
- static public void match(OutputAnalyzer oa, String what, String value) {
- oa.shouldMatch("^.*" + what + " *" + value + ".*$");
- }
-
- static public void noMatch(OutputAnalyzer oa, String what, String value) {
- oa.shouldNotMatch("^.*" + what + " *" + value + ".*$");
- }
-
- static final String good_value = "(\\d+|-1|Unlimited)";
- static final String bad_value = "(failed)";
-
- static final String[] variables = {"Memory Limit is:", "CPU Shares is:", "CPU Quota is:", "CPU Period is:", "active_processor_count:"};
-
- static public void isContainer(OutputAnalyzer oa) {
- for (String v: variables) {
- match(oa, v, good_value);
- }
- for (String v: variables) {
- noMatch(oa, v, bad_value);
- }
- }
-
- static public void isNotContainer(OutputAnalyzer oa) {
- oa.shouldMatch("^.*Can't open /proc/self/mountinfo.*$");
- }
-
- public static void main(String[] args) throws Exception {
- WhiteBox wb = WhiteBox.getWhiteBox();
- ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+container=trace", "-version");
- OutputAnalyzer output = new OutputAnalyzer(pb.start());
-
- if (wb.isContainerized()) {
- System.out.println("Inside a cgroup, testing...");
- isContainer(output);
- }
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/AttemptOOM.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-public class AttemptOOM {
- private static MyObj[] data;
-
- public static void main(String[] args) throws Exception {
- System.out.println("Entering AttemptOOM main");
-
- // each MyObj will allocate 1024 byte array
- int sizeInMb = Integer.parseInt(args[0]);
- data = new MyObj[sizeInMb*1024];
-
- System.out.println("data.length = " + data.length);
-
- for (int i=0; i < data.length; i++) {
- data[i] = new MyObj(1024);
- }
-
- System.out.println("AttemptOOM allocation successful");
- }
-
- private static class MyObj {
- private byte[] myData;
- MyObj(int size) {
- myData = new byte[size];
- }
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/CheckContainerized.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-import sun.hotspot.WhiteBox;
-
-public class CheckContainerized {
- public static String OUTSIDE_OF_CONTAINER =
- "CheckContainerized: Running outside of a container";
- public static String INSIDE_A_CONTAINER =
- "CheckContainerized: Running inside a container";
-
- public static void main(String[] args) {
- System.out.println("CheckContainerized: Entering");
- WhiteBox wb = WhiteBox.getWhiteBox();
-
- if (wb.isContainerized()) {
- System.out.println(INSIDE_A_CONTAINER);
-
- } else {
- System.out.println(OUTSIDE_OF_CONTAINER);
- }
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/DockerBasicTest.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,84 +0,0 @@
-/*
- * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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 Basic (sanity) test for JDK-under-test inside a docker image.
- * @requires docker.support
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @build HelloDocker
- * @run driver DockerBasicTest
- */
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-import jdk.test.lib.Platform;
-import jdk.test.lib.Utils;
-
-
-public class DockerBasicTest {
- private static final String imageNameAndTag = Common.imageName("basic");
-
- public static void main(String[] args) throws Exception {
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- DockerTestUtils.buildJdkDockerImage(imageNameAndTag, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- testJavaVersion();
- testHelloDocker();
- } finally {
- if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) {
- DockerTestUtils.removeDockerImage(imageNameAndTag);
- }
- }
- }
-
-
- private static void testJavaVersion() throws Exception {
- DockerRunOptions opts =
- new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "-version");
-
- DockerTestUtils.dockerRunJava(opts)
- .shouldHaveExitValue(0)
- .shouldContain(Platform.vmName);
- }
-
-
- private static void testHelloDocker() throws Exception {
- DockerRunOptions opts =
- new DockerRunOptions(imageNameAndTag, "/jdk/bin/java", "HelloDocker")
- .addJavaOpts("-cp", "/test-classes/")
- .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
-
- DockerTestUtils.dockerRunJava(opts)
- .shouldHaveExitValue(0)
- .shouldContain("Hello Docker");
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/HelloDocker.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-public class HelloDocker {
- public static void main(String args[]) {
- System.out.println("Hello Docker");
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/JfrReporter.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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.
- */
-
-import java.nio.file.Paths;
-import jdk.jfr.Recording;
-import jdk.jfr.consumer.RecordedEvent;
-import jdk.jfr.consumer.RecordingFile;
-
-
-// This class is intended to run inside a container
-public class JfrReporter {
- public static final String TEST_REPORTED_CORES="TEST_REPORTED_CORES";
- public static final String TEST_REPORTED_MEMORY="TEST_REPORTED_MEMORY";
- public static final String TEST_REPORTED_PID="TEST_REPORTED_PID";
- public static final String TESTCASE_CPU="cpu";
- public static final String TESTCASE_MEMORY="memory";
- public static final String TESTCASE_PROCESS="process";
-
- public static void main(String[] args) throws Exception {
- String testCase = args[0];
- System.out.println("Testcase: " + testCase);
- switch (testCase) {
- case TESTCASE_CPU:
- RecordedEvent event = testEvent("jdk.CPUInformation", "cpu.jfr");
- System.out.println(TEST_REPORTED_CORES + "=" + event.getInt("cores"));
- break;
- case TESTCASE_MEMORY:
- event = testEvent("jdk.PhysicalMemory", "memory.jfr");
- System.out.println(TEST_REPORTED_MEMORY + "=" + event.getLong("totalSize"));
- break;
- case TESTCASE_PROCESS:
- event = testEvent("jdk.SystemProcess", "process.jfr");
- System.out.println(TEST_REPORTED_PID + "=" + event.getString("pid"));
- break;
- default:
- throw new IllegalArgumentException("Invalid test case");
- }
- }
-
- private static RecordedEvent testEvent(String event, String recordingPath) throws Exception {
- System.out.println("========= Testing event: " + event);
- Recording r = new Recording();
- r.enable(event);
- r.setDestination(Paths.get("tmp", recordingPath));
- r.start();
- r.stop();
-
- RecordedEvent recordedEvent = RecordingFile.readAllEvents(r.getDestination()).get(0);
- System.out.println("RecordedEvent: " + recordedEvent);
- return recordedEvent;
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/PrintContainerInfo.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-import sun.hotspot.WhiteBox;
-
-public class PrintContainerInfo {
-
- public static void main(String[] args) {
- System.out.println("PrintContainerInfo: Entering");
- WhiteBox wb = WhiteBox.getWhiteBox();
-
- wb.printOsInfo();
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/TEST.properties Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-exclusiveAccess.dirs=.
--- a/test/hotspot/jtreg/runtime/containers/docker/TestCPUAwareness.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,209 +0,0 @@
-/*
- * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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 JVM's CPU resource awareness when running inside docker container
- * @requires docker.support
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @run driver TestCPUAwareness
- */
-import java.util.List;
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-import jdk.test.lib.containers.cgroup.CPUSetsReader;
-
-public class TestCPUAwareness {
- private static final String imageName = Common.imageName("cpu");
- private static final int availableCPUs = Runtime.getRuntime().availableProcessors();
-
- public static void main(String[] args) throws Exception {
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- System.out.println("Test Environment: detected availableCPUs = " + availableCPUs);
- DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- // cpuset, period, shares, expected Active Processor Count
- testComboWithCpuSets();
-
- // cpu shares - it should be safe to use CPU shares exceeding available CPUs
- testCpuShares(256, 1);
- testCpuShares(2048, 2);
- testCpuShares(4096, 4);
-
- // leave one CPU for system and tools, otherwise this test may be unstable
- int maxNrOfAvailableCpus = availableCPUs - 1;
- for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) {
- testCpus(i, i);
- }
-
- // If ActiveProcessorCount is set, the VM should use it, regardless of other
- // container settings, host settings or available CPUs on the host.
- testActiveProcessorCount(1, 1);
- testActiveProcessorCount(2, 2);
-
- // cpu quota and period
- testCpuQuotaAndPeriod(50*1000, 100*1000);
- testCpuQuotaAndPeriod(100*1000, 100*1000);
- testCpuQuotaAndPeriod(150*1000, 100*1000);
- testCpuQuotaAndPeriod(400*1000, 100*1000);
-
- } finally {
- DockerTestUtils.removeDockerImage(imageName);
- }
- }
-
-
- private static void testComboWithCpuSets() throws Exception {
- String cpuSetStr = CPUSetsReader.readFromProcStatus("Cpus_allowed_list");
- System.out.println("cpuSetStr = " + cpuSetStr);
-
- if (cpuSetStr == null) {
- System.out.printf("The cpuset test cases are skipped");
- } else {
- List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
-
- // Test subset of cpuset with one element
- if (cpuSet.size() >= 1) {
- String testCpuSet = CPUSetsReader.listToString(cpuSet, 1);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 4*1024, true, 1);
- }
-
- // Test subset of cpuset with two elements
- if (cpuSet.size() >= 2) {
- String testCpuSet = CPUSetsReader.listToString(cpuSet, 2);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 4*1024, true, 2);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, true, 2);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, false, 1);
- }
-
- // Test subset of cpuset with three elements
- if (cpuSet.size() >= 3) {
- String testCpuSet = CPUSetsReader.listToString(cpuSet, 3);
- testAPCCombo(testCpuSet, 100*1000, 100*1000, 2*1024, true, 1);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, true, 2);
- testAPCCombo(testCpuSet, 200*1000, 100*1000, 1023, false, 1);
- }
- }
- }
-
-
- private static void testActiveProcessorCount(int valueToSet, int expectedValue) throws Exception {
- Common.logNewTestCase("Test ActiveProcessorCount: valueToSet = " + valueToSet);
-
- DockerRunOptions opts = Common.newOpts(imageName)
- .addJavaOpts("-XX:ActiveProcessorCount=" + valueToSet, "-Xlog:os=trace");
- Common.run(opts)
- .shouldMatch("active processor count set by user.*" + expectedValue);
- }
-
-
- private static void testCpus(int valueToSet, int expectedTraceValue) throws Exception {
- Common.logNewTestCase("test cpus: " + valueToSet);
- DockerRunOptions opts = Common.newOpts(imageName)
- .addDockerOpts("--cpu-period=" + 10000)
- .addDockerOpts("--cpu-quota=" + valueToSet * 10000);
- Common.run(opts)
- .shouldMatch("active_processor_count.*" + expectedTraceValue);
- }
-
-
- // Expected active processor count can not exceed available CPU count
- private static int adjustExpectedAPCForAvailableCPUs(int expectedAPC) {
- if (expectedAPC > availableCPUs) {
- expectedAPC = availableCPUs;
- System.out.println("Adjusted expectedAPC = " + expectedAPC);
- }
- return expectedAPC;
- }
-
-
- private static void testCpuQuotaAndPeriod(int quota, int period)
- throws Exception {
- Common.logNewTestCase("test cpu quota and period: ");
- System.out.println("quota = " + quota);
- System.out.println("period = " + period);
-
- int expectedAPC = (int) Math.ceil((float) quota / (float) period);
- System.out.println("expectedAPC = " + expectedAPC);
- expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
-
- DockerRunOptions opts = Common.newOpts(imageName)
- .addDockerOpts("--cpu-period=" + period)
- .addDockerOpts("--cpu-quota=" + quota);
-
- Common.run(opts)
- .shouldMatch("CPU Period is.*" + period)
- .shouldMatch("CPU Quota is.*" + quota)
- .shouldMatch("active_processor_count.*" + expectedAPC);
- }
-
-
- // Test correctess of automatically selected active processor cound
- private static void testAPCCombo(String cpuset, int quota, int period, int shares,
- boolean usePreferContainerQuotaForCPUCount,
- int expectedAPC) throws Exception {
- Common.logNewTestCase("test APC Combo");
- System.out.println("cpuset = " + cpuset);
- System.out.println("quota = " + quota);
- System.out.println("period = " + period);
- System.out.println("shares = " + shares);
- System.out.println("usePreferContainerQuotaForCPUCount = " + usePreferContainerQuotaForCPUCount);
- System.out.println("expectedAPC = " + expectedAPC);
-
- expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
-
- DockerRunOptions opts = Common.newOpts(imageName)
- .addDockerOpts("--cpuset-cpus", "" + cpuset)
- .addDockerOpts("--cpu-period=" + period)
- .addDockerOpts("--cpu-quota=" + quota)
- .addDockerOpts("--cpu-shares=" + shares);
-
- if (!usePreferContainerQuotaForCPUCount) opts.addJavaOpts("-XX:-PreferContainerQuotaForCPUCount");
-
- Common.run(opts)
- .shouldMatch("active_processor_count.*" + expectedAPC);
- }
-
-
- private static void testCpuShares(int shares, int expectedAPC) throws Exception {
- Common.logNewTestCase("test cpu shares, shares = " + shares);
- System.out.println("expectedAPC = " + expectedAPC);
-
- expectedAPC = adjustExpectedAPCForAvailableCPUs(expectedAPC);
-
- DockerRunOptions opts = Common.newOpts(imageName)
- .addDockerOpts("--cpu-shares=" + shares);
- Common.run(opts)
- .shouldMatch("CPU Shares is.*" + shares)
- .shouldMatch("active_processor_count.*" + expectedAPC);
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/TestCPUSets.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,142 +0,0 @@
-/*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-
-/*
- * @test
- * @summary Test JVM's awareness of cpu sets (cpus and mems)
- * @requires docker.support
- * @requires (os.arch != "s390x")
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @build AttemptOOM sun.hotspot.WhiteBox PrintContainerInfo
- * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run driver TestCPUSets
- */
-import java.util.List;
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-import jdk.test.lib.containers.cgroup.CPUSetsReader;
-import jdk.test.lib.Asserts;
-import jdk.test.lib.Platform;
-import jdk.test.lib.Utils;
-import jdk.test.lib.process.OutputAnalyzer;
-
-
-public class TestCPUSets {
- private static final String imageName = Common.imageName("cpusets");
-
- public static void main(String[] args) throws Exception {
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- Common.prepareWhiteBox();
- DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- // Sanity test the cpu sets reader and parser
- CPUSetsReader.test();
- testTheSet("Cpus_allowed_list");
- testTheSet("Mems_allowed_list");
- } finally {
- DockerTestUtils.removeDockerImage(imageName);
- }
- }
-
-
- private static void testTheSet(String setType) throws Exception {
- String cpuSetStr = CPUSetsReader.readFromProcStatus(setType);
-
- if (cpuSetStr == null) {
- System.out.printf("The %s test is skipped %n", setType);
- } else {
- List<Integer> cpuSet = CPUSetsReader.parseCpuSet(cpuSetStr);
-
- // Test subset of one, full subset, and half of the subset
- testCpuSet(CPUSetsReader.listToString(cpuSet, 1));
- if (cpuSet.size() > 1) {
- testCpuSet(CPUSetsReader.listToString(cpuSet));
- }
- if (cpuSet.size() > 2) {
- testCpuSet(CPUSetsReader.listToString(cpuSet, cpuSet.size()/2 ));
- }
- }
- }
-
-
- private static DockerRunOptions commonOpts() {
- DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java",
- "PrintContainerInfo");
- opts.addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/");
- opts.addJavaOpts("-Xlog:os+container=trace", "-cp", "/test-classes/");
- Common.addWhiteBoxOpts(opts);
- return opts;
- }
-
-
- private static void checkResult(List<String> lines, String lineMarker, String value) {
- boolean lineMarkerFound = false;
-
- for (String line : lines) {
- if (line.contains(lineMarker)) {
- lineMarkerFound = true;
- String[] parts = line.split(":");
- System.out.println("DEBUG: line = " + line);
- System.out.println("DEBUG: parts.length = " + parts.length);
-
- Asserts.assertEquals(parts.length, 2);
- String set = parts[1].replaceAll("\\s","");
- String actual = CPUSetsReader.listToString(CPUSetsReader.parseCpuSet(set));
- Asserts.assertEquals(actual, value);
- break;
- }
- }
- Asserts.assertTrue(lineMarkerFound);
- }
-
-
- private static void testCpuSet(String value) throws Exception {
- Common.logNewTestCase("cpusets.cpus, value = " + value);
-
- DockerRunOptions opts = commonOpts();
- opts.addDockerOpts("--cpuset-cpus=" + value);
-
- List<String> lines = Common.run(opts).asLines();
- checkResult(lines, "cpuset.cpus is:", value);
- }
-
- private static void testMemSet(String value) throws Exception {
- Common.logNewTestCase("cpusets.mems, value = " + value);
-
- DockerRunOptions opts = commonOpts();
- opts.addDockerOpts("--cpuset-mems=" + value);
-
- List<String> lines = Common.run(opts).asLines();
- checkResult(lines, "cpuset.mems is:", value);
- }
-
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/TestJFREvents.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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 Ensure that certain JFR events return correct results for resource values
- * when run inside Docker container, such as available CPU and memory.
- * Also make sure that PIDs are based on value provided by container,
- * not by the host system.
- * @requires (docker.support & os.maxMemory >= 2g)
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @build JfrReporter
- * @run driver TestJFREvents
- */
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-import jdk.test.lib.Utils;
-
-
-public class TestJFREvents {
- private static final String imageName = Common.imageName("jfr-events");
- private static final int availableCPUs = Runtime.getRuntime().availableProcessors();
-
- public static void main(String[] args) throws Exception {
- System.out.println("Test Environment: detected availableCPUs = " + availableCPUs);
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- // leave one CPU for system and tools, otherwise this test may be unstable
- int maxNrOfAvailableCpus = availableCPUs - 1;
- for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) {
- testCPUInfo(i, i);
- }
-
- long MB = 1024*1024;
- testMemory("200m", "" + 200*MB);
- testMemory("500m", "" + 500*MB);
- testMemory("1g", "" + 1024*MB);
-
- testProcessInfo();
-
- } finally {
- DockerTestUtils.removeDockerImage(imageName);
- }
- }
-
-
- private static void testCPUInfo(int valueToSet, int expectedValue) throws Exception {
- Common.logNewTestCase("CPUInfo: --cpus = " + valueToSet);
- DockerTestUtils.dockerRunJava(
- commonDockerOpts()
- .addDockerOpts("--cpus=" + valueToSet)
- .addClassOptions(JfrReporter.TESTCASE_CPU))
- .shouldHaveExitValue(0)
- .shouldContain(JfrReporter.TEST_REPORTED_CORES);
-
- // The following assertion is currently disabled due to JFR reporting incorrect values.
- // JFR reports values for the host system as opposed to values for the container.
- // @ignore 8219999
- // .shouldContain(JfrReporter.TEST_REPORTED_CORES + "=" + expectedValue);
- }
-
-
- private static void testMemory(String valueToSet, String expectedValue) throws Exception {
- Common.logNewTestCase("Memory: --memory = " + valueToSet);
- DockerTestUtils.dockerRunJava(
- commonDockerOpts()
- .addDockerOpts("--memory=" + valueToSet)
- .addClassOptions(JfrReporter.TESTCASE_MEMORY))
- .shouldHaveExitValue(0)
- .shouldContain(JfrReporter.TEST_REPORTED_MEMORY + "=" + expectedValue);
- }
-
-
- private static void testProcessInfo() throws Exception {
- Common.logNewTestCase("ProcessInfo");
- DockerTestUtils.dockerRunJava(
- commonDockerOpts()
- .addClassOptions(JfrReporter.TESTCASE_PROCESS))
- .shouldHaveExitValue(0)
- .shouldContain(JfrReporter.TEST_REPORTED_PID + "=1");
-
- }
-
-
- private static DockerRunOptions commonDockerOpts() {
- return new DockerRunOptions(imageName, "/jdk/bin/java", "JfrReporter")
- .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/")
- .addJavaOpts("-cp", "/test-classes/");
- }
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/TestMemoryAwareness.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2017, 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
- * @summary Test JVM's memory resource awareness when running inside docker container
- * @requires docker.support
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @build AttemptOOM sun.hotspot.WhiteBox PrintContainerInfo
- * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run driver TestMemoryAwareness
- */
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-
-
-public class TestMemoryAwareness {
- private static final String imageName = Common.imageName("memory");
-
- public static void main(String[] args) throws Exception {
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- Common.prepareWhiteBox();
- DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- testMemoryLimit("100m", "104857600");
- testMemoryLimit("500m", "524288000");
- testMemoryLimit("1g", "1073741824");
- testMemoryLimit("4g", "4294967296");
-
- testMemorySoftLimit("500m", "524288000");
- testMemorySoftLimit("1g", "1073741824");
-
- // Add extra 10 Mb to allocator limit, to be sure to cause OOM
- testOOM("256m", 256 + 10);
-
- } finally {
- DockerTestUtils.removeDockerImage(imageName);
- }
- }
-
-
- private static void testMemoryLimit(String valueToSet, String expectedTraceValue)
- throws Exception {
-
- Common.logNewTestCase("memory limit: " + valueToSet);
-
- DockerRunOptions opts = Common.newOpts(imageName)
- .addDockerOpts("--memory", valueToSet);
-
- Common.run(opts)
- .shouldMatch("Memory Limit is:.*" + expectedTraceValue);
- }
-
-
- private static void testMemorySoftLimit(String valueToSet, String expectedTraceValue)
- throws Exception {
- Common.logNewTestCase("memory soft limit: " + valueToSet);
-
- DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
- Common.addWhiteBoxOpts(opts);
- opts.addDockerOpts("--memory-reservation=" + valueToSet);
-
- Common.run(opts)
- .shouldMatch("Memory Soft Limit.*" + expectedTraceValue);
- }
-
-
- // provoke OOM inside the container, see how VM reacts
- private static void testOOM(String dockerMemLimit, int sizeToAllocInMb) throws Exception {
- Common.logNewTestCase("OOM");
-
- DockerRunOptions opts = Common.newOpts(imageName, "AttemptOOM")
- .addDockerOpts("--memory", dockerMemLimit, "--memory-swap", dockerMemLimit);
- opts.classParams.add("" + sizeToAllocInMb);
-
- DockerTestUtils.dockerRunJava(opts)
- .shouldHaveExitValue(1)
- .shouldContain("Entering AttemptOOM main")
- .shouldNotContain("AttemptOOM allocation successful")
- .shouldContain("java.lang.OutOfMemoryError");
- }
-
-}
--- a/test/hotspot/jtreg/runtime/containers/docker/TestMisc.java Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-/*
- * Copyright (c) 2017, 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
- * @summary Test miscellanous functionality related to JVM running in docker container
- * @requires docker.support
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- * java.management
- * jdk.jartool/sun.tools.jar
- * @build CheckContainerized sun.hotspot.WhiteBox PrintContainerInfo
- * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run driver TestMisc
- */
-import jdk.test.lib.containers.docker.Common;
-import jdk.test.lib.containers.docker.DockerTestUtils;
-import jdk.test.lib.containers.docker.DockerRunOptions;
-import jdk.test.lib.process.OutputAnalyzer;
-import jdk.test.lib.process.ProcessTools;
-
-
-public class TestMisc {
- private static final String imageName = Common.imageName("misc");
-
- public static void main(String[] args) throws Exception {
- if (!DockerTestUtils.canTestDocker()) {
- return;
- }
-
- Common.prepareWhiteBox();
- DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");
-
- try {
- testMinusContainerSupport();
- testIsContainerized();
- testPrintContainerInfo();
- } finally {
- DockerTestUtils.removeDockerImage(imageName);
- }
- }
-
-
- private static void testMinusContainerSupport() throws Exception {
- Common.logNewTestCase("Test related flags: '-UseContainerSupport'");
- DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "-version");
- opts.addJavaOpts("-XX:-UseContainerSupport", "-Xlog:os+container=trace");
-
- Common.run(opts)
- .shouldContain("Container Support not enabled");
- }
-
-
- private static void testIsContainerized() throws Exception {
- Common.logNewTestCase("Test is_containerized() inside a docker container");
-
- DockerRunOptions opts = Common.newOpts(imageName, "CheckContainerized");
- Common.addWhiteBoxOpts(opts);
-
- Common.run(opts)
- .shouldContain(CheckContainerized.INSIDE_A_CONTAINER);
- }
-
-
- private static void testPrintContainerInfo() throws Exception {
- Common.logNewTestCase("Test print_container_info()");
-
- DockerRunOptions opts = Common.newOpts(imageName, "PrintContainerInfo");
- Common.addWhiteBoxOpts(opts);
-
- checkContainerInfo(Common.run(opts));
- }
-
-
- private static void checkContainerInfo(OutputAnalyzer out) throws Exception {
- String[] expectedToContain = new String[] {
- "cpuset.cpus",
- "cpuset.mems",
- "CPU Shares",
- "CPU Quota",
- "CPU Period",
- "OSContainer::active_processor_count",
- "Memory Limit",
- "Memory Soft Limit",
- "Memory Usage",
- "Maximum Memory Usage",
- "memory_max_usage_in_bytes"
- };
-
- for (String s : expectedToContain) {
- out.shouldContain(s);
- }
- }
-
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/testlibrary/ClassWithManyMethodsClassLoader.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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.DataInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+/**
+ * A factory that generates a class with many methods.
+ */
+public class ClassWithManyMethodsClassLoader extends ClassLoader {
+ /**
+ * Used to enable/disable keeping the class files and java sources for
+ * the generated classes.
+ */
+ private static boolean deleteFiles = Boolean.parseBoolean(
+ System.getProperty("ClassWithManyMethodsClassLoader.deleteFiles", "true"));
+
+ private JavaCompiler javac;
+
+ public ClassWithManyMethodsClassLoader() {
+ javac = ToolProvider.getSystemJavaCompiler();
+ }
+
+ private String generateSource(String className, String methodPrefix, int methodCount) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("public class ")
+ .append(className)
+ .append("{\n");
+
+ for (int i = 0; i < methodCount; i++) {
+ sb.append("public void ")
+ .append(methodPrefix)
+ .append(i)
+ .append("() {}\n");
+ }
+
+ sb.append("\n}");
+
+ return sb.toString();
+ }
+
+ private byte[] generateClassBytes(String className, String methodPrefix, int methodCount) throws IOException {
+ String src = generateSource(className, methodPrefix, methodCount);
+ File file = new File(className + ".java");
+ try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
+ pw.append(src);
+ pw.flush();
+ }
+ ByteArrayOutputStream err = new ByteArrayOutputStream();
+ int exitcode = javac.run(null, null, err, file.getCanonicalPath());
+ if (exitcode != 0) {
+ // Print Error
+ System.err.print(err);
+ if (err.toString().contains("java.lang.OutOfMemoryError: Java heap space")) {
+ throw new OutOfMemoryError("javac failed with resources exhausted");
+ } else {
+ throw new RuntimeException("javac failure when compiling: " +
+ file.getCanonicalPath());
+ }
+ } else {
+ if (deleteFiles) {
+ file.delete();
+ }
+ }
+
+ File classFile = new File(className + ".class");
+ byte[] bytes;
+ try (DataInputStream dis = new DataInputStream(new FileInputStream(classFile))) {
+ bytes = new byte[dis.available()];
+ dis.readFully(bytes);
+ }
+ if (deleteFiles) {
+ classFile.delete();
+ }
+
+ return bytes;
+ }
+
+ public Class<?> create(String className, String methodPrefix, int methodCount) throws IOException {
+ byte[] bytes = generateClassBytes(className, methodPrefix, methodCount);
+ return defineClass(className, bytes, 0, bytes.length);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/serviceability/jvmti/GenerateEvents/MyPackage/GenerateEventsTest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8222072
+ * @summary Send CompiledMethodLoad events only to the environment requested it with GenerateEvents
+ * @compile GenerateEventsTest.java
+ * @run main/othervm/native -agentlib:GenerateEvents1 -agentlib:GenerateEvents2 MyPackage.GenerateEventsTest
+ */
+
+package MyPackage;
+
+public class GenerateEventsTest {
+ static native void agent1GenerateEvents();
+ static native void agent2SetThread(Thread thread);
+ static native boolean agent1FailStatus();
+ static native boolean agent2FailStatus();
+
+ public static void main(String[] args) {
+ agent2SetThread(Thread.currentThread());
+ agent1GenerateEvents(); // Re-generate CompiledMethodLoad events
+ if (agent1FailStatus()|| agent2FailStatus()) {
+ throw new RuntimeException("GenerateEventsTest failed!");
+ }
+ System.out.println("GenerateEventsTest passed!");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/serviceability/jvmti/GenerateEvents/libGenerateEvents1.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 <string.h>
+#include "jvmti.h"
+
+extern "C" {
+
+#define AGENT_NAME "agent1"
+
+static JavaVM *java_vm = NULL;
+static jthread exp_thread = NULL;
+static jvmtiEnv *jvmti1 = NULL;
+static jint agent1_event_count = 0;
+static bool fail_status = false;
+
+static void
+check_jvmti_status(JNIEnv* env, jvmtiError err, const char* msg) {
+ if (err != JVMTI_ERROR_NONE) {
+ printf("check_jvmti_status: JVMTI function returned error: %d\n", err);
+ fail_status = true;
+ env->FatalError(msg);
+ }
+}
+
+static void JNICALL
+CompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method,
+ jint code_size, const void* code_addr,
+ jint map_length, const jvmtiAddrLocationMap* map,
+ const void* compile_info) {
+ JNIEnv* env = NULL;
+ jthread thread = NULL;
+ char* name = NULL;
+ char* sign = NULL;
+ jvmtiError err;
+
+ // Posted on JavaThread's, so it is legal to obtain JNIEnv*
+ if (java_vm->GetEnv((void **) (&env), JNI_VERSION_9) != JNI_OK) {
+ printf("CompiledMethodLoad: failed to obtain JNIEnv*\n");
+ fail_status = true;
+ return;
+ }
+
+ jvmti->GetCurrentThread(&thread);
+ if (!env->IsSameObject(thread, exp_thread)) {
+ return; // skip events from unexpected threads
+ }
+ agent1_event_count++;
+
+ err = jvmti->GetMethodName(method, &name, &sign, NULL);
+ check_jvmti_status(env, err, "CompiledMethodLoad: Error in JVMTI GetMethodName");
+
+ printf("%s: CompiledMethodLoad: %s%s\n", AGENT_NAME, name, sign);
+ fflush(0);
+}
+
+JNIEXPORT jint JNICALL
+Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
+ jvmtiEventCallbacks callbacks;
+ jvmtiCapabilities caps;
+ jvmtiError err;
+
+ java_vm = jvm;
+ if (jvm->GetEnv((void **) (&jvmti1), JVMTI_VERSION) != JNI_OK) {
+ printf("Agent_OnLoad: Error in GetEnv in obtaining jvmtiEnv*\n");
+ fail_status = true;
+ return JNI_ERR;
+ }
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.CompiledMethodLoad = &CompiledMethodLoad;
+
+ err = jvmti1->SetEventCallbacks(&callbacks, sizeof(jvmtiEventCallbacks));
+ if (err != JVMTI_ERROR_NONE) {
+ printf("Agent_OnLoad: Error in JVMTI SetEventCallbacks: %d\n", err);
+ fail_status = true;
+ return JNI_ERR;
+ }
+
+ memset(&caps, 0, sizeof(caps));
+ caps.can_generate_compiled_method_load_events = 1;
+
+ err = jvmti1->AddCapabilities(&caps);
+ if (err != JVMTI_ERROR_NONE) {
+ printf("Agent_OnLoad: Error in JVMTI AddCapabilities: %d\n", err);
+ fail_status = true;
+ return JNI_ERR;
+ }
+ return JNI_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_MyPackage_GenerateEventsTest_agent1GenerateEvents(JNIEnv *env, jclass cls) {
+ jthread thread = NULL;
+ jvmtiError err;
+
+ err = jvmti1->GetCurrentThread(&thread);
+ check_jvmti_status(env, err, "generateEvents1: Error in JVMTI GetCurrentThread");
+
+ exp_thread = (jthread)env->NewGlobalRef(thread);
+
+ err = jvmti1->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+ check_jvmti_status(env, err, "generateEvents1: Error in JVMTI SetEventNotificationMode: JVMTI_ENABLE");
+
+ err = jvmti1->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD);
+ check_jvmti_status(env, err, "generateEvents1: Error in JVMTI GenerateEvents");
+
+ err = jvmti1->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+ check_jvmti_status(env, err, "generateEvents1: Error in JVMTI SetEventNotificationMode: JVMTI_DISABLE");
+}
+
+JNIEXPORT jboolean JNICALL
+Java_MyPackage_GenerateEventsTest_agent1FailStatus(JNIEnv *env, jclass cls) {
+ return fail_status;
+}
+
+} // extern "C"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/serviceability/jvmti/GenerateEvents/libGenerateEvents2.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 <string.h>
+#include "jvmti.h"
+
+extern "C" {
+
+#define AGENT_NAME "agent2"
+
+static JavaVM *java_vm = NULL;
+static jthread exp_thread = NULL;
+static jvmtiEnv *jvmti2 = NULL;
+static jint agent2_event_count = 0;
+static bool fail_status = false;
+
+static void
+check_jvmti_status(JNIEnv* env, jvmtiError err, const char* msg) {
+ if (err != JVMTI_ERROR_NONE) {
+ printf("check_jvmti_status: JVMTI function returned error: %d\n", err);
+ fail_status = true;
+ env->FatalError(msg);
+ }
+}
+
+static void JNICALL
+CompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method,
+ jint code_size, const void* code_addr,
+ jint map_length, const jvmtiAddrLocationMap* map,
+ const void* compile_info) {
+ JNIEnv* env = NULL;
+ jthread thread = NULL;
+ char* name = NULL;
+ char* sign = NULL;
+ jvmtiError err;
+
+ // Posted on JavaThread's, so it is legal to obtain JNIEnv*
+ if (java_vm->GetEnv((void **) (&env), JNI_VERSION_9) != JNI_OK) {
+ fail_status = true;
+ return;
+ }
+
+ err = jvmti->GetCurrentThread(&thread);
+ check_jvmti_status(env, err, "CompiledMethodLoad: Error in JVMTI GetCurrentThread");
+ if (!env->IsSameObject(thread, exp_thread)) {
+ return; // skip events from unexpected threads
+ }
+ agent2_event_count++;
+
+ err = jvmti->GetMethodName(method, &name, &sign, NULL);
+ check_jvmti_status(env, err, "CompiledMethodLoad: Error in JVMTI GetMethodName");
+
+ printf("%s: CompiledMethodLoad: %s%s\n", AGENT_NAME, name, sign);
+ fflush(0);
+}
+
+JNIEXPORT jint JNICALL
+Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
+ jvmtiEventCallbacks callbacks;
+ jvmtiCapabilities caps;
+ jvmtiError err;
+
+ java_vm = jvm;
+ if (jvm->GetEnv((void **) (&jvmti2), JVMTI_VERSION_9) != JNI_OK) {
+ return JNI_ERR;
+ }
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.CompiledMethodLoad = &CompiledMethodLoad;
+
+ err = jvmti2->SetEventCallbacks(&callbacks, sizeof(jvmtiEventCallbacks));
+ if (err != JVMTI_ERROR_NONE) {
+ printf("Agent_OnLoad: Error in JVMTI SetEventCallbacks: %d\n", err);
+ fail_status = true;
+ return JNI_ERR;
+ }
+
+ memset(&caps, 0, sizeof(caps));
+ caps.can_generate_compiled_method_load_events = 1;
+
+ err = jvmti2->AddCapabilities(&caps);
+ if (err != JVMTI_ERROR_NONE) {
+ printf("Agent_OnLoad: Error in JVMTI AddCapabilities: %d\n", err);
+ fail_status = true;
+ return JNI_ERR;
+ }
+ return JNI_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_MyPackage_GenerateEventsTest_agent2SetThread(JNIEnv *env, jclass cls, jthread thread) {
+ jvmtiError err;
+
+ exp_thread = (jthread)env->NewGlobalRef(thread);
+
+ err = jvmti2->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+ check_jvmti_status(env, err, "setThread2: Error in JVMTI SetEventNotificationMode: JVMTI_ENABLE");
+}
+
+JNIEXPORT jboolean JNICALL
+Java_MyPackage_GenerateEventsTest_agent2FailStatus(JNIEnv *env, jclass cls) {
+ jvmtiError err;
+
+ err = jvmti2->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
+ check_jvmti_status(env, err, "check2: Error in JVMTI SetEventNotificationMode: JVMTI_DISABLE");
+
+ printf("\n");
+ if (agent2_event_count == 0) {
+ printf("check2: Zero events in agent2 as expected\n");
+ } else {
+ fail_status = true;
+ printf("check2: Unexpected non-zero event count in agent2: %d\n", agent2_event_count);
+ }
+ printf("\n");
+ fflush(0);
+
+ return fail_status;
+}
+
+} // extern "C"
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SingleStep/singlestep001/singlestep001.cpp Sat Apr 13 07:22:55 2019 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SingleStep/singlestep001/singlestep001.cpp Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -57,7 +57,7 @@
static jvmtiEnv *jvmti = NULL;
static jvmtiEventCallbacks callbacks;
-static int vm_started = 0;
+static volatile int callbacksEnabled = NSK_FALSE;
static jrawMonitorID agent_lock;
static void setBP(jvmtiEnv *jvmti_env, JNIEnv *env, jclass klass) {
@@ -77,7 +77,7 @@
jvmti->RawMonitorEnter(agent_lock);
- if (vm_started) {
+ if (callbacksEnabled) {
if (!NSK_JVMTI_VERIFY(jvmti_env->GetClassSignature(klass, &sig, &generic)))
env->FatalError("failed to obtain a class signature\n");
@@ -99,6 +99,13 @@
jclass klass;
char *sig, *generic;
+ jvmti->RawMonitorEnter(agent_lock);
+
+ if (!callbacksEnabled) {
+ jvmti->RawMonitorExit(agent_lock);
+ return;
+ }
+
NSK_DISPLAY0("Breakpoint event received\n");
if (!NSK_JVMTI_VERIFY(jvmti_env->GetMethodDeclaringClass(method, &klass)))
NSK_COMPLAIN0("TEST FAILURE: unable to get method declaring class\n\n");
@@ -118,6 +125,7 @@
NSK_COMPLAIN1("TEST FAILURE: unexpected breakpoint event in method of class \"%s\"\n\n",
sig);
}
+ jvmti->RawMonitorExit(agent_lock);
}
void JNICALL
@@ -197,7 +205,16 @@
VMStart(jvmtiEnv *jvmti_env, JNIEnv* jni_env) {
jvmti->RawMonitorEnter(agent_lock);
- vm_started = 1;
+ callbacksEnabled = NSK_TRUE;
+
+ jvmti->RawMonitorExit(agent_lock);
+}
+
+void JNICALL
+VMDeath(jvmtiEnv *jvmti_env, JNIEnv* jni_env) {
+ jvmti->RawMonitorEnter(agent_lock);
+
+ callbacksEnabled = NSK_FALSE;
jvmti->RawMonitorExit(agent_lock);
}
@@ -261,12 +278,15 @@
callbacks.Breakpoint = &Breakpoint;
callbacks.SingleStep = &SingleStep;
callbacks.VMStart = &VMStart;
+ callbacks.VMDeath = &VMDeath;
if (!NSK_JVMTI_VERIFY(jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks))))
return JNI_ERR;
NSK_DISPLAY0("setting event callbacks done\nenabling JVMTI events ...\n");
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_START, NULL)))
return JNI_ERR;
+ if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL)))
+ return JNI_ERR;
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL)))
return JNI_ERR;
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_BREAKPOINT, NULL)))
--- a/test/jdk/ProblemList.txt Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/ProblemList.txt Sat Apr 13 07:23:18 2019 +0100
@@ -158,12 +158,39 @@
java/awt/Mixing/AWT_Mixing/MixingPanelsResizing.java 8049405 generic-all
java/awt/Mixing/AWT_Mixing/JComboBoxOverlapping.java 8049405 macosx-all
java/awt/Mixing/AWT_Mixing/JPopupMenuOverlapping.java 8049405 macosx-all
+java/awt/Mixing/AWT_Mixing/JButtonInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JButtonOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JColorChooserOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JEditorPaneInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JEditorPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JLabelInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JLabelOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JListInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JListOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JPanelInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JPanelOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JProgressBarInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JProgressBarOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JScrollBarInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JScrollBarOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JSliderInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JSliderOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JSpinnerInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JSpinnerOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTableInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTableOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTextAreaInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTextAreaOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTextFieldInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JTextFieldOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JToggleButtonInGlassPaneOverlapping.java 8158801 windows-all
+java/awt/Mixing/AWT_Mixing/JToggleButtonOverlapping.java 8158801 windows-all
java/awt/Mixing/NonOpaqueInternalFrame.java 7124549 macosx-all
java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java 6829264 generic-all
java/awt/datatransfer/DragImage/MultiResolutionDragImageTest.java 8080982 generic-all
java/awt/datatransfer/SystemFlavorMap/AddFlavorTest.java 8079268 linux-all
java/awt/Toolkit/ScreenInsetsTest/ScreenInsetsTest.java 6829250 windows-all
-java/awt/Toolkit/RealSync/Test.java 6849383 macosx-all
+java/awt/Toolkit/RealSync/Test.java 6849383 macosx-all,linux-all
java/awt/LightweightComponent/LightweightEventTest/LightweightEventTest.java 8159252 windows-all
java/awt/EventDispatchThread/HandleExceptionOnEDT/HandleExceptionOnEDT.java 8203047 macosx-all
java/awt/EventDispatchThread/LoopRobustness/LoopRobustness.java 8073636 macosx-all
@@ -212,6 +239,7 @@
java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucent.java 8078999 macosx-all
java/awt/Window/ShapedAndTranslucentWindows/ShapedTranslucentWindowClick.java 8013450 macosx-all
java/awt/Window/ShapedAndTranslucentWindows/StaticallyShaped.java 8165218 macosx-all,linux-all
+java/awt/Window/ShapedAndTranslucentWindows/TranslucentChoice.java 8221901 linux-all
java/awt/Window/AlwaysOnTop/AutoTestOnTop.java 6847593 macosx-all
java/awt/Window/GrabSequence/GrabSequence.java 6848409 macosx-all,linux-all
java/awt/Window/LocationAtScreenCorner/LocationAtScreenCorner.java 8203371 linux-all,solaris-all
@@ -242,6 +270,7 @@
sun/java2d/SunGraphics2D/SimplePrimQuality.java 6992007 generic-all
sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java 8196185 generic-all
sun/java2d/pipe/InterpolationQualityTest.java 8171303 windows-all,linux-all,macosx-all
+sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh 8221451 linux-all
java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469 windows-all
java/awt/Graphics2D/DrawString/DrawRotatedStringUsingRotatedFont.java 8197796 generic-all
java/awt/TextArea/TextAreaScrolling/TextAreaScrolling.java 8196300 windows-all
@@ -249,6 +278,7 @@
java/awt/print/PrinterJob/GlyphPositions.java 7003378 generic-all
java/awt/Choice/PopupPosTest/PopupPosTest.java 8197811 windows-all
java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java 7100044 macosx-all,linux-all
+java/awt/Choice/ChoiceKeyEventReaction/ChoiceKeyEventReaction.java 8214469 macosx-all
java/awt/Component/CreateImage/CreateImage.java 8198334 windows-all
java/awt/Component/GetScreenLocTest/GetScreenLocTest.java 4753654 generic-all
java/awt/Clipboard/HTMLTransferTest/HTMLTransferTest.java 8017454 macosx-all
@@ -395,6 +425,7 @@
java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersUnitTest_Standard.java 7124407 macosx-all
java/awt/Mouse/RemovedComponentMouseListener/RemovedComponentMouseListener.java 8157170 macosx-all
java/awt/Modal/ToFront/DialogToFrontModeless1Test.java 8213530 linux-all
+java/awt/Modal/ToFront/DialogToFrontNonModalTest.java 8221899 linux-all
java/awt/Modal/ToBack/ToBackAppModal1Test.java 8196441 linux-all,macosx-all
java/awt/Modal/ToBack/ToBackAppModal2Test.java 8196441 linux-all,macosx-all
java/awt/Modal/ToBack/ToBackAppModal3Test.java 8196441 linux-all,macosx-all
@@ -702,6 +733,7 @@
javax/sound/sampled/Mixers/DisabledAssertionCrash.java 7067310 generic-all
javax/sound/midi/Sequencer/Recording.java 8167580 linux-all,solaris-all
+javax/sound/midi/Sequencer/MetaCallback.java 8178698 linux-all,solaris-all
############################################################################
@@ -813,6 +845,8 @@
javax/swing/JTable/6263446/bug6263446.java 8169959 macosx-all
javax/swing/JTree/6263446/bug6263446.java 8213125 macosx-all
javax/swing/JTree/8003400/Test8003400.java 8197560 macosx-all,linux-all
+javax/swing/RepaintManager/IconifyTest/IconifyTest.java 8221903 linux-all
+javax/swing/JRadioButton/FocusTraversal/FocusTraversal.java 8221902 linux-all
############################################################################
--- a/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/java/awt/print/RemotePrinterStatusRefresh/RemotePrinterStatusRefresh.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -21,244 +21,480 @@
* questions.
*/
-/**
+/*
* @test
- * @bug 8153732 8212202
+ * @bug 8153732 8212202 8221263 8221412
* @requires (os.family == "Windows")
* @summary Windows remote printer changes do not reflect in lookupPrintServices()
- * @ignore Requires a new network printer installation\removal
* @run main/manual RemotePrinterStatusRefresh
*/
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.GridLayout;
import java.awt.event.ActionEvent;
-import java.awt.print.PageFormat;
-import java.awt.print.Paper;
-import java.awt.print.PrinterException;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
+import javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
+import javax.swing.JList;
import javax.swing.JPanel;
+import javax.swing.JScrollPane;
import javax.swing.JTextArea;
+import javax.swing.JTextField;
import javax.swing.SwingUtilities;
-import java.awt.print.PrinterJob;
-import javax.print.PrintService;
+import javax.swing.Timer;
+
+import static javax.swing.BorderFactory.createTitledBorder;
+
+public class RemotePrinterStatusRefresh extends WindowAdapter {
+
+ private static final long refreshTime = getRefreshTime();
+
+ private static final long TIMEOUT = refreshTime * 4 + 60;
+
-public class RemotePrinterStatusRefresh
-{
- private static TestUI test = null;
- public static void main(String args[]) throws Exception {
- final CountDownLatch latch = new CountDownLatch(1);
+ private static final CountDownLatch latch = new CountDownLatch(1);
+ private static volatile RemotePrinterStatusRefresh test;
+
+ private volatile boolean testResult;
+ private volatile boolean testTimedOut;
+
+ private final JFrame frame;
- // Test UI creation
- test = new TestUI(latch);
+ private JButton refreshButton;
+ private JButton passButton;
+ private JButton failButton;
+
+ private final ServiceItemListModel beforeList;
+ private final ServiceItemListModel afterList;
+
+ private JTextField nextRefresh;
+ private JTextField timeLeft;
+
+ private final Timer timer;
+ private final long startTime;
+
- SwingUtilities.invokeAndWait(new Runnable() {
- @Override
- public void run() {
- try {
- test.createUI();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
+ private static class ServiceItem {
+ private enum State {
+ REMOVED, UNCHANGED, ADDED
+ }
+
+ final String name;
+ State state;
+
+ private ServiceItem(final String name) {
+ this.name = name;
+ state = State.UNCHANGED;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
- // RemotePrinterStatusRefresh creation
- RemotePrinterStatusRefresh RemotePrinterStatusRefresh = new RemotePrinterStatusRefresh();
- SwingUtilities.invokeAndWait(() -> {
- collectPrintersList(test.resultsTextArea, true);
- });
+ @Override
+ public boolean equals(Object obj) {
+ return (obj instanceof ServiceItem)
+ && ((ServiceItem) obj).name.equals(name);
+ }
- // 8 min = 480000 msec
- if(waitForFlag(480000)) {
- SwingUtilities.invokeAndWait(() -> {
- collectPrintersList(test.resultsTextArea, false);
- });
- } else {
- dispose();
- throw new RuntimeException("No new network printer got added/removed!! Test timed out!!");
+ @Override
+ public int hashCode() {
+ return name.hashCode();
+ }
+ }
+
+ private static class ServiceItemListModel extends AbstractListModel<ServiceItem> {
+ private final List<ServiceItem> list;
+
+ private ServiceItemListModel(List<ServiceItem> list) {
+ this.list = list;
+ }
+
+ @Override
+ public int getSize() {
+ return list.size();
}
- boolean status = latch.await(1, TimeUnit.MINUTES);
- if (!status) {
- dispose();
- throw new RuntimeException("Test timed out.");
+ @Override
+ public ServiceItem getElementAt(int index) {
+ return list.get(index);
+ }
+
+ private void refreshList(List<ServiceItem> newList) {
+ list.clear();
+ list.addAll(newList);
+ fireChanged();
}
- if (test.testResult == false) {
- dispose();
- throw new RuntimeException("Test Failed.");
+ private void fireChanged() {
+ fireContentsChanged(this, 0, list.size() - 1);
}
+ }
- dispose();
+ private static class ServiceItemListRenderer extends DefaultListCellRenderer {
+ @Override
+ public Component getListCellRendererComponent(JList<?> list,
+ Object value,
+ int index,
+ boolean isSelected,
+ boolean cellHasFocus) {
+ Component component =
+ super.getListCellRendererComponent(list, value, index,
+ isSelected, cellHasFocus);
+ switch (((ServiceItem) value).state) {
+ case REMOVED:
+ component.setBackground(Color.RED);
+ component.setForeground(Color.WHITE);
+ break;
+ case ADDED:
+ component.setBackground(Color.GREEN);
+ component.setForeground(Color.BLACK);
+ break;
+ case UNCHANGED:
+ default:
+ break;
+ }
+ return component;
+ }
}
- public static void dispose() throws Exception {
- SwingUtilities.invokeAndWait(() -> {
- test.disposeUI();
- });
+ private static final String INSTRUCTIONS_TEXT =
+ "Please follow the steps for this manual test:\n"
+ + "Step 0: \"Before\" list is populated with currently "
+ + "configured printers.\n"
+ + "Step 1: Add or Remove a network printer using "
+ + "Windows Control Panel.\n"
+ + "Step 2: Wait for 4 minutes after adding or removing.\n"
+ + " \"Next printer refresh in\" gives you a "
+ + "rough estimation on when update will happen.\n"
+ + "Step 3: Click Refresh."
+ + "\"After\" list is populated with updated list "
+ + "of printers.\n"
+ + "Step 4: Compare the list of printers in \"Before\" and "
+ + "\"After\" lists.\n"
+ + " Added printers are highlighted with "
+ + "green color, removed ones \u2014 with "
+ + "red color.\n"
+ + "Step 5: Click Pass if the list of printers is correctly "
+ + "updated.\n"
+ + "Step 6: If the list is not updated, wait for another "
+ + "4 minutes, and then click Refresh again.\n"
+ + "Step 7: If the list does not update, click Fail.\n"
+ + "\n"
+ + "You have to click Refresh to enable Pass and Fail buttons. "
+ + "If no button is pressed,\n"
+ + "the test will time out. "
+ + "Closing the window also fails the test.";
+
+ public static void main(String[] args) throws Exception {
+ SwingUtilities.invokeAndWait(RemotePrinterStatusRefresh::createUI);
+
+ latch.await();
+ if (!test.testResult) {
+ throw new RuntimeException("Test failed"
+ + (test.testTimedOut ? " because of time out" : ""));
+ }
}
- public static boolean waitForFlag (long maxTimeoutInMsec) throws Exception {
- while(!test.isAdded && maxTimeoutInMsec > 0) {
- maxTimeoutInMsec -= 100;
- Thread.sleep(100);
- }
-
- if(maxTimeoutInMsec <= 0) {
- return false;
- } else {
- return true;
+ private static long getRefreshTime() {
+ String refreshTime =
+ System.getProperty("sun.java2d.print.minRefreshTime", "240");
+ try {
+ long value = Long.parseLong(refreshTime);
+ return value < 240L ? 240L : value;
+ } catch (NumberFormatException e) {
+ return 240L;
}
}
- private static void collectPrintersList(JTextArea textArea, boolean before) {
- if(before) {
- System.out.println("List of printers(before): ");
- textArea.setText("List of printers(before): \n");
- for (PrintService printServiceBefore : PrinterJob.lookupPrintServices()) {
- System.out.println(printServiceBefore);
- textArea.append(printServiceBefore.toString());
- textArea.append("\n");
- }
- } else {
- textArea.append("\n");
- System.out.println("List of printers(after): ");
- textArea.append("List of printers(after): \n");
- for (PrintService printServiceAfter : PrinterJob.lookupPrintServices()) {
- System.out.println(printServiceAfter);
- textArea.append(printServiceAfter.toString());
- textArea.append("\n");
- }
- }
+ private static void createUI() {
+ test = new RemotePrinterStatusRefresh();
}
-}
+
+ private RemotePrinterStatusRefresh() {
+ frame = new JFrame("RemotePrinterStatusRefresh");
+ frame.addWindowListener(this);
+
+
+ JPanel northPanel = new JPanel(new BorderLayout());
+ northPanel.add(createInfoPanel(), BorderLayout.NORTH);
+ northPanel.add(createInstructionsPanel(), BorderLayout.SOUTH);
+
+
+ beforeList = new ServiceItemListModel(
+ Collections.unmodifiableList(collectPrinterList()));
+ afterList = new ServiceItemListModel(new ArrayList<>());
+ logList("Before:", beforeList.list);
+
+ JPanel listPanel = new JPanel(new GridLayout(1, 2));
+ listPanel.setBorder(createTitledBorder("Print Services"));
+ listPanel.add(createListPanel(beforeList, "Before:", 'b'));
+ listPanel.add(createListPanel(afterList, "After:", 'a'));
+
+
+ JPanel mainPanel = new JPanel(new BorderLayout());
+ mainPanel.add(northPanel, BorderLayout.NORTH);
+ mainPanel.add(listPanel, BorderLayout.CENTER);
+ mainPanel.add(createButtonPanel(), BorderLayout.SOUTH);
+
+
+ frame.add(mainPanel);
+ frame.pack();
+ refreshButton.requestFocusInWindow();
+ frame.setVisible(true);
+
+
+ timer = new Timer(1000, this::updateTimeLeft);
+ timer.start();
+ startTime = System.currentTimeMillis();
+ updateTimeLeft(null);
+ }
+
+ private JPanel createInfoPanel() {
+ JLabel javaLabel = new JLabel("Java version:");
+ JTextField javaVersion =
+ new JTextField(System.getProperty("java.runtime.version"));
+ javaVersion.setEditable(false);
+ javaLabel.setLabelFor(javaVersion);
-class TestUI {
- private static JFrame mainFrame;
- private static JPanel mainControlPanel;
+ JLabel refreshTimeLabel = new JLabel("Refresh interval:");
+ long minutes = refreshTime / 60;
+ long seconds = refreshTime % 60;
+ String interval = String.format("%1$d seconds%2$s",
+ refreshTime,
+ minutes > 0
+ ? String.format(" (%1$d %2$s%3$s)",
+ minutes,
+ minutes > 1 ? "minutes" : "minute",
+ seconds > 0
+ ? String.format(" %1$d %2$s",
+ seconds,
+ seconds > 1 ? "seconds" : "second")
+ : "")
+ : ""
+ );
+ JTextField refreshInterval = new JTextField(interval);
+ refreshInterval.setEditable(false);
+ refreshTimeLabel.setLabelFor(refreshInterval);
- private static JTextArea instructionTextArea;
+ JLabel nextRefreshLabel = new JLabel("Next printer refresh in:");
+ nextRefresh = new JTextField();
+ nextRefresh.setEditable(false);
+ nextRefreshLabel.setLabelFor(nextRefresh);
- private static JPanel resultButtonPanel;
- private static JButton passButton;
- private static JButton failButton;
- private static JButton addedButton;
+ JLabel timeoutLabel = new JLabel("Time left:");
+ timeLeft = new JTextField();
+ timeLeft.setEditable(false);
+ timeoutLabel.setLabelFor(timeLeft);
- private static JPanel testPanel;
- private static JButton testButton;
- private static JLabel buttonPressCountLabel;
+ JPanel infoPanel = new JPanel();
+ GroupLayout layout = new GroupLayout(infoPanel);
+ infoPanel.setLayout(layout);
+ infoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
+ layout.setAutoCreateGaps(true);
+ layout.setHorizontalGroup(
+ layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
+ .addComponent(javaLabel)
+ .addComponent(refreshTimeLabel)
+ .addComponent(nextRefreshLabel)
+ .addComponent(timeoutLabel)
+ )
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, true)
+ .addComponent(javaVersion)
+ .addComponent(refreshInterval)
+ .addComponent(nextRefresh)
+ .addComponent(timeLeft)
+ )
+ );
+ layout.setVerticalGroup(
+ layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
+ .addComponent(javaLabel)
+ .addComponent(javaVersion)
+ )
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
+ .addComponent(refreshTimeLabel)
+ .addComponent(refreshInterval))
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
+ .addComponent(nextRefreshLabel)
+ .addComponent(nextRefresh))
+ .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
+ .addComponent(timeoutLabel)
+ .addComponent(timeLeft))
+ );
+ return infoPanel;
+ }
- private static GridBagLayout layout;
- private final CountDownLatch latch;
- public boolean testResult = false;
- public volatile Boolean isAdded = false;
- public static JTextArea resultsTextArea;
-
- public TestUI(CountDownLatch latch) throws Exception {
- this.latch = latch;
+ private JPanel createInstructionsPanel() {
+ JPanel instructionsPanel = new JPanel(new BorderLayout());
+ JTextArea instructionText = new JTextArea(INSTRUCTIONS_TEXT);
+ instructionText.setEditable(false);
+ instructionsPanel.setBorder(createTitledBorder("Test Instructions"));
+ instructionsPanel.add(new JScrollPane(instructionText));
+ return instructionsPanel;
}
- public final void createUI() {
- mainFrame = new JFrame("RemotePrinterStatusRefresh");
- layout = new GridBagLayout();
- mainControlPanel = new JPanel(layout);
- resultButtonPanel = new JPanel(layout);
- testPanel = new JPanel(layout);
- GridBagConstraints gbc = new GridBagConstraints();
-
- // Create Test instructions
- String instructions
- = "This test displays the current list of printers(before) attached to \n"
- + "this computer in the results panel.\n\n"
- + "Please follow the below steps for this manual test\n"
- + "--------------------------------------------------------------------\n"
- + "Step 1: Add/Remove a new network printer and Wait for 4 minutes after adding/removing\n"
- + "Step 2: Then click on 'Printer Added/Removed' button\n"
- + "Step 2: Once the new network printer is added/removed, see if it is \n"
- + " the same as displayed/not displayed in the results panel.\n"
- + "Step 3: If displayed/not displayed, then click 'Pass' else click on 'Fail' button";
-
- instructionTextArea = new JTextArea();
- instructionTextArea.setText(instructions);
- instructionTextArea.setEditable(false);
- instructionTextArea.setBorder(BorderFactory.
- createTitledBorder("Test Instructions"));
+ private JPanel createListPanel(final ServiceItemListModel model,
+ final String title,
+ final char mnemonic) {
+ JPanel panel = new JPanel();
+ panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
+ JList<ServiceItem> list = new JList<>(model);
+ list.setCellRenderer(new ServiceItemListRenderer());
- gbc.gridx = 0;
- gbc.gridy = 0;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- mainControlPanel.add(instructionTextArea, gbc);
-
- gbc.gridx = 0;
- gbc.gridy = 1;
- testPanel.add(Box.createVerticalStrut(50));
- mainControlPanel.add(testPanel);
+ JLabel label = new JLabel(title);
+ label.setLabelFor(list);
+ label.setDisplayedMnemonic(mnemonic);
+ JPanel labelPanel = new JPanel();
+ labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
+ labelPanel.add(label, BorderLayout.EAST);
+ labelPanel.add(Box.createHorizontalGlue());
- addedButton = new JButton("Printer Added/Removed");
- addedButton.setActionCommand("Added");
- addedButton.addActionListener((ActionEvent e) -> {
- System.out.println("Added Button pressed!");
- isAdded = true;
- });
+ panel.add(labelPanel);
+ panel.add(new JScrollPane(list));
+ return panel;
+ }
- // Create resultButtonPanel with Pass, Fail buttons
+ private JPanel createButtonPanel() {
+ refreshButton = new JButton("Refresh");
+ refreshButton.addActionListener(this::refresh);
+
passButton = new JButton("Pass");
- passButton.setActionCommand("Pass");
- passButton.addActionListener((ActionEvent e) -> {
- System.out.println("Pass Button pressed!");
- testResult = true;
- latch.countDown();
- disposeUI();
- });
+ passButton.addActionListener(this::pass);
+ passButton.setEnabled(false);
failButton = new JButton("Fail");
- failButton.setActionCommand("Fail");
- failButton.addActionListener((ActionEvent e) -> {
- System.out.println("Fail Button pressed!");
- testResult = false;
- latch.countDown();
- disposeUI();
- });
+ failButton.addActionListener(this::fail);
+ failButton.setEnabled(false);
- gbc.gridx = 0;
- gbc.gridy = 0;
- resultButtonPanel.add(addedButton, gbc);
-
- gbc.gridx = 1;
- gbc.gridy = 0;
- resultButtonPanel.add(passButton, gbc);
+ JPanel buttonPanel = new JPanel();
+ buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
+ buttonPanel.add(Box.createHorizontalGlue());
+ buttonPanel.add(refreshButton);
+ buttonPanel.add(passButton);
+ buttonPanel.add(failButton);
+ buttonPanel.add(Box.createHorizontalGlue());
+ return buttonPanel;
+ }
- gbc.gridx = 2;
- gbc.gridy = 0;
- resultButtonPanel.add(failButton, gbc);
-
- resultsTextArea = new JTextArea();
- resultsTextArea.setEditable(false);
- resultsTextArea.setBorder(BorderFactory.
- createTitledBorder("Results"));
+ private static List<ServiceItem> collectPrinterList() {
+ PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
+ List<ServiceItem> list = new ArrayList<>(printServices.length);
+ for (PrintService service : printServices) {
+ list.add(new ServiceItem(service.getName()));
+ }
+ return list;
+ }
- gbc.gridx = 0;
- gbc.gridy = 1;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- mainControlPanel.add(resultsTextArea, gbc);
-
- gbc.gridx = 0;
- gbc.gridy = 2;
- mainControlPanel.add(resultButtonPanel, gbc);
-
- mainFrame.add(mainControlPanel);
- mainFrame.pack();
- mainFrame.setVisible(true);
+ private static void logList(final String title, final List<ServiceItem> list) {
+ System.out.println(title);
+ for (ServiceItem item : list) {
+ System.out.println(item.name);
+ }
+ System.out.println();
}
- public void disposeUI() {
- mainFrame.dispose();
+ private static void compareLists(final ServiceItemListModel before, final ServiceItemListModel after) {
+ boolean beforeUpdated = false;
+ boolean afterUpdated = false;
+
+ for (ServiceItem item : before.list) {
+ if (!after.list.contains(item)) {
+ item.state = ServiceItem.State.REMOVED;
+ beforeUpdated = true;
+ } else if (item.state != ServiceItem.State.UNCHANGED) {
+ item.state = ServiceItem.State.UNCHANGED;
+ beforeUpdated = true;
+ }
+ }
+
+ for (ServiceItem item : after.list) {
+ if (!before.list.contains(item)) {
+ item.state = ServiceItem.State.ADDED;
+ afterUpdated = true;
+ } else if (item.state != ServiceItem.State.UNCHANGED) {
+ item.state = ServiceItem.State.UNCHANGED;
+ afterUpdated = true;
+ }
+ }
+
+ if (beforeUpdated) {
+ before.fireChanged();
+ }
+ if (afterUpdated) {
+ after.fireChanged();
+ }
+ }
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.out.println("The window closed");
+ disposeUI();
+ }
+
+ private void disposeUI() {
+ timer.stop();
+ latch.countDown();
+ frame.dispose();
}
+
+ @SuppressWarnings("unused")
+ private void refresh(ActionEvent e) {
+ System.out.println("Refresh button pressed");
+ afterList.refreshList(collectPrinterList());
+ compareLists(beforeList, afterList);
+ passButton.setEnabled(true);
+ failButton.setEnabled(true);
+ logList("After:", afterList.list);
+ }
+
+ @SuppressWarnings("unused")
+ private void pass(ActionEvent e) {
+ System.out.println("Pass button pressed");
+ testResult = true;
+ disposeUI();
+ }
+
+ @SuppressWarnings("unused")
+ private void fail(ActionEvent e) {
+ System.out.println("Fail button pressed");
+ testResult = false;
+ disposeUI();
+ }
+
+ @SuppressWarnings("unused")
+ private void updateTimeLeft(ActionEvent e) {
+ long elapsed = (System.currentTimeMillis() - startTime) / 1000;
+ long left = TIMEOUT - elapsed;
+ if (left < 0) {
+ testTimedOut = true;
+ disposeUI();
+ }
+ timeLeft.setText(formatTime(left));
+ nextRefresh.setText(formatTime(refreshTime - (elapsed % refreshTime)));
+ }
+
+ private static String formatTime(final long seconds) {
+ long minutes = seconds / 60;
+ return String.format("%d:%02d", minutes, seconds - minutes * 60);
+ }
+
}
--- a/test/jdk/java/lang/Math/DivModTests.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/java/lang/Math/DivModTests.java Sat Apr 13 07:23:18 2019 +0100
@@ -91,6 +91,10 @@
testIntFloorDivMod(Integer.MIN_VALUE, 3, -715827883, 1);
testIntFloorDivMod(Integer.MIN_VALUE + 1, 3, -715827883, 2);
testIntFloorDivMod(Integer.MIN_VALUE + 1, -1, Integer.MAX_VALUE, 0);
+ testIntFloorDivMod(Integer.MAX_VALUE, Integer.MAX_VALUE, 1, 0);
+ testIntFloorDivMod(Integer.MAX_VALUE, Integer.MIN_VALUE, -1, -1);
+ testIntFloorDivMod(Integer.MIN_VALUE, Integer.MIN_VALUE, 1, 0);
+ testIntFloorDivMod(Integer.MIN_VALUE, Integer.MAX_VALUE, -2, 2147483646);
// Special case of integer overflow
testIntFloorDivMod(Integer.MIN_VALUE, -1, Integer.MIN_VALUE, 0);
}
@@ -179,6 +183,10 @@
testLongFloorDivMod(Long.MIN_VALUE, 3L, Long.MIN_VALUE / 3L - 1L, 1L);
testLongFloorDivMod(Long.MIN_VALUE + 1L, 3L, Long.MIN_VALUE / 3L - 1L, 2L);
testLongFloorDivMod(Long.MIN_VALUE + 1, -1, Long.MAX_VALUE, 0L);
+ testLongFloorDivMod(Long.MAX_VALUE, Long.MAX_VALUE, 1L, 0L);
+ testLongFloorDivMod(Long.MAX_VALUE, Long.MIN_VALUE, -1L, -1L);
+ testLongFloorDivMod(Long.MIN_VALUE, Long.MIN_VALUE, 1L, 0L);
+ testLongFloorDivMod(Long.MIN_VALUE, Long.MAX_VALUE, -2L, 9223372036854775806L);
// Special case of integer overflow
testLongFloorDivMod(Long.MIN_VALUE, -1, Long.MIN_VALUE, 0L);
}
@@ -283,6 +291,10 @@
testLongIntFloorDivMod(Long.MIN_VALUE, 3, Long.MIN_VALUE / 3L - 1L, 1L);
testLongIntFloorDivMod(Long.MIN_VALUE + 1L, 3, Long.MIN_VALUE / 3L - 1L, 2L);
testLongIntFloorDivMod(Long.MIN_VALUE + 1, -1, Long.MAX_VALUE, 0L);
+ testLongIntFloorDivMod(Long.MAX_VALUE, Integer.MAX_VALUE, 4294967298L, 1);
+ testLongIntFloorDivMod(Long.MAX_VALUE, Integer.MIN_VALUE, -4294967296L, -1);
+ testLongIntFloorDivMod(Long.MIN_VALUE, Integer.MIN_VALUE, 4294967296L, 0);
+ testLongIntFloorDivMod(Long.MIN_VALUE, Integer.MAX_VALUE, -4294967299L, 2147483645);
// Special case of integer overflow
testLongIntFloorDivMod(Long.MIN_VALUE, -1, Long.MIN_VALUE, 0L);
}
--- a/test/jdk/java/lang/StringBuffer/CompactStringBuffer.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/java/lang/StringBuffer/CompactStringBuffer.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
/*
* @test
- * @bug 8077559
+ * @bug 8077559 8221430
* @summary Tests Compact String. This test is testing StringBuffer
* behavior related to Compact String.
* @run testng/othervm -XX:+CompactStrings CompactStringBuffer
@@ -440,6 +440,12 @@
"abcdefgh1.23456");
check(new StringBuffer().append(bmp).append(1.23456).toString(),
"\u4e00\u4e01\u4e02\u4e03\u4e04\u4e05\u4e06\u4e07\u4e081.23456");
+
+ ////////////////////////////////////////////////////////////////////
+ check(new StringBuffer((CharSequence)new StringBuffer(ascii)).toString(),
+ ascii);
+ check(new StringBuffer((CharSequence)new StringBuffer(asciiMixed)).toString(),
+ asciiMixed);
}
private void checkGetChars(StringBuffer sb, int srcBegin, int srcEnd,
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/security/Permissions/DeserializeInvalidPermissions.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8020637
+ * @summary Deserialize a serialized Permissions object with incorrect Class to
+ * Permission mappings
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.security.Permissions;
+import java.util.Base64;
+
+public class DeserializeInvalidPermissions {
+
+ private static final String BASE = System.getProperty("test.src", ".");
+
+ /**
+ * A base64 encoded serialized Permissions object. This contains two
+ * Permissions, SecurityPermission("foo") and FilePermission("bar", "read").
+ * However, the Hashtable mappings have been switched, such that
+ * FilePermission.class maps to BasicPermissionCollection (which contains
+ * the SecurityPermission) and SecurityPermission.class maps to
+ * FilePermissionCollection.
+ */
+ private static String INVALID_PERMISSIONS =
+ "rO0ABXNyABlqYXZhLnNlY3VyaXR5LlBlcm1pc3Npb25zQ21LTdLID1ADAAJMAA1hbGxQ" +
+ "ZXJtaXNzaW9udAAkTGphdmEvc2VjdXJpdHkvUGVybWlzc2lvbkNvbGxlY3Rpb247TAAF" +
+ "cGVybXN0ABVMamF2YS91dGlsL0hhc2h0YWJsZTt4cgAiamF2YS5zZWN1cml0eS5QZXJt" +
+ "aXNzaW9uQ29sbGVjdGlvbqKk2tZqGAkpAgABWgAIcmVhZE9ubHl4cABwc3IAE2phdmEu" +
+ "dXRpbC5IYXNodGFibGUTuw8lIUrkuAMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4" +
+ "cD9AAAAAAAADdwgAAAAEAAAAAnZyABZqYXZhLmlvLkZpbGVQZXJtaXNzaW9ubg+fk/TA" +
+ "qbsDAAFMAAdhY3Rpb25zdAASTGphdmEvbGFuZy9TdHJpbmc7eHIAGGphdmEuc2VjdXJp" +
+ "dHkuUGVybWlzc2lvbrHG4T8oV1F+AgABTAAEbmFtZXEAfgAIeHBzcgAnamF2YS5zZWN1" +
+ "cml0eS5CYXNpY1Blcm1pc3Npb25Db2xsZWN0aW9uCkKHBI3t48cDAANaAAthbGxfYWxs" +
+ "b3dlZEwACXBlcm1DbGFzc3QAEUxqYXZhL2xhbmcvQ2xhc3M7TAALcGVybWlzc2lvbnNx" +
+ "AH4AAnhxAH4AAwAAdnIAIGphdmEuc2VjdXJpdHkuU2VjdXJpdHlQZXJtaXNzaW9uSKpm" +
+ "PrGHHSYCAAB4cgAdamF2YS5zZWN1cml0eS5CYXNpY1Blcm1pc3Npb25XJQvcz06megIA" +
+ "AHhxAH4ACXNxAH4ABT9AAAAAAAABdwgAAAACAAAAAXQAA2Zvb3NxAH4ADnEAfgASeHhx" +
+ "AH4AEHNyACBqYXZhLmlvLkZpbGVQZXJtaXNzaW9uQ29sbGVjdGlvbh6SeX3UjlWpAwAB" +
+ "TAALcGVybWlzc2lvbnN0ABJMamF2YS91dGlsL1ZlY3Rvcjt4cQB+AAMAc3IAEGphdmEu" +
+ "dXRpbC5WZWN0b3LZl31bgDuvAQMAA0kAEWNhcGFjaXR5SW5jcmVtZW50SQAMZWxlbWVu" +
+ "dENvdW50WwALZWxlbWVudERhdGF0ABNbTGphdmEvbGFuZy9PYmplY3Q7eHAAAAAAAAAA" +
+ "AXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAAFzcQB+AAd0AANi" +
+ "YXJ0AARyZWFkeHh4eHg=";
+
+ /**
+ * A base64 encoded serialized PermissionsHash object, which is an internal
+ * class used to store Permissions that do not implement their own
+ * PermissionCollection. This contains one Permission,
+ * PrivateCredentialPermission("a.b.PrivateCredential a.b.Principal
+ * \"duke\"", "read")
+ * However, the Hashtable entry has been modified to map the
+ * PrivateCredentialPermission to SecurityPermission("foo") instead of
+ * itself.
+ */
+ private static String INVALID_PERMISSIONS_HASH =
+ "rO0ABXNyABlqYXZhLnNlY3VyaXR5LlBlcm1pc3Npb25zQ21LTdLID1ADAAJMAA1hbGxQ" +
+ "ZXJtaXNzaW9udAAkTGphdmEvc2VjdXJpdHkvUGVybWlzc2lvbkNvbGxlY3Rpb247TAAF" +
+ "cGVybXN0ABVMamF2YS91dGlsL0hhc2h0YWJsZTt4cgAiamF2YS5zZWN1cml0eS5QZXJt" +
+ "aXNzaW9uQ29sbGVjdGlvbqKk2tZqGAkpAgABWgAIcmVhZE9ubHl4cAFwc3IAE2phdmEu" +
+ "dXRpbC5IYXNodGFibGUTuw8lIUrkuAMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4" +
+ "cD9AAAAAAAAEdwgAAAAGAAAAA3ZyABZqYXZhLmlvLkZpbGVQZXJtaXNzaW9ubg+fk/TA" +
+ "qbsDAAFMAAdhY3Rpb25zdAASTGphdmEvbGFuZy9TdHJpbmc7eHIAGGphdmEuc2VjdXJp" +
+ "dHkuUGVybWlzc2lvbrHG4T8oV1F+AgABTAAEbmFtZXEAfgAIeHBzcgAgamF2YS5pby5G" +
+ "aWxlUGVybWlzc2lvbkNvbGxlY3Rpb24eknl91I5VqQMAAUwAC3Blcm1pc3Npb25zdAAS" +
+ "TGphdmEvdXRpbC9WZWN0b3I7eHEAfgADAHNyABBqYXZhLnV0aWwuVmVjdG9y2Zd9W4A7" +
+ "rwEDAANJABFjYXBhY2l0eUluY3JlbWVudEkADGVsZW1lbnRDb3VudFsAC2VsZW1lbnRE" +
+ "YXRhdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwAAAAAAAAAAF1cgATW0xqYXZhLmxhbmcu" +
+ "T2JqZWN0O5DOWJ8QcylsAgAAeHAAAAABc3EAfgAHdAADYmFydAAEcmVhZHh4eHZyAC9q" +
+ "YXZheC5zZWN1cml0eS5hdXRoLlByaXZhdGVDcmVkZW50aWFsUGVybWlzc2lvbklV3Hd7" +
+ "UH9MAgADWgAHdGVzdGluZ0wAD2NyZWRlbnRpYWxDbGFzc3EAfgAITAAKcHJpbmNpcGFs" +
+ "c3QAD0xqYXZhL3V0aWwvU2V0O3hxAH4ACXNyAB1qYXZhLnNlY3VyaXR5LlBlcm1pc3Np" +
+ "b25zSGFzaIomZbSmPV1AAwABTAAFcGVybXNxAH4AAnhxAH4AAwBzcQB+AAU/QAAAAAAA" +
+ "AXcIAAAAAgAAAAFzcQB+ABZ0ACphLmIuUHJpdmF0ZUNyZWRlbnRpYWwgYS5iLlByaW5j" +
+ "aXBhbCAiZHVrZSIAdAAVYS5iLlByaXZhdGVDcmVkZW50aWFscHNyACBqYXZhLnNlY3Vy" +
+ "aXR5LlNlY3VyaXR5UGVybWlzc2lvbkiqZj6xhx0mAgAAeHIAHWphdmEuc2VjdXJpdHku" +
+ "QmFzaWNQZXJtaXNzaW9uVyUL3M9OpnoCAAB4cQB+AAl0AANmb294eHZxAH4AH3NyACdq" +
+ "YXZhLnNlY3VyaXR5LkJhc2ljUGVybWlzc2lvbkNvbGxlY3Rpb24KQocEje3jxwMAA1oA" +
+ "C2FsbF9hbGxvd2VkTAAJcGVybUNsYXNzdAARTGphdmEvbGFuZy9DbGFzcztMAAtwZXJt" +
+ "aXNzaW9uc3EAfgACeHEAfgADAABxAH4AI3NxAH4ABT9AAAAAAAABdwgAAAACAAAAAXEA" +
+ "fgAic3EAfgAfcQB+ACJ4eHh4";
+
+ public static void main(String[] args) throws Exception {
+
+ Base64.Decoder decoder = Base64.getDecoder();
+ deserialize(decoder.decode(INVALID_PERMISSIONS));
+ deserialize(decoder.decode(INVALID_PERMISSIONS_HASH));
+ }
+
+ private static void deserialize(byte[] serialBytes) throws Exception {
+ try (ObjectInputStream ois =
+ new ObjectInputStream(new ByteArrayInputStream(serialBytes))) {
+ try {
+ Permissions p = (Permissions) ois.readObject();
+ throw new Exception("expected InvalidObjectException");
+ } catch (InvalidObjectException ioe) {
+ // test passed
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/security/Signature/SignatureGetInstance.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8216039
+ * @summary Ensure the BC provider-reselection workaround in Signature class
+ * functions correctly
+ * @modules java.base/sun.security.util
+ * @run main/othervm SignatureGetInstance
+ */
+import java.security.*;
+import java.security.interfaces.*;
+import java.security.spec.*;
+import sun.security.util.SignatureUtil;
+
+public class SignatureGetInstance {
+
+ private static final String SIGALG = "RSASSA-PSS";
+
+ public static void main(String[] args) throws Exception {
+ Provider testProvider = new TestProvider();
+ // put test provider before SunRsaSign provider
+ Security.insertProviderAt(testProvider, 1);
+ //Security.addProvider(testProvider);
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
+ KeyPair kp = kpg.generateKeyPair();
+
+ MyPrivKey testPriv = new MyPrivKey();
+ MyPubKey testPub = new MyPubKey();
+
+ testDblInit(testPriv, testPub, true, "TestProvider");
+ testDblInit(kp.getPrivate(), kp.getPublic(), true, "SunRsaSign");
+ testDblInit(testPriv, kp.getPublic(), false, null);
+ testDblInit(kp.getPrivate(), testPub, false, null);
+
+ testSetAndInit(null, testPriv, true);
+ testSetAndInit(null, testPub, true);
+ testSetAndInit(null, kp.getPrivate(), true);
+ testSetAndInit(null, kp.getPublic(), true);
+
+ String provName = "SunRsaSign";
+ testSetAndInit(provName, testPriv, false);
+ testSetAndInit(provName, testPub, false);
+ testSetAndInit(provName, kp.getPrivate(), true);
+ testSetAndInit(provName, kp.getPublic(), true);
+
+ provName = "TestProvider";
+ testSetAndInit(provName, testPriv, true);
+ testSetAndInit(provName, testPub, true);
+ testSetAndInit(provName, kp.getPrivate(), false);
+ testSetAndInit(provName, kp.getPublic(), false);
+
+ System.out.println("Test Passed");
+ }
+
+ private static void checkName(Signature s, String name) {
+ if (name != null &&
+ !(name.equals(s.getProvider().getName()))) {
+ throw new RuntimeException("Fail: provider name mismatch");
+ }
+ }
+
+ private static void testDblInit(PrivateKey key1, PublicKey key2,
+ boolean shouldPass, String expectedProvName) throws Exception {
+ Signature sig = Signature.getInstance(SIGALG);
+ SignatureUtil.initSignWithParam(sig, key1, PSSParameterSpec.DEFAULT, null);
+ try {
+ sig.initVerify(key2);
+ if (!shouldPass) {
+ throw new RuntimeException("Fail: should throw InvalidKeyException");
+ }
+ checkName(sig, expectedProvName);
+ } catch (InvalidKeyException ike) {
+ if (shouldPass) {
+ System.out.println("Fail: Unexpected InvalidKeyException");
+ throw ike;
+ }
+ }
+ }
+
+ private static void testSetAndInit(String provName, Key key,
+ boolean shouldPass) throws Exception {
+ Signature sig;
+ if (provName == null) {
+ sig = Signature.getInstance(SIGALG);
+ } else {
+ sig = Signature.getInstance(SIGALG, provName);
+ }
+ AlgorithmParameterSpec params = PSSParameterSpec.DEFAULT;
+ boolean doSign = (key instanceof PrivateKey);
+ try {
+ if (doSign) {
+ SignatureUtil.initSignWithParam(sig, (PrivateKey)key, params, null);
+ } else {
+ SignatureUtil.initVerifyWithParam(sig, (PublicKey)key, params);
+ }
+ if (!shouldPass) {
+ throw new RuntimeException("Fail: should throw InvalidKeyException");
+ }
+ checkName(sig, provName);
+ // check that the earlier parameter is still there
+ if (sig.getParameters() == null) {
+ throw new RuntimeException("Fail: parameters not preserved");
+ }
+ } catch (InvalidKeyException ike) {
+ if (shouldPass) {
+ System.out.println("Fail: Unexpected InvalidKeyException");
+ throw ike;
+ }
+ }
+ }
+
+ // Test provider which only accepts its own Key objects
+ // Registered to be more preferred than SunRsaSign provider
+ // for testing deferred provider selection
+ public static class TestProvider extends Provider {
+ TestProvider() {
+ super("TestProvider", "1.0", "provider for SignatureGetInstance");
+ put("Signature.RSASSA-PSS",
+ "SignatureGetInstance$MySigImpl");
+ }
+ }
+
+ public static class MyPrivKey implements PrivateKey {
+ public String getAlgorithm() { return "RSASSA-PSS"; }
+ public String getFormat() { return "MyOwn"; }
+ public byte[] getEncoded() { return null; }
+ }
+
+ public static class MyPubKey implements PublicKey {
+ public String getAlgorithm() { return "RSASSA-PSS"; }
+ public String getFormat() { return "MyOwn"; }
+ public byte[] getEncoded() { return null; }
+ }
+
+ public static class MySigImpl extends SignatureSpi {
+ // simulate BC behavior of only using params set before init calls
+ AlgorithmParameterSpec initParamSpec = null;
+ AlgorithmParameterSpec paramSpec = null;
+
+ public MySigImpl() {
+ super();
+ }
+
+ @Override
+ protected void engineInitVerify(PublicKey publicKey)
+ throws InvalidKeyException {
+ if (!(publicKey instanceof MyPubKey)) {
+ throw new InvalidKeyException("Must be MyPubKey");
+ }
+ initParamSpec = paramSpec;
+ }
+
+ @Override
+ protected void engineInitSign(PrivateKey privateKey)
+ throws InvalidKeyException {
+ if (!(privateKey instanceof MyPrivKey)) {
+ throw new InvalidKeyException("Must be MyPrivKey");
+ }
+ initParamSpec = paramSpec;
+ }
+
+ @Override
+ protected void engineUpdate(byte b) throws SignatureException {
+ }
+
+ @Override
+ protected void engineUpdate(byte[] b, int off, int len)
+ throws SignatureException {
+ }
+
+ @Override
+ protected byte[] engineSign()
+ throws SignatureException {
+ return new byte[0];
+ }
+
+ @Override
+ protected boolean engineVerify(byte[] sigBytes)
+ throws SignatureException {
+ return false;
+ }
+
+ @Override
+ @Deprecated
+ protected void engineSetParameter(String param, Object value)
+ throws InvalidParameterException {
+ }
+
+ @Override
+ protected void engineSetParameter(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ paramSpec = params;
+ }
+
+ @Override
+ @Deprecated
+ protected AlgorithmParameters engineGetParameter(String param)
+ throws InvalidParameterException {
+ return null;
+ }
+
+ @Override
+ protected AlgorithmParameters engineGetParameters() {
+ if (initParamSpec != null) {
+ try {
+ AlgorithmParameters ap =
+ AlgorithmParameters.getInstance("RSASSA-PSS");
+ ap.init(initParamSpec);
+ return ap;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return null;
+ }
+ }
+}
--- a/test/jdk/java/util/Map/MapFactories.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/java/util/Map/MapFactories.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
/*
* @test
- * @bug 8048330
+ * @bug 8048330 8221924
* @summary Test convenience static factory methods on Map.
* @run testng MapFactories
*/
@@ -386,6 +386,11 @@
act.containsKey(null);
}
+ @Test(dataProvider="all", expectedExceptions=NullPointerException.class)
+ public void getNullShouldThrowNPE(Map<Integer,String> act, Map<Integer,String> exp) {
+ act.get(null);
+ }
+
@Test(dataProvider="all")
public void serialEquality(Map<Integer, String> act, Map<Integer, String> exp) {
// assume that act.equals(exp) tested elsewhere
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/javax/sound/midi/SysexMessage/Basic.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.Arrays;
+
+import javax.sound.midi.SysexMessage;
+
+import static javax.sound.midi.SysexMessage.SPECIAL_SYSTEM_EXCLUSIVE;
+import static javax.sound.midi.SysexMessage.SYSTEM_EXCLUSIVE;
+
+/**
+ * @test
+ * @bug 8221445
+ * @summary Checks basic functionality of javax.sound.midi.SysexMessage class
+ */
+public class Basic {
+
+ public static void main(final String[] args) throws Exception {
+ byte[] dataExclusive = {(byte) (SYSTEM_EXCLUSIVE)};
+ byte[] dataSpecialExclusive = {(byte) (SPECIAL_SYSTEM_EXCLUSIVE)};
+ byte[] empty = {};
+
+ ////////////////////////////
+ // Constructors
+ ////////////////////////////
+ SysexMessage msg = new SysexMessage(dataExclusive, 1);
+ test(msg, SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage(dataSpecialExclusive, 1);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage(SYSTEM_EXCLUSIVE, empty, 0);
+ test(msg, SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage(SPECIAL_SYSTEM_EXCLUSIVE, empty, 0);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage(SYSTEM_EXCLUSIVE, dataSpecialExclusive, 1);
+ test(msg, SYSTEM_EXCLUSIVE, dataSpecialExclusive, 2);
+ msg = new SysexMessage(SPECIAL_SYSTEM_EXCLUSIVE, dataExclusive, 1);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, dataExclusive, 2);
+
+ ////////////////////////////
+ // SysexMessage.setMessage()
+ ////////////////////////////
+ msg = new SysexMessage();
+ msg.setMessage(dataExclusive, 1);
+ test(msg, SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage();
+ msg.setMessage(dataSpecialExclusive, 1);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage();
+ msg.setMessage(SYSTEM_EXCLUSIVE, empty, 0);
+ test(msg, SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage();
+ msg.setMessage(SPECIAL_SYSTEM_EXCLUSIVE, empty, 0);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, empty, 1);
+ msg = new SysexMessage();
+ msg.setMessage(SYSTEM_EXCLUSIVE, dataSpecialExclusive, 1);
+ test(msg, SYSTEM_EXCLUSIVE, dataSpecialExclusive, 2);
+ msg = new SysexMessage();
+ msg.setMessage(SPECIAL_SYSTEM_EXCLUSIVE, dataExclusive, 1);
+ test(msg, SPECIAL_SYSTEM_EXCLUSIVE, dataExclusive, 2);
+ }
+
+ static void test(SysexMessage msg, int status, byte[] data, int length) {
+ if (msg.getStatus() != status) {
+ System.err.println("Expected status: " + status);
+ System.err.println("Actual status: " + msg.getStatus());
+ throw new RuntimeException();
+ }
+ if (msg.getLength() != length) {
+ System.err.println("Expected length: " + length);
+ System.err.println("Actual length: " + msg.getLength());
+ throw new RuntimeException();
+ }
+ if (!Arrays.equals(msg.getData(), data)) {
+ System.err.println("Expected data: " + Arrays.toString(data));
+ System.err.println("Actual data: " + Arrays.toString(msg.getData()));
+ throw new RuntimeException();
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/javax/sound/midi/SysexMessage/Exceptions.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 javax.sound.midi.InvalidMidiDataException;
+import javax.sound.midi.SysexMessage;
+
+import static javax.sound.midi.SysexMessage.SYSTEM_EXCLUSIVE;
+
+/**
+ * @test
+ * @bug 8221445
+ * @summary Checks exceptions thrown by javax.sound.midi.SysexMessage class
+ */
+public final class Exceptions {
+
+ public static void main(final String[] args) throws Exception {
+ testInvalidMidiDataException();
+ testIndexOutOfBoundsException();
+ testNullPointerException();
+ }
+
+ private static void testInvalidMidiDataException() {
+ try {
+ // data should conatins a status byte
+ new SysexMessage(new byte[0], 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ try {
+ // length is zero, no space for the status byte
+ new SysexMessage(new byte[]{(byte) (SYSTEM_EXCLUSIVE)}, 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ try {
+ // status should conatins a status byte (0xF0 or 0xF7)
+ new SysexMessage(0, new byte[0], 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ SysexMessage sysexMessage = new SysexMessage();
+ try {
+ // data should conatins a status byte
+ sysexMessage.setMessage(new byte[0], 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ try {
+ // length is zero, no space for the status byte
+ sysexMessage.setMessage(new byte[]{(byte) (SYSTEM_EXCLUSIVE)}, 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ try {
+ // data should conatins a status byte (0xF0 or 0xF7)
+ sysexMessage.setMessage(new byte[]{0}, 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ try {
+ // status should conatins a status byte (0xF0 or 0xF7)
+ sysexMessage.setMessage(0, new byte[0], 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final InvalidMidiDataException ignored) {
+ // ok
+ }
+ }
+
+ private static void testIndexOutOfBoundsException() throws Exception {
+ // length is bigger than data
+ try {
+ new SysexMessage(new byte[]{(byte) (0xF0 & 0xFF)}, 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ try {
+ new SysexMessage(0xF0, new byte[0], 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ SysexMessage sysexMessage = new SysexMessage();
+ try {
+ sysexMessage.setMessage(new byte[]{(byte) (0xF0 & 0xFF)}, 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ try {
+ sysexMessage.setMessage(0xF0, new byte[0], 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+
+ // length is negative
+ try {
+ new SysexMessage(new byte[]{(byte) (0xF0 & 0xFF)}, -1);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ try {
+ new SysexMessage(0xF0, new byte[0], -1);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ sysexMessage = new SysexMessage();
+ try {
+ sysexMessage.setMessage(new byte[]{(byte) (0xF0 & 0xFF)}, -1);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ try {
+ sysexMessage.setMessage(0xF0, new byte[0], -1);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final IndexOutOfBoundsException ignored) {
+ // ok
+ }
+ }
+
+ private static void testNullPointerException() throws Exception {
+ try {
+ new SysexMessage(null, 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final NullPointerException ignored) {
+ // ok
+ }
+ try {
+ new SysexMessage(SYSTEM_EXCLUSIVE, null, 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final NullPointerException ignored) {
+ // ok
+ }
+ SysexMessage sysexMessage = new SysexMessage();
+ try {
+ sysexMessage.setMessage(null, 0);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final NullPointerException ignored) {
+ // ok
+ }
+ sysexMessage = new SysexMessage();
+ try {
+ sysexMessage.setMessage(SYSTEM_EXCLUSIVE, null, 2);
+ throw new RuntimeException("Expected exception is not thrown");
+ } catch (final NullPointerException ignored) {
+ // ok
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/AlgOptions.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 5094028 6219522
+ * @summary test new jarsigner -sigalg and -digestalg options
+ * @author Sean Mullan
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+public class AlgOptions {
+ public static void main(String[] args) throws Exception {
+
+ // copy jar file into writeable location
+ Files.copy(Path.of(System.getProperty("test.src"), "AlgOptions.jar"),
+ Path.of("AlgOptionsTmp.jar"));
+
+ // test missing signature algorithm arg
+ sign("-sigalg").shouldNotHaveExitValue(0);
+
+ // test missing digest algorithm arg
+ sign("-digestalg").shouldNotHaveExitValue(0);
+
+ // test BOGUS signature algorithm
+ sign("-sigalg", "BOGUS").shouldNotHaveExitValue(0);
+
+ // test BOGUS digest algorithm
+ sign("-digestalg", "BOGUS").shouldNotHaveExitValue(0);
+
+ // test incompatible signature algorithm
+ sign("-sigalg", "SHA1withDSA").shouldNotHaveExitValue(0);
+
+ // test compatible signature algorithm
+ sign("-sigalg", "SHA512withRSA").shouldHaveExitValue(0);
+ verify();
+
+ // test non-default digest algorithm
+ sign("-digestalg", "SHA-1").shouldHaveExitValue(0);
+ verify();
+
+ // test SHA-512 digest algorithm (creates long lines)
+ sign("-digestalg", "SHA-512", "-sigalg", "SHA512withRSA")
+ .shouldHaveExitValue(0);
+ verify();
+ }
+
+ static OutputAnalyzer sign(String... options) throws Exception {
+ List<String> args = new ArrayList<>();
+ args.add("-keystore");
+ args.add(Path.of(System.getProperty("test.src"), "JarSigning.keystore")
+ .toString());
+ args.add("-storepass");
+ args.add("bbbbbb");
+ for (String option : options) {
+ args.add(option);
+ }
+ args.add("AlgOptionsTmp.jar");
+ args.add("c");
+ return SecurityTools.jarsigner(args);
+ }
+
+ static void verify() throws Exception {
+ SecurityTools.jarsigner(
+ "-verify", "AlgOptionsTmp.jar")
+ .shouldHaveExitValue(0);
+ }
+}
--- a/test/jdk/sun/security/tools/jarsigner/AlgOptions.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,224 +0,0 @@
-#
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 5094028 6219522
-# @summary test new jarsigner -sigalg and -digestalg options
-# @author Sean Mullan
-#
-# @run shell AlgOptions.sh
-#
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- CP="${FS}bin${FS}cp -f"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- CP="cp -f"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- CP="cp -f"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# copy jar file into writeable location
-${CP} ${TESTSRC}${FS}AlgOptions.jar ${TESTCLASSES}${FS}AlgOptionsTmp.jar
-
-failed=0
-# test missing signature algorithm arg
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -sigalg \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 1 failed"
- failed=1
-else
- echo "test 1 passed"
-fi
-
-# test missing digest algorithm arg
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 2 failed"
- failed=1
-else
- echo "test 2 passed"
-fi
-
-# test BOGUS signature algorithm
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -sigalg BOGUS \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 3 failed"
- failed=1
-else
- echo "test 3 passed"
-fi
-
-# test BOGUS digest algorithm
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg BOGUS \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 4 failed"
- failed=1
-else
- echo "test 4 passed"
-fi
-
-# test incompatible signature algorithm
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -sigalg SHA1withDSA \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 5 failed"
- failed=1
-else
- echo "test 5 passed"
-fi
-
-# test compatible signature algorithm
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -sigalg SHA512withRSA \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 6 passed"
-else
- echo "test 6 failed"
- failed=1
-fi
-
-# verify it
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -verify ${TESTCLASSES}${FS}AlgOptionsTmp.jar
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 7 passed"
-else
- echo "test 7 failed"
- failed=1
-fi
-
-# test non-default digest algorithm
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg SHA-256 \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 8 passed"
-else
- echo "test 8 failed"
- failed=1
-fi
-
-# verify it
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -verify ${TESTCLASSES}${FS}AlgOptionsTmp.jar
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 9 passed"
-else
- echo "test 9 failed"
- failed=1
-fi
-
-# test SHA-512 digest algorithm (creates long lines)
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg SHA-512 \
- -sigalg SHA512withRSA \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar c
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 10 passed"
-else
- echo "test 10 failed"
- failed=1
-fi
-
-# verify it
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -verify ${TESTCLASSES}${FS}AlgOptionsTmp.jar
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- echo "test 11 passed"
-else
- echo "test 11 failed"
- failed=1
-fi
-
-if [ $failed -eq 1 ]; then
- exit 1
-else
- exit 0
-fi
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/CertPolicy.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8036709
+ * @summary Java 7 jarsigner displays warning about cert policy tree
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.util.JarUtils;
+
+import java.io.FileOutputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class CertPolicy {
+ static OutputAnalyzer keytool(String cmd) throws Exception {
+ return SecurityTools.keytool("-keypass changeit -storepass changeit "
+ + "-keystore ks -keyalg rsa " + cmd);
+ }
+
+ static OutputAnalyzer jarsigner(String cmd) throws Exception {
+ return SecurityTools.jarsigner("-storepass changeit -keystore ks " + cmd);
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ keytool("-genkeypair -alias ca -dname CN=CA -ext bc");
+ keytool("-genkeypair -alias int -dname CN=Int");
+ keytool("-genkeypair -alias ee -dname CN=EE");
+
+ // CertificatePolicies [[PolicyId: [1.2.3]], [PolicyId: [1.2.4]]]
+ // PolicyConstraints: [Require: 0; Inhibit: unspecified]
+ keytool("-certreq -alias int -file int.req");
+ keytool("-gencert -rfc -alias ca "
+ + "-ext 2.5.29.32=300C300406022A03300406022A04 "
+ + "-ext 2.5.29.36=3003800100 "
+ + "-ext bc -infile int.req -outfile int.cert");
+ keytool("-import -alias int -file int.cert");
+
+ // CertificatePolicies [[PolicyId: [1.2.3]]]
+ keytool("-certreq -alias ee -file ee.req");
+ keytool("-gencert -rfc -alias int -ext 2.5.29.32=3006300406022A03 "
+ + "-infile ee.req -outfile ee.cert");
+ keytool("-import -alias ee -file ee.cert");
+
+ Files.write(Path.of("cc"), List.of(
+ keytool("-export -alias ee -rfc").getOutput(),
+ keytool("-export -alias int -rfc").getOutput(),
+ keytool("-export -alias ca -rfc").getOutput()));
+
+ keytool("-delete -alias int");
+
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("cc"));
+
+ // Make sure the certchain in the signed jar contains all 3 certs
+ jarsigner("-strict -certchain cc a.jar ee -debug")
+ .shouldHaveExitValue(0);
+
+ jarsigner("-strict -verify a.jar -debug")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/CheckUsage.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 7004168
+ * @summary jarsigner -verify checks for KeyUsage codesigning ext on all certs
+ * instead of just signing cert
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class CheckUsage {
+
+ static OutputAnalyzer keytool(String cmd) throws Exception {
+ return SecurityTools.keytool("-keypass changeit -storepass changeit "
+ + "-keyalg rsa " + cmd);
+ }
+
+ public static void main(String[] args) throws Exception {
+ Files.write(Path.of("x"), List.of("x"));
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("x"));
+
+ // ################### 3 Keystores #######################
+
+ // Keystore js.jks: including CA and Publisher
+ // CA contains a non-empty KeyUsage
+ keytool("-keystore js.jks -genkeypair -alias ca -dname CN=CA "
+ + "-ext KU=kCS -ext bc -validity 365");
+ keytool("-keystore js.jks -genkeypair -alias pub -dname CN=Publisher");
+
+ // Publisher contains the correct KeyUsage
+ keytool("-keystore js.jks -certreq -alias pub -file pub.req");
+ keytool("-keystore js.jks -gencert -alias ca -ext KU=dig -validity 365 "
+ + "-infile pub.req -outfile pub.cert");
+ keytool("-keystore js.jks -importcert -alias pub -file pub.cert");
+
+ // Keystore trust.jks: including CA only
+ keytool("-keystore js.jks -exportcert -alias ca -file ca.cert");
+ keytool("-keystore trust.jks -importcert -alias ca -noprompt -file ca.cert");
+
+ // Keystore unrelated.jks: unrelated
+ keytool("-keystore unrelated.jks -genkeypair -alias nothing "
+ + "-dname CN=Nothing -validity 365");
+
+ // ################### 4 Tests #######################
+
+ // Test 1: Sign should be OK
+
+ SecurityTools.jarsigner("-keystore js.jks -storepass changeit a.jar pub")
+ .shouldHaveExitValue(0);
+
+ // Test 2: Verify should be OK
+
+ SecurityTools.jarsigner("-keystore trust.jks -storepass changeit "
+ + "-strict -verify a.jar")
+ .shouldHaveExitValue(0);
+
+ // Test 3: When no keystore is specified, the error is only
+ // "chain invalid"
+
+ SecurityTools.jarsigner("-strict -verify a.jar")
+ .shouldHaveExitValue(4);
+
+ // Test 4: When unrelated keystore is specified, the error is
+ // "chain invalid" and "not alias in keystore"
+
+ SecurityTools.jarsigner("-keystore unrelated.jks -storepass changeit "
+ + "-strict -verify a.jar")
+ .shouldHaveExitValue(36);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/Collator.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8021789
+ * @summary jarsigner parses alias as command line option (depending on locale)
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class Collator {
+ public static void main(String[] args) throws Exception {
+
+ Files.write(Path.of("collator"), List.of("12345"));
+ JarUtils.createJarFile(
+ Path.of("collator.jar"), Path.of("."), Path.of("collator"));
+
+ SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keyalg rsa -keystore collator.jks -alias debug "
+ + "-dname CN=debug -genkey -validity 300")
+ .shouldHaveExitValue(0);
+
+ // use "debug" as alias name
+ SecurityTools.jarsigner("-keystore collator.jks "
+ + "-storepass changeit collator.jar debug")
+ .shouldHaveExitValue(0);
+
+ // use "" as alias name (although there will be a warning)
+ SecurityTools.jarsigner("-keystore", "collator.jks",
+ "-storepass", "changeit", "-verify", "collator.jar", "")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/ConciseJarsigner.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,273 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6802846 8172529
+ * @summary jarsigner needs enhanced cert validation(options)
+ * @library /test/lib
+ * @run main/timeout=240 ConciseJarsigner
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Calendar;
+import java.util.List;
+
+public class ConciseJarsigner {
+
+ static OutputAnalyzer kt(String cmd) throws Exception {
+ // Choose 1024-bit RSA to make sure it runs fine and fast. In
+ // fact, every keyalg/keysize combination is OK for this test.
+ return SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa -keysize 1024 " + cmd);
+ }
+
+ static void gencert(String owner, String cmd) throws Exception {
+ kt("-certreq -alias " + owner + " -file tmp.req");
+ kt("-gencert -infile tmp.req -outfile tmp.cert " + cmd);
+ kt("-import -alias " + owner + " -file tmp.cert");
+ }
+
+ static OutputAnalyzer js(String cmd) throws Exception {
+ return SecurityTools.jarsigner("-debug " + cmd);
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ Files.write(Path.of("A1"), List.of("a1"));
+ Files.write(Path.of("A2"), List.of("a2"));
+ Files.write(Path.of("A3"), List.of("a3"));
+ Files.write(Path.of("A4"), List.of("a4"));
+ Files.write(Path.of("A5"), List.of("a5"));
+ Files.write(Path.of("A6"), List.of("a6"));
+
+ String year = "" + Calendar.getInstance().get(Calendar.YEAR);
+
+ // ==========================================================
+ // First part: output format
+ // ==========================================================
+
+ kt("-genkeypair -alias a1 -dname CN=a1 -validity 366");
+ kt("-genkeypair -alias a2 -dname CN=a2 -validity 366");
+
+ // a.jar includes 8 unsigned, 2 signed by a1 and a2, 2 signed by a3
+ SecurityTools.jar("cvf a.jar A1 A2");
+ js("-keystore ks -storepass changeit a.jar a1");
+ SecurityTools.jar("uvf a.jar A3 A4");
+ js("-keystore ks -storepass changeit a.jar a2");
+ SecurityTools.jar("uvf a.jar A5 A6");
+
+ // Verify OK
+ js("-verify a.jar").shouldHaveExitValue(0);
+
+ // 4(chainNotValidated)+16(hasUnsignedEntry)
+ js("-verify a.jar -strict").shouldHaveExitValue(20);
+
+ // 16(hasUnsignedEntry)
+ js("-verify a.jar -strict -keystore ks -storepass changeit")
+ .shouldHaveExitValue(16);
+
+ // 16(hasUnsignedEntry)+32(notSignedByAlias)
+ js("-verify a.jar a1 -strict -keystore ks -storepass changeit")
+ .shouldHaveExitValue(48);
+
+ // 16(hasUnsignedEntry)
+ js("-verify a.jar a1 a2 -strict -keystore ks -storepass changeit")
+ .shouldHaveExitValue(16);
+
+ // 12 entries all together
+ Asserts.assertTrue(js("-verify a.jar -verbose")
+ .asLines().stream()
+ .filter(s -> s.contains(year))
+ .count() == 12);
+
+ // 12 entries all listed
+ Asserts.assertTrue(js("-verify a.jar -verbose:grouped")
+ .asLines().stream()
+ .filter(s -> s.contains(year))
+ .count() == 12);
+
+ // 4 groups: MANIFST, unrelated, signed, unsigned
+ Asserts.assertTrue(js("-verify a.jar -verbose:summary")
+ .asLines().stream()
+ .filter(s -> s.contains(year))
+ .count() == 4);
+
+ // still 4 groups, but MANIFEST group has no other file
+ Asserts.assertTrue(js("-verify a.jar -verbose:summary")
+ .asLines().stream()
+ .filter(s -> s.contains("more)"))
+ .count() == 3);
+
+ // 5 groups: MANIFEST, unrelated, signed by a1/a2, signed by a2, unsigned
+ Asserts.assertTrue(js("-verify a.jar -verbose:summary -certs")
+ .asLines().stream()
+ .filter(s -> s.contains(year))
+ .count() == 5);
+
+ // 2 for MANIFEST, 2*2 for A1/A2, 2 for A3/A4
+ Asserts.assertTrue(js("-verify a.jar -verbose -certs")
+ .asLines().stream()
+ .filter(s -> s.contains("[certificate"))
+ .count() == 8);
+
+ // a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4
+ Asserts.assertTrue(js("-verify a.jar -verbose:grouped -certs")
+ .asLines().stream()
+ .filter(s -> s.contains("[certificate"))
+ .count() == 5);
+
+ // a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4
+ Asserts.assertTrue(js("-verify a.jar -verbose:summary -certs")
+ .asLines().stream()
+ .filter(s -> s.contains("[certificate"))
+ .count() == 5);
+
+ // still 5 groups, but MANIFEST group has no other file
+ Asserts.assertTrue(js("-verify a.jar -verbose:summary -certs")
+ .asLines().stream()
+ .filter(s -> s.contains("more)"))
+ .count() == 4);
+
+ // ==========================================================
+ // Second part: exit code 2, 4, 8.
+ // 16 and 32 already covered in the first part
+ // ==========================================================
+
+ kt("-genkeypair -alias ca -dname CN=ca -ext bc -validity 365");
+ kt("-genkeypair -alias expired -dname CN=expired");
+ gencert("expired", "-alias ca -startdate -10m");
+ kt("-genkeypair -alias notyetvalid -dname CN=notyetvalid");
+ gencert("notyetvalid", "-alias ca -startdate +1m");
+ kt("-genkeypair -alias badku -dname CN=badku");
+ gencert("badku", "-alias ca -ext KU=cRLSign -validity 365");
+ kt("-genkeypair -alias badeku -dname CN=badeku");
+ gencert("badeku", "-alias ca -ext EKU=sa -validity 365");
+ kt("-genkeypair -alias goodku -dname CN=goodku");
+ gencert("goodku", "-alias ca -ext KU=dig -validity 365");
+ kt("-genkeypair -alias goodeku -dname CN=goodeku");
+ gencert("goodeku", "-alias ca -ext EKU=codesign -validity 365");
+
+ js("-strict -keystore ks -storepass changeit a.jar expired")
+ .shouldHaveExitValue(4);
+
+ js("-strict -keystore ks -storepass changeit a.jar notyetvalid")
+ .shouldHaveExitValue(4);
+
+ js("-strict -keystore ks -storepass changeit a.jar badku")
+ .shouldHaveExitValue(8);
+
+ js("-strict -keystore ks -storepass changeit a.jar badeku")
+ .shouldHaveExitValue(8);
+
+ js("-strict -keystore ks -storepass changeit a.jar goodku")
+ .shouldHaveExitValue(0);
+
+ js("-strict -keystore ks -storepass changeit a.jar goodeku")
+ .shouldHaveExitValue(0);
+
+ // badchain signed by ca1, but ca1 is removed later
+ kt("-genkeypair -alias badchain -dname CN=badchain -validity 365");
+ kt("-genkeypair -alias ca1 -dname CN=ca1 -ext bc -validity 365");
+ gencert("badchain", "-alias ca1 -validity 365");
+
+ // save ca1.cert for easy replay
+ kt("-exportcert -file ca1.cert -alias ca1");
+ kt("-delete -alias ca1");
+
+ js("-strict -keystore ks -storepass changeit a.jar badchain")
+ .shouldHaveExitValue(4);
+
+ js("-verify a.jar").shouldHaveExitValue(0);
+
+ // ==========================================================
+ // Third part: -certchain test
+ // ==========================================================
+
+ // altchain signed by ca2
+ kt("-genkeypair -alias altchain -dname CN=altchain -validity 365");
+ kt("-genkeypair -alias ca2 -dname CN=ca2 -ext bc -validity 365");
+ kt("-certreq -alias altchain -file altchain.req");
+ Files.write(Path.of("certchain"), List.of(
+ kt("-gencert -alias ca2 -validity 365 -rfc -infile altchain.req")
+ .getOutput(),
+ kt("-exportcert -alias ca2 -rfc").getOutput()));
+
+ // Self-signed cert does not work
+ js("-strict -keystore ks -storepass changeit a.jar altchain")
+ .shouldHaveExitValue(4);
+
+ // -certchain works
+ js("-strict -keystore ks -storepass changeit -certchain certchain "
+ + "a.jar altchain")
+ .shouldHaveExitValue(0);
+
+ // if ca2 is removed, -certchain still work because altchain is a
+ // self-signed entry and it is trusted by jarsigner
+ // save ca2.cert for easy replay
+ kt("-exportcert -file ca2.cert -alias ca2");
+ kt("-delete -alias ca2");
+ js("-strict -keystore ks -storepass changeit "
+ + "-certchain certchain a.jar altchain")
+ .shouldHaveExitValue(0);
+
+ // if cert is imported, -certchain won't work because this
+ // certificate entry is not trusted
+ kt("-importcert -file certchain -alias altchain -noprompt");
+ js("-strict -keystore ks -storepass changeit "
+ + "-certchain certchain a.jar altchain")
+ .shouldHaveExitValue(4);
+
+ js("-verify a.jar").shouldHaveExitValue(0);
+
+ // ==========================================================
+ // 8172529
+ // ==========================================================
+
+ kt("-genkeypair -alias ee -dname CN=ee");
+ kt("-genkeypair -alias caone -dname CN=caone");
+ kt("-genkeypair -alias catwo -dname CN=catwo");
+
+ kt("-certreq -alias ee -file ee.req");
+ kt("-certreq -alias catwo -file catwo.req");
+
+ // This certchain contains a cross-signed weak catwo.cert
+ Files.write(Path.of("ee2"), List.of(
+ kt("-gencert -alias catwo -rfc -infile ee.req").getOutput(),
+ kt("-gencert -alias caone -sigalg MD5withRSA -rfc "
+ + "-infile catwo.req").getOutput()));
+
+ kt("-importcert -alias ee -file ee2");
+
+ SecurityTools.jar("cvf a.jar A1");
+ js("-strict -keystore ks -storepass changeit a.jar ee")
+ .shouldHaveExitValue(0);
+ js("-strict -keystore ks -storepass changeit -verify a.jar")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/Crl.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6890876 6950931
+ * @summary jarsigner can add CRL info into signed jar (updated)
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class Crl {
+ static OutputAnalyzer kt(String cmd) throws Exception {
+ return SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa " + cmd);
+ }
+
+ public static void main(String[] args) throws Exception {
+ kt("-alias a -dname CN=a -keyalg rsa -genkey -validity 300");
+ kt("-alias a -gencrl -id 1:1 -id 2:2 -file crl1")
+ .shouldHaveExitValue(0);
+ kt("-alias a -gencrl -id 3:3 -id 4:4 -file crl2")
+ .shouldHaveExitValue(0);
+ kt("-alias a -gencrl -id 5:1 -id 6:2 -file crl3")
+ .shouldHaveExitValue(0);
+
+ // Test keytool -printcrl
+
+ kt("-printcrl -file crl1").shouldHaveExitValue(0);
+ kt("-printcrl -file crl2").shouldHaveExitValue(0);
+ kt("-printcrl -file crl3").shouldHaveExitValue(0);
+
+ // Test keytool -ext crl
+
+ kt("-alias b -dname CN=c -keyalg rsa -genkey -validity 300 "
+ + "-ext crl=uri:http://www.example.com/crl")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/DefaultOptions.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8049834
+ * @summary Two security tools tests do not run with only JRE
+ * @library /test/lib
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.jar.JarFile;
+
+public class DefaultOptions {
+
+ static OutputAnalyzer jarsigner(String cmd) throws Throwable {
+ ProcessBuilder pb = SecurityTools.getProcessBuilder(
+ "jarsigner", List.of(cmd.trim().split("\\s+")));
+ pb.environment().put("PASS", "changeit");
+ return ProcessTools.executeCommand(pb);
+ }
+
+ static OutputAnalyzer keytool(String cmd) throws Throwable {
+ cmd = "-storepass:env PASS -keypass:env PASS -keystore ks " + cmd;
+ ProcessBuilder pb = SecurityTools.getProcessBuilder(
+ "keytool", List.of(cmd.trim().split("\\s+")));
+ pb.environment().put("PASS", "changeit");
+ return ProcessTools.executeCommand(pb);
+ }
+
+ public static void main(String[] args) throws Throwable {
+ keytool("-genkeypair -dname CN=A -alias a -keyalg rsa")
+ .shouldHaveExitValue(0);
+ keytool("-genkeypair -dname CN=CA -alias ca -keyalg rsa")
+ .shouldHaveExitValue(0);
+ keytool("-alias a -certreq -file a.req");
+ keytool("-alias ca -gencert -infile a.req -outfile a.cert");
+ keytool("-alias a -import -file a.cert").shouldHaveExitValue(0);
+
+ Files.write(Path.of("js.conf"), List.of(
+ "jarsigner.all = -keystore ${user.dir}/ks -storepass:env PASS "
+ + "-debug -strict",
+ "jarsigner.sign = -digestalg SHA1",
+ "jarsigner.verify = -verbose:summary"));
+
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."),
+ Path.of("ks"), Path.of("js.conf"));
+
+ jarsigner("-conf js.conf a.jar a").shouldHaveExitValue(0);
+ jarsigner("-conf js.conf -verify a.jar").shouldHaveExitValue(0)
+ .shouldContain("and 1 more");
+
+ try (JarFile jf = new JarFile("a.jar")) {
+ Asserts.assertTrue(jf.getManifest().getAttributes("ks").keySet()
+ .stream()
+ .anyMatch(s -> s.toString().contains("SHA1-Digest")));
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/DiffEnd.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6948909
+ * @summary Jarsigner removes MANIFEST.MF info for badly packages jar's
+ * @library /test/lib
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+import java.io.FileOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class DiffEnd {
+
+ static void check() throws Exception {
+ SecurityTools.jarsigner("-keystore "
+ + Path.of(System.getProperty("test.src"), "JarSigning.keystore")
+ .toString()
+ + " -storepass bbbbbb -digestalg SHA1"
+ + " -signedjar diffend.new.jar diffend.jar c");
+
+ try (JarFile jf = new JarFile("diffend.new.jar")) {
+ Asserts.assertTrue(jf.getManifest().getMainAttributes()
+ .containsKey(new Attributes.Name("Today")));
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ // A MANIFEST.MF using \n as newlines and no double newlines at the end
+ byte[] manifest =
+ ("Manifest-Version: 1.0\n"
+ + "Created-By: 1.7.0-internal (Sun Microsystems Inc.)\n"
+ + "Today: Monday\n").getBytes(StandardCharsets.UTF_8);
+
+ // With the fake .RSA file, to trigger the if (wasSigned) block
+ try (FileOutputStream fos = new FileOutputStream("diffend.jar");
+ ZipOutputStream zos = new ZipOutputStream(fos)) {
+ zos.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
+ zos.write(manifest);
+ zos.putNextEntry(new ZipEntry("META-INF/x.RSA"));
+ zos.putNextEntry(new ZipEntry("1"));
+ zos.write(new byte[10]);
+ }
+
+ check();
+
+ // Without the fake .RSA file, to trigger the else block
+ try (FileOutputStream fos = new FileOutputStream("diffend.jar");
+ ZipOutputStream zos = new ZipOutputStream(fos)) {
+ zos.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
+ zos.write(manifest);
+ zos.putNextEntry(new ZipEntry("1"));
+ zos.write(new byte[10]);
+ }
+
+ check();
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/EC.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6870812
+ * @summary enhance security tools to use ECC algorithm
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class EC {
+ static OutputAnalyzer kt(String cmd) throws Exception {
+ return SecurityTools.keytool("-storepass changeit "
+ + "-keypass changeit -keystore ks " + cmd);
+ }
+
+ static void gencert(String owner, String cmd) throws Exception {
+ kt("-certreq -alias " + owner + " -file tmp.req")
+ .shouldHaveExitValue(0);
+ kt("-gencert -infile tmp.req -outfile tmp.cert " + cmd)
+ .shouldHaveExitValue(0);
+ kt("-import -alias " + owner + " -file tmp.cert")
+ .shouldHaveExitValue(0);
+ }
+
+ static OutputAnalyzer js(String cmd) throws Exception {
+ return SecurityTools.jarsigner("-keystore ks -storepass changeit " + cmd);
+ }
+
+ public static void main(String[] args) throws Exception {
+ Files.write(Path.of("A"), List.of("A"));
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("A"));
+
+ kt("-alias ca -dname CN=ca -keyalg ec -genkey -validity 300")
+ .shouldHaveExitValue(0);
+ kt("-alias a -dname CN=a -keyalg ec -genkey")
+ .shouldHaveExitValue(0);
+ gencert("a", "-alias ca -validity 300");
+
+ kt("-alias b -dname CN=b -keyalg ec -genkey")
+ .shouldHaveExitValue(0);
+ gencert("b", "-alias ca -validity 300");
+
+ // Ensure key length sufficient for intended hash (SHA512withECDSA)
+ kt("-alias c -dname CN=c -keyalg ec -genkey -keysize 521")
+ .shouldHaveExitValue(0);
+ gencert("c", "-alias ca -validity 300");
+
+ kt("-alias x -dname CN=x -keyalg ec -genkey -validity 300")
+ .shouldHaveExitValue(0);
+ gencert("x", "-alias ca -validity 300");
+
+ js("a.jar a -debug -strict").shouldHaveExitValue(0);
+ js("a.jar b -debug -strict -sigalg SHA1withECDSA").shouldHaveExitValue(0);
+ js("a.jar c -debug -strict -sigalg SHA512withECDSA").shouldHaveExitValue(0);
+
+ js("-verify a.jar a -debug -strict").shouldHaveExitValue(0);
+ js("-verify a.jar b -debug -strict").shouldHaveExitValue(0);
+ js("-verify a.jar c -debug -strict").shouldHaveExitValue(0);
+
+ // Not signed by x, should exit with non-zero
+ js("-verify a.jar x -debug -strict").shouldNotHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/EmptyManifest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6712755
+ * @summary jarsigner fails to sign itextasian.jar since 1.5.0_b14,
+ * it works with 1.5.0_13
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+import java.io.FileOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class EmptyManifest {
+
+ public static void main(String[] args) throws Exception {
+
+ try (FileOutputStream fos = new FileOutputStream("em.jar");
+ ZipOutputStream zos = new ZipOutputStream(fos)) {
+ zos.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
+ zos.write(new byte[]{'\r', '\n'});
+ zos.putNextEntry(new ZipEntry("A"));
+ zos.write(new byte[10]);
+ zos.putNextEntry(new ZipEntry("B"));
+ zos.write(new byte[0]);
+ }
+
+ SecurityTools.keytool("-keystore ks -storepass changeit "
+ + "-keypass changeit -alias a -dname CN=a -keyalg rsa "
+ + "-genkey -validity 300");
+
+ SecurityTools.jarsigner("-keystore ks -storepass changeit em.jar a")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner("-keystore ks -storepass changeit -verify "
+ + "-debug -strict em.jar")
+ .shouldHaveExitValue(0);
+ }
+}
--- a/test/jdk/sun/security/tools/jarsigner/EntriesOrder.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/tools/jarsigner/EntriesOrder.java Sat Apr 13 07:23:18 2019 +0100
@@ -64,9 +64,9 @@
// directory ignored), we can get 2 signed ones (inf, a).
// Prepares raw files
- Files.write(Paths.get("a"), "a".getBytes());
+ Files.write(Paths.get("a"), List.of("a"));
Files.createDirectory(Paths.get("META-INF/"));
- Files.write(Paths.get("META-INF/inf"), "inf".getBytes());
+ Files.write(Paths.get("META-INF/inf"), List.of("inf"));
// Pack, sign, and extract to get all files
sun.tools.jar.Main m =
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/JvIndex.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8022761
+ * @summary regression: SecurityException is NOT thrown while trying
+ * to pack a wrongly signed Indexed Jar file
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class JvIndex {
+ public static void main(String[] args) throws Exception {
+
+ Files.write(Path.of("abcde"), List.of("12345"));
+ JarUtils.createJarFile(Path.of("jvindex.jar"), Path.of("."),
+ Path.of("abcde"));
+ SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa -alias a -dname CN=a "
+ + "-genkey -validity 300")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner("-keystore ks -storepass changeit jvindex.jar a")
+ .shouldHaveExitValue(0);
+
+ SecurityTools.jar("i jvindex.jar");
+
+ // Make sure the $F line has "sm" (signed and in manifest)
+ SecurityTools.jarsigner("-keystore ks -storepass changeit -verify "
+ + "-verbose jvindex.jar")
+ .shouldHaveExitValue(0)
+ .shouldMatch("sm.*abcde");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/NameClash.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6876328
+ * @summary different names for the same digest algorithms breaks jarsigner
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class NameClash {
+ public static void main(String[] args) throws Exception {
+ String common = "-storepass changeit -keypass changeit -keystore ks ";
+
+ SecurityTools.keytool(common + "-alias a -dname CN=a -keyalg rsa "
+ + "-genkey -validity 300");
+ SecurityTools.keytool(common + "-alias b -dname CN=b -keyalg rsa "
+ + "-genkey -validity 300");
+
+ Files.write(Path.of("A"), List.of("A"));
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("A"));
+
+ SecurityTools.jarsigner(common + "a.jar a -digestalg SHA1")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner(common + "a.jar b -digestalg SHA-1")
+ .shouldHaveExitValue(0);
+
+ SecurityTools.jarsigner(common + "-verify -debug -strict a.jar")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/NewSize7.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6561126
+ * @summary keytool should use larger default keysize for keypairs
+ * @library /test/lib
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+public class NewSize7 {
+ public static void main(String[] args) throws Exception {
+ String common = "-storepass changeit -keypass changeit -keystore ks ";
+ SecurityTools.keytool(common
+ + "-keyalg rsa -genkeypair -alias me -dname CN=Me");
+ Files.write(Path.of("ns7.txt"), new byte[0]);
+ JarUtils.createJarFile(Path.of("ns7.jar"), Path.of("."),
+ Path.of("ns7.txt"));
+ SecurityTools.jarsigner(common + "ns7.jar me");
+
+ try (JarFile jf = new JarFile("ns7.jar")) {
+ try (InputStream is = jf.getInputStream(
+ jf.getEntry("META-INF/MANIFEST.MF"))) {
+ Asserts.assertTrue(new Manifest(is).getAttributes("ns7.txt")
+ .keySet().stream()
+ .anyMatch(s -> s.toString().contains("SHA-256")));
+ }
+ try (InputStream is = jf.getInputStream(
+ jf.getEntry("META-INF/ME.SF"))) {
+ Asserts.assertTrue(new Manifest(is).getAttributes("ns7.txt")
+ .keySet().stream()
+ .anyMatch(s -> s.toString().contains("SHA-256")));
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/OldSig.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6543940 6868865
+ * @summary Exception thrown when signing a jarfile in java 1.5
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class OldSig {
+ public static void main(String[] args) throws Exception {
+ Path src = Path.of(System.getProperty("test.src"));
+ // copy jar file into writeable location
+ Files.copy(src.resolve("oldsig/A.jar"), Path.of("B.jar"));
+ Files.copy(src.resolve("oldsig/A.class"), Path.of("B.class"));
+
+ JarUtils.updateJarFile(Path.of("B.jar"), Path.of("."),
+ Path.of("B.class"));
+
+ SecurityTools.jarsigner("-keystore " + src.resolve("JarSigning.keystore")
+ + " -storepass bbbbbb -digestalg SHA1 B.jar c");
+ SecurityTools.jarsigner("-verify B.jar");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/OnlyManifest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 7004035
+ * @summary signed jar with only META-INF/* inside is not verifiable
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class OnlyManifest {
+ static OutputAnalyzer kt(String cmd) throws Exception {
+ return SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa " + cmd);
+ }
+
+ static void gencert(String owner, String cmd) throws Exception {
+ kt("-certreq -alias " + owner + " -file tmp.req");
+ kt("-gencert -infile tmp.req -outfile tmp.cert " + cmd);
+ kt("-import -alias " + owner + " -file tmp.cert");
+ }
+
+ public static void main(String[] args) throws Exception {
+ // Create an empty jar file with only MANIFEST.MF
+ Files.write(Path.of("manifest"), List.of("Key: Value"));
+ SecurityTools.jar("cvfm a.jar manifest");
+
+ kt("-alias ca -dname CN=ca -genkey -validity 300")
+ .shouldHaveExitValue(0);
+ kt("-alias a -dname CN=a -genkey -validity 300")
+ .shouldHaveExitValue(0);
+ gencert("a", "-alias ca -validity 300");
+
+ SecurityTools.jarsigner("-keystore ks -storepass changeit"
+ + " a.jar a -debug -strict")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner("-keystore ks -storepass changeit"
+ + " -verify a.jar a -debug -strict")
+ .shouldHaveExitValue(0)
+ .shouldNotContain("unsigned");
+ }
+}
--- a/test/jdk/sun/security/tools/jarsigner/Options.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/tools/jarsigner/Options.java Sat Apr 13 07:23:18 2019 +0100
@@ -58,7 +58,7 @@
public static void main(String[] args) throws Exception {
// Prepares raw file
- Files.write(Paths.get("a"), "a".getBytes());
+ Files.write(Paths.get("a"), List.of("a"));
// Pack
JarUtils.createJar("a.jar", "a");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/PassType.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6868579
+ * @summary RFE: jarsigner to support reading password from environment variable
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class PassType {
+
+ static OutputAnalyzer jarsignerWithEnv(String cmd) throws Throwable {
+ ProcessBuilder pb = SecurityTools.getProcessBuilder(
+ "jarsigner", List.of(cmd.trim().split("\\s+")));
+ pb.environment().put("PASSENV", "test12");
+ return ProcessTools.executeCommand(pb);
+ }
+
+ static OutputAnalyzer keytoolWithEnv(String cmd) throws Throwable {
+ ProcessBuilder pb = SecurityTools.getProcessBuilder(
+ "keytool", List.of(cmd.trim().split("\\s+")));
+ pb.environment().put("PASSENV", "test12");
+ return ProcessTools.executeCommand(pb);
+ }
+
+ public static void main(String[] args) throws Throwable {
+
+ SecurityTools.keytool("-keystore ks -validity 300 -keyalg rsa "
+ + "-alias a -dname CN=a -keyalg rsa -genkey "
+ + "-storepass test12 -keypass test12")
+ .shouldHaveExitValue(0);
+ keytoolWithEnv("-keystore ks -validity 300 -keyalg rsa "
+ + "-alias b -dname CN=b -keyalg rsa -genkey "
+ + "-storepass:env PASSENV -keypass:env PASSENV")
+ .shouldHaveExitValue(0);
+ Files.write(Path.of("passfile"), List.of("test12"));
+ SecurityTools.keytool("-keystore ks -validity 300 -keyalg rsa "
+ + "-alias c -dname CN=c -keyalg rsa -genkey "
+ + "-storepass:file passfile -keypass:file passfile")
+ .shouldHaveExitValue(0);
+
+ Files.write(Path.of("A"), List.of("A"));
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("A"));
+
+ // Sign
+ SecurityTools.jarsigner("-keystore ks -storepass test12 a.jar a")
+ .shouldHaveExitValue(0);
+ jarsignerWithEnv("-keystore ks -storepass:env PASSENV a.jar b")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner("-keystore ks -storepass:file passfile a.jar c")
+ .shouldHaveExitValue(0);
+
+ // Verify
+ SecurityTools.jarsigner("-keystore ks -storepass test12 "
+ + "-verify -debug -strict a.jar")
+ .shouldHaveExitValue(0);
+ jarsignerWithEnv("-keystore ks -storepass:env PASSENV "
+ + "-verify -debug -strict a.jar")
+ .shouldHaveExitValue(0);
+ SecurityTools.jarsigner("-keystore ks -storepass:file passfile "
+ + "-verify -debug -strict a.jar")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/PercentSign.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6522933
+ * @summary jarsigner fails in a directory with a path containing a % sign
+ * @author Wang Weijun
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class PercentSign {
+ public static void main(String[] args) throws Exception {
+
+ // copy jar file into writeable location
+ Files.copy(Path.of(System.getProperty("test.src"), "AlgOptions.jar"),
+ Path.of("AlgOptionsTmp.jar"));
+
+ SecurityTools.jarsigner("-keystore "
+ + Path.of(System.getProperty("test.src"), "a%b", "percent.keystore")
+ + " -storepass changeit AlgOptionsTmp.jar ok")
+ .shouldHaveExitValue(0);
+ }
+}
--- a/test/jdk/sun/security/tools/jarsigner/PercentSign.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-#
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6522933
-# @summary jarsigner fails in a directory with a path contianing a % sign
-# @author Wang Weijun
-#
-# @run shell PercentSign.sh
-#
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- CP="${FS}bin${FS}cp -f"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- CP="cp -f"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- CP="cp -f"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# copy jar file into writeable location
-${CP} ${TESTSRC}${FS}AlgOptions.jar ${TESTCLASSES}${FS}AlgOptionsTmp.jar
-
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}a%b${FS}percent.keystore \
- -storepass changeit \
- ${TESTCLASSES}${FS}AlgOptionsTmp.jar ok
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/SameName.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6866479
+ * @summary libzip.so caused JVM to crash when running jarsigner
+ * @library /test/lib
+ */
+
+import jdk.test.lib.Platform;
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class SameName {
+ public static void main(String[] args) throws Exception {
+
+ String signedJar = Platform.isWindows() ? "EM.jar" : "em.jar";
+
+ Files.write(Path.of("A"), List.of("A"));
+ JarUtils.createJarFile(Path.of("em.jar"), Path.of("."), Path.of("A"));
+
+ SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa -alias a -dname CN=a "
+ + "-keyalg rsa -genkey -validity 300")
+ .shouldHaveExitValue(0);
+
+ SecurityTools.jarsigner("-keystore ks -storepass changeit "
+ + "-signedjar " + signedJar + " em.jar a")
+ .shouldHaveExitValue(0);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/jarsigner/WeakSize.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8044755
+ * @summary Add a test for algorithm constraints check in jarsigner
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.util.JarUtils;
+
+import java.nio.file.Path;
+
+public class WeakSize {
+
+ static OutputAnalyzer kt(String cmd) throws Exception {
+ // The sigalg used is MD2withRSA, which is obsolete.
+ return SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa -sigalg MD2withRSA " + cmd);
+ }
+
+ static void gencert(String owner, String cmd) throws Exception {
+ kt("-certreq -alias " + owner + " -file tmp.req");
+ kt("-gencert -infile tmp.req -outfile tmp.cert " + cmd);
+ kt("-import -alias " + owner + " -file tmp.cert");
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ kt("-genkeypair -alias ca -dname CN=CA -ext bc");
+ kt("-genkeypair -alias signer -dname CN=Signer");
+ gencert("signer", "-alias ca -ext ku=dS -rfc");
+
+ JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), Path.of("ks"));
+
+ // We always trust a TrustedCertificateEntry
+ SecurityTools.jarsigner("-keystore ks -storepass changeit "
+ + "-strict -debug a.jar ca")
+ .shouldNotContain("chain is invalid");
+
+ // An end-entity cert must follow algorithm constraints
+ SecurityTools.jarsigner("-keystore ks -storepass changeit "
+ + "-strict -debug a.jar signer")
+ .shouldContain("chain is invalid");
+ }
+}
--- a/test/jdk/sun/security/tools/jarsigner/certpolicy.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-#
-# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8036709
-# @summary Java 7 jarsigner displays warning about cert policy tree
-#
-# @run shell certpolicy.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-KT="$TESTJAVA/bin/keytool $TESTTOOLVMOPTS \
- -keypass changeit -storepass changeit -keystore ks -keyalg rsa"
-JS="$TESTJAVA/bin/jarsigner $TESTTOOLVMOPTS -storepass changeit -keystore ks"
-JAR="$TESTJAVA/bin/jar $TESTTOOLVMOPTS"
-
-rm ks 2> /dev/null
-$KT -genkeypair -alias ca -dname CN=CA -ext bc
-$KT -genkeypair -alias int -dname CN=Int
-$KT -genkeypair -alias ee -dname CN=EE
-
-# CertificatePolicies [[PolicyId: [1.2.3]], [PolicyId: [1.2.4]]]
-# PolicyConstraints: [Require: 0; Inhibit: unspecified]
-$KT -certreq -alias int | \
- $KT -gencert -rfc -alias ca \
- -ext 2.5.29.32="30 0C 30 04 06 02 2A 03 30 04 06 02 2A 04" \
- -ext "2.5.29.36=30 03 80 01 00" -ext bc | \
- $KT -import -alias int
-
-# CertificatePolicies [[PolicyId: [1.2.3]]]
-$KT -certreq -alias ee | \
- $KT -gencert -rfc -alias int \
- -ext 2.5.29.32="30 06 30 04 06 02 2A 03" | \
- $KT -import -alias ee
-
-$KT -export -alias ee -rfc > cc
-$KT -export -alias int -rfc >> cc
-$KT -export -alias ca -rfc >> cc
-
-$KT -delete -alias int
-
-ERR=''
-$JAR cvf a.jar cc
-
-# Make sure the certchain in the signed jar contains all 3 certs
-$JS -strict -certchain cc a.jar ee -debug || ERR="sign"
-$JS -strict -verify a.jar -debug || ERR="$ERR verify"
-
-if [ "$ERR" = "" ]; then
- echo "Success"
- exit 0
-else
- echo "Failed: $ERR"
- exit 1
-fi
-
--- a/test/jdk/sun/security/tools/jarsigner/checkusage.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,109 +0,0 @@
-#
-# Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 7004168
-# @summary jarsigner -verify checks for KeyUsage codesigning ext on all certs
-# instead of just signing cert
-#
-# @run shell checkusage.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keyalg rsa"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS}"
-
-rm js.jks trust.jks unrelated.jks 2> /dev/null
-
-echo x > x
-$JAR cvf a.jar x
-
-################### 3 Keystores #######################
-
-# Keystore js.jks: including CA and Publisher
-# CA contains a non-empty KeyUsage
-$KT -keystore js.jks -genkeypair -alias ca -dname CN=CA -ext KU=kCS -ext bc -validity 365
-$KT -keystore js.jks -genkeypair -alias pub -dname CN=Publisher
-
-# Publisher contains the correct KeyUsage
-$KT -keystore js.jks -certreq -alias pub | \
- $KT -keystore js.jks -gencert -alias ca -ext KU=dig -validity 365 | \
- $KT -keystore js.jks -importcert -alias pub
-
-# Keystore trust.jks: including CA only
-$KT -keystore js.jks -exportcert -alias ca | \
- $KT -keystore trust.jks -importcert -alias ca -noprompt
-
-# Keystore unrelated.jks: unrelated
-$KT -keystore unrelated.jks -genkeypair -alias nothing -dname CN=Nothing -validity 365
-
-
-################### 4 Tests #######################
-
-# Test 1: Sign should be OK
-
-$JARSIGNER -keystore js.jks -storepass changeit a.jar pub
-RESULT=$?
-echo $RESULT
-#[ $RESULT = 0 ] || exit 1
-
-# Test 2: Verify should be OK
-
-$JARSIGNER -keystore trust.jks -strict -verify a.jar
-RESULT=$?
-echo $RESULT
-#[ $RESULT = 0 ] || exit 2
-
-# Test 3: When no keystore is specified, the error is only
-# "chain invalid"
-
-$JARSIGNER -strict -verify a.jar
-RESULT=$?
-echo $RESULT
-#[ $RESULT = 4 ] || exit 3
-
-# Test 4: When unrelated keystore is specified, the error is
-# "chain invalid" and "not alias in keystore"
-
-$JARSIGNER -keystore unrelated.jks -strict -verify a.jar
-RESULT=$?
-echo $RESULT
-#[ $RESULT = 36 ] || exit 4
-
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/collator.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-#
-# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8021789
-# @summary jarsigner parses alias as command line option (depending on locale)
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-F=collator
-KS=collator.jks
-JFILE=collator.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit \
- -keyalg rsa -keystore $KS"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore $KS -storepass changeit"
-
-rm $F $KS $JFILE 2> /dev/null
-
-echo 12345 > $F
-$JAR cvf $JFILE $F
-
-ERR=""
-
-$KT -alias debug -dname CN=debug -genkey -validity 300 || ERR="$ERR 1"
-
-# use "debug" as alias name
-$JARSIGNER $JFILE debug || ERR="$ERR 2"
-
-# use "" as alias name (although there will be a warning)
-$JARSIGNER -verify $JFILE "" || ERR="$ERR 3"
-
-if [ "$ERR" = "" ]; then
- exit 0
-else
- echo "ERR is $ERR"
- exit 1
-fi
--- a/test/jdk/sun/security/tools/jarsigner/concise_jarsigner.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,247 +0,0 @@
-#
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6802846 8172529
-# @summary jarsigner needs enhanced cert validation(options)
-#
-# @run shell/timeout=240 concise_jarsigner.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-# Choose 1024-bit RSA to make sure it runs fine and fast on all platforms. In
-# fact, every keyalg/keysize combination is OK for this test.
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-KS=js.ks
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa -keysize 1024"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -debug"
-JAVAC="$TESTJAVA${FS}bin${FS}javac ${TESTTOOLVMOPTS} ${TESTJAVACOPTS}"
-
-rm $KS
-
-echo class A1 {} > A1.java
-echo class A2 {} > A2.java
-echo class A3 {} > A3.java
-echo class A4 {} > A4.java
-echo class A5 {} > A5.java
-echo class A6 {} > A6.java
-
-$JAVAC A1.java A2.java A3.java A4.java A5.java A6.java
-YEAR=`date +%Y`
-
-# ==========================================================
-# First part: output format
-# ==========================================================
-
-$KT -genkeypair -alias a1 -dname CN=a1 -validity 366
-$KT -genkeypair -alias a2 -dname CN=a2 -validity 366
-
-# a.jar includes 8 unsigned, 2 signed by a1 and a2, 2 signed by a3
-$JAR cvf a.jar A1.class A2.class
-$JARSIGNER -keystore $KS -storepass changeit a.jar a1
-$JAR uvf a.jar A3.class A4.class
-$JARSIGNER -keystore $KS -storepass changeit a.jar a2
-$JAR uvf a.jar A5.class A6.class
-
-# Verify OK
-$JARSIGNER -verify a.jar
-[ $? = 0 ] || exit $LINENO
-
-# 4(chainNotValidated)+16(hasUnsignedEntry)
-$JARSIGNER -verify a.jar -strict
-[ $? = 20 ] || exit $LINENO
-
-# 16(hasUnsignedEntry)
-$JARSIGNER -verify a.jar -strict -keystore $KS -storepass changeit
-[ $? = 16 ] || exit $LINENO
-
-# 16(hasUnsignedEntry)+32(notSignedByAlias)
-$JARSIGNER -verify a.jar a1 -strict -keystore $KS -storepass changeit
-[ $? = 48 ] || exit $LINENO
-
-# 16(hasUnsignedEntry)
-$JARSIGNER -verify a.jar a1 a2 -strict -keystore $KS -storepass changeit
-[ $? = 16 ] || exit $LINENO
-
-# 12 entries all together
-LINES=`$JARSIGNER -verify a.jar -verbose | grep $YEAR | wc -l`
-[ $LINES = 12 ] || exit $LINENO
-
-# 12 entries all listed
-LINES=`$JARSIGNER -verify a.jar -verbose:grouped | grep $YEAR | wc -l`
-[ $LINES = 12 ] || exit $LINENO
-
-# 4 groups: MANIFST, unrelated, signed, unsigned
-LINES=`$JARSIGNER -verify a.jar -verbose:summary | grep $YEAR | wc -l`
-[ $LINES = 4 ] || exit $LINENO
-
-# still 4 groups, but MANIFEST group has no other file
-LINES=`$JARSIGNER -verify a.jar -verbose:summary | grep "more)" | wc -l`
-[ $LINES = 3 ] || exit $LINENO
-
-# 5 groups: MANIFEST, unrelated, signed by a1/a2, signed by a2, unsigned
-LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep $YEAR | wc -l`
-[ $LINES = 5 ] || exit $LINENO
-
-# 2 for MANIFEST, 2*2 for A1/A2, 2 for A3/A4
-LINES=`$JARSIGNER -verify a.jar -verbose -certs | grep "\[certificate" | wc -l`
-[ $LINES = 8 ] || exit $LINENO
-
-# a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4
-LINES=`$JARSIGNER -verify a.jar -verbose:grouped -certs | grep "\[certificate" | wc -l`
-[ $LINES = 5 ] || exit $LINENO
-
-# a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4
-LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep "\[certificate" | wc -l`
-[ $LINES = 5 ] || exit $LINENO
-
-# still 5 groups, but MANIFEST group has no other file
-LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep "more)" | wc -l`
-[ $LINES = 4 ] || exit $LINENO
-
-# ==========================================================
-# Second part: exit code 2, 4, 8.
-# 16 and 32 already covered in the first part
-# ==========================================================
-
-$KT -genkeypair -alias ca -dname CN=ca -ext bc -validity 365
-$KT -genkeypair -alias expired -dname CN=expired
-$KT -certreq -alias expired | $KT -gencert -alias ca -startdate -10m | $KT -import -alias expired
-$KT -genkeypair -alias notyetvalid -dname CN=notyetvalid
-$KT -certreq -alias notyetvalid | $KT -gencert -alias ca -startdate +1m | $KT -import -alias notyetvalid
-$KT -genkeypair -alias badku -dname CN=badku
-$KT -certreq -alias badku | $KT -gencert -alias ca -ext KU=cRLSign -validity 365 | $KT -import -alias badku
-$KT -genkeypair -alias badeku -dname CN=badeku
-$KT -certreq -alias badeku | $KT -gencert -alias ca -ext EKU=sa -validity 365 | $KT -import -alias badeku
-$KT -genkeypair -alias goodku -dname CN=goodku
-$KT -certreq -alias goodku | $KT -gencert -alias ca -ext KU=dig -validity 365 | $KT -import -alias goodku
-$KT -genkeypair -alias goodeku -dname CN=goodeku
-$KT -certreq -alias goodeku | $KT -gencert -alias ca -ext EKU=codesign -validity 365 | $KT -import -alias goodeku
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar expired
-[ $? = 4 ] || exit $LINENO
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar notyetvalid
-[ $? = 4 ] || exit $LINENO
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badku
-[ $? = 8 ] || exit $LINENO
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badeku
-[ $? = 8 ] || exit $LINENO
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar goodku
-[ $? = 0 ] || exit $LINENO
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar goodeku
-[ $? = 0 ] || exit $LINENO
-
-# badchain signed by ca1, but ca1 is removed later
-$KT -genkeypair -alias badchain -dname CN=badchain -validity 365
-$KT -genkeypair -alias ca1 -dname CN=ca1 -ext bc -validity 365
-$KT -certreq -alias badchain | $KT -gencert -alias ca1 -validity 365 | \
- $KT -importcert -alias badchain
-# save ca1.cert for easy replay
-$KT -exportcert -file ca1.cert -alias ca1
-$KT -delete -alias ca1
-
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar badchain
-[ $? = 4 ] || exit $LINENO
-
-$JARSIGNER -verify a.jar
-[ $? = 0 ] || exit $LINENO
-
-# ==========================================================
-# Third part: -certchain test
-# ==========================================================
-
-# altchain signed by ca2
-$KT -genkeypair -alias altchain -dname CN=altchain -validity 365
-$KT -genkeypair -alias ca2 -dname CN=ca2 -ext bc -validity 365
-$KT -certreq -alias altchain | $KT -gencert -alias ca2 -validity 365 -rfc > certchain
-$KT -exportcert -alias ca2 -rfc >> certchain
-
-# Self-signed cert does not work
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar altchain
-[ $? = 4 ] || exit $LINENO
-
-# -certchain works
-$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
-[ $? = 0 ] || exit $LINENO
-
-# if ca2 is removed, -certchain still work because altchain is a self-signed entry and
-# it is trusted by jarsigner
-# save ca2.cert for easy replay
-$KT -exportcert -file ca2.cert -alias ca2
-$KT -delete -alias ca2
-$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
-[ $? = 0 ] || exit $LINENO
-
-# if cert is imported, -certchain won't work because this certificate entry is not trusted
-$KT -importcert -file certchain -alias altchain -noprompt
-$JARSIGNER -strict -keystore $KS -storepass changeit -certchain certchain a.jar altchain
-[ $? = 4 ] || exit $LINENO
-
-$JARSIGNER -verify a.jar
-[ $? = 0 ] || exit $LINENO
-
-# ==========================================================
-# 8172529
-# ==========================================================
-
-$KT -genkeypair -alias ee -dname CN=ee
-$KT -genkeypair -alias caone -dname CN=caone
-$KT -genkeypair -alias catwo -dname CN=catwo
-
-$KT -certreq -alias ee | $KT -gencert -alias catwo -rfc > ee.cert
-$KT -certreq -alias catwo | $KT -gencert -alias caone -sigalg MD5withRSA -rfc > catwo.cert
-
-# This certchain contains a cross-signed weak catwo.cert
-cat ee.cert catwo.cert | $KT -importcert -alias ee
-
-$JAR cvf a.jar A1.class
-$JARSIGNER -strict -keystore $KS -storepass changeit a.jar ee
-[ $? = 0 ] || exit $LINENO
-$JARSIGNER -strict -keystore $KS -storepass changeit -verify a.jar
-[ $? = 0 ] || exit $LINENO
-
-echo OK
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/crl.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-#
-# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6890876 6950931
-# @summary jarsigner can add CRL info into signed jar (updated)
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-
-OS=`uname -s`
-case "$OS" in
- Windows* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=crl.jks
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa"
-
-rm $KS 2> /dev/null
-
-# Test keytool -gencrl
-
-$KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
-$KT -alias a -gencrl -id 1:1 -id 2:2 -file crl1 || exit 1
-$KT -alias a -gencrl -id 3:3 -id 4:4 -file crl2 || exit 2
-$KT -alias a -gencrl -id 5:1 -id 6:2 -file crl3 || exit 4
-
-# Test keytool -printcrl
-
-$KT -printcrl -file crl1 || exit 5
-$KT -printcrl -file crl2 || exit 6
-$KT -printcrl -file crl3 || exit 7
-
-
-# Test keytool -ext crl
-
-$KT -alias b -dname CN=c -keyalg rsa -genkey -validity 300 \
- -ext crl=uri:http://www.example.com/crl || exit 10
-
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/default_options.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,68 +0,0 @@
-#
-# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8049834
-# @summary Two security tools tests do not run with only JRE
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-PASS=changeit
-export PASS
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-KS=ks
-KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -storepass:env PASS -keypass:env PASS -keystore $KS"
-JAR="$TESTJAVA/bin/jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA/bin/jarsigner ${TESTTOOLVMOPTS}"
-
-rm $KS 2> /dev/null
-
-$KEYTOOL -genkeypair -dname CN=A -alias a -keyalg rsa || exit 1
-$KEYTOOL -genkeypair -dname CN=CA -alias ca -keyalg rsa || exit 2
-$KEYTOOL -alias a -certreq |
- $KEYTOOL -alias ca -gencert |
- $KEYTOOL -alias a -import || exit 3
-
-cat <<EOF > js.conf
-jarsigner.all = -keystore \${user.dir}/$KS -storepass:env PASS -debug -strict
-jarsigner.sign = -digestalg SHA1
-jarsigner.verify = -verbose:summary
-
-EOF
-
-$JAR cvf a.jar ks js.conf
-
-$JARSIGNER -conf js.conf a.jar a || exit 21
-$JARSIGNER -conf js.conf -verify a.jar > jarsigner.out || exit 22
-grep "and 1 more" jarsigner.out || exit 23
-$JAR xvf a.jar META-INF/MANIFEST.MF
-grep "SHA1-Digest" META-INF/MANIFEST.MF || exit 24
-
-echo Done
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/diffend.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,110 +0,0 @@
-#
-# Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6948909
-# @summary Jarsigner removes MANIFEST.MF info for badly packages jar's
-#
-
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- CP="${FS}bin${FS}cp -f"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- CP="cp -f"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- CP="cp -f"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-echo 1 > 1
-mkdir META-INF
-
-# Create a fake .RSA file so that jarsigner believes it's signed
-
-touch META-INF/x.RSA
-
-# A MANIFEST.MF using \n as newlines and no double newlines at the end
-
-cat > META-INF/MANIFEST.MF <<EOF
-Manifest-Version: 1.0
-Created-By: 1.7.0-internal (Sun Microsystems Inc.)
-Today: Monday
-EOF
-
-# With the fake .RSA file, to trigger the if (wasSigned) block
-
-rm diffend.jar
-zip diffend.jar META-INF/MANIFEST.MF META-INF/x.RSA 1
-
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg SHA1 \
- -signedjar diffend.new.jar \
- diffend.jar c
-
-unzip -p diffend.new.jar META-INF/MANIFEST.MF | grep Today || exit 1
-
-# Without the fake .RSA file, to trigger the else block
-
-rm diffend.jar
-zip diffend.jar META-INF/MANIFEST.MF 1
-
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg SHA1 \
- -signedjar diffend.new.jar \
- diffend.jar c
-
-unzip -p diffend.new.jar META-INF/MANIFEST.MF | grep Today || exit 2
-
--- a/test/jdk/sun/security/tools/jarsigner/ec.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-#
-# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6870812
-# @summary enhance security tools to use ECC algorithm
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=ec.jks
-JFILE=ec.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS}"
-
-rm $KS $JFILE
-echo A > A
-$JAR cvf $JFILE A
-
-$KT -alias ca -dname CN=ca -keyalg ec -genkey -validity 300 || exit 11
-
-$KT -alias a -dname CN=a -keyalg ec -genkey || exit 11
-$KT -alias a -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias a || exit 111
-
-$KT -alias b -dname CN=b -keyalg ec -genkey || exit 12
-$KT -alias b -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias b || exit 121
-
-# Ensure that key length is sufficient for the intended hash (SHA512withECDSA)
-$KT -alias c -dname CN=c -keyalg ec -genkey -keysize 521 || exit 13
-$KT -alias c -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias c || exit 131
-
-$KT -alias x -dname CN=x -keyalg ec -genkey -validity 300 || exit 14
-$KT -alias x -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias x || exit 141
-
-$JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 21
-$JARSIGNER -keystore $KS -storepass changeit $JFILE b -debug -strict -sigalg SHA1withECDSA || exit 22
-$JARSIGNER -keystore $KS -storepass changeit $JFILE c -debug -strict -sigalg SHA512withECDSA || exit 23
-
-$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE a -debug -strict || exit 31
-$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE b -debug -strict || exit 32
-$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE c -debug -strict || exit 33
-
-# Not signed by x, should exit with non-zero
-$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE x -debug -strict && exit 34
-
-exit 0
-
--- a/test/jdk/sun/security/tools/jarsigner/emptymanifest.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-#
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6712755
-# @summary jarsigner fails to sign itextasian.jar since 1.5.0_b14, it works with 1.5.0_13
-#
-# @run shell emptymanifest.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=emptymanifest.ks
-JFILE=em.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JAVA="$TESTJAVA${FS}bin${FS}java ${TESTVMOPTS}"
-JAVAC="$TESTJAVA${FS}bin${FS}javac ${TESTTOOLVMOPTS} ${TESTJAVACOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore $KS -storepass changeit"
-
-rm $KS $JFILE
-echo A > A
-echo B > B
-mkdir META-INF
-cat <<EOF > CrLf.java
-class CrLf {
- public static void main(String[] args) throws Exception {
- System.out.write(new byte[] {'\r', '\n'});
- }
-}
-EOF
-$JAVAC CrLf.java
-$JAVA CrLf > META-INF${FS}MANIFEST.MF
-zip $JFILE META-INF${FS}MANIFEST.MF A B
-
-$KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
-
-$JARSIGNER $JFILE a || exit 1
-$JARSIGNER -verify -debug -strict $JFILE || exit 2
-
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/jvindex.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,74 +0,0 @@
-#
-# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8022761
-# @summary regression: SecurityException is NOT thrown while trying to pack a wrongly signed Indexed Jar file
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-F=abcde
-KS=jvindex.jks
-JFILE=jvindex.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit \
- -keystore $KS -keyalg rsa"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore $KS -storepass changeit"
-
-rm $F $KS $JFILE 2> /dev/null
-
-echo 12345 > $F
-$JAR cvf $JFILE $F
-
-ERR=""
-
-$KT -alias a -dname CN=a -genkey -validity 300 || ERR="$ERR 1"
-
-$JARSIGNER $JFILE a || ERR="$ERR 2"
-$JAR i $JFILE
-
-# Make sure the $F line has "sm" (signed and in manifest)
-$JARSIGNER -verify -verbose $JFILE | grep $F | grep sm || ERR="$ERR 3"
-
-if [ "$ERR" = "" ]; then
- exit 0
-else
- echo "ERR is $ERR"
- exit 1
-fi
--- a/test/jdk/sun/security/tools/jarsigner/nameclash.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-#
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6876328
-# @summary different names for the same digest algorithms breaks jarsigner
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=nc.ks
-JFILE=nc.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore $KS -storepass changeit"
-
-rm $KS $JFILE
-
-$KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
-$KT -alias b -dname CN=b -keyalg rsa -genkey -validity 300
-
-echo A > A
-$JAR cvf $JFILE A
-
-$JARSIGNER $JFILE a -digestalg SHA1 || exit 1
-$JARSIGNER $JFILE b -digestalg SHA-1 || exit 2
-
-$JARSIGNER -verify -debug -strict $JFILE || exit 3
-
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/newsize7.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-#
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6561126
-# @summary keytool should use larger default keysize for keypairs
-#
-# @run shell newsize7.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVA_CMD=`which java`
- TESTJAVA=`dirname $JAVA_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KSFILE=ns7.jks
-
-KT="${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -keystore ns7.jks -storepass changeit -keypass changeit -keyalg rsa"
-JAR="${TESTJAVA}${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JS="${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -keystore ns7.jks -storepass changeit"
-
-rm ns7.*
-
-$KT -genkeypair -alias me -dname CN=Me
-
-touch ns7.txt
-$JAR cvf ns7.jar ns7.txt
-
-$JS ns7.jar me
-$JAR xvf ns7.jar
-
-grep SHA-256 META-INF/MANIFEST.MF || exit 1
-grep SHA-256 META-INF/ME.SF || exit 2
-
-#rm -rf META-INF
-
-exit 0
--- a/test/jdk/sun/security/tools/jarsigner/oldsig.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-#
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6543940 6868865
-# @summary Exception thrown when signing a jarfile in java 1.5
-#
-# @run shell oldsig.sh
-
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- CP="${FS}bin${FS}cp -f"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- CP="cp -f"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- CP="cp -f"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# copy jar file into writeable location
-${CP} ${TESTSRC}${FS}oldsig${FS}A.jar B.jar
-${CP} ${TESTSRC}${FS}oldsig${FS}A.class B.class
-
-${TESTJAVA}${FS}bin${FS}jar ${TESTTOOLVMOPTS} uvf B.jar B.class
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} \
- -keystore ${TESTSRC}${FS}JarSigning.keystore \
- -storepass bbbbbb \
- -digestalg SHA1 \
- B.jar c
-${TESTJAVA}${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -verify B.jar
--- a/test/jdk/sun/security/tools/jarsigner/onlymanifest.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,70 +0,0 @@
-#
-# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 7004035
-# @summary signed jar with only META-INF/* inside is not verifiable
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=onlymanifest.jks
-JFILE=onlymanifest.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit \
- -keystore $KS -keyalg rsa"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS}"
-
-rm $KS $JFILE 2> /dev/null
-
-# Create an empty jar file with only MANIFEST.MF
-
-echo "Key: Value" > manifest
-$JAR cvfm $JFILE manifest
-
-$KT -alias ca -dname CN=ca -genkey -validity 300 || exit 1
-$KT -alias a -dname CN=a -genkey -validity 300 || exit 2
-$KT -alias a -certreq | $KT -gencert -alias ca -validity 300 | $KT -import -alias a || exit 3
-$JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 4
-$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE a -debug -strict \
- > onlymanifest.out || exit 5
-
-grep unsigned onlymanifest.out && exit 6
-
-exit 0
-
--- a/test/jdk/sun/security/tools/jarsigner/passtype.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-#
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6868579
-# @summary RFE: jarsigner to support reading password from environment variable
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=pt.ks
-JFILE=pt.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -keystore $KS -validity 300 -keyalg rsa"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS}"
-
-rm $KS $JFILE
-
-$KT -alias a -dname CN=a -keyalg rsa -genkey \
- -storepass test12 -keypass test12 || exit 1
-PASSENV=test12 $KT -alias b -dname CN=b -keyalg rsa -genkey \
- -storepass:env PASSENV -keypass:env PASSENV || exit 2
-echo test12 > passfile
-$KT -alias c -dname CN=c -keyalg rsa -genkey \
- -storepass:file passfile -keypass:file passfile || exit 3
-
-echo A > A
-$JAR cvf $JFILE A
-
-# Sign
-$JARSIGNER -keystore $KS -storepass test12 $JFILE a || exit 4
-PASSENV=test12 $JARSIGNER -keystore $KS -storepass:env PASSENV $JFILE b || exit 5
-$JARSIGNER -keystore $KS -storepass:file passfile $JFILE b || exit 6
-
-# Verify
-$JARSIGNER -keystore $KS -storepass test12 -verify -debug -strict $JFILE || exit 7
-PASSENV=test12 $JARSIGNER -keystore $KS -storepass:env PASSENV -verify -debug -strict $JFILE || exit 8
-$JARSIGNER -keystore $KS -storepass:file passfile -verify -debug -strict $JFILE || exit 9
-
-exit 0
-
--- a/test/jdk/sun/security/tools/jarsigner/samename.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-#
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6866479
-# @summary libzip.so caused JVM to crash when running jarsigner
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* | CYGWIN* )
- SIGNEDJAR=EM.jar
- FS="\\"
- ;;
- * )
- SIGNEDJAR=em.jar
- FS="/"
- ;;
-esac
-
-KS=samename.jks
-JFILE=em.jar
-
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa"
-JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
-JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS}"
-
-rm $KS $JFILE $SIGNEDJAR
-echo A > A
-$JAR cvf $JFILE A
-
-$KT -alias a -dname CN=a -keyalg rsa -genkey -validity 300
-
-$JARSIGNER -keystore $KS -storepass changeit -signedjar $SIGNEDJAR $JFILE a
-
--- a/test/jdk/sun/security/tools/jarsigner/weaksize.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,62 +0,0 @@
-#
-# Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 8044755
-# @summary Add a test for algorithm constraints check in jarsigner
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-# The sigalg used is MD2withRSA, which is obsolete.
-
-KT="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -keystore ks
- -storepass changeit -keypass changeit
- -keyalg rsa -sigalg MD2withRSA -debug"
-JS="$TESTJAVA/bin/jarsigner ${TESTTOOLVMOPTS} -keystore ks
- -storepass changeit -strict -debug"
-JAR="$TESTJAVA/bin/jar ${TESTTOOLVMOPTS}"
-
-rm ks 2> /dev/null
-
-$KT -genkeypair -alias ca -dname CN=CA -ext bc
-$KT -genkeypair -alias signer -dname CN=Signer
-
-$KT -certreq -alias signer | \
- $KT -gencert -alias ca -ext ku=dS -rfc | \
- $KT -importcert -alias signer
-
-$JAR cvf a.jar ks
-
-# We always trust a TrustedCertificateEntry
-$JS a.jar ca | grep "chain is invalid" && exit 1
-
-# An end-entity cert must follow algorithm constraints
-$JS a.jar signer | grep "chain is invalid" || exit 2
-
-exit 0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/CloneKeyAskPassword.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2004, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6178366
+ * @library /test/lib
+ * @summary confirm that keytool correctly finds (and clones) a private key
+ * when the user is prompted for the key's password.
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+
+public class CloneKeyAskPassword {
+ public static void main(String[] args) throws Exception {
+
+ // Different storepass and keypass
+ Files.copy(Path.of(
+ System.getProperty("test.src"), "CloneKeyAskPassword.jks"),
+ Path.of("CloneKeyAskPassword.jks"));
+
+ // Clone with original keypass
+ SecurityTools.setResponse("test456", "");
+ SecurityTools.keytool(
+ "-keyclone",
+ "-alias", "mykey",
+ "-dest", "myclone1",
+ "-keystore", "CloneKeyAskPassword.jks",
+ "-storepass", "test123").shouldHaveExitValue(0);
+
+ // Clone with new keypass
+ SecurityTools.setResponse("test456", "test789", "test789");
+ SecurityTools.keytool(
+ "-keyclone",
+ "-alias", "mykey",
+ "-dest", "myclone2",
+ "-keystore", "CloneKeyAskPassword.jks",
+ "-storepass", "test123").shouldHaveExitValue(0);
+
+ KeyStore ks = KeyStore.getInstance(
+ new File("CloneKeyAskPassword.jks"), "test123".toCharArray());
+ Asserts.assertNotNull(ks.getKey("myclone1", "test456".toCharArray()));
+ Asserts.assertNotNull(ks.getKey("myclone2", "test789".toCharArray()));
+ }
+}
--- a/test/jdk/sun/security/tools/keytool/CloneKeyAskPassword.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-#
-# Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6178366
-# @summary confirm that keytool correctly finds (and clones) a private key
-# when the user is prompted for the key's password.
-#
-# @run shell CloneKeyAskPassword.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS )
- PATHSEP=":"
- FILESEP="/"
- ;;
- Linux )
- PATHSEP=":"
- FILESEP="/"
- ;;
- Darwin )
- PATHSEP=":"
- FILESEP="/"
- ;;
- AIX )
- PATHSEP=":"
- FILESEP="/"
- ;;
- CYGWIN* )
- PATHSEP=";"
- FILESEP="/"
- ;;
- Windows* )
- PATHSEP=";"
- FILESEP="\\"
- ;;
- * )
- echo "Unrecognized system!"
- exit 1;
- ;;
-esac
-
-# get a writeable keystore
-cp ${TESTSRC}${FILESEP}CloneKeyAskPassword.jks .
-chmod 644 CloneKeyAskPassword.jks
-
-# run the test: attempt to clone the private key
-${TESTJAVA}${FILESEP}bin${FILESEP}keytool ${TESTTOOLVMOPTS} \
- -keyclone \
- -alias mykey \
- -dest myclone \
- -keystore CloneKeyAskPassword.jks \
- -storepass test123 <<EOF
-test456
-EOF
-
-exit $?
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/DefaultOptions.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8023197
+ * @summary Pre-configured command line options for keytool and jarsigner
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class DefaultOptions {
+
+ public static void main(String[] args) throws Throwable {
+
+ Files.write(Path.of("kt.conf"), List.of(
+ "# A Pre-configured options file",
+ "keytool.all = -storepass:env PASS -keypass:env PASS "
+ + "-keystore ${user.dir}/ks -debug",
+ "keytool.genkey = -keyalg ec -ext bc",
+ "keytool.delete = -keystore nothing"));
+
+ // kt.conf is read
+ keytool("-conf kt.conf -genkeypair -dname CN=A -alias a")
+ .shouldHaveExitValue(0);
+ keytool("-conf kt.conf -list -alias a -v")
+ .shouldHaveExitValue(0)
+ .shouldMatch("Signature algorithm name.*ECDSA")
+ .shouldContain("BasicConstraints");
+
+ // kt.conf is read, and dup multi-valued options processed as expected
+ keytool("-conf kt.conf -genkeypair -dname CN=B -alias b -ext ku=ds")
+ .shouldHaveExitValue(0);
+ keytool("-conf kt.conf -list -alias b -v")
+ .shouldHaveExitValue(0)
+ .shouldContain("BasicConstraints")
+ .shouldContain("DigitalSignature");
+
+ // Single-valued option in command section override all
+ keytool("-conf kt.conf -delete -alias a")
+ .shouldNotHaveExitValue(0);
+
+ // Single-valued option on command line overrides again
+ keytool("-conf kt.conf -delete -alias b -keystore ks")
+ .shouldHaveExitValue(0);
+
+ // Error cases
+
+ // File does not exist
+ keytool("-conf no-such-file -help -list")
+ .shouldNotHaveExitValue(0);
+
+ // Cannot have both standard name (-genkeypair) and legacy name (-genkey)
+ Files.write(Path.of("bad.conf"), List.of(
+ "keytool.all = -storepass:env PASS -keypass:env PASS -keystore ks",
+ "keytool.genkeypair = -keyalg rsa",
+ "keytool.genkey = -keyalg ec"));
+
+ keytool("-conf bad.conf -genkeypair -alias me -dname cn=me")
+ .shouldNotHaveExitValue(0);
+
+ // Unknown options are rejected by tool
+ Files.write(Path.of("bad.conf"), List.of(
+ "keytool.all=-unknown"));
+
+ keytool("-conf bad.conf -help -list").shouldNotHaveExitValue(0);
+
+ // System property must be present
+ Files.write(Path.of("bad.conf"), List.of(
+ "keytool.all = -keystore ${no.such.prop}"));
+
+ keytool("-conf bad.conf -help -list").shouldNotHaveExitValue(0);
+ }
+
+ // Run keytool with one environment variable PASS=changeit
+ static OutputAnalyzer keytool(String cmd) throws Throwable {
+ ProcessBuilder pb = SecurityTools.getProcessBuilder(
+ "keytool", List.of(cmd.trim().split("\\s+")));
+ pb.environment().put("PASS", "changeit");
+ return ProcessTools.executeCommand(pb);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/EmptySubject.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6847026
+ * @summary keytool should be able to generate certreq and cert without subject name
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class EmptySubject{
+ static final String KS = "emptysubject.jks";
+ public static void main(String[] args) throws Exception {
+ kt("-alias", "ca", "-dname", "CN=CA", "-genkeypair");
+ kt("-alias", "me", "-dname", "CN=Me", "-genkeypair");
+
+ // When -dname is recognized, SAN must be specified, otherwise,
+ // -printcert fails.
+ kt("-alias", "me", "-certreq", "-dname", "", "-file", "me1.req")
+ .shouldHaveExitValue(0);
+ kt("-alias", "ca", "-gencert",
+ "-infile", "me1.req", "-outfile", "me1.crt")
+ .shouldHaveExitValue(0);
+ kt("-printcert", "-file", "me1.crt").shouldNotHaveExitValue(0);
+
+ kt("-alias", "me", "-certreq", "-file", "me2.req")
+ .shouldHaveExitValue(0);
+ kt("-alias", "ca", "-gencert", "-dname", "",
+ "-infile", "me2.req", "-outfile", "me2.crt")
+ .shouldHaveExitValue(0);
+ kt("-printcert", "-file", "me2.crt").shouldNotHaveExitValue(0);
+
+ kt("-alias", "me", "-certreq", "-dname", "", "-file", "me3.req")
+ .shouldHaveExitValue(0);
+ kt("-alias", "ca", "-gencert", "-ext", "san:c=email:me@me.com",
+ "-infile", "me3.req", "-outfile", "me3.crt")
+ .shouldHaveExitValue(0);
+ kt("-printcert", "-file", "me3.crt").shouldHaveExitValue(0);
+
+ kt("-alias", "me", "-certreq", "-file", "me4.req")
+ .shouldHaveExitValue(0);
+ kt("-alias", "ca", "-gencert", "-dname", "",
+ "-ext", "san:c=email:me@me.com",
+ "-infile", "me4.req", "-outfile", "me4.crt")
+ .shouldHaveExitValue(0);
+ kt("-printcert", "-file", "me4.crt").shouldHaveExitValue(0);
+ }
+
+ static OutputAnalyzer kt(String... s) throws Exception {
+ List<String> cmd = new ArrayList<>();
+ cmd.addAll(Arrays.asList(
+ "-storepass", "changeit",
+ "-keypass", "changeit",
+ "-keystore", KS,
+ "-keyalg", "rsa"));
+ cmd.addAll(Arrays.asList(s));
+ return SecurityTools.keytool(cmd);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/FileInHelp.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6922482
+ * @summary keytool's help on -file always shows 'output file'
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+public class FileInHelp {
+ public static void main(String[] args) throws Exception {
+ SecurityTools.keytool("-printcertreq -help")
+ .shouldHaveExitValue(0)
+ .shouldContain("input file");
+ SecurityTools.keytool("-exportcert -help")
+ .shouldHaveExitValue(0)
+ .shouldContain("output file");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/ImportReadAll.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6819272
+ * @summary keytool -importcert should read the whole input
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class ImportReadAll {
+ public static void main(String[] args) throws Exception {
+ keytool("-genkeypair -alias a -dname CN=a").shouldHaveExitValue(0);
+ keytool("-genkeypair -alias ca -dname CN=ca").shouldHaveExitValue(0);
+
+ keytool("-certreq -alias a -file a.req").shouldHaveExitValue(0);
+ keytool("-gencert -alias ca -infile a.req -outfile a.crt")
+ .shouldHaveExitValue(0);
+ keytool("-importcert -alias a -file a.crt").shouldHaveExitValue(0);
+ }
+
+ static OutputAnalyzer keytool(String s) throws Exception {
+ return SecurityTools.keytool(
+ "-keystore importreadall.jks "
+ + "-storepass changeit -keypass changeit -keyalg rsa " + s);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/KeyAlg.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8029659
+ * @summary Keytool, print key algorithm of certificate or key entry
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class KeyAlg {
+ public static void main(String[] args) throws Exception {
+ keytool("-genkeypair -alias ca -dname CN=CA -keyalg EC")
+ .shouldHaveExitValue(0);
+ keytool("-genkeypair -alias user -dname CN=User -keyalg RSA -keysize 1024")
+ .shouldHaveExitValue(0);
+ keytool("-certreq -alias user -file user.req").shouldHaveExitValue(0);
+ keytool("-gencert -alias ca -rfc -sigalg SHA1withECDSA"
+ + " -infile user.req -outfile user.crt")
+ .shouldHaveExitValue(0);
+ keytool("-printcert -file user.crt")
+ .shouldHaveExitValue(0)
+ .shouldMatch("Signature algorithm name:.*SHA1withECDSA")
+ .shouldMatch("Subject Public Key Algorithm:.*1024.*RSA");
+ }
+
+ static OutputAnalyzer keytool(String s) throws Exception {
+ return SecurityTools.keytool(
+ "-keystore ks -storepass changeit -keypass changeit " + s);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/NewHelp.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6324292
+ * @summary keytool -help is unhelpful
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+public class NewHelp {
+ public static void main(String[] args) throws Exception {
+ SecurityTools.keytool("-help")
+ .shouldHaveExitValue(0)
+ .shouldContain("Commands:");
+ SecurityTools.keytool("-help -list")
+ .shouldHaveExitValue(0)
+ .shouldContain("Options:");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/NoExtNPE.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6813402
+ * @summary keytool cannot -printcert entries without extensions
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+import java.nio.file.Path;
+
+public class NoExtNPE {
+ public static void main(String[] args) throws Exception {
+ SecurityTools.keytool("-list -v -keystore " +
+ Path.of(System.getProperty("test.src"), "CloneKeyAskPassword.jks")
+ + " -storepass test123").shouldHaveExitValue(0);
+ }
+}
--- a/test/jdk/sun/security/tools/keytool/NoExtNPE.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-#
-# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6813402
-# @summary keytool cannot -printcert entries without extensions
-#
-# @run shell NoExtNPE.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS )
- FILESEP="/"
- ;;
- Linux )
- FILESEP="/"
- ;;
- Darwin )
- FILESEP="/"
- ;;
- AIX )
- PATHSEP=":"
- FILESEP="/"
- ;;
- CYGWIN* )
- FILESEP="/"
- ;;
- Windows* )
- FILESEP="\\"
- ;;
- * )
- echo "Unrecognized system!"
- exit 1;
- ;;
-esac
-
-${TESTJAVA}${FILESEP}bin${FILESEP}keytool ${TESTTOOLVMOPTS} \
- -list -v \
- -keystore ${TESTSRC}${FILESEP}CloneKeyAskPassword.jks \
- -storepass test123
-
-exit $?
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/Resource.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6239297
+ * @summary keytool usage is broken after changing Resources.java
+ * @author Max Wang
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+public class Resource {
+ public static void main(String[] args) throws Exception {
+ SecurityTools.keytool()
+ .shouldNotContain("MissingResourceException");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/SecretKeyKS.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 4694076
+ * @summary KeyTool throws ArrayIndexOutOfBoundsException for listing
+ * SecretKey entries in non-verbose mode.
+ * @author Valerie Peng
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+
+import java.nio.file.Path;
+
+public class SecretKeyKS {
+ public static void main(String[] args) throws Exception {
+ SecurityTools.keytool("-list -keystore " +
+ Path.of(System.getProperty("test.src"), "SecretKeyKS.jks") +
+ " -storepass password").shouldHaveExitValue(0);
+ }
+}
--- a/test/jdk/sun/security/tools/keytool/SecretKeyKS.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-#
-# Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 4694076
-# @summary KeyTool throws ArrayIndexOutOfBoundsException for listing
-# SecretKey entries in non-verbose mode.
-# @author Valerie Peng
-#
-# @run shell SecretKeyKS.sh
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# the test code
-
-${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -list -keystore ${TESTSRC}${FS}SecretKeyKS.jks -storepass password
-
-exit $?
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/SecurityToolsTest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8180573
+ * @summary Enhance SecurityTools input line parsing
+ * @library /test/lib
+ */
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.SecurityTools;
+
+import java.util.List;
+
+public class SecurityToolsTest {
+ public static void main(String[] args) {
+ Asserts.assertEQ(SecurityTools.makeList("a b c"),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList(" a b c "),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("a\tb\nc"),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("a `b` c"),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("`a` b c"),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("a b `c`"),
+ List.of("a", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("`a b` b c"),
+ List.of("a b", "b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("`a b c`"),
+ List.of("a b c"));
+ Asserts.assertEQ(SecurityTools.makeList("a ` b ` c"),
+ List.of("a", " b ", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("a`b c"),
+ List.of("a`b", "c"));
+ Asserts.assertEQ(SecurityTools.makeList("a `\"b\"` c"),
+ List.of("a", "\"b\"", "c"));
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/SelfIssued.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 6825352 6937978
+ * @summary support self-issued certificate in keytool and let -gencert generate the chain
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class SelfIssued {
+ public static void main(String[] args) throws Exception {
+ keytool("-alias ca -dname CN=CA -genkeypair");
+ keytool("-alias ca1 -dname CN=CA1 -genkeypair");
+ keytool("-alias ca2 -dname CN=CA2 -genkeypair");
+ keytool("-alias e1 -dname CN=E1 -genkeypair");
+
+ // ca signs ca1, ca1 signs ca2, all self-issued
+ keytool("-alias ca1 -certreq -file ca1.req");
+ keytool("-alias ca -gencert -ext san=dns:ca1 "
+ + "-infile ca1.req -outfile ca1.crt");
+ keytool("-alias ca1 -importcert -file ca1.crt");
+
+ keytool("-alias ca2 -certreq -file ca2.req");
+ keytool("-alias ca1 -gencert -ext san=dns:ca2 "
+ + "-infile ca2.req -outfile ca2.crt");
+ keytool("-alias ca2 -importcert -file ca2.crt");
+
+ // Import e1 signed by ca2, should add ca2 and ca1, at least 3 certs in the chain
+ keytool("-alias e1 -certreq -file e1.req");
+ keytool("-alias ca2 -gencert -infile e1.req -outfile e1.crt");
+
+ keytool("-alias ca1 -delete");
+ keytool("-alias ca2 -delete");
+ keytool("-alias e1 -importcert -file e1.crt");
+ keytool("-alias e1 -list -v")
+ .shouldContain("[3]");
+ }
+
+ static OutputAnalyzer keytool(String s) throws Exception {
+ return SecurityTools.keytool("-storepass changeit -keypass changeit "
+ + "-keystore ks -keyalg rsa " + s);
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/StandardAlgName.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2004, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 4909889
+ * @summary KeyTool accepts any input that user make as long as we can make some
+ * sense out of it, but when comes to present the info the user, it
+ * promotes a standard look.
+ * @author Andrew Fan
+ * @library /test/lib
+ * @run main/timeout=240 StandardAlgName
+ */
+
+import jdk.test.lib.SecurityTools;
+
+public class StandardAlgName {
+ public static void main(String[] args) throws Exception {
+ // CA
+ SecurityTools.keytool("-genkey", "-v", "-alias", "pkcs12testCA",
+ "-keyalg", "RsA", "-keysize", "2048",
+ "-sigalg", "ShA1wItHRSA",
+ "-dname", "cn=PKCS12 Test CA, ou = Security SQE, o = JavaSoft, c = US",
+ "-validity", "3650",
+ "-keypass", "storepass", "-keystore", "keystoreCA.jceks.data",
+ "-storepass", "storepass", "-storetype", "jceKS")
+ .shouldHaveExitValue(0)
+ .shouldNotContain("RsA")
+ .shouldNotContain("ShA1wItHRSA")
+ .shouldContain("RSA")
+ .shouldContain("SHA1withRSA");
+
+ // Lead
+ SecurityTools.keytool("-genkey", "-v", "-alias", "pkcs12testLead",
+ "-keyalg", "rSA", "-keysize", "1024",
+ "-sigalg", "mD5withRSA",
+ "-dname", "cn=PKCS12 Test Lead, ou=Security SQE, o=JavaSoft, c=US",
+ "-validity", "3650",
+ "-keypass", "storepass", "-keystore", "keystoreLead.jceks.data",
+ "-storepass", "storepass", "-storetype", "jCeks")
+ .shouldHaveExitValue(0)
+ .shouldNotContain("rSA")
+ .shouldNotContain("mD5withRSA")
+ .shouldContain("RSA")
+ .shouldContain("MD5withRSA");
+
+ // End User 1
+ SecurityTools.keytool("-genkey", "-v", "-alias", "pkcs12testEndUser1",
+ "-keyalg", "RSa", "-keysize", "1024",
+ "-sigalg", "sHa1wIThRSA",
+ "-dname", "cn=PKCS12 Test End User 1, ou=Security SQE, o=JavaSoft, c=US",
+ "-validity", "3650",
+ "-keypass", "storepass", "-keystore", "keystoreEndUser1.jceks.data",
+ "-storepass", "storepass", "-storetype", "Jceks")
+ .shouldHaveExitValue(0)
+ .shouldNotContain("RSa")
+ .shouldNotContain("sHa1wIThRSA")
+ .shouldContain("RSA")
+ .shouldContain("SHA1withRSA");
+ }
+}
--- a/test/jdk/sun/security/tools/keytool/StandardAlgName.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-#
-# Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test 1.1 04/11/12
-# @bug 4909889
-# @summary KeyTool accepts any input that user make as long as we can make some
-# sense out of it, but when comes to present the info the user, it
-# promotes a standard look.
-# @author Andrew Fan
-#
-# @run shell/timeout=240 StandardAlgName.sh
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- PS=":"
- FS="/"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- ;;
- Windows_* )
- NULL=NUL
- PS=";"
- FS="\\"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# the test code
-#CA
-${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -genkey -v -alias pkcs12testCA -keyalg "RsA" -keysize 2048 -sigalg "ShA1wItHRSA" -dname "cn=PKCS12 Test CA, ou=Security SQE, o=JavaSoft, c=US" -validity 3650 -keypass storepass -keystore keystoreCA.jceks.data -storepass storepass -storetype jceKS 2>&1 | egrep 'RsA|ShA1wItHRSA'
-
-RESULT=$?
-if [ $RESULT -eq 0 ]; then
- exit 1
-else
- #Lead
- ${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -genkey -v -alias pkcs12testLead -keyalg "rSA" -keysize 1024 -sigalg "mD5withRSA" -dname "cn=PKCS12 Test Lead, ou=Security SQE, o=JavaSoft, c=US" -validity 3650 -keypass storepass -keystore keystoreLead.jceks.data -storepass storepass -storetype jCeks 2>&1 | egrep 'rSA|mD5withRSA'
- RESULT=$?
- if [ $RESULT -eq 0 ]; then
- exit 1
- else
- #End User 1
- ${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -genkey -v -alias pkcs12testEndUser1 -keyalg "RSa" -keysize 1024 -sigalg "sHa1wIThRSA" -dname "cn=PKCS12 Test End User 1, ou=Security SQE, o=JavaSoft, c=US" -validity 3650 -keypass storepass -keystore keystoreEndUser1.jceks.data -storepass storepass -storetype Jceks 2>&1 | egrep 'RSa|sHa1wIThRSA'
- RESULT=$?
- if [ $RESULT -eq 0 ]; then
- exit 1
- else
- exit 0
- fi
- fi
-fi
-
--- a/test/jdk/sun/security/tools/keytool/StorePasswords.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/tools/keytool/StorePasswords.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,12 @@
* @test
* @bug 8008296
* @summary Store and retrieve user passwords using PKCS#12 keystore
+ * @library /test/lib
*/
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
import java.io.*;
import java.security.*;
import java.util.*;
@@ -79,6 +83,18 @@
"recovered " + recoverCount + " user passwords");
new File(KEYSTORE).delete();
+
+ storeCount = storeByShell();
+ recoverCount = recoverByShell();
+
+ if (recoverCount != storeCount || storeCount < 11) {
+ throw new Exception("Stored " + storeCount + " user passwords, " +
+ "recovered " + recoverCount + " user passwords");
+ }
+ System.out.println("\nStored " + storeCount + " user passwords, " +
+ "recovered " + recoverCount + " user passwords");
+
+ new File(KEYSTORE).delete();
}
private static int store() throws Exception {
@@ -189,4 +205,35 @@
return count;
}
+
+ private static int storeByShell() throws Exception {
+ int count = 0;
+ for (String algorithm : PBE_ALGORITHMS) {
+ System.out.println("Storing user password (protected by " + algorithm + " )");
+ String importCmd = count < 5 ? "-importpassword" : "-importpass";
+ String keyAlg = algorithm.equals("default PBE algorithm")
+ ? "" : (" -keyalg " + algorithm);
+ SecurityTools.setResponse("hello1");
+ OutputAnalyzer oa = SecurityTools.keytool(importCmd
+ + " -storetype pkcs12 -keystore mykeystore.p12"
+ + " -storepass changeit -alias `this entry is protected by "
+ + algorithm + "`" + keyAlg);
+ if (oa.getExitValue() == 0) {
+ System.out.println("OK");
+ count++;
+ } else {
+ System.out.println("ERROR");
+ }
+ }
+ return count;
+ }
+
+ private static int recoverByShell() throws Exception {
+ return (int)SecurityTools.keytool("-list -storetype pkcs12"
+ + " -keystore mykeystore.p12 -storepass changeit")
+ .shouldHaveExitValue(0)
+ .asLines().stream()
+ .filter(s -> s.contains("this entry is protected by"))
+ .count();
+ }
}
--- a/test/jdk/sun/security/tools/keytool/StorePasswordsByShell.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,132 +0,0 @@
-#
-# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8008296
-# @summary confirm that keytool correctly imports user passwords
-#
-# @run shell StorePasswordsByShell.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX)
- PATHSEP=":"
- FILESEP="/"
- ;;
- CYGWIN* )
- PATHSEP=";"
- FILESEP="/"
- ;;
- Windows* )
- PATHSEP=";"
- FILESEP="\\"
- ;;
- * )
- echo "Unrecognized system!"
- exit 1;
- ;;
-esac
-
-PBE_ALGORITHMS="\
- default-PBE-algorithm \
- PBEWithMD5AndDES \
- PBEWithSHA1AndDESede \
- PBEWithSHA1AndRC2_40 \
- PBEWithSHA1AndRC2_128
- PBEWithSHA1AndRC4_40 \
- PBEWithSHA1AndRC4_128 \
- PBEWithHmacSHA1AndAES_128 \
- PBEWithHmacSHA224AndAES_128 \
- PBEWithHmacSHA256AndAES_128 \
- PBEWithHmacSHA384AndAES_128 \
- PBEWithHmacSHA512AndAES_128 \
- PBEWithHmacSHA1AndAES_256 \
- PBEWithHmacSHA224AndAES_256 \
- PBEWithHmacSHA256AndAES_256 \
- PBEWithHmacSHA384AndAES_256 \
- PBEWithHmacSHA512AndAES_256"
-
-USER_PWD="hello1\n"
-ALIAS_PREFIX="this entry is protected by "
-COUNTER=0
-
-# cleanup
-rm mykeystore.p12 > /dev/null 2>&1
-
-echo
-for i in $PBE_ALGORITHMS; do
-
- if [ $i = "default-PBE-algorithm" ]; then
- KEYALG=""
- else
- KEYALG="-keyalg ${i}"
- fi
-
- if [ $COUNTER -lt 5 ]; then
- IMPORTPASSWORD="-importpassword"
- else
- IMPORTPASSWORD="-importpass"
- fi
-
- echo "Storing user password (protected by ${i})"
- echo "${USER_PWD}" | \
- ${TESTJAVA}${FILESEP}bin${FILESEP}keytool ${TESTTOOLVMOPTS} ${IMPORTPASSWORD} \
- -storetype pkcs12 -keystore mykeystore.p12 -storepass changeit \
- -alias "${ALIAS_PREFIX}${i}" ${KEYALG} > /dev/null 2>&1
- if [ $? -ne 0 ]; then
- echo Error
- else
- echo OK
- COUNTER=`expr ${COUNTER} + 1`
- fi
-done
-echo
-
-COUNTER2=`${TESTJAVA}${FILESEP}bin${FILESEP}keytool ${TESTTOOLVMOPTS} -list -storetype pkcs12 \
- -keystore mykeystore.p12 -storepass changeit | grep -c "${ALIAS_PREFIX}"`
-
-RESULT="stored ${COUNTER} user passwords, detected ${COUNTER2} user passwords"
-if [ $COUNTER -ne $COUNTER2 -o $COUNTER -lt 11 ]; then
- echo "ERROR: $RESULT"
- exit 1
-else
- echo "OK: $RESULT"
- exit 0
-fi
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/tools/keytool/TryStore.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 7047200
+ * @summary keytool can try save to a byte array before overwrite the file
+ * @library /test/lib
+ */
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class TryStore {
+ public static void main(String[] args) throws Exception {
+ keytool("-genkeypair -alias a -dname CN=A -storepass changeit -keypass changeit");
+ keytool("-genkeypair -alias b -dname CN=B -storepass changeit -keypass changeit");
+
+ // We use -protected for JKS keystore. This is illegal so the command should
+ // fail. Then we can check if the keystore is damaged.
+
+ keytool("-genkeypair -protected -alias b -delete -debug")
+ .shouldNotHaveExitValue(0);
+
+ keytool("-list -storepass changeit")
+ .shouldHaveExitValue(0);
+ }
+
+ static OutputAnalyzer keytool(String s) throws Exception {
+ return SecurityTools.keytool(
+ "-storetype jks -keystore trystore.jks -keyalg rsa " + s);
+ }
+}
--- a/test/jdk/sun/security/tools/keytool/default_options.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,99 +0,0 @@
-#
-# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8023197
-# @summary Pre-configured command line options for keytool and jarsigner
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-KS=ks
-KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS}"
-
-rm $KS 2> /dev/null
-
-PASS=changeit
-export PASS
-
-cat <<EOF > kt.conf
-# A Pre-configured options file
-keytool.all = -storepass:env PASS -keypass:env PASS -keystore \${user.dir}/$KS -debug
-keytool.genkey = -keyalg ec -ext bc
-keytool.delete = -keystore nothing
-EOF
-
-# kt.conf is read
-$KEYTOOL -conf kt.conf -genkeypair -dname CN=A -alias a || exit 1
-$KEYTOOL -conf kt.conf -list -alias a -v > a_certinfo || exit 2
-grep "Signature algorithm name" a_certinfo | grep ECDSA || exit 3
-grep "BasicConstraints" a_certinfo || exit 4
-
-# kt.conf is read, and dup multi-valued options processed as expected
-$KEYTOOL -conf kt.conf -genkeypair -dname CN=B -alias b -ext ku=ds \
- || exit 11
-$KEYTOOL -conf kt.conf -list -alias b -v > b_certinfo || exit 12
-grep "BasicConstraints" b_certinfo || exit 14
-grep "DigitalSignature" b_certinfo || exit 15
-
-# Single-valued option in command section override all
-$KEYTOOL -conf kt.conf -delete -alias a && exit 16
-
-# Single-valued option on command line overrides again
-$KEYTOOL -conf kt.conf -delete -alias b -keystore $KS || exit 17
-
-# Error cases
-
-# File does not exist
-$KEYTOOL -conf no-such-file -help -list && exit 31
-
-# Cannot have both standard name (-genkeypair) and legacy name (-genkey)
-cat <<EOF > bad.conf
-keytool.all = -storepass:env PASS -keypass:env PASS -keystore ks
-keytool.genkeypair = -keyalg rsa
-keytool.genkey = -keyalg ec
-EOF
-
-$KEYTOOL -conf bad.conf -genkeypair -alias me -dname "cn=me" && exit 32
-
-# Unknown options are rejected by tool
-cat <<EOF > bad.conf
-keytool.all=-unknown
-EOF
-
-$KEYTOOL -conf bad.conf -help -list && exit 33
-
-# System property must be present
-cat <<EOF > bad.conf
-keytool.all = -keystore \${no.such.prop}
-EOF
-
-$KEYTOOL -conf bad.conf -help -list && exit 34
-
-echo Done
-exit 0
--- a/test/jdk/sun/security/tools/keytool/emptysubject.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,68 +0,0 @@
-#
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6847026
-# @summary keytool should be able to generate certreq and cert without subject name
-#
-# @run shell emptysubject.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=emptysubject.jks
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa"
-
-rm $KS
-
-$KT -alias ca -dname CN=CA -genkeypair
-$KT -alias me -dname CN=Me -genkeypair
-
-# When -dname is recognized, SAN must be specfied, otherwise, -printcert fails.
-$KT -alias me -certreq -dname "" | \
- $KT -alias ca -gencert | $KT -printcert && exit 1
-$KT -alias me -certreq | \
- $KT -alias ca -gencert -dname "" | $KT -printcert && exit 2
-$KT -alias me -certreq -dname "" | \
- $KT -alias ca -gencert -ext san:c=email:me@me.com | \
- $KT -printcert || exit 3
-$KT -alias me -certreq | \
- $KT -alias ca -gencert -dname "" -ext san:c=email:me@me.com | \
- $KT -printcert || exit 4
-
-exit 0
-
--- a/test/jdk/sun/security/tools/keytool/file-in-help.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-#
-# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6922482
-# @summary keytool's help on -file always shows 'output file'
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -printcertreq -help 2> h1 || exit 1
-$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -exportcert -help 2> h2 || exit 2
-
-grep "input file" h1 || exit 3
-grep "output file" h2 || exit 4
-
-exit 0
-
--- a/test/jdk/sun/security/tools/keytool/i18n.html Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/tools/keytool/i18n.html Sat Apr 13 07:23:18 2019 +0100
@@ -1,11 +1,7 @@
<html>
<body>
-<applet width=100 height=100 code=i18n.class>
-</applet>
-
-This is a multi-stage test. Click on "done" when you have completed
-reading these instructions. For each instruction, make sure the output
+This is a multi-stage test. For each instruction, make sure the output
from keytool is correct (you can read everything in english fine).
<ol>
@@ -115,7 +111,5 @@
If all the output (english) is correct, then the test passed.
Otherwise, the test failed.
-Press "Pass" if ... press "Fail" otherwise.
-
</body>
</html>
--- a/test/jdk/sun/security/tools/keytool/i18n.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/tools/keytool/i18n.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -21,8 +21,19 @@
* questions.
*/
-// This trivial file is only necessary to display instructions and "pass/fail"
-// buttons for a manual test.
-public class i18n extends java.applet.Applet
-{
+/*
+ * @test
+ * @bug 4348369 8076069
+ * @summary keytool not i18n compliant
+ * @author charlie lai
+ * @run main/manual i18n
+ */
+
+import java.nio.file.Path;
+
+public class i18n{
+ public static void main(String[] args) throws Exception {
+ System.out.println("see i18n.html");
+ System.out.println(Path.of(System.getProperty("test.jdk"), "bin", "keytool"));
+ }
}
--- a/test/jdk/sun/security/tools/keytool/i18n.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-#
-# Copyright (c) 2000, 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 4348369 8076069
-# @summary keytool not i18n compliant
-# @author charlie lai
-# @run shell/manual i18n.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- AIX | Darwin | Linux | SunOS )
- NULL=/dev/null
- PS=":"
- FS="/"
- ;;
- CYGWIN* )
- NULL=/dev/null
- PS=";"
- FS="/"
- ;;
- Windows* )
- NULL=NUL
- PS=";"
- FS="\\"
- ;;
- * )
- echo "Unrecognized system!"
- exit 1;
- ;;
-esac
-KEYTOOL=${TESTJAVA}${FS}bin${FS}keytool
-
-# the test code
-
-# see i18n.html
-
-exit $?
--- a/test/jdk/sun/security/tools/keytool/importreadall.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,62 +0,0 @@
-#
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6819272
-# @summary keytool -importcert should read the whole input
-#
-# @run shell importreadall.sh
-
-# set a few environment variables so that the shell-script can run stand-alone
-# in the source directory
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVA_CMD=`which java`
- TESTJAVA=`dirname $JAVA_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KEYTOOL="${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -keystore importreadall.jks -storepass changeit -keypass changeit -keyalg rsa"
-
-# In case the test is run twice in the same directory
-
-$KEYTOOL -delete -alias a
-$KEYTOOL -delete -alias ca
-$KEYTOOL -genkeypair -alias a -dname CN=a || exit 1
-$KEYTOOL -genkeypair -alias ca -dname CN=ca || exit 2
-$KEYTOOL -certreq -alias a | $KEYTOOL -gencert -alias ca | $KEYTOOL -importcert -alias a
-
-exit $?
--- a/test/jdk/sun/security/tools/keytool/keyalg.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-#
-# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 8029659
-# @summary Keytool, print key algorithm of certificate or key entry
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-KS=ks
-KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -keystore ks -storepass changeit -keypass changeit"
-
-rm $KS 2> /dev/null
-
-$KEYTOOL -genkeypair -alias ca -dname CN=CA -keyalg EC || exit 1
-$KEYTOOL -genkeypair -alias user -dname CN=User -keyalg RSA -keysize 1024 || exit 2
-$KEYTOOL -certreq -alias user |
- $KEYTOOL -gencert -alias ca -rfc -sigalg SHA1withECDSA |
- $KEYTOOL -printcert > user.dump || exit 3
-
-cat user.dump | grep "Signature algorithm name:" | grep SHA1withECDSA || exit 4
-cat user.dump | grep "Subject Public Key Algorithm:" | grep RSA | grep 1024 || exit 5
-
--- a/test/jdk/sun/security/tools/keytool/newhelp.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-#
-# Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6324292
-# @summary keytool -help is unhelpful
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
-
-$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -help 2> h1 || exit 1
-$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -help -list 2> h2 || exit 2
-
-grep Commands: h1 || exit 3
-grep Options: h2 || exit 4
-
-exit 0
-
--- a/test/jdk/sun/security/tools/keytool/resource.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,72 +0,0 @@
-#
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 6239297
-# @summary keytool usage is broken after changing Resources.java
-# @author Max Wang
-#
-# @run shell resource.sh
-
-if [ "${TESTSRC}" = "" ] ; then
- TESTSRC="."
-fi
-if [ "${TESTCLASSES}" = "" ] ; then
- TESTCLASSES="."
-fi
-if [ "${TESTJAVA}" = "" ] ; then
- echo "TESTJAVA not set. Test cannot execute."
- echo "FAILED!!!"
- exit 1
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- SunOS | Linux | Darwin | AIX )
- NULL=/dev/null
- FS="/"
- ;;
- CYGWIN* )
- NULL=/dev/null
- FS="/"
- ;;
- Windows_* )
- NULL=NUL
- FS="\\"
- ;;
- * )
- echo "Unrecognized operating system!"
- exit 1;
- ;;
-esac
-
-# the test code
-${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} > temp_file_40875602475 2> ${NULL}
-grep MissingResourceException temp_file_40875602475
-
-if [ $? -eq 0 ]; then
- exit 1
-fi
-
-exit 0
--- a/test/jdk/sun/security/tools/keytool/selfissued.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-#
-# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# @test
-# @bug 6825352 6937978
-# @summary support self-issued certificate in keytool and let -gencert generate the chain
-#
-# @run shell selfissued.sh
-#
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-KS=selfsigned.ks
-KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa"
-
-rm $KS
-
-$KT -alias ca -dname CN=CA -genkeypair
-$KT -alias ca1 -dname CN=CA1 -genkeypair
-$KT -alias ca2 -dname CN=CA2 -genkeypair
-$KT -alias e1 -dname CN=E1 -genkeypair
-
-# ca signs ca1, ca1 signs ca2, all self-issued
-$KT -alias ca1 -certreq | $KT -alias ca -gencert -ext san=dns:ca1 \
- | $KT -alias ca1 -importcert
-$KT -alias ca2 -certreq | $KT -alias ca1 -gencert -ext san=dns:ca2 \
- | $KT -alias ca2 -importcert
-
-# Import e1 signed by ca2, should add ca2 and ca1, at least 3 certs in the chain
-$KT -alias e1 -certreq | $KT -alias ca2 -gencert > e1.cert
-$KT -alias ca1 -delete
-$KT -alias ca2 -delete
-cat e1.cert | $KT -alias e1 -importcert
-$KT -alias e1 -list -v | grep '\[3\]' || { echo Bad E1; exit 1; }
-
-echo Good
-
--- a/test/jdk/sun/security/tools/keytool/trystore.sh Sat Apr 13 07:22:55 2019 +0100
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-#
-# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# 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 7047200
-# @summary keytool can try save to a byte array before overwrite the file
-
-if [ "${TESTJAVA}" = "" ] ; then
- JAVAC_CMD=`which javac`
- TESTJAVA=`dirname $JAVAC_CMD`/..
-fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
- Windows_* )
- FS="\\"
- ;;
- * )
- FS="/"
- ;;
-esac
-
-rm trystore.jks 2> /dev/null
-
-KEYTOOL="${TESTJAVA}${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storetype jks -keystore trystore.jks -keyalg rsa"
-$KEYTOOL -genkeypair -alias a -dname CN=A -storepass changeit -keypass changeit
-$KEYTOOL -genkeypair -alias b -dname CN=B -storepass changeit -keypass changeit
-
-# We use -protected for JKS keystore. This is illegal so the command should
-# fail. Then we can check if the keystore is damaged.
-
-$KEYTOOL -genkeypair -protected -alias b -delete -debug
-
-if [ $? = 0 ]; then
- echo "What? -protected works for JKS?"
- exit 1
-fi
-
-$KEYTOOL -list -storepass changeit
-
-if [ $? != 0 ]; then
- echo "Keystore file damaged"
- exit 2
-fi
--- a/test/jdk/sun/security/util/misc/SetNullSigParams.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/jdk/sun/security/util/misc/SetNullSigParams.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,8 @@
/*
* @test
- * @bug 8214096
- * @summary Make sure SignatureUtil can accept null algorithm parameters
+ * @bug 8214096 8216039
+ * @summary Make sure SignatureUtil works with null algorithm parameters
* @modules java.base/sun.security.util
*/
import java.security.*;
@@ -35,8 +35,8 @@
public static void main(String[] args) throws Exception {
Signature sig = new SpecialSigImpl();
- SignatureUtil.specialSetParameter(sig, (byte[]) null);
- SignatureUtil.specialSetParameter(sig, (AlgorithmParameters) null);
+ SignatureUtil.initVerifyWithParam(sig, (PublicKey) null, null);
+ SignatureUtil.initSignWithParam(sig, null, null, null);
}
// Sample Signature impl class which simulates 3rd party provider behavior
--- a/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLandmarkRegions.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLandmarkRegions.java Sat Apr 13 07:23:18 2019 +0100
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 8210047 8199892
+ * @bug 8210047 8199892 8215599
* @summary some pages contains content outside of landmark region
* @library /tools/lib ../../lib
* @modules
@@ -57,7 +57,6 @@
TestHtmlLandmarkRegions() {
tb = new ToolBox();
- setAutomaticCheckLinks(false); // @ignore 8217013
}
@Test
--- a/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java Sat Apr 13 07:23:18 2019 +0100
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 8190875
+ * @bug 8190875 8215599
* @summary modules not listed in overview/index page
* @library /tools/lib ../../lib
* @modules
@@ -83,7 +83,6 @@
//multiple modules with frames
@Test
public void testIndexWithMultipleModules1(Path base) throws Exception {
- setAutomaticCheckLinks(false); // @ignore 8217013
Path out = base.resolve("out");
javadoc("-d", out.toString(),
"--module-source-path", src.toString(),
@@ -98,7 +97,6 @@
"<a href=\"m1/module-summary.html\">m1</a>",
"<a href=\"m3/module-summary.html\">m3</a>",
"<a href=\"m4/module-summary.html\">m4</a>");
- setAutomaticCheckLinks(true); // @ignore 8217013
}
//multiple modules with out frames
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/T8222035/MinContextOpTest.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2019, Google LLC. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8222035
+ * @summary minimal inference context optimization is forcing resolution with incomplete constraints
+ * @compile/fail/ref=MinContextOpTest.out -XDrawDiagnostics MinContextOpTest.java
+ */
+
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collector;
+import java.util.stream.Stream;
+
+public class MinContextOpTest {
+ abstract class A {
+ abstract static class T<K> {
+ abstract String f();
+ }
+
+ abstract <E> Function<E, E> id();
+
+ abstract static class ImmutableMap<K, V> implements Map<K, V> {}
+
+ abstract <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
+ Function<? super T, ? extends K> k, Function<? super T, ? extends V> v);
+
+ ImmutableMap<String, T<?>> test(Stream<T> stream) {
+ return stream.collect(toImmutableMap(T::f, id()));
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/T8222035/MinContextOpTest.out Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,4 @@
+MinContextOpTest.java:38:25: compiler.err.mod.not.allowed.here: static
+MinContextOpTest.java:44:25: compiler.err.mod.not.allowed.here: static
+MinContextOpTest.java:50:34: compiler.err.prob.found.req: (compiler.misc.infer.no.conforming.assignment.exists: T,K,V,E, (compiler.misc.inconvertible.types: java.util.function.Function<MinContextOpTest.A.T,MinContextOpTest.A.T>, java.util.function.Function<? super MinContextOpTest.A.T,? extends MinContextOpTest.A.T<?>>))
+3 errors
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/api/lazy/LoadParameterNamesLazily.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8217047
+ * @summary Verify the parameter names can be injected using ParameterNameProvider.
+ * @library /tools/lib
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ * jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox
+ * @run main LoadParameterNamesLazily
+ */
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.ElementFilter;
+
+import com.sun.source.util.*;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.TestRunner;
+import toolbox.ToolBox;
+
+public class LoadParameterNamesLazily extends TestRunner {
+
+ public static void main(String... args) throws Exception {
+ LoadParameterNamesLazily t = new LoadParameterNamesLazily();
+ t.runTests();
+ }
+
+ private static final String libClass =
+ "package lib;" +
+ "/**Lib javadoc.*/" +
+ "public class Lib {" +
+ " /**Lib method javadoc.*/" +
+ " public static void m(int param, int other) {}" +
+ "}";
+ private final ToolBox tb = new ToolBox();
+
+ LoadParameterNamesLazily() throws IOException {
+ super(System.err);
+ }
+
+ @Test
+ public void testLoadTreesLazily() throws IOException {
+ Path libSrc = Paths.get("lib-src");
+ tb.writeJavaFiles(libSrc, libClass);
+ Path libClasses = Paths.get("lib-classes");
+ Files.createDirectories(libClasses);
+
+ new JavacTask(tb)
+ .outdir(libClasses)
+ .options()
+ .files(tb.findJavaFiles(libSrc))
+ .run(Task.Expect.SUCCESS)
+ .writeAll();
+
+ Path src = Paths.get("src");
+ tb.writeJavaFiles(src,
+ "class Use {" +
+ " lib.Lib lib;" +
+ "}");
+ Path classes = Paths.get("classes");
+ Files.createDirectories(classes);
+
+ new JavacTask(tb)
+ .outdir(classes)
+ .options("-classpath", libClasses.toString())
+ .files(tb.findJavaFiles(src))
+ .callback(task -> {
+ task.setParameterNameProvider(parameter -> {
+ ExecutableElement method = (ExecutableElement) parameter.getEnclosingElement();
+ TypeElement clazz =
+ (TypeElement) method.getEnclosingElement();
+ if (clazz.getQualifiedName().contentEquals("lib.Lib")) {
+ if (method.getParameters().indexOf(parameter) == 0) {
+ return "testName";
+ } else {
+ return null;
+ }
+ }
+ return null;
+ });
+ task.addTaskListener(new TaskListener() {
+ @Override
+ public void finished(TaskEvent e) {
+ if (e.getKind() == TaskEvent.Kind.ANALYZE) {
+ TypeElement lib = task.getElements().getTypeElement("lib.Lib");
+ lib.getClass(); //not null
+ ExecutableElement method =
+ ElementFilter.methodsIn(lib.getEnclosedElements()).get(0);
+ Name paramName0 = method.getParameters().get(0).getSimpleName();
+ if (!paramName0.contentEquals("testName")) {
+ throw new IllegalStateException("Unexpected parameter name: " +
+ paramName0);
+ }
+ Name paramName1 = method.getParameters().get(1).getSimpleName();
+ if (!paramName1.contentEquals("arg1")) {
+ throw new IllegalStateException("Unexpected parameter name: " +
+ paramName1);
+ }
+ }
+ }
+ });
+ })
+ .run(Task.Expect.SUCCESS)
+ .writeAll();
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/classreader/8215407/BrokenEnclosingClass.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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 8215407
+ * @summary Verify broken EnclosingMethod attribute does not break ClassReader.
+ * @library /tools/javac/lib
+ * @modules java.compiler
+ * @build JavacTestingAbstractProcessor
+ * @compile BrokenEnclosingClass.java UnrelatedClass.jcod Enclosing$1.jcod
+ * @compile -processor BrokenEnclosingClass BrokenEnclosingClass.java
+ */
+
+import java.util.Set;
+
+import javax.annotation.processing.RoundEnvironment;
+import javax.lang.model.element.TypeElement;
+
+public class BrokenEnclosingClass extends JavacTestingAbstractProcessor {
+
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+ if (processingEnv.getElementUtils().getTypeElement("UnrelatedClass") == null) {
+ throw new AssertionError("Cannot find UnrelatedClass.");
+ }
+ if (processingEnv.getElementUtils().getTypeElement("Enclosing$1") != null) {
+ throw new AssertionError("Enclosing$1 was found.");
+ }
+ return false;
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/classreader/8215407/Enclosing$1.jcod Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,91 @@
+class Enclosing$1 {
+ 0xCAFEBABE;
+ 0; // minor version
+ 52; // version
+ [] { // Constant Pool
+ ; // first element is empty
+ Field #3 #16; // #1
+ Method #4 #17; // #2
+ class #18; // #3
+ class #20; // #4
+ Utf8 "this$0"; // #5
+ Utf8 "LUnrelatedClass;"; // #6
+ Utf8 "<init>"; // #7
+ Utf8 "(LUnrelatedClass;)V"; // #8
+ Utf8 "Code"; // #9
+ Utf8 "LineNumberTable"; // #10
+ Utf8 "SourceFile"; // #11
+ Utf8 "Enclosing.java"; // #12
+ Utf8 "EnclosingMethod"; // #13
+ class #21; // #14
+ NameAndType #22 #23; // #15
+ NameAndType #5 #6; // #16
+ NameAndType #7 #23; // #17
+ Utf8 "Enclosing$1"; // #18
+ Utf8 "InnerClasses"; // #19
+ Utf8 "java/lang/Object"; // #20
+ Utf8 "UnrelatedClass"; // #21
+ Utf8 "t"; // #22
+ Utf8 "()V"; // #23
+ } // Constant Pool
+
+ 0x0020; // access
+ #3;// this_cpx
+ #4;// super_cpx
+
+ [] { // Interfaces
+ } // Interfaces
+
+ [] { // fields
+ { // Member
+ 0x1010; // access
+ #5; // name_cpx
+ #6; // sig_cpx
+ [] { // Attributes
+ } // Attributes
+ } // Member
+ } // fields
+
+ [] { // methods
+ { // Member
+ 0x0000; // access
+ #7; // name_cpx
+ #8; // sig_cpx
+ [] { // Attributes
+ Attr(#9) { // Code
+ 2; // max_stack
+ 2; // max_locals
+ Bytes[]{
+ 0x2A2BB500012AB700;
+ 0x02B1;
+ }
+ [] { // Traps
+ } // end Traps
+ [] { // Attributes
+ Attr(#10) { // LineNumberTable
+ [] { // LineNumberTable
+ 0 3;
+ }
+ } // end LineNumberTable
+ } // Attributes
+ } // end Code
+ } // Attributes
+ } // Member
+ } // methods
+
+ [] { // Attributes
+ Attr(#11) { // SourceFile
+ #12;
+ } // end SourceFile
+ ;
+ Attr(#13) { // EnclosingMethod
+ #14; #15;
+ } // end EnclosingMethod
+ ;
+ Attr(#19) { // InnerClasses
+ [] { // InnerClasses
+ #3 #0 #0 0;
+ }
+ } // end InnerClasses
+ } // Attributes
+} // end class Enclosing$1
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/classreader/8215407/UnrelatedClass.jcod Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,101 @@
+class UnrelatedClass {
+ 0xCAFEBABE;
+ 0; // minor version
+ 52; // version
+ [] { // Constant Pool
+ ; // first element is empty
+ Method #5 #14; // #1
+ class #15; // #2
+ Method #2 #16; // #3
+ class #17; // #4
+ class #18; // #5
+ Utf8 "InnerClasses"; // #6
+ Utf8 "<init>"; // #7
+ Utf8 "()V"; // #8
+ Utf8 "Code"; // #9
+ Utf8 "LineNumberTable"; // #10
+ Utf8 "t"; // #11
+ Utf8 "SourceFile"; // #12
+ Utf8 "Enclosing.java"; // #13
+ NameAndType #7 #8; // #14
+ Utf8 "Enclosing$1"; // #15
+ NameAndType #7 #19; // #16
+ Utf8 "UnrelatedClass"; // #17
+ Utf8 "java/lang/Object"; // #18
+ Utf8 "(LUnrelatedClass;)V"; // #19
+ } // Constant Pool
+
+ 0x0021; // access
+ #4;// this_cpx
+ #5;// super_cpx
+
+ [] { // Interfaces
+ } // Interfaces
+
+ [] { // fields
+ } // fields
+
+ [] { // methods
+ { // Member
+ 0x0001; // access
+ #7; // name_cpx
+ #8; // sig_cpx
+ [] { // Attributes
+ Attr(#9) { // Code
+ 1; // max_stack
+ 1; // max_locals
+ Bytes[]{
+ 0x2AB70001B1;
+ }
+ [] { // Traps
+ } // end Traps
+ [] { // Attributes
+ Attr(#10) { // LineNumberTable
+ [] { // LineNumberTable
+ 0 1;
+ }
+ } // end LineNumberTable
+ } // Attributes
+ } // end Code
+ } // Attributes
+ } // Member
+ ;
+ { // Member
+ 0x0001; // access
+ #11; // name_cpx
+ #8; // sig_cpx
+ [] { // Attributes
+ Attr(#9) { // Code
+ 3; // max_stack
+ 1; // max_locals
+ Bytes[]{
+ 0xBB0002592AB70003;
+ 0x57B1;
+ }
+ [] { // Traps
+ } // end Traps
+ [] { // Attributes
+ Attr(#10) { // LineNumberTable
+ [] { // LineNumberTable
+ 0 3;
+ 9 4;
+ }
+ } // end LineNumberTable
+ } // Attributes
+ } // end Code
+ } // Attributes
+ } // Member
+ } // methods
+
+ [] { // Attributes
+ Attr(#12) { // SourceFile
+ #13;
+ } // end SourceFile
+ ;
+ Attr(#6) { // InnerClasses
+ [] { // InnerClasses
+ #2 #0 #0 0;
+ }
+ } // end InnerClasses
+ } // Attributes
+} // end class UnrelatedClass
--- a/test/lib/jdk/test/lib/SecurityTools.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/lib/jdk/test/lib/SecurityTools.java Sat Apr 13 07:23:18 2019 +0100
@@ -28,6 +28,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -52,7 +53,7 @@
private SecurityTools() {}
- private static ProcessBuilder getProcessBuilder(String tool, List<String> args) {
+ public static ProcessBuilder getProcessBuilder(String tool, List<String> args) {
JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK(tool)
.addVMArg("-Duser.language=en")
.addVMArg("-Duser.country=US");
@@ -62,6 +63,9 @@
for (String arg : args) {
if (arg.startsWith("-J")) {
launcher.addVMArg(arg.substring(2));
+ } else if (Platform.isWindows() && arg.isEmpty()) {
+ // JDK-6518827: special handling for empty argument on Windows
+ launcher.addToolArg("\"\"");
} else {
launcher.addToolArg(arg);
}
@@ -97,14 +101,13 @@
/**
* Runs keytool.
*
- * @param args arguments to keytool in a single string. Only call this if
- * there is no white space inside an argument. This string will
- * be split with {@code \s+}.
+ * @param args arguments to keytool in a single string. The string is
+ * converted to be List with makeList.
* @return an {@link OutputAnalyzer} object
* @throws Exception if there is an error
*/
public static OutputAnalyzer keytool(String args) throws Exception {
- return keytool(args.split("\\s+"));
+ return keytool(makeList(args));
}
/**
@@ -174,15 +177,14 @@
/**
* Runs jarsigner.
*
- * @param args arguments to jarsigner in a single string. Only call this if
- * there is no white space inside an argument. This string will
- * be split with {@code \s+}.
+ * @param args arguments to jarsigner in a single string. The string is
+ * converted to be List with makeList.
* @return an {@link OutputAnalyzer} object
* @throws Exception if there is an error
*/
public static OutputAnalyzer jarsigner(String args) throws Exception {
- return jarsigner(args.split("\\s+"));
+ return jarsigner(makeList(args));
}
/**
@@ -199,29 +201,79 @@
/**
* Runs ktab.
*
- * @param args arguments to ktab in a single string. Only call this if
- * there is no white space inside an argument. This string will
- * be split with {@code \s+}.
+ * @param args arguments to ktab in a single string. The string is
+ * converted to be List with makeList.
* @return an {@link OutputAnalyzer} object
* @throws Exception if there is an error
*/
public static OutputAnalyzer ktab(String args) throws Exception {
- return execute(getProcessBuilder(
- "ktab", List.of(args.trim().split("\\s+"))));
+ return execute(getProcessBuilder("ktab", makeList(args)));
}
/**
* Runs klist.
*
- * @param args arguments to klist in a single string. Only call this if
- * there is no white space inside an argument. This string will
- * be split with {@code \s+}.
+ * @param args arguments to klist in a single string. The string is
+ * converted to be List with makeList.
* @return an {@link OutputAnalyzer} object
* @throws Exception if there is an error
*/
public static OutputAnalyzer klist(String args) throws Exception {
- return execute(getProcessBuilder(
- "klist", List.of(args.trim().split("\\s+"))));
+ return execute(getProcessBuilder("klist", makeList(args)));
+ }
+
+ /**
+ * Runs jar.
+ *
+ * @param args arguments to jar in a single string. The string is
+ * converted to be List with makeList.
+ * @return an {@link OutputAnalyzer} object
+ * @throws Exception if there is an error
+ */
+ public static OutputAnalyzer jar(String args) throws Exception {
+ return execute(getProcessBuilder("jar", makeList(args)));
+ }
+
+ /**
+ * Split a line to a list of string. All whitespaces are treated as
+ * delimiters unless quoted between ` and `.
+ *
+ * @param line the input
+ * @return the list
+ */
+ public static List<String> makeList(String line) {
+ List<String> result = new ArrayList<>();
+ StringBuilder sb = new StringBuilder();
+ boolean inBackTick = false;
+ for (char c : line.toCharArray()) {
+ if (inBackTick) {
+ if (c == '`') {
+ result.add(sb.toString());
+ sb.setLength(0);
+ inBackTick = false;
+ } else {
+ sb.append(c);
+ }
+ } else {
+ if (sb.length() == 0 && c == '`') {
+ // Allow ` inside a string
+ inBackTick = true;
+ } else {
+ if (Character.isWhitespace(c)) {
+ if (sb.length() != 0) {
+ result.add(sb.toString());
+ sb.setLength(0);
+ }
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ }
+ if (sb.length() != 0) {
+ result.add(sb.toString());
+ }
+ return result;
}
}
--- a/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java Sat Apr 13 07:23:18 2019 +0100
@@ -169,11 +169,17 @@
generateDockerFile(buildDir.resolve("Dockerfile"),
DockerfileConfig.getBaseImageName(),
DockerfileConfig.getBaseImageVersion());
-
- // Build the docker
- execute(DOCKER_COMMAND, "build", "--no-cache", "--tag", imageName, buildDir.toString())
- .shouldHaveExitValue(0)
- .shouldContain("Successfully built");
+ try {
+ // Build the docker
+ execute(DOCKER_COMMAND, "build", "--no-cache", "--tag", imageName, buildDir.toString())
+ .shouldHaveExitValue(0)
+ .shouldContain("Successfully built");
+ } catch (Exception e) {
+ // If docker image building fails there is a good chance it happens due to environment and/or
+ // configuration other than product failure. Throw jtreg skipped exception in such case
+ // instead of failing the test.
+ throw new SkippedException("Building docker image failed. Details: \n" + e.getMessage());
+ }
}
--- a/test/lib/sun/hotspot/WhiteBox.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/lib/sun/hotspot/WhiteBox.java Sat Apr 13 07:23:18 2019 +0100
@@ -541,7 +541,7 @@
public native void disableElfSectionCache();
// Resolved Method Table
- public native int resolvedMethodRemovedCount();
+ public native long resolvedMethodItemsCount();
// Protection Domain Table
public native int protectionDomainRemovedCount();
--- a/test/lib/sun/hotspot/gc/GC.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/lib/sun/hotspot/gc/GC.java Sat Apr 13 07:23:18 2019 +0100
@@ -70,4 +70,16 @@
public static boolean isSelectedErgonomically() {
return WB.isGCSelectedErgonomically();
}
+
+ /**
+ * @return the selected GC.
+ */
+ public static GC selected() {
+ for (GC gc : values()) {
+ if (gc.isSelected()) {
+ return gc;
+ }
+ }
+ throw new IllegalStateException("No selected GC found");
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/test/micro/org/openjdk/bench/java/lang/MathBench.java Sat Apr 13 07:23:18 2019 +0100
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package org.openjdk.bench.java.lang;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.CompilerControl;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Threads;
+
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Thread)
+public class MathBench {
+
+ @Param("0")
+ public long seed;
+
+ public int dividend;
+ public int divisor;
+
+ public long longDividend;
+ public long longDivisor;
+
+ @Setup
+ public void setupValues() {
+ Random random = new Random(seed);
+ dividend = Math.abs(random.nextInt() + 4711);
+ divisor = Math.abs(random.nextInt(dividend) + 17);
+ longDividend = Math.abs(random.nextLong() + 4711L);
+ longDivisor = Math.abs(random.nextLong() + longDividend);
+ }
+
+ @Benchmark
+ @CompilerControl(CompilerControl.Mode.DONT_INLINE)
+ public int floorModIntIntPositive() {
+ return Math.floorMod(dividend, divisor);
+ }
+
+ @Benchmark
+ @CompilerControl(CompilerControl.Mode.DONT_INLINE)
+ public int floorModIntInt() {
+ return Math.floorMod( dividend, divisor) +
+ Math.floorMod( dividend, -divisor) +
+ Math.floorMod(-dividend, divisor) +
+ Math.floorMod(-dividend, -divisor);
+ }
+
+ @Benchmark
+ @CompilerControl(CompilerControl.Mode.DONT_INLINE)
+ public int floorModLongInt() {
+ return Math.floorMod( longDividend, divisor) +
+ Math.floorMod( longDividend, -divisor) +
+ Math.floorMod(-longDividend, divisor) +
+ Math.floorMod(-longDividend, -divisor);
+ }
+
+ @Benchmark
+ @CompilerControl(CompilerControl.Mode.DONT_INLINE)
+ public long floorModLongLong() {
+ return Math.floorMod( longDividend, longDivisor) +
+ Math.floorMod( longDividend, -longDivisor) +
+ Math.floorMod(-longDividend, longDivisor) +
+ Math.floorMod(-longDividend, -longDivisor);
+ }
+
+}
--- a/test/micro/org/openjdk/bench/java/lang/StringBuilders.java Sat Apr 13 07:22:55 2019 +0100
+++ b/test/micro/org/openjdk/bench/java/lang/StringBuilders.java Sat Apr 13 07:23:18 2019 +0100
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -42,6 +42,8 @@
private String[] str16p8p7;
private String[] str3p9p8;
private String[] str22p40p31;
+ private StringBuilder sbLatin1;
+ private StringBuilder sbUtf16;
@Setup
public void setup() {
@@ -53,6 +55,8 @@
str16p8p7 = new String[]{"1234567890123456", "12345678", "1234567"};
str3p9p8 = new String[]{"123", "123456789", "12345678"};
str22p40p31 = new String[]{"1234567890123456789012", "1234567890123456789012345678901234567890", "1234567890123456789012345678901"};
+ sbLatin1 = new StringBuilder("Latin1 string");
+ sbUtf16 = new StringBuilder("UTF-\uFF11\uFF16 string");
}
/** StringBuilder wins over StringMaker. */
@@ -256,4 +260,24 @@
result.append("stringelinglinglinglong");
return result.toString();
}
+
+ @Benchmark
+ public StringBuilder fromLatin1String() {
+ return new StringBuilder("Latin1 string");
+ }
+
+ @Benchmark
+ public StringBuilder fromUtf16String() {
+ return new StringBuilder("UTF-\uFF11\uFF16 string");
+ }
+
+ @Benchmark
+ public StringBuilder fromLatin1StringBuilder() {
+ return new StringBuilder(sbLatin1);
+ }
+
+ @Benchmark
+ public StringBuilder fromUtf16StringBuilder() {
+ return new StringBuilder(sbUtf16);
+ }
}