From cdf49edb29d2b2e6ab920dbb59649beacf19ff68 Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Fri, 14 Dec 2018 06:39:14 +0100 Subject: [PATCH 001/174] Added tag jdk-12+24 for changeset 7d4397b43fa3 --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 479d7b40b59..f2d1a58c394 100644 --- a/.hgtags +++ b/.hgtags @@ -526,3 +526,4 @@ dc1f9dec2018a37fedba47d8a2aedef99faaec64 jdk-12+19 f8fb0c86f2b3d24294d39c5685a628e1beb14ba7 jdk-12+21 732bec44c89e8b93a38296bf690f97b7230c5b6d jdk-12+22 eef755718cb24813031a842bbfc716a6cea18e9a jdk-12+23 +7d4397b43fa305806160785a4c7210600d59581a jdk-12+24 From 78669ad35ec26f34690acacf3bc1a2bd45f46530 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Fri, 14 Dec 2018 12:02:39 +0100 Subject: [PATCH 002/174] 8215380: Backout accidental change to String::length Reviewed-by: darcy, smarks --- src/java.base/share/classes/java/lang/String.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index 9251e6c0895..be9f846341b 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -664,7 +664,7 @@ public final class String * object. */ public int length() { - return isLatin1() ? value.length : value.length >> UTF16; + return value.length >> coder(); } /** From 7f21b8e73b525d2dc0a14e13c8e8525342897ac4 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Fri, 14 Dec 2018 12:56:57 +0100 Subject: [PATCH 003/174] 8215353: x86_32 build failures after JDK-8214751 (X86: Support for VNNI Instructions) Reviewed-by: thartmann, kvn --- src/hotspot/cpu/x86/x86_32.ad | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/hotspot/cpu/x86/x86_32.ad b/src/hotspot/cpu/x86/x86_32.ad index 1c7d0f4440c..87ccfb6ee19 100644 --- a/src/hotspot/cpu/x86/x86_32.ad +++ b/src/hotspot/cpu/x86/x86_32.ad @@ -7760,9 +7760,9 @@ instruct mulAddS2I_rReg(rRegI dst, rRegI src1, rRegI src2, rRegI src3, eFlagsReg match(Set dst (MulAddS2I (Binary dst src1) (Binary src2 src3))); effect(KILL cr, KILL src2); - expand %{ mulI_rReg(dst, src1, cr); - mulI_rReg(src2, src3, cr); - addI_rReg(dst, src2, cr); %} + expand %{ mulI_eReg(dst, src1, cr); + mulI_eReg(src2, src3, cr); + addI_eReg(dst, src2, cr); %} %} // Multiply Register Int to Long From 80acd4f3996dbc5d2d7940bcb8da8d317ec4d2e7 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Fri, 14 Dec 2018 12:56:59 +0100 Subject: [PATCH 004/174] 8215374: 32-bit build failures after JDK-8181143 (Introduce diagnostic flag to abort VM on too long VM operations) Reviewed-by: roland --- src/hotspot/share/runtime/vmThread.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hotspot/share/runtime/vmThread.cpp b/src/hotspot/share/runtime/vmThread.cpp index c0667686f38..c2de946a0e6 100644 --- a/src/hotspot/share/runtime/vmThread.cpp +++ b/src/hotspot/share/runtime/vmThread.cpp @@ -206,7 +206,7 @@ void VMOperationTimeoutTask::task() { if (is_armed()) { jlong delay = (os::javaTimeMillis() - _arm_time); if (delay > AbortVMOnVMOperationTimeoutDelay) { - fatal("VM operation took too long: " SIZE_FORMAT " ms (timeout: " SIZE_FORMAT " ms)", + fatal("VM operation took too long: " JLONG_FORMAT " ms (timeout: " INTX_FORMAT " ms)", delay, AbortVMOnVMOperationTimeoutDelay); } } From dd6344fc769e588a4205070d33933db12bcc3e39 Mon Sep 17 00:00:00 2001 From: Yang Zhang Date: Wed, 28 Nov 2018 16:22:03 +0800 Subject: [PATCH 005/174] 8213134: AArch64: vector shift failed with MaxVectorSize=8 Add vshiftcnt instructions for vector64 and add vsra/vsrl instructions to AArch64 backend. To detect shift failures, MaxVectorSize options are added to jtreg test cases. Reviewed-by: aph, kvn --- src/hotspot/cpu/aarch64/aarch64.ad | 271 ++++++++++++++---- .../compiler/c2/cr6340864/TestByteVect.java | 3 + .../compiler/c2/cr6340864/TestDoubleVect.java | 3 + .../compiler/c2/cr6340864/TestFloatVect.java | 3 + .../compiler/c2/cr6340864/TestIntVect.java | 3 + .../compiler/c2/cr6340864/TestLongVect.java | 3 + .../compiler/c2/cr6340864/TestShortVect.java | 3 + .../jtreg/compiler/codegen/TestCharVect2.java | 3 + 8 files changed, 241 insertions(+), 51 deletions(-) diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index 9ba919947b8..ed575070c48 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -2133,7 +2133,12 @@ const uint Matcher::vector_ideal_reg(int len) { } const uint Matcher::vector_shift_count_ideal_reg(int size) { - return Op_VecX; + switch(size) { + case 8: return Op_VecD; + case 16: return Op_VecX; + } + ShouldNotReachHere(); + return 0; } // AES support not yet implemented @@ -16524,32 +16529,32 @@ instruct vxor16B(vecX dst, vecX src1, vecX src2) %} // ------------------------------ Shift --------------------------------------- - -instruct vshiftcntL(vecX dst, iRegIorL2I cnt) %{ +instruct vshiftcnt8B(vecD dst, iRegIorL2I cnt) %{ + predicate(n->as_Vector()->length_in_bytes() == 8); match(Set dst (LShiftCntV cnt)); - format %{ "dup $dst, $cnt\t# shift count (vecX)" %} - ins_encode %{ - __ dup(as_FloatRegister($dst$$reg), __ T16B, as_Register($cnt$$reg)); - %} - ins_pipe(vdup_reg_reg128); -%} - -// Right shifts on aarch64 SIMD are implemented as left shift by -ve amount -instruct vshiftcntR(vecX dst, iRegIorL2I cnt) %{ match(Set dst (RShiftCntV cnt)); - format %{ "dup $dst, $cnt\t# shift count (vecX)\n\tneg $dst, $dst\t T16B" %} + format %{ "dup $dst, $cnt\t# shift count vector (8B)" %} + ins_encode %{ + __ dup(as_FloatRegister($dst$$reg), __ T8B, as_Register($cnt$$reg)); + %} + ins_pipe(vdup_reg_reg64); +%} + +instruct vshiftcnt16B(vecX dst, iRegIorL2I cnt) %{ + predicate(n->as_Vector()->length_in_bytes() == 16); + match(Set dst (LShiftCntV cnt)); + match(Set dst (RShiftCntV cnt)); + format %{ "dup $dst, $cnt\t# shift count vector (16B)" %} ins_encode %{ __ dup(as_FloatRegister($dst$$reg), __ T16B, as_Register($cnt$$reg)); - __ negr(as_FloatRegister($dst$$reg), __ T16B, as_FloatRegister($dst$$reg)); %} ins_pipe(vdup_reg_reg128); %} -instruct vsll8B(vecD dst, vecD src, vecX shift) %{ +instruct vsll8B(vecD dst, vecD src, vecD shift) %{ predicate(n->as_Vector()->length() == 4 || n->as_Vector()->length() == 8); match(Set dst (LShiftVB src shift)); - match(Set dst (RShiftVB src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (8B)" %} ins_encode %{ @@ -16563,7 +16568,6 @@ instruct vsll8B(vecD dst, vecD src, vecX shift) %{ instruct vsll16B(vecX dst, vecX src, vecX shift) %{ predicate(n->as_Vector()->length() == 16); match(Set dst (LShiftVB src shift)); - match(Set dst (RShiftVB src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (16B)" %} ins_encode %{ @@ -16574,29 +16578,93 @@ instruct vsll16B(vecX dst, vecX src, vecX shift) %{ ins_pipe(vshift128); %} -instruct vsrl8B(vecD dst, vecD src, vecX shift) %{ +// Right shifts with vector shift count on aarch64 SIMD are implemented +// as left shift by negative shift count. +// There are two cases for vector shift count. +// +// Case 1: The vector shift count is from replication. +// | | +// LoadVector RShiftCntV +// | / +// RShiftVI +// Note: In inner loop, multiple neg instructions are used, which can be +// moved to outer loop and merge into one neg instruction. +// +// Case 2: The vector shift count is from loading. +// This case isn't supported by middle-end now. But it's supported by +// panama/vectorIntrinsics(JEP 338: Vector API). +// | | +// LoadVector LoadVector +// | / +// RShiftVI +// + +instruct vsra8B(vecD dst, vecD src, vecD shift, vecD tmp) %{ predicate(n->as_Vector()->length() == 4 || n->as_Vector()->length() == 8); - match(Set dst (URShiftVB src shift)); + match(Set dst (RShiftVB src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (8B)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (8B)" %} ins_encode %{ - __ ushl(as_FloatRegister($dst$$reg), __ T8B, - as_FloatRegister($src$$reg), + __ negr(as_FloatRegister($tmp$$reg), __ T8B, as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift64); %} -instruct vsrl16B(vecX dst, vecX src, vecX shift) %{ +instruct vsra16B(vecX dst, vecX src, vecX shift, vecX tmp) %{ + predicate(n->as_Vector()->length() == 16); + match(Set dst (RShiftVB src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (16B)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T16B, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift128); +%} + +instruct vsrl8B(vecD dst, vecD src, vecD shift, vecD tmp) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (URShiftVB src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (8B)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T8B, + as_FloatRegister($shift$$reg)); + __ ushl(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift64); +%} + +instruct vsrl16B(vecX dst, vecX src, vecX shift, vecX tmp) %{ predicate(n->as_Vector()->length() == 16); match(Set dst (URShiftVB src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (16B)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (16B)" %} ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); __ ushl(as_FloatRegister($dst$$reg), __ T16B, as_FloatRegister($src$$reg), - as_FloatRegister($shift$$reg)); + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift128); %} @@ -16708,11 +16776,10 @@ instruct vsrl16B_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(vshift128_imm); %} -instruct vsll4S(vecD dst, vecD src, vecX shift) %{ +instruct vsll4S(vecD dst, vecD src, vecD shift) %{ predicate(n->as_Vector()->length() == 2 || n->as_Vector()->length() == 4); match(Set dst (LShiftVS src shift)); - match(Set dst (RShiftVS src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (4H)" %} ins_encode %{ @@ -16726,7 +16793,6 @@ instruct vsll4S(vecD dst, vecD src, vecX shift) %{ instruct vsll8S(vecX dst, vecX src, vecX shift) %{ predicate(n->as_Vector()->length() == 8); match(Set dst (LShiftVS src shift)); - match(Set dst (RShiftVS src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (8H)" %} ins_encode %{ @@ -16737,29 +16803,72 @@ instruct vsll8S(vecX dst, vecX src, vecX shift) %{ ins_pipe(vshift128); %} -instruct vsrl4S(vecD dst, vecD src, vecX shift) %{ +instruct vsra4S(vecD dst, vecD src, vecD shift, vecD tmp) %{ predicate(n->as_Vector()->length() == 2 || n->as_Vector()->length() == 4); - match(Set dst (URShiftVS src shift)); + match(Set dst (RShiftVS src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (4H)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (4H)" %} ins_encode %{ - __ ushl(as_FloatRegister($dst$$reg), __ T4H, - as_FloatRegister($src$$reg), + __ negr(as_FloatRegister($tmp$$reg), __ T8B, as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift64); %} -instruct vsrl8S(vecX dst, vecX src, vecX shift) %{ +instruct vsra8S(vecX dst, vecX src, vecX shift, vecX tmp) %{ + predicate(n->as_Vector()->length() == 8); + match(Set dst (RShiftVS src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (8H)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T8H, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift128); +%} + +instruct vsrl4S(vecD dst, vecD src, vecD shift, vecD tmp) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (URShiftVS src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (4H)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T8B, + as_FloatRegister($shift$$reg)); + __ ushl(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift64); +%} + +instruct vsrl8S(vecX dst, vecX src, vecX shift, vecX tmp) %{ predicate(n->as_Vector()->length() == 8); match(Set dst (URShiftVS src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (8H)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (8H)" %} ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); __ ushl(as_FloatRegister($dst$$reg), __ T8H, as_FloatRegister($src$$reg), - as_FloatRegister($shift$$reg)); + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift128); %} @@ -16871,10 +16980,9 @@ instruct vsrl8S_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(vshift128_imm); %} -instruct vsll2I(vecD dst, vecD src, vecX shift) %{ +instruct vsll2I(vecD dst, vecD src, vecD shift) %{ predicate(n->as_Vector()->length() == 2); match(Set dst (LShiftVI src shift)); - match(Set dst (RShiftVI src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (2S)" %} ins_encode %{ @@ -16888,7 +16996,6 @@ instruct vsll2I(vecD dst, vecD src, vecX shift) %{ instruct vsll4I(vecX dst, vecX src, vecX shift) %{ predicate(n->as_Vector()->length() == 4); match(Set dst (LShiftVI src shift)); - match(Set dst (RShiftVI src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (4S)" %} ins_encode %{ @@ -16899,28 +17006,70 @@ instruct vsll4I(vecX dst, vecX src, vecX shift) %{ ins_pipe(vshift128); %} -instruct vsrl2I(vecD dst, vecD src, vecX shift) %{ +instruct vsra2I(vecD dst, vecD src, vecD shift, vecD tmp) %{ predicate(n->as_Vector()->length() == 2); - match(Set dst (URShiftVI src shift)); + match(Set dst (RShiftVI src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (2S)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (2S)" %} ins_encode %{ - __ ushl(as_FloatRegister($dst$$reg), __ T2S, - as_FloatRegister($src$$reg), + __ negr(as_FloatRegister($tmp$$reg), __ T8B, as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift64); %} -instruct vsrl4I(vecX dst, vecX src, vecX shift) %{ +instruct vsra4I(vecX dst, vecX src, vecX shift, vecX tmp) %{ + predicate(n->as_Vector()->length() == 4); + match(Set dst (RShiftVI src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (4S)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T4S, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift128); +%} + +instruct vsrl2I(vecD dst, vecD src, vecD shift, vecD tmp) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (URShiftVI src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (2S)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T8B, + as_FloatRegister($shift$$reg)); + __ ushl(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift64); +%} + +instruct vsrl4I(vecX dst, vecX src, vecX shift, vecX tmp) %{ predicate(n->as_Vector()->length() == 4); match(Set dst (URShiftVI src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (4S)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (4S)" %} ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); __ ushl(as_FloatRegister($dst$$reg), __ T4S, as_FloatRegister($src$$reg), - as_FloatRegister($shift$$reg)); + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift128); %} @@ -17006,7 +17155,6 @@ instruct vsrl4I_imm(vecX dst, vecX src, immI shift) %{ instruct vsll2L(vecX dst, vecX src, vecX shift) %{ predicate(n->as_Vector()->length() == 2); match(Set dst (LShiftVL src shift)); - match(Set dst (RShiftVL src shift)); ins_cost(INSN_COST); format %{ "sshl $dst,$src,$shift\t# vector (2D)" %} ins_encode %{ @@ -17017,15 +17165,36 @@ instruct vsll2L(vecX dst, vecX src, vecX shift) %{ ins_pipe(vshift128); %} -instruct vsrl2L(vecX dst, vecX src, vecX shift) %{ +instruct vsra2L(vecX dst, vecX src, vecX shift, vecX tmp) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (RShiftVL src shift)); + ins_cost(INSN_COST); + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "sshl $dst,$src,$tmp\t# vector (2D)" %} + ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); + __ sshl(as_FloatRegister($dst$$reg), __ T2D, + as_FloatRegister($src$$reg), + as_FloatRegister($tmp$$reg)); + %} + ins_pipe(vshift128); +%} + +instruct vsrl2L(vecX dst, vecX src, vecX shift, vecX tmp) %{ predicate(n->as_Vector()->length() == 2); match(Set dst (URShiftVL src shift)); ins_cost(INSN_COST); - format %{ "ushl $dst,$src,$shift\t# vector (2D)" %} + effect(TEMP tmp); + format %{ "negr $tmp,$shift\t" + "ushl $dst,$src,$tmp\t# vector (2D)" %} ins_encode %{ + __ negr(as_FloatRegister($tmp$$reg), __ T16B, + as_FloatRegister($shift$$reg)); __ ushl(as_FloatRegister($dst$$reg), __ T2D, as_FloatRegister($src$$reg), - as_FloatRegister($shift$$reg)); + as_FloatRegister($tmp$$reg)); %} ins_pipe(vshift128); %} diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestByteVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestByteVect.java index 42b3ebf9a38..97310e0a31d 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestByteVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestByteVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestByteVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestByteVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestByteVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestByteVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestDoubleVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestDoubleVect.java index 56fce03cc83..63f4d449f13 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestDoubleVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestDoubleVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestDoubleVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestDoubleVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestDoubleVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestDoubleVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestFloatVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestFloatVect.java index c64c28ba0ec..5676a77a3cb 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestFloatVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestFloatVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestFloatVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestFloatVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestFloatVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestFloatVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestIntVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestIntVect.java index 87c8557adb9..40180f74310 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestIntVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestIntVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestIntVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestIntVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestIntVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestIntVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestLongVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestLongVect.java index 1bd0bf5c91b..da454146d17 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestLongVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestLongVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestLongVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestLongVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestLongVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestLongVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/c2/cr6340864/TestShortVect.java b/test/hotspot/jtreg/compiler/c2/cr6340864/TestShortVect.java index e2bf2a90308..1aa3bd86f20 100644 --- a/test/hotspot/jtreg/compiler/c2/cr6340864/TestShortVect.java +++ b/test/hotspot/jtreg/compiler/c2/cr6340864/TestShortVect.java @@ -27,6 +27,9 @@ * @summary Implement vectorization optimizations in hotspot-server * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.c2.cr6340864.TestShortVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.c2.cr6340864.TestShortVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.c2.cr6340864.TestShortVect + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.c2.cr6340864.TestShortVect */ package compiler.c2.cr6340864; diff --git a/test/hotspot/jtreg/compiler/codegen/TestCharVect2.java b/test/hotspot/jtreg/compiler/codegen/TestCharVect2.java index 6c349239ad7..881bb9052b9 100644 --- a/test/hotspot/jtreg/compiler/codegen/TestCharVect2.java +++ b/test/hotspot/jtreg/compiler/codegen/TestCharVect2.java @@ -27,6 +27,9 @@ * @summary incorrect results of char vectors right shift operaiton * * @run main/othervm/timeout=400 -Xbatch -Xmx128m compiler.codegen.TestCharVect2 + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=8 compiler.codegen.TestCharVect2 + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=16 compiler.codegen.TestCharVect2 + * @run main/othervm/timeout=400 -Xbatch -Xmx128m -XX:MaxVectorSize=32 compiler.codegen.TestCharVect2 */ package compiler.codegen; From 7223ed2205419a16271fa4ad7ba057863a5cef9f Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Wed, 12 Dec 2018 12:00:02 +0100 Subject: [PATCH 006/174] 8152724: Sum of eden before GC and current survivor capacity may be larger than heap size Limit the maximum survivor size for a given GC to the remaining number of free regions. Reviewed-by: sjohanss, sangheki --- src/hotspot/share/gc/g1/g1CollectedHeap.hpp | 3 + src/hotspot/share/gc/g1/g1HeapTransition.cpp | 4 +- src/hotspot/share/gc/g1/g1Policy.cpp | 25 +++++--- src/hotspot/share/gc/g1/g1Policy.hpp | 2 +- .../gc/g1/TestEdenSurvivorLessThanMax.java | 61 +++++++++++++++++++ 5 files changed, 85 insertions(+), 10 deletions(-) create mode 100644 test/hotspot/jtreg/gc/g1/TestEdenSurvivorLessThanMax.java diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp index c9a79f4054a..72e1b5f9988 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp @@ -1026,6 +1026,9 @@ public: // The number of regions that are completely free. uint num_free_regions() const { return _hrm.num_free_regions(); } + // The number of regions that can be allocated into. + uint num_free_or_available_regions() const { return num_free_regions() + _hrm.available(); } + MemoryUsage get_auxiliary_data_memory_usage() const { return _hrm.get_auxiliary_data_memory_usage(); } diff --git a/src/hotspot/share/gc/g1/g1HeapTransition.cpp b/src/hotspot/share/gc/g1/g1HeapTransition.cpp index 2a1e695eb4c..5af4b03617d 100644 --- a/src/hotspot/share/gc/g1/g1HeapTransition.cpp +++ b/src/hotspot/share/gc/g1/g1HeapTransition.cpp @@ -89,7 +89,7 @@ void G1HeapTransition::print() { Data after(_g1_heap); size_t eden_capacity_length_after_gc = _g1_heap->g1_policy()->young_list_target_length() - after._survivor_length; - size_t survivor_capacity_length_after_gc = _g1_heap->g1_policy()->max_survivor_regions(); + size_t survivor_capacity_length_before_gc = _g1_heap->g1_policy()->max_survivor_regions(); DetailedUsage usage; if (log_is_enabled(Trace, gc, heap)) { @@ -112,7 +112,7 @@ void G1HeapTransition::print() { log_trace(gc, heap)(" Used: 0K, Waste: 0K"); log_info(gc, heap)("Survivor regions: " SIZE_FORMAT "->" SIZE_FORMAT "(" SIZE_FORMAT ")", - _before._survivor_length, after._survivor_length, survivor_capacity_length_after_gc); + _before._survivor_length, after._survivor_length, survivor_capacity_length_before_gc); log_trace(gc, heap)(" Used: " SIZE_FORMAT "K, Waste: " SIZE_FORMAT "K", usage._survivor_used / K, ((after._survivor_length * HeapRegion::GrainBytes) - usage._survivor_used) / K); diff --git a/src/hotspot/share/gc/g1/g1Policy.cpp b/src/hotspot/share/gc/g1/g1Policy.cpp index 49ce5c82cc9..36ec52dd24a 100644 --- a/src/hotspot/share/gc/g1/g1Policy.cpp +++ b/src/hotspot/share/gc/g1/g1Policy.cpp @@ -470,6 +470,10 @@ void G1Policy::record_collection_pause_start(double start_time_sec) { // every time we calculate / recalculate the target young length. update_survivors_policy(); + assert(max_survivor_regions() + _g1h->num_used_regions() <= _g1h->max_regions(), + "Maximum survivor regions %u plus used regions %u exceeds max regions %u", + max_survivor_regions(), _g1h->num_used_regions(), _g1h->max_regions()); + assert(_g1h->used() == _g1h->recalculate_used(), "sanity, used: " SIZE_FORMAT " recalculate_used: " SIZE_FORMAT, _g1h->used(), _g1h->recalculate_used()); @@ -899,8 +903,8 @@ bool G1Policy::adaptive_young_list_length() const { return _young_gen_sizer.adaptive_young_list_length(); } -size_t G1Policy::desired_survivor_size() const { - size_t const survivor_capacity = HeapRegion::GrainWords * _max_survivor_regions; +size_t G1Policy::desired_survivor_size(uint max_regions) const { + size_t const survivor_capacity = HeapRegion::GrainWords * max_regions; return (size_t)((((double)survivor_capacity) * TargetSurvivorRatio) / 100); } @@ -927,15 +931,22 @@ void G1Policy::update_max_gc_locker_expansion() { void G1Policy::update_survivors_policy() { double max_survivor_regions_d = (double) _young_list_target_length / (double) SurvivorRatio; - // We use ceiling so that if max_survivor_regions_d is > 0.0 (but - // smaller than 1.0) we'll get 1. - _max_survivor_regions = (uint) ceil(max_survivor_regions_d); - _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(desired_survivor_size()); + // Calculate desired survivor size based on desired max survivor regions (unconstrained + // by remaining heap). Otherwise we may cause undesired promotions as we are + // already getting close to end of the heap, impacting performance even more. + uint const desired_max_survivor_regions = ceil(max_survivor_regions_d); + size_t const survivor_size = desired_survivor_size(desired_max_survivor_regions); + + _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(survivor_size); if (UsePerfData) { _policy_counters->tenuring_threshold()->set_value(_tenuring_threshold); - _policy_counters->desired_survivor_size()->set_value(desired_survivor_size() * oopSize); + _policy_counters->desired_survivor_size()->set_value(survivor_size * oopSize); } + // The real maximum survivor size is bounded by the number of regions that can + // be allocated into. + _max_survivor_regions = MIN2(desired_max_survivor_regions, + _g1h->num_free_or_available_regions()); } bool G1Policy::force_initial_mark_if_outside_cycle(GCCause::Cause gc_cause) { diff --git a/src/hotspot/share/gc/g1/g1Policy.hpp b/src/hotspot/share/gc/g1/g1Policy.hpp index d4dceb7a5b1..e4f752c5446 100644 --- a/src/hotspot/share/gc/g1/g1Policy.hpp +++ b/src/hotspot/share/gc/g1/g1Policy.hpp @@ -399,7 +399,7 @@ private: AgeTable _survivors_age_table; - size_t desired_survivor_size() const; + size_t desired_survivor_size(uint max_regions) const; public: // Fraction used when predicting how many optional regions to include in // the CSet. This fraction of the available time is used for optional regions, diff --git a/test/hotspot/jtreg/gc/g1/TestEdenSurvivorLessThanMax.java b/test/hotspot/jtreg/gc/g1/TestEdenSurvivorLessThanMax.java new file mode 100644 index 00000000000..c2d387664df --- /dev/null +++ b/test/hotspot/jtreg/gc/g1/TestEdenSurvivorLessThanMax.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test TestEdenSurvivorLessThanMax + * @bug 8152724 + * @summary Check that G1 eden plus survivor max capacity after GC does not exceed maximum number of regions. + * @requires vm.gc.G1 + * @key gc + * @library /test/lib + * @build sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -Xlog:gc+heap=debug -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:+UseG1GC -Xmx64M -Xms64M -Xmn50M -XX:SurvivorRatio=1 TestEdenSurvivorLessThanMax + */ + +import sun.hotspot.WhiteBox; + +// The test fills the heap in a way that previous to 8152724 the maximum number of survivor regions +// for that young gc was higher than there was free space left which is impossible. +public class TestEdenSurvivorLessThanMax { + private static final long BYTES_TO_FILL = 50 * 1024 * 1024; + + private static final WhiteBox WB = WhiteBox.getWhiteBox(); + + public static void main(String[] args) throws Exception { + Object o = new int[100]; + + long objSize = WB.getObjectSize(o); + + // Fill eden to approximately ~90%. + int numObjs = (int)((BYTES_TO_FILL / objSize) * 9 / 10); + for (int i = 0; i < numObjs; i++) { + o = new int[100]; + } + + WB.youngGC(); + + System.out.println(o.toString()); + } +} + From 8c4f51f6668ab150efb786f9cea47f5a74fa429d Mon Sep 17 00:00:00 2001 From: Ralf Schmelter Date: Wed, 12 Dec 2018 11:34:08 +0000 Subject: [PATCH 007/174] 8214892: Delayed starting of debugging via jcmd Reviewed-by: cjplummer, clanger --- .../share/services/diagnosticCommand.cpp | 46 ++++++++ .../share/services/diagnosticCommand.hpp | 22 ++++ .../share/native/libjdwp/debugInit.c | 66 ++++++++++- test/jdk/com/sun/jdi/OnJcmdTest.java | 109 ++++++++++++++++++ 4 files changed, 242 insertions(+), 1 deletion(-) create mode 100644 test/jdk/com/sun/jdi/OnJcmdTest.java diff --git a/src/hotspot/share/services/diagnosticCommand.cpp b/src/hotspot/share/services/diagnosticCommand.cpp index c9e36d02066..3191211e7b1 100644 --- a/src/hotspot/share/services/diagnosticCommand.cpp +++ b/src/hotspot/share/services/diagnosticCommand.cpp @@ -37,6 +37,7 @@ #include "runtime/fieldDescriptor.inline.hpp" #include "runtime/flags/jvmFlag.hpp" #include "runtime/handles.inline.hpp" +#include "runtime/interfaceSupport.inline.hpp" #include "runtime/javaCalls.hpp" #include "runtime/os.hpp" #include "services/diagnosticArgument.hpp" @@ -123,6 +124,11 @@ void DCmdRegistrant::register_dcmds(){ DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(jmx_agent_export_flags, true,false)); DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(jmx_agent_export_flags, true,false)); + // Debug on cmd (only makes sense with JVMTI since the agentlib needs it). +#if INCLUDE_JVMTI + DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); +#endif // INCLUDE_JVMTI + } #ifndef HAVE_EXTRA_DCMD @@ -1054,3 +1060,43 @@ void TouchedMethodsDCmd::execute(DCmdSource source, TRAPS) { int TouchedMethodsDCmd::num_arguments() { return 0; } + +#if INCLUDE_JVMTI +extern "C" typedef char const* (JNICALL *debugInit_startDebuggingViaCommandPtr)(JNIEnv* env, jthread thread, char const** transport_name, + char const** address, jboolean* first_start); +static debugInit_startDebuggingViaCommandPtr dvc_start_ptr = NULL; + +DebugOnCmdStartDCmd::DebugOnCmdStartDCmd(outputStream* output, bool heap) : DCmdWithParser(output, heap) { +} + +void DebugOnCmdStartDCmd::execute(DCmdSource source, TRAPS) { + char const* transport = NULL; + char const* addr = NULL; + jboolean is_first_start = JNI_FALSE; + JavaThread* thread = (JavaThread*) THREAD; + jthread jt = JNIHandles::make_local(thread->threadObj()); + ThreadToNativeFromVM ttn(thread); + const char *error = "Could not find jdwp agent."; + + if (!dvc_start_ptr) { + for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { + if ((strcmp("jdwp", agent->name()) == 0) && (dvc_start_ptr == NULL)) { + char const* func = "debugInit_startDebuggingViaCommand"; + dvc_start_ptr = (debugInit_startDebuggingViaCommandPtr) os::find_agent_function(agent, false, &func, 1); + } + } + } + + if (dvc_start_ptr) { + error = dvc_start_ptr(thread->jni_environment(), jt, &transport, &addr, &is_first_start); + } + + if (error != NULL) { + output()->print_cr("Debugging has not been started: %s", error); + } else { + output()->print_cr(is_first_start ? "Debugging has been started." : "Debugging is already active."); + output()->print_cr("Transport : %s", transport ? transport : "#unknown"); + output()->print_cr("Address : %s", addr ? addr : "#unknown"); + } +} +#endif // INCLUDE_JVMTI diff --git a/src/hotspot/share/services/diagnosticCommand.hpp b/src/hotspot/share/services/diagnosticCommand.hpp index f0a76783308..45bb2a32107 100644 --- a/src/hotspot/share/services/diagnosticCommand.hpp +++ b/src/hotspot/share/services/diagnosticCommand.hpp @@ -867,4 +867,26 @@ public: virtual void execute(DCmdSource source, TRAPS); }; +#if INCLUDE_JVMTI +class DebugOnCmdStartDCmd : public DCmdWithParser { +public: + DebugOnCmdStartDCmd(outputStream* output, bool heap); + static const char* name() { + return "VM.start_java_debugging"; + } + static const char* description() { + return "Starts up the Java debugging if the jdwp agentlib was enabled with the option onjcmd=y."; + } + static const char* impact() { + return "High: Switches the VM into Java debug mode."; + } + static const JavaPermission permission() { + JavaPermission p = { "java.lang.management.ManagementPermission", "monitor", NULL }; + return p; + } + static int num_arguments() { return 0; } + virtual void execute(DCmdSource source, TRAPS); +}; +#endif // INCLUDE_JVMTI + #endif // SHARE_VM_SERVICES_DIAGNOSTICCOMMAND_HPP diff --git a/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c b/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c index d9f50a73aa7..23e7cec6bb0 100644 --- a/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c +++ b/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c @@ -82,6 +82,9 @@ static unsigned logflags = 0; /* Log flags */ static char *names; /* strings derived from OnLoad options */ +static jboolean allowStartViaJcmd = JNI_FALSE; /* if true we allow the debugging to be started via a jcmd */ +static jboolean startedViaJcmd = JNI_FALSE; /* if false, we have not yet started debugging via a jcmd */ + /* * Elements of the transports bag */ @@ -870,6 +873,7 @@ printUsage(void) "launch= run debugger on event none\n" "onthrow= debug on throw none\n" "onuncaught=y|n debug on any uncaught? n\n" + "onjcmd=y|n start debug via jcmd? n\n" "timeout= for listen/attach in milliseconds n\n" "mutf8=y|n output modified utf-8 n\n" "quiet=y|n control over terminal messages n\n")); @@ -1010,6 +1014,7 @@ parseOptions(char *options) int length; char *str; char *errmsg; + jboolean onJcmd = JNI_FALSE; /* Set defaults */ gdata->assertOn = DEFAULT_ASSERT_ON; @@ -1229,6 +1234,10 @@ parseOptions(char *options) if ( !get_boolean(&str, &useStandardAlloc) ) { goto syntax_error; } + } else if (strcmp(buf, "onjcmd") == 0) { + if (!get_boolean(&str, &onJcmd)) { + goto syntax_error; + } } else { goto syntax_error; } @@ -1254,7 +1263,6 @@ parseOptions(char *options) goto bad_option_with_errmsg; } - if (!isServer) { jboolean specified = bagEnumerateOver(transports, checkAddress, NULL); if (!specified) { @@ -1280,6 +1288,20 @@ parseOptions(char *options) } } + if (onJcmd) { + if (launchOnInit != NULL) { + errmsg = "Cannot combine onjcmd and launch suboptions"; + goto bad_option_with_errmsg; + } + if (!isServer) { + errmsg = "Can only use onjcmd with server=y"; + goto bad_option_with_errmsg; + } + suspendOnInit = JNI_FALSE; + initOnStartup = JNI_FALSE; + allowStartViaJcmd = JNI_TRUE; + } + return JNI_TRUE; syntax_error: @@ -1348,3 +1370,45 @@ debugInit_exit(jvmtiError error, const char *msg) // Last chance to die, this kills the entire process. forceExit(EXIT_JVMTI_ERROR); } + +static jboolean getFirstTransport(void *item, void *arg) +{ + TransportSpec** store = arg; + *store = item; + + return JNI_FALSE; /* Want the first */ +} + +/* Call to start up debugging. */ +JNIEXPORT char const* JNICALL debugInit_startDebuggingViaCommand(JNIEnv* env, jthread thread, char const** transport_name, + char const** address, jboolean* first_start) { + jboolean is_first_start = JNI_FALSE; + TransportSpec* spec = NULL; + + if (!vmInitialized) { + return "Not yet initialized. Try again later."; + } + + if (!allowStartViaJcmd) { + return "Starting debugging via jcmd was not enabled via the onjcmd option of the jdwp agent."; + } + + if (!startedViaJcmd) { + startedViaJcmd = JNI_TRUE; + is_first_start = JNI_TRUE; + initialize(env, thread, EI_VM_INIT); + } + + bagEnumerateOver(transports, getFirstTransport, &spec); + + if ((spec != NULL) && (transport_name != NULL) && (address != NULL)) { + *transport_name = spec->name; + *address = spec->address; + } + + if (first_start != NULL) { + *first_start = is_first_start; + } + + return NULL; +} diff --git a/test/jdk/com/sun/jdi/OnJcmdTest.java b/test/jdk/com/sun/jdi/OnJcmdTest.java new file mode 100644 index 00000000000..e8dcf719395 --- /dev/null +++ b/test/jdk/com/sun/jdi/OnJcmdTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, SAP SE. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8214892 + * @summary Test that the onjcmd option of the jdwp agent works. + * + * @author Ralf Schmelter + * + * @library /test/lib + * @run compile --add-exports java.base/jdk.internal.vm=ALL-UNNAMED -g OnJcmdTest.java + * @run main/othervm --add-exports java.base/jdk.internal.vm=ALL-UNNAMED -agentlib:jdwp=transport=dt_socket,address=localhost:0,onjcmd=y,server=y OnJcmdTest + */ + +import java.lang.reflect.Method; +import java.util.Properties; + +import jdk.internal.vm.VMSupport; +import jdk.test.lib.JDKToolFinder; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +public class OnJcmdTest { + + private static String getListenerAddress() throws Exception { + Properties props = VMSupport.getAgentProperties(); + return props.getProperty("sun.jdwp.listenerAddress", null); + } + + public static void main(String[] args) throws Throwable { + // First check if we get the expected errors. + OutputAnalyzer output = ProcessTools.executeTestJvm( + "-agentlib:jdwp=transport=dt_socket,address=any,onjcmd=y"); + output.shouldContain("Can only use onjcmd with server=y"); + output.shouldHaveExitValue(1); + + output = ProcessTools.executeTestJvm( + "-agentlib:jdwp=transport=dt_socket,address=any,onjcmd=y,onthrow=a,launch=a"); + output.shouldContain("Cannot combine onjcmd and launch suboptions"); + output.shouldHaveExitValue(1); + + // Make sure debugging is not yet started. + String prop = getListenerAddress(); + + if (prop != null) { + throw new RuntimeException("Listener address was set to " + prop); + } + + // Now start it (test that it is OK to do this more than once). + for (int i = 0; i < 3; ++i) { + String jcmd = JDKToolFinder.getJDKTool("jcmd"); + output = ProcessTools.executeProcess(jcmd, + Long.toString(ProcessTools.getProcessId()), + "VM.start_java_debugging"); + + String exp_str = i == 0 ? "Debugging has been started." : + "Debugging is already active."; + output.shouldContain(exp_str); + output.shouldContain("Transport : dt_socket"); + output.shouldHaveExitValue(0); + } + + // Now the property should be set, as the jdwp agent waits for a + // connection. + long t1 = System.currentTimeMillis(); + long t2 = t1; + + while(t2 - t1 < 4000) { + prop = getListenerAddress(); + + if (prop != null) { + if (prop.equals("localhost:0")) { + throw new RuntimeException("Port was not expanded"); + } else if (!prop.startsWith("dt_socket:")) { + throw new RuntimeException("Invalid transport prop " + prop); + } + + return; + } + + Thread.sleep(50); + t2 = System.currentTimeMillis(); + } + + throw new RuntimeException("Debugging backend didn't start"); + } +} From ade1d52ab6fa4bc9042ea1ba649a01805102e1d7 Mon Sep 17 00:00:00 2001 From: Dmitrij Pochepko Date: Wed, 12 Dec 2018 15:26:49 +0300 Subject: [PATCH 008/174] 8205421: AARCH64: StubCodeMark should be placed after alignment Reviewed-by: aph --- .../cpu/aarch64/stubGenerator_aarch64.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp b/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp index 87e044e0aa2..218db0d295c 100644 --- a/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/stubGenerator_aarch64.cpp @@ -725,8 +725,11 @@ class StubGenerator: public StubCodeGenerator { stub_name = "forward_copy_longs"; else stub_name = "backward_copy_longs"; - StubCodeMark mark(this, "StubRoutines", stub_name); + __ align(CodeEntryAlignment); + + StubCodeMark mark(this, "StubRoutines", stub_name); + __ bind(start); Label unaligned_copy_long; @@ -1976,9 +1979,10 @@ class StubGenerator: public StubCodeGenerator { const Register dst_pos = c_rarg3; // destination position const Register length = c_rarg4; + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", name); - __ align(CodeEntryAlignment); address start = __ pc(); __ enter(); // required for proper stackwalking of RuntimeStub frame @@ -3653,7 +3657,6 @@ class StubGenerator: public StubCodeGenerator { } address generate_has_negatives(address &has_negatives_long) { - StubCodeMark mark(this, "StubRoutines", "has_negatives"); const u1 large_loop_size = 64; const uint64_t UPPER_BIT_MASK=0x8080808080808080; int dcache_line = VM_Version::dcache_line_size(); @@ -3661,6 +3664,9 @@ class StubGenerator: public StubCodeGenerator { Register ary1 = r1, len = r2, result = r0; __ align(CodeEntryAlignment); + + StubCodeMark mark(this, "StubRoutines", "has_negatives"); + address entry = __ pc(); __ enter(); @@ -3900,7 +3906,6 @@ class StubGenerator: public StubCodeGenerator { // cnt1 = r10 - amount of elements left to check, reduced by wordSize // r3-r5 are reserved temporary registers address generate_large_array_equals() { - StubCodeMark mark(this, "StubRoutines", "large_array_equals"); Register a1 = r1, a2 = r2, result = r0, cnt1 = r10, tmp1 = rscratch1, tmp2 = rscratch2, tmp3 = r3, tmp4 = r4, tmp5 = r5, tmp6 = r11, tmp7 = r12, tmp8 = r13; @@ -3915,6 +3920,9 @@ class StubGenerator: public StubCodeGenerator { tmp5, tmp6, tmp7, tmp8); __ align(CodeEntryAlignment); + + StubCodeMark mark(this, "StubRoutines", "large_array_equals"); + address entry = __ pc(); __ enter(); __ sub(cnt1, cnt1, wordSize); // first 8 bytes were loaded outside of stub From d1ef9b19d7b9df0cb6703226e49ae3b5a8d3b28a Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Wed, 12 Dec 2018 13:28:50 +0100 Subject: [PATCH 009/174] 8215159: Improve initial setup of system Properties Reviewed-by: mchung, rriggs, plevart, briangoetz, robilad --- .../share/classes/java/lang/System.java | 50 ++++++++++++++----- .../java/lang/VersionProps.java.template | 30 +++++------ .../share/classes/jdk/internal/misc/VM.java | 27 ++++------ .../jdk/internal/util/SystemProps.java | 40 ++++++++------- 4 files changed, 84 insertions(+), 63 deletions(-) diff --git a/src/java.base/share/classes/java/lang/System.java b/src/java.base/share/classes/java/lang/System.java index fb0ac21675b..42b97d670fe 100644 --- a/src/java.base/share/classes/java/lang/System.java +++ b/src/java.base/share/classes/java/lang/System.java @@ -801,8 +801,9 @@ public final class System { } if (props == null) { - props = SystemProps.initProperties(); - VersionProps.init(props); + Map tempProps = SystemProps.initProperties(); + VersionProps.init(tempProps); + props = createProperties(tempProps); } System.props = props; } @@ -1959,18 +1960,42 @@ public final class System { } } + /** + * Create the Properties object from a map - masking out system properties + * that are not intended for public access. + */ + private static Properties createProperties(Map initialProps) { + Properties properties = new Properties(initialProps.size()); + for (var entry : initialProps.entrySet()) { + String prop = entry.getKey(); + switch (prop) { + // Do not add private system properties to the Properties + case "sun.nio.MaxDirectMemorySize": + case "sun.nio.PageAlignDirectMemory": + // used by java.lang.Integer.IntegerCache + case "java.lang.Integer.IntegerCache.high": + // used by sun.launcher.LauncherHelper + case "sun.java.launcher.diag": + // used by jdk.internal.loader.ClassLoaders + case "jdk.boot.class.path.append": + break; + default: + properties.put(prop, entry.getValue()); + } + } + return properties; + } + /** * Initialize the system class. Called after thread initialization. */ private static void initPhase1() { - // VM might invoke JNU_NewStringPlatform() to set those encoding // sensitive properties (user.home, user.name, boot.class.path, etc.) // during "props" initialization. // The charset is initialized in System.c and does not depend on the Properties. - props = SystemProps.initProperties(); - VersionProps.init(props); - StaticProperty.javaHome(); // Load StaticProperty to cache the property values + Map tempProps = SystemProps.initProperties(); + VersionProps.init(tempProps); // There are certain system configurations that may be controlled by // VM options such as the maximum amount of direct memory and @@ -1978,15 +2003,14 @@ public final class System { // of autoboxing. Typically, the library will obtain these values // from the properties set by the VM. If the properties are for // internal implementation use only, these properties should be - // removed from the system properties. - // - // See java.lang.Integer.IntegerCache and the - // VM.saveAndRemoveProperties method for example. + // masked from the system properties. // // Save a private copy of the system properties object that - // can only be accessed by the internal implementation. Remove - // certain system properties that are not intended for public access. - VM.saveAndRemoveProperties(props); + // can only be accessed by the internal implementation. + VM.saveProperties(tempProps); + props = createProperties(tempProps); + + StaticProperty.javaHome(); // Load StaticProperty to cache the property values lineSeparator = props.getProperty("line.separator"); diff --git a/src/java.base/share/classes/java/lang/VersionProps.java.template b/src/java.base/share/classes/java/lang/VersionProps.java.template index 9ed15112ed1..66035a130ae 100644 --- a/src/java.base/share/classes/java/lang/VersionProps.java.template +++ b/src/java.base/share/classes/java/lang/VersionProps.java.template @@ -28,8 +28,8 @@ package java.lang; import java.io.PrintStream; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Optional; -import java.util.Properties; class VersionProps { @@ -88,25 +88,25 @@ class VersionProps { /** * Initialize system properties using build provided values. * - * @param props Properties instance in which to insert the properties + * @param props Map instance in which to insert the properties */ - public static void init(Properties props) { - props.setProperty("java.version", java_version); - props.setProperty("java.version.date", java_version_date); - props.setProperty("java.runtime.version", java_runtime_version); - props.setProperty("java.runtime.name", java_runtime_name); + public static void init(Map props) { + props.put("java.version", java_version); + props.put("java.version.date", java_version_date); + props.put("java.runtime.version", java_runtime_version); + props.put("java.runtime.name", java_runtime_name); if (VENDOR_VERSION_STRING.length() > 0) - props.setProperty("java.vendor.version", VENDOR_VERSION_STRING); + props.put("java.vendor.version", VENDOR_VERSION_STRING); - props.setProperty("java.class.version", CLASSFILE_MAJOR_MINOR); + props.put("java.class.version", CLASSFILE_MAJOR_MINOR); - props.setProperty("java.specification.version", VERSION_SPECIFICATION); - props.setProperty("java.specification.name", "Java Platform API Specification"); - props.setProperty("java.specification.vendor", "Oracle Corporation"); + props.put("java.specification.version", VERSION_SPECIFICATION); + props.put("java.specification.name", "Java Platform API Specification"); + props.put("java.specification.vendor", "Oracle Corporation"); - props.setProperty("java.vendor", VENDOR); - props.setProperty("java.vendor.url", VENDOR_URL); - props.setProperty("java.vendor.url.bug", VENDOR_URL_BUG); + props.put("java.vendor", VENDOR); + props.put("java.vendor.url", VENDOR_URL); + props.put("java.vendor.url.bug", VENDOR_URL_BUG); } private static int parseVersionNumber(String version, int prevIndex, int index) { diff --git a/src/java.base/share/classes/jdk/internal/misc/VM.java b/src/java.base/share/classes/jdk/internal/misc/VM.java index 561b3aaa253..872c3abdd83 100644 --- a/src/java.base/share/classes/jdk/internal/misc/VM.java +++ b/src/java.base/share/classes/jdk/internal/misc/VM.java @@ -26,6 +26,8 @@ package jdk.internal.misc; import static java.lang.Thread.State.*; + +import java.util.Collections; import java.util.Map; import java.util.Properties; @@ -175,7 +177,7 @@ public class VM { if (savedProps == null) throw new IllegalStateException("Not yet initialized"); - return savedProps; + return Collections.unmodifiableMap(savedProps); } private static Map savedProps; @@ -184,16 +186,15 @@ public class VM { // the system properties that are not intended for public access. // // This method can only be invoked during system initialization. - public static void saveAndRemoveProperties(Properties props) { + public static void saveProperties(Map props) { if (initLevel() != 0) throw new IllegalStateException("Wrong init level"); - @SuppressWarnings({"rawtypes", "unchecked"}) - Map sp = - Map.ofEntries(props.entrySet().toArray(new Map.Entry[0])); // only main thread is running at this time, so savedProps and // its content will be correctly published to threads started later - savedProps = sp; + if (savedProps == null) { + savedProps = props; + } // Set the maximum amount of direct memory. This value is controlled // by the vm option -XX:MaxDirectMemorySize=. @@ -201,7 +202,7 @@ public class VM { // from the system property sun.nio.MaxDirectMemorySize set by the VM. // If not set or set to -1, the max memory will be used // The system property will be removed. - String s = (String)props.remove("sun.nio.MaxDirectMemorySize"); + String s = props.get("sun.nio.MaxDirectMemorySize"); if (s == null || s.isEmpty() || s.equals("-1")) { // -XX:MaxDirectMemorySize not given, take default directMemory = Runtime.getRuntime().maxMemory(); @@ -212,19 +213,9 @@ public class VM { } // Check if direct buffers should be page aligned - s = (String)props.remove("sun.nio.PageAlignDirectMemory"); + s = props.get("sun.nio.PageAlignDirectMemory"); if ("true".equals(s)) pageAlignDirectMemory = true; - - // Remove other private system properties - // used by java.lang.Integer.IntegerCache - props.remove("java.lang.Integer.IntegerCache.high"); - - // used by sun.launcher.LauncherHelper - props.remove("sun.java.launcher.diag"); - - // used by jdk.internal.loader.ClassLoaders - props.remove("jdk.boot.class.path.append"); } // Initialize any miscellaneous operating system settings that need to be diff --git a/src/java.base/share/classes/jdk/internal/util/SystemProps.java b/src/java.base/share/classes/jdk/internal/util/SystemProps.java index 6209529007e..6bda754a04d 100644 --- a/src/java.base/share/classes/jdk/internal/util/SystemProps.java +++ b/src/java.base/share/classes/jdk/internal/util/SystemProps.java @@ -26,7 +26,8 @@ package jdk.internal.util; import java.lang.annotation.Native; -import java.util.Properties; +import java.util.HashMap; +import java.util.Map; /** * System Property initialization for internal use only @@ -47,12 +48,13 @@ public final class SystemProps { * * @return a Properties instance initialized with all of the properties */ - public static Properties initProperties() { + public static Map initProperties() { + // Initially, cmdProperties only includes -D and props from the VM Raw raw = new Raw(); - Properties props = raw.cmdProperties(); + HashMap props = raw.cmdProperties(); - String javaHome = props.getProperty("java.home"); + String javaHome = props.get("java.home"); assert javaHome != null : "java.home not set"; putIfAbsent(props, "user.home", raw.propDefault(Raw._user_home_NDX)); @@ -120,7 +122,7 @@ public final class SystemProps { * @param key the key * @param value the value */ - private static void put(Properties props, String key, String value) { + private static void put(HashMap props, String key, String value) { if (value != null) { props.put(key, value); } @@ -132,7 +134,7 @@ public final class SystemProps { * @param key the key * @param value the value */ - private static void putIfAbsent(Properties props, String key, String value) { + private static void putIfAbsent(HashMap props, String key, String value) { if (value != null) { props.putIfAbsent(key, value); } @@ -147,10 +149,12 @@ public final class SystemProps { * @param display the display value for the base * @param format the format value for the base */ - private static void fillI18nProps(Properties cmdProps, String base, String display, + private static void fillI18nProps(HashMap cmdProps, + String base, + String display, String format) { // Do not override command line setting - String baseValue = cmdProps.getProperty(base); + String baseValue = cmdProps.get(base); if (baseValue != null) { return; // Do not override value from the command line } @@ -163,7 +167,7 @@ public final class SystemProps { /* user.xxx.display property */ String disp = base.concat(".display"); - String dispValue = cmdProps.getProperty(disp); + String dispValue = cmdProps.get(disp); if (dispValue == null && display != null && !display.equals(baseValue)) { // Create the property only if different from the base property cmdProps.put(disp, display); @@ -171,7 +175,7 @@ public final class SystemProps { /* user.xxx.format property */ String fmt = base.concat(".format"); - String fmtValue = cmdProps.getProperty(fmt); + String fmtValue = cmdProps.get(fmt); if (fmtValue == null && format != null && !format.equals(baseValue)) { // Create the property only if different than the base property cmdProps.put(fmt, format); @@ -253,15 +257,17 @@ public final class SystemProps { * * @return return a Properties instance of the command line and VM options */ - private Properties cmdProperties() { + private HashMap cmdProperties() { String[] vmProps = vmProperties(); - int nProps = vmProps.length / 2; - var cmdProps = new Properties(nProps + Raw.FIXED_LENGTH); - for (int i = 0; i < nProps; i++) { - String k = vmProps[i * 2]; + // While optimal initialCapacity here would be the exact number of properties + // divided by LOAD_FACTOR, a large portion of the properties in Raw are + // usually not set, so for typical cases the chosen capacity avoids resizing + var cmdProps = new HashMap((vmProps.length / 2) + Raw.FIXED_LENGTH); + for (int i = 0; i < vmProps.length;) { + String k = vmProps[i++]; if (k != null) { - String v = vmProps[i * 2 + 1]; - cmdProps.setProperty(k, v != null ? v : ""); + String v = vmProps[i++]; + cmdProps.put(k, v != null ? v : ""); } else { // no more key/value pairs break; From 31fbc28af5d8933f7b8d6b25249fccb1a738ffb6 Mon Sep 17 00:00:00 2001 From: Michihiro Horie Date: Tue, 11 Dec 2018 20:31:18 -0500 Subject: [PATCH 010/174] 8213754: PPC64: Add Intrinsics for isDigit/isLowerCase/isUpperCase/isWhitespace Reviewed-by: kvn, rriggs, mdoerr, gromero --- .../CharacterData00.java.template | 15 ++ .../CharacterData01.java.template | 15 ++ .../CharacterData02.java.template | 17 ++- .../CharacterData0E.java.template | 17 ++- .../CharacterDataLatin1.java.template | 20 +++ .../CharacterDataPrivateUse.java.template | 38 +++-- .../CharacterDataUndefined.java.template | 42 ++++-- src/hotspot/cpu/ppc/assembler_ppc.hpp | 13 +- src/hotspot/cpu/ppc/assembler_ppc.inline.hpp | 4 + src/hotspot/cpu/ppc/ppc.ad | 131 ++++++++++++++++++ src/hotspot/cpu/ppc/vm_version_ppc.cpp | 7 + src/hotspot/share/classfile/vmSymbols.cpp | 10 ++ src/hotspot/share/classfile/vmSymbols.hpp | 10 ++ src/hotspot/share/opto/c2_globals.hpp | 5 +- src/hotspot/share/opto/c2compiler.cpp | 12 ++ src/hotspot/share/opto/classes.hpp | 4 + src/hotspot/share/opto/intrinsicnode.hpp | 38 ++++- src/hotspot/share/opto/library_call.cpp | 33 +++++ .../share/classes/java/lang/Character.java | 6 +- .../classes/java/lang/CharacterData.java | 5 +- .../openjdk/bench/java/lang/Characters.java | 64 +++++++++ 21 files changed, 468 insertions(+), 38 deletions(-) create mode 100644 test/micro/org/openjdk/bench/java/lang/Characters.java diff --git a/make/data/characterdata/CharacterData00.java.template b/make/data/characterdata/CharacterData00.java.template index 46f90a138b4..a334bb11ca3 100644 --- a/make/data/characterdata/CharacterData00.java.template +++ b/make/data/characterdata/CharacterData00.java.template @@ -754,6 +754,21 @@ class CharacterData00 extends CharacterData { return retval; } + boolean isDigit(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.DECIMAL_DIGIT_NUMBER; + } + + boolean isLowerCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.LOWERCASE_LETTER; + } + + boolean isUpperCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.UPPERCASE_LETTER; + } + boolean isWhitespace(int ch) { int props = getProperties(ch); return ((props & $$maskIdentifierInfo) == $$valueJavaWhitespace); diff --git a/make/data/characterdata/CharacterData01.java.template b/make/data/characterdata/CharacterData01.java.template index 65008af5efd..d2ba89f60ee 100644 --- a/make/data/characterdata/CharacterData01.java.template +++ b/make/data/characterdata/CharacterData01.java.template @@ -460,6 +460,21 @@ class CharacterData01 extends CharacterData { return retval; } + boolean isDigit(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.DECIMAL_DIGIT_NUMBER; + } + + boolean isLowerCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.LOWERCASE_LETTER; + } + + boolean isUpperCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.UPPERCASE_LETTER; + } + boolean isWhitespace(int ch) { int props = getProperties(ch); return ((props & $$maskIdentifierInfo) == $$valueJavaWhitespace); diff --git a/make/data/characterdata/CharacterData02.java.template b/make/data/characterdata/CharacterData02.java.template index ea50e8f5219..561a0a10c41 100644 --- a/make/data/characterdata/CharacterData02.java.template +++ b/make/data/characterdata/CharacterData02.java.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -217,6 +217,21 @@ class CharacterData02 extends CharacterData { return retval; } + boolean isDigit(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.DECIMAL_DIGIT_NUMBER; + } + + boolean isLowerCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.LOWERCASE_LETTER; + } + + boolean isUpperCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.UPPERCASE_LETTER; + } + boolean isWhitespace(int ch) { return (getProperties(ch) & $$maskIdentifierInfo) == $$valueJavaWhitespace; } diff --git a/make/data/characterdata/CharacterData0E.java.template b/make/data/characterdata/CharacterData0E.java.template index 7b27d647479..ac147476b4d 100644 --- a/make/data/characterdata/CharacterData0E.java.template +++ b/make/data/characterdata/CharacterData0E.java.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -217,6 +217,21 @@ class CharacterData0E extends CharacterData { return retval; } + boolean isDigit(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.DECIMAL_DIGIT_NUMBER; + } + + boolean isLowerCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.LOWERCASE_LETTER; + } + + boolean isUpperCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.UPPERCASE_LETTER; + } + boolean isWhitespace(int ch) { int props = getProperties(ch); return ((props & $$maskIdentifierInfo) == $$valueJavaWhitespace); diff --git a/make/data/characterdata/CharacterDataLatin1.java.template b/make/data/characterdata/CharacterDataLatin1.java.template index a3a116781a2..564d640b55a 100644 --- a/make/data/characterdata/CharacterDataLatin1.java.template +++ b/make/data/characterdata/CharacterDataLatin1.java.template @@ -25,6 +25,8 @@ package java.lang; +import jdk.internal.HotSpotIntrinsicCandidate; + /** The CharacterData class encapsulates the large tables found in Java.lang.Character. */ @@ -78,6 +80,23 @@ class CharacterDataLatin1 extends CharacterData { return props; } + @HotSpotIntrinsicCandidate + boolean isDigit(int ch) { + return '0' <= ch && ch <= '9'; + } + + @HotSpotIntrinsicCandidate + boolean isLowerCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.LOWERCASE_LETTER; + } + + @HotSpotIntrinsicCandidate + boolean isUpperCase(int ch) { + int props = getProperties(ch); + return (props & $$maskType) == Character.UPPERCASE_LETTER; + } + boolean isOtherLowercase(int ch) { int props = getPropertiesEx(ch); return (props & $$maskOtherLowercase) != 0; @@ -214,6 +233,7 @@ class CharacterDataLatin1 extends CharacterData { return retval; } + @HotSpotIntrinsicCandidate boolean isWhitespace(int ch) { int props = getProperties(ch); return ((props & $$maskIdentifierInfo) == $$valueJavaWhitespace); diff --git a/make/data/characterdata/CharacterDataPrivateUse.java.template b/make/data/characterdata/CharacterDataPrivateUse.java.template index 3caf6f550fb..49c34966354 100644 --- a/make/data/characterdata/CharacterDataPrivateUse.java.template +++ b/make/data/characterdata/CharacterDataPrivateUse.java.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,47 +41,59 @@ class CharacterDataPrivateUse extends CharacterData { } boolean isJavaIdentifierStart(int ch) { - return false; + return false; } boolean isJavaIdentifierPart(int ch) { - return false; + return false; } boolean isUnicodeIdentifierStart(int ch) { - return false; + return false; } boolean isUnicodeIdentifierPart(int ch) { - return false; + return false; } boolean isIdentifierIgnorable(int ch) { - return false; + return false; } int toLowerCase(int ch) { - return ch; + return ch; } int toUpperCase(int ch) { - return ch; + return ch; } int toTitleCase(int ch) { - return ch; + return ch; } int digit(int ch, int radix) { - return -1; + return -1; } int getNumericValue(int ch) { - return -1; + return -1; + } + + boolean isDigit(int ch) { + return false; + } + + boolean isLowerCase(int ch) { + return false; + } + + boolean isUpperCase(int ch) { + return false; } boolean isWhitespace(int ch) { - return false; + return false; } byte getDirectionality(int ch) { @@ -91,7 +103,7 @@ class CharacterDataPrivateUse extends CharacterData { } boolean isMirrored(int ch) { - return false; + return false; } static final CharacterData instance = new CharacterDataPrivateUse(); diff --git a/make/data/characterdata/CharacterDataUndefined.java.template b/make/data/characterdata/CharacterDataUndefined.java.template index 41360e6c348..a6d240f11b4 100644 --- a/make/data/characterdata/CharacterDataUndefined.java.template +++ b/make/data/characterdata/CharacterDataUndefined.java.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,59 +35,71 @@ class CharacterDataUndefined extends CharacterData { } int getType(int ch) { - return Character.UNASSIGNED; + return Character.UNASSIGNED; } boolean isJavaIdentifierStart(int ch) { - return false; + return false; } boolean isJavaIdentifierPart(int ch) { - return false; + return false; } boolean isUnicodeIdentifierStart(int ch) { - return false; + return false; } boolean isUnicodeIdentifierPart(int ch) { - return false; + return false; } boolean isIdentifierIgnorable(int ch) { - return false; + return false; } int toLowerCase(int ch) { - return ch; + return ch; } int toUpperCase(int ch) { - return ch; + return ch; } int toTitleCase(int ch) { - return ch; + return ch; } int digit(int ch, int radix) { - return -1; + return -1; } int getNumericValue(int ch) { - return -1; + return -1; + } + + boolean isDigit(int ch) { + return false; + } + + boolean isLowerCase(int ch) { + return false; + } + + boolean isUpperCase(int ch) { + return false; } boolean isWhitespace(int ch) { - return false; + return false; } byte getDirectionality(int ch) { - return Character.DIRECTIONALITY_UNDEFINED; + return Character.DIRECTIONALITY_UNDEFINED; } boolean isMirrored(int ch) { - return false; + return false; } static final CharacterData instance = new CharacterDataUndefined(); diff --git a/src/hotspot/cpu/ppc/assembler_ppc.hpp b/src/hotspot/cpu/ppc/assembler_ppc.hpp index 246e7efda85..9e5ed32b382 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.hpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2012, 2017 SAP SE. All rights reserved. + * Copyright (c) 2012, 2018 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -299,6 +299,8 @@ class Assembler : public AbstractAssembler { CMPI_OPCODE = (11u << OPCODE_SHIFT), CMPL_OPCODE = (31u << OPCODE_SHIFT | 32u << 1), CMPLI_OPCODE = (10u << OPCODE_SHIFT), + CMPRB_OPCODE = (31u << OPCODE_SHIFT | 192u << 1), + CMPEQB_OPCODE = (31u << OPCODE_SHIFT | 224u << 1), ISEL_OPCODE = (31u << OPCODE_SHIFT | 15u << 1), @@ -336,6 +338,7 @@ class Assembler : public AbstractAssembler { MTCRF_OPCODE = (31u << OPCODE_SHIFT | 144u << 1), MFCR_OPCODE = (31u << OPCODE_SHIFT | 19u << 1), MCRF_OPCODE = (19u << OPCODE_SHIFT | 0u << 1), + SETB_OPCODE = (31u << OPCODE_SHIFT | 128u << 1), // condition register logic instructions CRAND_OPCODE = (19u << OPCODE_SHIFT | 257u << 1), @@ -1076,7 +1079,7 @@ class Assembler : public AbstractAssembler { static int frs( int x) { return opp_u_field(x, 10, 6); } static int frt( int x) { return opp_u_field(x, 10, 6); } static int fxm( int x) { return opp_u_field(x, 19, 12); } - static int l10( int x) { return opp_u_field(x, 10, 10); } + static int l10( int x) { assert(x == 0 || x == 1, "must be 0 or 1"); return opp_u_field(x, 10, 10); } static int l14( int x) { return opp_u_field(x, 15, 14); } static int l15( int x) { return opp_u_field(x, 15, 15); } static int l910( int x) { return opp_u_field(x, 10, 9); } @@ -1443,6 +1446,10 @@ class Assembler : public AbstractAssembler { inline void cmplw( ConditionRegister crx, Register a, Register b); inline void cmpld( ConditionRegister crx, Register a, Register b); + // >= Power9 + inline void cmprb( ConditionRegister bf, int l, Register a, Register b); + inline void cmpeqb(ConditionRegister bf, Register a, Register b); + inline void isel( Register d, Register a, Register b, int bc); // Convenient version which takes: Condition register, Condition code and invert flag. Omit b to keep old value. inline void isel( Register d, ConditionRegister cr, Condition cc, bool inv, Register a, Register b = noreg); @@ -1642,6 +1649,8 @@ class Assembler : public AbstractAssembler { inline void mfcr( Register d); inline void mcrf( ConditionRegister crd, ConditionRegister cra); inline void mtcr( Register s); + // >= Power9 + inline void setb( Register d, ConditionRegister cra); // Special purpose registers // Exception Register diff --git a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp index e3b2cbb51a4..1159a219bf1 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp @@ -171,6 +171,8 @@ inline void Assembler::cmpi( ConditionRegister f, int l, Register a, int si16) inline void Assembler::cmp( ConditionRegister f, int l, Register a, Register b) { emit_int32( CMP_OPCODE | bf(f) | l10(l) | ra(a) | rb(b)); } inline void Assembler::cmpli( ConditionRegister f, int l, Register a, int ui16) { emit_int32( CMPLI_OPCODE | bf(f) | l10(l) | ra(a) | uimm(ui16,16)); } inline void Assembler::cmpl( ConditionRegister f, int l, Register a, Register b) { emit_int32( CMPL_OPCODE | bf(f) | l10(l) | ra(a) | rb(b)); } +inline void Assembler::cmprb( ConditionRegister f, int l, Register a, Register b) { emit_int32( CMPRB_OPCODE | bf(f) | l10(l) | ra(a) | rb(b)); } +inline void Assembler::cmpeqb(ConditionRegister f, Register a, Register b) { emit_int32( CMPEQB_OPCODE| bf(f) | ra(a) | rb(b)); } // extended mnemonics of Compare Instructions inline void Assembler::cmpwi( ConditionRegister crx, Register a, int si16) { Assembler::cmpi( crx, 0, a, si16); } @@ -371,6 +373,8 @@ inline void Assembler::mfcr( Register d ) { emit_int32(MFCR_OPCODE | rt inline void Assembler::mcrf( ConditionRegister crd, ConditionRegister cra) { emit_int32(MCRF_OPCODE | bf(crd) | bfa(cra)); } inline void Assembler::mtcr( Register s) { Assembler::mtcrf(0xff, s); } +inline void Assembler::setb(Register d, ConditionRegister cra) + { emit_int32(SETB_OPCODE | rt(d) | bfa(cra)); } // Special purpose registers // Exception Register diff --git a/src/hotspot/cpu/ppc/ppc.ad b/src/hotspot/cpu/ppc/ppc.ad index 988abf1d861..40f8c4b223a 100644 --- a/src/hotspot/cpu/ppc/ppc.ad +++ b/src/hotspot/cpu/ppc/ppc.ad @@ -2257,6 +2257,11 @@ const bool Matcher::match_rule_supported(int opcode) { return SuperwordUseVSX; case Op_PopCountVI: return (SuperwordUseVSX && UsePopCountInstruction); + case Op_Digit: + case Op_LowerCase: + case Op_UpperCase: + case Op_Whitespace: + return UseCharacterCompareIntrinsics; } return true; // Per default match rules are supported. @@ -12400,6 +12405,132 @@ instruct cmpD3_reg_reg_ExEx(iRegIdst dst, regD src1, regD src2) %{ %} %} +// Compare char +instruct cmprb_Digit_reg_reg(iRegIdst dst, iRegIsrc src1, iRegIsrc src2, flagsReg crx) %{ + match(Set dst (Digit src1)); + effect(TEMP src2, TEMP crx); + ins_cost(3 * DEFAULT_COST); + + format %{ "LI $src2, 0x3930\n\t" + "CMPRB $crx, 0, $src1, $src2\n\t" + "SETB $dst, $crx" %} + size(12); + ins_encode %{ + // 0x30: 0, 0x39: 9 + __ li($src2$$Register, 0x3930); + // compare src1 with ranges 0x30 to 0x39 + __ cmprb($crx$$CondRegister, 0, $src1$$Register, $src2$$Register); + __ setb($dst$$Register, $crx$$CondRegister); + %} + ins_pipe(pipe_class_default); +%} + +instruct cmprb_LowerCase_reg_reg(iRegIdst dst, iRegIsrc src1, iRegIsrc src2, flagsReg crx) %{ + match(Set dst (LowerCase src1)); + effect(TEMP src2, TEMP crx); + ins_cost(12 * DEFAULT_COST); + + format %{ "LI $src2, 0x7A61\n\t" + "CMPRB $crx, 0, $src1, $src2\n\t" + "BGT $crx, done\n\t" + "LIS $src2, (signed short)0xF6DF\n\t" + "ORI $src2, $src2, 0xFFF8\n\t" + "CMPRB $crx, 1, $src1, $src2\n\t" + "BGT $crx, done\n\t" + "LIS $src2, (signed short)0xAAB5\n\t" + "ORI $src2, $src2, 0xBABA\n\t" + "INSRDI $src2, $src2, 32, 0\n\t" + "CMPEQB $crx, 1, $src1, $src2\n" + "done:\n\t" + "SETB $dst, $crx" %} + + size(48); + ins_encode %{ + Label done; + // 0x61: a, 0x7A: z + __ li($src2$$Register, 0x7A61); + // compare src1 with ranges 0x61 to 0x7A + __ cmprb($crx$$CondRegister, 0, $src1$$Register, $src2$$Register); + __ bgt($crx$$CondRegister, done); + + // 0xDF: sharp s, 0xFF: y with diaeresis, 0xF7 is not the lower case + __ lis($src2$$Register, (signed short)0xF6DF); + __ ori($src2$$Register, $src2$$Register, 0xFFF8); + // compare src1 with ranges 0xDF to 0xF6 and 0xF8 to 0xFF + __ cmprb($crx$$CondRegister, 1, $src1$$Register, $src2$$Register); + __ bgt($crx$$CondRegister, done); + + // 0xAA: feminine ordinal indicator + // 0xB5: micro sign + // 0xBA: masculine ordinal indicator + __ lis($src2$$Register, (signed short)0xAAB5); + __ ori($src2$$Register, $src2$$Register, 0xBABA); + __ insrdi($src2$$Register, $src2$$Register, 32, 0); + // compare src1 with 0xAA, 0xB5, and 0xBA + __ cmpeqb($crx$$CondRegister, $src1$$Register, $src2$$Register); + + __ bind(done); + __ setb($dst$$Register, $crx$$CondRegister); + %} + ins_pipe(pipe_class_default); +%} + +instruct cmprb_UpperCase_reg_reg(iRegIdst dst, iRegIsrc src1, iRegIsrc src2, flagsReg crx) %{ + match(Set dst (UpperCase src1)); + effect(TEMP src2, TEMP crx); + ins_cost(7 * DEFAULT_COST); + + format %{ "LI $src2, 0x5A41\n\t" + "CMPRB $crx, 0, $src1, $src2\n\t" + "BGT $crx, done\n\t" + "LIS $src2, (signed short)0xD6C0\n\t" + "ORI $src2, $src2, 0xDED8\n\t" + "CMPRB $crx, 1, $src1, $src2\n" + "done:\n\t" + "SETB $dst, $crx" %} + + size(28); + ins_encode %{ + Label done; + // 0x41: A, 0x5A: Z + __ li($src2$$Register, 0x5A41); + // compare src1 with a range 0x41 to 0x5A + __ cmprb($crx$$CondRegister, 0, $src1$$Register, $src2$$Register); + __ bgt($crx$$CondRegister, done); + + // 0xC0: a with grave, 0xDE: thorn, 0xD7 is not the upper case + __ lis($src2$$Register, (signed short)0xD6C0); + __ ori($src2$$Register, $src2$$Register, 0xDED8); + // compare src1 with ranges 0xC0 to 0xD6 and 0xD8 to 0xDE + __ cmprb($crx$$CondRegister, 1, $src1$$Register, $src2$$Register); + + __ bind(done); + __ setb($dst$$Register, $crx$$CondRegister); + %} + ins_pipe(pipe_class_default); +%} + +instruct cmprb_Whitespace_reg_reg(iRegIdst dst, iRegIsrc src1, iRegIsrc src2, flagsReg crx) %{ + match(Set dst (Whitespace src1)); + effect(TEMP src2, TEMP crx); + ins_cost(4 * DEFAULT_COST); + + format %{ "LI $src2, 0x0D09\n\t" + "ADDIS $src2, 0x201C\n\t" + "CMPRB $crx, 1, $src1, $src2\n\t" + "SETB $dst, $crx" %} + size(16); + ins_encode %{ + // 0x09 to 0x0D, 0x1C to 0x20 + __ li($src2$$Register, 0x0D09); + __ addis($src2$$Register, $src2$$Register, 0x0201C); + // compare src with ranges 0x09 to 0x0D and 0x1C to 0x20 + __ cmprb($crx$$CondRegister, 1, $src1$$Register, $src2$$Register); + __ setb($dst$$Register, $crx$$CondRegister); + %} + ins_pipe(pipe_class_default); +%} + //----------Branches--------------------------------------------------------- // Jump diff --git a/src/hotspot/cpu/ppc/vm_version_ppc.cpp b/src/hotspot/cpu/ppc/vm_version_ppc.cpp index ae8a4b52945..e5a62383801 100644 --- a/src/hotspot/cpu/ppc/vm_version_ppc.cpp +++ b/src/hotspot/cpu/ppc/vm_version_ppc.cpp @@ -134,11 +134,18 @@ void VM_Version::initialize() { if (FLAG_IS_DEFAULT(UseCountTrailingZerosInstructionsPPC64)) { FLAG_SET_ERGO(bool, UseCountTrailingZerosInstructionsPPC64, true); } + if (FLAG_IS_DEFAULT(UseCharacterCompareIntrinsics)) { + FLAG_SET_ERGO(bool, UseCharacterCompareIntrinsics, true); + } } else { if (UseCountTrailingZerosInstructionsPPC64) { warning("UseCountTrailingZerosInstructionsPPC64 specified, but needs at least Power9."); FLAG_SET_DEFAULT(UseCountTrailingZerosInstructionsPPC64, false); } + if (UseCharacterCompareIntrinsics) { + warning("UseCharacterCompareIntrinsics specified, but needs at least Power9."); + FLAG_SET_DEFAULT(UseCharacterCompareIntrinsics, false); + } } #endif diff --git a/src/hotspot/share/classfile/vmSymbols.cpp b/src/hotspot/share/classfile/vmSymbols.cpp index 1def05a9c4d..b8b56e4a84d 100644 --- a/src/hotspot/share/classfile/vmSymbols.cpp +++ b/src/hotspot/share/classfile/vmSymbols.cpp @@ -379,6 +379,10 @@ bool vmIntrinsics::preserves_state(vmIntrinsics::ID id) { case vmIntrinsics::_vectorizedMismatch: case vmIntrinsics::_fmaD: case vmIntrinsics::_fmaF: + case vmIntrinsics::_isDigit: + case vmIntrinsics::_isLowerCase: + case vmIntrinsics::_isUpperCase: + case vmIntrinsics::_isWhitespace: return true; default: return false; @@ -828,6 +832,12 @@ bool vmIntrinsics::is_disabled_by_flags(vmIntrinsics::ID id) { case vmIntrinsics::_subtractExactL: if (!UseMathExactIntrinsics || !InlineMathNatives) return true; break; + case vmIntrinsics::_isDigit: + case vmIntrinsics::_isLowerCase: + case vmIntrinsics::_isUpperCase: + case vmIntrinsics::_isWhitespace: + if (!UseCharacterCompareIntrinsics) return true; + break; #endif // COMPILER2 default: return false; diff --git a/src/hotspot/share/classfile/vmSymbols.hpp b/src/hotspot/share/classfile/vmSymbols.hpp index a3034fc217e..0e0b77aca1c 100644 --- a/src/hotspot/share/classfile/vmSymbols.hpp +++ b/src/hotspot/share/classfile/vmSymbols.hpp @@ -71,6 +71,7 @@ template(java_lang_Boolean, "java/lang/Boolean") \ template(java_lang_Character, "java/lang/Character") \ template(java_lang_Character_CharacterCache, "java/lang/Character$CharacterCache") \ + template(java_lang_CharacterDataLatin1, "java/lang/CharacterDataLatin1") \ template(java_lang_Float, "java/lang/Float") \ template(java_lang_Double, "java/lang/Double") \ template(java_lang_Byte, "java/lang/Byte") \ @@ -933,6 +934,15 @@ do_intrinsic(_equalsL, java_lang_StringLatin1,equals_name, equalsB_signature, F_S) \ do_intrinsic(_equalsU, java_lang_StringUTF16, equals_name, equalsB_signature, F_S) \ \ + do_intrinsic(_isDigit, java_lang_CharacterDataLatin1, isDigit_name, int_bool_signature, F_R) \ + do_name( isDigit_name, "isDigit") \ + do_intrinsic(_isLowerCase, java_lang_CharacterDataLatin1, isLowerCase_name, int_bool_signature, F_R) \ + do_name( isLowerCase_name, "isLowerCase") \ + do_intrinsic(_isUpperCase, java_lang_CharacterDataLatin1, isUpperCase_name, int_bool_signature, F_R) \ + do_name( isUpperCase_name, "isUpperCase") \ + do_intrinsic(_isWhitespace, java_lang_CharacterDataLatin1, isWhitespace_name, int_bool_signature, F_R) \ + do_name( isWhitespace_name, "isWhitespace") \ + \ do_intrinsic(_Preconditions_checkIndex, jdk_internal_util_Preconditions, checkIndex_name, Preconditions_checkIndex_signature, F_S) \ do_signature(Preconditions_checkIndex_signature, "(IILjava/util/function/BiFunction;)I") \ \ diff --git a/src/hotspot/share/opto/c2_globals.hpp b/src/hotspot/share/opto/c2_globals.hpp index 868833c780b..8111a63d489 100644 --- a/src/hotspot/share/opto/c2_globals.hpp +++ b/src/hotspot/share/opto/c2_globals.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -710,6 +710,9 @@ diagnostic(bool, UseMathExactIntrinsics, true, \ "Enables intrinsification of various java.lang.Math functions") \ \ + diagnostic(bool, UseCharacterCompareIntrinsics, false, \ + "Enables intrinsification of java.lang.Character functions") \ + \ diagnostic(bool, UseMultiplyToLenIntrinsic, false, \ "Enables intrinsification of BigInteger.multiplyToLen()") \ \ diff --git a/src/hotspot/share/opto/c2compiler.cpp b/src/hotspot/share/opto/c2compiler.cpp index 7f4243d993f..0b2ff2b190a 100644 --- a/src/hotspot/share/opto/c2compiler.cpp +++ b/src/hotspot/share/opto/c2compiler.cpp @@ -428,6 +428,18 @@ bool C2Compiler::is_intrinsic_supported(const methodHandle& method, bool is_virt case vmIntrinsics::_fmaF: if (!UseFMA || !Matcher::match_rule_supported(Op_FmaF)) return false; break; + case vmIntrinsics::_isDigit: + if (!Matcher::match_rule_supported(Op_Digit)) return false; + break; + case vmIntrinsics::_isLowerCase: + if (!Matcher::match_rule_supported(Op_LowerCase)) return false; + break; + case vmIntrinsics::_isUpperCase: + if (!Matcher::match_rule_supported(Op_UpperCase)) return false; + break; + case vmIntrinsics::_isWhitespace: + if (!Matcher::match_rule_supported(Op_Whitespace)) return false; + break; case vmIntrinsics::_hashCode: case vmIntrinsics::_identityHashCode: case vmIntrinsics::_getClass: diff --git a/src/hotspot/share/opto/classes.hpp b/src/hotspot/share/opto/classes.hpp index d92a5840127..edfbc6afa2a 100644 --- a/src/hotspot/share/opto/classes.hpp +++ b/src/hotspot/share/opto/classes.hpp @@ -394,3 +394,7 @@ macro(ExtractI) macro(ExtractL) macro(ExtractF) macro(ExtractD) +macro(Digit) +macro(LowerCase) +macro(UpperCase) +macro(Whitespace) diff --git a/src/hotspot/share/opto/intrinsicnode.hpp b/src/hotspot/share/opto/intrinsicnode.hpp index 450638076b8..eb36919971e 100644 --- a/src/hotspot/share/opto/intrinsicnode.hpp +++ b/src/hotspot/share/opto/intrinsicnode.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -180,4 +180,40 @@ class EncodeISOArrayNode: public Node { virtual const Type* Value(PhaseGVN* phase) const; }; +//-------------------------------DigitNode---------------------------------------- +class DigitNode : public Node { +public: + DigitNode(Node* control, Node *in1) : Node(control, in1) {} + virtual int Opcode() const; + const Type* bottom_type() const { return TypeInt::BOOL; } + virtual uint ideal_reg() const { return Op_RegI; } +}; + +//------------------------------LowerCaseNode------------------------------------ +class LowerCaseNode : public Node { +public: + LowerCaseNode(Node* control, Node *in1) : Node(control, in1) {} + virtual int Opcode() const; + const Type* bottom_type() const { return TypeInt::BOOL; } + virtual uint ideal_reg() const { return Op_RegI; } +}; + +//------------------------------UpperCaseNode------------------------------------ +class UpperCaseNode : public Node { +public: + UpperCaseNode(Node* control, Node *in1) : Node(control, in1) {} + virtual int Opcode() const; + const Type* bottom_type() const { return TypeInt::BOOL; } + virtual uint ideal_reg() const { return Op_RegI; } +}; + +//------------------------------WhitespaceCode----------------------------------- +class WhitespaceNode : public Node { +public: + WhitespaceNode(Node* control, Node *in1) : Node(control, in1) {} + virtual int Opcode() const; + const Type* bottom_type() const { return TypeInt::BOOL; } + virtual uint ideal_reg() const { return Op_RegI; } +}; + #endif // SHARE_VM_OPTO_INTRINSICNODE_HPP diff --git a/src/hotspot/share/opto/library_call.cpp b/src/hotspot/share/opto/library_call.cpp index 2f733e1e73a..60d97657b00 100644 --- a/src/hotspot/share/opto/library_call.cpp +++ b/src/hotspot/share/opto/library_call.cpp @@ -324,6 +324,7 @@ class LibraryCallKit : public GraphKit { bool inline_montgomerySquare(); bool inline_vectorizedMismatch(); bool inline_fma(vmIntrinsics::ID id); + bool inline_character_compare(vmIntrinsics::ID id); bool inline_profileBoolean(); bool inline_isCompileConstant(); @@ -867,6 +868,12 @@ bool LibraryCallKit::try_to_inline(int predicate) { case vmIntrinsics::_fmaF: return inline_fma(intrinsic_id()); + case vmIntrinsics::_isDigit: + case vmIntrinsics::_isLowerCase: + case vmIntrinsics::_isUpperCase: + case vmIntrinsics::_isWhitespace: + return inline_character_compare(intrinsic_id()); + default: // If you get here, it may be that someone has added a new intrinsic // to the list in vmSymbols.hpp without implementing it here. @@ -6555,6 +6562,32 @@ bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) { return true; } +bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) { + // argument(0) is receiver + Node* codePoint = argument(1); + Node* n = NULL; + + switch (id) { + case vmIntrinsics::_isDigit : + n = new DigitNode(control(), codePoint); + break; + case vmIntrinsics::_isLowerCase : + n = new LowerCaseNode(control(), codePoint); + break; + case vmIntrinsics::_isUpperCase : + n = new UpperCaseNode(control(), codePoint); + break; + case vmIntrinsics::_isWhitespace : + n = new WhitespaceNode(control(), codePoint); + break; + default: + fatal_unexpected_iid(id); + } + + set_result(_gvn.transform(n)); + return true; +} + bool LibraryCallKit::inline_profileBoolean() { Node* counts = argument(1); const TypeAryPtr* ary = NULL; diff --git a/src/java.base/share/classes/java/lang/Character.java b/src/java.base/share/classes/java/lang/Character.java index 7f1ebc6e392..1c3580c24d7 100644 --- a/src/java.base/share/classes/java/lang/Character.java +++ b/src/java.base/share/classes/java/lang/Character.java @@ -9085,7 +9085,7 @@ class Character implements java.io.Serializable, Comparable { * @since 1.5 */ public static boolean isLowerCase(int codePoint) { - return getType(codePoint) == Character.LOWERCASE_LETTER || + return CharacterData.of(codePoint).isLowerCase(codePoint) || CharacterData.of(codePoint).isOtherLowercase(codePoint); } @@ -9151,7 +9151,7 @@ class Character implements java.io.Serializable, Comparable { * @since 1.5 */ public static boolean isUpperCase(int codePoint) { - return getType(codePoint) == Character.UPPERCASE_LETTER || + return CharacterData.of(codePoint).isUpperCase(codePoint) || CharacterData.of(codePoint).isOtherUppercase(codePoint); } @@ -9302,7 +9302,7 @@ class Character implements java.io.Serializable, Comparable { * @since 1.5 */ public static boolean isDigit(int codePoint) { - return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER; + return CharacterData.of(codePoint).isDigit(codePoint); } /** diff --git a/src/java.base/share/classes/java/lang/CharacterData.java b/src/java.base/share/classes/java/lang/CharacterData.java index d6b05f4f847..1cc296fa82a 100644 --- a/src/java.base/share/classes/java/lang/CharacterData.java +++ b/src/java.base/share/classes/java/lang/CharacterData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -28,6 +28,9 @@ package java.lang; abstract class CharacterData { abstract int getProperties(int ch); abstract int getType(int ch); + abstract boolean isDigit(int ch); + abstract boolean isLowerCase(int ch); + abstract boolean isUpperCase(int ch); abstract boolean isWhitespace(int ch); abstract boolean isMirrored(int ch); abstract boolean isJavaIdentifierStart(int ch); diff --git a/test/micro/org/openjdk/bench/java/lang/Characters.java b/test/micro/org/openjdk/bench/java/lang/Characters.java new file mode 100644 index 00000000000..3d1df9dc3ee --- /dev/null +++ b/test/micro/org/openjdk/bench/java/lang/Characters.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.java.lang; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +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.State; + +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +public class Characters { + + @Param({"9", "48", "65", "97", "128", "170", "192", "223"}) + private int codePoint; + + @Benchmark + public boolean isDigit() { + return Character.isDigit(codePoint); + } + + @Benchmark + public boolean isLowerCase() { + return Character.isLowerCase(codePoint); + } + + @Benchmark + public boolean isUpperCase() { + return Character.isUpperCase(codePoint); + } + + @Benchmark + public boolean isWhitespace() { + return Character.isWhitespace(codePoint); + } +} From b7bd4bccbfd82833755053a136844b4071068a6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20=C3=96sterlund?= Date: Wed, 12 Dec 2018 14:18:16 +0100 Subject: [PATCH 011/174] 8215206: VtableStubs::find_stub is not appropriately protected by VtableStubs_lock Reviewed-by: thartmann, pliden --- src/hotspot/share/code/vtableStubs.cpp | 55 ++++++++++++++------------ 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/src/hotspot/share/code/vtableStubs.cpp b/src/hotspot/share/code/vtableStubs.cpp index ae0787e28ce..eb994f2bd80 100644 --- a/src/hotspot/share/code/vtableStubs.cpp +++ b/src/hotspot/share/code/vtableStubs.cpp @@ -51,6 +51,7 @@ VMReg VtableStub::_receiver_location = VMRegImpl::Bad(); void* VtableStub::operator new(size_t size, int code_size) throw() { + assert_lock_strong(VtableStubs_lock); assert(size == sizeof(VtableStub), "mismatched size"); // compute real VtableStub size (rounded to nearest word) const int real_size = align_up(code_size + (int)sizeof(VtableStub), wordSize); @@ -208,31 +209,35 @@ void VtableStubs::bookkeeping(MacroAssembler* masm, outputStream* out, VtableStu address VtableStubs::find_stub(bool is_vtable_stub, int vtable_index) { assert(vtable_index >= 0, "must be positive"); - VtableStub* s = ShareVtableStubs ? lookup(is_vtable_stub, vtable_index) : NULL; - if (s == NULL) { - if (is_vtable_stub) { - s = create_vtable_stub(vtable_index); - } else { - s = create_itable_stub(vtable_index); - } - - // Creation of vtable or itable can fail if there is not enough free space in the code cache. + VtableStub* s; + { + MutexLockerEx ml(VtableStubs_lock, Mutex::_no_safepoint_check_flag); + s = ShareVtableStubs ? lookup(is_vtable_stub, vtable_index) : NULL; if (s == NULL) { - return NULL; - } + if (is_vtable_stub) { + s = create_vtable_stub(vtable_index); + } else { + s = create_itable_stub(vtable_index); + } - enter(is_vtable_stub, vtable_index, s); - if (PrintAdapterHandlers) { - tty->print_cr("Decoding VtableStub %s[%d]@" INTX_FORMAT, - is_vtable_stub? "vtbl": "itbl", vtable_index, p2i(VtableStub::receiver_location())); - Disassembler::decode(s->code_begin(), s->code_end()); - } - // Notify JVMTI about this stub. The event will be recorded by the enclosing - // JvmtiDynamicCodeEventCollector and posted when this thread has released - // all locks. - if (JvmtiExport::should_post_dynamic_code_generated()) { - JvmtiExport::post_dynamic_code_generated_while_holding_locks(is_vtable_stub? "vtable stub": "itable stub", - s->code_begin(), s->code_end()); + // Creation of vtable or itable can fail if there is not enough free space in the code cache. + if (s == NULL) { + return NULL; + } + + enter(is_vtable_stub, vtable_index, s); + if (PrintAdapterHandlers) { + tty->print_cr("Decoding VtableStub %s[%d]@" INTX_FORMAT, + is_vtable_stub? "vtbl": "itbl", vtable_index, p2i(VtableStub::receiver_location())); + Disassembler::decode(s->code_begin(), s->code_end()); + } + // Notify JVMTI about this stub. The event will be recorded by the enclosing + // JvmtiDynamicCodeEventCollector and posted when this thread has released + // all locks. + if (JvmtiExport::should_post_dynamic_code_generated()) { + JvmtiExport::post_dynamic_code_generated_while_holding_locks(is_vtable_stub? "vtable stub": "itable stub", + s->code_begin(), s->code_end()); + } } } return s->entry_point(); @@ -247,7 +252,7 @@ inline uint VtableStubs::hash(bool is_vtable_stub, int vtable_index){ VtableStub* VtableStubs::lookup(bool is_vtable_stub, int vtable_index) { - MutexLockerEx ml(VtableStubs_lock, Mutex::_no_safepoint_check_flag); + assert_lock_strong(VtableStubs_lock); unsigned hash = VtableStubs::hash(is_vtable_stub, vtable_index); VtableStub* s = _table[hash]; while( s && !s->matches(is_vtable_stub, vtable_index)) s = s->next(); @@ -256,7 +261,7 @@ VtableStub* VtableStubs::lookup(bool is_vtable_stub, int vtable_index) { void VtableStubs::enter(bool is_vtable_stub, int vtable_index, VtableStub* s) { - MutexLockerEx ml(VtableStubs_lock, Mutex::_no_safepoint_check_flag); + assert_lock_strong(VtableStubs_lock); assert(s->matches(is_vtable_stub, vtable_index), "bad vtable stub"); unsigned int h = VtableStubs::hash(is_vtable_stub, vtable_index); // enter s at the beginning of the corresponding list From 85ffc2803c38fa41fb29b553a6e0bd0d9c9b8d3b Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Wed, 12 Dec 2018 18:35:26 +0100 Subject: [PATCH 012/174] 8165675: Trace event for thread park has incorrect unit for timeout Reviewed-by: mgronlun --- src/hotspot/share/jfr/metadata/metadata.xml | 6 ++- src/hotspot/share/prims/unsafe.cpp | 16 ++++-- .../jdk/internal/event/EventHelper.java | 3 ++ .../jdk/jfr/consumer/RecordedObject.java | 12 ++++- .../jdk/jfr/internal/tool/PrettyWriter.java | 43 ++++++++++++++-- .../event/runtime/TestThreadParkEvent.java | 49 +++++++++++++++---- .../jmx/security/TestEnoughPermission.java | 2 +- test/lib/jdk/test/lib/jfr/Events.java | 47 ++++++++++++++++++ 8 files changed, 158 insertions(+), 20 deletions(-) diff --git a/src/hotspot/share/jfr/metadata/metadata.xml b/src/hotspot/share/jfr/metadata/metadata.xml index 8c665c87222..83bb36c8037 100644 --- a/src/hotspot/share/jfr/metadata/metadata.xml +++ b/src/hotspot/share/jfr/metadata/metadata.xml @@ -40,7 +40,8 @@ - + + @@ -1140,5 +1141,6 @@ - + + diff --git a/src/hotspot/share/prims/unsafe.cpp b/src/hotspot/share/prims/unsafe.cpp index 2775123fe37..91d10f7a62d 100644 --- a/src/hotspot/share/prims/unsafe.cpp +++ b/src/hotspot/share/prims/unsafe.cpp @@ -926,11 +926,12 @@ UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, job } } UNSAFE_END -static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout) { +static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout_nanos, jlong until_epoch_millis) { assert(event != NULL, "invariant"); assert(event->should_commit(), "invariant"); event->set_parkedClass((obj != NULL) ? obj->klass() : NULL); - event->set_timeout(timeout); + event->set_timeout(timeout_nanos); + event->set_until(until_epoch_millis); event->set_address((obj != NULL) ? (u8)cast_from_oop(obj) : 0); event->commit(); } @@ -942,7 +943,16 @@ UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, JavaThreadParkedState jtps(thread, time != 0); thread->parker()->park(isAbsolute != 0, time); if (event.should_commit()) { - post_thread_park_event(&event, thread->current_park_blocker(), time); + const oop obj = thread->current_park_blocker(); + if (time == 0) { + post_thread_park_event(&event, obj, min_jlong, min_jlong); + } else { + if (isAbsolute != 0) { + post_thread_park_event(&event, obj, min_jlong, time); + } else { + post_thread_park_event(&event, obj, time, min_jlong); + } + } } HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker()); } UNSAFE_END diff --git a/src/java.base/share/classes/jdk/internal/event/EventHelper.java b/src/java.base/share/classes/jdk/internal/event/EventHelper.java index 2832945ee81..5eacb9392d5 100644 --- a/src/java.base/share/classes/jdk/internal/event/EventHelper.java +++ b/src/java.base/share/classes/jdk/internal/event/EventHelper.java @@ -101,6 +101,9 @@ public final class EventHelper { */ private static String getDurationString(Instant start) { if (start != null) { + if (start.equals(Instant.MIN)) { + return "N/A"; + } Duration duration = Duration.between(start, Instant.now()); long micros = duration.toNanos() / 1_000; if (micros < 1_000_000) { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordedObject.java b/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordedObject.java index 2d9ed1be696..5633c6068ce 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordedObject.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordedObject.java @@ -726,6 +726,9 @@ public class RecordedObject { private Duration getDuration(long timespan, String name) throws InternalError { ValueDescriptor v = getValueDescriptor(descriptors, name, null); + if (timespan == Long.MIN_VALUE) { + return Duration.ofSeconds(Long.MIN_VALUE, 0); + } Timespan ts = v.getAnnotation(Timespan.class); if (ts != null) { switch (ts.value()) { @@ -797,13 +800,16 @@ public class RecordedObject { return getInstant(Short.toUnsignedLong((Byte) u), name); } } - throw newIllegalArgumentException(name, "java,time.Instant"); + throw newIllegalArgumentException(name, "java.time.Instant"); } private Instant getInstant(long timestamp, String name) { ValueDescriptor v = getValueDescriptor(descriptors, name, null); Timestamp ts = v.getAnnotation(Timestamp.class); if (ts != null) { + if (timestamp == Long.MIN_VALUE) { + return Instant.MIN; + } switch (ts.value()) { case Timestamp.MILLISECONDS_SINCE_EPOCH: return Instant.ofEpochMilli(timestamp); @@ -884,6 +890,10 @@ public class RecordedObject { // package private for now. Used by EventWriter OffsetDateTime getOffsetDateTime(String name) { + Instant instant = getInstant(name); + if (instant.equals(Instant.MIN)) { + return OffsetDateTime.MIN; + } return OffsetDateTime.ofInstant(getInstant(name), timeConverter.getZoneOffset()); } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java index 152b282b29f..eb5260449c0 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java @@ -281,7 +281,7 @@ public final class PrettyWriter extends EventPrintWriter { private void printValue(Object value, ValueDescriptor field, String postFix) { if (value == null) { - println("null" + postFix); + println("N/A" + postFix); return; } if (value instanceof RecordedObject) { @@ -320,6 +320,35 @@ public final class PrettyWriter extends EventPrintWriter { return; } } + if (value instanceof Double) { + Double d = (Double) value; + if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) { + println("N/A"); + return; + } + } + if (value instanceof Float) { + Float f = (Float) value; + if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY) { + println("N/A"); + return; + } + } + if (value instanceof Long) { + Long l = (Long) value; + if (l == Long.MIN_VALUE) { + println("N/A"); + return; + } + } + if (value instanceof Integer) { + Integer i = (Integer) value; + if (i == Integer.MIN_VALUE) { + println("N/A"); + return; + } + } + String text = String.valueOf(value); if (value instanceof String) { text = "\"" + text + "\""; @@ -443,6 +472,10 @@ public final class PrettyWriter extends EventPrintWriter { private boolean printFormatted(ValueDescriptor field, Object value) { if (value instanceof Duration) { Duration d = (Duration) value; + if (d.getSeconds() == Long.MIN_VALUE) { + println("N/A"); + return true; + } double s = d.toNanosPart() / 1000_000_000.0 + d.toSecondsPart(); if (s < 1.0) { if (s < 0.001) { @@ -460,8 +493,12 @@ public final class PrettyWriter extends EventPrintWriter { return true; } if (value instanceof OffsetDateTime) { - OffsetDateTime zdt = (OffsetDateTime) value; - println(TIME_FORMAT.format(zdt)); + OffsetDateTime odt = (OffsetDateTime) value; + if (odt.equals(OffsetDateTime.MIN)) { + println("N/A"); + return true; + } + println(TIME_FORMAT.format(odt)); return true; } Percentage percentage = field.getAnnotation(Percentage.class); diff --git a/test/jdk/jdk/jfr/event/runtime/TestThreadParkEvent.java b/test/jdk/jdk/jfr/event/runtime/TestThreadParkEvent.java index a8f5253264e..8f017ddc118 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestThreadParkEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestThreadParkEvent.java @@ -25,22 +25,25 @@ package jdk.jfr.event.runtime; -import static jdk.test.lib.Asserts.assertFalse; import static jdk.test.lib.Asserts.assertTrue; +import java.nio.file.Files; +import java.nio.file.Paths; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.LockSupport; +import java.util.function.Consumer; import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedEvent; +import jdk.test.lib.Asserts; import jdk.test.lib.jfr.EventNames; import jdk.test.lib.jfr.Events; import jdk.test.lib.management.ThreadMXBeanTool; import jdk.test.lib.thread.TestThread; - /** * @test * @key jfr @@ -58,12 +61,39 @@ public class TestThreadParkEvent { } public static void main(String[] args) throws Throwable { + testParkNoTimeout(); + testParkTimeout(); + testParkUntil(); + } + + private static void testParkNoTimeout() throws Exception { + RecordedEvent event = testPark(x -> LockSupport.park(x), Thread.State.WAITING); + Events.assertMissingValue(event, "timeout"); + Events.assertMissingValue(event, "until"); + } + + private static void testParkTimeout() throws Exception { + Duration expected = Duration.ofNanos(1_234_567_890_123L); + RecordedEvent event = testPark(x -> LockSupport.parkNanos(x, expected.toNanos()), Thread.State.TIMED_WAITING); + Events.assertDuration(event, "timeout", expected); + Events.assertMissingValue(event, "until"); + } + + private static void testParkUntil() throws Exception { + long epochMillis = Instant.now().plusSeconds(1000000).toEpochMilli(); + RecordedEvent event = testPark(x -> LockSupport.parkUntil(x, epochMillis), Thread.State.TIMED_WAITING); + Events.assertMissingValue(event, "timeout"); + Events.assertInstant(event, "until", Instant.ofEpochMilli(epochMillis)); + } + + static RecordedEvent testPark(Consumer parkOperation, Thread.State threadState) throws Exception { + final CountDownLatch stop = new CountDownLatch(1); final Blocker blocker = new Blocker(); TestThread parkThread = new TestThread(new Runnable() { public void run() { while (stop.getCount() > 0) { - LockSupport.park(blocker); + parkOperation.accept(blocker); } } }); @@ -73,7 +103,7 @@ public class TestThreadParkEvent { try { recording.start(); parkThread.start(); - ThreadMXBeanTool.waitUntilBlockingOnObject(parkThread, Thread.State.WAITING, blocker); + ThreadMXBeanTool.waitUntilBlockingOnObject(parkThread, threadState, blocker); // sleep so we know the event is recorded Thread.sleep(2 * THRESHOLD_MILLIS); } finally { @@ -82,22 +112,21 @@ public class TestThreadParkEvent { parkThread.join(); recording.stop(); } - List events = Events.fromRecording(recording); Events.hasEvents(events); - boolean isAnyFound = false; + RecordedEvent foundEvent = null; for (RecordedEvent event : events) { System.out.println("Event:" + event); String klassName = Events.assertField(event, "parkedClass.name").notNull().getValue(); if (klassName.equals(blocker.getClass().getName().replace('.', '/'))) { - assertFalse(isAnyFound, "Found more than 1 event"); - isAnyFound = true; - Events.assertField(event, "timeout").equal(0L); + Asserts.assertNull(foundEvent , "Found more than 1 event"); Events.assertField(event, "address").notEqual(0L); Events.assertEventThread(event, parkThread); + foundEvent = event; } } - assertTrue(isAnyFound, "Correct event not found"); + Asserts.assertNotNull(foundEvent, "Correct event not found"); + return foundEvent; } } diff --git a/test/jdk/jdk/jfr/jmx/security/TestEnoughPermission.java b/test/jdk/jdk/jfr/jmx/security/TestEnoughPermission.java index 715885e7894..17f56103672 100644 --- a/test/jdk/jdk/jfr/jmx/security/TestEnoughPermission.java +++ b/test/jdk/jdk/jfr/jmx/security/TestEnoughPermission.java @@ -85,7 +85,7 @@ public class TestEnoughPermission { System.out.println("E"); bean.stopRecording(recId); - final Path path = Paths.get(".", String.format("rec%d.jfr", recId)); + final Path path = Paths.get(".", "rec" + recId + ".jfr"); bean.copyTo(recId, path.toString()); //EventSet events = EventSet.fromFile(path); return recId; diff --git a/test/lib/jdk/test/lib/jfr/Events.java b/test/lib/jdk/test/lib/jfr/Events.java index 1b715b3ff1d..6e275d94045 100644 --- a/test/lib/jdk/test/lib/jfr/Events.java +++ b/test/lib/jdk/test/lib/jfr/Events.java @@ -33,12 +33,16 @@ import static jdk.test.lib.Asserts.fail; import java.io.File; import java.io.IOException; import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; import java.util.List; import jdk.jfr.AnnotationElement; import jdk.jfr.EventType; import jdk.jfr.Recording; import jdk.jfr.SettingDescriptor; +import jdk.jfr.Timespan; +import jdk.jfr.Timestamp; import jdk.jfr.ValueDescriptor; import jdk.jfr.consumer.RecordingFile; import jdk.test.lib.Asserts; @@ -183,6 +187,49 @@ public class Events { assertThread(assertField(event, structName).notNull().getValue(), thread); } + public static void assertDuration(RecordedEvent event, String name, Duration duration) { + assertEquals(event.getDuration(name), duration); + } + + public static void assertInstant(RecordedEvent event, String name, Instant instant) { + assertEquals(event.getInstant(name), instant); + } + + public static void assertMissingValue(RecordedEvent event, String name) { + ValueDescriptor v = event.getEventType().getField(name); + if (v.getAnnotation(Timespan.class) != null) { + Duration d = event.getDuration(name); + assertTrue(d.getSeconds() == Long.MIN_VALUE && d.getNano() == 0); + return; + } + if (v.getAnnotation(Timestamp.class) != null) { + Instant instant = event.getInstant(name); + assertTrue(instant.equals(Instant.MIN)); + return; + } + if (v.getTypeName().equals("double")) { + double d = event.getDouble(name); + assertTrue(Double.isNaN(d) || d == Double.NEGATIVE_INFINITY); + return; + } + if (v.getTypeName().equals("float")) { + float f = event.getFloat(name); + assertTrue(Float.isNaN(f) || f == Float.NEGATIVE_INFINITY); + return; + } + if (v.getTypeName().equals("int")) { + int i = event.getInt(name); + assertTrue(i == Integer.MIN_VALUE); + return; + } + if (v.getTypeName().equals("long")) { + assertEquals(event.getLong(name), Long.MIN_VALUE); + return; + } + Object o = event.getValue(name); + Asserts.assertNull(o); + } + private static void assertThread(RecordedThread eventThread, Thread thread) { assertNotNull(eventThread, "Thread in event was null"); assertEquals(eventThread.getJavaThreadId(), thread.getId(), "Wrong thread id"); From 8988f970df07e7ef71c9351f593701ec3d800e4e Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Wed, 12 Dec 2018 18:43:16 +0100 Subject: [PATCH 013/174] 8214750: Unnecessary

tags in jfr classes Reviewed-by: mgronlun --- src/jdk.jfr/share/classes/jdk/jfr/package-info.java | 1 - .../share/classes/jdk/management/jfr/FlightRecorderMXBean.java | 1 - 2 files changed, 2 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/package-info.java b/src/jdk.jfr/share/classes/jdk/jfr/package-info.java index 2af1651d956..a33e6b041d0 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/package-info.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/package-info.java @@ -105,7 +105,6 @@ * {@link jdk.jfr.ValueDescriptor#getName()}. *

* Predefined settings - *

* * * diff --git a/src/jdk.management.jfr/share/classes/jdk/management/jfr/FlightRecorderMXBean.java b/src/jdk.management.jfr/share/classes/jdk/management/jfr/FlightRecorderMXBean.java index 8ddde88569a..8b1231b2773 100644 --- a/src/jdk.management.jfr/share/classes/jdk/management/jfr/FlightRecorderMXBean.java +++ b/src/jdk.management.jfr/share/classes/jdk/management/jfr/FlightRecorderMXBean.java @@ -517,7 +517,6 @@ public interface FlightRecorderMXBean extends PlatformManagedObject { * event type is obtained by invoking * {@link jdk.jfr.EventType#getSettingDescriptors()} and * {@link jdk.jfr.ValueDescriptor#getName()}. - *

* * @param recordingId ID of the recording * From c25a638fd1747bc777206f9dafa87fd07fb60729 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Wed, 12 Dec 2018 09:50:39 -0800 Subject: [PATCH 014/174] 8215239: Make deletes images/jdk/bin/java if something goes wrong Reviewed-by: redestad, dholmes, tbell, ihse --- make/Images.gmk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make/Images.gmk b/make/Images.gmk index 3bf8695815a..0f1f871ea91 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -36,7 +36,7 @@ JRE_TARGETS := # Hook to include the corresponding custom file, if present. $(eval $(call IncludeCustomExtension, Images-pre.gmk)) -############################################################################ +################################################################################ # All modules for the current target platform. ALL_MODULES := $(call FindAllModules) @@ -57,7 +57,7 @@ BASE_RELEASE_FILE := $(JDK_OUTPUTDIR)/release JMODS := $(wildcard $(IMAGES_OUTPUTDIR)/jmods/*.jmod) # Use this file inside the image as target for make rule -JIMAGE_TARGET_FILE := bin/java$(EXE_SUFFIX) +JIMAGE_TARGET_FILE := release JLINK_ORDER_RESOURCES := **module-info.class JLINK_JLI_CLASSES := From 6217349ee65fa4f564b0679774877716594981d3 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 11 Dec 2018 15:47:31 +0100 Subject: [PATCH 015/174] 8214910: If pandoc is present, markdown spec files should be processed Reviewed-by: erikj, lancea --- make/Docs.gmk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make/Docs.gmk b/make/Docs.gmk index 9cbd5694d75..e97a6bec55e 100644 --- a/make/Docs.gmk +++ b/make/Docs.gmk @@ -532,9 +532,9 @@ $(foreach m, $(ALL_MODULES), \ ) \ ) -ifeq ($(ENABLE_FULL_DOCS), true) +ifneq ($(PANDOC), ) # For all markdown files in $module/share/specs directories, convert them to - # html. + # html, if we have pandoc (otherwise we'll just skip this). GLOBAL_SPECS_DEFAULT_CSS_FILE := $(DOCS_OUTPUTDIR)/resources/jdk-default.css From 0e9a8ba9f89dcede12848624c147f7eed22a7ed6 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Wed, 12 Dec 2018 18:59:23 +0100 Subject: [PATCH 016/174] 8214741: docs/index.html has no title or copyright Reviewed-by: erikj --- make/Docs.gmk | 17 +-------------- make/data/docs-resources/index.html | 33 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 make/data/docs-resources/index.html diff --git a/make/Docs.gmk b/make/Docs.gmk index e97a6bec55e..4ef887fda75 100644 --- a/make/Docs.gmk +++ b/make/Docs.gmk @@ -168,14 +168,6 @@ JAVADOC_TOP := \ font-family: DejaVu Sans, Arial, Helvetica, sans-serif; \ font-weight: normal;">$(DRAFT_TEXT) -JDK_INDEX_CONTENT := \ - \ - \ - \ - \ - \ - - ################################################################################ # JDK javadoc titles/text snippets @@ -485,14 +477,7 @@ $(eval $(call SetupApiDocsGeneration, REFERENCE_API, \ ################################################################################ -JDK_INDEX_HTML := $(DOCS_OUTPUTDIR)/index.html - -$(JDK_INDEX_HTML): - $(ECHO) '$(JDK_INDEX_CONTENT)' > $@ - -JDK_INDEX_TARGETS += $(JDK_INDEX_HTML) - -# Copy the global resources +# Copy the global resources, including the top-level redirect index.html GLOBAL_SPECS_RESOURCES_DIR := $(TOPDIR)/make/data/docs-resources/ $(eval $(call SetupCopyFiles, COPY_GLOBAL_RESOURCES, \ SRC := $(GLOBAL_SPECS_RESOURCES_DIR), \ diff --git a/make/data/docs-resources/index.html b/make/data/docs-resources/index.html new file mode 100644 index 00000000000..460525dd2f6 --- /dev/null +++ b/make/data/docs-resources/index.html @@ -0,0 +1,33 @@ + + + + + +Java API Documentation redirect + + + + From 2e94091ff25a9b3a77828ba5bcfd4919f78f1cc8 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Wed, 12 Dec 2018 19:04:05 +0100 Subject: [PATCH 017/174] 8215304: Make target "docs-jdk-index" has unnecessary dependencies Reviewed-by: lancea --- make/Main.gmk | 2 -- 1 file changed, 2 deletions(-) diff --git a/make/Main.gmk b/make/Main.gmk index f6bbd4d2f20..b276a023953 100644 --- a/make/Main.gmk +++ b/make/Main.gmk @@ -862,8 +862,6 @@ else docs-jdk-specs: $(JVM_DOCS_TARGETS) jdk.jdi-gensrc \ docs-jdk-index - docs-jdk-index: exploded-image buildtools-modules - docs-zip: docs-jdk # Tests From 4de0c13ff8c4bef2a782f8e8fd90b34b7d4ff2c4 Mon Sep 17 00:00:00 2001 From: Toshio Nakamura Date: Thu, 13 Dec 2018 00:46:39 +0900 Subject: [PATCH 018/174] 8213183: InputMethod cannot be used after its restarting Retains masks at XSelectInput and deletes all IM data at DestroyXIMCallback Reviewed-by: naoto --- .../unix/classes/sun/awt/X11/XMSelection.java | 10 +- .../native/libawt_xawt/awt/awt_InputMethod.c | 7 +- .../awt/im/InputContext/ReconnectTest.java | 253 ++++++++++++++++++ 3 files changed, 268 insertions(+), 2 deletions(-) create mode 100644 test/jdk/java/awt/im/InputContext/ReconnectTest.java diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XMSelection.java b/src/java.desktop/unix/classes/sun/awt/X11/XMSelection.java index 0c425c7de82..7cd242a52ea 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XMSelection.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XMSelection.java @@ -97,7 +97,15 @@ public class XMSelection { XToolkit.awtLock(); try { long root = XlibWrapper.RootWindow(display,screen); - XlibWrapper.XSelectInput(display, root, XConstants.StructureNotifyMask); + XWindowAttributes wattr = new XWindowAttributes(); + try { + XlibWrapper.XGetWindowAttributes(display, root, wattr.pData); + XlibWrapper.XSelectInput(display, root, + XConstants.StructureNotifyMask | + wattr.get_your_event_mask()); + } finally { + wattr.dispose(); + } XToolkit.addEventDispatcher(root, new XEventDispatcher() { public void dispatchEvent(XEvent ev) { diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/awt_InputMethod.c b/src/java.desktop/unix/native/libawt_xawt/awt/awt_InputMethod.c index 1a829017b79..a86bc7cbb61 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/awt_InputMethod.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/awt_InputMethod.c @@ -1277,9 +1277,14 @@ static void DestroyXIMCallback(XIM im, XPointer client_data, XPointer call_data) /* mark that XIM server was destroyed */ X11im = NULL; JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); + + AWT_LOCK(); /* free the old pX11IMData and set it to null. this also avoids crashing * the jvm if the XIM server reappears */ - X11InputMethodData *pX11IMData = getX11InputMethodData(env, currentX11InputMethodInstance); + while (x11InputMethodGRefListHead != NULL) { + getX11InputMethodData(env, x11InputMethodGRefListHead->inputMethodGRef); + } + AWT_UNLOCK(); } JNIEXPORT jboolean JNICALL diff --git a/test/jdk/java/awt/im/InputContext/ReconnectTest.java b/test/jdk/java/awt/im/InputContext/ReconnectTest.java new file mode 100644 index 00000000000..33f8656074c --- /dev/null +++ b/test/jdk/java/awt/im/InputContext/ReconnectTest.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + /* + * @test + * @key headful + * @bug 8213183 + * @summary verifies InputMethod reconnection + * @run main/manual ReconnectTest + */ +import java.awt.*; +import java.awt.event.*; + +public class ReconnectTest { + + private static void init() throws Exception { + String[] instructions + = { + "This test supports Linux and Japanese/Korean/Chinese", + "input method(IM). Under other environment, press Pass.", + "Test steps:", + "1.Turn on IM and input some Asian characters to TestWindow.", + "2.kill IM frontend by OS, and restart it.", + " e.g. for ibus, $ ibus-daemon -r --xim &", + "3.Change focus to this Instructions window and back to TestWindow.", + "4.Confirm IM can be activated." + }; + + Sysout.createDialog(); + Sysout.printInstructions(instructions); + } + + static Frame mainFrame; + + public static void initTestWindow() { + mainFrame = new Frame(); + mainFrame.setTitle("TestWindow"); + mainFrame.setLayout(new BorderLayout()); + Panel p0 = new Panel(); + p0.setLayout(new FlowLayout()); + mainFrame.add(p0, BorderLayout.CENTER); + TextArea text = new TextArea(); + p0.add(text); + + mainFrame.pack(); + mainFrame.setLocation(700, 10); + mainFrame.setVisible(true); + } + + public static void dispose() { + Sysout.dispose(); + mainFrame.dispose(); + } + + /** + * *************************************************** + * Standard Test Machinery Section DO NOT modify anything in this section -- + * it's a standard chunk of code which has all of the synchronisation + * necessary for the test harness. By keeping it the same in all tests, it + * is easier to read and understand someone else's test, as well as insuring + * that all tests behave correctly with the test harness. There is a section + * following this for test-defined classes + * **************************************************** + */ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + private static Thread mainThread = null; + final private static int sleepTime = 300000; + + public static void main(String args[]) throws Exception { + mainThread = Thread.currentThread(); + try { + init(); + initTestWindow(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + mainThread.sleep(sleepTime); + } catch (InterruptedException e) { + dispose(); + if (testGeneratedInterrupt && !theTestPassed) { + throw new Exception(failureMessage); + } + } + if (!testGeneratedInterrupt) { + dispose(); + throw new RuntimeException("Timed out after " + sleepTime / 1000 + + " seconds"); + } + } + + public static synchronized void pass() { + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public static synchronized void fail(String whyFailed) { + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + } +} + +// *********** End Standard Test Machinery Section ********** +/** + * ************************************************** + * Standard Test Machinery DO NOT modify anything below -- it's a standard chunk + * of code whose purpose is to make user interaction uniform, and thereby make + * it simpler to read and understand someone else's test. + * ************************************************** + */ +/** + * This is part of the standard test machinery. It creates a dialog (with the + * instructions), and is the interface for sending text messages to the user. To + * print the instructions, send an array of strings to Sysout.createDialog + * WithInstructions method. Put one line of instructions per array entry. To + * display a message for the tester to see, simply call Sysout.println with the + * string to be displayed. This mimics System.out.println but works within the + * test harness as well as standalone. + */ +class Sysout { + + private static TestDialog dialog; + private static Frame frame; + + public static void createDialog() { + frame = new Frame(); + dialog = new TestDialog(frame, "Instructions"); + String[] defInstr = {"Instructions will appear here. ", ""}; + dialog.printInstructions(defInstr); + dialog.setVisible(true); + println("Any messages for the tester will display here."); + } + + public static void printInstructions(String[] instructions) { + dialog.printInstructions(instructions); + } + + public static void println(String messageIn) { + dialog.displayMessage(messageIn); + } + + public static void dispose() { + dialog.dispose(); + frame.dispose(); + } +} + +/** + * This is part of the standard test machinery. It provides a place for the test + * instructions to be displayed, and a place for interactive messages to the + * user to be displayed. To have the test instructions displayed, see Sysout. To + * have a message to the user be displayed, see Sysout. Do not call anything in + * this dialog directly. + */ +class TestDialog extends Dialog implements ActionListener { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + Panel buttonP; + Button failB; + Button passB; + + // DO NOT call this directly, go through Sysout + public TestDialog(Frame frame, String name) { + super(frame, name); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); + add("North", instructionsText); + + messageText = new TextArea("", 5, maxStringLength, scrollBoth); + add("Center", messageText); + + buttonP = new Panel(); + failB = new Button("Fail"); + failB.setActionCommand("fail"); + failB.addActionListener(this); + passB = new Button("Pass"); + buttonP.add(passB); + buttonP.add(failB); + passB.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent ae) { + ReconnectTest.pass(); + } + }); + + add("South", buttonP); + pack(); + setVisible(true); + } + + // DO NOT call this directly, go through Sysout + public void printInstructions(String[] instructions) { + instructionsText.setText(""); + String printStr, remainingStr; + for (int i = 0; i < instructions.length; i++) { + remainingStr = instructions[i]; + while (remainingStr.length() > 0) { + if (remainingStr.length() >= maxStringLength) { + int posOfSpace = remainingStr. + lastIndexOf(' ', maxStringLength - 1); + + if (posOfSpace <= 0) { + posOfSpace = maxStringLength - 1; + } + + printStr = remainingStr.substring(0, posOfSpace + 1); + remainingStr = remainingStr.substring(posOfSpace + 1); + } else { + printStr = remainingStr; + remainingStr = ""; + } + instructionsText.append(printStr + "\n"); + } + } + } + + public void displayMessage(String messageIn) { + messageText.append(messageIn + "\n"); + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand() == "fail") { + ReconnectTest.fail("User Clicked Fail"); + } + } +} From 85857dfe80cd889f5a15e41f0fa9e7595c5364a6 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Wed, 12 Dec 2018 11:17:21 -0800 Subject: [PATCH 019/174] 8215238: (jdeps) update jdk8_internals.txt per the removal of javafx, corba, EE modules Reviewed-by: lancea, alanb --- .../classes/com/sun/tools/jdeps/Module.java | 2 +- .../com/sun/tools/jdeps/ModuleDotGraph.java | 4 +- .../tools/jdeps/resources/jdk8_internals.txt | 534 ------------------ 3 files changed, 2 insertions(+), 538 deletions(-) diff --git a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java index b18fae32ec5..5e47cc04331 100644 --- a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java +++ b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java @@ -115,7 +115,7 @@ class Module extends Archive { public boolean isJDK() { String mn = name(); return isSystem && - (mn.startsWith("java.") || mn.startsWith("jdk.") || mn.startsWith("javafx.")); + (mn.startsWith("java.") || mn.startsWith("jdk.")); } public boolean isSystem() { diff --git a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleDotGraph.java b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleDotGraph.java index 17908ac3eff..b9d5fb4bab6 100644 --- a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleDotGraph.java +++ b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleDotGraph.java @@ -307,9 +307,7 @@ public class ModuleDotGraph { .map(ModuleReference::descriptor) .map(ModuleDescriptor::name) .filter(name -> !JAVA_SE_SUBGRAPH.contains(name) && - (name.startsWith("java.") || - name.startsWith("jdk.") || - name.startsWith("javafx."))) + (name.startsWith("java.") || name.startsWith("jdk."))) .collect(Collectors.toSet()); } diff --git a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdk8_internals.txt b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdk8_internals.txt index be46f2e0398..1f2b073eb8c 100644 --- a/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdk8_internals.txt +++ b/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdk8_internals.txt @@ -9,19 +9,8 @@ com.apple.eawt.event com.apple.eio com.apple.laf com.apple.laf.resources -com.oracle.jrockit.jfr -com.oracle.jrockit.jfr.client -com.oracle.jrockit.jfr.management com.oracle.security.ucrypto -com.oracle.util -com.oracle.webservices.internal.api -com.oracle.webservices.internal.api.databinding -com.oracle.webservices.internal.api.message -com.oracle.webservices.internal.impl.encoding -com.oracle.webservices.internal.impl.internalspi.encoding -com.oracle.xmlns.internal.webservices.jaxws_databinding com.sun.accessibility.internal.resources -com.sun.activation.registries com.sun.awt com.sun.beans com.sun.beans.decoder @@ -29,90 +18,8 @@ com.sun.beans.editors com.sun.beans.finder com.sun.beans.infos com.sun.beans.util -com.sun.codemodel.internal -com.sun.codemodel.internal.fmt -com.sun.codemodel.internal.util -com.sun.codemodel.internal.writer -com.sun.corba.se.impl.activation -com.sun.corba.se.impl.copyobject -com.sun.corba.se.impl.corba -com.sun.corba.se.impl.dynamicany -com.sun.corba.se.impl.encoding -com.sun.corba.se.impl.interceptors -com.sun.corba.se.impl.io -com.sun.corba.se.impl.ior -com.sun.corba.se.impl.ior.iiop -com.sun.corba.se.impl.javax.rmi -com.sun.corba.se.impl.javax.rmi.CORBA -com.sun.corba.se.impl.legacy.connection -com.sun.corba.se.impl.logging -com.sun.corba.se.impl.monitoring -com.sun.corba.se.impl.naming.cosnaming -com.sun.corba.se.impl.naming.namingutil -com.sun.corba.se.impl.naming.pcosnaming -com.sun.corba.se.impl.oa -com.sun.corba.se.impl.oa.poa -com.sun.corba.se.impl.oa.toa -com.sun.corba.se.impl.orb -com.sun.corba.se.impl.orbutil -com.sun.corba.se.impl.orbutil.closure -com.sun.corba.se.impl.orbutil.concurrent -com.sun.corba.se.impl.orbutil.fsm -com.sun.corba.se.impl.orbutil.graph -com.sun.corba.se.impl.orbutil.threadpool -com.sun.corba.se.impl.presentation.rmi -com.sun.corba.se.impl.protocol -com.sun.corba.se.impl.protocol.giopmsgheaders -com.sun.corba.se.impl.resolver -com.sun.corba.se.impl.transport -com.sun.corba.se.impl.util -com.sun.corba.se.internal.CosNaming -com.sun.corba.se.internal.Interceptors -com.sun.corba.se.internal.POA -com.sun.corba.se.internal.corba -com.sun.corba.se.internal.iiop -com.sun.corba.se.org.omg.CORBA -com.sun.corba.se.pept.broker -com.sun.corba.se.pept.encoding -com.sun.corba.se.pept.protocol -com.sun.corba.se.pept.transport -com.sun.corba.se.spi.activation -com.sun.corba.se.spi.activation.InitialNameServicePackage -com.sun.corba.se.spi.activation.LocatorPackage -com.sun.corba.se.spi.activation.RepositoryPackage -com.sun.corba.se.spi.copyobject -com.sun.corba.se.spi.encoding -com.sun.corba.se.spi.extension -com.sun.corba.se.spi.ior -com.sun.corba.se.spi.ior.iiop -com.sun.corba.se.spi.legacy.connection -com.sun.corba.se.spi.legacy.interceptor -com.sun.corba.se.spi.logging -com.sun.corba.se.spi.monitoring -com.sun.corba.se.spi.oa -com.sun.corba.se.spi.orb -com.sun.corba.se.spi.orbutil.closure -com.sun.corba.se.spi.orbutil.fsm -com.sun.corba.se.spi.orbutil.proxy -com.sun.corba.se.spi.orbutil.threadpool -com.sun.corba.se.spi.presentation.rmi -com.sun.corba.se.spi.protocol -com.sun.corba.se.spi.resolver -com.sun.corba.se.spi.servicecontext -com.sun.corba.se.spi.transport com.sun.crypto.provider com.sun.demo.jvmti.hprof -com.sun.deploy.uitoolkit.impl.fx -com.sun.deploy.uitoolkit.impl.fx.ui -com.sun.deploy.uitoolkit.impl.fx.ui.resources -com.sun.glass.events -com.sun.glass.events.mac -com.sun.glass.ui -com.sun.glass.ui.delegate -com.sun.glass.ui.gtk -com.sun.glass.ui.mac -com.sun.glass.ui.win -com.sun.glass.utils com.sun.image.codec.jpeg com.sun.imageio.plugins.bmp com.sun.imageio.plugins.common @@ -122,10 +29,6 @@ com.sun.imageio.plugins.png com.sun.imageio.plugins.wbmp com.sun.imageio.spi com.sun.imageio.stream -com.sun.istack.internal -com.sun.istack.internal.localization -com.sun.istack.internal.logging -com.sun.istack.internal.tools com.sun.java.accessibility com.sun.java.accessibility.util.java.awt com.sun.java.browser.dom @@ -140,130 +43,27 @@ com.sun.java.swing.plaf.windows com.sun.java.swing.plaf.windows.resources com.sun.java.util.jar.pack com.sun.java_cup.internal.runtime -com.sun.javafx -com.sun.javafx.animation -com.sun.javafx.applet -com.sun.javafx.application -com.sun.javafx.beans -com.sun.javafx.beans.event -com.sun.javafx.binding -com.sun.javafx.charts -com.sun.javafx.collections -com.sun.javafx.css -com.sun.javafx.css.converters -com.sun.javafx.css.parser -com.sun.javafx.cursor -com.sun.javafx.effect -com.sun.javafx.embed -com.sun.javafx.event -com.sun.javafx.font -com.sun.javafx.font.coretext -com.sun.javafx.font.directwrite -com.sun.javafx.font.freetype -com.sun.javafx.font.t2k -com.sun.javafx.fxml -com.sun.javafx.fxml.builder -com.sun.javafx.fxml.expression -com.sun.javafx.geom -com.sun.javafx.geom.transform -com.sun.javafx.geometry -com.sun.javafx.iio -com.sun.javafx.iio.bmp -com.sun.javafx.iio.common -com.sun.javafx.iio.gif -com.sun.javafx.iio.ios -com.sun.javafx.iio.jpeg -com.sun.javafx.iio.png -com.sun.javafx.image -com.sun.javafx.image.impl -com.sun.javafx.jmx -com.sun.javafx.logging -com.sun.javafx.media -com.sun.javafx.menu -com.sun.javafx.perf -com.sun.javafx.print -com.sun.javafx.property -com.sun.javafx.property.adapter -com.sun.javafx.robot -com.sun.javafx.robot.impl -com.sun.javafx.runtime -com.sun.javafx.runtime.async -com.sun.javafx.runtime.eula -com.sun.javafx.scene -com.sun.javafx.scene.control -com.sun.javafx.scene.control.behavior -com.sun.javafx.scene.control.skin -com.sun.javafx.scene.control.skin.resources -com.sun.javafx.scene.input -com.sun.javafx.scene.layout.region -com.sun.javafx.scene.paint -com.sun.javafx.scene.shape -com.sun.javafx.scene.text -com.sun.javafx.scene.transform -com.sun.javafx.scene.traversal -com.sun.javafx.scene.web -com.sun.javafx.scene.web.behavior -com.sun.javafx.scene.web.skin -com.sun.javafx.sg.prism -com.sun.javafx.sg.prism.web -com.sun.javafx.stage -com.sun.javafx.text -com.sun.javafx.tk -com.sun.javafx.tk.quantum -com.sun.javafx.util -com.sun.javafx.webkit -com.sun.javafx.webkit.drt -com.sun.javafx.webkit.prism -com.sun.javafx.webkit.prism.theme -com.sun.javafx.webkit.theme com.sun.jmx.defaults com.sun.jmx.interceptor com.sun.jmx.mbeanserver com.sun.jmx.remote.internal -com.sun.jmx.remote.protocol.iiop com.sun.jmx.remote.protocol.rmi com.sun.jmx.remote.security com.sun.jmx.remote.util -com.sun.jmx.snmp -com.sun.jmx.snmp.IPAcl -com.sun.jmx.snmp.agent -com.sun.jmx.snmp.daemon -com.sun.jmx.snmp.defaults -com.sun.jmx.snmp.internal -com.sun.jmx.snmp.mpm -com.sun.jmx.snmp.tasks -com.sun.jndi.cosnaming com.sun.jndi.dns com.sun.jndi.ldap com.sun.jndi.ldap.ext com.sun.jndi.ldap.pool com.sun.jndi.ldap.sasl com.sun.jndi.rmi.registry -com.sun.jndi.toolkit.corba com.sun.jndi.toolkit.ctx com.sun.jndi.toolkit.dir com.sun.jndi.toolkit.url -com.sun.jndi.url.corbaname com.sun.jndi.url.dns -com.sun.jndi.url.iiop -com.sun.jndi.url.iiopname com.sun.jndi.url.ldap com.sun.jndi.url.ldaps com.sun.jndi.url.rmi com.sun.management.jmx -com.sun.media.jfxmedia -com.sun.media.jfxmedia.control -com.sun.media.jfxmedia.effects -com.sun.media.jfxmedia.events -com.sun.media.jfxmedia.locator -com.sun.media.jfxmedia.logging -com.sun.media.jfxmedia.track -com.sun.media.jfxmediaimpl -com.sun.media.jfxmediaimpl.platform -com.sun.media.jfxmediaimpl.platform.gstreamer -com.sun.media.jfxmediaimpl.platform.ios -com.sun.media.jfxmediaimpl.platform.java -com.sun.media.jfxmediaimpl.platform.osx com.sun.media.sound com.sun.naming.internal com.sun.net.ssl @@ -375,20 +175,6 @@ com.sun.org.apache.xpath.internal.objects com.sun.org.apache.xpath.internal.operations com.sun.org.apache.xpath.internal.patterns com.sun.org.apache.xpath.internal.res -com.sun.org.glassfish.external.amx -com.sun.org.glassfish.external.arc -com.sun.org.glassfish.external.probe.provider -com.sun.org.glassfish.external.probe.provider.annotations -com.sun.org.glassfish.external.statistics -com.sun.org.glassfish.external.statistics.annotations -com.sun.org.glassfish.external.statistics.impl -com.sun.org.glassfish.gmbal -com.sun.org.glassfish.gmbal.util -com.sun.org.omg.CORBA -com.sun.org.omg.CORBA.ValueDefPackage -com.sun.org.omg.CORBA.portable -com.sun.org.omg.SendingContext -com.sun.org.omg.SendingContext.CodeBasePackage com.sun.pisces com.sun.prism com.sun.prism.d3d @@ -411,22 +197,6 @@ com.sun.rmi.rmid com.sun.rowset com.sun.rowset.internal com.sun.rowset.providers -com.sun.scenario -com.sun.scenario.animation -com.sun.scenario.animation.shared -com.sun.scenario.effect -com.sun.scenario.effect.impl -com.sun.scenario.effect.impl.es2 -com.sun.scenario.effect.impl.hw -com.sun.scenario.effect.impl.hw.d3d -com.sun.scenario.effect.impl.prism -com.sun.scenario.effect.impl.prism.ps -com.sun.scenario.effect.impl.prism.sw -com.sun.scenario.effect.impl.state -com.sun.scenario.effect.impl.sw -com.sun.scenario.effect.impl.sw.java -com.sun.scenario.effect.impl.sw.sse -com.sun.scenario.effect.light com.sun.security.cert.internal.x509 com.sun.security.ntlm com.sun.security.sasl @@ -438,11 +208,6 @@ com.sun.swing.internal.plaf.basic.resources com.sun.swing.internal.plaf.metal.resources com.sun.swing.internal.plaf.synth.resources com.sun.tools.classfile -com.sun.tools.corba.se.idl -com.sun.tools.corba.se.idl.constExpr -com.sun.tools.corba.se.idl.som.cff -com.sun.tools.corba.se.idl.som.idlemit -com.sun.tools.corba.se.idl.toJavaPortable com.sun.tools.doclets.formats.html com.sun.tools.doclets.formats.html.markup com.sun.tools.doclets.formats.html.resources @@ -457,75 +222,6 @@ com.sun.tools.doclint.resources com.sun.tools.example.debug.expr com.sun.tools.example.debug.tty com.sun.tools.extcheck -com.sun.tools.hat -com.sun.tools.hat.internal.model -com.sun.tools.hat.internal.oql -com.sun.tools.hat.internal.parser -com.sun.tools.hat.internal.server -com.sun.tools.hat.internal.util -com.sun.tools.internal.jxc -com.sun.tools.internal.jxc.ap -com.sun.tools.internal.jxc.api -com.sun.tools.internal.jxc.api.impl.j2s -com.sun.tools.internal.jxc.gen.config -com.sun.tools.internal.jxc.model.nav -com.sun.tools.internal.ws -com.sun.tools.internal.ws.api -com.sun.tools.internal.ws.api.wsdl -com.sun.tools.internal.ws.processor -com.sun.tools.internal.ws.processor.generator -com.sun.tools.internal.ws.processor.model -com.sun.tools.internal.ws.processor.model.exporter -com.sun.tools.internal.ws.processor.model.java -com.sun.tools.internal.ws.processor.model.jaxb -com.sun.tools.internal.ws.processor.modeler -com.sun.tools.internal.ws.processor.modeler.annotation -com.sun.tools.internal.ws.processor.modeler.wsdl -com.sun.tools.internal.ws.processor.util -com.sun.tools.internal.ws.resources -com.sun.tools.internal.ws.spi -com.sun.tools.internal.ws.util -com.sun.tools.internal.ws.util.xml -com.sun.tools.internal.ws.wscompile -com.sun.tools.internal.ws.wscompile.plugin.at_generated -com.sun.tools.internal.ws.wsdl.document -com.sun.tools.internal.ws.wsdl.document.http -com.sun.tools.internal.ws.wsdl.document.jaxws -com.sun.tools.internal.ws.wsdl.document.mime -com.sun.tools.internal.ws.wsdl.document.schema -com.sun.tools.internal.ws.wsdl.document.soap -com.sun.tools.internal.ws.wsdl.framework -com.sun.tools.internal.ws.wsdl.parser -com.sun.tools.internal.xjc -com.sun.tools.internal.xjc.addon.accessors -com.sun.tools.internal.xjc.addon.at_generated -com.sun.tools.internal.xjc.addon.code_injector -com.sun.tools.internal.xjc.addon.episode -com.sun.tools.internal.xjc.addon.locator -com.sun.tools.internal.xjc.addon.sync -com.sun.tools.internal.xjc.api -com.sun.tools.internal.xjc.api.impl.s2j -com.sun.tools.internal.xjc.api.util -com.sun.tools.internal.xjc.generator.annotation.spec -com.sun.tools.internal.xjc.generator.bean -com.sun.tools.internal.xjc.generator.bean.field -com.sun.tools.internal.xjc.generator.util -com.sun.tools.internal.xjc.model -com.sun.tools.internal.xjc.model.nav -com.sun.tools.internal.xjc.outline -com.sun.tools.internal.xjc.reader -com.sun.tools.internal.xjc.reader.dtd -com.sun.tools.internal.xjc.reader.dtd.bindinfo -com.sun.tools.internal.xjc.reader.gbind -com.sun.tools.internal.xjc.reader.internalizer -com.sun.tools.internal.xjc.reader.relaxng -com.sun.tools.internal.xjc.reader.xmlschema -com.sun.tools.internal.xjc.reader.xmlschema.bindinfo -com.sun.tools.internal.xjc.reader.xmlschema.ct -com.sun.tools.internal.xjc.reader.xmlschema.parser -com.sun.tools.internal.xjc.runtime -com.sun.tools.internal.xjc.util -com.sun.tools.internal.xjc.writer com.sun.tools.javac.api com.sun.tools.javac.code com.sun.tools.javac.comp @@ -551,212 +247,8 @@ com.sun.tools.jdeps.resources com.sun.tools.jdi com.sun.tools.jdi.resources com.sun.tools.script.shell -com.sun.tracing -com.sun.tracing.dtrace -com.sun.webkit -com.sun.webkit.dom -com.sun.webkit.event -com.sun.webkit.graphics -com.sun.webkit.network -com.sun.webkit.network.about -com.sun.webkit.network.data -com.sun.webkit.perf -com.sun.webkit.plugin -com.sun.webkit.text -com.sun.xml.internal.bind -com.sun.xml.internal.bind.annotation -com.sun.xml.internal.bind.api -com.sun.xml.internal.bind.api.impl -com.sun.xml.internal.bind.marshaller -com.sun.xml.internal.bind.unmarshaller -com.sun.xml.internal.bind.util -com.sun.xml.internal.bind.v2 -com.sun.xml.internal.bind.v2.bytecode -com.sun.xml.internal.bind.v2.model.annotation -com.sun.xml.internal.bind.v2.model.core -com.sun.xml.internal.bind.v2.model.impl -com.sun.xml.internal.bind.v2.model.nav -com.sun.xml.internal.bind.v2.model.runtime -com.sun.xml.internal.bind.v2.model.util -com.sun.xml.internal.bind.v2.runtime -com.sun.xml.internal.bind.v2.runtime.output -com.sun.xml.internal.bind.v2.runtime.property -com.sun.xml.internal.bind.v2.runtime.reflect -com.sun.xml.internal.bind.v2.runtime.reflect.opt -com.sun.xml.internal.bind.v2.runtime.unmarshaller -com.sun.xml.internal.bind.v2.schemagen -com.sun.xml.internal.bind.v2.schemagen.episode -com.sun.xml.internal.bind.v2.schemagen.xmlschema -com.sun.xml.internal.bind.v2.util -com.sun.xml.internal.dtdparser -com.sun.xml.internal.fastinfoset -com.sun.xml.internal.fastinfoset.algorithm -com.sun.xml.internal.fastinfoset.alphabet -com.sun.xml.internal.fastinfoset.dom -com.sun.xml.internal.fastinfoset.org.apache.xerces.util -com.sun.xml.internal.fastinfoset.sax -com.sun.xml.internal.fastinfoset.stax -com.sun.xml.internal.fastinfoset.stax.events -com.sun.xml.internal.fastinfoset.stax.factory -com.sun.xml.internal.fastinfoset.stax.util -com.sun.xml.internal.fastinfoset.tools -com.sun.xml.internal.fastinfoset.util -com.sun.xml.internal.fastinfoset.vocab -com.sun.xml.internal.messaging.saaj -com.sun.xml.internal.messaging.saaj.client.p2p -com.sun.xml.internal.messaging.saaj.packaging.mime -com.sun.xml.internal.messaging.saaj.packaging.mime.internet -com.sun.xml.internal.messaging.saaj.packaging.mime.util -com.sun.xml.internal.messaging.saaj.soap -com.sun.xml.internal.messaging.saaj.soap.dynamic -com.sun.xml.internal.messaging.saaj.soap.impl -com.sun.xml.internal.messaging.saaj.soap.name -com.sun.xml.internal.messaging.saaj.soap.ver1_1 -com.sun.xml.internal.messaging.saaj.soap.ver1_2 -com.sun.xml.internal.messaging.saaj.util -com.sun.xml.internal.messaging.saaj.util.transform -com.sun.xml.internal.org.jvnet.fastinfoset -com.sun.xml.internal.org.jvnet.fastinfoset.sax -com.sun.xml.internal.org.jvnet.fastinfoset.sax.helpers -com.sun.xml.internal.org.jvnet.fastinfoset.stax -com.sun.xml.internal.org.jvnet.mimepull -com.sun.xml.internal.org.jvnet.staxex -com.sun.xml.internal.rngom.ast.builder -com.sun.xml.internal.rngom.ast.om -com.sun.xml.internal.rngom.ast.util -com.sun.xml.internal.rngom.binary -com.sun.xml.internal.rngom.binary.visitor -com.sun.xml.internal.rngom.digested -com.sun.xml.internal.rngom.dt -com.sun.xml.internal.rngom.dt.builtin -com.sun.xml.internal.rngom.nc -com.sun.xml.internal.rngom.parse -com.sun.xml.internal.rngom.parse.compact -com.sun.xml.internal.rngom.parse.host -com.sun.xml.internal.rngom.parse.xml -com.sun.xml.internal.rngom.util -com.sun.xml.internal.rngom.xml.sax -com.sun.xml.internal.rngom.xml.util -com.sun.xml.internal.stream -com.sun.xml.internal.stream.buffer -com.sun.xml.internal.stream.buffer.sax -com.sun.xml.internal.stream.buffer.stax -com.sun.xml.internal.stream.dtd -com.sun.xml.internal.stream.dtd.nonvalidating -com.sun.xml.internal.stream.events -com.sun.xml.internal.stream.util -com.sun.xml.internal.stream.writers -com.sun.xml.internal.txw2 -com.sun.xml.internal.txw2.annotation -com.sun.xml.internal.txw2.output -com.sun.xml.internal.ws -com.sun.xml.internal.ws.addressing -com.sun.xml.internal.ws.addressing.model -com.sun.xml.internal.ws.addressing.policy -com.sun.xml.internal.ws.addressing.v200408 -com.sun.xml.internal.ws.api -com.sun.xml.internal.ws.api.addressing -com.sun.xml.internal.ws.api.client -com.sun.xml.internal.ws.api.config.management -com.sun.xml.internal.ws.api.config.management.policy -com.sun.xml.internal.ws.api.databinding -com.sun.xml.internal.ws.api.fastinfoset -com.sun.xml.internal.ws.api.ha -com.sun.xml.internal.ws.api.handler -com.sun.xml.internal.ws.api.message -com.sun.xml.internal.ws.api.message.saaj -com.sun.xml.internal.ws.api.message.stream -com.sun.xml.internal.ws.api.model -com.sun.xml.internal.ws.api.model.soap -com.sun.xml.internal.ws.api.model.wsdl -com.sun.xml.internal.ws.api.model.wsdl.editable -com.sun.xml.internal.ws.api.pipe -com.sun.xml.internal.ws.api.pipe.helper -com.sun.xml.internal.ws.api.policy -com.sun.xml.internal.ws.api.policy.subject -com.sun.xml.internal.ws.api.server -com.sun.xml.internal.ws.api.streaming -com.sun.xml.internal.ws.api.wsdl.parser -com.sun.xml.internal.ws.api.wsdl.writer -com.sun.xml.internal.ws.assembler -com.sun.xml.internal.ws.assembler.dev -com.sun.xml.internal.ws.assembler.jaxws -com.sun.xml.internal.ws.binding -com.sun.xml.internal.ws.client -com.sun.xml.internal.ws.client.dispatch -com.sun.xml.internal.ws.client.sei -com.sun.xml.internal.ws.commons.xmlutil -com.sun.xml.internal.ws.config.management.policy -com.sun.xml.internal.ws.config.metro.dev -com.sun.xml.internal.ws.config.metro.util -com.sun.xml.internal.ws.db -com.sun.xml.internal.ws.db.glassfish -com.sun.xml.internal.ws.developer -com.sun.xml.internal.ws.dump -com.sun.xml.internal.ws.encoding -com.sun.xml.internal.ws.encoding.fastinfoset -com.sun.xml.internal.ws.encoding.policy -com.sun.xml.internal.ws.encoding.soap -com.sun.xml.internal.ws.encoding.soap.streaming -com.sun.xml.internal.ws.encoding.xml -com.sun.xml.internal.ws.fault -com.sun.xml.internal.ws.handler -com.sun.xml.internal.ws.message -com.sun.xml.internal.ws.message.jaxb -com.sun.xml.internal.ws.message.saaj -com.sun.xml.internal.ws.message.source -com.sun.xml.internal.ws.message.stream -com.sun.xml.internal.ws.model -com.sun.xml.internal.ws.model.soap -com.sun.xml.internal.ws.model.wsdl -com.sun.xml.internal.ws.org.objectweb.asm -com.sun.xml.internal.ws.policy -com.sun.xml.internal.ws.policy.jaxws -com.sun.xml.internal.ws.policy.jaxws.spi -com.sun.xml.internal.ws.policy.privateutil -com.sun.xml.internal.ws.policy.sourcemodel -com.sun.xml.internal.ws.policy.sourcemodel.attach -com.sun.xml.internal.ws.policy.sourcemodel.wspolicy -com.sun.xml.internal.ws.policy.spi -com.sun.xml.internal.ws.policy.subject -com.sun.xml.internal.ws.protocol.soap -com.sun.xml.internal.ws.protocol.xml -com.sun.xml.internal.ws.resources -com.sun.xml.internal.ws.runtime.config -com.sun.xml.internal.ws.server -com.sun.xml.internal.ws.server.provider -com.sun.xml.internal.ws.server.sei -com.sun.xml.internal.ws.spi -com.sun.xml.internal.ws.spi.db -com.sun.xml.internal.ws.streaming -com.sun.xml.internal.ws.transport -com.sun.xml.internal.ws.transport.http -com.sun.xml.internal.ws.transport.http.client -com.sun.xml.internal.ws.transport.http.server -com.sun.xml.internal.ws.util -com.sun.xml.internal.ws.util.exception -com.sun.xml.internal.ws.util.pipe -com.sun.xml.internal.ws.util.xml -com.sun.xml.internal.ws.wsdl -com.sun.xml.internal.ws.wsdl.parser -com.sun.xml.internal.ws.wsdl.writer -com.sun.xml.internal.ws.wsdl.writer.document -com.sun.xml.internal.ws.wsdl.writer.document.http -com.sun.xml.internal.ws.wsdl.writer.document.soap -com.sun.xml.internal.ws.wsdl.writer.document.soap12 -com.sun.xml.internal.ws.wsdl.writer.document.xsd -com.sun.xml.internal.xsom -com.sun.xml.internal.xsom.impl -com.sun.xml.internal.xsom.impl.parser -com.sun.xml.internal.xsom.impl.parser.state -com.sun.xml.internal.xsom.impl.scd -com.sun.xml.internal.xsom.impl.util -com.sun.xml.internal.xsom.parser -com.sun.xml.internal.xsom.util -com.sun.xml.internal.xsom.visitor java.awt.dnd.peer java.awt.peer -javafx.embed.swt jdk jdk.internal.cmm jdk.internal.dynalink @@ -774,7 +266,6 @@ jdk.internal.org.xml.sax jdk.internal.org.xml.sax.helpers jdk.internal.util.xml jdk.internal.util.xml.impl -jdk.jfr.events jdk.management.resource.internal jdk.management.resource.internal.inst jdk.nashorn.internal @@ -802,21 +293,8 @@ jdk.nashorn.internal.runtime.regexp.joni.encoding jdk.nashorn.internal.runtime.regexp.joni.exception jdk.nashorn.internal.scripts jdk.nashorn.tools -oracle.jrockit.jfr -oracle.jrockit.jfr.events -oracle.jrockit.jfr.jdkevents -oracle.jrockit.jfr.jdkevents.throwabletransform -oracle.jrockit.jfr.openmbean -oracle.jrockit.jfr.parser -oracle.jrockit.jfr.settings -oracle.jrockit.jfr.tools org.jcp.xml.dsig.internal org.jcp.xml.dsig.internal.dom -org.omg.stub.javax.management.remote.rmi -org.relaxng.datatype -org.relaxng.datatype.helpers -sun.applet -sun.applet.resources sun.audio sun.awt sun.awt.X11 @@ -832,7 +310,6 @@ sun.awt.resources sun.awt.shell sun.awt.util sun.awt.windows -sun.corba sun.dc sun.dc.path sun.dc.pr @@ -876,10 +353,6 @@ sun.management.counter.perf sun.management.jdp sun.management.jmxremote sun.management.resources -sun.management.snmp -sun.management.snmp.jvminstr -sun.management.snmp.jvmmib -sun.management.snmp.util sun.misc sun.misc.resources sun.net @@ -930,9 +403,6 @@ sun.reflect.misc sun.rmi.log sun.rmi.registry sun.rmi.rmic -sun.rmi.rmic.iiop -sun.rmi.rmic.newrmic -sun.rmi.rmic.newrmic.jrmp sun.rmi.runtime sun.rmi.server sun.rmi.transport @@ -1008,13 +478,9 @@ sun.tools.jps sun.tools.jstack sun.tools.jstat sun.tools.jstatd -sun.tools.native2ascii -sun.tools.native2ascii.resources sun.tools.serialver sun.tools.tree sun.tools.util -sun.tracing -sun.tracing.dtrace sun.usagetracker sun.util sun.util.calendar From 0e86ce571588a8eed08cbdc461c2fa0d8b656a4e Mon Sep 17 00:00:00 2001 From: Henry Jen Date: Wed, 12 Dec 2018 11:45:10 -0800 Subject: [PATCH 020/174] 8215000: tools/launcher/JliLaunchTest.java fails on Windows Reviewed-by: bchristi, mchung --- test/jdk/tools/launcher/JliLaunchTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/jdk/tools/launcher/JliLaunchTest.java b/test/jdk/tools/launcher/JliLaunchTest.java index 19a0251a5f1..24453b1d33a 100644 --- a/test/jdk/tools/launcher/JliLaunchTest.java +++ b/test/jdk/tools/launcher/JliLaunchTest.java @@ -49,10 +49,12 @@ public class JliLaunchTest { Map env = pb.environment(); if (Platform.isWindows()) { // The DLL should be in JDK/bin + String libdir = Paths.get(Utils.TEST_JDK).resolve("bin").toAbsolutePath().toString(); + env.compute("PATH", (k, v) -> (v == null) ? libdir : libdir + ";" + v); } else { String libdir = Paths.get(Utils.TEST_JDK).resolve("lib").toAbsolutePath().toString(); String LD_LIBRARY_PATH = Platform.isOSX() ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH"; - env.compute(LD_LIBRARY_PATH, (k, v) -> (k == null) ? libdir : v + ":" + libdir); + env.compute(LD_LIBRARY_PATH, (k, v) -> (v == null) ? libdir : libdir + ":" + v); } OutputAnalyzer outputf = new OutputAnalyzer(pb.start()); From 3623c99b2795199bf6fbb49070257f1e29e92fef Mon Sep 17 00:00:00 2001 From: Smita Kamath Date: Wed, 12 Dec 2018 12:17:33 -0800 Subject: [PATCH 021/174] 8214074: Ghash optimization using AVX instructions Reviewed-by: kvn, ascarpino --- src/hotspot/cpu/x86/assembler_x86.cpp | 24 +- src/hotspot/cpu/x86/assembler_x86.hpp | 2 + src/hotspot/cpu/x86/macroAssembler_x86.hpp | 16 +- .../cpu/x86/macroAssembler_x86_aes.cpp | 322 ++++++++++++++++++ src/hotspot/cpu/x86/stubGenerator_x86_64.cpp | 51 ++- src/hotspot/cpu/x86/stubRoutines_x86.cpp | 2 + src/hotspot/cpu/x86/stubRoutines_x86.hpp | 4 + .../com/sun/crypto/provider/GHASH.java | 20 +- 8 files changed, 426 insertions(+), 15 deletions(-) create mode 100644 src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp diff --git a/src/hotspot/cpu/x86/assembler_x86.cpp b/src/hotspot/cpu/x86/assembler_x86.cpp index 46bd55a3d2b..f27c66ca5ed 100644 --- a/src/hotspot/cpu/x86/assembler_x86.cpp +++ b/src/hotspot/cpu/x86/assembler_x86.cpp @@ -4178,6 +4178,17 @@ void Assembler::psrldq(XMMRegister dst, int shift) { emit_int8(shift); } +void Assembler::vpsrldq(XMMRegister dst, XMMRegister src, int shift, int vector_len) { + assert(vector_len == AVX_128bit ? VM_Version::supports_avx() : + vector_len == AVX_256bit ? VM_Version::supports_avx2() : + vector_len == AVX_512bit ? VM_Version::supports_avx512bw() : 0, ""); + InstructionAttr attributes(vector_len, /*vex_w */ false, /* legacy_mode */ _legacy_mode_bw, /* no_mask_reg */ true, /* uses_vl */ true); + int encode = vex_prefix_and_encode(xmm3->encoding(), dst->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F, &attributes); + emit_int8(0x73); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(shift & 0xFF); +} + void Assembler::pslldq(XMMRegister dst, int shift) { // Shift left 128 bit value in dst XMMRegister by shift number of bytes. NOT_LP64(assert(VM_Version::supports_sse2(), "")); @@ -4189,6 +4200,17 @@ void Assembler::pslldq(XMMRegister dst, int shift) { emit_int8(shift); } +void Assembler::vpslldq(XMMRegister dst, XMMRegister src, int shift, int vector_len) { + assert(vector_len == AVX_128bit ? VM_Version::supports_avx() : + vector_len == AVX_256bit ? VM_Version::supports_avx2() : + vector_len == AVX_512bit ? VM_Version::supports_avx512bw() : 0, ""); + InstructionAttr attributes(vector_len, /*vex_w */ false, /* legacy_mode */ _legacy_mode_bw, /* no_mask_reg */ true, /* uses_vl */ true); + int encode = vex_prefix_and_encode(xmm7->encoding(), dst->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F, &attributes); + emit_int8(0x73); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(shift & 0xFF); +} + void Assembler::ptest(XMMRegister dst, Address src) { assert(VM_Version::supports_sse4_1(), ""); assert((UseAVX > 0), "SSE mode requires address alignment 16 bytes"); @@ -4200,7 +4222,7 @@ void Assembler::ptest(XMMRegister dst, Address src) { } void Assembler::ptest(XMMRegister dst, XMMRegister src) { - assert(VM_Version::supports_sse4_1(), ""); + assert(VM_Version::supports_sse4_1() || VM_Version::supports_avx(), ""); InstructionAttr attributes(AVX_128bit, /* rex_w */ false, /* legacy_mode */ true, /* no_mask_reg */ true, /* uses_vl */ false); int encode = simd_prefix_and_encode(dst, xnoreg, src, VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); emit_int8(0x17); diff --git a/src/hotspot/cpu/x86/assembler_x86.hpp b/src/hotspot/cpu/x86/assembler_x86.hpp index fb59d89273a..e9d85e3d225 100644 --- a/src/hotspot/cpu/x86/assembler_x86.hpp +++ b/src/hotspot/cpu/x86/assembler_x86.hpp @@ -2055,6 +2055,7 @@ private: void vpsllw(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); void vpslld(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); void vpsllq(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); + void vpslldq(XMMRegister dst, XMMRegister src, int shift, int vector_len); // Logical shift right packed integers void psrlw(XMMRegister dst, int shift); @@ -2069,6 +2070,7 @@ private: void vpsrlw(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); void vpsrld(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); void vpsrlq(XMMRegister dst, XMMRegister src, XMMRegister shift, int vector_len); + void vpsrldq(XMMRegister dst, XMMRegister src, int shift, int vector_len); void evpsrlvw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); void evpsllvw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.hpp b/src/hotspot/cpu/x86/macroAssembler_x86.hpp index d0f5016838c..c60076e60f0 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.hpp @@ -943,12 +943,17 @@ class MacroAssembler: public Assembler { int iter); void addm(int disp, Register r1, Register r2); - + void gfmul(XMMRegister tmp0, XMMRegister t); + void schoolbookAAD(int i, Register subkeyH, XMMRegister data, XMMRegister tmp0, + XMMRegister tmp1, XMMRegister tmp2, XMMRegister tmp3); + void generateHtbl_one_block(Register htbl); + void generateHtbl_eight_blocks(Register htbl); public: void sha256_AVX2(XMMRegister msg, XMMRegister state0, XMMRegister state1, XMMRegister msgtmp0, XMMRegister msgtmp1, XMMRegister msgtmp2, XMMRegister msgtmp3, XMMRegister msgtmp4, Register buf, Register state, Register ofs, Register limit, Register rsp, bool multi_block, XMMRegister shuf_mask); + void avx_ghash(Register state, Register htbl, Register data, Register blocks); #endif #ifdef _LP64 @@ -1498,6 +1503,15 @@ public: // 0x11 - multiply upper 64 bits [64:127] Assembler::vpclmulqdq(dst, nds, src, 0x11); } + void vpclmullqhqdq(XMMRegister dst, XMMRegister nds, XMMRegister src) { + // 0x10 - multiply nds[0:63] and src[64:127] + Assembler::vpclmulqdq(dst, nds, src, 0x10); + } + void vpclmulhqlqdq(XMMRegister dst, XMMRegister nds, XMMRegister src) { + //0x01 - multiply nds[64:127] and src[0:63] + Assembler::vpclmulqdq(dst, nds, src, 0x01); + } + void evpclmulldq(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { // 0x00 - multiply lower 64 bits [0:63] Assembler::evpclmulqdq(dst, nds, src, 0x00, vector_len); diff --git a/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp b/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp new file mode 100644 index 00000000000..135923ea569 --- /dev/null +++ b/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp @@ -0,0 +1,322 @@ +/* +* Copyright (c) 2018, Intel Corporation. +* +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* This code is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License version 2 only, as +* published by the Free Software Foundation. +* +* This code is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +* version 2 for more details (a copy is included in the LICENSE file that +* accompanied this code). +* +* You should have received a copy of the GNU General Public License version +* 2 along with this work; if not, write to the Free Software Foundation, +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +* +* Please 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 "precompiled.hpp" +#include "asm/assembler.hpp" +#include "asm/assembler.inline.hpp" +#include "runtime/stubRoutines.hpp" +#include "macroAssembler_x86.hpp" + +// Multiply 128 x 128 bits, using 4 pclmulqdq operations +void MacroAssembler::schoolbookAAD(int i, Register htbl, XMMRegister data, + XMMRegister tmp0, XMMRegister tmp1, XMMRegister tmp2, XMMRegister tmp3) { + movdqu(xmm15, Address(htbl, i * 16)); + vpclmulhqlqdq(tmp3, data, xmm15); // 0x01 + vpxor(tmp2, tmp2, tmp3, Assembler::AVX_128bit); + vpclmulldq(tmp3, data, xmm15); // 0x00 + vpxor(tmp0, tmp0, tmp3, Assembler::AVX_128bit); + vpclmulhdq(tmp3, data, xmm15); // 0x11 + vpxor(tmp1, tmp1, tmp3, Assembler::AVX_128bit); + vpclmullqhqdq(tmp3, data, xmm15); // 0x10 + vpxor(tmp2, tmp2, tmp3, Assembler::AVX_128bit); +} + +// Multiply two 128 bit numbers resulting in a 256 bit value +// Result of the multiplication followed by reduction stored in state +void MacroAssembler::gfmul(XMMRegister tmp0, XMMRegister state) { + const XMMRegister tmp1 = xmm4; + const XMMRegister tmp2 = xmm5; + const XMMRegister tmp3 = xmm6; + const XMMRegister tmp4 = xmm7; + + vpclmulldq(tmp1, state, tmp0); //0x00 (a0 * b0) + vpclmulhdq(tmp4, state, tmp0);//0x11 (a1 * b1) + vpclmullqhqdq(tmp2, state, tmp0);//0x10 (a1 * b0) + vpclmulhqlqdq(tmp3, state, tmp0); //0x01 (a0 * b1) + + vpxor(tmp2, tmp2, tmp3, Assembler::AVX_128bit); // (a0 * b1) + (a1 * b0) + + vpslldq(tmp3, tmp2, 8, Assembler::AVX_128bit); + vpsrldq(tmp2, tmp2, 8, Assembler::AVX_128bit); + vpxor(tmp1, tmp1, tmp3, Assembler::AVX_128bit); // tmp1 and tmp4 hold the result + vpxor(tmp4, tmp4, tmp2, Assembler::AVX_128bit); // of carryless multiplication + // Follows the reduction technique mentioned in + // Shift-XOR reduction described in Gueron-Kounavis May 2010 + // First phase of reduction + // + vpslld(xmm8, tmp1, 31, Assembler::AVX_128bit); // packed right shift shifting << 31 + vpslld(xmm9, tmp1, 30, Assembler::AVX_128bit); // packed right shift shifting << 30 + vpslld(xmm10, tmp1, 25, Assembler::AVX_128bit);// packed right shift shifting << 25 + // xor the shifted versions + vpxor(xmm8, xmm8, xmm9, Assembler::AVX_128bit); + vpxor(xmm8, xmm8, xmm10, Assembler::AVX_128bit); + vpslldq(xmm9, xmm8, 12, Assembler::AVX_128bit); + vpsrldq(xmm8, xmm8, 4, Assembler::AVX_128bit); + vpxor(tmp1, tmp1, xmm9, Assembler::AVX_128bit);// first phase of the reduction complete + // + // Second phase of the reduction + // + vpsrld(xmm9, tmp1, 1, Assembler::AVX_128bit);// packed left shifting >> 1 + vpsrld(xmm10, tmp1, 2, Assembler::AVX_128bit);// packed left shifting >> 2 + vpsrld(xmm11, tmp1, 7, Assembler::AVX_128bit);// packed left shifting >> 7 + vpxor(xmm9, xmm9, xmm10, Assembler::AVX_128bit);// xor the shifted versions + vpxor(xmm9, xmm9, xmm11, Assembler::AVX_128bit); + vpxor(xmm9, xmm9, xmm8, Assembler::AVX_128bit); + vpxor(tmp1, tmp1, xmm9, Assembler::AVX_128bit); + vpxor(state, tmp4, tmp1, Assembler::AVX_128bit);// the result is in state + ret(0); +} + +// This method takes the subkey after expansion as input and generates 1 * 16 power of subkey H. +// The power of H is used in reduction process for one block ghash +void MacroAssembler::generateHtbl_one_block(Register htbl) { + const XMMRegister t = xmm13; + + // load the original subkey hash + movdqu(t, Address(htbl, 0)); + // shuffle using long swap mask + movdqu(xmm10, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr())); + vpshufb(t, t, xmm10, Assembler::AVX_128bit); + + // Compute H' = GFMUL(H, 2) + vpsrld(xmm3, t, 7, Assembler::AVX_128bit); + movdqu(xmm4, ExternalAddress(StubRoutines::x86::ghash_shufflemask_addr())); + vpshufb(xmm3, xmm3, xmm4, Assembler::AVX_128bit); + movl(rax, 0xff00); + movdl(xmm4, rax); + vpshufb(xmm4, xmm4, xmm3, Assembler::AVX_128bit); + movdqu(xmm5, ExternalAddress(StubRoutines::x86::ghash_polynomial_addr())); + vpand(xmm5, xmm5, xmm4, Assembler::AVX_128bit); + vpsrld(xmm3, t, 31, Assembler::AVX_128bit); + vpslld(xmm4, t, 1, Assembler::AVX_128bit); + vpslldq(xmm3, xmm3, 4, Assembler::AVX_128bit); + vpxor(t, xmm4, xmm3, Assembler::AVX_128bit);// t holds p(x) <<1 or H * 2 + + //Adding p(x)<<1 to xmm5 which holds the reduction polynomial + vpxor(t, t, xmm5, Assembler::AVX_128bit); + movdqu(Address(htbl, 1 * 16), t); // H * 2 + + ret(0); +} + +// This method takes the subkey after expansion as input and generates the remaining powers of subkey H. +// The power of H is used in reduction process for eight block ghash +void MacroAssembler::generateHtbl_eight_blocks(Register htbl) { + const XMMRegister t = xmm13; + const XMMRegister tmp0 = xmm1; + Label GFMUL; + + movdqu(t, Address(htbl, 1 * 16)); + movdqu(tmp0, t); + + // tmp0 and t hold H. Now we compute powers of H by using GFMUL(H, H) + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 2 * 16), t); //H ^ 2 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 3 * 16), t); //H ^ 3 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 4 * 16), t); //H ^ 4 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 5 * 16), t); //H ^ 5 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 6 * 16), t); //H ^ 6 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 7 * 16), t); //H ^ 7 * 2 + call(GFMUL, relocInfo::none); + movdqu(Address(htbl, 8 * 16), t); //H ^ 8 * 2 + ret(0); + + bind(GFMUL); + gfmul(tmp0, t); +} + +// Multiblock and single block GHASH computation using Shift XOR reduction technique +void MacroAssembler::avx_ghash(Register input_state, Register htbl, + Register input_data, Register blocks) { + + // temporary variables to hold input data and input state + const XMMRegister data = xmm1; + const XMMRegister state = xmm0; + // temporary variables to hold intermediate results + const XMMRegister tmp0 = xmm3; + const XMMRegister tmp1 = xmm4; + const XMMRegister tmp2 = xmm5; + const XMMRegister tmp3 = xmm6; + // temporary variables to hold byte and long swap masks + const XMMRegister bswap_mask = xmm2; + const XMMRegister lswap_mask = xmm14; + + Label GENERATE_HTBL_1_BLK, GENERATE_HTBL_8_BLKS, BEGIN_PROCESS, GFMUL, BLOCK8_REDUCTION, + ONE_BLK_INIT, PROCESS_1_BLOCK, PROCESS_8_BLOCKS, SAVE_STATE, EXIT_GHASH; + + testptr(blocks, blocks); + jcc(Assembler::zero, EXIT_GHASH); + + // Check if Hashtable (1*16) has been already generated + // For anything less than 8 blocks, we generate only the first power of H. + movdqu(tmp2, Address(htbl, 1 * 16)); + ptest(tmp2, tmp2); + jcc(Assembler::notZero, BEGIN_PROCESS); + call(GENERATE_HTBL_1_BLK, relocInfo::none); + + // Shuffle the input state + bind(BEGIN_PROCESS); + movdqu(lswap_mask, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr())); + movdqu(state, Address(input_state, 0)); + vpshufb(state, state, lswap_mask, Assembler::AVX_128bit); + + cmpl(blocks, 8); + jcc(Assembler::below, ONE_BLK_INIT); + // If we have 8 blocks or more data, then generate remaining powers of H + movdqu(tmp2, Address(htbl, 8 * 16)); + ptest(tmp2, tmp2); + jcc(Assembler::notZero, PROCESS_8_BLOCKS); + call(GENERATE_HTBL_8_BLKS, relocInfo::none); + + //Do 8 multiplies followed by a reduction processing 8 blocks of data at a time + //Each block = 16 bytes. + bind(PROCESS_8_BLOCKS); + subl(blocks, 8); + movdqu(bswap_mask, ExternalAddress(StubRoutines::x86::ghash_byte_swap_mask_addr())); + movdqu(data, Address(input_data, 16 * 7)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + //Loading 1*16 as calculated powers of H required starts at that location. + movdqu(xmm15, Address(htbl, 1 * 16)); + //Perform carryless multiplication of (H*2, data block #7) + vpclmulhqlqdq(tmp2, data, xmm15);//a0 * b1 + vpclmulldq(tmp0, data, xmm15);//a0 * b0 + vpclmulhdq(tmp1, data, xmm15);//a1 * b1 + vpclmullqhqdq(tmp3, data, xmm15);//a1* b0 + vpxor(tmp2, tmp2, tmp3, Assembler::AVX_128bit);// (a0 * b1) + (a1 * b0) + + movdqu(data, Address(input_data, 16 * 6)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^2 * 2, data block #6) + schoolbookAAD(2, htbl, data, tmp0, tmp1, tmp2, tmp3); + + movdqu(data, Address(input_data, 16 * 5)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^3 * 2, data block #5) + schoolbookAAD(3, htbl, data, tmp0, tmp1, tmp2, tmp3); + movdqu(data, Address(input_data, 16 * 4)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^4 * 2, data block #4) + schoolbookAAD(4, htbl, data, tmp0, tmp1, tmp2, tmp3); + movdqu(data, Address(input_data, 16 * 3)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^5 * 2, data block #3) + schoolbookAAD(5, htbl, data, tmp0, tmp1, tmp2, tmp3); + movdqu(data, Address(input_data, 16 * 2)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^6 * 2, data block #2) + schoolbookAAD(6, htbl, data, tmp0, tmp1, tmp2, tmp3); + movdqu(data, Address(input_data, 16 * 1)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^7 * 2, data block #1) + schoolbookAAD(7, htbl, data, tmp0, tmp1, tmp2, tmp3); + movdqu(data, Address(input_data, 16 * 0)); + // xor data block#0 with input state before perfoming carry-less multiplication + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + vpxor(data, data, state, Assembler::AVX_128bit); + // Perform carryless multiplication of (H^8 * 2, data block #0) + schoolbookAAD(8, htbl, data, tmp0, tmp1, tmp2, tmp3); + vpslldq(tmp3, tmp2, 8, Assembler::AVX_128bit); + vpsrldq(tmp2, tmp2, 8, Assembler::AVX_128bit); + vpxor(tmp0, tmp0, tmp3, Assembler::AVX_128bit);// tmp0, tmp1 contains aggregated results of + vpxor(tmp1, tmp1, tmp2, Assembler::AVX_128bit);// the multiplication operation + + // we have the 2 128-bit partially accumulated multiplication results in tmp0:tmp1 + // with higher 128-bit in tmp1 and lower 128-bit in corresponding tmp0 + // Follows the reduction technique mentioned in + // Shift-XOR reduction described in Gueron-Kounavis May 2010 + bind(BLOCK8_REDUCTION); + // First Phase of the reduction + vpslld(xmm8, tmp0, 31, Assembler::AVX_128bit); // packed right shifting << 31 + vpslld(xmm9, tmp0, 30, Assembler::AVX_128bit); // packed right shifting << 30 + vpslld(xmm10, tmp0, 25, Assembler::AVX_128bit); // packed right shifting << 25 + // xor the shifted versions + vpxor(xmm8, xmm8, xmm10, Assembler::AVX_128bit); + vpxor(xmm8, xmm8, xmm9, Assembler::AVX_128bit); + + vpslldq(xmm9, xmm8, 12, Assembler::AVX_128bit); + vpsrldq(xmm8, xmm8, 4, Assembler::AVX_128bit); + + vpxor(tmp0, tmp0, xmm9, Assembler::AVX_128bit); // first phase of reduction is complete + // second phase of the reduction + vpsrld(xmm9, tmp0, 1, Assembler::AVX_128bit); // packed left shifting >> 1 + vpsrld(xmm10, tmp0, 2, Assembler::AVX_128bit); // packed left shifting >> 2 + vpsrld(tmp2, tmp0, 7, Assembler::AVX_128bit); // packed left shifting >> 7 + // xor the shifted versions + vpxor(xmm9, xmm9, xmm10, Assembler::AVX_128bit); + vpxor(xmm9, xmm9, tmp2, Assembler::AVX_128bit); + vpxor(xmm9, xmm9, xmm8, Assembler::AVX_128bit); + vpxor(tmp0, xmm9, tmp0, Assembler::AVX_128bit); + // Final result is in state + vpxor(state, tmp0, tmp1, Assembler::AVX_128bit); + + lea(input_data, Address(input_data, 16 * 8)); + cmpl(blocks, 8); + jcc(Assembler::below, ONE_BLK_INIT); + jmp(PROCESS_8_BLOCKS); + + // Since this is one block operation we will only use H * 2 i.e. the first power of H + bind(ONE_BLK_INIT); + movdqu(tmp0, Address(htbl, 1 * 16)); + movdqu(bswap_mask, ExternalAddress(StubRoutines::x86::ghash_byte_swap_mask_addr())); + + //Do one (128 bit x 128 bit) carry-less multiplication at a time followed by a reduction. + bind(PROCESS_1_BLOCK); + cmpl(blocks, 0); + jcc(Assembler::equal, SAVE_STATE); + subl(blocks, 1); + movdqu(data, Address(input_data, 0)); + vpshufb(data, data, bswap_mask, Assembler::AVX_128bit); + vpxor(state, state, data, Assembler::AVX_128bit); + // gfmul(H*2, state) + call(GFMUL, relocInfo::none); + addptr(input_data, 16); + jmp(PROCESS_1_BLOCK); + + bind(SAVE_STATE); + vpshufb(state, state, lswap_mask, Assembler::AVX_128bit); + movdqu(Address(input_state, 0), state); + jmp(EXIT_GHASH); + + bind(GFMUL); + gfmul(tmp0, state); + + bind(GENERATE_HTBL_1_BLK); + generateHtbl_one_block(htbl); + + bind(GENERATE_HTBL_8_BLKS); + generateHtbl_eight_blocks(htbl); + + bind(EXIT_GHASH); + // zero out xmm registers used for Htbl storage + vpxor(xmm0, xmm0, xmm0, Assembler::AVX_128bit); + vpxor(xmm1, xmm1, xmm1, Assembler::AVX_128bit); + vpxor(xmm3, xmm3, xmm3, Assembler::AVX_128bit); + vpxor(xmm15, xmm15, xmm15, Assembler::AVX_128bit); +} \ No newline at end of file diff --git a/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp b/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp index 4500bc51125..634b78b6092 100644 --- a/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp +++ b/src/hotspot/cpu/x86/stubGenerator_x86_64.cpp @@ -4388,6 +4388,45 @@ address generate_cipherBlockChaining_decryptVectorAESCrypt() { return start; } +// Polynomial x^128+x^127+x^126+x^121+1 +address ghash_polynomial_addr() { + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", "_ghash_poly_addr"); + address start = __ pc(); + __ emit_data64(0x0000000000000001, relocInfo::none); + __ emit_data64(0xc200000000000000, relocInfo::none); + return start; +} + +address ghash_shufflemask_addr() { + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", "_ghash_shuffmask_addr"); + address start = __ pc(); + __ emit_data64(0x0f0f0f0f0f0f0f0f, relocInfo::none); + __ emit_data64(0x0f0f0f0f0f0f0f0f, relocInfo::none); + return start; +} + +// Ghash single and multi block operations using AVX instructions +address generate_avx_ghash_processBlocks() { + __ align(CodeEntryAlignment); + + StubCodeMark mark(this, "StubRoutines", "ghash_processBlocks"); + address start = __ pc(); + + // arguments + const Register state = c_rarg0; + const Register htbl = c_rarg1; + const Register data = c_rarg2; + const Register blocks = c_rarg3; + __ enter(); + // Save state before entering routine + __ avx_ghash(state, htbl, data, blocks); + __ leave(); // required for proper stackwalking of RuntimeStub frame + __ ret(0); + return start; +} + // byte swap x86 long address generate_ghash_long_swap_mask() { __ align(CodeEntryAlignment); @@ -5886,9 +5925,15 @@ address generate_cipherBlockChaining_decryptVectorAESCrypt() { // Generate GHASH intrinsics code if (UseGHASHIntrinsics) { - StubRoutines::x86::_ghash_long_swap_mask_addr = generate_ghash_long_swap_mask(); - StubRoutines::x86::_ghash_byte_swap_mask_addr = generate_ghash_byte_swap_mask(); - StubRoutines::_ghash_processBlocks = generate_ghash_processBlocks(); + StubRoutines::x86::_ghash_long_swap_mask_addr = generate_ghash_long_swap_mask(); + StubRoutines::x86::_ghash_byte_swap_mask_addr = generate_ghash_byte_swap_mask(); + if (VM_Version::supports_avx()) { + StubRoutines::x86::_ghash_shuffmask_addr = ghash_shufflemask_addr(); + StubRoutines::x86::_ghash_poly_addr = ghash_polynomial_addr(); + StubRoutines::_ghash_processBlocks = generate_avx_ghash_processBlocks(); + } else { + StubRoutines::_ghash_processBlocks = generate_ghash_processBlocks(); + } } if (UseBASE64Intrinsics) { diff --git a/src/hotspot/cpu/x86/stubRoutines_x86.cpp b/src/hotspot/cpu/x86/stubRoutines_x86.cpp index 9e375a8c0cf..519f12273c4 100644 --- a/src/hotspot/cpu/x86/stubRoutines_x86.cpp +++ b/src/hotspot/cpu/x86/stubRoutines_x86.cpp @@ -38,6 +38,8 @@ address StubRoutines::x86::_key_shuffle_mask_addr = NULL; address StubRoutines::x86::_counter_shuffle_mask_addr = NULL; address StubRoutines::x86::_ghash_long_swap_mask_addr = NULL; address StubRoutines::x86::_ghash_byte_swap_mask_addr = NULL; +address StubRoutines::x86::_ghash_poly_addr = NULL; +address StubRoutines::x86::_ghash_shuffmask_addr = NULL; address StubRoutines::x86::_upper_word_mask_addr = NULL; address StubRoutines::x86::_shuffle_byte_flip_mask_addr = NULL; address StubRoutines::x86::_k256_adr = NULL; diff --git a/src/hotspot/cpu/x86/stubRoutines_x86.hpp b/src/hotspot/cpu/x86/stubRoutines_x86.hpp index 251f26bdad2..728b6f84c28 100644 --- a/src/hotspot/cpu/x86/stubRoutines_x86.hpp +++ b/src/hotspot/cpu/x86/stubRoutines_x86.hpp @@ -128,6 +128,8 @@ class x86 { // swap mask for ghash static address _ghash_long_swap_mask_addr; static address _ghash_byte_swap_mask_addr; + static address _ghash_poly_addr; + static address _ghash_shuffmask_addr; // upper word mask for sha1 static address _upper_word_mask_addr; @@ -205,6 +207,8 @@ class x86 { static address crc_by128_masks_addr() { return (address)_crc_by128_masks; } static address ghash_long_swap_mask_addr() { return _ghash_long_swap_mask_addr; } static address ghash_byte_swap_mask_addr() { return _ghash_byte_swap_mask_addr; } + static address ghash_shufflemask_addr() { return _ghash_shuffmask_addr; } + static address ghash_polynomial_addr() { return _ghash_poly_addr; } static address upper_word_mask_addr() { return _upper_word_mask_addr; } static address shuffle_byte_flip_mask_addr() { return _shuffle_byte_flip_mask_addr; } static address k256_addr() { return _k256_adr; } diff --git a/src/java.base/share/classes/com/sun/crypto/provider/GHASH.java b/src/java.base/share/classes/com/sun/crypto/provider/GHASH.java index d917bfdbdf3..3b7464580d7 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/GHASH.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/GHASH.java @@ -124,10 +124,10 @@ final class GHASH { } - /* subkeyH and state are stored in long[] for GHASH intrinsic use */ + /* subkeyHtbl and state are stored in long[] for GHASH intrinsic use */ - // hash subkey H; should not change after the object has been constructed - private final long[] subkeyH; + // hashtable subkeyHtbl; holds 2*9 powers of subkeyH computed using carry-less multiplication + private long[] subkeyHtbl; // buffer for storing hash private final long[] state; @@ -149,9 +149,9 @@ final class GHASH { throw new ProviderException("Internal error"); } state = new long[2]; - this.subkeyH = new long[2]; - this.subkeyH[0] = getLong(subkeyH, 0); - this.subkeyH[1] = getLong(subkeyH, 8); + subkeyHtbl = new long[2*9]; + subkeyHtbl[0] = getLong(subkeyH, 0); + subkeyHtbl[1] = getLong(subkeyH, 8); } /** @@ -194,8 +194,8 @@ final class GHASH { if (inLen == 0) { return; } - ghashRangeCheck(in, inOfs, inLen, state, subkeyH); - processBlocks(in, inOfs, inLen/AES_BLOCK_SIZE, state, subkeyH); + ghashRangeCheck(in, inOfs, inLen, state, subkeyHtbl); + processBlocks(in, inOfs, inLen/AES_BLOCK_SIZE, state, subkeyHtbl); } private static void ghashRangeCheck(byte[] in, int inOfs, int inLen, long[] st, long[] subH) { @@ -219,8 +219,8 @@ final class GHASH { throw new RuntimeException("internal state has invalid length: " + st.length); } - if (subH.length != 2) { - throw new RuntimeException("internal subkeyH has invalid length: " + + if (subH.length != 18) { + throw new RuntimeException("internal subkeyHtbl has invalid length: " + subH.length); } } From 40d7e4c2e9f09bdf77a3f5c96fe666af422c8f1d Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Wed, 12 Dec 2018 15:35:20 -0500 Subject: [PATCH 022/174] 8215309: Convert package.html files to package-info.java files Reviewed-by: darcy, lancea --- .../java/util/logging/package-info.java | 118 ++++++ .../classes/java/util/logging/package.html | 127 ------- .../classes/java/util/prefs/package-info.java | 34 ++ .../classes/java/util/prefs/package.html | 44 --- .../java/rmi/activation/package-info.java | 42 +++ .../classes/java/rmi/activation/package.html | 61 --- .../classes/java/rmi/dgc/package-info.java | 37 ++ .../share/classes/java/rmi/dgc/package.html | 55 --- .../share/classes/java/rmi/package-info.java | 40 ++ .../share/classes/java/rmi/package.html | 59 --- .../java/rmi/registry/package-info.java | 37 ++ .../classes/java/rmi/registry/package.html | 57 --- .../classes/java/rmi/server/package-info.java | 55 +++ .../classes/java/rmi/server/package.html | 74 ---- .../classes/javax/rmi/ssl/package-info.java | 33 ++ .../share/classes/javax/rmi/ssl/package.html | 38 -- .../javax/smartcardio/package-info.java | 96 +++++ .../classes/javax/smartcardio/package.html | 98 ----- .../classes/com/sun/rowset/package-info.java | 76 ++++ .../share/classes/com/sun/rowset/package.html | 86 ----- .../sun/rowset/providers/package-info.java | 158 ++++++++ .../com/sun/rowset/providers/package.html | 170 --------- .../javax/sql/rowset/serial/package-info.java | 227 +++++++++++ .../javax/sql/rowset/serial/package.html | 239 ------------ .../share/classes/java/sql/package-info.java | 343 +++++++++++++++++ .../share/classes/java/sql/package.html | 351 ------------------ .../share/classes/javax/sql/package-info.java | 294 +++++++++++++++ .../share/classes/javax/sql/package.html | 302 --------------- 28 files changed, 1590 insertions(+), 1761 deletions(-) create mode 100644 src/java.logging/share/classes/java/util/logging/package-info.java delete mode 100644 src/java.logging/share/classes/java/util/logging/package.html create mode 100644 src/java.prefs/share/classes/java/util/prefs/package-info.java delete mode 100644 src/java.prefs/share/classes/java/util/prefs/package.html create mode 100644 src/java.rmi/share/classes/java/rmi/activation/package-info.java delete mode 100644 src/java.rmi/share/classes/java/rmi/activation/package.html create mode 100644 src/java.rmi/share/classes/java/rmi/dgc/package-info.java delete mode 100644 src/java.rmi/share/classes/java/rmi/dgc/package.html create mode 100644 src/java.rmi/share/classes/java/rmi/package-info.java delete mode 100644 src/java.rmi/share/classes/java/rmi/package.html create mode 100644 src/java.rmi/share/classes/java/rmi/registry/package-info.java delete mode 100644 src/java.rmi/share/classes/java/rmi/registry/package.html create mode 100644 src/java.rmi/share/classes/java/rmi/server/package-info.java delete mode 100644 src/java.rmi/share/classes/java/rmi/server/package.html create mode 100644 src/java.rmi/share/classes/javax/rmi/ssl/package-info.java delete mode 100644 src/java.rmi/share/classes/javax/rmi/ssl/package.html create mode 100644 src/java.smartcardio/share/classes/javax/smartcardio/package-info.java delete mode 100644 src/java.smartcardio/share/classes/javax/smartcardio/package.html create mode 100644 src/java.sql.rowset/share/classes/com/sun/rowset/package-info.java delete mode 100644 src/java.sql.rowset/share/classes/com/sun/rowset/package.html create mode 100644 src/java.sql.rowset/share/classes/com/sun/rowset/providers/package-info.java delete mode 100644 src/java.sql.rowset/share/classes/com/sun/rowset/providers/package.html create mode 100644 src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package-info.java delete mode 100644 src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package.html create mode 100644 src/java.sql/share/classes/java/sql/package-info.java delete mode 100644 src/java.sql/share/classes/java/sql/package.html create mode 100644 src/java.sql/share/classes/javax/sql/package-info.java delete mode 100644 src/java.sql/share/classes/javax/sql/package.html diff --git a/src/java.logging/share/classes/java/util/logging/package-info.java b/src/java.logging/share/classes/java/util/logging/package-info.java new file mode 100644 index 00000000000..2d665ee5597 --- /dev/null +++ b/src/java.logging/share/classes/java/util/logging/package-info.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides the classes and interfaces of + * the Java™ 2 platform's core logging facilities. + * The central goal of the logging APIs is to support maintaining and servicing + * software at customer sites. + * + *

+ * There are four main target uses of the logs: + *

+ * + *
    + *
  1. Problem diagnosis by end users and system administrators. + * This consists of simple logging of common problems that can be fixed + * or tracked locally, such as running out of resources, security failures, + * and simple configuration errors. + * + *
  2. Problem diagnosis by field service engineers. The logging information + * used by field service engineers may be considerably more complex and + * verbose than that required by system administrators. Typically such information + * will require extra logging within particular subsystems. + * + *
  3. Problem diagnosis by the development organization. + * When a problem occurs in the field, it may be necessary to return the captured logging + * information to the original development team for diagnosis. This logging + * information may be extremely detailed and fairly inscrutable. Such information might include + * detailed tracing on the internal execution of particular subsystems. + * + *
  4. Problem diagnosis by developers. The Logging APIs may also be + * used to help debug an application under development. This may + * include logging information generated by the target application + * as well as logging information generated by lower-level libraries. + * Note however that while this use is perfectly reasonable, + * the logging APIs are not intended to replace the normal debugging + * and profiling tools that may already exist in the development environment. + *
+ * + *

+ * The key elements of this package include: + *

    + *
  • Logger: The main entity on which applications make + * logging calls. A Logger object is used to log messages + * for a specific system or application + * component. + *
  • LogRecord: Used to pass logging requests between the logging + * framework and individual log handlers. + *
  • Handler: Exports LogRecord objects to a variety of destinations + * including memory, output streams, consoles, files, and sockets. + * A variety of Handler subclasses exist for this purpose. Additional Handlers + * may be developed by third parties and delivered on top of the core platform. + *
  • Level: Defines a set of standard logging levels that can be used + * to control logging output. Programs can be configured to output logging + * for some levels while ignoring output for others. + *
  • Filter: Provides fine-grained control over what gets logged, + * beyond the control provided by log levels. The logging APIs support a general-purpose + * filter mechanism that allows application code to attach arbitrary filters to + * control logging output. + * + *
  • Formatter: Provides support for formatting LogRecord objects. This + * package includes two formatters, SimpleFormatter and + * XMLFormatter, for formatting log records in plain text + * or XML respectively. As with Handlers, additional Formatters + * may be developed by third parties. + *
+ *

+ * The Logging APIs offer both static and dynamic configuration control. + * Static control enables field service staff to set up a particular configuration and then re-launch the + * application with the new logging settings. Dynamic control allows for updates to the + * logging configuration within a currently running program. The APIs also allow for logging to be + * enabled or disabled for different functional areas of the system. For example, + * a field service engineer might be interested in tracing all AWT events, but might have no interest in + * socket events or memory management. + *

+ * + *

Null Pointers

+ *

+ * In general, unless otherwise noted in the javadoc, methods and + * constructors will throw NullPointerException if passed a null argument. + * The one broad exception to this rule is that the logging convenience + * methods in the Logger class (the config, entering, exiting, fine, finer, finest, + * log, logp, logrb, severe, throwing, and warning methods) + * will accept null values + * for all arguments except for the initial Level argument (if any). + * + *

Related Documentation

+ *

+ * For an overview of control flow, + * please refer to the + * {@extLink logging_overview Java Logging Overview} + *

+ * + * @since 1.4 + */ +package java.util.logging; diff --git a/src/java.logging/share/classes/java/util/logging/package.html b/src/java.logging/share/classes/java/util/logging/package.html deleted file mode 100644 index 16891121119..00000000000 --- a/src/java.logging/share/classes/java/util/logging/package.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - -

-Provides the classes and interfaces of -the Java™ 2 platform's core logging facilities. -The central goal of the logging APIs is to support maintaining and servicing -software at customer sites. - -

-There are four main target uses of the logs: -

- -
    -
  1. Problem diagnosis by end users and system administrators. - This consists of simple logging of common problems that can be fixed - or tracked locally, such as running out of resources, security failures, - and simple configuration errors. - -
  2. Problem diagnosis by field service engineers. The logging information - used by field service engineers may be considerably more complex and - verbose than that required by system administrators. Typically such information - will require extra logging within particular subsystems. - -
  3. Problem diagnosis by the development organization. - When a problem occurs in the field, it may be necessary to return the captured logging - information to the original development team for diagnosis. This logging - information may be extremely detailed and fairly inscrutable. Such information might include - detailed tracing on the internal execution of particular subsystems. - -
  4. Problem diagnosis by developers. The Logging APIs may also be - used to help debug an application under development. This may - include logging information generated by the target application - as well as logging information generated by lower-level libraries. - Note however that while this use is perfectly reasonable, - the logging APIs are not intended to replace the normal debugging - and profiling tools that may already exist in the development environment. -
- -

-The key elements of this package include: -

    -
  • Logger: The main entity on which applications make - logging calls. A Logger object is used to log messages - for a specific system or application - component. -
  • LogRecord: Used to pass logging requests between the logging - framework and individual log handlers. -
  • Handler: Exports LogRecord objects to a variety of destinations - including memory, output streams, consoles, files, and sockets. - A variety of Handler subclasses exist for this purpose. Additional Handlers - may be developed by third parties and delivered on top of the core platform. -
  • Level: Defines a set of standard logging levels that can be used - to control logging output. Programs can be configured to output logging - for some levels while ignoring output for others. -
  • Filter: Provides fine-grained control over what gets logged, - beyond the control provided by log levels. The logging APIs support a general-purpose - filter mechanism that allows application code to attach arbitrary filters to - control logging output. - -
  • Formatter: Provides support for formatting LogRecord objects. This - package includes two formatters, SimpleFormatter and - XMLFormatter, for formatting log records in plain text - or XML respectively. As with Handlers, additional Formatters - may be developed by third parties. -
-

-The Logging APIs offer both static and dynamic configuration control. -Static control enables field service staff to set up a particular configuration and then re-launch the -application with the new logging settings. Dynamic control allows for updates to the -logging configuration within a currently running program. The APIs also allow for logging to be -enabled or disabled for different functional areas of the system. For example, -a field service engineer might be interested in tracing all AWT events, but might have no interest in -socket events or memory management. -

- -

Null Pointers

-

-In general, unless otherwise noted in the javadoc, methods and -constructors will throw NullPointerException if passed a null argument. -The one broad exception to this rule is that the logging convenience -methods in the Logger class (the config, entering, exiting, fine, finer, finest, -log, logp, logrb, severe, throwing, and warning methods) -will accept null values -for all arguments except for the initial Level argument (if any). - -

Related Documentation

-

-For an overview of control flow, -please refer to the -{@extLink logging_overview Java Logging Overview} -

- - - -@since 1.4 - - - - diff --git a/src/java.prefs/share/classes/java/util/prefs/package-info.java b/src/java.prefs/share/classes/java/util/prefs/package-info.java new file mode 100644 index 00000000000..e125ed4a521 --- /dev/null +++ b/src/java.prefs/share/classes/java/util/prefs/package-info.java @@ -0,0 +1,34 @@ +/* + * 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. 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. + */ + +/** + * This package allows applications to store and retrieve user and system + * preference and configuration data. This data is stored persistently in an + * implementation-dependent backing store. There are two separate trees of + * preference nodes, one for user preferences and one for system preferences. + * + * @since 1.4 + */ +package java.util.prefs; diff --git a/src/java.prefs/share/classes/java/util/prefs/package.html b/src/java.prefs/share/classes/java/util/prefs/package.html deleted file mode 100644 index cd5a0a799cc..00000000000 --- a/src/java.prefs/share/classes/java/util/prefs/package.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - -This package allows applications to store and retrieve user and system -preference and configuration data. This data is stored persistently in an -implementation-dependent backing store. There are two separate trees of -preference nodes, one for user preferences and one for system preferences. - - - -@since 1.4 - - diff --git a/src/java.rmi/share/classes/java/rmi/activation/package-info.java b/src/java.rmi/share/classes/java/rmi/activation/package-info.java new file mode 100644 index 00000000000..88a3e29d6b5 --- /dev/null +++ b/src/java.rmi/share/classes/java/rmi/activation/package-info.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + *

+ * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides support for RMI Object Activation. A remote + * object's reference can be made ``persistent'' and later activated into a + * ``live'' object using the RMI activation mechanism. + * + *

Implementations are not required to support the activation + * mechanism. If activation is not supported by this implementation, + * several specific activation API methods are all required to throw + * {@code UnsupportedOperationException}. If activation is supported by this + * implementation, these methods must never throw {@code + * UnsupportedOperationException}. These methods are denoted by the + * presence of an entry for {@code UnsupportedOperationException} in the + * Throws section of each method's specification. + * + * @since 1.2 + */ +package java.rmi.activation; diff --git a/src/java.rmi/share/classes/java/rmi/activation/package.html b/src/java.rmi/share/classes/java/rmi/activation/package.html deleted file mode 100644 index ed4bb79bffe..00000000000 --- a/src/java.rmi/share/classes/java/rmi/activation/package.html +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - -Provides support for RMI Object Activation. A remote -object's reference can be made ``persistent'' and later activated into a -``live'' object using the RMI activation mechanism. - -

Implementations are not required to support the activation -mechanism. If activation is not supported by this implementation, -several specific activation API methods are all required to throw -{@code UnsupportedOperationException}. If activation is supported by this -implementation, these methods must never throw {@code -UnsupportedOperationException}. These methods are denoted by the -presence of an entry for {@code UnsupportedOperationException} in the -Throws section of each method's specification. - - - -@since 1.2 - - diff --git a/src/java.rmi/share/classes/java/rmi/dgc/package-info.java b/src/java.rmi/share/classes/java/rmi/dgc/package-info.java new file mode 100644 index 00000000000..46512987c88 --- /dev/null +++ b/src/java.rmi/share/classes/java/rmi/dgc/package-info.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + *

+ * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides classes and interface for RMI distributed + * garbage-collection (DGC). When the RMI server returns an object to + * its client (caller of the remote method), it tracks the remote + * object's usage in the client. When there are no more references to the + * remote object on the client, or if the reference's ``lease'' expires and + * not renewed, the server garbage-collects the remote object. + * + * + * @since 1.1 + */ +package java.rmi.dgc; diff --git a/src/java.rmi/share/classes/java/rmi/dgc/package.html b/src/java.rmi/share/classes/java/rmi/dgc/package.html deleted file mode 100644 index 35a89ea250a..00000000000 --- a/src/java.rmi/share/classes/java/rmi/dgc/package.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - -Provides classes and interface for RMI distributed -garbage-collection (DGC). When the RMI server returns an object to -its client (caller of the remote method), it tracks the remote -object's usage in the client. When there are no more references to the -remote object on the client, or if the reference's ``lease'' expires and -not renewed, the server garbage-collects the remote object. - - - -@since 1.1 - - diff --git a/src/java.rmi/share/classes/java/rmi/package-info.java b/src/java.rmi/share/classes/java/rmi/package-info.java new file mode 100644 index 00000000000..13f7ec8a12f --- /dev/null +++ b/src/java.rmi/share/classes/java/rmi/package-info.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + *

+ * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides the RMI package. RMI is Remote Method Invocation. It is a + * mechanism that enables an object on one Java virtual machine to invoke + * methods on an object in another Java virtual machine. Any object that + * can be invoked this way must implement the Remote interface. When such + * an object is invoked, its arguments are ``marshalled'' and sent from the + * local virtual machine to the remote one, where the arguments are + * ``unmarshalled.'' When the method terminates, the results are + * marshalled from the remote machine and sent to the caller's virtual + * machine. If the method invocation results in an exception being + * thrown, the exception is indicated to caller. + * + * @since 1.1 + */ +package java.rmi; diff --git a/src/java.rmi/share/classes/java/rmi/package.html b/src/java.rmi/share/classes/java/rmi/package.html deleted file mode 100644 index 812f52168e4..00000000000 --- a/src/java.rmi/share/classes/java/rmi/package.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - -Provides the RMI package. RMI is Remote Method Invocation. It is a -mechanism that enables an object on one Java virtual machine to invoke -methods on an object in another Java virtual machine. Any object that -can be invoked this way must implement the Remote interface. When such -an object is invoked, its arguments are ``marshalled'' and sent from the -local virtual machine to the remote one, where the arguments are -``unmarshalled.'' When the method terminates, the results are -marshalled from the remote machine and sent to the caller's virtual -machine. If the method invocation results in an exception being -thrown, the exception is indicated to caller. - - - -@since 1.1 - - diff --git a/src/java.rmi/share/classes/java/rmi/registry/package-info.java b/src/java.rmi/share/classes/java/rmi/registry/package-info.java new file mode 100644 index 00000000000..c2291be95b7 --- /dev/null +++ b/src/java.rmi/share/classes/java/rmi/registry/package-info.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + *

+ * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides a class and two interfaces for the RMI registry. + * A registry is a remote object that maps names to remote objects. A + * server registers its remote objects with the registry so that they can + * be looked up. When an object wants to invoke a method on a remote + * object, it must first lookup the remote object using its name. The + * registry returns to the calling object a reference to the remote + * object, using which a remote method can be invoked. + * + * @since 1.1 + */ +package java.rmi.registry; diff --git a/src/java.rmi/share/classes/java/rmi/registry/package.html b/src/java.rmi/share/classes/java/rmi/registry/package.html deleted file mode 100644 index 7d2426baf1b..00000000000 --- a/src/java.rmi/share/classes/java/rmi/registry/package.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - -Provides a class and two interfaces for the RMI registry. -A registry is a remote object that maps names to remote objects. A -server registers its remote objects with the registry so that they can -be looked up. When an object wants to invoke a method on a remote -object, it must first lookup the remote object using its name. The -registry returns to the calling object a reference to the remote -object, using which a remote method can be invoked. - - - -@since 1.1 - - diff --git a/src/java.rmi/share/classes/java/rmi/server/package-info.java b/src/java.rmi/share/classes/java/rmi/server/package-info.java new file mode 100644 index 00000000000..991f03d0642 --- /dev/null +++ b/src/java.rmi/share/classes/java/rmi/server/package-info.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + *

+ * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides classes and interfaces for supporting the server + * side of RMI. A group of classes are used by the stubs and skeletons + * generated by the rmic stub compiler. Another group of classes + * implements the RMI Transport protocol and HTTP tunneling. + * + *

Deprecated: HTTP Tunneling. The HTTP tunneling + * mechanism has been deprecated. See {@link java.rmi.server.RMISocketFactory} for + * further information. + * + *

Deprecated: Skeletons and Static Stubs. + * + * Skeletons and statically generated stubs are deprecated. This + * includes the APIs in this package that require the use of skeletons + * or static stubs, the runtime support for them, and the use of the + * {@code rmic} stub compiler to generate them. Support for skeletons + * and static stubs may be removed in a future release of the + * platform. Skeletons are unnecessary, as server-side method dispatching + * is handled directly by the RMI runtime. Statically generated stubs are + * unnecessary, as stubs are generated dynamically using {@link + * java.lang.reflect.Proxy Proxy} objects. See {@link + * java.rmi.server.UnicastRemoteObject UnicastRemoteObject} for + * information about dynamic stub generation. Generation of skeletons and + * static stubs was typically performed as part of an application's build + * process by calling the {@code rmic} tool. This is unnecessary, and + * calls to {@code rmic} can simply be omitted. + * + * @since 1.1 + */ +package java.rmi.server; diff --git a/src/java.rmi/share/classes/java/rmi/server/package.html b/src/java.rmi/share/classes/java/rmi/server/package.html deleted file mode 100644 index 02b6f437016..00000000000 --- a/src/java.rmi/share/classes/java/rmi/server/package.html +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - -Provides classes and interfaces for supporting the server -side of RMI. A group of classes are used by the stubs and skeletons -generated by the rmic stub compiler. Another group of classes -implements the RMI Transport protocol and HTTP tunneling. - -

Deprecated: HTTP Tunneling. The HTTP tunneling -mechanism has been deprecated. See {@link java.rmi.server.RMISocketFactory} for -further information. - -

Deprecated: Skeletons and Static Stubs. - -Skeletons and statically generated stubs are deprecated. This -includes the APIs in this package that require the use of skeletons -or static stubs, the runtime support for them, and the use of the -{@code rmic} stub compiler to generate them. Support for skeletons -and static stubs may be removed in a future release of the -platform. Skeletons are unnecessary, as server-side method dispatching -is handled directly by the RMI runtime. Statically generated stubs are -unnecessary, as stubs are generated dynamically using {@link -java.lang.reflect.Proxy Proxy} objects. See {@link -java.rmi.server.UnicastRemoteObject UnicastRemoteObject} for -information about dynamic stub generation. Generation of skeletons and -static stubs was typically performed as part of an application's build -process by calling the {@code rmic} tool. This is unnecessary, and -calls to {@code rmic} can simply be omitted. - - - -@since 1.1 - - diff --git a/src/java.rmi/share/classes/javax/rmi/ssl/package-info.java b/src/java.rmi/share/classes/javax/rmi/ssl/package-info.java new file mode 100644 index 00000000000..1b408db93b5 --- /dev/null +++ b/src/java.rmi/share/classes/javax/rmi/ssl/package-info.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides implementations of {@link java.rmi.server.RMIClientSocketFactory} + * and {@link java.rmi.server.RMIServerSocketFactory} over + * the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols. + * + * @since 1.5 + */ +package javax.rmi.ssl; diff --git a/src/java.rmi/share/classes/javax/rmi/ssl/package.html b/src/java.rmi/share/classes/javax/rmi/ssl/package.html deleted file mode 100644 index 469345d14c3..00000000000 --- a/src/java.rmi/share/classes/javax/rmi/ssl/package.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - -Provides implementations of {@link java.rmi.server.RMIClientSocketFactory} -and {@link java.rmi.server.RMIServerSocketFactory} over -the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols. - -@since 1.5 - - diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/package-info.java b/src/java.smartcardio/share/classes/javax/smartcardio/package-info.java new file mode 100644 index 00000000000..d920e569b05 --- /dev/null +++ b/src/java.smartcardio/share/classes/javax/smartcardio/package-info.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * Java™ Smart Card I/O API. + * + * This specification describes the Java Smart Card I/O API defined by + * JSR 268. + * + * It defines a Java API for communication with Smart Cards + * using ISO/IEC 7816-4 APDUs. It thereby allows Java applications to interact with + * applications running on the Smart Card, to store and retrieve data + * on the card, etc. + * + *

+ * The API is defined by classes in the package + * javax.smartcardio. They can be classified as follows: + * + *

+ *
Classes describing the corresponding Smart Card structures + *
+ * ATR, + * CommandAPDU, + * ResponseAPDU + * + *
Factory to obtain implementations + *
+ * TerminalFactory + * + *
Main classes for card and terminal functions + *
+ * CardTerminals, + * CardTerminal, + * Card, + * CardChannel + * + *
Supporting permission and exception classes + *
+ * CardPermission, + * CardException, + * CardNotPresentException + * + *
Service provider interface, not accessed directly by applications + *
+ * TerminalFactorySpi + * + *
+ * + * + *

API Example

+ * + * A simple example of using the API is: + *
+ *      // show the list of available terminals
+ *      TerminalFactory factory = TerminalFactory.getDefault();
+ *      List<CardTerminal> terminals = factory.terminals().list();
+ *      System.out.println("Terminals: " + terminals);
+ *      // get the first terminal
+ *      CardTerminal terminal = terminals.get(0);
+ *      // establish a connection with the card
+ *      Card card = terminal.connect("T=0");
+ *      System.out.println("card: " + card);
+ *      CardChannel channel = card.getBasicChannel();
+ *      ResponseAPDU r = channel.transmit(new CommandAPDU(c1));
+ *      System.out.println("response: " + toString(r.getBytes()));
+ *      // disconnect
+ *      card.disconnect(false);
+ * 
+ * + * @since 1.6 + * @author Andreas Sterbenz + * @author JSR 268 Expert Group + */ +package javax.smartcardio; diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/package.html b/src/java.smartcardio/share/classes/javax/smartcardio/package.html deleted file mode 100644 index 6686916e6f8..00000000000 --- a/src/java.smartcardio/share/classes/javax/smartcardio/package.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - -

Java™ Smart Card I/O API

- -This specification describes the Java Smart Card I/O API defined by -JSR 268. - -It defines a Java API for communication with Smart Cards -using ISO/IEC 7816-4 APDUs. It thereby allows Java applications to interact with -applications running on the Smart Card, to store and retrieve data -on the card, etc. - -

-The API is defined by classes in the package -javax.smartcardio. They can be classified as follows: - -

-
Classes describing the corresponding Smart Card structures -
-ATR, -CommandAPDU, -ResponseAPDU - -
Factory to obtain implementations -
-TerminalFactory - -
Main classes for card and terminal functions -
-CardTerminals, -CardTerminal, -Card, -CardChannel - -
Supporting permission and exception classes -
-CardPermission, -CardException, -CardNotPresentException - -
Service provider interface, not accessed directly by applications -
-TerminalFactorySpi - -
- - -

API Example

- -A simple example of using the API is: -
-	// show the list of available terminals
-	TerminalFactory factory = TerminalFactory.getDefault();
-	List<CardTerminal> terminals = factory.terminals().list();
-	System.out.println("Terminals: " + terminals);
-	// get the first terminal
-	CardTerminal terminal = terminals.get(0);
-	// establish a connection with the card
-	Card card = terminal.connect("T=0");
-	System.out.println("card: " + card);
-	CardChannel channel = card.getBasicChannel();
-	ResponseAPDU r = channel.transmit(new CommandAPDU(c1));
-	System.out.println("response: " + toString(r.getBytes()));
-	// disconnect
-	card.disconnect(false);
-
- -@since 1.6 -@author Andreas Sterbenz -@author JSR 268 Expert Group - - - diff --git a/src/java.sql.rowset/share/classes/com/sun/rowset/package-info.java b/src/java.sql.rowset/share/classes/com/sun/rowset/package-info.java new file mode 100644 index 00000000000..d2fe494965f --- /dev/null +++ b/src/java.sql.rowset/share/classes/com/sun/rowset/package-info.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides five standard implementations of the standard JDBC RowSet implementation + * interface definitions. These reference implementations are included with the J2SE version + * 1.5 platform and represent the benchmark standard RowSet implementations as verified + * by the Test Compatibility Kit (TCK) as mandated by the Java Community Process. + *
+ * + *

1.0 Available JDBC RowSet Reference Implementations

+ * The following implementations are provided:
+ * + *
JdbcRowSetImpl - The javax.sql.rowset.JdbcRowSet + * interface reference implementation.
+ *
+ * CachedRowSetImpl - The javax.sql.rowset.CachedRowSet interface + * reference implementation.
+ *
+ * WebRowSetImpl - The javax.sql.rowset.WebRowSet interface + * reference implementation.
+ *
+ * FilteredRowSetImpl - The javax.sql.rowset.FilteredRowSet + * interface reference implementation.
+ *
+ * JoinRowSetImpl - The javax.sql.rowset.JoinRowSet interface + * reference implementation.
+ *
+ * + * All details on their expected behavior, including their interactions with the SyncProvider + * SPI and helper classes are provided in the interface definitions in the javax.sql.rowset + * package specification.
+ * + *

2.0 Usage

+ * The reference implementations represent robust implementations of the standard + * RowSet interfaces defined in the javax.sql.rowset package. + * All disconnected RowSet implementations, such as the CachedRowSetImpl + * and WebRowSetImpl, are flexible enough to use the SyncFactory SPIs to + * leverage non-reference implementation SyncProvider implementations to obtain + * differing synchronization semantics. Furthermore, developers and vendors alike are free + * to use these implementations and integrate them into their products just as they + * can with to other components of the Java platform.
+ * + *

3.0 Extending the JDBC RowSet Implementations

+ * + * The JDBC RowSet reference implementations are provided as non-final + * classes so that any developer can extend them to provide additional features + * while maintaining the core required standard functionality and compatibility. It + * is anticipated that many vendors and developers will extend the standard feature + * set to their their particular needs. The website for JDBC Technology will + * provider a portal where implementations can be listed, similar to the way it + * provides a site for JDBC drivers. + */ + package com.sun.rowset; diff --git a/src/java.sql.rowset/share/classes/com/sun/rowset/package.html b/src/java.sql.rowset/share/classes/com/sun/rowset/package.html deleted file mode 100644 index 5945c539e56..00000000000 --- a/src/java.sql.rowset/share/classes/com/sun/rowset/package.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - com.sun.rowset Package - - -Provides five standard implementations of the standard JDBC RowSet implementation -interface definitions. These reference implementations are included with the J2SE version -1.5 platform and represent the benchmark standard RowSet implementations as verified -by the Test Compatibility Kit (TCK) as mandated by the Java Community Process. -
- -

1.0 Available JDBC RowSet Reference Implementations

-The following implementations are provided:
- -
JdbcRowSetImpl - The javax.sql.rowset.JdbcRowSet -interface reference implementation.
-
-CachedRowSetImpl - The javax.sql.rowset.CachedRowSet interface -reference implementation.
-
-WebRowSetImpl - The javax.sql.rowset.WebRowSet interface -reference implementation.
-
-FilteredRowSetImpl - The javax.sql.rowset.FilteredRowSet -interface reference implementation.
-
-JoinRowSetImpl - The javax.sql.rowset.JoinRowSet interface -reference implementation.
-
- -All details on their expected behavior, including their interactions with the SyncProvider -SPI and helper classes are provided in the interface definitions in the javax.sql.rowset -package specification.
- -

2.0 Usage

-The reference implementations represent robust implementations of the standard -RowSet interfaces defined in the javax.sql.rowset package. -All disconnected RowSet implementations, such as the CachedRowSetImpl -and WebRowSetImpl, are flexible enough to use the SyncFactory SPIs to -leverage non-reference implementation SyncProvider implementations to obtain -differing synchronization semantics. Furthermore, developers and vendors alike are free -to use these implementations and integrate them into their products just as they -can with to other components of the Java platform.
- -

3.0 Extending the JDBC RowSet Implementations

- -The JDBC RowSet reference implementations are provided as non-final -classes so that any developer can extend them to provide additional features -while maintaining the core required standard functionality and compatibility. It -is anticipated that many vendors and developers will extend the standard feature -set to their their particular needs. The website for JDBC Technology will -provider a portal where implementations can be listed, similar to the way it -provides a site for JDBC drivers. -
-
- - diff --git a/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package-info.java b/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package-info.java new file mode 100644 index 00000000000..7d2a0a25ec7 --- /dev/null +++ b/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package-info.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * 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. + */ + +/** + * + * Repository for the RowSet reference implementations of the + * SyncProvider abstract class. These implementations provide a + * disconnected RowSet + * object with the ability to synchronize the data in the underlying data + * source with its data. These implementations are provided as + * the default SyncProvider implementations and are accessible via the + * SyncProvider SPI managed by the SyncFactory. + * + *

1.0 SyncProvider Reference Implementations

+ * The main job of a SyncProvider implementation is to manage + * the reader and writer mechanisms. + * The SyncProvider SPI, as specified in the javax.sql.rowset.spi + * package, provides a pluggable mechanism by which javax.sql.RowSetReader + * and javax.sql.RowSetWriter implementations can be supplied to a disconnected + * RowSet object. + *

+ * A reader, a javax.sql.RowSetReader + * object, does the work necessary to populate a RowSet object with data. + * A writer, a javax.sql.RowSetWriter object, does the work necessary for + * synchronizing a RowSet object's data with the data in the originating + * source of data. Put another way, a writer writes a RowSet + * object's data back to the data source. + *

+ * Generally speaking, the course of events is this. The reader makes a connection to + * the data source and reads the data from a ResultSet object into its + * RowSet object. Then it closes the connection. While + * the RowSet object is disconnected, an application makes some modifications + * to the data and calls the method acceptChanges. At this point, the + * writer is called to write the changes back to the database table or view + * from which the original data came. This is called synchronization. + *

+ * If the data in the originating data source has not changed, there is no problem + * with just writing the RowSet object's new data to the data source. + * If it has changed, however, there is a conflict that needs to be resolved. One + * way to solve the problem is not to let the data in the data source be changed in + * the first place, which can be done by setting locks on a row, a table, or the + * whole data source. Setting locks is a way to avoid conflicts, but it can be + * very expensive. Another approach, which is at the other end of the spectrum, + * is simply to assume that no conflicts will occur and thus do nothing to avoid + * conflicts. + * Different SyncProvider implementations may handle synchronization in + * any of these ways, varying from doing no checking for + * conflicts, to doing various levels of checking, to guaranteeing that there are no + * conflicts. + *

+ * The SyncProvider class offers methods to help a RowSet + * object discover and manage how a provider handles synchronization. + * The method getProviderGrade returns the + * grade of synchronization a provider offers. An application can + * direct the provider to use a particular level of locking by calling + * the method setDataSourceLock and specifying the level of locking desired. + * If a RowSet object's data came from an SQL VIEW, an + * application may call the method supportsUpdatableView to + * find out whether the VIEW can be updated. + *

+ * Synchronization is done completely behind the scenes, so it is third party vendors of + * synchronization provider implementations who have to take care of this complex task. + * Application programmers can decide which provider to use and the level of locking to + * be done, but they are free from having to worry about the implementation details. + *

+ * The JDBC RowSet Implementations reference implementation provides two + * implementations of the SyncProvider class: + * + *

    + *
  • + * RIOptimisticProvider - provides the javax.sql.RowSetReader + * and javax.sql.RowSetWriter interface implementations and provides + * an optimistic concurrency model for synchronization. This model assumes that there + * will be few conflicts and therefore uses a relatively low grade of synchronization. + * If no other provider is available, this is the default provider that the + * SyncFactory will supply to a RowSet object. + *
    + *
  • + * RIXMLProvider - provides the XmlReader (an extension + * of the javax.sql.RowSetReader interface) and the XmlWriter + * (an extension of the javax.sql.RowSetWriter interface) to enable + * WebRowSet objects to write their state to a + * well formed XML document according to the WebRowSet XML schema + * definition.
    + *
+ * + *

2.0 Basics in RowSet Population & Synchronization

+ * A rowset's first task is to populate itself with rows of column values. + * Generally, these rows will come from a relational database, so a rowset + * has properties that supply what is necessary for making a connection to + * a database and executing a query. A rowset that does not need to establish + * a connection and execute a command, such as one that gets its data from + * a tabular file instead of a relational database, does not need to have these + * properties set. The vast majority of RowSets, however, do need to set these + * properties. The general rule is that a RowSet is required to set only the + * properties that it uses.
+ *
+ * The command property contains the query that determines what + * data a RowSet will contain. Rowsets have methods for setting a query's + * parameter(s), which means that a query can be executed multiple times with + * different parameters to produce different result sets. Or the query can be + * changed to something completely new to get a new result set. + *

Once a rowset contains the rows from a ResultSet object or some + * other data source, its column values can be updated, and its rows can be + * inserted or deleted. Any method that causes a change in the rowset's values + * or cursor position also notifies any object that has been registered as + * a listener with the rowset. So, for example, a table that displays the rowset's + * data in an applet can be notified of changes and make updates as they + * occur.
+ *
+ * The changes made to a rowset can be propagated back to the original data + * source to keep the rowset and its data source synchronized. Although this + * involves many operations behind the scenes, it is completely transparent + * to the application programmer and remains the concern of the RowSet provider + * developer. All an application has to do is invoke the method acceptChanges, + * and the data source backing the rowset will be updated to match the current + * values in the rowset.

+ * + *

A disconnected rowset, such as a CachedRowSet or WebRowSet + * object, establishes a connection to populate itself with data from a database + * and then closes the connection. The RowSet object will remain + * disconnected until it wants to propagate changes back to its database table, + * which is optional. To write its changes back to the database (synchronize with + * the database), the rowset establishes a connection, write the changes, and then + * once again disconnects itself.
+ *

+ * + *

3.0 Other Possible Implementations

+ * There are many other possible implementations of the SyncProvider abstract + * class. One possibility is to employ a more robust synchronization model, which + * would give a RowSet object increased trust in the provider's + * ability to get any updates back to the original data source. Another possibility + * is a more formal synchronization mechanism such as SyncML + * (http://www.syncml.org/)
+ */ +package com.sun.rowset.providers; diff --git a/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package.html b/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package.html deleted file mode 100644 index 1910541538d..00000000000 --- a/src/java.sql.rowset/share/classes/com/sun/rowset/providers/package.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - - - - javax.sql.rowset.providers Package - - -Repository for the RowSet reference implementations of the -SyncProvider abstract class. These implementations provide a -disconnected RowSet -object with the ability to synchronize the data in the underlying data -source with its data. These implementations are provided as -the default SyncProvider implementations and are accessible via the -SyncProvider SPI managed by the SyncFactory. - -

1.0 SyncProvider Reference Implementations

- The main job of a SyncProvider implementation is to manage -the reader and writer mechanisms. - The SyncProvider SPI, as specified in the javax.sql.rowset.spi -package, provides a pluggable mechanism by which javax.sql.RowSetReader -and javax.sql.RowSetWriter implementations can be supplied to a disconnected -RowSet object. -

- A reader, a javax.sql.RowSetReader -object, does the work necessary to populate a RowSet object with data. -A writer, a javax.sql.RowSetWriter object, does the work necessary for -synchronizing a RowSet object's data with the data in the originating -source of data. Put another way, a writer writes a RowSet -object's data back to the data source. -

-Generally speaking, the course of events is this. The reader makes a connection to -the data source and reads the data from a ResultSet object into its -RowSet object. Then it closes the connection. While -the RowSet object is disconnected, an application makes some modifications -to the data and calls the method acceptChanges. At this point, the -writer is called to write the changes back to the database table or view -from which the original data came. This is called synchronization. -

-If the data in the originating data source has not changed, there is no problem -with just writing the RowSet object's new data to the data source. -If it has changed, however, there is a conflict that needs to be resolved. One -way to solve the problem is not to let the data in the data source be changed in -the first place, which can be done by setting locks on a row, a table, or the -whole data source. Setting locks is a way to avoid conflicts, but it can be -very expensive. Another approach, which is at the other end of the spectrum, - is simply to assume that no conflicts will occur and thus do nothing to avoid -conflicts. -Different SyncProvider implementations may handle synchronization in -any of these ways, varying from doing no checking for -conflicts, to doing various levels of checking, to guaranteeing that there are no -conflicts. -

-The SyncProvider class offers methods to help a RowSet -object discover and manage how a provider handles synchronization. -The method getProviderGrade returns the -grade of synchronization a provider offers. An application can -direct the provider to use a particular level of locking by calling -the method setDataSourceLock and specifying the level of locking desired. -If a RowSet object's data came from an SQL VIEW, an -application may call the method supportsUpdatableView to -find out whether the VIEW can be updated. -

-Synchronization is done completely behind the scenes, so it is third party vendors of -synchronization provider implementations who have to take care of this complex task. -Application programmers can decide which provider to use and the level of locking to -be done, but they are free from having to worry about the implementation details. -

-The JDBC RowSet Implementations reference implementation provides two -implementations of the SyncProvider class: - -

    -
  • -RIOptimisticProvider - provides the javax.sql.RowSetReader -and javax.sql.RowSetWriter interface implementations and provides -an optimistic concurrency model for synchronization. This model assumes that there -will be few conflicts and therefore uses a relatively low grade of synchronization. -If no other provider is available, this is the default provider that the -SyncFactory will supply to a RowSet object. -
    -
  • -RIXMLProvider - provides the XmlReader (an extension -of the javax.sql.RowSetReader interface) and the XmlWriter -(an extension of the javax.sql.RowSetWriter interface) to enable -WebRowSet objects to write their state to a -well formed XML document according to the WebRowSet XML schema -definition.
    -
- -

2.0 Basics in RowSet Population & Synchronization

-A rowset's first task is to populate itself with rows of column values. -Generally, these rows will come from a relational database, so a rowset -has properties that supply what is necessary for making a connection to -a database and executing a query. A rowset that does not need to establish -a connection and execute a command, such as one that gets its data from -a tabular file instead of a relational database, does not need to have these -properties set. The vast majority of RowSets, however, do need to set these -properties. The general rule is that a RowSet is required to set only the -properties that it uses.
-
-The command property contains the query that determines what -data a RowSet will contain. Rowsets have methods for setting a query's -parameter(s), which means that a query can be executed multiple times with -different parameters to produce different result sets. Or the query can be -changed to something completely new to get a new result set. -

Once a rowset contains the rows from a ResultSet object or some -other data source, its column values can be updated, and its rows can be -inserted or deleted. Any method that causes a change in the rowset's values -or cursor position also notifies any object that has been registered as -a listener with the rowset. So, for example, a table that displays the rowset's -data in an applet can be notified of changes and make updates as they -occur.
-
-The changes made to a rowset can be propagated back to the original data -source to keep the rowset and its data source synchronized. Although this -involves many operations behind the scenes, it is completely transparent -to the application programmer and remains the concern of the RowSet provider -developer. All an application has to do is invoke the method acceptChanges, -and the data source backing the rowset will be updated to match the current -values in the rowset.

- -

A disconnected rowset, such as a CachedRowSet or WebRowSet - object, establishes a connection to populate itself with data from a database - and then closes the connection. The RowSet object will remain - disconnected until it wants to propagate changes back to its database table, - which is optional. To write its changes back to the database (synchronize with - the database), the rowset establishes a connection, write the changes, and then - once again disconnects itself.
-

- -

3.0 Other Possible Implementations

- There are many other possible implementations of the SyncProvider abstract - class. One possibility is to employ a more robust synchronization model, which - would give a RowSet object increased trust in the provider's - ability to get any updates back to the original data source. Another possibility - is a more formal synchronization mechanism such as SyncML - (http://www.syncml.org/)
-
-
- - diff --git a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package-info.java b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package-info.java new file mode 100644 index 00000000000..a0b77122966 --- /dev/null +++ b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package-info.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides utility classes to allow serializable mappings between SQL types + * and data types in the Java programming language. + *

Standard JDBC RowSet implementations may use these utility + * classes to + * assist in the serialization of disconnected RowSet objects. + * This is useful + * when transmitting a disconnected RowSet object over the wire to + * a different VM or across layers within an application.
+ *

+ * + *

1.0 SerialArray

+ * A serializable mapping in the Java programming language of an SQL ARRAY + * value.
+ *
+ * The SerialArray class provides a constructor for creating a SerialArray + * instance from an Array object, methods for getting the base type and + * the SQL name for the base type, and methods for copying all or part of a + * SerialArray object.
+ * + *

2.0 SerialBlob

+ * A serializable mapping in the Java programming language of an SQL BLOB + * value.
+ *
+ * The SerialBlobclass provides a constructor for creating an instance + * from a Blob object. Note that the Blob object should have brought the SQL + * BLOB value's data over to the client before a SerialBlobobject + * is constructed from it. The data of an SQL BLOB value can be materialized + * on the client as an array of bytes (using the method Blob.getBytes) + * or as a stream of uninterpreted bytes (using the method Blob.getBinaryStream). + *
+ *
+ * SerialBlob methods make it possible to make a copy of a SerialBlob + * object as an array of bytes or as a stream. They also make it possible + * to locate a given pattern of bytes or a Blob object within a SerialBlob + * object.
+ * + *

3.0 SerialClob

+ * A serializable mapping in the Java programming language of an SQL CLOB + * value.
+ *
+ * The SerialClob class provides a constructor for creating an instance + * from a Clob object. Note that the Clob object should have + * brought the SQL CLOB value's data over to the client before a SerialClob + * object is constructed from it. The data of an SQL CLOB value can be + * materialized on the client as a stream of Unicode characters.
+ *
+ * SerialClob methods make it possible to get a substring from a + * SerialClob object or to locate the start of a pattern of characters. + *
+ * + *

5.0 SerialDatalink

+ * A serializable mapping in the Java programming language of an SQL DATALINK + * value. A DATALINK value references a file outside of the underlying data source + * that the originating data source manages.
+ *
+ * RowSet implementations can use the method RowSet.getURL() to retrieve + * a java.net.URL object, which can be used to manipulate the external data. + *
+ *
+ *       java.net.URL url = rowset.getURL(1);
+ * + *

6.0 SerialJavaObject

+ * A serializable mapping in the Java programming language of an SQL JAVA_OBJECT + * value. Assuming the Java object instance implements the Serializable interface, + * this simply wraps the serialization process.
+ *
+ * If however, the serialization is not possible in the case where the Java + * object is not immediately serializable, this class will attempt to serialize + * all non static members to permit the object instance state to be serialized. + * Static or transient fields cannot be serialized and attempting to do so + * will result in a SerialException being thrown.
+ * + *

7.0 SerialRef

+ * A serializable mapping between the SQL REF type and the Java programming + * language.
+ *
+ * The SerialRef class provides a constructor for creating a SerialRef + * instance from a Ref type and provides methods for getting + * and setting the Ref object type.
+ * + *

8.0 SerialStruct

+ * A serializable mapping in the Java programming language of an SQL structured + * type. Each attribute that is not already serializable is mapped to a serializable + * form, and if an attribute is itself a structured type, each of its attributes + * that is not already serializable is mapped to a serializable form.
+ *
+ * In addition, if a Map object is passed to one of the constructors or + * to the method getAttributes, the structured type is custom mapped + * according to the mapping specified in the Map object. + *
+ * The SerialStruct class provides a constructor for creating an + * instance from a Struct object, a method for retrieving the SQL + * type name of the SQL structured type in the database, and methods for retrieving + * its attribute values.
+ * + *

9.0 SQLInputImpl

+ * An input stream used for custom mapping user-defined types (UDTs). An + * SQLInputImpl object is an input stream that contains a stream of + * values that are + * the attributes of a UDT. This class is used by the driver behind the scenes + * when the method getObject is called on an SQL structured or distinct + * type that has a custom mapping; a programmer never invokes SQLInputImpl + * methods directly.
+ *
+ * The SQLInputImpl class provides a set of reader methods + * analogous to the ResultSet getter methods. These methods make it + * possible to read the values in an SQLInputImpl object. The method + * wasNull is used to determine whether the last value read was SQL NULL. + *
+ *
+ * When a constructor or getter method that takes a Map object is called, + * the JDBC driver calls the method + * SQLData.getSQLType to determine the SQL type of the UDT being custom + * mapped. The driver creates an instance of SQLInputImpl, populating it with + * the attributes of the UDT. The driver then passes the input stream to the + * method SQLData.readSQL, which in turn calls the SQLInputImpl + * methods to read the attributes from the input stream.
+ * + *

10.0 SQLOutputImpl

+ * The output stream for writing the attributes of a custom mapped user-defined + * type (UDT) back to the database. The driver uses this interface internally, + * and its methods are never directly invoked by an application programmer. + *
+ *
+ * When an application calls the method PreparedStatement.setObject, the + * driver checks to see whether the value to be written is a UDT with a custom + * mapping. If it is, there will be an entry in a type map containing the Class + * object for the class that implements SQLData for this UDT. If the + * value to be written is an instance of SQLData, the driver will + * create an instance of SQLOutputImpl and pass it to the method + * SQLData.writeSQL. + * The method writeSQL in turn calls the appropriate SQLOutputImpl + * writer methods to write data from the SQLData object to the + * SQLOutputImpl + * output stream as the representation of an SQL user-defined type. + * + *

Custom Mapping

+ * The JDBC API provides mechanisms for mapping an SQL structured type or DISTINCT + * type to the Java programming language. Typically, a structured type is mapped + * to a class, and its attributes are mapped to fields in the class. + * (A DISTINCT type can thought of as having one attribute.) However, there are + * many other possibilities, and there may be any number of different mappings. + *

+ * A programmer defines the mapping by implementing the interface SQLData. + * For example, if an SQL structured type named AUTHORS has the attributes NAME, + * TITLE, and PUBLISHER, it could be mapped to a Java class named Authors. The + * Authors class could have the fields name, title, and publisher, to which the + * attributes of AUTHORS are mapped. In such a case, the implementation of + * SQLData could look like the following: + *

+ *    public class Authors implements SQLData {
+ *        public String name;
+ *        public String title;
+ *        public String publisher;
+ *
+ *        private String sql_type;
+ *        public String getSQLTypeName() {
+ *            return sql_type;
+ *        }
+ *
+ *        public void readSQL(SQLInput stream, String type)
+ *                                   throws SQLException  {
+ *            sql_type = type;
+ *            name = stream.readString();
+ *            title = stream.readString();
+ *            publisher = stream.readString();
+ *        }
+ *
+ *        public void writeSQL(SQLOutput stream) throws SQLException {
+ *            stream.writeString(name);
+ *            stream.writeString(title);
+ *            stream.writeString(publisher);
+ *        }
+ *    }
+ * 
+ * + * A java.util.Map object is used to associate the SQL structured + * type with its mapping to the class Authors. The following code fragment shows + * how a Map object might be created and given an entry associating + * AUTHORS and Authors. + *
+ *     java.util.Map map = new java.util.HashMap();
+ *     map.put("SCHEMA_NAME.AUTHORS", Class.forName("Authors");
+ * 
+ * + * The Map object map now contains an entry with the + * fully qualified name of the SQL structured type and the Class + * object for the class Authors. It can be passed to a method + * to tell the driver how to map AUTHORS to Authors. + *

+ * For a disconnected RowSet object, custom mapping can be done + * only when a Map object is passed to the method or constructor + * that will be doing the custom mapping. The situation is different for + * connected RowSet objects because they maintain a connection + * with the data source. A method that does custom mapping and is called by + * a disconnected RowSet object may use the Map + * object that is associated with the Connection object being + * used. So, in other words, if no map is specified, the connection's type + * map can be used by default. + */ +package javax.sql.rowset.serial; diff --git a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package.html b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package.html deleted file mode 100644 index 055fa6052aa..00000000000 --- a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/package.html +++ /dev/null @@ -1,239 +0,0 @@ - - - - - - - - -javax.sql.rowset.serial - - -Provides utility classes to allow serializable mappings between SQL types -and data types in the Java programming language. -

Standard JDBC RowSet implementations may use these utility -classes to -assist in the serialization of disconnected RowSet objects. -This is useful -when transmitting a disconnected RowSet object over the wire to -a different VM or across layers within an application.
-

- -

1.0 SerialArray

-A serializable mapping in the Java programming language of an SQL ARRAY -value.
-
-The SerialArray class provides a constructor for creating a SerialArray -instance from an Array object, methods for getting the base type and -the SQL name for the base type, and methods for copying all or part of a -SerialArray object.
- -

2.0 SerialBlob

-A serializable mapping in the Java programming language of an SQL BLOB -value.
-
-The SerialBlobclass provides a constructor for creating an instance -from a Blob object. Note that the Blob object should have brought the SQL -BLOB value's data over to the client before a SerialBlobobject -is constructed from it. The data of an SQL BLOB value can be materialized -on the client as an array of bytes (using the method Blob.getBytes) -or as a stream of uninterpreted bytes (using the method Blob.getBinaryStream). -
-
-SerialBlob methods make it possible to make a copy of a SerialBlob -object as an array of bytes or as a stream. They also make it possible -to locate a given pattern of bytes or a Blob object within a SerialBlob -object.
- -

3.0 SerialClob

-A serializable mapping in the Java programming language of an SQL CLOB -value.
-
-The SerialClob class provides a constructor for creating an instance -from a Clob object. Note that the Clob object should have -brought the SQL CLOB value's data over to the client before a SerialClob -object is constructed from it. The data of an SQL CLOB value can be -materialized on the client as a stream of Unicode characters.
-
-SerialClob methods make it possible to get a substring from a -SerialClob object or to locate the start of a pattern of characters. -
- -

5.0 SerialDatalink

-A serializable mapping in the Java programming language of an SQL DATALINK -value. A DATALINK value references a file outside of the underlying data source -that the originating data source manages.
-
-RowSet implementations can use the method RowSet.getURL() to retrieve -a java.net.URL object, which can be used to manipulate the external data. -
-
-      java.net.URL url = rowset.getURL(1);
- -

6.0 SerialJavaObject

-A serializable mapping in the Java programming language of an SQL JAVA_OBJECT -value. Assuming the Java object instance implements the Serializable interface, -this simply wraps the serialization process.
-
-If however, the serialization is not possible in the case where the Java -object is not immediately serializable, this class will attempt to serialize -all non static members to permit the object instance state to be serialized. -Static or transient fields cannot be serialized and attempting to do so -will result in a SerialException being thrown.
- -

7.0 SerialRef

-A serializable mapping between the SQL REF type and the Java programming -language.
-
-The SerialRef class provides a constructor for creating a SerialRef -instance from a Ref type and provides methods for getting -and setting the Ref object type.
- -

8.0 SerialStruct

-A serializable mapping in the Java programming language of an SQL structured -type. Each attribute that is not already serializable is mapped to a serializable -form, and if an attribute is itself a structured type, each of its attributes -that is not already serializable is mapped to a serializable form.
-
-In addition, if a Map object is passed to one of the constructors or -to the method getAttributes, the structured type is custom mapped -according to the mapping specified in the Map object. -
-The SerialStruct class provides a constructor for creating an -instance from a Struct object, a method for retrieving the SQL -type name of the SQL structured type in the database, and methods for retrieving -its attribute values.
- -

9.0 SQLInputImpl

- An input stream used for custom mapping user-defined types (UDTs). An - SQLInputImpl object is an input stream that contains a stream of - values that are -the attributes of a UDT. This class is used by the driver behind the scenes -when the method getObject is called on an SQL structured or distinct -type that has a custom mapping; a programmer never invokes SQLInputImpl -methods directly.
-
-The SQLInputImpl class provides a set of reader methods -analogous to the ResultSet getter methods. These methods make it -possible to read the values in an SQLInputImpl object. The method -wasNull is used to determine whether the last value read was SQL NULL. -
-
-When a constructor or getter method that takes a Map object is called, -the JDBC driver calls the method -SQLData.getSQLType to determine the SQL type of the UDT being custom -mapped. The driver creates an instance of SQLInputImpl, populating it with -the attributes of the UDT. The driver then passes the input stream to the -method SQLData.readSQL, which in turn calls the SQLInputImpl -methods to read the attributes from the input stream.
- -

10.0 SQLOutputImpl

- The output stream for writing the attributes of a custom mapped user-defined - type (UDT) back to the database. The driver uses this interface internally, - and its methods are never directly invoked by an application programmer. -
-
-When an application calls the method PreparedStatement.setObject, the -driver checks to see whether the value to be written is a UDT with a custom -mapping. If it is, there will be an entry in a type map containing the Class -object for the class that implements SQLData for this UDT. If the -value to be written is an instance of SQLData, the driver will -create an instance of SQLOutputImpl and pass it to the method -SQLData.writeSQL. -The method writeSQL in turn calls the appropriate SQLOutputImpl -writer methods to write data from the SQLData object to the -SQLOutputImpl -output stream as the representation of an SQL user-defined type. - -

Custom Mapping

-The JDBC API provides mechanisms for mapping an SQL structured type or DISTINCT -type to the Java programming language. Typically, a structured type is mapped -to a class, and its attributes are mapped to fields in the class. -(A DISTINCT type can thought of as having one attribute.) However, there are -many other possibilities, and there may be any number of different mappings. -

-A programmer defines the mapping by implementing the interface SQLData. -For example, if an SQL structured type named AUTHORS has the attributes NAME, -TITLE, and PUBLISHER, it could be mapped to a Java class named Authors. The -Authors class could have the fields name, title, and publisher, to which the -attributes of AUTHORS are mapped. In such a case, the implementation of -SQLData could look like the following: -

-   public class Authors implements SQLData {
-       public String name;
-       public String title;
-       public String publisher;
-
-       private String sql_type;
-       public String getSQLTypeName() {
-           return sql_type;
-       }
-
-       public void readSQL(SQLInput stream, String type)
-                                  throws SQLException  {
-           sql_type = type;
-           name = stream.readString();
-           title = stream.readString();
-           publisher = stream.readString();
-       }
-
-       public void writeSQL(SQLOutput stream) throws SQLException {
-           stream.writeString(name);
-           stream.writeString(title);
-           stream.writeString(publisher);
-       }
-   } 
-
- -A java.util.Map object is used to associate the SQL structured -type with its mapping to the class Authors. The following code fragment shows -how a Map object might be created and given an entry associating -AUTHORS and Authors. -
-    java.util.Map map = new java.util.HashMap();
-    map.put("SCHEMA_NAME.AUTHORS", Class.forName("Authors");
-
- -The Map object map now contains an entry with the -fully qualified name of the SQL structured type and the Class - object for the class Authors. It can be passed to a method -to tell the driver how to map AUTHORS to Authors. -

-For a disconnected RowSet object, custom mapping can be done -only when a Map object is passed to the method or constructor -that will be doing the custom mapping. The situation is different for -connected RowSet objects because they maintain a connection -with the data source. A method that does custom mapping and is called by -a disconnected RowSet object may use the Map -object that is associated with the Connection object being -used. So, in other words, if no map is specified, the connection's type -map can be used by default. - -
- - diff --git a/src/java.sql/share/classes/java/sql/package-info.java b/src/java.sql/share/classes/java/sql/package-info.java new file mode 100644 index 00000000000..3468a5ef21e --- /dev/null +++ b/src/java.sql/share/classes/java/sql/package-info.java @@ -0,0 +1,343 @@ +/* + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * + * Provides the API for accessing and processing data stored in a + * data source (usually a relational database) using the + * Java™ programming language. + * This API includes a framework whereby different + * drivers can be installed dynamically to access different data sources. + * Although the JDBC™ API is mainly geared + * to passing SQL statements to a database, it provides for reading and + * writing data from any data source with a tabular format. + * The reader/writer facility, available through the + * javax.sql.RowSet group of interfaces, can be customized to + * use and update data from a spread sheet, flat file, or any other tabular + * data source. + * + *

What the JDBC™ 4.3 API Includes

+ * The JDBC™ 4.3 API includes both + * the java.sql package, referred to as the JDBC core API, + * and the javax.sql package, referred to as the JDBC Optional + * Package API. This complete JDBC API + * is included in the Java™ Standard Edition (Java SE™), version 7. + * The javax.sql package extends the functionality of the JDBC API + * from a client-side API to a server-side API, and it is an essential part + * of the Java™ Enterprise Edition + * (Java EE™) technology. + * + *

Versions

+ * The JDBC 4.3 API incorporates all of the previous JDBC API versions: + *
    + *
  • The JDBC 4.2 API
  • + *
  • The JDBC 4.1 API
  • + *
  • The JDBC 4.0 API
  • + *
  • The JDBC 3.0 API
  • + *
  • The JDBC 2.1 core API
  • + *
  • The JDBC 2.0 Optional Package API
    + * (Note that the JDBC 2.1 core API and the JDBC 2.0 Optional Package + * API together are referred to as the JDBC 2.0 API.)
  • + *
  • The JDBC 1.2 API
  • + *
  • The JDBC 1.0 API
  • + *
+ *

+ * Classes, interfaces, methods, fields, constructors, and exceptions + * have the following "since" tags that indicate when they were introduced + * into the Java platform. When these "since" tags are used in + * Javadoc™ comments for the JDBC API, + * they indicate the following: + *

    + *
  • Since 9 -- new in the JDBC 4.3 API and part of the Java SE platform, + * version 9
  • + *
  • Since 1.8 -- new in the JDBC 4.2 API and part of the Java SE platform, + * version 8
  • + *
  • Since 1.7 -- new in the JDBC 4.1 API and part of the Java SE platform, + * version 7
  • + *
  • Since 1.6 -- new in the JDBC 4.0 API and part of the Java SE platform, + * version 6
  • + *
  • Since 1.4 -- new in the JDBC 3.0 API and part of the J2SE platform, + * version 1.4
  • + *
  • Since 1.2 -- new in the JDBC 2.0 API and part of the J2SE platform, + * version 1.2
  • + *
  • Since 1.1 or no "since" tag -- in the original JDBC 1.0 API and part of + * the JDK™, version 1.1
  • + *
+ *

+ * NOTE: Many of the new features are optional; consequently, there is + * some variation in drivers and the features they support. Always + * check your driver's documentation to see whether it supports a feature before + * you try to use it. + *

+ * NOTE: The class SQLPermission was added in the + * Java™ 2 SDK, Standard Edition, + * version 1.3 release. This class is used to prevent unauthorized + * access to the logging stream associated with the DriverManager, + * which may contain information such as table names, column data, and so on. + * + *

What the java.sql Package Contains

+ * The java.sql package contains API for the following: + *
    + *
  • Making a connection with a database via the DriverManager facility + *
      + *
    • DriverManager class -- makes a connection with a driver + *
    • SQLPermission class -- provides permission when code + * running within a Security Manager, such as an applet, + * attempts to set up a logging stream through the + * DriverManager + *
    • Driver interface -- provides the API for registering + * and connecting drivers based on JDBC technology ("JDBC drivers"); + * generally used only by the DriverManager class + *
    • DriverPropertyInfo class -- provides properties for a + * JDBC driver; not used by the general user + *
    + *
  • Sending SQL statements to a database + *
      + *
    • Statement -- used to send basic SQL statements + *
    • PreparedStatement -- used to send prepared statements or + * basic SQL statements (derived from Statement) + *
    • CallableStatement -- used to call database stored + * procedures (derived from PreparedStatement) + *
    • Connection interface -- provides methods for creating + * statements and managing connections and their properties + *
    • Savepoint -- provides savepoints in a transaction + * + *
    + *
  • Retrieving and updating the results of a query + *
      + *
    • ResultSet interface + *
    + *
  • Standard mappings for SQL types to classes and interfaces in the + * Java programming language + *
      + *
    • Array interface -- mapping for SQL ARRAY + *
    • Blob interface -- mapping for SQL BLOB + *
    • Clob interface -- mapping for SQL CLOB + *
    • Date class -- mapping for SQL DATE + *
    • NClob interface -- mapping for SQL NCLOB + *
    • Ref interface -- mapping for SQL REF + *
    • RowId interface -- mapping for SQL ROWID + *
    • Struct interface -- mapping for SQL STRUCT + *
    • SQLXML interface -- mapping for SQL XML + *
    • Time class -- mapping for SQL TIME + *
    • Timestamp class -- mapping for SQL TIMESTAMP + *
    • Types class -- provides constants for SQL types + *
    + *
  • Custom mapping an SQL user-defined type (UDT) to a class in the + * Java programming language + *
      + *
    • SQLData interface -- specifies the mapping of + * a UDT to an instance of this class + *
    • SQLInput interface -- provides methods for reading + * UDT attributes from a stream + *
    • SQLOutput interface -- provides methods for writing + * UDT attributes back to a stream + *
    + *
  • Metadata + *
      + *
    • DatabaseMetaData interface -- provides information + * about the database + *
    • ResultSetMetaData interface -- provides information + * about the columns of a ResultSet object + *
    • ParameterMetaData interface -- provides information + * about the parameters to PreparedStatement commands + *
    + *
  • Exceptions + *
      + *
    • SQLException -- thrown by most methods when there + * is a problem accessing data and by some methods for other reasons + *
    • SQLWarning -- thrown to indicate a warning + *
    • DataTruncation -- thrown to indicate that data may have + * been truncated + *
    • BatchUpdateException -- thrown to indicate that not all + * commands in a batch update executed successfully + *
    + *
+ * + *

java.sql and javax.sql Features Introduced in the JDBC 4.3 API

+ *
    + *
  • Added Sharding support
  • + *
  • Enhanced Connection to be able to provide hints + * to the driver that a request, an independent unit of work, + * is beginning or ending
  • + *
  • Enhanced DatabaseMetaData to determine if Sharding is + * supported
  • + *
  • Added the method drivers to DriverManager + * to return a Stream of the currently loaded and + * available JDBC drivers
  • + *
  • Added support to Statement for enquoting literals + * and simple identifiers
  • + *
  • Clarified the Java SE version that methods were deprecated
  • + *
+ * + *

java.sql and javax.sql Features Introduced in the JDBC 4.2 API

+ *
    + *
  • Added JDBCType enum and SQLType interface
  • + *
  • Support for REF CURSORS in CallableStatement + *
  • + *
  • DatabaseMetaData methods to return maximum Logical LOB size + * and if Ref Cursors are supported
  • + *
  • Added support for large update counts
  • + * + *
+ * + *

java.sql and javax.sql Features Introduced in the JDBC 4.1 API

+ *
    + *
  • Allow Connection, + * ResultSet and Statement objects to be + * used with the try-with-resources statement
  • + *
  • Support added to CallableStatement and + * ResultSet to specify the Java type to convert to via the + * getObject method
  • + *
  • DatabaseMetaData methods to return PseudoColumns and if a + * generated key is always returned
  • + *
  • Added support to Connection to specify a database schema, + * abort and timeout a physical connection.
  • + *
  • Added support to close a Statement object when its dependent + * objects have been closed
  • + *
  • Support for obtaining the parent logger for a Driver, + * DataSource, ConnectionPoolDataSource and + * XADataSource
  • + * + *
+ *

java.sql and javax.sql Features Introduced in the JDBC 4.0 API

+ *
    + *
  • auto java.sql.Driver discovery -- no longer need to load a + * java.sql.Driver class via Class.forName + *
  • National Character Set support added + *
  • Support added for the SQL:2003 XML data type + *
  • SQLException enhancements -- Added support for cause chaining; New SQLExceptions + * added for common SQLState class value codes + *
  • Enhanced Blob/Clob functionality -- Support provided to create and free a Blob/Clob instance + * as well as additional methods added to improve accessibility + *
  • Support added for accessing a SQL ROWID + *
  • Support added to allow a JDBC application to access an instance of a JDBC resource + * that has been wrapped by a vendor, usually in an application server or connection + * pooling environment. + *
  • Availability to be notified when a PreparedStatement that is associated + * with a PooledConnection has been closed or the driver determines is invalid + * + * + *
+ * + * + *

java.sql and javax.sql Features Introduced in the JDBC 3.0 API

+ *
    + *
  • Pooled statements -- reuse of statements associated with a pooled + * connection + *
  • Savepoints -- allow a transaction to be rolled back to a designated + * savepoint + *
  • Properties defined for ConnectionPoolDataSource -- specify + * how connections are to be pooled + *
  • Metadata for parameters of a PreparedStatement object + *
  • Ability to retrieve values from automatically generated columns + *
  • Ability to have multiple ResultSet objects + * returned from CallableStatement objects open at the + * same time + *
  • Ability to identify parameters to CallableStatement + * objects by name as well as by index + *
  • ResultSet holdability -- ability to specify whether cursors + * should be held open or closed at the end of a transaction + *
  • Ability to retrieve and update the SQL structured type instance that a + * Ref object references + *
  • Ability to programmatically update BLOB, + * CLOB, ARRAY, and REF values. + *
  • Addition of the java.sql.Types.DATALINK data type -- + * allows JDBC drivers access to objects stored outside a data source + *
  • Addition of metadata for retrieving SQL type hierarchies + *
+ * + *

java.sql Features Introduced in the JDBC 2.1 Core API

+ *
    + *
  • Scrollable result sets--using new methods in the ResultSet + * interface that allow the cursor to be moved to a particular row or to a + * position relative to its current position + *
  • Batch updates + *
  • Programmatic updates--using ResultSet updater methods + *
  • New data types--interfaces mapping the SQL3 data types + *
  • Custom mapping of user-defined types (UDTs) + *
  • Miscellaneous features, including performance hints, the use of character + * streams, full precision for java.math.BigDecimal values, + * additional security, and + * support for time zones in date, time, and timestamp values. + *
+ * + *

javax.sql Features Introduced in the JDBC 2.0 Optional + * Package API

+ *
    + *
  • The DataSource interface as a means of making a connection. The + * Java Naming and Directory Interface™ + * (JNDI) is used for registering a DataSource object with a + * naming service and also for retrieving it. + *
  • Pooled connections -- allowing connections to be used and reused + *
  • Distributed transactions -- allowing a transaction to span diverse + * DBMS servers + *
  • RowSet technology -- providing a convenient means of + * handling and passing data + *
+ * + * + *

Custom Mapping of UDTs

+ * A user-defined type (UDT) defined in SQL can be mapped to a class in the Java + * programming language. An SQL structured type or an SQL DISTINCT + * type are the UDTs that may be custom mapped. The following three + * steps set up a custom mapping: + *
    + *
  1. Defining the SQL structured type or DISTINCT type in SQL + *
  2. Defining the class in the Java programming language to which the + * SQL UDT will be mapped. This class must implement the + * SQLData interface. + *
  3. Making an entry in a Connection object's type map + * that contains two things: + *
      + *
    • the fully-qualified SQL name of the UDT + *
    • the Class object for the class that implements the + * SQLData interface + *
    + *
+ *

+ * When these are in place for a UDT, calling the methods + * ResultSet.getObject or CallableStatement.getObject + * on that UDT will automatically retrieve the custom mapping for it. Also, the + * PreparedStatement.setObject method will automatically map the + * object back to its SQL type to store it in the data source. + * + *

Package Specification

+ * + * + * + *

Related Documentation

+ * + * + */ +package java.sql; diff --git a/src/java.sql/share/classes/java/sql/package.html b/src/java.sql/share/classes/java/sql/package.html deleted file mode 100644 index a8b2e7cc816..00000000000 --- a/src/java.sql/share/classes/java/sql/package.html +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - - - - -Provides the API for accessing and processing data stored in a -data source (usually a relational database) using the -Java™ programming language. -This API includes a framework whereby different -drivers can be installed dynamically to access different data sources. -Although the JDBC™ API is mainly geared -to passing SQL statements to a database, it provides for reading and -writing data from any data source with a tabular format. -The reader/writer facility, available through the -javax.sql.RowSet group of interfaces, can be customized to -use and update data from a spread sheet, flat file, or any other tabular -data source. - -

What the JDBC™ 4.3 API Includes

-The JDBC™ 4.3 API includes both -the java.sql package, referred to as the JDBC core API, -and the javax.sql package, referred to as the JDBC Optional -Package API. This complete JDBC API -is included in the Java™ Standard Edition (Java SE™), version 7. -The javax.sql package extends the functionality of the JDBC API -from a client-side API to a server-side API, and it is an essential part -of the Java™ Enterprise Edition -(Java EE™) technology. - -

Versions

-The JDBC 4.3 API incorporates all of the previous JDBC API versions: -
    -
  • The JDBC 4.2 API
  • -
  • The JDBC 4.1 API
  • -
  • The JDBC 4.0 API
  • -
  • The JDBC 3.0 API
  • -
  • The JDBC 2.1 core API
  • -
  • The JDBC 2.0 Optional Package API
    - (Note that the JDBC 2.1 core API and the JDBC 2.0 Optional Package - API together are referred to as the JDBC 2.0 API.)
  • -
  • The JDBC 1.2 API
  • -
  • The JDBC 1.0 API
  • -
-

-Classes, interfaces, methods, fields, constructors, and exceptions -have the following "since" tags that indicate when they were introduced -into the Java platform. When these "since" tags are used in -Javadoc™ comments for the JDBC API, -they indicate the following: -

    -
  • Since 9 -- new in the JDBC 4.3 API and part of the Java SE platform, - version 9
  • -
  • Since 1.8 -- new in the JDBC 4.2 API and part of the Java SE platform, - version 8
  • -
  • Since 1.7 -- new in the JDBC 4.1 API and part of the Java SE platform, - version 7
  • -
  • Since 1.6 -- new in the JDBC 4.0 API and part of the Java SE platform, - version 6
  • -
  • Since 1.4 -- new in the JDBC 3.0 API and part of the J2SE platform, - version 1.4
  • -
  • Since 1.2 -- new in the JDBC 2.0 API and part of the J2SE platform, - version 1.2
  • -
  • Since 1.1 or no "since" tag -- in the original JDBC 1.0 API and part of - the JDK™, version 1.1
  • -
-

-NOTE: Many of the new features are optional; consequently, there is -some variation in drivers and the features they support. Always -check your driver's documentation to see whether it supports a feature before -you try to use it. -

-NOTE: The class SQLPermission was added in the -Java™ 2 SDK, Standard Edition, -version 1.3 release. This class is used to prevent unauthorized -access to the logging stream associated with the DriverManager, -which may contain information such as table names, column data, and so on. - -

What the java.sql Package Contains

-The java.sql package contains API for the following: -
    -
  • Making a connection with a database via the DriverManager facility -
      -
    • DriverManager class -- makes a connection with a driver -
    • SQLPermission class -- provides permission when code - running within a Security Manager, such as an applet, - attempts to set up a logging stream through the - DriverManager -
    • Driver interface -- provides the API for registering - and connecting drivers based on JDBC technology ("JDBC drivers"); - generally used only by the DriverManager class -
    • DriverPropertyInfo class -- provides properties for a - JDBC driver; not used by the general user -
    -
  • Sending SQL statements to a database -
      -
    • Statement -- used to send basic SQL statements -
    • PreparedStatement -- used to send prepared statements or - basic SQL statements (derived from Statement) -
    • CallableStatement -- used to call database stored - procedures (derived from PreparedStatement) -
    • Connection interface -- provides methods for creating - statements and managing connections and their properties -
    • Savepoint -- provides savepoints in a transaction - -
    -
  • Retrieving and updating the results of a query -
      -
    • ResultSet interface -
    -
  • Standard mappings for SQL types to classes and interfaces in the - Java programming language -
      -
    • Array interface -- mapping for SQL ARRAY -
    • Blob interface -- mapping for SQL BLOB -
    • Clob interface -- mapping for SQL CLOB -
    • Date class -- mapping for SQL DATE -
    • NClob interface -- mapping for SQL NCLOB -
    • Ref interface -- mapping for SQL REF -
    • RowId interface -- mapping for SQL ROWID -
    • Struct interface -- mapping for SQL STRUCT -
    • SQLXML interface -- mapping for SQL XML -
    • Time class -- mapping for SQL TIME -
    • Timestamp class -- mapping for SQL TIMESTAMP -
    • Types class -- provides constants for SQL types -
    -
  • Custom mapping an SQL user-defined type (UDT) to a class in the - Java programming language -
      -
    • SQLData interface -- specifies the mapping of - a UDT to an instance of this class -
    • SQLInput interface -- provides methods for reading - UDT attributes from a stream -
    • SQLOutput interface -- provides methods for writing - UDT attributes back to a stream -
    -
  • Metadata -
      -
    • DatabaseMetaData interface -- provides information - about the database -
    • ResultSetMetaData interface -- provides information - about the columns of a ResultSet object -
    • ParameterMetaData interface -- provides information - about the parameters to PreparedStatement commands -
    -
  • Exceptions -
      -
    • SQLException -- thrown by most methods when there - is a problem accessing data and by some methods for other reasons -
    • SQLWarning -- thrown to indicate a warning -
    • DataTruncation -- thrown to indicate that data may have - been truncated -
    • BatchUpdateException -- thrown to indicate that not all - commands in a batch update executed successfully -
    -
- -

java.sql and javax.sql Features Introduced in the JDBC 4.3 API

-
    -
  • Added Sharding support
  • -
  • Enhanced Connection to be able to provide hints - to the driver that a request, an independent unit of work, - is beginning or ending
  • -
  • Enhanced DatabaseMetaData to determine if Sharding is - supported
  • -
  • Added the method drivers to DriverManager - to return a Stream of the currently loaded and - available JDBC drivers
  • -
  • Added support to Statement for enquoting literals - and simple identifiers
  • -
  • Clarified the Java SE version that methods were deprecated
  • -
- -

java.sql and javax.sql Features Introduced in the JDBC 4.2 API

-
    -
  • Added JDBCType enum and SQLType interface
  • -
  • Support for REF CURSORS in CallableStatement -
  • -
  • DatabaseMetaData methods to return maximum Logical LOB size - and if Ref Cursors are supported
  • -
  • Added support for large update counts
  • - -
- -

java.sql and javax.sql Features Introduced in the JDBC 4.1 API

-
    -
  • Allow Connection, - ResultSet and Statement objects to be - used with the try-with-resources statement
  • -
  • Support added to CallableStatement and - ResultSet to specify the Java type to convert to via the - getObject method
  • -
  • DatabaseMetaData methods to return PseudoColumns and if a - generated key is always returned
  • -
  • Added support to Connection to specify a database schema, - abort and timeout a physical connection.
  • -
  • Added support to close a Statement object when its dependent - objects have been closed
  • -
  • Support for obtaining the parent logger for a Driver, - DataSource, ConnectionPoolDataSource and - XADataSource
  • - -
-

java.sql and javax.sql Features Introduced in the JDBC 4.0 API

-
    -
  • auto java.sql.Driver discovery -- no longer need to load a -java.sql.Driver class via Class.forName -
  • National Character Set support added -
  • Support added for the SQL:2003 XML data type -
  • SQLException enhancements -- Added support for cause chaining; New SQLExceptions - added for common SQLState class value codes -
  • Enhanced Blob/Clob functionality -- Support provided to create and free a Blob/Clob instance - as well as additional methods added to improve accessibility -
  • Support added for accessing a SQL ROWID -
  • Support added to allow a JDBC application to access an instance of a JDBC resource - that has been wrapped by a vendor, usually in an application server or connection - pooling environment. -
  • Availability to be notified when a PreparedStatement that is associated - with a PooledConnection has been closed or the driver determines is invalid - - -
- - -

java.sql and javax.sql Features Introduced in the JDBC 3.0 API

-
    -
  • Pooled statements -- reuse of statements associated with a pooled - connection -
  • Savepoints -- allow a transaction to be rolled back to a designated - savepoint -
  • Properties defined for ConnectionPoolDataSource -- specify - how connections are to be pooled -
  • Metadata for parameters of a PreparedStatement object -
  • Ability to retrieve values from automatically generated columns -
  • Ability to have multiple ResultSet objects - returned from CallableStatement objects open at the - same time -
  • Ability to identify parameters to CallableStatement - objects by name as well as by index -
  • ResultSet holdability -- ability to specify whether cursors - should be held open or closed at the end of a transaction -
  • Ability to retrieve and update the SQL structured type instance that a - Ref object references -
  • Ability to programmatically update BLOB, - CLOB, ARRAY, and REF values. -
  • Addition of the java.sql.Types.DATALINK data type -- - allows JDBC drivers access to objects stored outside a data source -
  • Addition of metadata for retrieving SQL type hierarchies -
- -

java.sql Features Introduced in the JDBC 2.1 Core API

-
    -
  • Scrollable result sets--using new methods in the ResultSet - interface that allow the cursor to be moved to a particular row or to a - position relative to its current position -
  • Batch updates -
  • Programmatic updates--using ResultSet updater methods -
  • New data types--interfaces mapping the SQL3 data types -
  • Custom mapping of user-defined types (UDTs) -
  • Miscellaneous features, including performance hints, the use of character - streams, full precision for java.math.BigDecimal values, - additional security, and - support for time zones in date, time, and timestamp values. -
- -

javax.sql Features Introduced in the JDBC 2.0 Optional -Package API

-
    -
  • The DataSource interface as a means of making a connection. The - Java Naming and Directory Interface™ - (JNDI) is used for registering a DataSource object with a - naming service and also for retrieving it. -
  • Pooled connections -- allowing connections to be used and reused -
  • Distributed transactions -- allowing a transaction to span diverse - DBMS servers -
  • RowSet technology -- providing a convenient means of - handling and passing data -
- - -

Custom Mapping of UDTs

-A user-defined type (UDT) defined in SQL can be mapped to a class in the Java -programming language. An SQL structured type or an SQL DISTINCT -type are the UDTs that may be custom mapped. The following three -steps set up a custom mapping: -
    -
  1. Defining the SQL structured type or DISTINCT type in SQL -
  2. Defining the class in the Java programming language to which the - SQL UDT will be mapped. This class must implement the - SQLData interface. -
  3. Making an entry in a Connection object's type map - that contains two things: -
      -
    • the fully-qualified SQL name of the UDT -
    • the Class object for the class that implements the - SQLData interface -
    -
-

-When these are in place for a UDT, calling the methods -ResultSet.getObject or CallableStatement.getObject -on that UDT will automatically retrieve the custom mapping for it. Also, the -PreparedStatement.setObject method will automatically map the -object back to its SQL type to store it in the data source. - -

Package Specification

- - - -

Related Documentation

- - - - - diff --git a/src/java.sql/share/classes/javax/sql/package-info.java b/src/java.sql/share/classes/javax/sql/package-info.java new file mode 100644 index 00000000000..d88cfe3aa30 --- /dev/null +++ b/src/java.sql/share/classes/javax/sql/package-info.java @@ -0,0 +1,294 @@ +/** + * 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + *

+ * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + *

+ * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + *

+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides the API for server side data source access and processing from + * the Java™ programming language. + * This package supplements the java.sql + * package and, as of the version 1.4 release, is included in the + * Java Platform, Standard Edition (Java SE™). + * It remains an essential part of the Java Platform, Enterprise Edition + * (Java EE™). + *

+ * The javax.sql package provides for the following: + *

    + *
  1. The DataSource interface as an alternative to the + * DriverManager for establishing a + * connection with a data source + *
  2. Connection pooling and Statement pooling + *
  3. Distributed transactions + *
  4. Rowsets + *
+ *

+ * Applications use the DataSource and RowSet + * APIs directly, but the connection pooling and distributed transaction + * APIs are used internally by the middle-tier infrastructure. + * + *

Using a DataSource Object to Make a Connection

+ *

+ * The javax.sql package provides the preferred + * way to make a connection with a data source. The DriverManager + * class, the original mechanism, is still valid, and code using it will + * continue to run. However, the newer DataSource mechanism + * is preferred because it offers many advantages over the + * DriverManager mechanism. + *

+ * These are the main advantages of using a DataSource object to + * make a connection: + *

    + * + *
  • Changes can be made to a data source's properties, which means + * that it is not necessary to make changes in application code when + * something about the data source or driver changes. + *
  • Connection and Statement pooling and distributed transactions are available + * through a DataSource object that is + * implemented to work with the middle-tier infrastructure. + * Connections made through the DriverManager + * do not have connection and statement pooling or distributed transaction + * capabilities. + *
+ *

+ * Driver vendors provide DataSource implementations. A + * particular DataSource object represents a particular + * physical data source, and each connection the DataSource object + * creates is a connection to that physical data source. + *

+ * A logical name for the data source is registered with a naming service that + * uses the Java Naming and Directory Interface™ + * (JNDI) API, usually by a system administrator or someone performing the + * duties of a system administrator. An application can retrieve the + * DataSource object it wants by doing a lookup on the logical + * name that has been registered for it. The application can then use the + * DataSource object to create a connection to the physical data + * source it represents. + *

+ * A DataSource object can be implemented to work with the + * middle tier infrastructure so that the connections it produces will be + * pooled for reuse. An application that uses such a DataSource + * implementation will automatically get a connection that participates in + * connection pooling. + * A DataSource object can also be implemented to work with the + * middle tier infrastructure so that the connections it produces can be + * used for distributed transactions without any special coding. + * + *

Connection Pooling and Statement Pooling

+ *

+ * Connections made via a DataSource + * object that is implemented to work with a middle tier connection pool manager + * will participate in connection pooling. This can improve performance + * dramatically because creating new connections is very expensive. + * Connection pooling allows a connection to be used and reused, + * thus cutting down substantially on the number of new connections + * that need to be created. + *

+ * Connection pooling is totally transparent. It is done automatically + * in the middle tier of a Java EE configuration, so from an application's + * viewpoint, no change in code is required. An application simply uses + * the DataSource.getConnection method to get the pooled + * connection and uses it the same way it uses any Connection + * object. + *

+ * The classes and interfaces used for connection pooling are: + *

    + *
  • ConnectionPoolDataSource + *
  • PooledConnection + *
  • ConnectionEvent + *
  • ConnectionEventListener + *
  • StatementEvent + *
  • StatementEventListener + *
+ * The connection pool manager, a facility in the middle tier of + * a three-tier architecture, uses these classes and interfaces + * behind the scenes. When a ConnectionPoolDataSource object + * is called on to create a PooledConnection object, the + * connection pool manager will register as a ConnectionEventListener + * object with the new PooledConnection object. When the connection + * is closed or there is an error, the connection pool manager (being a listener) + * gets a notification that includes a ConnectionEvent object. + *

+ * If the connection pool manager supports Statement pooling, for + * PreparedStatements, which can be determined by invoking the method + * DatabaseMetaData.supportsStatementPooling, the + * connection pool manager will register as a StatementEventListener + * object with the new PooledConnection object. When the + * PreparedStatement is closed or there is an error, the connection + * pool manager (being a listener) + * gets a notification that includes a StatementEvent object. + * + *

Distributed Transactions

+ *

+ * As with pooled connections, connections made via a DataSource + * object that is implemented to work with the middle tier infrastructure + * may participate in distributed transactions. This gives an application + * the ability to involve data sources on multiple servers in a single + * transaction. + *

+ * The classes and interfaces used for distributed transactions are: + *

    + *
  • XADataSource + *
  • XAConnection + *
+ * These interfaces are used by the transaction manager; an application does + * not use them directly. + *

+ * The XAConnection interface is derived from the + * PooledConnection interface, so what applies to a pooled connection + * also applies to a connection that is part of a distributed transaction. + * A transaction manager in the middle tier handles everything transparently. + * The only change in application code is that an application cannot do anything + * that would interfere with the transaction manager's handling of the transaction. + * Specifically, an application cannot call the methods Connection.commit + * or Connection.rollback, and it cannot set the connection to be in + * auto-commit mode (that is, it cannot call + * Connection.setAutoCommit(true)). + *

+ * An application does not need to do anything special to participate in a + * distributed transaction. + * It simply creates connections to the data sources it wants to use via + * the DataSource.getConnection method, just as it normally does. + * The transaction manager manages the transaction behind the scenes. The + * XADataSource interface creates XAConnection objects, and + * each XAConnection object creates an XAResource object + * that the transaction manager uses to manage the connection. + * + * + *

Rowsets

+ * The RowSet interface works with various other classes and + * interfaces behind the scenes. These can be grouped into three categories. + *
    + *
  1. Event Notification + *
      + *
    • RowSetListener
      + * A RowSet object is a JavaBeans™ + * component because it has properties and participates in the JavaBeans + * event notification mechanism. The RowSetListener interface + * is implemented by a component that wants to be notified about events that + * occur to a particular RowSet object. Such a component registers + * itself as a listener with a rowset via the RowSet.addRowSetListener + * method. + *

      + * When the RowSet object changes one of its rows, changes all of + * it rows, or moves its cursor, it also notifies each listener that is registered + * with it. The listener reacts by carrying out its implementation of the + * notification method called on it. + *

    • RowSetEvent
      + * As part of its internal notification process, a RowSet object + * creates an instance of RowSetEvent and passes it to the listener. + * The listener can use this RowSetEvent object to find out which rowset + * had the event. + *
    + *
  2. Metadata + *
      + *
    • RowSetMetaData
      + * This interface, derived from the + * ResultSetMetaData interface, provides information about + * the columns in a RowSet object. An application can use + * RowSetMetaData methods to find out how many columns the + * rowset contains and what kind of data each column can contain. + *

      + * The RowSetMetaData interface provides methods for + * setting the information about columns, but an application would not + * normally use these methods. When an application calls the RowSet + * method execute, the RowSet object will contain + * a new set of rows, and its RowSetMetaData object will have been + * internally updated to contain information about the new columns. + *

    + *
  3. The Reader/Writer Facility
    + * A RowSet object that implements the RowSetInternal + * interface can call on the RowSetReader object associated with it + * to populate itself with data. It can also call on the RowSetWriter + * object associated with it to write any changes to its rows back to the + * data source from which it originally got the rows. + * A rowset that remains connected to its data source does not need to use a + * reader and writer because it can simply operate on the data source directly. + * + *
      + *
    • RowSetInternal
      + * By implementing the RowSetInternal interface, a + * RowSet object gets access to + * its internal state and is able to call on its reader and writer. A rowset + * keeps track of the values in its current rows and of the values that immediately + * preceded the current ones, referred to as the original values. A rowset + * also keeps track of (1) the parameters that have been set for its command and + * (2) the connection that was passed to it, if any. A rowset uses the + * RowSetInternal methods behind the scenes to get access to + * this information. An application does not normally invoke these methods directly. + * + *
    • RowSetReader
      + * A disconnected RowSet object that has implemented the + * RowSetInternal interface can call on its reader (the + * RowSetReader object associated with it) to populate it with + * data. When an application calls the RowSet.execute method, + * that method calls on the rowset's reader to do much of the work. Implementations + * can vary widely, but generally a reader makes a connection to the data source, + * reads data from the data source and populates the rowset with it, and closes + * the connection. A reader may also update the RowSetMetaData object + * for its rowset. The rowset's internal state is also updated, either by the + * reader or directly by the method RowSet.execute. + * + * + *
    • RowSetWriter
      + * A disconnected RowSet object that has implemented the + * RowSetInternal interface can call on its writer (the + * RowSetWriter object associated with it) to write changes + * back to the underlying data source. Implementations may vary widely, but + * generally, a writer will do the following: + * + *
        + *
      • Make a connection to the data source + *
      • Check to see whether there is a conflict, that is, whether + * a value that has been changed in the rowset has also been changed + * in the data source + *
      • Write the new values to the data source if there is no conflict + *
      • Close the connection + *
      + * + * + *
    + *
+ *

+ * The RowSet interface may be implemented in any number of + * ways, and anyone may write an implementation. Developers are encouraged + * to use their imaginations in coming up with new ways to use rowsets. + * + * + *

Package Specification

+ * + * + * + *

Related Documentation

+ *

+ * The Java Series book published by Addison-Wesley Longman provides detailed + * information about the classes and interfaces in the javax.sql + * package: + * + *

+ */ +package javax.sql; diff --git a/src/java.sql/share/classes/javax/sql/package.html b/src/java.sql/share/classes/javax/sql/package.html deleted file mode 100644 index 8ee4c44913b..00000000000 --- a/src/java.sql/share/classes/javax/sql/package.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - - - - - - - - -Provides the API for server side data source access and processing from -the Java™ programming language. -This package supplements the java.sql -package and, as of the version 1.4 release, is included in the -Java Platform, Standard Edition (Java SE™). -It remains an essential part of the Java Platform, Enterprise Edition -(Java EE™). -

-The javax.sql package provides for the following: -

    -
  1. The DataSource interface as an alternative to the - DriverManager for establishing a - connection with a data source -
  2. Connection pooling and Statement pooling -
  3. Distributed transactions -
  4. Rowsets -
-

-Applications use the DataSource and RowSet -APIs directly, but the connection pooling and distributed transaction -APIs are used internally by the middle-tier infrastructure. - -

Using a DataSource Object to Make a Connection

- -The javax.sql package provides the preferred -way to make a connection with a data source. The DriverManager -class, the original mechanism, is still valid, and code using it will -continue to run. However, the newer DataSource mechanism -is preferred because it offers many advantages over the -DriverManager mechanism. -

-These are the main advantages of using a DataSource object to -make a connection: -

    - -
  • Changes can be made to a data source's properties, which means - that it is not necessary to make changes in application code when - something about the data source or driver changes. -
  • Connection and Statement pooling and distributed transactions are available - through a DataSource object that is - implemented to work with the middle-tier infrastructure. - Connections made through the DriverManager - do not have connection and statement pooling or distributed transaction - capabilities. -
-

-Driver vendors provide DataSource implementations. A -particular DataSource object represents a particular -physical data source, and each connection the DataSource object -creates is a connection to that physical data source. -

-A logical name for the data source is registered with a naming service that -uses the Java Naming and Directory Interface™ -(JNDI) API, usually by a system administrator or someone performing the -duties of a system administrator. An application can retrieve the -DataSource object it wants by doing a lookup on the logical -name that has been registered for it. The application can then use the -DataSource object to create a connection to the physical data -source it represents. -

-A DataSource object can be implemented to work with the -middle tier infrastructure so that the connections it produces will be -pooled for reuse. An application that uses such a DataSource -implementation will automatically get a connection that participates in -connection pooling. -A DataSource object can also be implemented to work with the -middle tier infrastructure so that the connections it produces can be -used for distributed transactions without any special coding. - -

Connection Pooling and Statement Pooling

- -Connections made via a DataSource -object that is implemented to work with a middle tier connection pool manager -will participate in connection pooling. This can improve performance -dramatically because creating new connections is very expensive. -Connection pooling allows a connection to be used and reused, -thus cutting down substantially on the number of new connections -that need to be created. -

-Connection pooling is totally transparent. It is done automatically -in the middle tier of a Java EE configuration, so from an application's -viewpoint, no change in code is required. An application simply uses -the DataSource.getConnection method to get the pooled -connection and uses it the same way it uses any Connection -object. -

-The classes and interfaces used for connection pooling are: -

    -
  • ConnectionPoolDataSource -
  • PooledConnection -
  • ConnectionEvent -
  • ConnectionEventListener -
  • StatementEvent -
  • StatementEventListener -
-The connection pool manager, a facility in the middle tier of -a three-tier architecture, uses these classes and interfaces -behind the scenes. When a ConnectionPoolDataSource object -is called on to create a PooledConnection object, the -connection pool manager will register as a ConnectionEventListener -object with the new PooledConnection object. When the connection -is closed or there is an error, the connection pool manager (being a listener) -gets a notification that includes a ConnectionEvent object. -

-If the connection pool manager supports Statement pooling, for -PreparedStatements, which can be determined by invoking the method -DatabaseMetaData.supportsStatementPooling, the -connection pool manager will register as a StatementEventListener -object with the new PooledConnection object. When the -PreparedStatement is closed or there is an error, the connection -pool manager (being a listener) -gets a notification that includes a StatementEvent object. - -

Distributed Transactions

- -As with pooled connections, connections made via a DataSource -object that is implemented to work with the middle tier infrastructure -may participate in distributed transactions. This gives an application -the ability to involve data sources on multiple servers in a single -transaction. -

-The classes and interfaces used for distributed transactions are: -

    -
  • XADataSource -
  • XAConnection -
-These interfaces are used by the transaction manager; an application does -not use them directly. -

-The XAConnection interface is derived from the -PooledConnection interface, so what applies to a pooled connection -also applies to a connection that is part of a distributed transaction. -A transaction manager in the middle tier handles everything transparently. -The only change in application code is that an application cannot do anything -that would interfere with the transaction manager's handling of the transaction. -Specifically, an application cannot call the methods Connection.commit -or Connection.rollback, and it cannot set the connection to be in -auto-commit mode (that is, it cannot call -Connection.setAutoCommit(true)). -

-An application does not need to do anything special to participate in a -distributed transaction. -It simply creates connections to the data sources it wants to use via -the DataSource.getConnection method, just as it normally does. -The transaction manager manages the transaction behind the scenes. The -XADataSource interface creates XAConnection objects, and -each XAConnection object creates an XAResource object -that the transaction manager uses to manage the connection. - - -

Rowsets

-The RowSet interface works with various other classes and -interfaces behind the scenes. These can be grouped into three categories. -
    -
  1. Event Notification -
      -
    • RowSetListener
      -A RowSet object is a JavaBeans™ -component because it has properties and participates in the JavaBeans -event notification mechanism. The RowSetListener interface -is implemented by a component that wants to be notified about events that -occur to a particular RowSet object. Such a component registers -itself as a listener with a rowset via the RowSet.addRowSetListener -method. -

      -When the RowSet object changes one of its rows, changes all of -it rows, or moves its cursor, it also notifies each listener that is registered -with it. The listener reacts by carrying out its implementation of the -notification method called on it. -

    • RowSetEvent
      -As part of its internal notification process, a RowSet object -creates an instance of RowSetEvent and passes it to the listener. -The listener can use this RowSetEvent object to find out which rowset -had the event. -
    -
  2. Metadata -
      -
    • RowSetMetaData
      -This interface, derived from the -ResultSetMetaData interface, provides information about -the columns in a RowSet object. An application can use -RowSetMetaData methods to find out how many columns the -rowset contains and what kind of data each column can contain. -

      -The RowSetMetaData interface provides methods for -setting the information about columns, but an application would not -normally use these methods. When an application calls the RowSet -method execute, the RowSet object will contain -a new set of rows, and its RowSetMetaData object will have been -internally updated to contain information about the new columns. -

    -
  3. The Reader/Writer Facility
    -A RowSet object that implements the RowSetInternal -interface can call on the RowSetReader object associated with it -to populate itself with data. It can also call on the RowSetWriter -object associated with it to write any changes to its rows back to the -data source from which it originally got the rows. -A rowset that remains connected to its data source does not need to use a -reader and writer because it can simply operate on the data source directly. - -
      -
    • RowSetInternal
      -By implementing the RowSetInternal interface, a -RowSet object gets access to -its internal state and is able to call on its reader and writer. A rowset -keeps track of the values in its current rows and of the values that immediately -preceded the current ones, referred to as the original values. A rowset -also keeps track of (1) the parameters that have been set for its command and -(2) the connection that was passed to it, if any. A rowset uses the -RowSetInternal methods behind the scenes to get access to -this information. An application does not normally invoke these methods directly. - -
    • RowSetReader
      -A disconnected RowSet object that has implemented the -RowSetInternal interface can call on its reader (the -RowSetReader object associated with it) to populate it with -data. When an application calls the RowSet.execute method, -that method calls on the rowset's reader to do much of the work. Implementations -can vary widely, but generally a reader makes a connection to the data source, -reads data from the data source and populates the rowset with it, and closes -the connection. A reader may also update the RowSetMetaData object -for its rowset. The rowset's internal state is also updated, either by the -reader or directly by the method RowSet.execute. - - -
    • RowSetWriter
      -A disconnected RowSet object that has implemented the -RowSetInternal interface can call on its writer (the -RowSetWriter object associated with it) to write changes -back to the underlying data source. Implementations may vary widely, but -generally, a writer will do the following: - -
        -
      • Make a connection to the data source -
      • Check to see whether there is a conflict, that is, whether - a value that has been changed in the rowset has also been changed - in the data source -
      • Write the new values to the data source if there is no conflict -
      • Close the connection -
      - - -
    -
-

-The RowSet interface may be implemented in any number of -ways, and anyone may write an implementation. Developers are encouraged -to use their imaginations in coming up with new ways to use rowsets. - - -

Package Specification

- - - -

Related Documentation

- -The Java Series book published by Addison-Wesley Longman provides detailed -information about the classes and interfaces in the javax.sql -package: - - - - From 05e175bf1beeaecc24c120846595347cf08dd2c0 Mon Sep 17 00:00:00 2001 From: Vivek Deshpande Date: Wed, 12 Dec 2018 14:48:34 -0800 Subject: [PATCH 023/174] 8214751: X86: Support for VNNI Instructions Co-authored-by: Razvan A Lupusoru Reviewed-by: kvn --- src/hotspot/cpu/x86/assembler_x86.cpp | 28 ++++ src/hotspot/cpu/x86/assembler_x86.hpp | 6 + src/hotspot/cpu/x86/vm_version_x86.cpp | 2 +- src/hotspot/cpu/x86/vm_version_x86.hpp | 4 + src/hotspot/cpu/x86/x86.ad | 116 +++++++++++++++++ src/hotspot/cpu/x86/x86_32.ad | 10 ++ src/hotspot/cpu/x86/x86_64.ad | 10 ++ src/hotspot/share/adlc/formssel.cpp | 1 + src/hotspot/share/opto/classes.hpp | 2 + src/hotspot/share/opto/loopnode.hpp | 3 + src/hotspot/share/opto/loopopts.cpp | 53 ++++++++ src/hotspot/share/opto/matcher.cpp | 9 ++ src/hotspot/share/opto/mulnode.hpp | 11 ++ src/hotspot/share/opto/superword.cpp | 84 +++++++++++- src/hotspot/share/opto/superword.hpp | 1 + src/hotspot/share/opto/vectornode.cpp | 24 ++++ src/hotspot/share/opto/vectornode.hpp | 11 ++ .../loopopts/superword/Vec_MulAddS2I.java | 120 ++++++++++++++++++ 18 files changed, 491 insertions(+), 4 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/loopopts/superword/Vec_MulAddS2I.java diff --git a/src/hotspot/cpu/x86/assembler_x86.cpp b/src/hotspot/cpu/x86/assembler_x86.cpp index f27c66ca5ed..0076100103b 100644 --- a/src/hotspot/cpu/x86/assembler_x86.cpp +++ b/src/hotspot/cpu/x86/assembler_x86.cpp @@ -3966,6 +3966,34 @@ void Assembler::vpmovzxwd(XMMRegister dst, XMMRegister src, int vector_len) { emit_int8((unsigned char)(0xC0 | encode)); } +void Assembler::pmaddwd(XMMRegister dst, XMMRegister src) { + NOT_LP64(assert(VM_Version::supports_sse2(), "")); + InstructionAttr attributes(AVX_128bit, /* rex_w */ false, /* legacy_mode */ _legacy_mode_bw, /* no_mask_reg */ true, /* uses_vl */ true); + int encode = simd_prefix_and_encode(dst, dst, src, VEX_SIMD_66, VEX_OPCODE_0F, &attributes); + emit_int8((unsigned char)0xF5); + emit_int8((unsigned char)(0xC0 | encode)); +} + +void Assembler::vpmaddwd(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(vector_len == AVX_128bit ? VM_Version::supports_avx() : + (vector_len == AVX_256bit ? VM_Version::supports_avx2() : + (vector_len == AVX_512bit ? VM_Version::supports_evex() : 0)), ""); + InstructionAttr attributes(vector_len, /* rex_w */ false, /* legacy_mode */ _legacy_mode_bw, /* no_mask_reg */ true, /* uses_vl */ true); + int encode = simd_prefix_and_encode(dst, nds, src, VEX_SIMD_66, VEX_OPCODE_0F, &attributes); + emit_int8((unsigned char)0xF5); + emit_int8((unsigned char)(0xC0 | encode)); +} + +void Assembler::evpdpwssd(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) { + assert(VM_Version::supports_evex(), ""); + assert(VM_Version::supports_vnni(), "must support vnni"); + InstructionAttr attributes(vector_len, /* vex_w */ false, /* legacy_mode */ false, /* no_mask_reg */ true, /* uses_vl */ true); + attributes.set_is_evex_instruction(); + int encode = vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(), VEX_SIMD_66, VEX_OPCODE_0F_38, &attributes); + emit_int8(0x52); + emit_int8((unsigned char)(0xC0 | encode)); +} + // generic void Assembler::pop(Register dst) { int encode = prefix_and_encode(dst->encoding()); diff --git a/src/hotspot/cpu/x86/assembler_x86.hpp b/src/hotspot/cpu/x86/assembler_x86.hpp index e9d85e3d225..7ad59531479 100644 --- a/src/hotspot/cpu/x86/assembler_x86.hpp +++ b/src/hotspot/cpu/x86/assembler_x86.hpp @@ -1668,6 +1668,12 @@ private: void evpmovdb(Address dst, XMMRegister src, int vector_len); + // Multiply add + void pmaddwd(XMMRegister dst, XMMRegister src); + void vpmaddwd(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); + // Multiply add accumulate + void evpdpwssd(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len); + #ifndef _LP64 // no 32bit push/pop on amd64 void popl(Address dst); #endif diff --git a/src/hotspot/cpu/x86/vm_version_x86.cpp b/src/hotspot/cpu/x86/vm_version_x86.cpp index a621609fd71..1550df75035 100644 --- a/src/hotspot/cpu/x86/vm_version_x86.cpp +++ b/src/hotspot/cpu/x86/vm_version_x86.cpp @@ -1289,7 +1289,7 @@ void VM_Version::get_processor_features() { if (FLAG_IS_DEFAULT(UseXMMForArrayCopy)) { UseXMMForArrayCopy = true; // use SSE2 movq on new Intel cpus } - if (supports_sse4_2() && supports_ht()) { // Newest Intel cpus + if ((supports_sse4_2() && supports_ht()) || supports_avx()) { // Newest Intel cpus if (FLAG_IS_DEFAULT(UseUnalignedLoadStores)) { UseUnalignedLoadStores = true; // use movdqu on newest Intel cpus } diff --git a/src/hotspot/cpu/x86/vm_version_x86.hpp b/src/hotspot/cpu/x86/vm_version_x86.hpp index 2e360729dd3..e435ea53be6 100644 --- a/src/hotspot/cpu/x86/vm_version_x86.hpp +++ b/src/hotspot/cpu/x86/vm_version_x86.hpp @@ -336,6 +336,7 @@ protected: #define CPU_AVX512_VPOPCNTDQ ((uint64_t)UCONST64(0x2000000000)) // Vector popcount #define CPU_VPCLMULQDQ ((uint64_t)UCONST64(0x4000000000)) //Vector carryless multiplication #define CPU_VAES ((uint64_t)UCONST64(0x8000000000)) // Vector AES instructions +#define CPU_VNNI ((uint64_t)UCONST64(0x16000000000)) // Vector Neural Network Instructions enum Extended_Family { // AMD @@ -548,6 +549,8 @@ protected: result |= CPU_VPCLMULQDQ; if (_cpuid_info.sef_cpuid7_ecx.bits.vaes != 0) result |= CPU_VAES; + if (_cpuid_info.sef_cpuid7_ecx.bits.avx512_vnni != 0) + result |= CPU_VNNI; } } if(_cpuid_info.sef_cpuid7_ebx.bits.bmi1 != 0) @@ -828,6 +831,7 @@ public: static bool supports_vpopcntdq() { return (_features & CPU_AVX512_VPOPCNTDQ) != 0; } static bool supports_vpclmulqdq() { return (_features & CPU_VPCLMULQDQ) != 0; } static bool supports_vaes() { return (_features & CPU_VAES) != 0; } + static bool supports_vnni() { return (_features & CPU_VNNI) != 0; } // Intel features static bool is_intel_family_core() { return is_intel() && diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index 69c0572e6e3..6e52124df10 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -1446,6 +1446,10 @@ const bool Matcher::match_rule_supported(int opcode) { if (VM_Version::supports_on_spin_wait() == false) ret_value = false; break; + case Op_MulAddVS2VI: + if (UseSSE < 2) + ret_value = false; + break; } return ret_value; // Per default match rules are supported. @@ -9855,6 +9859,118 @@ instruct vfma16F_mem(vecZ a, memory b, vecZ c) %{ ins_pipe( pipe_slow ); %} +// --------------------------------- Vector Multiply Add -------------------------------------- + +instruct smuladd4S2I_reg(vecD dst, vecD src1) %{ + predicate(UseSSE >= 2 && UseAVX == 0 && n->as_Vector()->length() == 2); + match(Set dst (MulAddVS2VI dst src1)); + format %{ "pmaddwd $dst,$dst,$src1\t! muladd packed4Sto2I" %} + ins_encode %{ + __ pmaddwd($dst$$XMMRegister, $src1$$XMMRegister); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladd4S2I_reg(vecD dst, vecD src1, vecD src2) %{ + predicate(UseAVX > 0 && n->as_Vector()->length() == 2); + match(Set dst (MulAddVS2VI src1 src2)); + format %{ "vpmaddwd $dst,$src1,$src2\t! muladd packed4Sto2I" %} + ins_encode %{ + int vector_len = 0; + __ vpmaddwd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct smuladd8S4I_reg(vecX dst, vecX src1) %{ + predicate(UseSSE >= 2 && UseAVX == 0 && n->as_Vector()->length() == 4); + match(Set dst (MulAddVS2VI dst src1)); + format %{ "pmaddwd $dst,$dst,$src1\t! muladd packed8Sto4I" %} + ins_encode %{ + __ pmaddwd($dst$$XMMRegister, $src1$$XMMRegister); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladd8S4I_reg(vecX dst, vecX src1, vecX src2) %{ + predicate(UseAVX > 0 && n->as_Vector()->length() == 4); + match(Set dst (MulAddVS2VI src1 src2)); + format %{ "vpmaddwd $dst,$src1,$src2\t! muladd packed8Sto4I" %} + ins_encode %{ + int vector_len = 0; + __ vpmaddwd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladd16S8I_reg(vecY dst, vecY src1, vecY src2) %{ + predicate(UseAVX > 1 && n->as_Vector()->length() == 8); + match(Set dst (MulAddVS2VI src1 src2)); + format %{ "vpmaddwd $dst,$src1,$src2\t! muladd packed16Sto8I" %} + ins_encode %{ + int vector_len = 1; + __ vpmaddwd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladd32S16I_reg(vecZ dst, vecZ src1, vecZ src2) %{ + predicate(UseAVX > 2 && n->as_Vector()->length() == 16); + match(Set dst (MulAddVS2VI src1 src2)); + format %{ "vpmaddwd $dst,$src1,$src2\t! muladd packed32Sto16I" %} + ins_encode %{ + int vector_len = 2; + __ vpmaddwd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +// --------------------------------- Vector Multiply Add Add ---------------------------------- + +instruct vmuladdadd4S2I_reg(vecD dst, vecD src1, vecD src2) %{ + predicate(VM_Version::supports_vnni() && UseAVX > 2 && n->as_Vector()->length() == 2); + match(Set dst (AddVI (MulAddVS2VI src1 src2) dst)); + format %{ "evpdpwssd $dst,$src1,$src2\t! muladdadd packed4Sto2I" %} + ins_encode %{ + int vector_len = 0; + __ evpdpwssd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladdadd8S4I_reg(vecX dst, vecX src1, vecX src2) %{ + predicate(VM_Version::supports_vnni() && UseAVX > 2 && n->as_Vector()->length() == 4); + match(Set dst (AddVI (MulAddVS2VI src1 src2) dst)); + format %{ "evpdpwssd $dst,$src1,$src2\t! muladdadd packed8Sto4I" %} + ins_encode %{ + int vector_len = 0; + __ evpdpwssd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladdadd16S8I_reg(vecY dst, vecY src1, vecY src2) %{ + predicate(VM_Version::supports_vnni() && UseAVX > 2 && n->as_Vector()->length() == 8); + match(Set dst (AddVI (MulAddVS2VI src1 src2) dst)); + format %{ "evpdpwssd $dst,$src1,$src2\t! muladdadd packed16Sto8I" %} + ins_encode %{ + int vector_len = 1; + __ evpdpwssd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + +instruct vmuladdadd32S16I_reg(vecZ dst, vecZ src1, vecZ src2) %{ + predicate(VM_Version::supports_vnni() && UseAVX > 2 && n->as_Vector()->length() == 16); + match(Set dst (AddVI (MulAddVS2VI src1 src2) dst)); + format %{ "evpdpwssd $dst,$src1,$src2\t! muladdadd packed32Sto16I" %} + ins_encode %{ + int vector_len = 2; + __ evpdpwssd($dst$$XMMRegister, $src1$$XMMRegister, $src2$$XMMRegister, vector_len); + %} + ins_pipe( pipe_slow ); +%} + // --------------------------------- PopCount -------------------------------------- instruct vpopcount2I(vecD dst, vecD src) %{ diff --git a/src/hotspot/cpu/x86/x86_32.ad b/src/hotspot/cpu/x86/x86_32.ad index a296e1b76aa..1c7d0f4440c 100644 --- a/src/hotspot/cpu/x86/x86_32.ad +++ b/src/hotspot/cpu/x86/x86_32.ad @@ -7755,6 +7755,16 @@ instruct mulI(rRegI dst, memory src, eFlagsReg cr) %{ ins_pipe( ialu_reg_mem_alu0 ); %} +instruct mulAddS2I_rReg(rRegI dst, rRegI src1, rRegI src2, rRegI src3, eFlagsReg cr) +%{ + match(Set dst (MulAddS2I (Binary dst src1) (Binary src2 src3))); + effect(KILL cr, KILL src2); + + expand %{ mulI_rReg(dst, src1, cr); + mulI_rReg(src2, src3, cr); + addI_rReg(dst, src2, cr); %} +%} + // Multiply Register Int to Long instruct mulI2L(eADXRegL dst, eAXRegI src, nadxRegI src1, eFlagsReg flags) %{ // Basic Idea: long = (long)int * (long)int diff --git a/src/hotspot/cpu/x86/x86_64.ad b/src/hotspot/cpu/x86/x86_64.ad index 412d42fd5a0..a8ae966fa62 100644 --- a/src/hotspot/cpu/x86/x86_64.ad +++ b/src/hotspot/cpu/x86/x86_64.ad @@ -8175,6 +8175,16 @@ instruct mulI_mem_imm(rRegI dst, memory src, immI imm, rFlagsReg cr) ins_pipe(ialu_reg_mem_alu0); %} +instruct mulAddS2I_rReg(rRegI dst, rRegI src1, rRegI src2, rRegI src3, rFlagsReg cr) +%{ + match(Set dst (MulAddS2I (Binary dst src1) (Binary src2 src3))); + effect(KILL cr, KILL src2); + + expand %{ mulI_rReg(dst, src1, cr); + mulI_rReg(src2, src3, cr); + addI_rReg(dst, src2, cr); %} +%} + instruct mulL_rReg(rRegL dst, rRegL src, rFlagsReg cr) %{ match(Set dst (MulL dst src)); diff --git a/src/hotspot/share/adlc/formssel.cpp b/src/hotspot/share/adlc/formssel.cpp index c5296d0c002..f1996c27f03 100644 --- a/src/hotspot/share/adlc/formssel.cpp +++ b/src/hotspot/share/adlc/formssel.cpp @@ -4181,6 +4181,7 @@ bool MatchRule::is_vector() const { "AddReductionVF", "AddReductionVD", "MulReductionVI", "MulReductionVL", "MulReductionVF", "MulReductionVD", + "MulAddVS2VI", "LShiftCntV","RShiftCntV", "LShiftVB","LShiftVS","LShiftVI","LShiftVL", "RShiftVB","RShiftVS","RShiftVI","RShiftVL", diff --git a/src/hotspot/share/opto/classes.hpp b/src/hotspot/share/opto/classes.hpp index edfbc6afa2a..8f5f9f6eeb2 100644 --- a/src/hotspot/share/opto/classes.hpp +++ b/src/hotspot/share/opto/classes.hpp @@ -201,6 +201,7 @@ macro(Loop) macro(LoopLimit) macro(Mach) macro(MachProj) +macro(MulAddS2I) macro(MaxI) macro(MemBarAcquire) macro(LoadFence) @@ -341,6 +342,7 @@ macro(MulVF) macro(MulReductionVF) macro(MulVD) macro(MulReductionVD) +macro(MulAddVS2VI) macro(FmaVD) macro(FmaVF) macro(DivVF) diff --git a/src/hotspot/share/opto/loopnode.hpp b/src/hotspot/share/opto/loopnode.hpp index aff577e2ce1..bf030aed428 100644 --- a/src/hotspot/share/opto/loopnode.hpp +++ b/src/hotspot/share/opto/loopnode.hpp @@ -1249,6 +1249,9 @@ public: // important (common) to do address expressions. Node *remix_address_expressions( Node *n ); + // Convert add to muladd to generate MuladdS2I under certain criteria + Node * convert_add_to_muladd(Node * n); + // Attempt to use a conditional move instead of a phi/branch Node *conditional_move( Node *n ); diff --git a/src/hotspot/share/opto/loopopts.cpp b/src/hotspot/share/opto/loopopts.cpp index cfa2c45728c..aae56b63b20 100644 --- a/src/hotspot/share/opto/loopopts.cpp +++ b/src/hotspot/share/opto/loopopts.cpp @@ -493,6 +493,54 @@ Node *PhaseIdealLoop::remix_address_expressions( Node *n ) { return NULL; } +// Optimize ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1])) +Node *PhaseIdealLoop::convert_add_to_muladd(Node* n) { + assert(n->Opcode() == Op_AddI, "sanity"); + Node * nn = NULL; + Node * in1 = n->in(1); + Node * in2 = n->in(2); + if (in1->Opcode() == Op_MulI && in2->Opcode() == Op_MulI) { + IdealLoopTree* loop_n = get_loop(get_ctrl(n)); + if (loop_n->_head->as_Loop()->is_valid_counted_loop() && + Matcher::match_rule_supported(Op_MulAddS2I) && + Matcher::match_rule_supported(Op_MulAddVS2VI)) { + Node* mul_in1 = in1->in(1); + Node* mul_in2 = in1->in(2); + Node* mul_in3 = in2->in(1); + Node* mul_in4 = in2->in(2); + if (mul_in1->Opcode() == Op_LoadS && + mul_in2->Opcode() == Op_LoadS && + mul_in3->Opcode() == Op_LoadS && + mul_in4->Opcode() == Op_LoadS) { + IdealLoopTree* loop1 = get_loop(get_ctrl(mul_in1)); + IdealLoopTree* loop2 = get_loop(get_ctrl(mul_in2)); + IdealLoopTree* loop3 = get_loop(get_ctrl(mul_in3)); + IdealLoopTree* loop4 = get_loop(get_ctrl(mul_in4)); + IdealLoopTree* loop5 = get_loop(get_ctrl(in1)); + IdealLoopTree* loop6 = get_loop(get_ctrl(in2)); + // All nodes should be in the same counted loop. + if (loop_n == loop1 && loop_n == loop2 && loop_n == loop3 && + loop_n == loop4 && loop_n == loop5 && loop_n == loop6) { + Node* adr1 = mul_in1->in(MemNode::Address); + Node* adr2 = mul_in2->in(MemNode::Address); + Node* adr3 = mul_in3->in(MemNode::Address); + Node* adr4 = mul_in4->in(MemNode::Address); + if (adr1->is_AddP() && adr2->is_AddP() && adr3->is_AddP() && adr4->is_AddP()) { + if ((adr1->in(AddPNode::Base) == adr3->in(AddPNode::Base)) && + (adr2->in(AddPNode::Base) == adr4->in(AddPNode::Base))) { + nn = new MulAddS2INode(mul_in1, mul_in2, mul_in3, mul_in4); + register_new_node(nn, get_ctrl(n)); + _igvn.replace_node(n, nn); + return nn; + } + } + } + } + } + } + return nn; +} + //------------------------------conditional_move------------------------------- // Attempt to replace a Phi with a conditional move. We have some pretty // strict profitability requirements. All Phis at the merge point must @@ -927,6 +975,11 @@ Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) { Node *m = remix_address_expressions( n ); if( m ) return m; + if (n_op == Op_AddI) { + Node *nn = convert_add_to_muladd( n ); + if ( nn ) return nn; + } + if (n->is_ConstraintCast()) { Node* dom_cast = n->as_ConstraintCast()->dominating_cast(&_igvn, this); // ConstraintCastNode::dominating_cast() uses node control input to determine domination. diff --git a/src/hotspot/share/opto/matcher.cpp b/src/hotspot/share/opto/matcher.cpp index 271cb5c56ea..5d707645c24 100644 --- a/src/hotspot/share/opto/matcher.cpp +++ b/src/hotspot/share/opto/matcher.cpp @@ -2352,6 +2352,15 @@ void Matcher::find_shared_post_visit(Node* n, uint opcode) { n->del_req(3); break; } + case Op_MulAddS2I: { + Node* pair1 = new BinaryNode(n->in(1), n->in(2)); + Node* pair2 = new BinaryNode(n->in(3), n->in(4)); + n->set_req(1, pair1); + n->set_req(2, pair2); + n->del_req(4); + n->del_req(3); + break; + } default: break; } diff --git a/src/hotspot/share/opto/mulnode.hpp b/src/hotspot/share/opto/mulnode.hpp index 4d693970ca3..1520ab4f00d 100644 --- a/src/hotspot/share/opto/mulnode.hpp +++ b/src/hotspot/share/opto/mulnode.hpp @@ -285,4 +285,15 @@ public: virtual const Type* Value(PhaseGVN* phase) const; }; +//------------------------------MulAddS2INode---------------------------------- +// Multiply shorts into integers and add them. +// Semantics: I_OUT = S1 * S2 + S3 * S4 +class MulAddS2INode : public Node { +public: + MulAddS2INode(Node* in1, Node *in2, Node *in3, Node* in4) : Node(0, in1, in2, in3, in4) {} + virtual int Opcode() const; + const Type *bottom_type() const { return TypeInt::INT; } + virtual uint ideal_reg() const { return Op_RegI; } +}; + #endif // SHARE_VM_OPTO_MULNODE_HPP diff --git a/src/hotspot/share/opto/superword.cpp b/src/hotspot/share/opto/superword.cpp index 7e657f498b6..90dbef57c62 100644 --- a/src/hotspot/share/opto/superword.cpp +++ b/src/hotspot/share/opto/superword.cpp @@ -645,6 +645,10 @@ void SuperWord::find_adjacent_refs() { // with a different alignment were created before. for (uint i = 0; i < align_to_refs.size(); i++) { MemNode* mr = align_to_refs.at(i)->as_Mem(); + if (mr == mem_ref) { + // Skip when we are looking at same memory operation. + continue; + } if (same_velt_type(mr, mem_ref) && memory_alignment(mr, iv_adjustment) != 0) create_pack = false; @@ -846,6 +850,27 @@ MemNode* SuperWord::find_align_to_ref(Node_List &memops) { return NULL; } +//------------------span_works_for_memory_size----------------------------- +static bool span_works_for_memory_size(MemNode* mem, int span, int mem_size, int offset) { + bool span_matches_memory = false; + if ((mem_size == type2aelembytes(T_BYTE) || mem_size == type2aelembytes(T_SHORT)) + && ABS(span) == type2aelembytes(T_INT)) { + // There is a mismatch on span size compared to memory. + for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) { + Node* use = mem->fast_out(j); + if (!VectorNode::is_type_transition_to_int(use)) { + return false; + } + } + // If all uses transition to integer, it means that we can successfully align even on mismatch. + return true; + } + else { + span_matches_memory = ABS(span) == mem_size; + } + return span_matches_memory && (ABS(offset) % mem_size) == 0; +} + //------------------------------ref_is_alignable--------------------------- // Can the preloop align the reference to position zero in the vector? bool SuperWord::ref_is_alignable(SWPointer& p) { @@ -862,7 +887,7 @@ bool SuperWord::ref_is_alignable(SWPointer& p) { int offset = p.offset_in_bytes(); // Stride one accesses are alignable if offset is aligned to memory operation size. // Offset can be unaligned when UseUnalignedAccesses is used. - if (ABS(span) == mem_size && (ABS(offset) % mem_size) == 0) { + if (span_works_for_memory_size(p.mem(), span, mem_size, offset)) { return true; } // If the initial offset from start of the object is computable, @@ -915,6 +940,28 @@ bool SuperWord::ref_is_alignable(SWPointer& p) { } return false; } +//---------------------------get_vw_bytes_special------------------------ +int SuperWord::get_vw_bytes_special(MemNode* s) { + // Get the vector width in bytes. + int vw = vector_width_in_bytes(s); + + // Check for special case where there is an MulAddS2I usage where short vectors are going to need combined. + BasicType btype = velt_basic_type(s); + if (type2aelembytes(btype) == 2) { + bool should_combine_adjacent = true; + for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) { + Node* user = s->fast_out(i); + if (!VectorNode::is_muladds2i(user)) { + should_combine_adjacent = false; + } + } + if (should_combine_adjacent) { + vw = MIN2(Matcher::max_vector_size(btype)*type2aelembytes(btype), vw * 2); + } + } + + return vw; +} //---------------------------get_iv_adjustment--------------------------- // Calculate loop's iv adjustment for this memory ops. @@ -923,7 +970,7 @@ int SuperWord::get_iv_adjustment(MemNode* mem_ref) { int offset = align_to_ref_p.offset_in_bytes(); int scale = align_to_ref_p.scale_in_bytes(); int elt_size = align_to_ref_p.memory_size(); - int vw = vector_width_in_bytes(mem_ref); + int vw = get_vw_bytes_special(mem_ref); assert(vw > 1, "sanity"); int iv_adjustment; if (scale != 0) { @@ -2303,6 +2350,12 @@ void SuperWord::output() { const TypePtr* atyp = n->adr_type(); vn = StoreVectorNode::make(opc, ctl, mem, adr, atyp, val, vlen); vlen_in_bytes = vn->as_StoreVector()->memory_size(); + } else if (VectorNode::is_muladds2i(n)) { + assert(n->req() == 5u, "MulAddS2I should have 4 operands."); + Node* in1 = vector_opd(p, 1); + Node* in2 = vector_opd(p, 2); + vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n)); + vlen_in_bytes = vn->as_Vector()->length_in_bytes(); } else if (n->req() == 3 && !is_cmov_pack(p)) { // Promote operands to vector Node* in1 = NULL; @@ -2615,6 +2668,16 @@ Node* SuperWord::vector_opd(Node_List* p, int opd_idx) { } assert(opd_bt == in->bottom_type()->basic_type(), "all same type"); pk->add_opd(in); + if (VectorNode::is_muladds2i(pi)) { + Node* in2 = pi->in(opd_idx + 2); + assert(my_pack(in2) == NULL, "Should already have been unpacked"); + if (my_pack(in2) != NULL) { + NOT_PRODUCT(if (is_trace_loop_reverse() || TraceLoopOpts) { tty->print_cr("Should already have been unpacked"); }) + return NULL; + } + assert(opd_bt == in2->bottom_type()->basic_type(), "all same type"); + pk->add_opd(in2); + } } _igvn.register_new_node_with_optimizer(pk); _phase->set_ctrl(pk, _phase->get_ctrl(opd)); @@ -2692,6 +2755,21 @@ bool SuperWord::is_vector_use(Node* use, int u_idx) { } return true; } + if (VectorNode::is_muladds2i(use)) { + // MulAddS2I takes shorts and produces ints - hence the special checks + // on alignment and size. + if (u_pk->size() * 2 != d_pk->size()) { + return false; + } + for (uint i = 0; i < MIN2(d_pk->size(), u_pk->size()); i++) { + Node* ui = u_pk->at(i); + Node* di = d_pk->at(i); + if (alignment(ui) != alignment(di) * 2) { + return false; + } + } + return true; + } if (u_pk->size() != d_pk->size()) return false; for (uint i = 0; i < u_pk->size(); i++) { @@ -3017,7 +3095,7 @@ int SuperWord::memory_alignment(MemNode* s, int iv_adjust) { NOT_PRODUCT(if(is_trace_alignment()) tty->print("SWPointer::memory_alignment: SWPointer p invalid, return bottom_align");) return bottom_align; } - int vw = vector_width_in_bytes(s); + int vw = get_vw_bytes_special(s); if (vw < 2) { NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: vector_width_in_bytes < 2, return bottom_align");) return bottom_align; // No vectors for this type diff --git a/src/hotspot/share/opto/superword.hpp b/src/hotspot/share/opto/superword.hpp index 0db64bc940f..0be9e96b62f 100644 --- a/src/hotspot/share/opto/superword.hpp +++ b/src/hotspot/share/opto/superword.hpp @@ -347,6 +347,7 @@ class SuperWord : public ResourceObj { BasicType bt = velt_basic_type(n); return vector_width(n)*type2aelembytes(bt); } + int get_vw_bytes_special(MemNode* s); MemNode* align_to_ref() { return _align_to_ref; } void set_align_to_ref(MemNode* m) { _align_to_ref = m; } diff --git a/src/hotspot/share/opto/vectornode.cpp b/src/hotspot/share/opto/vectornode.cpp index 593baf97255..0e8021b8114 100644 --- a/src/hotspot/share/opto/vectornode.cpp +++ b/src/hotspot/share/opto/vectornode.cpp @@ -196,6 +196,8 @@ int VectorNode::opcode(int sopc, BasicType bt) { case Op_StoreF: case Op_StoreD: return Op_StoreVector; + case Op_MulAddS2I: + return Op_MulAddVS2VI; default: return 0; // Unimplemented @@ -214,6 +216,25 @@ bool VectorNode::implemented(int opc, uint vlen, BasicType bt) { return false; } +bool VectorNode::is_type_transition_short_to_int(Node* n) { + switch (n->Opcode()) { + case Op_MulAddS2I: + return true; + } + return false; +} + +bool VectorNode::is_type_transition_to_int(Node* n) { + return is_type_transition_short_to_int(n); +} + +bool VectorNode::is_muladds2i(Node* n) { + if (n->Opcode() == Op_MulAddS2I) { + return true; + } + return false; +} + bool VectorNode::is_shift(Node* n) { switch (n->Opcode()) { case Op_LShiftI: @@ -277,6 +298,7 @@ void VectorNode::vector_operands(Node* n, uint* start, uint* end) { case Op_AndI: case Op_AndL: case Op_OrI: case Op_OrL: case Op_XorI: case Op_XorL: + case Op_MulAddS2I: *start = 1; *end = 3; // 2 vector operands break; @@ -354,6 +376,8 @@ VectorNode* VectorNode::make(int opc, Node* n1, Node* n2, uint vlen, BasicType b case Op_AndV: return new AndVNode(n1, n2, vt); case Op_OrV: return new OrVNode (n1, n2, vt); case Op_XorV: return new XorVNode(n1, n2, vt); + + case Op_MulAddVS2VI: return new MulAddVS2VINode(n1, n2, vt); default: fatal("Missed vector creation for '%s'", NodeClassNames[vopc]); return NULL; diff --git a/src/hotspot/share/opto/vectornode.hpp b/src/hotspot/share/opto/vectornode.hpp index 850b1101bea..675564c9d82 100644 --- a/src/hotspot/share/opto/vectornode.hpp +++ b/src/hotspot/share/opto/vectornode.hpp @@ -67,6 +67,9 @@ class VectorNode : public TypeNode { static int opcode(int opc, BasicType bt); static bool implemented(int opc, uint vlen, BasicType bt); static bool is_shift(Node* n); + static bool is_type_transition_short_to_int(Node* n); + static bool is_type_transition_to_int(Node* n); + static bool is_muladds2i(Node* n); static bool is_invariant_vector(Node* n); // [Start, end) half-open range defining which operands are vectors static void vector_operands(Node* n, uint* start, uint* end); @@ -261,6 +264,14 @@ public: virtual int Opcode() const; }; +//------------------------------MulAddVS2VINode-------------------------------- +// Vector multiply shorts to int and add adjacent ints. +class MulAddVS2VINode : public VectorNode { + public: + MulAddVS2VINode(Node* in1, Node* in2, const TypeVect* vt) : VectorNode(in1, in2, vt) {} + virtual int Opcode() const; +}; + //------------------------------FmaVDNode-------------------------------------- // Vector multiply double class FmaVDNode : public VectorNode { diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/Vec_MulAddS2I.java b/test/hotspot/jtreg/compiler/loopopts/superword/Vec_MulAddS2I.java new file mode 100644 index 00000000000..cd55ab207fc --- /dev/null +++ b/test/hotspot/jtreg/compiler/loopopts/superword/Vec_MulAddS2I.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8214751 + * @summary Add C2 x86 Superword support for VNNI VPDPWSSD Instruction + * @requires os.arch=="x86" | os.arch=="i386" | os.arch=="amd64" | os.arch=="x86_64" + * + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:+SuperWord + * -XX:LoopMaxUnroll=2 + * compiler.loopopts.superword.Vec_MulAddS2I + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:-SuperWord + * -XX:LoopMaxUnroll=2 + * compiler.loopopts.superword.Vec_MulAddS2I + * + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:+SuperWord + * -XX:LoopMaxUnroll=4 + * compiler.loopopts.superword.Vec_MulAddS2I + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:-SuperWord + * -XX:LoopMaxUnroll=4 + * compiler.loopopts.superword.Vec_MulAddS2I + * + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:+SuperWord + * -XX:LoopMaxUnroll=8 + * compiler.loopopts.superword.Vec_MulAddS2I + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:-SuperWord + * -XX:LoopMaxUnroll=8 + * compiler.loopopts.superword.Vec_MulAddS2I + * + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:+SuperWord + * -XX:LoopMaxUnroll=16 + * compiler.loopopts.superword.Vec_MulAddS2I + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:LoopUnrollLimit=250 + * -XX:CompileThresholdScaling=0.1 + * -XX:-SuperWord + * -XX:LoopMaxUnroll=16 + * compiler.loopopts.superword.Vec_MulAddS2I + */ + +package compiler.loopopts.superword; +import java.util.Random; + +public class Vec_MulAddS2I { + static final int NUM = 1024; + static int[] out = new int[NUM]; + static short[] in1 = new short[2*NUM]; + static short[] in2 = new short[2*NUM]; + public static void main(String[] args) throws Exception { + Vec_MulAddS2IInit(in1, in2); + int result = 0; + int valid = 204800000; + for (int j = 0; j < 10000*512; j++) { + result = Vec_MulAddS2IImplement(in1, in2, out); + } + if (result == valid) { + System.out.println("Success"); + } else { + System.out.println("Invalid calculation of element variables in the out array: " + result); + System.out.println("Expected value for each element of out array = " + valid); + throw new Exception("Failed"); + } + } + + public static void Vec_MulAddS2IInit( + short[] in1, + short[] in2) { + for (int i=0; i<2*NUM; i++) { + in1[i] = (short)4; + in2[i] = (short)5; + } + } + + public static int Vec_MulAddS2IImplement( + short[] in1, + short[] in2, + int[] out) { + for (int i = 0; i < NUM; i++) { + out[i] += ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1])); + } + Random rand = new Random(); + int n = rand.nextInt(NUM-1); + return out[n]; + } + +} From 2556622607ca4edb4e291798d4afbfa9e1abaa0a Mon Sep 17 00:00:00 2001 From: Mark Reinhold Date: Wed, 12 Dec 2018 15:01:29 -0800 Subject: [PATCH 024/174] 8215301: Module-summary page is unreadably wide Reviewed-by: mchung --- .../build/tools/jigsaw/ModuleSummary.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/make/jdk/src/classes/build/tools/jigsaw/ModuleSummary.java b/make/jdk/src/classes/build/tools/jigsaw/ModuleSummary.java index 520fb1b96b0..47fdc7aff0e 100644 --- a/make/jdk/src/classes/build/tools/jigsaw/ModuleSummary.java +++ b/make/jdk/src/classes/build/tools/jigsaw/ModuleSummary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,11 +36,13 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -552,6 +554,21 @@ public class ModuleSummary { return sb.toString(); } + private String providesEntry(Provides p) { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("provides %s
\n", p.service())); + List pvs = new ArrayList<>(p.providers()); + pvs.sort(Comparator.naturalOrder()); + for (int i = 0; i < pvs.size(); i++) { // My kingdom for Stream::zip ... + String fmt = ((i == 0) + ? "    with %s" + : ",
         %s"); + sb.append(String.format(fmt, pvs.get(i))); + } + sb.append("\n"); + return sb.toString(); + } + public String servicesColumn() { StringBuilder sb = new StringBuilder(); sb.append(String.format("
"); return sb.toString(); From f47bd19cbc9bd7a8b9e8d8cdafb9c207ecd6f6f6 Mon Sep 17 00:00:00 2001 From: John Jiang Date: Thu, 13 Dec 2018 08:23:56 +0800 Subject: [PATCH 025/174] 8214520: [TEST_BUG] sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java failed with incorrect jtreg tags order Reviewed-by: xuelei --- .../sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jdk/sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java b/test/jdk/sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java index 637adf51d99..b78ade34eae 100644 --- a/test/jdk/sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java +++ b/test/jdk/sun/security/mscapi/nonUniqueAliases/NonUniqueAliases.java @@ -23,11 +23,11 @@ /* * @test - * @ignore Uses certutil.exe that isn't guaranteed to be installed * @bug 6483657 8154113 * @requires os.family == "windows" * @library /test/lib * @summary Test "keytool -list" displays correctly same named certificates + * @ignore Uses certutil.exe that isn't guaranteed to be installed */ import jdk.test.lib.process.ProcessTools; From 0b05ebed2ecd6ee8c5f0809194bd3f3b200a41a0 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Thu, 13 Dec 2018 01:15:21 +0000 Subject: [PATCH 026/174] 7092821: java.security.Provider.getService() is synchronized and became scalability bottleneck Changed Provider class to use ConcurrentHashMap and default providers to use putService() Reviewed-by: weijun, mullan --- .../com/sun/crypto/provider/SunJCE.java | 1280 ++++++++--------- .../share/classes/java/security/Provider.java | 144 +- .../classes/sun/security/provider/Sun.java | 27 +- .../sun/security/provider/SunEntries.java | 380 +++-- .../provider/VerificationProvider.java | 34 +- .../classes/sun/security/rsa/SunRsaSign.java | 28 +- .../sun/security/rsa/SunRsaSignEntries.java | 163 +-- .../classes/sun/security/ssl/SunJSSE.java | 115 +- 8 files changed, 1019 insertions(+), 1152 deletions(-) diff --git a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java index eeda0f1af73..3a086cf2694 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java @@ -28,8 +28,12 @@ package com.sun.crypto.provider; import java.security.AccessController; import java.security.Provider; import java.security.SecureRandom; +import java.security.PrivilegedAction; +import java.util.HashMap; +import java.util.List; import static sun.security.util.SecurityConstants.PROVIDER_VER; - +import static sun.security.provider.SunEntries.createAliases; +import static sun.security.provider.SunEntries.createAliasesWithOid; /** * The "SunJCE" Cryptographic Service Provider. @@ -81,16 +85,6 @@ public final class SunJCE extends Provider { "(implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, " + "Diffie-Hellman, HMAC, ChaCha20)"; - private static final String OID_PKCS12_RC4_128 = "1.2.840.113549.1.12.1.1"; - private static final String OID_PKCS12_RC4_40 = "1.2.840.113549.1.12.1.2"; - private static final String OID_PKCS12_DESede = "1.2.840.113549.1.12.1.3"; - private static final String OID_PKCS12_RC2_128 = "1.2.840.113549.1.12.1.5"; - private static final String OID_PKCS12_RC2_40 = "1.2.840.113549.1.12.1.6"; - private static final String OID_PKCS5_MD5_DES = "1.2.840.113549.1.5.3"; - private static final String OID_PKCS5_PBKDF2 = "1.2.840.113549.1.5.12"; - private static final String OID_PKCS5_PBES2 = "1.2.840.113549.1.5.13"; - private static final String OID_PKCS3 = "1.2.840.113549.1.3.1"; - /* Are we debugging? -- for developers */ static final boolean debug = false; @@ -105,10 +99,105 @@ public final class SunJCE extends Provider { } static SecureRandom getRandom() { return SecureRandomHolder.RANDOM; } + private void ps(String type, String algo, String cn, + List aliases, HashMap attrs) { + putService(new Provider.Service(this, type, algo, cn, aliases, attrs)); + } + public SunJCE() { /* We are the "SunJCE" provider */ super("SunJCE", PROVIDER_VER, info); + // if there is no security manager installed, put directly into + // the provider + if (System.getSecurityManager() == null) { + putEntries(); + } else { + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Void run() { + putEntries(); + return null; + } + }); + } + if (instance == null) { + instance = this; + } + } + + void putEntries() { + // common aliases and oids + List aesAliases = createAliases("Rijndael"); + List desEdeAliases = createAliases("TripleDES"); + List arcFourAliases = createAliases("RC4"); + List sunTlsMSAliases = createAliases( + "SunTls12MasterSecret", "SunTlsExtendedMasterSecret" + ); + List sunTlsKMAliases = createAliases("SunTls12KeyMaterial"); + List sunTlsRsaPMSAliases = createAliases("SunTls12RsaPremasterSecret"); + + String aes128Oid = "2.16.840.1.101.3.4.1."; + String aes192Oid = "2.16.840.1.101.3.4.1.2"; + String aes256Oid = "2.16.840.1.101.3.4.1.4"; + + List pkcs12RC4_128Aliases = + createAliasesWithOid("1.2.840.113549.1.12.1.1"); + + List pkcs12RC4_40Aliases = + createAliasesWithOid("1.2.840.113549.1.12.1.2"); + + List pkcs12DESedeAliases = + createAliasesWithOid("1.2.840.113549.1.12.1.3"); + + List pkcs12RC2_128Aliases = + createAliasesWithOid("1.2.840.113549.1.12.1.5"); + + List pkcs12RC2_40Aliases = + createAliasesWithOid("1.2.840.113549.1.12.1.6"); + + List pkcs5MD5_DESAliases = + createAliasesWithOid("1.2.840.113549.1.5.3", "PBE"); + + List pkcs5PBKDF2Aliases = + createAliasesWithOid("1.2.840.113549.1.5.12"); + + List pkcs5PBES2Aliases = + createAliasesWithOid("1.2.840.113549.1.5.13"); + + List diffieHellmanAliases = + createAliasesWithOid("1.2.840.113549.1.3.1", "DH"); + + List chachaPolyAliases = + createAliasesWithOid("1.2.840.113549.1.9.16.3.18"); + + String macOidBase = "1.2.840.113549.2."; + List macSHA1Aliases = createAliasesWithOid(macOidBase + "7"); + List macSHA224Aliases = createAliasesWithOid(macOidBase + "8"); + List macSHA256Aliases = createAliasesWithOid(macOidBase + "9"); + List macSHA384Aliases = createAliasesWithOid(macOidBase + "10"); + List macSHA512Aliases = createAliasesWithOid(macOidBase + "11"); + + // reuse attribute map and reset before each reuse + HashMap attrs = new HashMap<>(3); + attrs.put("SupportedModes", "ECB"); + attrs.put("SupportedPaddings", "NOPADDING|PKCS1PADDING|OAEPPADDING" + + "|OAEPWITHMD5ANDMGF1PADDING" + + "|OAEPWITHSHA1ANDMGF1PADDING" + + "|OAEPWITHSHA-1ANDMGF1PADDING" + + "|OAEPWITHSHA-224ANDMGF1PADDING" + + "|OAEPWITHSHA-256ANDMGF1PADDING" + + "|OAEPWITHSHA-384ANDMGF1PADDING" + + "|OAEPWITHSHA-512ANDMGF1PADDING" + + "|OAEPWITHSHA-512/224ANDMGF1PADDING" + + "|OAEPWITHSHA-512/256ANDMGF1PADDING"); + attrs.put("SupportedKeyClasses", + "java.security.interfaces.RSAPublicKey" + + "|java.security.interfaces.RSAPrivateKey"); + ps("Cipher", "RSA", + "com.sun.crypto.provider.RSACipher", null, attrs); + + // common block cipher modes, pads final String BLOCK_MODES = "ECB|CBC|PCBC|CTR|CTS|CFB|OFB" + "|CFB8|CFB16|CFB24|CFB32|CFB40|CFB48|CFB56|CFB64" + "|OFB8|OFB16|OFB24|OFB32|OFB40|OFB48|OFB56|OFB64"; @@ -117,699 +206,536 @@ public final class SunJCE extends Provider { "|OFB72|OFB80|OFB88|OFB96|OFB104|OFB112|OFB120|OFB128"; final String BLOCK_PADS = "NOPADDING|PKCS5PADDING|ISO10126PADDING"; - AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public Object run() { + attrs.clear(); + attrs.put("SupportedModes", BLOCK_MODES); + attrs.put("SupportedPaddings", BLOCK_PADS); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "DES", + "com.sun.crypto.provider.DESCipher", null, attrs); + ps("Cipher", "DESede", "com.sun.crypto.provider.DESedeCipher", + desEdeAliases, attrs); + ps("Cipher", "Blowfish", + "com.sun.crypto.provider.BlowfishCipher", null, attrs); - /* - * Cipher engines - */ - put("Cipher.RSA", "com.sun.crypto.provider.RSACipher"); - put("Cipher.RSA SupportedModes", "ECB"); - put("Cipher.RSA SupportedPaddings", - "NOPADDING|PKCS1PADDING|OAEPPADDING" - + "|OAEPWITHMD5ANDMGF1PADDING" - + "|OAEPWITHSHA1ANDMGF1PADDING" - + "|OAEPWITHSHA-1ANDMGF1PADDING" - + "|OAEPWITHSHA-224ANDMGF1PADDING" - + "|OAEPWITHSHA-256ANDMGF1PADDING" - + "|OAEPWITHSHA-384ANDMGF1PADDING" - + "|OAEPWITHSHA-512ANDMGF1PADDING" - + "|OAEPWITHSHA-512/224ANDMGF1PADDING" - + "|OAEPWITHSHA-512/256ANDMGF1PADDING"); - put("Cipher.RSA SupportedKeyClasses", - "java.security.interfaces.RSAPublicKey" + - "|java.security.interfaces.RSAPrivateKey"); + ps("Cipher", "RC2", + "com.sun.crypto.provider.RC2Cipher", null, attrs); - put("Cipher.DES", "com.sun.crypto.provider.DESCipher"); - put("Cipher.DES SupportedModes", BLOCK_MODES); - put("Cipher.DES SupportedPaddings", BLOCK_PADS); - put("Cipher.DES SupportedKeyFormats", "RAW"); + attrs.clear(); + attrs.put("SupportedModes", BLOCK_MODES128); + attrs.put("SupportedPaddings", BLOCK_PADS); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "AES", "com.sun.crypto.provider.AESCipher$General", + aesAliases, attrs); - put("Cipher.DESede", "com.sun.crypto.provider.DESedeCipher"); - put("Alg.Alias.Cipher.TripleDES", "DESede"); - put("Cipher.DESede SupportedModes", BLOCK_MODES); - put("Cipher.DESede SupportedPaddings", BLOCK_PADS); - put("Cipher.DESede SupportedKeyFormats", "RAW"); + attrs.clear(); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "AES_128/ECB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES128_ECB_NoPadding", + createAliasesWithOid(aes128Oid+"1"), attrs); + ps("Cipher", "AES_128/CBC/NoPadding", + "com.sun.crypto.provider.AESCipher$AES128_CBC_NoPadding", + createAliasesWithOid(aes128Oid+"2"), attrs); + ps("Cipher", "AES_128/OFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES128_OFB_NoPadding", + createAliasesWithOid(aes128Oid+"3"), attrs); + ps("Cipher", "AES_128/CFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES128_CFB_NoPadding", + createAliasesWithOid(aes128Oid+"4"), attrs); + ps("Cipher", "AES_128/GCM/NoPadding", + "com.sun.crypto.provider.AESCipher$AES128_GCM_NoPadding", + createAliasesWithOid(aes128Oid+"6"), attrs); - put("Cipher.DESedeWrap", - "com.sun.crypto.provider.DESedeWrapCipher"); - put("Cipher.DESedeWrap SupportedModes", "CBC"); - put("Cipher.DESedeWrap SupportedPaddings", "NOPADDING"); - put("Cipher.DESedeWrap SupportedKeyFormats", "RAW"); + ps("Cipher", "AES_192/ECB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES192_ECB_NoPadding", + createAliasesWithOid(aes192Oid+"1"), attrs); + ps("Cipher", "AES_192/CBC/NoPadding", + "com.sun.crypto.provider.AESCipher$AES192_CBC_NoPadding", + createAliasesWithOid(aes192Oid+"2"), attrs); + ps("Cipher", "AES_192/OFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES192_OFB_NoPadding", + createAliasesWithOid(aes192Oid+"3"), attrs); + ps("Cipher", "AES_192/CFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES192_CFB_NoPadding", + createAliasesWithOid(aes192Oid+"4"), attrs); + ps("Cipher", "AES_192/GCM/NoPadding", + "com.sun.crypto.provider.AESCipher$AES192_GCM_NoPadding", + createAliasesWithOid(aes192Oid+"6"), attrs); - // PBES1 + ps("Cipher", "AES_256/ECB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES256_ECB_NoPadding", + createAliasesWithOid(aes256Oid+"1"), attrs); + ps("Cipher", "AES_256/CBC/NoPadding", + "com.sun.crypto.provider.AESCipher$AES256_CBC_NoPadding", + createAliasesWithOid(aes256Oid+"2"), attrs); + ps("Cipher", "AES_256/OFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES256_OFB_NoPadding", + createAliasesWithOid(aes256Oid+"3"), attrs); + ps("Cipher", "AES_256/CFB/NoPadding", + "com.sun.crypto.provider.AESCipher$AES256_CFB_NoPadding", + createAliasesWithOid(aes256Oid+"4"), attrs); + ps("Cipher", "AES_256/GCM/NoPadding", + "com.sun.crypto.provider.AESCipher$AES256_GCM_NoPadding", + createAliasesWithOid(aes256Oid+"6"), attrs); - put("Cipher.PBEWithMD5AndDES", - "com.sun.crypto.provider.PBEWithMD5AndDESCipher"); - put("Alg.Alias.Cipher.OID."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); - put("Alg.Alias.Cipher."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); + attrs.clear(); + attrs.put("SupportedModes", "CBC"); + attrs.put("SupportedPaddings", "NOPADDING"); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "DESedeWrap", + "com.sun.crypto.provider.DESedeWrapCipher", null, attrs); - put("Cipher.PBEWithMD5AndTripleDES", - "com.sun.crypto.provider.PBEWithMD5AndTripleDESCipher"); + attrs.clear(); + attrs.put("SupportedModes", "ECB"); + attrs.put("SupportedPaddings", "NOPADDING"); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "ARCFOUR", "com.sun.crypto.provider.ARCFOURCipher", + arcFourAliases, attrs); + ps("Cipher", "AESWrap", "com.sun.crypto.provider.AESWrapCipher$General", + null, attrs); + ps("Cipher", "AESWrap_128", + "com.sun.crypto.provider.AESWrapCipher$AES128", + createAliasesWithOid(aes128Oid+"5"), attrs); + ps("Cipher", "AESWrap_192", + "com.sun.crypto.provider.AESWrapCipher$AES192", + createAliasesWithOid(aes192Oid+"5"), attrs); + ps("Cipher", "AESWrap_256", + "com.sun.crypto.provider.AESWrapCipher$AES256", + createAliasesWithOid(aes256Oid+"5"), attrs); - put("Cipher.PBEWithSHA1AndDESede", - "com.sun.crypto.provider.PKCS12PBECipherCore$" + - "PBEWithSHA1AndDESede"); - put("Alg.Alias.Cipher.OID." + OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); - put("Alg.Alias.Cipher." + OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); + attrs.clear(); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Cipher", "ChaCha20", + "com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Only", + null, attrs); + ps("Cipher", "ChaCha20-Poly1305", + "com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Poly1305", + chachaPolyAliases, attrs); - put("Cipher.PBEWithSHA1AndRC2_40", - "com.sun.crypto.provider.PKCS12PBECipherCore$" + - "PBEWithSHA1AndRC2_40"); - put("Alg.Alias.Cipher.OID." + OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); - put("Alg.Alias.Cipher." + OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); + // PBES1 + ps("Cipher", "PBEWithMD5AndDES", + "com.sun.crypto.provider.PBEWithMD5AndDESCipher", + pkcs5MD5_DESAliases, null); + ps("Cipher", "PBEWithMD5AndTripleDES", + "com.sun.crypto.provider.PBEWithMD5AndTripleDESCipher", + null, null); + ps("Cipher", "PBEWithSHA1AndDESede", + "com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndDESede", + pkcs12DESedeAliases, null); + ps("Cipher", "PBEWithSHA1AndRC2_40", + "com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC2_40", + pkcs12RC2_40Aliases, null); + ps("Cipher", "PBEWithSHA1AndRC2_128", + "com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC2_128", + pkcs12RC2_128Aliases, null); + ps("Cipher", "PBEWithSHA1AndRC4_40", + "com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC4_40", + pkcs12RC4_40Aliases, null); - put("Cipher.PBEWithSHA1AndRC2_128", - "com.sun.crypto.provider.PKCS12PBECipherCore$" + - "PBEWithSHA1AndRC2_128"); - put("Alg.Alias.Cipher.OID." + OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); - put("Alg.Alias.Cipher." + OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); + ps("Cipher", "PBEWithSHA1AndRC4_128", + "com.sun.crypto.provider.PKCS12PBECipherCore$PBEWithSHA1AndRC4_128", + pkcs12RC4_128Aliases, null); - put("Cipher.PBEWithSHA1AndRC4_40", - "com.sun.crypto.provider.PKCS12PBECipherCore$" + - "PBEWithSHA1AndRC4_40"); - put("Alg.Alias.Cipher.OID." + OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); - put("Alg.Alias.Cipher." + OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); + // PBES2 + ps("Cipher", "PBEWithHmacSHA1AndAES_128", + "com.sun.crypto.provider.PBES2Core$HmacSHA1AndAES_128", + null, null); - put("Cipher.PBEWithSHA1AndRC4_128", - "com.sun.crypto.provider.PKCS12PBECipherCore$" + - "PBEWithSHA1AndRC4_128"); - put("Alg.Alias.Cipher.OID." + OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); - put("Alg.Alias.Cipher." + OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); + ps("Cipher", "PBEWithHmacSHA224AndAES_128", + "com.sun.crypto.provider.PBES2Core$HmacSHA224AndAES_128", + null, null); - //PBES2 + ps("Cipher", "PBEWithHmacSHA256AndAES_128", + "com.sun.crypto.provider.PBES2Core$HmacSHA256AndAES_128", + null, null); - put("Cipher.PBEWithHmacSHA1AndAES_128", - "com.sun.crypto.provider.PBES2Core$HmacSHA1AndAES_128"); + ps("Cipher", "PBEWithHmacSHA384AndAES_128", + "com.sun.crypto.provider.PBES2Core$HmacSHA384AndAES_128", + null, null); - put("Cipher.PBEWithHmacSHA224AndAES_128", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA224AndAES_128"); + ps("Cipher", "PBEWithHmacSHA512AndAES_128", + "com.sun.crypto.provider.PBES2Core$HmacSHA512AndAES_128", + null, null); - put("Cipher.PBEWithHmacSHA256AndAES_128", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA256AndAES_128"); + ps("Cipher", "PBEWithHmacSHA1AndAES_256", + "com.sun.crypto.provider.PBES2Core$HmacSHA1AndAES_256", + null, null); - put("Cipher.PBEWithHmacSHA384AndAES_128", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA384AndAES_128"); + ps("Cipher", "PBEWithHmacSHA224AndAES_256", + "com.sun.crypto.provider.PBES2Core$HmacSHA224AndAES_256", + null, null); - put("Cipher.PBEWithHmacSHA512AndAES_128", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA512AndAES_128"); + ps("Cipher", "PBEWithHmacSHA256AndAES_256", + "com.sun.crypto.provider.PBES2Core$HmacSHA256AndAES_256", + null, null); - put("Cipher.PBEWithHmacSHA1AndAES_256", - "com.sun.crypto.provider.PBES2Core$HmacSHA1AndAES_256"); + ps("Cipher", "PBEWithHmacSHA384AndAES_256", + "com.sun.crypto.provider.PBES2Core$HmacSHA384AndAES_256", + null, null); - put("Cipher.PBEWithHmacSHA224AndAES_256", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA224AndAES_256"); + ps("Cipher", "PBEWithHmacSHA512AndAES_256", + "com.sun.crypto.provider.PBES2Core$HmacSHA512AndAES_256", + null, null); - put("Cipher.PBEWithHmacSHA256AndAES_256", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA256AndAES_256"); + /* + * Key(pair) Generator engines + */ + ps("KeyGenerator", "DES", + "com.sun.crypto.provider.DESKeyGenerator", + null, null); + ps("KeyGenerator", "DESede", + "com.sun.crypto.provider.DESedeKeyGenerator", + desEdeAliases, null); + ps("KeyGenerator", "Blowfish", + "com.sun.crypto.provider.BlowfishKeyGenerator", + null, null); + ps("KeyGenerator", "AES", + "com.sun.crypto.provider.AESKeyGenerator", + aesAliases, null); + ps("KeyGenerator", "RC2", + "com.sun.crypto.provider.KeyGeneratorCore$RC2KeyGenerator", + null, null); + ps("KeyGenerator", "ARCFOUR", + "com.sun.crypto.provider.KeyGeneratorCore$ARCFOURKeyGenerator", + arcFourAliases, null); + ps("KeyGenerator", "ChaCha20", + "com.sun.crypto.provider.KeyGeneratorCore$ChaCha20KeyGenerator", + null, null); + ps("KeyGenerator", "HmacMD5", + "com.sun.crypto.provider.HmacMD5KeyGenerator", + null, null); - put("Cipher.PBEWithHmacSHA384AndAES_256", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA384AndAES_256"); + ps("KeyGenerator", "HmacSHA1", + "com.sun.crypto.provider.HmacSHA1KeyGenerator", + macSHA1Aliases, null); + ps("KeyGenerator", "HmacSHA224", + "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA224", + macSHA224Aliases, null); + ps("KeyGenerator", "HmacSHA256", + "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA256", + macSHA256Aliases, null); + ps("KeyGenerator", "HmacSHA384", + "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA384", + macSHA384Aliases, null); + ps("KeyGenerator", "HmacSHA512", + "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA512", + macSHA512Aliases, null); - put("Cipher.PBEWithHmacSHA512AndAES_256", - "com.sun.crypto.provider.PBES2Core$" + - "HmacSHA512AndAES_256"); + ps("KeyPairGenerator", "DiffieHellman", + "com.sun.crypto.provider.DHKeyPairGenerator", + diffieHellmanAliases, null); - put("Cipher.Blowfish", - "com.sun.crypto.provider.BlowfishCipher"); - put("Cipher.Blowfish SupportedModes", BLOCK_MODES); - put("Cipher.Blowfish SupportedPaddings", BLOCK_PADS); - put("Cipher.Blowfish SupportedKeyFormats", "RAW"); + /* + * Algorithm parameter generation engines + */ + ps("AlgorithmParameterGenerator", + "DiffieHellman", "com.sun.crypto.provider.DHParameterGenerator", + diffieHellmanAliases, null); - put("Cipher.AES", "com.sun.crypto.provider.AESCipher$General"); - put("Alg.Alias.Cipher.Rijndael", "AES"); - put("Cipher.AES SupportedModes", BLOCK_MODES128); - put("Cipher.AES SupportedPaddings", BLOCK_PADS); - put("Cipher.AES SupportedKeyFormats", "RAW"); - - put("Cipher.AES_128/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_ECB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.1", "AES_128/ECB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.1", "AES_128/ECB/NoPadding"); - put("Cipher.AES_128/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_CBC_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.2", "AES_128/CBC/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.2", "AES_128/CBC/NoPadding"); - put("Cipher.AES_128/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_OFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.3", "AES_128/OFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.3", "AES_128/OFB/NoPadding"); - put("Cipher.AES_128/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_CFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding"); - put("Cipher.AES_128/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_GCM_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.6", "AES_128/GCM/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.6", "AES_128/GCM/NoPadding"); - - put("Cipher.AES_192/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_ECB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.21", "AES_192/ECB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.21", "AES_192/ECB/NoPadding"); - put("Cipher.AES_192/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_CBC_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.22", "AES_192/CBC/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.22", "AES_192/CBC/NoPadding"); - put("Cipher.AES_192/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_OFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.23", "AES_192/OFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.23", "AES_192/OFB/NoPadding"); - put("Cipher.AES_192/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_CFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding"); - put("Cipher.AES_192/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_GCM_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.26", "AES_192/GCM/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.26", "AES_192/GCM/NoPadding"); - - put("Cipher.AES_256/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_ECB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.41", "AES_256/ECB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.41", "AES_256/ECB/NoPadding"); - put("Cipher.AES_256/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_CBC_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.42", "AES_256/CBC/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.42", "AES_256/CBC/NoPadding"); - put("Cipher.AES_256/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_OFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.43", "AES_256/OFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.43", "AES_256/OFB/NoPadding"); - put("Cipher.AES_256/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_CFB_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding"); - put("Cipher.AES_256/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_GCM_NoPadding"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.46", "AES_256/GCM/NoPadding"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.46", "AES_256/GCM/NoPadding"); - - put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher$General"); - put("Cipher.AESWrap SupportedModes", "ECB"); - put("Cipher.AESWrap SupportedPaddings", "NOPADDING"); - put("Cipher.AESWrap SupportedKeyFormats", "RAW"); - - put("Cipher.AESWrap_128", "com.sun.crypto.provider.AESWrapCipher$AES128"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.5", "AESWrap_128"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.5", "AESWrap_128"); - put("Cipher.AESWrap_192", "com.sun.crypto.provider.AESWrapCipher$AES192"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.25", "AESWrap_192"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.25", "AESWrap_192"); - put("Cipher.AESWrap_256", "com.sun.crypto.provider.AESWrapCipher$AES256"); - put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.45", "AESWrap_256"); - put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.45", "AESWrap_256"); - - put("Cipher.RC2", - "com.sun.crypto.provider.RC2Cipher"); - put("Cipher.RC2 SupportedModes", BLOCK_MODES); - put("Cipher.RC2 SupportedPaddings", BLOCK_PADS); - put("Cipher.RC2 SupportedKeyFormats", "RAW"); - - put("Cipher.ARCFOUR", - "com.sun.crypto.provider.ARCFOURCipher"); - put("Alg.Alias.Cipher.RC4", "ARCFOUR"); - put("Cipher.ARCFOUR SupportedModes", "ECB"); - put("Cipher.ARCFOUR SupportedPaddings", "NOPADDING"); - put("Cipher.ARCFOUR SupportedKeyFormats", "RAW"); - - put("Cipher.ChaCha20", - "com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Only"); - put("Cipher.ChaCha20 SupportedKeyFormats", "RAW"); - put("Cipher.ChaCha20-Poly1305", - "com.sun.crypto.provider.ChaCha20Cipher$ChaCha20Poly1305"); - put("Cipher.ChaCha20-Poly1305 SupportedKeyFormats", "RAW"); - put("Alg.Alias.Cipher.1.2.840.113549.1.9.16.3.18", "ChaCha20-Poly1305"); - put("Alg.Alias.Cipher.OID.1.2.840.113549.1.9.16.3.18", "ChaCha20-Poly1305"); - - /* - * Key(pair) Generator engines - */ - put("KeyGenerator.DES", - "com.sun.crypto.provider.DESKeyGenerator"); - - put("KeyGenerator.DESede", - "com.sun.crypto.provider.DESedeKeyGenerator"); - put("Alg.Alias.KeyGenerator.TripleDES", "DESede"); - - put("KeyGenerator.Blowfish", - "com.sun.crypto.provider.BlowfishKeyGenerator"); - - put("KeyGenerator.AES", - "com.sun.crypto.provider.AESKeyGenerator"); - put("Alg.Alias.KeyGenerator.Rijndael", "AES"); - - put("KeyGenerator.RC2", - "com.sun.crypto.provider.KeyGeneratorCore$" + - "RC2KeyGenerator"); - put("KeyGenerator.ARCFOUR", - "com.sun.crypto.provider.KeyGeneratorCore$" + - "ARCFOURKeyGenerator"); - put("Alg.Alias.KeyGenerator.RC4", "ARCFOUR"); - - put("KeyGenerator.ChaCha20", - "com.sun.crypto.provider.KeyGeneratorCore$" + - "ChaCha20KeyGenerator"); - - put("KeyGenerator.HmacMD5", - "com.sun.crypto.provider.HmacMD5KeyGenerator"); - - put("KeyGenerator.HmacSHA1", - "com.sun.crypto.provider.HmacSHA1KeyGenerator"); - put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.7", "HmacSHA1"); - put("Alg.Alias.KeyGenerator.1.2.840.113549.2.7", "HmacSHA1"); - - put("KeyGenerator.HmacSHA224", - "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA224"); - put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.8", "HmacSHA224"); - put("Alg.Alias.KeyGenerator.1.2.840.113549.2.8", "HmacSHA224"); - - put("KeyGenerator.HmacSHA256", - "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA256"); - put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.9", "HmacSHA256"); - put("Alg.Alias.KeyGenerator.1.2.840.113549.2.9", "HmacSHA256"); - - put("KeyGenerator.HmacSHA384", - "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA384"); - put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.10", "HmacSHA384"); - put("Alg.Alias.KeyGenerator.1.2.840.113549.2.10", "HmacSHA384"); - - put("KeyGenerator.HmacSHA512", - "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA512"); - put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.11", "HmacSHA512"); - put("Alg.Alias.KeyGenerator.1.2.840.113549.2.11", "HmacSHA512"); - - put("KeyPairGenerator.DiffieHellman", - "com.sun.crypto.provider.DHKeyPairGenerator"); - put("Alg.Alias.KeyPairGenerator.DH", "DiffieHellman"); - put("Alg.Alias.KeyPairGenerator.OID."+OID_PKCS3, - "DiffieHellman"); - put("Alg.Alias.KeyPairGenerator."+OID_PKCS3, - "DiffieHellman"); - - /* - * Algorithm parameter generation engines - */ - put("AlgorithmParameterGenerator.DiffieHellman", - "com.sun.crypto.provider.DHParameterGenerator"); - put("Alg.Alias.AlgorithmParameterGenerator.DH", - "DiffieHellman"); - put("Alg.Alias.AlgorithmParameterGenerator.OID."+OID_PKCS3, - "DiffieHellman"); - put("Alg.Alias.AlgorithmParameterGenerator."+OID_PKCS3, - "DiffieHellman"); - - /* - * Key Agreement engines - */ - put("KeyAgreement.DiffieHellman", - "com.sun.crypto.provider.DHKeyAgreement"); - put("Alg.Alias.KeyAgreement.DH", "DiffieHellman"); - put("Alg.Alias.KeyAgreement.OID."+OID_PKCS3, "DiffieHellman"); - put("Alg.Alias.KeyAgreement."+OID_PKCS3, "DiffieHellman"); - - put("KeyAgreement.DiffieHellman SupportedKeyClasses", - "javax.crypto.interfaces.DHPublicKey" + + /* + * Key Agreement engines + */ + attrs.clear(); + attrs.put("SupportedKeyClasses", "javax.crypto.interfaces.DHPublicKey" + "|javax.crypto.interfaces.DHPrivateKey"); + ps("KeyAgreement", "DiffieHellman", + "com.sun.crypto.provider.DHKeyAgreement", + diffieHellmanAliases, attrs); + + /* + * Algorithm Parameter engines + */ + ps("AlgorithmParameters", "DiffieHellman", + "com.sun.crypto.provider.DHParameters", + diffieHellmanAliases, null); - /* - * Algorithm Parameter engines - */ - put("AlgorithmParameters.DiffieHellman", - "com.sun.crypto.provider.DHParameters"); - put("Alg.Alias.AlgorithmParameters.DH", "DiffieHellman"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS3, - "DiffieHellman"); - put("Alg.Alias.AlgorithmParameters."+OID_PKCS3, - "DiffieHellman"); - - put("AlgorithmParameters.DES", - "com.sun.crypto.provider.DESParameters"); - - put("AlgorithmParameters.DESede", - "com.sun.crypto.provider.DESedeParameters"); - put("Alg.Alias.AlgorithmParameters.TripleDES", "DESede"); - - put("AlgorithmParameters.PBE", - "com.sun.crypto.provider.PBEParameters"); - - put("AlgorithmParameters.PBEWithMD5AndDES", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); - put("Alg.Alias.AlgorithmParameters."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); - - put("AlgorithmParameters.PBEWithMD5AndTripleDES", - "com.sun.crypto.provider.PBEParameters"); - - put("AlgorithmParameters.PBEWithSHA1AndDESede", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); - put("Alg.Alias.AlgorithmParameters."+OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); - - put("AlgorithmParameters.PBEWithSHA1AndRC2_40", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); - put("Alg.Alias.AlgorithmParameters." + OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); - - put("AlgorithmParameters.PBEWithSHA1AndRC2_128", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); - put("Alg.Alias.AlgorithmParameters." + OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); - - put("AlgorithmParameters.PBEWithSHA1AndRC4_40", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); - put("Alg.Alias.AlgorithmParameters." + OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); - - put("AlgorithmParameters.PBEWithSHA1AndRC4_128", - "com.sun.crypto.provider.PBEParameters"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); - put("Alg.Alias.AlgorithmParameters." + OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); - - put("AlgorithmParameters.PBES2", - "com.sun.crypto.provider.PBES2Parameters$General"); - put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS5_PBES2, - "PBES2"); - put("Alg.Alias.AlgorithmParameters." + OID_PKCS5_PBES2, - "PBES2"); - - put("AlgorithmParameters.PBEWithHmacSHA1AndAES_128", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA1AndAES_128"); - - put("AlgorithmParameters.PBEWithHmacSHA224AndAES_128", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA224AndAES_128"); - - put("AlgorithmParameters.PBEWithHmacSHA256AndAES_128", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA256AndAES_128"); - - put("AlgorithmParameters.PBEWithHmacSHA384AndAES_128", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA384AndAES_128"); - - put("AlgorithmParameters.PBEWithHmacSHA512AndAES_128", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA512AndAES_128"); - - put("AlgorithmParameters.PBEWithHmacSHA1AndAES_256", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA1AndAES_256"); - - put("AlgorithmParameters.PBEWithHmacSHA224AndAES_256", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA224AndAES_256"); - - put("AlgorithmParameters.PBEWithHmacSHA256AndAES_256", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA256AndAES_256"); - - put("AlgorithmParameters.PBEWithHmacSHA384AndAES_256", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA384AndAES_256"); - - put("AlgorithmParameters.PBEWithHmacSHA512AndAES_256", - "com.sun.crypto.provider.PBES2Parameters$HmacSHA512AndAES_256"); - - put("AlgorithmParameters.Blowfish", - "com.sun.crypto.provider.BlowfishParameters"); - - put("AlgorithmParameters.AES", - "com.sun.crypto.provider.AESParameters"); - put("Alg.Alias.AlgorithmParameters.Rijndael", "AES"); - put("AlgorithmParameters.GCM", - "com.sun.crypto.provider.GCMParameters"); - - - put("AlgorithmParameters.RC2", - "com.sun.crypto.provider.RC2Parameters"); - - put("AlgorithmParameters.OAEP", - "com.sun.crypto.provider.OAEPParameters"); - - put("AlgorithmParameters.ChaCha20-Poly1305", - "com.sun.crypto.provider.ChaCha20Poly1305Parameters"); - - /* - * Key factories - */ - put("KeyFactory.DiffieHellman", - "com.sun.crypto.provider.DHKeyFactory"); - put("Alg.Alias.KeyFactory.DH", "DiffieHellman"); - put("Alg.Alias.KeyFactory.OID."+OID_PKCS3, - "DiffieHellman"); - put("Alg.Alias.KeyFactory."+OID_PKCS3, "DiffieHellman"); - - /* - * Secret-key factories - */ - put("SecretKeyFactory.DES", - "com.sun.crypto.provider.DESKeyFactory"); - - put("SecretKeyFactory.DESede", - "com.sun.crypto.provider.DESedeKeyFactory"); - put("Alg.Alias.SecretKeyFactory.TripleDES", "DESede"); - - put("SecretKeyFactory.PBEWithMD5AndDES", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithMD5AndDES" - ); - put("Alg.Alias.SecretKeyFactory.OID."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); - put("Alg.Alias.SecretKeyFactory."+OID_PKCS5_MD5_DES, - "PBEWithMD5AndDES"); - - put("Alg.Alias.SecretKeyFactory.PBE", - "PBEWithMD5AndDES"); - - /* - * Internal in-house crypto algorithm used for - * the JCEKS keystore type. Since this was developed - * internally, there isn't an OID corresponding to this - * algorithm. - */ - put("SecretKeyFactory.PBEWithMD5AndTripleDES", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithMD5AndTripleDES" - ); - - put("SecretKeyFactory.PBEWithSHA1AndDESede", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndDESede" - ); - put("Alg.Alias.SecretKeyFactory.OID."+OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS12_DESede, - "PBEWithSHA1AndDESede"); - - put("SecretKeyFactory.PBEWithSHA1AndRC2_40", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC2_40" - ); - put("Alg.Alias.SecretKeyFactory.OID." + OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS12_RC2_40, - "PBEWithSHA1AndRC2_40"); - - put("SecretKeyFactory.PBEWithSHA1AndRC2_128", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC2_128" - ); - put("Alg.Alias.SecretKeyFactory.OID." + OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS12_RC2_128, - "PBEWithSHA1AndRC2_128"); - - put("SecretKeyFactory.PBEWithSHA1AndRC4_40", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC4_40" - ); - - put("Alg.Alias.SecretKeyFactory.OID." + OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS12_RC4_40, - "PBEWithSHA1AndRC4_40"); - - put("SecretKeyFactory.PBEWithSHA1AndRC4_128", - "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC4_128" - ); - - put("Alg.Alias.SecretKeyFactory.OID." + OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS12_RC4_128, - "PBEWithSHA1AndRC4_128"); - - put("SecretKeyFactory.PBEWithHmacSHA1AndAES_128", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA1AndAES_128"); - - put("SecretKeyFactory.PBEWithHmacSHA224AndAES_128", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA224AndAES_128"); - - put("SecretKeyFactory.PBEWithHmacSHA256AndAES_128", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA256AndAES_128"); - - put("SecretKeyFactory.PBEWithHmacSHA384AndAES_128", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA384AndAES_128"); - - put("SecretKeyFactory.PBEWithHmacSHA512AndAES_128", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA512AndAES_128"); - - put("SecretKeyFactory.PBEWithHmacSHA1AndAES_256", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA1AndAES_256"); - - put("SecretKeyFactory.PBEWithHmacSHA224AndAES_256", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA224AndAES_256"); - - put("SecretKeyFactory.PBEWithHmacSHA256AndAES_256", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA256AndAES_256"); - - put("SecretKeyFactory.PBEWithHmacSHA384AndAES_256", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA384AndAES_256"); - - put("SecretKeyFactory.PBEWithHmacSHA512AndAES_256", - "com.sun.crypto.provider.PBEKeyFactory$" + - "PBEWithHmacSHA512AndAES_256"); - - // PBKDF2 - - put("SecretKeyFactory.PBKDF2WithHmacSHA1", - "com.sun.crypto.provider.PBKDF2Core$HmacSHA1"); - put("Alg.Alias.SecretKeyFactory.OID." + OID_PKCS5_PBKDF2, - "PBKDF2WithHmacSHA1"); - put("Alg.Alias.SecretKeyFactory." + OID_PKCS5_PBKDF2, - "PBKDF2WithHmacSHA1"); - - put("SecretKeyFactory.PBKDF2WithHmacSHA224", - "com.sun.crypto.provider.PBKDF2Core$HmacSHA224"); - put("SecretKeyFactory.PBKDF2WithHmacSHA256", - "com.sun.crypto.provider.PBKDF2Core$HmacSHA256"); - put("SecretKeyFactory.PBKDF2WithHmacSHA384", - "com.sun.crypto.provider.PBKDF2Core$HmacSHA384"); - put("SecretKeyFactory.PBKDF2WithHmacSHA512", - "com.sun.crypto.provider.PBKDF2Core$HmacSHA512"); - - /* - * MAC - */ - put("Mac.HmacMD5", "com.sun.crypto.provider.HmacMD5"); - put("Mac.HmacSHA1", "com.sun.crypto.provider.HmacSHA1"); - put("Alg.Alias.Mac.OID.1.2.840.113549.2.7", "HmacSHA1"); - put("Alg.Alias.Mac.1.2.840.113549.2.7", "HmacSHA1"); - put("Mac.HmacSHA224", - "com.sun.crypto.provider.HmacCore$HmacSHA224"); - put("Alg.Alias.Mac.OID.1.2.840.113549.2.8", "HmacSHA224"); - put("Alg.Alias.Mac.1.2.840.113549.2.8", "HmacSHA224"); - put("Mac.HmacSHA256", - "com.sun.crypto.provider.HmacCore$HmacSHA256"); - put("Alg.Alias.Mac.OID.1.2.840.113549.2.9", "HmacSHA256"); - put("Alg.Alias.Mac.1.2.840.113549.2.9", "HmacSHA256"); - put("Mac.HmacSHA384", - "com.sun.crypto.provider.HmacCore$HmacSHA384"); - put("Alg.Alias.Mac.OID.1.2.840.113549.2.10", "HmacSHA384"); - put("Alg.Alias.Mac.1.2.840.113549.2.10", "HmacSHA384"); - put("Mac.HmacSHA512", - "com.sun.crypto.provider.HmacCore$HmacSHA512"); - put("Alg.Alias.Mac.OID.1.2.840.113549.2.11", "HmacSHA512"); - put("Alg.Alias.Mac.1.2.840.113549.2.11", "HmacSHA512"); - - // TODO: aliases with OIDs - put("Mac.HmacSHA512/224", - "com.sun.crypto.provider.HmacCore$HmacSHA512_224"); - put("Mac.HmacSHA512/256", - "com.sun.crypto.provider.HmacCore$HmacSHA512_256"); - - put("Mac.HmacPBESHA1", - "com.sun.crypto.provider.HmacPKCS12PBESHA1"); - - // PBMAC1 - - put("Mac.PBEWithHmacSHA1", - "com.sun.crypto.provider.PBMAC1Core$HmacSHA1"); - put("Mac.PBEWithHmacSHA224", - "com.sun.crypto.provider.PBMAC1Core$HmacSHA224"); - put("Mac.PBEWithHmacSHA256", - "com.sun.crypto.provider.PBMAC1Core$HmacSHA256"); - put("Mac.PBEWithHmacSHA384", - "com.sun.crypto.provider.PBMAC1Core$HmacSHA384"); - put("Mac.PBEWithHmacSHA512", - "com.sun.crypto.provider.PBMAC1Core$HmacSHA512"); - - put("Mac.SslMacMD5", - "com.sun.crypto.provider.SslMacCore$SslMacMD5"); - put("Mac.SslMacSHA1", - "com.sun.crypto.provider.SslMacCore$SslMacSHA1"); - - put("Mac.HmacMD5 SupportedKeyFormats", "RAW"); - put("Mac.HmacSHA1 SupportedKeyFormats", "RAW"); - put("Mac.HmacSHA224 SupportedKeyFormats", "RAW"); - put("Mac.HmacSHA256 SupportedKeyFormats", "RAW"); - put("Mac.HmacSHA384 SupportedKeyFormats", "RAW"); - put("Mac.HmacSHA512 SupportedKeyFormats", "RAW"); - put("Mac.HmacPBESHA1 SupportedKeyFormats", "RAW"); - put("Mac.PBEWithHmacSHA1 SupportedKeyFormatS", "RAW"); - put("Mac.PBEWithHmacSHA224 SupportedKeyFormats", "RAW"); - put("Mac.PBEWithHmacSHA256 SupportedKeyFormats", "RAW"); - put("Mac.PBEWithHmacSHA384 SupportedKeyFormats", "RAW"); - put("Mac.PBEWithHmacSHA512 SupportedKeyFormats", "RAW"); - put("Mac.SslMacMD5 SupportedKeyFormats", "RAW"); - put("Mac.SslMacSHA1 SupportedKeyFormats", "RAW"); - - /* - * KeyStore - */ - put("KeyStore.JCEKS", "com.sun.crypto.provider.JceKeyStore"); - - /* - * SSL/TLS mechanisms - * - * These are strictly internal implementations and may - * be changed at any time. These names were chosen - * because PKCS11/SunPKCS11 does not yet have TLS1.2 - * mechanisms, and it will cause calls to come here. - */ - put("KeyGenerator.SunTlsPrf", - "com.sun.crypto.provider.TlsPrfGenerator$V10"); - put("KeyGenerator.SunTls12Prf", - "com.sun.crypto.provider.TlsPrfGenerator$V12"); - - put("KeyGenerator.SunTlsMasterSecret", - "com.sun.crypto.provider.TlsMasterSecretGenerator"); - put("Alg.Alias.KeyGenerator.SunTls12MasterSecret", - "SunTlsMasterSecret"); - put("Alg.Alias.KeyGenerator.SunTlsExtendedMasterSecret", - "SunTlsMasterSecret"); - - put("KeyGenerator.SunTlsKeyMaterial", - "com.sun.crypto.provider.TlsKeyMaterialGenerator"); - put("Alg.Alias.KeyGenerator.SunTls12KeyMaterial", - "SunTlsKeyMaterial"); - - put("KeyGenerator.SunTlsRsaPremasterSecret", - "com.sun.crypto.provider.TlsRsaPremasterSecretGenerator"); - put("Alg.Alias.KeyGenerator.SunTls12RsaPremasterSecret", - "SunTlsRsaPremasterSecret"); - - return null; - } - }); - - if (instance == null) { - instance = this; - } + ps("AlgorithmParameters", "DES", + "com.sun.crypto.provider.DESParameters", + null, null); + + ps("AlgorithmParameters", "DESede", + "com.sun.crypto.provider.DESedeParameters", + desEdeAliases, null); + + ps("AlgorithmParameters", "PBEWithMD5AndDES", + "com.sun.crypto.provider.PBEParameters", + pkcs5MD5_DESAliases, null); + + ps("AlgorithmParameters", "PBEWithMD5AndTripleDES", + "com.sun.crypto.provider.PBEParameters", + null, null); + + ps("AlgorithmParameters", "PBEWithSHA1AndDESede", + "com.sun.crypto.provider.PBEParameters", + pkcs12DESedeAliases, null); + + ps("AlgorithmParameters", "PBEWithSHA1AndRC2_40", + "com.sun.crypto.provider.PBEParameters", + pkcs12RC2_40Aliases, null); + + ps("AlgorithmParameters", "PBEWithSHA1AndRC2_128", + "com.sun.crypto.provider.PBEParameters", + pkcs12RC2_128Aliases, null); + + ps("AlgorithmParameters", "PBEWithSHA1AndRC4_40", + "com.sun.crypto.provider.PBEParameters", + pkcs12RC4_40Aliases, null); + + ps("AlgorithmParameters", "PBEWithSHA1AndRC4_128", + "com.sun.crypto.provider.PBEParameters", + pkcs12RC4_128Aliases, null); + + ps("AlgorithmParameters", "PBES2", + "com.sun.crypto.provider.PBES2Parameters$General", + pkcs5PBES2Aliases, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA1AndAES_128", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA1AndAES_128", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA224AndAES_128", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA224AndAES_128", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA256AndAES_128", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA256AndAES_128", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA384AndAES_128", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA384AndAES_128", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA512AndAES_128", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA512AndAES_128", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA1AndAES_256", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA1AndAES_256", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA224AndAES_256", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA224AndAES_256", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA256AndAES_256", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA256AndAES_256", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA384AndAES_256", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA384AndAES_256", + null, null); + + ps("AlgorithmParameters", "PBEWithHmacSHA512AndAES_256", + "com.sun.crypto.provider.PBES2Parameters$HmacSHA512AndAES_256", + null, null); + + ps("AlgorithmParameters", "Blowfish", + "com.sun.crypto.provider.BlowfishParameters", + null, null); + + ps("AlgorithmParameters", "AES", + "com.sun.crypto.provider.AESParameters", + aesAliases, null); + + ps("AlgorithmParameters", "GCM", + "com.sun.crypto.provider.GCMParameters", + null, null); + + ps("AlgorithmParameters", "RC2", + "com.sun.crypto.provider.RC2Parameters", + null, null); + + ps("AlgorithmParameters", "OAEP", + "com.sun.crypto.provider.OAEPParameters", + null, null); + + ps("AlgorithmParameters", "ChaCha20-Poly1305", + "com.sun.crypto.provider.ChaCha20Poly1305Parameters", + chachaPolyAliases, null); + + /* + * Key factories + */ + ps("KeyFactory", "DiffieHellman", + "com.sun.crypto.provider.DHKeyFactory", + diffieHellmanAliases, null); + + /* + * Secret-key factories + */ + ps("SecretKeyFactory", "DES", + "com.sun.crypto.provider.DESKeyFactory", + null, null); + + ps("SecretKeyFactory", "DESede", + "com.sun.crypto.provider.DESedeKeyFactory", + desEdeAliases, null); + + ps("SecretKeyFactory", "PBEWithMD5AndDES", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithMD5AndDES", + pkcs5MD5_DESAliases, null); + + /* + * Internal in-house crypto algorithm used for + * the JCEKS keystore type. Since this was developed + * internally, there isn't an OID corresponding to this + * algorithm. + */ + ps("SecretKeyFactory", "PBEWithMD5AndTripleDES", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithMD5AndTripleDES", + null, null); + + ps("SecretKeyFactory", "PBEWithSHA1AndDESede", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndDESede", + pkcs12DESedeAliases, null); + + ps("SecretKeyFactory", "PBEWithSHA1AndRC2_40", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC2_40", + pkcs12RC2_40Aliases, null); + + ps("SecretKeyFactory", "PBEWithSHA1AndRC2_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC2_128", + pkcs12RC2_128Aliases, null); + + ps("SecretKeyFactory", "PBEWithSHA1AndRC4_40", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC4_40", + pkcs12RC4_40Aliases,null); + + ps("SecretKeyFactory", "PBEWithSHA1AndRC4_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithSHA1AndRC4_128", + pkcs12RC4_128Aliases, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA1AndAES_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA1AndAES_128", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA224AndAES_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA224AndAES_128", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA256AndAES_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA256AndAES_128", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA384AndAES_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA384AndAES_128", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA512AndAES_128", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA512AndAES_128", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA1AndAES_256", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA1AndAES_256", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA224AndAES_256", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA224AndAES_256", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA256AndAES_256", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA256AndAES_256", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA384AndAES_256", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA384AndAES_256", + null, null); + + ps("SecretKeyFactory", "PBEWithHmacSHA512AndAES_256", + "com.sun.crypto.provider.PBEKeyFactory$PBEWithHmacSHA512AndAES_256", + null, null); + + // PBKDF2 + ps("SecretKeyFactory", "PBKDF2WithHmacSHA1", + "com.sun.crypto.provider.PBKDF2Core$HmacSHA1", + pkcs5PBKDF2Aliases, null); + ps("SecretKeyFactory", "PBKDF2WithHmacSHA224", + "com.sun.crypto.provider.PBKDF2Core$HmacSHA224", + null, null); + ps("SecretKeyFactory", "PBKDF2WithHmacSHA256", + "com.sun.crypto.provider.PBKDF2Core$HmacSHA256", + null, null); + ps("SecretKeyFactory", "PBKDF2WithHmacSHA384", + "com.sun.crypto.provider.PBKDF2Core$HmacSHA384", + null, null); + ps("SecretKeyFactory", "PBKDF2WithHmacSHA512", + "com.sun.crypto.provider.PBKDF2Core$HmacSHA512", + null, null); + + /* + * MAC + */ + attrs.clear(); + attrs.put("SupportedKeyFormats", "RAW"); + ps("Mac", "HmacMD5", "com.sun.crypto.provider.HmacMD5", null, attrs); + ps("Mac", "HmacSHA1", "com.sun.crypto.provider.HmacSHA1", + macSHA1Aliases, attrs); + ps("Mac", "HmacSHA224", "com.sun.crypto.provider.HmacCore$HmacSHA224", + macSHA224Aliases, attrs); + ps("Mac", "HmacSHA256", "com.sun.crypto.provider.HmacCore$HmacSHA256", + macSHA256Aliases, attrs); + ps("Mac", "HmacSHA384", "com.sun.crypto.provider.HmacCore$HmacSHA384", + macSHA384Aliases, attrs); + ps("Mac", "HmacSHA512", "com.sun.crypto.provider.HmacCore$HmacSHA512", + macSHA512Aliases, attrs); + // TODO: aliases with OIDs + ps("Mac", "HmacSHA512/224", + "com.sun.crypto.provider.HmacCore$HmacSHA512_224", + null, attrs); + ps("Mac", "HmacSHA512/256", + "com.sun.crypto.provider.HmacCore$HmacSHA512_256", + null, attrs); + ps("Mac", "HmacPBESHA1", "com.sun.crypto.provider.HmacPKCS12PBESHA1", + null, attrs); + // PBMAC1 + ps("Mac", "PBEWithHmacSHA1", + "com.sun.crypto.provider.PBMAC1Core$HmacSHA1", null, attrs); + ps("Mac", "PBEWithHmacSHA224", + "com.sun.crypto.provider.PBMAC1Core$HmacSHA224", null, attrs); + ps("Mac", "PBEWithHmacSHA256", + "com.sun.crypto.provider.PBMAC1Core$HmacSHA256", null, attrs); + ps("Mac", "PBEWithHmacSHA384", + "com.sun.crypto.provider.PBMAC1Core$HmacSHA384", null, attrs); + ps("Mac", "PBEWithHmacSHA512", + "com.sun.crypto.provider.PBMAC1Core$HmacSHA512", null, attrs); + ps("Mac", "SslMacMD5", + "com.sun.crypto.provider.SslMacCore$SslMacMD5", null, attrs); + ps("Mac", "SslMacSHA1", + "com.sun.crypto.provider.SslMacCore$SslMacSHA1", null, attrs); + + /* + * KeyStore + */ + ps("KeyStore", "JCEKS", + "com.sun.crypto.provider.JceKeyStore", + null, null); + + /* + * SSL/TLS mechanisms + * + * These are strictly internal implementations and may + * be changed at any time. These names were chosen + * because PKCS11/SunPKCS11 does not yet have TLS1.2 + * mechanisms, and it will cause calls to come here. + */ + ps("KeyGenerator", "SunTlsPrf", + "com.sun.crypto.provider.TlsPrfGenerator$V10", + null, null); + ps("KeyGenerator", "SunTls12Prf", + "com.sun.crypto.provider.TlsPrfGenerator$V12", + null, null); + + ps("KeyGenerator", "SunTlsMasterSecret", + "com.sun.crypto.provider.TlsMasterSecretGenerator", + createAliases("SunTls12MasterSecret", + "SunTlsExtendedMasterSecret"), null); + + ps("KeyGenerator", "SunTlsKeyMaterial", + "com.sun.crypto.provider.TlsKeyMaterialGenerator", + createAliases("SunTls12KeyMaterial"), null); + + ps("KeyGenerator", "SunTlsRsaPremasterSecret", + "com.sun.crypto.provider.TlsRsaPremasterSecretGenerator", + createAliases("SunTls12RsaPremasterSecret"), null); } // Return the instance of this class or create one if needed. diff --git a/src/java.base/share/classes/java/security/Provider.java b/src/java.base/share/classes/java/security/Provider.java index 324de1bf9a4..3ebd72104ee 100644 --- a/src/java.base/share/classes/java/security/Provider.java +++ b/src/java.base/share/classes/java/security/Provider.java @@ -33,6 +33,7 @@ import java.lang.reflect.*; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; +import java.util.concurrent.ConcurrentHashMap; /** * This class represents a "provider" for the @@ -225,6 +226,7 @@ public abstract class Provider extends Properties { this.version = version; this.versionStr = Double.toString(version); this.info = info; + this.serviceMap = new ConcurrentHashMap<>(); putId(); initialized = true; } @@ -262,6 +264,7 @@ public abstract class Provider extends Properties { this.versionStr = versionStr; this.version = parseVersionStr(versionStr); this.info = info; + this.serviceMap = new ConcurrentHashMap<>(); putId(); initialized = true; } @@ -852,10 +855,7 @@ public abstract class Provider extends Properties { // legacy properties changed since last call to any services method? private transient boolean legacyChanged; // serviceMap changed since last call to getServices() - private transient boolean servicesChanged; - - // Map - private transient Map legacyStrings; + private volatile transient boolean servicesChanged; // Map // used for services added via putService(), initialized on demand @@ -905,22 +905,18 @@ public abstract class Provider extends Properties { // otherwise, set version based on versionStr this.version = parseVersionStr(this.versionStr); } + this.serviceMap = new ConcurrentHashMap<>(); implClear(); initialized = true; putAll(copy); } - private boolean checkLegacy(Object key) { + private static boolean isProviderInfo(Object key) { String keyString = (String)key; if (keyString.startsWith("Provider.")) { - return false; + return true; } - - legacyChanged = true; - if (legacyStrings == null) { - legacyStrings = new LinkedHashMap<>(); - } - return true; + return false; } /** @@ -936,20 +932,20 @@ public abstract class Provider extends Properties { private Object implRemove(Object key) { if (key instanceof String) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.remove((String)key); + legacyChanged = true; } return super.remove(key); } private boolean implRemove(Object key, Object value) { if (key instanceof String && value instanceof String) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return false; } - legacyStrings.remove((String)key, value); + legacyChanged = true; } return super.remove(key, value); } @@ -957,21 +953,20 @@ public abstract class Provider extends Properties { private boolean implReplace(Object key, Object oldValue, Object newValue) { if ((key instanceof String) && (oldValue instanceof String) && (newValue instanceof String)) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return false; } - legacyStrings.replace((String)key, (String)oldValue, - (String)newValue); + legacyChanged = true; } return super.replace(key, oldValue, newValue); } private Object implReplace(Object key, Object value) { if ((key instanceof String) && (value instanceof String)) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.replace((String)key, (String)value); + legacyChanged = true; } return super.replace(key, value); } @@ -980,12 +975,6 @@ public abstract class Provider extends Properties { private void implReplaceAll(BiFunction function) { legacyChanged = true; - if (legacyStrings == null) { - legacyStrings = new LinkedHashMap<>(); - } else { - legacyStrings.replaceAll((BiFunction) function); - } super.replaceAll(function); } @@ -993,11 +982,10 @@ public abstract class Provider extends Properties { private Object implMerge(Object key, Object value, BiFunction remappingFunction) { if ((key instanceof String) && (value instanceof String)) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.merge((String)key, (String)value, - (BiFunction) remappingFunction); + legacyChanged = true; } return super.merge(key, value, remappingFunction); } @@ -1006,11 +994,10 @@ public abstract class Provider extends Properties { private Object implCompute(Object key, BiFunction remappingFunction) { if (key instanceof String) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.compute((String) key, - (BiFunction) remappingFunction); + legacyChanged = true; } return super.compute(key, remappingFunction); } @@ -1019,11 +1006,10 @@ public abstract class Provider extends Properties { private Object implComputeIfAbsent(Object key, Function mappingFunction) { if (key instanceof String) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.computeIfAbsent((String) key, - (Function) mappingFunction); + legacyChanged = true; } return super.computeIfAbsent(key, mappingFunction); } @@ -1032,45 +1018,39 @@ public abstract class Provider extends Properties { private Object implComputeIfPresent(Object key, BiFunction remappingFunction) { if (key instanceof String) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.computeIfPresent((String) key, - (BiFunction) remappingFunction); + legacyChanged = true; } return super.computeIfPresent(key, remappingFunction); } private Object implPut(Object key, Object value) { if ((key instanceof String) && (value instanceof String)) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.put((String)key, (String)value); + legacyChanged = true; } return super.put(key, value); } private Object implPutIfAbsent(Object key, Object value) { if ((key instanceof String) && (value instanceof String)) { - if (!checkLegacy(key)) { + if (isProviderInfo(key)) { return null; } - legacyStrings.putIfAbsent((String)key, (String)value); + legacyChanged = true; } return super.putIfAbsent(key, value); } private void implClear() { - if (legacyStrings != null) { - legacyStrings.clear(); - } if (legacyMap != null) { legacyMap.clear(); } - if (serviceMap != null) { - serviceMap.clear(); - } + serviceMap.clear(); legacyChanged = false; servicesChanged = false; serviceSet = null; @@ -1090,13 +1070,13 @@ public abstract class Provider extends Properties { this.algorithm = intern ? algorithm.intern() : algorithm; } public int hashCode() { - return type.hashCode() + algorithm.hashCode(); + return Objects.hash(type, algorithm); } public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj instanceof ServiceKey == false) { + if (!(obj instanceof ServiceKey)) { return false; } ServiceKey other = (ServiceKey)obj; @@ -1113,16 +1093,16 @@ public abstract class Provider extends Properties { * service objects. */ private void ensureLegacyParsed() { - if ((legacyChanged == false) || (legacyStrings == null)) { + if (legacyChanged == false) { return; } serviceSet = null; if (legacyMap == null) { - legacyMap = new LinkedHashMap<>(); + legacyMap = new ConcurrentHashMap<>(); } else { legacyMap.clear(); } - for (Map.Entry entry : legacyStrings.entrySet()) { + for (Map.Entry entry : super.entrySet()) { parseLegacyPut(entry.getKey(), entry.getValue()); } removeInvalidServices(legacyMap); @@ -1161,7 +1141,15 @@ public abstract class Provider extends Properties { private static final String ALIAS_PREFIX_LOWER = "alg.alias."; private static final int ALIAS_LENGTH = ALIAS_PREFIX.length(); - private void parseLegacyPut(String name, String value) { + private void parseLegacyPut(Object k, Object v) { + if (!(k instanceof String) || !(v instanceof String)) { + return; + } + String name = (String) k; + String value = (String) v; + if (isProviderInfo(name)) { + return; + } if (name.toLowerCase(ENGLISH).startsWith(ALIAS_PREFIX_LOWER)) { // e.g. put("Alg.Alias.MessageDigest.SHA", "SHA-1"); // aliasKey ~ MessageDigest.SHA @@ -1248,22 +1236,28 @@ public abstract class Provider extends Properties { * * @since 1.5 */ - public synchronized Service getService(String type, String algorithm) { + public Service getService(String type, String algorithm) { checkInitialized(); - // avoid allocating a new key object if possible + + // avoid allocating a new ServiceKey object if possible ServiceKey key = previousKey; if (key.matches(type, algorithm) == false) { key = new ServiceKey(type, algorithm, false); previousKey = key; } - if (serviceMap != null) { - Service service = serviceMap.get(key); - if (service != null) { - return service; + if (!serviceMap.isEmpty()) { + Service s = serviceMap.get(key); + if (s != null) { + return s; } } - ensureLegacyParsed(); - return (legacyMap != null) ? legacyMap.get(key) : null; + synchronized (this) { + ensureLegacyParsed(); + } + if (legacyMap != null && !legacyMap.isEmpty()) { + return legacyMap.get(key); + } + return null; } // ServiceKey from previous getService() call @@ -1292,10 +1286,10 @@ public abstract class Provider extends Properties { if (serviceSet == null) { ensureLegacyParsed(); Set set = new LinkedHashSet<>(); - if (serviceMap != null) { + if (!serviceMap.isEmpty()) { set.addAll(serviceMap.values()); } - if (legacyMap != null) { + if (legacyMap != null && !legacyMap.isEmpty()) { set.addAll(legacyMap.values()); } serviceSet = Collections.unmodifiableSet(set); @@ -1333,7 +1327,7 @@ public abstract class Provider extends Properties { * * @since 1.5 */ - protected synchronized void putService(Service s) { + protected void putService(Service s) { check("putProviderProperty." + name); if (debug != null) { debug.println(name + ".putService(): " + s); @@ -1345,20 +1339,18 @@ public abstract class Provider extends Properties { throw new IllegalArgumentException ("service.getProvider() must match this Provider object"); } - if (serviceMap == null) { - serviceMap = new LinkedHashMap<>(); - } - servicesChanged = true; String type = s.getType(); String algorithm = s.getAlgorithm(); ServiceKey key = new ServiceKey(type, algorithm, true); - // remove existing service implRemoveService(serviceMap.get(key)); serviceMap.put(key, s); for (String alias : s.getAliases()) { serviceMap.put(new ServiceKey(type, alias, true), s); } - putPropertyStrings(s); + servicesChanged = true; + synchronized (this) { + putPropertyStrings(s); + } } /** @@ -1425,7 +1417,7 @@ public abstract class Provider extends Properties { * * @since 1.5 */ - protected synchronized void removeService(Service s) { + protected void removeService(Service s) { check("removeProviderProperty." + name); if (debug != null) { debug.println(name + ".removeService(): " + s); @@ -1437,7 +1429,7 @@ public abstract class Provider extends Properties { } private void implRemoveService(Service s) { - if ((s == null) || (serviceMap == null)) { + if ((s == null) || serviceMap.isEmpty()) { return; } String type = s.getType(); @@ -1452,7 +1444,9 @@ public abstract class Provider extends Properties { for (String alias : s.getAliases()) { serviceMap.remove(new ServiceKey(type, alias, false)); } - removePropertyStrings(s); + synchronized (this) { + removePropertyStrings(s); + } } // Wrapped String that behaves in a case insensitive way for equals/hashCode diff --git a/src/java.base/share/classes/sun/security/provider/Sun.java b/src/java.base/share/classes/sun/security/provider/Sun.java index 4de677d4b87..3d7fcc75912 100644 --- a/src/java.base/share/classes/sun/security/provider/Sun.java +++ b/src/java.base/share/classes/sun/security/provider/Sun.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -28,7 +28,6 @@ package sun.security.provider; import java.util.*; import java.security.*; -import sun.security.action.PutAllAction; import static sun.security.util.SecurityConstants.PROVIDER_VER; @@ -51,17 +50,27 @@ public final class Sun extends Provider { /* We are the SUN provider */ super("SUN", PROVIDER_VER, INFO); + Provider p = this; + Iterator serviceIter = new SunEntries(p).iterator(); + // if there is no security manager installed, put directly into - // the provider. Otherwise, create a temporary map and use a - // doPrivileged() call at the end to transfer the contents + // the provider if (System.getSecurityManager() == null) { - SunEntries.putEntries(this); + putEntries(serviceIter); } else { - // use LinkedHashMap to preserve the order of the PRNGs - Map map = new LinkedHashMap<>(); - SunEntries.putEntries(map); - AccessController.doPrivileged(new PutAllAction(this, map)); + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Void run() { + putEntries(serviceIter); + return null; + } + }); } } + void putEntries(Iterator i) { + while (i.hasNext()) { + putService(i.next()); + } + } } diff --git a/src/java.base/share/classes/sun/security/provider/SunEntries.java b/src/java.base/share/classes/sun/security/provider/SunEntries.java index 872c14b7b55..905fa03ea40 100644 --- a/src/java.base/share/classes/sun/security/provider/SunEntries.java +++ b/src/java.base/share/classes/sun/security/provider/SunEntries.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -27,7 +27,7 @@ package sun.security.provider; import java.io.*; import java.net.*; -import java.util.Map; +import java.util.*; import java.security.*; import jdk.internal.util.StaticProperty; @@ -75,17 +75,28 @@ import sun.security.action.GetPropertyAction; * - JavaLoginConfig is the default file-based LoginModule Configuration type. */ -final class SunEntries { +public final class SunEntries { - private static final boolean useLegacyDSA = - Boolean.parseBoolean(GetPropertyAction.privilegedGetProperty - ("jdk.security.legacyDSAKeyPairGenerator")); - - private SunEntries() { - // empty + // create an aliases List from the specified aliases + public static List createAliases(String ... aliases) { + return Arrays.asList(aliases); } - static void putEntries(Map map) { + // create an aliases List from the specified oid followed by other aliases + public static List createAliasesWithOid(String ... oids) { + String[] result = Arrays.copyOf(oids, oids.length + 1); + result[result.length - 1] = "OID." + oids[0]; + return Arrays.asList(result); + } + + // extend LinkedHashSet to preserve the ordering (needed by SecureRandom?) + SunEntries(Provider p) { + services = new LinkedHashSet<>(50, 0.9f); + + // start populating content using the specified provider + + // common attribute map + HashMap attrs = new HashMap<>(3); /* * SecureRandom @@ -100,266 +111,217 @@ final class SunEntries { boolean useNativePRNG = seedSource.equals(URL_DEV_URANDOM) || seedSource.equals(URL_DEV_RANDOM); + attrs.put("ThreadSafe", "true"); if (nativeAvailable && useNativePRNG) { - map.put("SecureRandom.NativePRNG", - "sun.security.provider.NativePRNG"); - map.put("SecureRandom.NativePRNG ThreadSafe", "true"); + add(p, "SecureRandom", "NativePRNG", + "sun.security.provider.NativePRNG", null, attrs); } - - map.put("SecureRandom.DRBG", "sun.security.provider.DRBG"); - map.put("SecureRandom.DRBG ThreadSafe", "true"); - - map.put("SecureRandom.SHA1PRNG", - "sun.security.provider.SecureRandom"); - - map.put("SecureRandom.SHA1PRNG ThreadSafe", "true"); + attrs.put("ImplementedIn", "Software"); + add(p, "SecureRandom", "DRBG", "sun.security.provider.DRBG", null, attrs); + add(p, "SecureRandom", "SHA1PRNG", + "sun.security.provider.SecureRandom", null, attrs); + attrs.remove("ImplementedIn"); if (nativeAvailable && !useNativePRNG) { - map.put("SecureRandom.NativePRNG", - "sun.security.provider.NativePRNG"); - map.put("SecureRandom.NativePRNG ThreadSafe", "true"); + add(p, "SecureRandom", "NativePRNG", "sun.security.provider.NativePRNG", + null, attrs); } if (NativePRNG.Blocking.isAvailable()) { - map.put("SecureRandom.NativePRNGBlocking", - "sun.security.provider.NativePRNG$Blocking"); - map.put("SecureRandom.NativePRNGBlocking ThreadSafe", "true"); + add(p, "SecureRandom", "NativePRNGBlocking", + "sun.security.provider.NativePRNG$Blocking", null, attrs); } - if (NativePRNG.NonBlocking.isAvailable()) { - map.put("SecureRandom.NativePRNGNonBlocking", - "sun.security.provider.NativePRNG$NonBlocking"); - map.put("SecureRandom.NativePRNGNonBlocking ThreadSafe", "true"); + add(p, "SecureRandom", "NativePRNGNonBlocking", + "sun.security.provider.NativePRNG$NonBlocking", null, attrs); } /* * Signature engines */ - map.put("Signature.SHA1withDSA", - "sun.security.provider.DSA$SHA1withDSA"); - map.put("Signature.NONEwithDSA", "sun.security.provider.DSA$RawDSA"); - map.put("Alg.Alias.Signature.RawDSA", "NONEwithDSA"); - map.put("Signature.SHA224withDSA", - "sun.security.provider.DSA$SHA224withDSA"); - map.put("Signature.SHA256withDSA", - "sun.security.provider.DSA$SHA256withDSA"); - - map.put("Signature.SHA1withDSAinP1363Format", - "sun.security.provider.DSA$SHA1withDSAinP1363Format"); - map.put("Signature.NONEwithDSAinP1363Format", - "sun.security.provider.DSA$RawDSAinP1363Format"); - map.put("Signature.SHA224withDSAinP1363Format", - "sun.security.provider.DSA$SHA224withDSAinP1363Format"); - map.put("Signature.SHA256withDSAinP1363Format", - "sun.security.provider.DSA$SHA256withDSAinP1363Format"); - + attrs.clear(); String dsaKeyClasses = "java.security.interfaces.DSAPublicKey" + "|java.security.interfaces.DSAPrivateKey"; - map.put("Signature.SHA1withDSA SupportedKeyClasses", dsaKeyClasses); - map.put("Signature.NONEwithDSA SupportedKeyClasses", dsaKeyClasses); - map.put("Signature.SHA224withDSA SupportedKeyClasses", dsaKeyClasses); - map.put("Signature.SHA256withDSA SupportedKeyClasses", dsaKeyClasses); + attrs.put("SupportedKeyClasses", dsaKeyClasses); + attrs.put("ImplementedIn", "Software"); - map.put("Alg.Alias.Signature.DSA", "SHA1withDSA"); - map.put("Alg.Alias.Signature.DSS", "SHA1withDSA"); - map.put("Alg.Alias.Signature.SHA/DSA", "SHA1withDSA"); - map.put("Alg.Alias.Signature.SHA-1/DSA", "SHA1withDSA"); - map.put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA"); - map.put("Alg.Alias.Signature.SHAwithDSA", "SHA1withDSA"); - map.put("Alg.Alias.Signature.DSAWithSHA1", "SHA1withDSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", - "SHA1withDSA"); - map.put("Alg.Alias.Signature.1.2.840.10040.4.3", "SHA1withDSA"); - map.put("Alg.Alias.Signature.1.3.14.3.2.13", "SHA1withDSA"); - map.put("Alg.Alias.Signature.1.3.14.3.2.27", "SHA1withDSA"); - map.put("Alg.Alias.Signature.OID.2.16.840.1.101.3.4.3.1", - "SHA224withDSA"); - map.put("Alg.Alias.Signature.2.16.840.1.101.3.4.3.1", "SHA224withDSA"); - map.put("Alg.Alias.Signature.OID.2.16.840.1.101.3.4.3.2", - "SHA256withDSA"); - map.put("Alg.Alias.Signature.2.16.840.1.101.3.4.3.2", "SHA256withDSA"); + attrs.put("KeySize", "1024"); // for NONE and SHA1 DSA signatures + + add(p, "Signature", "SHA1withDSA", + "sun.security.provider.DSA$SHA1withDSA", + createAliasesWithOid("1.2.840.10040.4.3", "DSA", "DSS", "SHA/DSA", + "SHA-1/DSA", "SHA1/DSA", "SHAwithDSA", "DSAWithSHA1", + "1.3.14.3.2.13", "1.3.14.3.2.27"), attrs); + add(p, "Signature", "NONEwithDSA", "sun.security.provider.DSA$RawDSA", + createAliases("RawDSA"), attrs); + + attrs.put("KeySize", "2048"); // for SHA224 and SHA256 DSA signatures + + add(p, "Signature", "SHA224withDSA", + "sun.security.provider.DSA$SHA224withDSA", + createAliasesWithOid("2.16.840.1.101.3.4.3.1"), attrs); + add(p, "Signature", "SHA256withDSA", + "sun.security.provider.DSA$SHA256withDSA", + createAliasesWithOid("2.16.840.1.101.3.4.3.2"), attrs); + + attrs.remove("KeySize"); + + add(p, "Signature", "SHA1withDSAinP1363Format", + "sun.security.provider.DSA$SHA1withDSAinP1363Format", + null, null); + add(p, "Signature", "NONEwithDSAinP1363Format", + "sun.security.provider.DSA$RawDSAinP1363Format", + null, null); + add(p, "Signature", "SHA224withDSAinP1363Format", + "sun.security.provider.DSA$SHA224withDSAinP1363Format", + null, null); + add(p, "Signature", "SHA256withDSAinP1363Format", + "sun.security.provider.DSA$SHA256withDSAinP1363Format", + null, null); /* * Key Pair Generator engines */ + attrs.clear(); + attrs.put("ImplementedIn", "Software"); + attrs.put("KeySize", "2048"); // for DSA KPG and APG only + + String dsaOid = "1.2.840.10040.4.1"; + List dsaAliases = createAliasesWithOid(dsaOid, "1.3.14.3.2.12"); String dsaKPGImplClass = "sun.security.provider.DSAKeyPairGenerator$"; dsaKPGImplClass += (useLegacyDSA? "Legacy" : "Current"); - map.put("KeyPairGenerator.DSA", dsaKPGImplClass); - map.put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSA"); - - /* - * Digest engines - */ - map.put("MessageDigest.MD2", "sun.security.provider.MD2"); - map.put("MessageDigest.MD5", "sun.security.provider.MD5"); - map.put("MessageDigest.SHA", "sun.security.provider.SHA"); - - map.put("Alg.Alias.MessageDigest.SHA-1", "SHA"); - map.put("Alg.Alias.MessageDigest.SHA1", "SHA"); - map.put("Alg.Alias.MessageDigest.1.3.14.3.2.26", "SHA"); - map.put("Alg.Alias.MessageDigest.OID.1.3.14.3.2.26", "SHA"); - - map.put("MessageDigest.SHA-224", "sun.security.provider.SHA2$SHA224"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.4", "SHA-224"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.4", - "SHA-224"); - - map.put("MessageDigest.SHA-256", "sun.security.provider.SHA2$SHA256"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.1", "SHA-256"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.1", - "SHA-256"); - map.put("MessageDigest.SHA-384", "sun.security.provider.SHA5$SHA384"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.2", "SHA-384"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.2", - "SHA-384"); - map.put("MessageDigest.SHA-512", "sun.security.provider.SHA5$SHA512"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.3", "SHA-512"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.3", - "SHA-512"); - map.put("MessageDigest.SHA-512/224", "sun.security.provider.SHA5$SHA512_224"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.5", "SHA-512/224"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.5", - "SHA-512/224"); - map.put("MessageDigest.SHA-512/256", "sun.security.provider.SHA5$SHA512_256"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.6", "SHA-512/256"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.6", - "SHA-512/256"); - - map.put("MessageDigest.SHA3-224", "sun.security.provider.SHA3$SHA224"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.7", "SHA3-224"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.7", - "SHA3-224"); - - map.put("MessageDigest.SHA3-256", "sun.security.provider.SHA3$SHA256"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.8", "SHA3-256"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.8", - "SHA3-256"); - map.put("MessageDigest.SHA3-384", "sun.security.provider.SHA3$SHA384"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.9", "SHA3-384"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.9", - "SHA3-384"); - map.put("MessageDigest.SHA3-512", "sun.security.provider.SHA3$SHA512"); - map.put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.10", "SHA3-512"); - map.put("Alg.Alias.MessageDigest.OID.2.16.840.1.101.3.4.2.10", - "SHA3-512"); - + add(p, "KeyPairGenerator", "DSA", dsaKPGImplClass, dsaAliases, attrs); /* * Algorithm Parameter Generator engines */ - map.put("AlgorithmParameterGenerator.DSA", - "sun.security.provider.DSAParameterGenerator"); + add(p, "AlgorithmParameterGenerator", "DSA", + "sun.security.provider.DSAParameterGenerator", dsaAliases, attrs); + attrs.remove("KeySize"); /* * Algorithm Parameter engines */ - map.put("AlgorithmParameters.DSA", - "sun.security.provider.DSAParameters"); - map.put("Alg.Alias.AlgorithmParameters.OID.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.AlgorithmParameters.1.3.14.3.2.12", "DSA"); + add(p, "AlgorithmParameters", "DSA", + "sun.security.provider.DSAParameters", dsaAliases, attrs); /* * Key factories */ - map.put("KeyFactory.DSA", "sun.security.provider.DSAKeyFactory"); - map.put("Alg.Alias.KeyFactory.OID.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA"); - map.put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA"); + add(p, "KeyFactory", "DSA", "sun.security.provider.DSAKeyFactory", + dsaAliases, attrs); + + /* + * Digest engines + */ + add(p, "MessageDigest", "MD2", "sun.security.provider.MD2", null, attrs); + add(p, "MessageDigest", "MD5", "sun.security.provider.MD5", null, attrs); + add(p, "MessageDigest", "SHA", "sun.security.provider.SHA", + createAliasesWithOid("1.3.14.3.2.26", "SHA-1", "SHA1"), attrs); + + String sha2BaseOid = "2.16.840.1.101.3.4.2"; + add(p, "MessageDigest", "SHA-224", "sun.security.provider.SHA2$SHA224", + createAliasesWithOid(sha2BaseOid + ".4"), attrs); + add(p, "MessageDigest", "SHA-256", "sun.security.provider.SHA2$SHA256", + createAliasesWithOid(sha2BaseOid + ".1"), attrs); + add(p, "MessageDigest", "SHA-384", "sun.security.provider.SHA5$SHA384", + createAliasesWithOid(sha2BaseOid + ".2"), attrs); + add(p, "MessageDigest", "SHA-512", "sun.security.provider.SHA5$SHA512", + createAliasesWithOid(sha2BaseOid + ".3"), attrs); + add(p, "MessageDigest", "SHA-512/224", + "sun.security.provider.SHA5$SHA512_224", + createAliasesWithOid(sha2BaseOid + ".5"), attrs); + add(p, "MessageDigest", "SHA-512/256", + "sun.security.provider.SHA5$SHA512_256", + createAliasesWithOid(sha2BaseOid + ".6"), attrs); + add(p, "MessageDigest", "SHA3-224", "sun.security.provider.SHA3$SHA224", + createAliasesWithOid(sha2BaseOid + ".7"), attrs); + add(p, "MessageDigest", "SHA3-256", "sun.security.provider.SHA3$SHA256", + createAliasesWithOid(sha2BaseOid + ".8"), attrs); + add(p, "MessageDigest", "SHA3-384", "sun.security.provider.SHA3$SHA384", + createAliasesWithOid(sha2BaseOid + ".9"), attrs); + add(p, "MessageDigest", "SHA3-512", "sun.security.provider.SHA3$SHA512", + createAliasesWithOid(sha2BaseOid + ".10"), attrs); /* * Certificates */ - map.put("CertificateFactory.X.509", - "sun.security.provider.X509Factory"); - map.put("Alg.Alias.CertificateFactory.X509", "X.509"); + add(p, "CertificateFactory", "X.509", + "sun.security.provider.X509Factory", + createAliases("X509"), attrs); /* * KeyStore */ - map.put("KeyStore.PKCS12", - "sun.security.pkcs12.PKCS12KeyStore$DualFormatPKCS12"); - map.put("KeyStore.JKS", - "sun.security.provider.JavaKeyStore$DualFormatJKS"); - map.put("KeyStore.CaseExactJKS", - "sun.security.provider.JavaKeyStore$CaseExactJKS"); - map.put("KeyStore.DKS", "sun.security.provider.DomainKeyStore$DKS"); + add(p, "KeyStore", "PKCS12", + "sun.security.pkcs12.PKCS12KeyStore$DualFormatPKCS12", + null, null); + add(p, "KeyStore", "JKS", + "sun.security.provider.JavaKeyStore$DualFormatJKS", + null, attrs); + add(p, "KeyStore", "CaseExactJKS", + "sun.security.provider.JavaKeyStore$CaseExactJKS", + null, attrs); + add(p, "KeyStore", "DKS", "sun.security.provider.DomainKeyStore$DKS", + null, attrs); - /* - * Policy - */ - map.put("Policy.JavaPolicy", "sun.security.provider.PolicySpiFile"); - - /* - * Configuration - */ - map.put("Configuration.JavaLoginConfig", - "sun.security.provider.ConfigFile$Spi"); - - /* - * CertPathBuilder - */ - map.put("CertPathBuilder.PKIX", - "sun.security.provider.certpath.SunCertPathBuilder"); - map.put("CertPathBuilder.PKIX ValidationAlgorithm", - "RFC5280"); - - /* - * CertPathValidator - */ - map.put("CertPathValidator.PKIX", - "sun.security.provider.certpath.PKIXCertPathValidator"); - map.put("CertPathValidator.PKIX ValidationAlgorithm", - "RFC5280"); /* * CertStores */ - map.put("CertStore.Collection", - "sun.security.provider.certpath.CollectionCertStore"); - map.put("CertStore.com.sun.security.IndexedCollection", - "sun.security.provider.certpath.IndexedCollectionCertStore"); + add(p, "CertStore", "Collection", + "sun.security.provider.certpath.CollectionCertStore", + null, attrs); + add(p, "CertStore", "com.sun.security.IndexedCollection", + "sun.security.provider.certpath.IndexedCollectionCertStore", + null, attrs); /* - * KeySize + * Policy */ - map.put("Signature.NONEwithDSA KeySize", "1024"); - map.put("Signature.SHA1withDSA KeySize", "1024"); - map.put("Signature.SHA224withDSA KeySize", "2048"); - map.put("Signature.SHA256withDSA KeySize", "2048"); - - map.put("KeyPairGenerator.DSA KeySize", "2048"); - map.put("AlgorithmParameterGenerator.DSA KeySize", "2048"); + add(p, "Policy", "JavaPolicy", "sun.security.provider.PolicySpiFile", + null, null); /* - * Implementation type: software or hardware + * Configuration */ - map.put("Signature.SHA1withDSA ImplementedIn", "Software"); - map.put("KeyPairGenerator.DSA ImplementedIn", "Software"); - map.put("MessageDigest.MD5 ImplementedIn", "Software"); - map.put("MessageDigest.SHA ImplementedIn", "Software"); - map.put("AlgorithmParameterGenerator.DSA ImplementedIn", - "Software"); - map.put("AlgorithmParameters.DSA ImplementedIn", "Software"); - map.put("KeyFactory.DSA ImplementedIn", "Software"); - map.put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); - map.put("SecureRandom.DRBG ImplementedIn", "Software"); - map.put("CertificateFactory.X.509 ImplementedIn", "Software"); - map.put("KeyStore.JKS ImplementedIn", "Software"); - map.put("CertPathValidator.PKIX ImplementedIn", "Software"); - map.put("CertPathBuilder.PKIX ImplementedIn", "Software"); - map.put("CertStore.Collection ImplementedIn", "Software"); - map.put("CertStore.com.sun.security.IndexedCollection ImplementedIn", - "Software"); + add(p, "Configuration", "JavaLoginConfig", + "sun.security.provider.ConfigFile$Spi", null, null); + /* + * CertPathBuilder and CertPathValidator + */ + attrs.clear(); + attrs.put("ValidationAlgorithm", "RFC5280"); + attrs.put("ImplementedIn", "Software"); + + add(p, "CertPathBuilder", "PKIX", + "sun.security.provider.certpath.SunCertPathBuilder", + null, attrs); + add(p, "CertPathValidator", "PKIX", + "sun.security.provider.certpath.PKIXCertPathValidator", + null, attrs); } + Iterator iterator() { + return services.iterator(); + } + + private void add(Provider p, String type, String algo, String cn, + List aliases, HashMap attrs) { + services.add(new Provider.Service(p, type, algo, cn, aliases, attrs)); + } + + private LinkedHashSet services; + // name of the *System* property, takes precedence over PROP_RNDSOURCE private static final String PROP_EGD = "java.security.egd"; // name of the *Security* property private static final String PROP_RNDSOURCE = "securerandom.source"; + private static final boolean useLegacyDSA = + Boolean.parseBoolean(GetPropertyAction.privilegedGetProperty + ("jdk.security.legacyDSAKeyPairGenerator")); + static final String URL_DEV_RANDOM = "file:/dev/random"; static final String URL_DEV_URANDOM = "file:/dev/urandom"; diff --git a/src/java.base/share/classes/sun/security/provider/VerificationProvider.java b/src/java.base/share/classes/sun/security/provider/VerificationProvider.java index f4016a867f7..485e08605f1 100644 --- a/src/java.base/share/classes/sun/security/provider/VerificationProvider.java +++ b/src/java.base/share/classes/sun/security/provider/VerificationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -28,8 +28,6 @@ package sun.security.provider; import java.util.*; import java.security.*; -import sun.security.action.PutAllAction; - import sun.security.rsa.SunRsaSignEntries; import static sun.security.util.SecurityConstants.PROVIDER_VER; @@ -70,18 +68,30 @@ public final class VerificationProvider extends Provider { return; } + Provider p = this; + Iterator sunIter = new SunEntries(p).iterator(); + Iterator rsaIter = + new SunRsaSignEntries(p).iterator(); + // if there is no security manager installed, put directly into - // the provider. Otherwise, create a temporary map and use a - // doPrivileged() call at the end to transfer the contents + // the provider if (System.getSecurityManager() == null) { - SunEntries.putEntries(this); - SunRsaSignEntries.putEntries(this); + putEntries(sunIter); + putEntries(rsaIter); } else { - // use LinkedHashMap to preserve the order of the PRNGs - Map map = new LinkedHashMap<>(); - SunEntries.putEntries(map); - SunRsaSignEntries.putEntries(map); - AccessController.doPrivileged(new PutAllAction(this, map)); + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + putEntries(sunIter); + putEntries(rsaIter); + return null; + } + }); + } + } + + void putEntries(Iterator i) { + while (i.hasNext()) { + putService(i.next()); } } diff --git a/src/java.base/share/classes/sun/security/rsa/SunRsaSign.java b/src/java.base/share/classes/sun/security/rsa/SunRsaSign.java index e80634c369b..2586a6a12cf 100644 --- a/src/java.base/share/classes/sun/security/rsa/SunRsaSign.java +++ b/src/java.base/share/classes/sun/security/rsa/SunRsaSign.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,6 @@ import java.util.*; import java.security.*; -import sun.security.action.PutAllAction; import static sun.security.util.SecurityConstants.PROVIDER_VER; /** @@ -46,17 +45,24 @@ public final class SunRsaSign extends Provider { public SunRsaSign() { super("SunRsaSign", PROVIDER_VER, "Sun RSA signature provider"); - // if there is no security manager installed, put directly into - // the provider. Otherwise, create a temporary map and use a - // doPrivileged() call at the end to transfer the contents + Provider p = this; + Iterator serviceIter = new SunRsaSignEntries(p).iterator(); + if (System.getSecurityManager() == null) { - SunRsaSignEntries.putEntries(this); + putEntries(serviceIter); } else { - // use LinkedHashMap to preserve the order of the PRNGs - Map map = new HashMap<>(); - SunRsaSignEntries.putEntries(map); - AccessController.doPrivileged(new PutAllAction(this, map)); + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Void run() { + putEntries(serviceIter); + return null; + } + }); + } + } + void putEntries(Iterator i) { + while (i.hasNext()) { + putService(i.next()); } } - } diff --git a/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java b/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java index a5592d55495..a5cab587d28 100644 --- a/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java +++ b/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java @@ -25,7 +25,9 @@ package sun.security.rsa; -import java.util.Map; +import java.util.*; +import java.security.Provider; +import static sun.security.provider.SunEntries.createAliasesWithOid; /** * Defines the entries of the SunRsaSign provider. @@ -34,102 +36,81 @@ import java.util.Map; */ public final class SunRsaSignEntries { - private SunRsaSignEntries() { - // empty + private void add(Provider p, String type, String algo, String cn, + List aliases, HashMap attrs) { + services.add(new Provider.Service(p, type, algo, cn, aliases, attrs)); } - public static void putEntries(Map map) { + // extend LinkedHashSet for consistency with SunEntries + // used by sun.security.provider.VerificationProvider + public SunRsaSignEntries(Provider p) { + services = new LinkedHashSet<>(20, 0.9f); - // main algorithms - map.put("KeyFactory.RSA", - "sun.security.rsa.RSAKeyFactory$Legacy"); - map.put("KeyPairGenerator.RSA", - "sun.security.rsa.RSAKeyPairGenerator$Legacy"); - map.put("Signature.MD2withRSA", - "sun.security.rsa.RSASignature$MD2withRSA"); - map.put("Signature.MD5withRSA", - "sun.security.rsa.RSASignature$MD5withRSA"); - map.put("Signature.SHA1withRSA", - "sun.security.rsa.RSASignature$SHA1withRSA"); - map.put("Signature.SHA224withRSA", - "sun.security.rsa.RSASignature$SHA224withRSA"); - map.put("Signature.SHA256withRSA", - "sun.security.rsa.RSASignature$SHA256withRSA"); - map.put("Signature.SHA384withRSA", - "sun.security.rsa.RSASignature$SHA384withRSA"); - map.put("Signature.SHA512withRSA", - "sun.security.rsa.RSASignature$SHA512withRSA"); - map.put("Signature.SHA512/224withRSA", - "sun.security.rsa.RSASignature$SHA512_224withRSA"); - map.put("Signature.SHA512/256withRSA", - "sun.security.rsa.RSASignature$SHA512_256withRSA"); + // start populating content using the specified provider - map.put("KeyFactory.RSASSA-PSS", - "sun.security.rsa.RSAKeyFactory$PSS"); - map.put("KeyPairGenerator.RSASSA-PSS", - "sun.security.rsa.RSAKeyPairGenerator$PSS"); - map.put("Signature.RSASSA-PSS", - "sun.security.rsa.RSAPSSSignature"); - map.put("AlgorithmParameters.RSASSA-PSS", - "sun.security.rsa.PSSParameters"); + // common oids + String rsaOid = "1.2.840.113549.1.1"; + List rsaAliases = createAliasesWithOid(rsaOid); + List rsapssAliases = createAliasesWithOid(rsaOid + ".10"); + String sha1withRSAOid2 = "1.3.14.3.2.29"; - // attributes for supported key classes - String rsaKeyClasses = "java.security.interfaces.RSAPublicKey" + - "|java.security.interfaces.RSAPrivateKey"; - map.put("Signature.MD2withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.MD5withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA1withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA224withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA256withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA384withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA512withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA512/224withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.SHA512/256withRSA SupportedKeyClasses", rsaKeyClasses); - map.put("Signature.RSASSA-PSS SupportedKeyClasses", rsaKeyClasses); + // common attribute map + HashMap attrs = new HashMap<>(3); + attrs.put("SupportedKeyClasses", + "java.security.interfaces.RSAPublicKey" + + "|java.security.interfaces.RSAPrivateKey"); - // aliases - map.put("Alg.Alias.KeyFactory.1.2.840.113549.1.1", "RSA"); - map.put("Alg.Alias.KeyFactory.OID.1.2.840.113549.1.1", "RSA"); + add(p, "KeyFactory", "RSA", + "sun.security.rsa.RSAKeyFactory$Legacy", + rsaAliases, null); + add(p, "KeyPairGenerator", "RSA", + "sun.security.rsa.RSAKeyPairGenerator$Legacy", + rsaAliases, null); + add(p, "Signature", "MD2withRSA", + "sun.security.rsa.RSASignature$MD2withRSA", + createAliasesWithOid(rsaOid + ".2"), attrs); + add(p, "Signature", "MD5withRSA", + "sun.security.rsa.RSASignature$MD5withRSA", + createAliasesWithOid(rsaOid + ".4"), attrs); + add(p, "Signature", "SHA1withRSA", + "sun.security.rsa.RSASignature$SHA1withRSA", + createAliasesWithOid(rsaOid + ".5", sha1withRSAOid2), attrs); + add(p, "Signature", "SHA224withRSA", + "sun.security.rsa.RSASignature$SHA224withRSA", + createAliasesWithOid(rsaOid + ".14"), attrs); + add(p, "Signature", "SHA256withRSA", + "sun.security.rsa.RSASignature$SHA256withRSA", + createAliasesWithOid(rsaOid + ".11"), attrs); + add(p, "Signature", "SHA384withRSA", + "sun.security.rsa.RSASignature$SHA384withRSA", + createAliasesWithOid(rsaOid + ".12"), attrs); + add(p, "Signature", "SHA512withRSA", + "sun.security.rsa.RSASignature$SHA512withRSA", + createAliasesWithOid(rsaOid + ".13"), attrs); + add(p, "Signature", "SHA512/224withRSA", + "sun.security.rsa.RSASignature$SHA512_224withRSA", + createAliasesWithOid(rsaOid + ".15"), attrs); + add(p, "Signature", "SHA512/256withRSA", + "sun.security.rsa.RSASignature$SHA512_256withRSA", + createAliasesWithOid(rsaOid + ".16"), attrs); - map.put("Alg.Alias.KeyPairGenerator.1.2.840.113549.1.1", "RSA"); - map.put("Alg.Alias.KeyPairGenerator.OID.1.2.840.113549.1.1", "RSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.2", "MD2withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.2", "MD2withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.4", "MD5withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.4", "MD5withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.5", "SHA1withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.5", "SHA1withRSA"); - map.put("Alg.Alias.Signature.1.3.14.3.2.29", "SHA1withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.14", "SHA224withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.14", "SHA224withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.11", "SHA256withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", "SHA256withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.12", "SHA384withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", "SHA384withRSA"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.13", "SHA512withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", "SHA512withRSA"); - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.15", "SHA512/224withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.15", "SHA512/224withRSA"); - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.16", "SHA512/256withRSA"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.16", "SHA512/256withRSA"); - - map.put("Alg.Alias.KeyFactory.1.2.840.113549.1.1.10", "RSASSA-PSS"); - map.put("Alg.Alias.KeyFactory.OID.1.2.840.113549.1.1.10", "RSASSA-PSS"); - - map.put("Alg.Alias.KeyPairGenerator.1.2.840.113549.1.1.10", "RSASSA-PSS"); - map.put("Alg.Alias.KeyPairGenerator.OID.1.2.840.113549.1.1.10", "RSASSA-PSS"); - - map.put("Alg.Alias.Signature.1.2.840.113549.1.1.10", "RSASSA-PSS"); - map.put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.10", "RSASSA-PSS"); - - map.put("Alg.Alias.AlgorithmParameters.1.2.840.113549.1.1.10", "RSASSA-PSS"); - map.put("Alg.Alias.AlgorithmParameters.OID.1.2.840.113549.1.1.10", "RSASSA-PSS"); + add(p, "KeyFactory", "RSASSA-PSS", + "sun.security.rsa.RSAKeyFactory$PSS", + rsapssAliases, null); + add(p, "KeyPairGenerator", "RSASSA-PSS", + "sun.security.rsa.RSAKeyPairGenerator$PSS", + rsapssAliases, null); + add(p, "Signature", "RSASSA-PSS", + "sun.security.rsa.RSAPSSSignature", + rsapssAliases, attrs); + add(p, "AlgorithmParameters", "RSASSA-PSS", + "sun.security.rsa.PSSParameters", + rsapssAliases, null); } + + public Iterator iterator() { + return services.iterator(); + } + + private LinkedHashSet services; } diff --git a/src/java.base/share/classes/sun/security/ssl/SunJSSE.java b/src/java.base/share/classes/sun/security/ssl/SunJSSE.java index b84567c3d9c..c50ba93ecfc 100644 --- a/src/java.base/share/classes/sun/security/ssl/SunJSSE.java +++ b/src/java.base/share/classes/sun/security/ssl/SunJSSE.java @@ -26,7 +26,10 @@ package sun.security.ssl; import java.security.*; +import java.util.*; +import sun.security.rsa.SunRsaSignEntries; import static sun.security.util.SecurityConstants.PROVIDER_VER; +import static sun.security.provider.SunEntries.createAliases; /** * The JSSE provider. @@ -157,86 +160,62 @@ public abstract class SunJSSE extends java.security.Provider { }); } + private void ps(String type, String algo, String cn, + List aliases, HashMap attrs) { + putService(new Provider.Service(this, type, algo, cn, aliases, attrs)); + } + private void doRegister(boolean isfips) { if (isfips == false) { - put("KeyFactory.RSA", - "sun.security.rsa.RSAKeyFactory$Legacy"); - put("Alg.Alias.KeyFactory.1.2.840.113549.1.1", "RSA"); - put("Alg.Alias.KeyFactory.OID.1.2.840.113549.1.1", "RSA"); - - put("KeyPairGenerator.RSA", - "sun.security.rsa.RSAKeyPairGenerator$Legacy"); - put("Alg.Alias.KeyPairGenerator.1.2.840.113549.1.1", "RSA"); - put("Alg.Alias.KeyPairGenerator.OID.1.2.840.113549.1.1", "RSA"); - - put("Signature.MD2withRSA", - "sun.security.rsa.RSASignature$MD2withRSA"); - put("Alg.Alias.Signature.1.2.840.113549.1.1.2", "MD2withRSA"); - put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.2", - "MD2withRSA"); - - put("Signature.MD5withRSA", - "sun.security.rsa.RSASignature$MD5withRSA"); - put("Alg.Alias.Signature.1.2.840.113549.1.1.4", "MD5withRSA"); - put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.4", - "MD5withRSA"); - - put("Signature.SHA1withRSA", - "sun.security.rsa.RSASignature$SHA1withRSA"); - put("Alg.Alias.Signature.1.2.840.113549.1.1.5", "SHA1withRSA"); - put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.5", - "SHA1withRSA"); - put("Alg.Alias.Signature.1.3.14.3.2.29", "SHA1withRSA"); - put("Alg.Alias.Signature.OID.1.3.14.3.2.29", "SHA1withRSA"); - + Iterator rsaIter = + new SunRsaSignEntries(this).iterator(); + while (rsaIter.hasNext()) { + putService(rsaIter.next()); + } } - put("Signature.MD5andSHA1withRSA", - "sun.security.ssl.RSASignature"); + ps("Signature", "MD5andSHA1withRSA", + "sun.security.ssl.RSASignature", null, null); - put("KeyManagerFactory.SunX509", - "sun.security.ssl.KeyManagerFactoryImpl$SunX509"); - put("KeyManagerFactory.NewSunX509", - "sun.security.ssl.KeyManagerFactoryImpl$X509"); - put("Alg.Alias.KeyManagerFactory.PKIX", "NewSunX509"); + ps("KeyManagerFactory", "SunX509", + "sun.security.ssl.KeyManagerFactoryImpl$SunX509", null, null); + ps("KeyManagerFactory", "NewSunX509", + "sun.security.ssl.KeyManagerFactoryImpl$X509", + createAliases("PKIX"), null); - put("TrustManagerFactory.SunX509", - "sun.security.ssl.TrustManagerFactoryImpl$SimpleFactory"); - put("TrustManagerFactory.PKIX", - "sun.security.ssl.TrustManagerFactoryImpl$PKIXFactory"); - put("Alg.Alias.TrustManagerFactory.SunPKIX", "PKIX"); - put("Alg.Alias.TrustManagerFactory.X509", "PKIX"); - put("Alg.Alias.TrustManagerFactory.X.509", "PKIX"); + ps("TrustManagerFactory", "SunX509", + "sun.security.ssl.TrustManagerFactoryImpl$SimpleFactory", null, null); + ps("TrustManagerFactory", "PKIX", + "sun.security.ssl.TrustManagerFactoryImpl$PKIXFactory", + createAliases("SunPKIX", "X509", "X.509"), null); - put("SSLContext.TLSv1", - "sun.security.ssl.SSLContextImpl$TLS10Context"); - put("SSLContext.TLSv1.1", - "sun.security.ssl.SSLContextImpl$TLS11Context"); - put("SSLContext.TLSv1.2", - "sun.security.ssl.SSLContextImpl$TLS12Context"); - put("SSLContext.TLSv1.3", - "sun.security.ssl.SSLContextImpl$TLS13Context"); - put("SSLContext.TLS", - "sun.security.ssl.SSLContextImpl$TLSContext"); - if (isfips == false) { - put("Alg.Alias.SSLContext.SSL", "TLS"); - put("Alg.Alias.SSLContext.SSLv3", "TLSv1"); - } + ps("SSLContext", "TLSv1", + "sun.security.ssl.SSLContextImpl$TLS10Context", + (isfips? null : createAliases("SSLv3")), null); + ps("SSLContext", "TLSv1.1", + "sun.security.ssl.SSLContextImpl$TLS11Context", null, null); + ps("SSLContext", "TLSv1.2", + "sun.security.ssl.SSLContextImpl$TLS12Context", null, null); + ps("SSLContext", "TLSv1.3", + "sun.security.ssl.SSLContextImpl$TLS13Context", null, null); + ps("SSLContext", "TLS", + "sun.security.ssl.SSLContextImpl$TLSContext", + (isfips? null : createAliases("SSL")), null); - put("SSLContext.DTLSv1.0", - "sun.security.ssl.SSLContextImpl$DTLS10Context"); - put("SSLContext.DTLSv1.2", - "sun.security.ssl.SSLContextImpl$DTLS12Context"); - put("SSLContext.DTLS", - "sun.security.ssl.SSLContextImpl$DTLSContext"); + ps("SSLContext", "DTLSv1.0", + "sun.security.ssl.SSLContextImpl$DTLS10Context", null, null); + ps("SSLContext", "DTLSv1.2", + "sun.security.ssl.SSLContextImpl$DTLS12Context", null, null); + ps("SSLContext", "DTLS", + "sun.security.ssl.SSLContextImpl$DTLSContext", null, null); - put("SSLContext.Default", - "sun.security.ssl.SSLContextImpl$DefaultSSLContext"); + ps("SSLContext", "Default", + "sun.security.ssl.SSLContextImpl$DefaultSSLContext", null, null); /* * KeyStore */ - put("KeyStore.PKCS12", - "sun.security.pkcs12.PKCS12KeyStore"); + ps("KeyStore", "PKCS12", + "sun.security.pkcs12.PKCS12KeyStore", null, null); } // com.sun.net.ssl.internal.ssl.Provider has been deprecated since JDK 9 From 9136c7d1d0e1247ea1ac95a6577acbb789169031 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 13 Dec 2018 11:16:33 +0800 Subject: [PATCH 027/174] 8076190: Customizing the generation of a PKCS12 keystore Reviewed-by: mullan --- ...S12PBESHA1.java => HmacPKCS12PBECore.java} | 64 ++- .../sun/crypto/provider/PBES2Parameters.java | 57 +- .../com/sun/crypto/provider/SunJCE.java | 23 +- .../share/classes/java/security/KeyStore.java | 13 +- .../sun/security/pkcs12/PKCS12KeyStore.java | 505 ++++++++++++------ .../sun/security/tools/keytool/Main.java | 270 +++++----- .../sun/security/x509/AlgorithmId.java | 9 + .../share/conf/security/java.security | 71 +++ .../security/pkcs12/ParamsPreferences.java | 234 ++++++++ test/jdk/sun/security/pkcs12/ParamsTest.java | 434 +++++++++++++++ test/jdk/sun/security/pkcs12/params/README | 54 ++ test/jdk/sun/security/pkcs12/params/kandc | 55 ++ test/jdk/sun/security/pkcs12/params/ks | 45 ++ test/jdk/sun/security/pkcs12/params/os2 | 42 ++ test/jdk/sun/security/pkcs12/params/os3 | 43 ++ test/jdk/sun/security/pkcs12/params/os4 | 44 ++ test/jdk/sun/security/pkcs12/params/os5 | 48 ++ .../tools/keytool/ProbingFailure.java | 4 +- test/lib/jdk/test/lib/security/DerUtils.java | 117 ++++ 19 files changed, 1782 insertions(+), 350 deletions(-) rename src/java.base/share/classes/com/sun/crypto/provider/{HmacPKCS12PBESHA1.java => HmacPKCS12PBECore.java} (74%) create mode 100644 test/jdk/sun/security/pkcs12/ParamsPreferences.java create mode 100644 test/jdk/sun/security/pkcs12/ParamsTest.java create mode 100644 test/jdk/sun/security/pkcs12/params/README create mode 100644 test/jdk/sun/security/pkcs12/params/kandc create mode 100644 test/jdk/sun/security/pkcs12/params/ks create mode 100644 test/jdk/sun/security/pkcs12/params/os2 create mode 100644 test/jdk/sun/security/pkcs12/params/os3 create mode 100644 test/jdk/sun/security/pkcs12/params/os4 create mode 100644 test/jdk/sun/security/pkcs12/params/os5 create mode 100644 test/lib/jdk/test/lib/security/DerUtils.java diff --git a/src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java b/src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBECore.java similarity index 74% rename from src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java rename to src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBECore.java index 9c76839f385..1fd6230d83b 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/HmacPKCS12PBECore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,7 @@ package com.sun.crypto.provider; import java.util.Arrays; -import java.nio.ByteBuffer; -import javax.crypto.MacSpi; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.PBEParameterSpec; @@ -36,18 +34,65 @@ import java.security.*; import java.security.spec.*; /** - * This is an implementation of the HMAC-PBESHA1 algorithm as defined - * in PKCS#12 v1.0 standard. + * This is an implementation of the HMAC algorithms as defined + * in PKCS#12 v1.1 standard (see RFC 7292 Appendix B.4). * * @author Valerie Peng */ -public final class HmacPKCS12PBESHA1 extends HmacCore { +abstract class HmacPKCS12PBECore extends HmacCore { + + public static final class HmacPKCS12PBE_SHA1 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA1() throws NoSuchAlgorithmException { + super("SHA1", 64); + } + } + + public static final class HmacPKCS12PBE_SHA224 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA224() throws NoSuchAlgorithmException { + super("SHA-224", 64); + } + } + + public static final class HmacPKCS12PBE_SHA256 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA256() throws NoSuchAlgorithmException { + super("SHA-256", 64); + } + } + + public static final class HmacPKCS12PBE_SHA384 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA384() throws NoSuchAlgorithmException { + super("SHA-384", 128); + } + } + + public static final class HmacPKCS12PBE_SHA512 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA512() throws NoSuchAlgorithmException { + super("SHA-512", 128); + } + } + + public static final class HmacPKCS12PBE_SHA512_224 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA512_224() throws NoSuchAlgorithmException { + super("SHA-512/224", 128); + } + } + + public static final class HmacPKCS12PBE_SHA512_256 extends HmacPKCS12PBECore { + public HmacPKCS12PBE_SHA512_256() throws NoSuchAlgorithmException { + super("SHA-512/256", 128); + } + } + + private final String algorithm; + private final int bl; /** * Standard constructor, creates a new HmacSHA1 instance. */ - public HmacPKCS12PBESHA1() throws NoSuchAlgorithmException { - super("SHA1", 64); + public HmacPKCS12PBECore(String algorithm, int bl) throws NoSuchAlgorithmException { + super(algorithm, bl); + this.algorithm = algorithm; + this.bl = bl; } /** @@ -132,7 +177,8 @@ public final class HmacPKCS12PBESHA1 extends HmacCore { ("IterationCount must be a positive number"); } derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, - iCount, engineGetMacLength(), PKCS12PBECipherCore.MAC_KEY); + iCount, engineGetMacLength(), PKCS12PBECipherCore.MAC_KEY, + algorithm, bl); } finally { Arrays.fill(passwdChars, '\0'); } diff --git a/src/java.base/share/classes/com/sun/crypto/provider/PBES2Parameters.java b/src/java.base/share/classes/com/sun/crypto/provider/PBES2Parameters.java index ab189971136..968d591ac6c 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/PBES2Parameters.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/PBES2Parameters.java @@ -314,41 +314,48 @@ abstract class PBES2Parameters extends AlgorithmParametersSpi { + "not an ASN.1 OCTET STRING tag"); } iCount = pBKDF2_params.data.getInteger(); + + DerValue prf = null; // keyLength INTEGER (1..MAX) OPTIONAL, if (pBKDF2_params.data.available() > 0) { DerValue keyLength = pBKDF2_params.data.getDerValue(); if (keyLength.tag == DerValue.tag_Integer) { keysize = keyLength.getInteger() * 8; // keysize (in bits) + } else { + // Should be the prf + prf = keyLength; } } // prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 String kdfAlgo = "HmacSHA1"; - if (pBKDF2_params.data.available() > 0) { - if (pBKDF2_params.tag == DerValue.tag_Sequence) { - DerValue prf = pBKDF2_params.data.getDerValue(); - kdfAlgo_OID = prf.data.getOID(); - if (hmacWithSHA1_OID.equals(kdfAlgo_OID)) { - kdfAlgo = "HmacSHA1"; - } else if (hmacWithSHA224_OID.equals(kdfAlgo_OID)) { - kdfAlgo = "HmacSHA224"; - } else if (hmacWithSHA256_OID.equals(kdfAlgo_OID)) { - kdfAlgo = "HmacSHA256"; - } else if (hmacWithSHA384_OID.equals(kdfAlgo_OID)) { - kdfAlgo = "HmacSHA384"; - } else if (hmacWithSHA512_OID.equals(kdfAlgo_OID)) { - kdfAlgo = "HmacSHA512"; - } else { + if (prf == null) { + if (pBKDF2_params.data.available() > 0) { + prf = pBKDF2_params.data.getDerValue(); + } + } + if (prf != null) { + kdfAlgo_OID = prf.data.getOID(); + if (hmacWithSHA1_OID.equals(kdfAlgo_OID)) { + kdfAlgo = "HmacSHA1"; + } else if (hmacWithSHA224_OID.equals(kdfAlgo_OID)) { + kdfAlgo = "HmacSHA224"; + } else if (hmacWithSHA256_OID.equals(kdfAlgo_OID)) { + kdfAlgo = "HmacSHA256"; + } else if (hmacWithSHA384_OID.equals(kdfAlgo_OID)) { + kdfAlgo = "HmacSHA384"; + } else if (hmacWithSHA512_OID.equals(kdfAlgo_OID)) { + kdfAlgo = "HmacSHA512"; + } else { + throw new IOException("PBE parameter parsing error: " + + "expecting the object identifier for a HmacSHA key " + + "derivation function"); + } + if (prf.data.available() != 0) { + // parameter is 'NULL' for all HmacSHA KDFs + DerValue parameter = prf.data.getDerValue(); + if (parameter.tag != DerValue.tag_Null) { throw new IOException("PBE parameter parsing error: " - + "expecting the object identifier for a HmacSHA key " - + "derivation function"); - } - if (prf.data.available() != 0) { - // parameter is 'NULL' for all HmacSHA KDFs - DerValue parameter = prf.data.getDerValue(); - if (parameter.tag != DerValue.tag_Null) { - throw new IOException("PBE parameter parsing error: " - + "not an ASN.1 NULL tag"); - } + + "not an ASN.1 NULL tag"); } } } diff --git a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java index 3a086cf2694..414e2c5c6c4 100644 --- a/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java +++ b/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java @@ -684,8 +684,29 @@ public final class SunJCE extends Provider { ps("Mac", "HmacSHA512/256", "com.sun.crypto.provider.HmacCore$HmacSHA512_256", null, attrs); - ps("Mac", "HmacPBESHA1", "com.sun.crypto.provider.HmacPKCS12PBESHA1", + ps("Mac", "HmacPBESHA1", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA1", null, attrs); + ps("Mac", "HmacPBESHA224", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA224", + null, attrs); + ps("Mac", "HmacPBESHA256", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA256", + null, attrs); + ps("Mac", "HmacPBESHA384", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA384", + null, attrs); + ps("Mac", "HmacPBESHA512", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA512", + null, attrs); + ps("Mac", "HmacPBESHA512/224", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA512_224", + null, attrs); + ps("Mac", "HmacPBESHA512/256", + "com.sun.crypto.provider.HmacPKCS12PBECore$HmacPKCS12PBE_SHA512_256", + null, attrs); + + // PBMAC1 ps("Mac", "PBEWithHmacSHA1", "com.sun.crypto.provider.PBMAC1Core$HmacSHA1", null, attrs); diff --git a/src/java.base/share/classes/java/security/KeyStore.java b/src/java.base/share/classes/java/security/KeyStore.java index acb34db2383..fb7e90fed8f 100644 --- a/src/java.base/share/classes/java/security/KeyStore.java +++ b/src/java.base/share/classes/java/security/KeyStore.java @@ -314,14 +314,7 @@ public class KeyStore { /** * Gets the name of the protection algorithm. * If none was set then the keystore provider will use its default - * protection algorithm. The name of the default protection algorithm - * for a given keystore type is set using the - * {@code 'keystore..keyProtectionAlgorithm'} security property. - * For example, the - * {@code keystore.PKCS12.keyProtectionAlgorithm} property stores the - * name of the default key protection algorithm used for PKCS12 - * keystores. If the security property is not set, an - * implementation-specific algorithm will be used. + * protection algorithm. * * @return the algorithm name, or {@code null} if none was set * @@ -1813,8 +1806,8 @@ public class KeyStore { } } - throw new KeyStoreException("This keystore does not support probing " - + "and must be loaded with a specified type"); + throw new KeyStoreException("Unrecognized keystore format. " + + "Please load it with a specified type"); } /** diff --git a/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java index 59d081bb56f..b696ee8d7bd 100644 --- a/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java +++ b/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java @@ -53,7 +53,6 @@ import java.util.*; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; import javax.crypto.spec.PBEParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; @@ -70,6 +69,7 @@ import sun.security.util.DerOutputStream; import sun.security.util.DerValue; import sun.security.util.ObjectIdentifier; import sun.security.pkcs.ContentInfo; +import sun.security.util.SecurityProperties; import sun.security.x509.AlgorithmId; import sun.security.pkcs.EncryptedPrivateKeyInfo; import sun.security.provider.JavaKeyStore.JKS; @@ -81,9 +81,11 @@ import sun.security.util.KeyStoreDelegator; * Implements the PKCS#12 PFX protected using the Password privacy mode. * The contents are protected using Password integrity mode. * - * Currently we support following PBE algorithms: - * - pbeWithSHAAnd3KeyTripleDESCBC to encrypt private keys - * - pbeWithSHAAnd40BitRC2CBC to encrypt certificates + * Currently these PBE algorithms are used by default: + * - PBEWithSHA1AndDESede to encrypt private keys, iteration count 50000. + * - PBEWithSHA1AndRC2_40 to encrypt certificates, iteration count 50000. + * + * The default Mac algorithm is HmacPBESHA1, iteration count 100000. * * Supported encryption of various implementations : * @@ -126,11 +128,7 @@ import sun.security.util.KeyStoreDelegator; * @author Jeff Nisewanger * @author Jan Luehe * - * @see KeyProtector * @see java.security.KeyStoreSpi - * @see KeyTool - * - * */ public final class PKCS12KeyStore extends KeyStoreSpi { @@ -143,14 +141,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { public static final int VERSION_3 = 3; - private static final String[] KEY_PROTECTION_ALGORITHM = { - "keystore.pkcs12.keyProtectionAlgorithm", - "keystore.PKCS12.keyProtectionAlgorithm" - }; - private static final int MAX_ITERATION_COUNT = 5000000; - private static final int PBE_ITERATION_COUNT = 50000; // default - private static final int MAC_ITERATION_COUNT = 100000; // default private static final int SALT_LEN = 20; // friendlyName, localKeyId, trustedKeyUsage @@ -171,10 +162,6 @@ public final class PKCS12KeyStore extends KeyStoreSpi { private static final int[] pkcs9certType = {1, 2, 840, 113549, 1, 9, 22, 1}; - private static final int[] pbeWithSHAAnd40BitRC2CBC = - {1, 2, 840, 113549, 1, 12, 1, 6}; - private static final int[] pbeWithSHAAnd3KeyTripleDESCBC = - {1, 2, 840, 113549, 1, 12, 1, 3}; private static final int[] pbes2 = {1, 2, 840, 113549, 1, 5, 13}; // TODO: temporary Oracle OID /* @@ -185,17 +172,15 @@ public final class PKCS12KeyStore extends KeyStoreSpi { {2, 16, 840, 1, 113894, 746875, 1, 1}; private static final int[] AnyExtendedKeyUsage = {2, 5, 29, 37, 0}; - private static ObjectIdentifier PKCS8ShroudedKeyBag_OID; - private static ObjectIdentifier CertBag_OID; - private static ObjectIdentifier SecretBag_OID; - private static ObjectIdentifier PKCS9FriendlyName_OID; - private static ObjectIdentifier PKCS9LocalKeyId_OID; - private static ObjectIdentifier PKCS9CertType_OID; - private static ObjectIdentifier pbeWithSHAAnd40BitRC2CBC_OID; - private static ObjectIdentifier pbeWithSHAAnd3KeyTripleDESCBC_OID; - private static ObjectIdentifier pbes2_OID; - private static ObjectIdentifier TrustedKeyUsage_OID; - private static ObjectIdentifier[] AnyUsage; + private static final ObjectIdentifier PKCS8ShroudedKeyBag_OID; + private static final ObjectIdentifier CertBag_OID; + private static final ObjectIdentifier SecretBag_OID; + private static final ObjectIdentifier PKCS9FriendlyName_OID; + private static final ObjectIdentifier PKCS9LocalKeyId_OID; + private static final ObjectIdentifier PKCS9CertType_OID; + private static final ObjectIdentifier pbes2_OID; + private static final ObjectIdentifier TrustedKeyUsage_OID; + private static final ObjectIdentifier[] AnyUsage; private int counter = 0; @@ -210,6 +195,17 @@ public final class PKCS12KeyStore extends KeyStoreSpi { // certificate count private int certificateCount = 0; + // Alg/params used for *this* keystore. Initialized as -1 for ic and + // null for algorithm names. When an existing file is read, they will be + // assigned inside engineLoad() so storing an existing keystore uses the + // old alg/params. This makes sure if a keystore is created password-less + // it will be password-less forever. Otherwise, engineStore() will read + // the default values. These fields are always reset when load() is called. + private String certProtectionAlgorithm = null; + private int certPbeIterationCount = -1; + private String macAlgorithm = null; + private int macIterationCount = -1; + // the source of randomness private SecureRandom random; @@ -221,16 +217,12 @@ public final class PKCS12KeyStore extends KeyStoreSpi { PKCS9FriendlyName_OID = new ObjectIdentifier(pkcs9Name); PKCS9LocalKeyId_OID = new ObjectIdentifier(pkcs9KeyId); PKCS9CertType_OID = new ObjectIdentifier(pkcs9certType); - pbeWithSHAAnd40BitRC2CBC_OID = - new ObjectIdentifier(pbeWithSHAAnd40BitRC2CBC); - pbeWithSHAAnd3KeyTripleDESCBC_OID = - new ObjectIdentifier(pbeWithSHAAnd3KeyTripleDESCBC); pbes2_OID = new ObjectIdentifier(pbes2); TrustedKeyUsage_OID = new ObjectIdentifier(TrustedKeyUsage); AnyUsage = new ObjectIdentifier[]{ new ObjectIdentifier(AnyExtendedKeyUsage)}; } catch (IOException ioe) { - // should not happen + throw new AssertionError("OID not initialized", ioe); } } @@ -391,7 +383,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { ic = pbeSpec.getIterationCount(); if (ic > MAX_ITERATION_COUNT) { - throw new IOException("PBE iteration count too large"); + throw new IOException("key PBE iteration count too large"); } } else { ic = 0; @@ -424,7 +416,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { if (debug != null) { debug.println("Retrieved a protected private key at alias" + " '" + alias + "' (" + - new AlgorithmId(algOid).getName() + + mapPBEParamsToAlgorithm(algOid, algParams) + " iterations: " + ic + ")"); } return tmp; @@ -449,7 +441,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { if (debug != null) { debug.println("Retrieved a protected secret key at alias " + "'" + alias + "' (" + - new AlgorithmId(algOid).getName() + + mapPBEParamsToAlgorithm(algOid, algParams) + " iterations: " + ic + ")"); } return tmp; @@ -701,7 +693,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { entries.put(alias.toLowerCase(Locale.ENGLISH), entry); } catch (Exception nsae) { - throw new KeyStoreException("Key protection " + + throw new KeyStoreException("Key protection" + " algorithm not found: " + nsae, nsae); } } @@ -801,14 +793,13 @@ public final class PKCS12KeyStore extends KeyStoreSpi { /* * Generate PBE Algorithm Parameters */ - private AlgorithmParameters getPBEAlgorithmParameters(String algorithm) - throws IOException - { + private AlgorithmParameters getPBEAlgorithmParameters( + String algorithm, int iterationCount) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = - new PBEParameterSpec(getSalt(), PBE_ITERATION_COUNT); + new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); @@ -871,13 +862,14 @@ public final class PKCS12KeyStore extends KeyStoreSpi { } /* - * Encrypt private key using Password-based encryption (PBE) + * Encrypt private key or secret key using Password-based encryption (PBE) * as defined in PKCS#5. * * NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is * used to derive the key and IV. * - * @return encrypted private key encoded as EncryptedPrivateKeyInfo + * @return encrypted private key or secret key encoded as + * EncryptedPrivateKeyInfo */ private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) @@ -899,27 +891,14 @@ public final class PKCS12KeyStore extends KeyStoreSpi { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(algParamSpec); } else { - algParams = getPBEAlgorithmParameters(algorithm); + algParams = getPBEAlgorithmParameters(algorithm, + defaultKeyPbeIterationCount()); } } else { // Check default key protection algorithm for PKCS12 keystores - algorithm = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - String prop = - Security.getProperty( - KEY_PROTECTION_ALGORITHM[0]); - if (prop == null) { - prop = Security.getProperty( - KEY_PROTECTION_ALGORITHM[1]); - } - return prop; - } - }); - if (algorithm == null || algorithm.isEmpty()) { - algorithm = "PBEWithSHA1AndDESede"; - } - algParams = getPBEAlgorithmParameters(algorithm); + algorithm = defaultKeyProtectionAlgorithm(); + algParams = getPBEAlgorithmParameters(algorithm, + defaultKeyPbeIterationCount()); } ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm); @@ -977,7 +956,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { if (algorithm.equals(pbes2_OID) && algParams != null) { return algParams.toString(); } - return algorithm.toString(); + return new AlgorithmId(algorithm).getName(); } /** @@ -1209,10 +1188,6 @@ public final class PKCS12KeyStore extends KeyStoreSpi { public synchronized void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { - // password is mandatory when storing - if (password == null) { - throw new IllegalArgumentException("password can't be null"); - } // -- Create PFX DerOutputStream pfx = new DerOutputStream(); @@ -1245,16 +1220,28 @@ public final class PKCS12KeyStore extends KeyStoreSpi { // -- create EncryptedContentInfo if (certificateCount > 0) { + if (certProtectionAlgorithm == null) { + certProtectionAlgorithm = defaultCertProtectionAlgorithm(); + } + if (certPbeIterationCount < 0) { + certPbeIterationCount = defaultCertPbeIterationCount(); + } + if (debug != null) { debug.println("Storing " + certificateCount + " certificate(s) in a PKCS#7 encryptedData"); } byte[] encrData = createEncryptedData(password); - ContentInfo encrContentInfo = - new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID, + if (!certProtectionAlgorithm.equalsIgnoreCase("NONE")) { + ContentInfo encrContentInfo = + new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID, new DerValue(encrData)); - encrContentInfo.encode(authSafeContentInfo); + encrContentInfo.encode(authSafeContentInfo); + } else { + ContentInfo dataContentInfo = new ContentInfo(encrData); + dataContentInfo.encode(authSafeContentInfo); + } } // wrap as SequenceOf ContentInfos @@ -1269,9 +1256,16 @@ public final class PKCS12KeyStore extends KeyStoreSpi { pfx.write(authSafeData); // -- MAC - byte[] macData = calculateMac(password, authenticatedSafe); - pfx.write(macData); - + if (macAlgorithm == null) { + macAlgorithm = defaultMacAlgorithm(); + } + if (macIterationCount < 0) { + macIterationCount = defaultMacIterationCount(); + } + if (!macAlgorithm.equalsIgnoreCase("NONE")) { + byte[] macData = calculateMac(password, authenticatedSafe); + pfx.write(macData); + } // write PFX to output stream DerOutputStream pfxout = new DerOutputStream(); pfxout.write(DerValue.tag_Sequence, pfx); @@ -1481,24 +1475,6 @@ public final class PKCS12KeyStore extends KeyStoreSpi { return entry.attributes; } - /* - * Generate Hash. - */ - private byte[] generateHash(byte[] data) throws IOException - { - byte[] digest = null; - - try { - MessageDigest md = MessageDigest.getInstance("SHA1"); - md.update(data); - digest = md.digest(); - } catch (Exception e) { - throw new IOException("generateHash failed: " + e, e); - } - return digest; - } - - /* * Calculate MAC using HMAC algorithm (required for password integrity) * @@ -1509,16 +1485,16 @@ public final class PKCS12KeyStore extends KeyStoreSpi { throws IOException { byte[] mData = null; - String algName = "SHA1"; + String algName = macAlgorithm.substring(7); try { // Generate a random salt. byte[] salt = getSalt(); // generate MAC (MAC key is generated within JCE) - Mac m = Mac.getInstance("HmacPBESHA1"); + Mac m = Mac.getInstance(macAlgorithm); PBEParameterSpec params = - new PBEParameterSpec(salt, MAC_ITERATION_COUNT); + new PBEParameterSpec(salt, macIterationCount); SecretKey key = getPBEKey(passwd); m.init(key, params); m.update(data); @@ -1526,7 +1502,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { // encode as MacData MacData macData = new MacData(algName, macResult, salt, - MAC_ITERATION_COUNT); + macIterationCount); DerOutputStream bytes = new DerOutputStream(); bytes.write(macData.getEncoded()); mData = bytes.toByteArray(); @@ -1799,15 +1775,19 @@ public final class PKCS12KeyStore extends KeyStoreSpi { byte[] safeBagData = safeBagValue.toByteArray(); // encrypt the content (EncryptedContentInfo) - byte[] encrContentInfo = encryptContent(safeBagData, password); + if (!certProtectionAlgorithm.equalsIgnoreCase("NONE")) { + byte[] encrContentInfo = encryptContent(safeBagData, password); - // -- SEQUENCE of EncryptedData - DerOutputStream encrData = new DerOutputStream(); - DerOutputStream encrDataContent = new DerOutputStream(); - encrData.putInteger(0); - encrData.write(encrContentInfo); - encrDataContent.write(DerValue.tag_Sequence, encrData); - return encrDataContent.toByteArray(); + // -- SEQUENCE of EncryptedData + DerOutputStream encrData = new DerOutputStream(); + DerOutputStream encrDataContent = new DerOutputStream(); + encrData.putInteger(0); + encrData.write(encrContentInfo); + encrDataContent.write(DerValue.tag_Sequence, encrData); + return encrDataContent.toByteArray(); + } else { + return safeBagData; + } } /* @@ -1916,47 +1896,52 @@ public final class PKCS12KeyStore extends KeyStoreSpi { byte[] encryptedData = null; - // create AlgorithmParameters - AlgorithmParameters algParams = - getPBEAlgorithmParameters("PBEWithSHA1AndRC2_40"); - DerOutputStream bytes = new DerOutputStream(); - AlgorithmId algId = - new AlgorithmId(pbeWithSHAAnd40BitRC2CBC_OID, algParams); - algId.encode(bytes); - byte[] encodedAlgId = bytes.toByteArray(); try { + // create AlgorithmParameters + AlgorithmParameters algParams = getPBEAlgorithmParameters( + certProtectionAlgorithm, certPbeIterationCount); + DerOutputStream bytes = new DerOutputStream(); + // Use JCE SecretKey skey = getPBEKey(password); - Cipher cipher = Cipher.getInstance("PBEWithSHA1AndRC2_40"); + Cipher cipher = Cipher.getInstance(certProtectionAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, skey, algParams); encryptedData = cipher.doFinal(data); + AlgorithmId algId = new AlgorithmId( + mapPBEAlgorithmToOID(certProtectionAlgorithm), + cipher.getParameters()); + // cipher.getParameters() now has IV + algId.encode(bytes); + byte[] encodedAlgId = bytes.toByteArray(); + if (debug != null) { debug.println(" (Cipher algorithm: " + cipher.getAlgorithm() + - ")"); + ")"); } + // create EncryptedContentInfo + DerOutputStream bytes2 = new DerOutputStream(); + bytes2.putOID(ContentInfo.DATA_OID); + bytes2.write(encodedAlgId); + + // Wrap encrypted data in a context-specific tag. + DerOutputStream tmpout2 = new DerOutputStream(); + tmpout2.putOctetString(encryptedData); + bytes2.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT, + false, (byte) 0), tmpout2); + + // wrap EncryptedContentInfo in a Sequence + DerOutputStream out = new DerOutputStream(); + out.write(DerValue.tag_Sequence, bytes2); + return out.toByteArray(); + } catch (IOException ioe) { + throw ioe; } catch (Exception e) { throw new IOException("Failed to encrypt" + " safe contents entry: " + e, e); } - - // create EncryptedContentInfo - DerOutputStream bytes2 = new DerOutputStream(); - bytes2.putOID(ContentInfo.DATA_OID); - bytes2.write(encodedAlgId); - - // Wrap encrypted data in a context-specific tag. - DerOutputStream tmpout2 = new DerOutputStream(); - tmpout2.putOctetString(encryptedData); - bytes2.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT, - false, (byte)0), tmpout2); - - // wrap EncryptedContentInfo in a Sequence - DerOutputStream out = new DerOutputStream(); - out.write(DerValue.tag_Sequence, bytes2); - return out.toByteArray(); } /** @@ -1979,10 +1964,12 @@ public final class PKCS12KeyStore extends KeyStoreSpi { public synchronized void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { - DataInputStream dis; - CertificateFactory cf = null; - ByteArrayInputStream bais = null; - byte[] encoded = null; + + // Reset config when loading a different keystore. + certProtectionAlgorithm = null; + certPbeIterationCount = -1; + macAlgorithm = null; + macIterationCount = -1; if (stream == null) return; @@ -2022,6 +2009,8 @@ public final class PKCS12KeyStore extends KeyStoreSpi { secretKeyCount = 0; certificateCount = 0; + boolean seeEncBag = false; + /* * Spin over the ContentInfos. */ @@ -2047,6 +2036,21 @@ public final class PKCS12KeyStore extends KeyStoreSpi { debug.println("Warning: skipping PKCS#7 encryptedData" + " - no password was supplied"); } + // No password to decrypt ENCRYPTED_DATA_OID. *Skip it*. + // This means user will see a PrivateKeyEntry without + // certificates and a whole TrustedCertificateEntry will + // be lost. This is not a perfect solution but alternative + // solutions are more disruptive: + // + // We cannot just fail, since KeyStore.load(is, null) + // has been known to never fail because of a null password. + // + // We cannot just throw away the whole PrivateKeyEntry, + // this is too silent and no one will notice anything. + // + // We also cannot fail when getCertificate() on such a + // PrivateKeyEntry is called, since the method has not + // specified this behavior. continue; } @@ -2084,13 +2088,18 @@ public final class PKCS12KeyStore extends KeyStoreSpi { ic = pbeSpec.getIterationCount(); if (ic > MAX_ITERATION_COUNT) { - throw new IOException("PBE iteration count too large"); + throw new IOException("cert PBE iteration count too large"); } + + certProtectionAlgorithm + = mapPBEParamsToAlgorithm(algOid, algParams); + certPbeIterationCount = ic; + seeEncBag = true; } if (debug != null) { debug.println("Loading PKCS#7 encryptedData " + - "(" + new AlgorithmId(algOid).getName() + + "(" + mapPBEParamsToAlgorithm(algOid, algParams) + " iterations: " + ic + ")"); } @@ -2115,48 +2124,62 @@ public final class PKCS12KeyStore extends KeyStoreSpi { } } + // No ENCRYPTED_DATA_OID but see certificate. Must be passwordless. + if (!seeEncBag && certificateCount > 0) { + certProtectionAlgorithm = "NONE"; + } + // The MacData is optional. - if (password != null && s.available() > 0) { - MacData macData = new MacData(s); - int ic = macData.getIterations(); + if (s.available() > 0) { + // If there is no password, we cannot fail. KeyStore.load(is, null) + // has been known to never fail because of a null password. + if (password != null) { + MacData macData = new MacData(s); + int ic = macData.getIterations(); - try { - if (ic > MAX_ITERATION_COUNT) { - throw new InvalidAlgorithmParameterException( - "MAC iteration count too large: " + ic); + try { + if (ic > MAX_ITERATION_COUNT) { + throw new InvalidAlgorithmParameterException( + "MAC iteration count too large: " + ic); + } + + String algName = + macData.getDigestAlgName().toUpperCase(Locale.ENGLISH); + + // Change SHA-1 to SHA1 + algName = algName.replace("-", ""); + + macAlgorithm = "HmacPBE" + algName; + macIterationCount = ic; + + // generate MAC (MAC key is created within JCE) + Mac m = Mac.getInstance(macAlgorithm); + PBEParameterSpec params = + new PBEParameterSpec(macData.getSalt(), ic); + + RetryWithZero.run(pass -> { + SecretKey key = getPBEKey(pass); + m.init(key, params); + m.update(authSafeData); + byte[] macResult = m.doFinal(); + + if (debug != null) { + debug.println("Checking keystore integrity " + + "(" + m.getAlgorithm() + " iterations: " + ic + ")"); + } + + if (!MessageDigest.isEqual(macData.getDigest(), macResult)) { + throw new UnrecoverableKeyException("Failed PKCS12" + + " integrity checking"); + } + return (Void) null; + }, password); + } catch (Exception e) { + throw new IOException("Integrity check failed: " + e, e); } - - String algName = - macData.getDigestAlgName().toUpperCase(Locale.ENGLISH); - - // Change SHA-1 to SHA1 - algName = algName.replace("-", ""); - - // generate MAC (MAC key is created within JCE) - Mac m = Mac.getInstance("HmacPBE" + algName); - PBEParameterSpec params = - new PBEParameterSpec(macData.getSalt(), ic); - - RetryWithZero.run(pass -> { - SecretKey key = getPBEKey(pass); - m.init(key, params); - m.update(authSafeData); - byte[] macResult = m.doFinal(); - - if (debug != null) { - debug.println("Checking keystore integrity " + - "(" + m.getAlgorithm() + " iterations: " + ic + ")"); - } - - if (!MessageDigest.isEqual(macData.getDigest(), macResult)) { - throw new UnrecoverableKeyException("Failed PKCS12" + - " integrity checking"); - } - return (Void)null; - }, password); - } catch (Exception e) { - throw new IOException("Integrity check failed: " + e, e); } + } else { + macAlgorithm = "NONE"; } /* @@ -2196,8 +2219,14 @@ public final class PKCS12KeyStore extends KeyStoreSpi { cert = certsMap.get(issuerDN); } /* Update existing KeyEntry in entries table */ - if (chain.size() > 0) + if (chain.size() > 0) { entry.chain = chain.toArray(new Certificate[chain.size()]); + } else { + // Remove private key entries where there is no associated + // certs. Most likely the keystore is loaded with a null + // password. + entries.remove(entry); + } } } @@ -2221,6 +2250,46 @@ public final class PKCS12KeyStore extends KeyStoreSpi { keyList.clear(); } + /** + * Returns if a pkcs12 file is password-less. This means no cert is + * encrypted and there is no Mac. Please note that the private key + * can be encrypted. + * + * This is a simplified version of {@link #engineLoad} that only looks + * at the ContentInfo types. + * + * @param f the pkcs12 file + * @return if it's password-less + * @throws IOException + */ + public static boolean isPasswordless(File f) throws IOException { + + try (FileInputStream stream = new FileInputStream(f)) { + DerValue val = new DerValue(stream); + DerInputStream s = val.toDerInputStream(); + + s.getInteger(); // skip version + + ContentInfo authSafe = new ContentInfo(s); + DerInputStream as = new DerInputStream(authSafe.getData()); + for (DerValue seq : as.getSequence(2)) { + DerInputStream sci = new DerInputStream(seq.toByteArray()); + ContentInfo safeContents = new ContentInfo(sci); + if (safeContents.getContentType() + .equals(ContentInfo.ENCRYPTED_DATA_OID)) { + // Certificate encrypted + return false; + } + } + + if (s.available() > 0) { + // The MacData exists. + return false; + } + } + return true; + } + /** * Locates a matched CertEntry from certEntries, and returns its cert. * @param entry the KeyEntry to match @@ -2368,8 +2437,8 @@ public final class PKCS12KeyStore extends KeyStoreSpi { if (bagItem instanceof KeyEntry) { KeyEntry entry = (KeyEntry)bagItem; - if (bagItem instanceof PrivateKeyEntry) { - if (keyId == null) { + if (keyId == null) { + if (bagItem instanceof PrivateKeyEntry) { // Insert a localKeyID for the privateKey // Note: This is a workaround to allow null localKeyID // attribute in pkcs12 with one private key entry and @@ -2379,6 +2448,9 @@ public final class PKCS12KeyStore extends KeyStoreSpi { } else { continue; } + } else { + // keyId in a SecretKeyEntry is not significant + keyId = "00".getBytes("UTF8"); } } entry.keyId = keyId; @@ -2518,4 +2590,83 @@ public final class PKCS12KeyStore extends KeyStoreSpi { return result; } + + // 8076190: Customizing the generation of a PKCS12 keystore + + private static String defaultCertProtectionAlgorithm() { + String result = SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.certProtectionAlgorithm"); + return (result != null && !result.isEmpty()) + ? result : "PBEWithSHA1AndRC2_40"; + } + + private static int defaultCertPbeIterationCount() { + String result = SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.certPbeIterationCount"); + return (result != null && !result.isEmpty()) + ? string2IC("certPbeIterationCount", result) : 50000; + } + + // Read both "keystore.pkcs12.keyProtectionAlgorithm" and + // "keystore.PKCS12.keyProtectionAlgorithm" for compatibility. + private static String defaultKeyProtectionAlgorithm() { + String result = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + String result; + String name1 = "keystore.pkcs12.keyProtectionAlgorithm"; + String name2 = "keystore.PKCS12.keyProtectionAlgorithm"; + result = System.getProperty(name1); + if (result != null) { + return result; + } + result = System.getProperty(name2); + if (result != null) { + return result; + } + result = Security.getProperty(name1); + if (result != null) { + return result; + } + return Security.getProperty(name2); + } + }); + return (result != null && !result.isEmpty()) + ? result : "PBEWithSHA1AndDESede"; + } + + private static int defaultKeyPbeIterationCount() { + String result = SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.keyPbeIterationCount"); + return (result != null && !result.isEmpty()) + ? string2IC("keyPbeIterationCount", result) : 50000; + } + + private static String defaultMacAlgorithm() { + String result = SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.macAlgorithm"); + return (result != null && !result.isEmpty()) + ? result : "HmacPBESHA1"; + } + + private static int defaultMacIterationCount() { + String result = SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.macIterationCount"); + return (result != null && !result.isEmpty()) + ? string2IC("macIterationCount", result) : 100000; + } + + private static int string2IC(String type, String value) { + int number; + try { + number = Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("keystore.pkcs12." + type + + " is not a number: " + value); + } + if (number <= 0 || number > MAX_ITERATION_COUNT) { + throw new IllegalArgumentException("Invalid keystore.pkcs12." + + type + ": " + value); + } + return number; + } } diff --git a/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/src/java.base/share/classes/sun/security/tools/keytool/Main.java index 8cbeb43fb80..295df6e5a56 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -70,6 +70,7 @@ import java.security.cert.X509CRLSelector; import javax.security.auth.x500.X500Principal; import java.util.Base64; +import sun.security.pkcs12.PKCS12KeyStore; import sun.security.util.ECKeySizeParameterSpec; import sun.security.util.KeyUtil; import sun.security.util.NamedCurve; @@ -79,6 +80,7 @@ import sun.security.pkcs10.PKCS10Attribute; import sun.security.provider.X509Factory; import sun.security.provider.certpath.ssl.SSLServerCertStore; import sun.security.util.Password; +import sun.security.util.SecurityProperties; import sun.security.util.SecurityProviderConstants; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; @@ -188,6 +190,7 @@ public final class Main { private static final Set SIG_PRIMITIVE_SET = Collections .unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE)); + private boolean isPasswordlessKeyStore = false; enum Command { CERTREQ("Generates.a.certificate.request", @@ -919,6 +922,9 @@ public final class Main { storetype == null && !inplaceImport) { keyStore = KeyStore.getInstance(ksfile, storePass); storetype = keyStore.getType(); + if (storetype.equalsIgnoreCase("pkcs12")) { + isPasswordlessKeyStore = PKCS12KeyStore.isPasswordless(ksfile); + } } else { if (storetype == null) { storetype = KeyStore.getDefaultType(); @@ -928,6 +934,15 @@ public final class Main { } else { keyStore = KeyStore.getInstance(storetype, providerName); } + // When creating a new pkcs12 file, Do not prompt for storepass + // if certProtectionAlgorithm and macAlgorithm are both NONE. + if (storetype.equalsIgnoreCase("pkcs12")) { + isPasswordlessKeyStore = + "NONE".equals(SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.certProtectionAlgorithm")) + && "NONE".equals(SecurityProperties.privilegedGetOverridable( + "keystore.pkcs12.macAlgorithm")); + } /* * Load the keystore data. @@ -979,11 +994,10 @@ public final class Main { ("Keystore.password.must.be.at.least.6.characters")); } } else if (storePass == null) { - - // only prompt if (protectedPath == false) - - if (!protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) && - (command == CERTREQ || + if (!protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) + && isKeyStoreRelated(command) + && !isPasswordlessKeyStore) { + if (command == CERTREQ || command == DELETE || command == GENKEYPAIR || command == GENSECKEY || @@ -995,59 +1009,58 @@ public final class Main { command == SELFCERT || command == STOREPASSWD || command == KEYPASSWD || - command == IDENTITYDB)) { - int count = 0; - do { - if (command == IMPORTKEYSTORE) { - System.err.print - (rb.getString("Enter.destination.keystore.password.")); - } else { - System.err.print - (rb.getString("Enter.keystore.password.")); - } - System.err.flush(); - storePass = Password.readPassword(System.in); - passwords.add(storePass); + command == IDENTITYDB) { + int count = 0; + do { + if (command == IMPORTKEYSTORE) { + System.err.print + (rb.getString("Enter.destination.keystore.password.")); + } else { + System.err.print + (rb.getString("Enter.keystore.password.")); + } + System.err.flush(); + storePass = Password.readPassword(System.in); + passwords.add(storePass); - // If we are creating a new non nullStream-based keystore, - // insist that the password be at least 6 characters - if (!nullStream && (storePass == null || storePass.length < 6)) { - System.err.println(rb.getString - ("Keystore.password.is.too.short.must.be.at.least.6.characters")); - storePass = null; - } - - // If the keystore file does not exist and needs to be - // created, the storepass should be prompted twice. - if (storePass != null && !nullStream && ksStream == null) { - System.err.print(rb.getString("Re.enter.new.password.")); - char[] storePassAgain = Password.readPassword(System.in); - passwords.add(storePassAgain); - if (!Arrays.equals(storePass, storePassAgain)) { - System.err.println - (rb.getString("They.don.t.match.Try.again")); + // If we are creating a new non nullStream-based keystore, + // insist that the password be at least 6 characters + if (!nullStream && (storePass == null || storePass.length < 6)) { + System.err.println(rb.getString + ("Keystore.password.is.too.short.must.be.at.least.6.characters")); storePass = null; } + + // If the keystore file does not exist and needs to be + // created, the storepass should be prompted twice. + if (storePass != null && !nullStream && ksStream == null) { + System.err.print(rb.getString("Re.enter.new.password.")); + char[] storePassAgain = Password.readPassword(System.in); + passwords.add(storePassAgain); + if (!Arrays.equals(storePass, storePassAgain)) { + System.err.println + (rb.getString("They.don.t.match.Try.again")); + storePass = null; + } + } + + count++; + } while ((storePass == null) && count < 3); + + + if (storePass == null) { + System.err.println + (rb.getString("Too.many.failures.try.later")); + return; + } + } else { + // here we have EXPORTCERT and LIST (info valid until STOREPASSWD) + if (command != PRINTCRL) { + System.err.print(rb.getString("Enter.keystore.password.")); + System.err.flush(); + storePass = Password.readPassword(System.in); + passwords.add(storePass); } - - count++; - } while ((storePass == null) && count < 3); - - - if (storePass == null) { - System.err.println - (rb.getString("Too.many.failures.try.later")); - return; - } - } else if (!protectedPath - && !KeyStoreUtil.isWindowsKeyStore(storetype) - && isKeyStoreRelated(command)) { - // here we have EXPORTCERT and LIST (info valid until STOREPASSWD) - if (command != PRINTCRL) { - System.err.print(rb.getString("Enter.keystore.password.")); - System.err.flush(); - storePass = Password.readPassword(System.in); - passwords.add(storePass); } } @@ -1233,7 +1246,8 @@ public final class Main { kssave = true; } else if (command == LIST) { if (storePass == null - && !KeyStoreUtil.isWindowsKeyStore(storetype)) { + && !KeyStoreUtil.isWindowsKeyStore(storetype) + && !isPasswordlessKeyStore) { printNoIntegrityWarning(); } @@ -1602,7 +1616,8 @@ public final class Main { throws Exception { if (storePass == null - && !KeyStoreUtil.isWindowsKeyStore(storetype)) { + && !KeyStoreUtil.isWindowsKeyStore(storetype) + && !isPasswordlessKeyStore) { printNoIntegrityWarning(); } if (alias == null) { @@ -1633,7 +1648,7 @@ public final class Main { * @param origPass the password to copy from if user press ENTER */ private char[] promptForKeyPass(String alias, String orig, char[] origPass) throws Exception{ - if (P12KEYSTORE.equalsIgnoreCase(storetype)) { + if (origPass != null && P12KEYSTORE.equalsIgnoreCase(storetype)) { return origPass; } else if (!token && !protectedPath) { // Prompt for key password @@ -1642,22 +1657,25 @@ public final class Main { MessageFormat form = new MessageFormat(rb.getString ("Enter.key.password.for.alias.")); Object[] source = {alias}; - System.err.println(form.format(source)); - if (orig == null) { - System.err.print(rb.getString - (".RETURN.if.same.as.keystore.password.")); - } else { - form = new MessageFormat(rb.getString - (".RETURN.if.same.as.for.otherAlias.")); - Object[] src = {orig}; - System.err.print(form.format(src)); + System.err.print(form.format(source)); + if (origPass != null) { + System.err.println(); + if (orig == null) { + System.err.print(rb.getString + (".RETURN.if.same.as.keystore.password.")); + } else { + form = new MessageFormat(rb.getString + (".RETURN.if.same.as.for.otherAlias.")); + Object[] src = {orig}; + System.err.print(form.format(src)); + } } System.err.flush(); char[] entered = Password.readPassword(System.in); passwords.add(entered); - if (entered == null) { + if (entered == null && origPass != null) { return origPass; - } else if (entered.length >= 6) { + } else if (entered != null && entered.length >= 6) { System.err.print(rb.getString("Re.enter.new.password.")); char[] passAgain = Password.readPassword(System.in); passwords.add(passAgain); @@ -2066,6 +2084,9 @@ public final class Main { getCertFingerPrint("SHA-256", chain[0])); checkWeak(label, chain); } + } else { + out.println(rb.getString + ("Certificate.chain.length.") + 0); } } else if (keyStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) { @@ -2130,6 +2151,7 @@ public final class Main { InputStream is = null; File srcksfile = null; + boolean srcIsPasswordless = false; if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) || KeyStoreUtil.isWindowsKeyStore(srcstoretype)) { @@ -2151,6 +2173,9 @@ public final class Main { srcstoretype == null) { store = KeyStore.getInstance(srcksfile, srcstorePass); srcstoretype = store.getType(); + if (srcstoretype.equalsIgnoreCase("pkcs12")) { + srcIsPasswordless = PKCS12KeyStore.isPasswordless(srcksfile); + } } else { if (srcstoretype == null) { srcstoretype = KeyStore.getDefaultType(); @@ -2164,7 +2189,8 @@ public final class Main { if (srcstorePass == null && !srcprotectedPath - && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) { + && !KeyStoreUtil.isWindowsKeyStore(srcstoretype) + && !srcIsPasswordless) { System.err.print(rb.getString("Enter.source.keystore.password.")); System.err.flush(); srcstorePass = Password.readPassword(System.in); @@ -2191,6 +2217,7 @@ public final class Main { } if (srcstorePass == null + && !srcIsPasswordless && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) { // anti refactoring, copied from printNoIntegrityWarning(), // but change 2 lines @@ -3537,25 +3564,25 @@ public final class Main { if (keyPass == null) { // Try to recover the key using the keystore password - try { - key = keyStore.getKey(alias, storePass); - - keyPass = storePass; - passwords.add(keyPass); - } catch (UnrecoverableKeyException e) { - // Did not work out, so prompt user for key password - if (!token) { - keyPass = getKeyPasswd(alias, null, null); - key = keyStore.getKey(alias, keyPass); - } else { - throw e; + if (storePass != null) { + try { + key = keyStore.getKey(alias, storePass); + passwords.add(storePass); + return Pair.of(key, storePass); + } catch (UnrecoverableKeyException e) { + if (token) { + throw e; + } } } + // prompt user for key password + keyPass = getKeyPasswd(alias, null, null); + key = keyStore.getKey(alias, keyPass); + return Pair.of(key, keyPass); } else { key = keyStore.getKey(alias, keyPass); + return Pair.of(key, keyPass); } - - return Pair.of(key, keyPass); } /** @@ -3570,68 +3597,59 @@ public final class Main { char[] pstore, char[] pkey) throws Exception { - if (ks.containsAlias(alias) == false) { - MessageFormat form = new MessageFormat - (rb.getString("Alias.alias.does.not.exist")); + if (!ks.containsAlias(alias)) { + MessageFormat form = new MessageFormat( + rb.getString("Alias.alias.does.not.exist")); Object[] source = {alias}; throw new Exception(form.format(source)); } - PasswordProtection pp = null; - Entry entry; - + // Step 1: First attempt to access entry without key password + // (PKCS11 entry or trusted certificate entry, for example). + // If fail, go next. try { - // First attempt to access entry without key password - // (PKCS11 entry or trusted certificate entry, for example) - - entry = ks.getEntry(alias, pp); - pkey = null; + Entry entry = ks.getEntry(alias, null); + return Pair.of(entry, null); } catch (UnrecoverableEntryException une) { - if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) || - KeyStoreUtil.isWindowsKeyStore(ks.getType())) { + KeyStoreUtil.isWindowsKeyStore(ks.getType())) { // should not happen, but a possibility throw une; } + } - // entry is protected + // entry is protected - if (pkey != null) { + // Step 2: try pkey if not null. If fail, fail. + if (pkey != null) { + PasswordProtection pp = new PasswordProtection(pkey); + Entry entry = ks.getEntry(alias, pp); + return Pair.of(entry, pkey); + } - // try provided key password - - pp = new PasswordProtection(pkey); - entry = ks.getEntry(alias, pp); - - } else { - - // try store pass - - try { - pp = new PasswordProtection(pstore); - entry = ks.getEntry(alias, pp); - pkey = pstore; - } catch (UnrecoverableEntryException une2) { - if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) { - - // P12 keystore currently does not support separate - // store and entry passwords - - throw une2; - } else { - - // prompt for entry password - - pkey = getKeyPasswd(alias, null, null); - pp = new PasswordProtection(pkey); - entry = ks.getEntry(alias, pp); - } + // Step 3: try pstore if not null. If fail, go next. + if (pstore != null) { + try { + PasswordProtection pp = new PasswordProtection(pstore); + Entry entry = ks.getEntry(alias, pp); + return Pair.of(entry, pstore); + } catch (UnrecoverableEntryException une) { + if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) { + // P12 keystore currently does not support separate + // store and entry passwords. We will not prompt for + // entry password. + throw une; } } } + // Step 4: prompt for entry password + pkey = getKeyPasswd(alias, null, null); + PasswordProtection pp = new PasswordProtection(pkey); + Entry entry = ks.getEntry(alias, pp); return Pair.of(entry, pkey); } + /** * Gets the requested finger print of the certificate. */ diff --git a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index ffb0974df8b..825e4ffb81e 100644 --- a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -771,8 +771,14 @@ public class AlgorithmId implements Serializable, DerEncoder { ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 10}); public static final ObjectIdentifier pbeWithSHA1AndRC2_oid = ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 11}); + public static ObjectIdentifier pbeWithSHA1AndRC4_128_oid = + ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 1}); + public static ObjectIdentifier pbeWithSHA1AndRC4_40_oid = + ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 2}); public static ObjectIdentifier pbeWithSHA1AndDESede_oid = ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 3}); + public static ObjectIdentifier pbeWithSHA1AndRC2_128_oid = + ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 5}); public static ObjectIdentifier pbeWithSHA1AndRC2_40_oid = ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 6}); @@ -961,7 +967,10 @@ public class AlgorithmId implements Serializable, DerEncoder { nameTable.put(pbeWithMD5AndRC2_oid, "PBEWithMD5AndRC2"); nameTable.put(pbeWithSHA1AndDES_oid, "PBEWithSHA1AndDES"); nameTable.put(pbeWithSHA1AndRC2_oid, "PBEWithSHA1AndRC2"); + nameTable.put(pbeWithSHA1AndRC4_128_oid, "PBEWithSHA1AndRC4_128"); + nameTable.put(pbeWithSHA1AndRC4_40_oid, "PBEWithSHA1AndRC4_40"); nameTable.put(pbeWithSHA1AndDESede_oid, "PBEWithSHA1AndDESede"); + nameTable.put(pbeWithSHA1AndRC2_128_oid, "PBEWithSHA1AndRC2_128"); nameTable.put(pbeWithSHA1AndRC2_40_oid, "PBEWithSHA1AndRC2_40"); } diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index afa12fa91a6..78521fdb861 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -1060,6 +1060,77 @@ jdk.xml.dsig.secureValidationPolicy=\ jceks.key.serialFilter = java.base/java.lang.Enum;java.base/java.security.KeyRep;\ java.base/java.security.KeyRep$Type;java.base/javax.crypto.spec.SecretKeySpec;!* +# +# PKCS12 KeyStore properties +# +# The following properties, if configured, are used by the PKCS12 KeyStore +# implementation during the creation of a new keystore. Several of the +# properties may also be used when modifying an existing keystore. The +# properties can be overridden by a KeyStore API that specifies its own +# algorithms and parameters. +# +# If an existing PKCS12 keystore is loaded and then stored, the algorithm and +# parameter used to generate the existing Mac will be reused. If the existing +# keystore does not have a Mac, no Mac will be created while storing. If there +# is at least one certificate in the existing keystore, the algorithm and +# parameters used to encrypt the last certificate in the existing keystore will +# be reused to encrypt all certificates while storing. If the last certificate +# in the existing keystore is not encrypted, all certificates will be stored +# unencrypted. If there is no certificate in the existing keystore, any newly +# added certificate will be encrypted (or stored unencrypted if algorithm +# value is "NONE") using the "keystore.pkcs12.certProtectionAlgorithm" and +# "keystore.pkcs12.certPbeIterationCount" values defined here. Existing private +# and secret key(s) are not changed. Newly set private and secret key(s) will +# be encrypted using the "keystore.pkcs12.keyProtectionAlgorithm" and +# "keystore.pkcs12.keyPbeIterationCount" values defined here. +# +# In order to apply new algorithms and parameters to all entries in an +# existing keystore, one can create a new keystore and add entries in the +# existing keystore into the new keystore. This can be achieved by calling the +# "keytool -importkeystore" command. +# +# If a system property of the same name is also specified, it supersedes the +# security property value defined here. +# +# If the property is set to an illegal value, +# an iteration count that is not a positive integer, or an unknown algorithm +# name, an exception will be thrown when the property is used. +# If the property is not set or empty, a default value will be used. +# +# Note: These properties are currently used by the JDK Reference implementation. +# They are not guaranteed to be examined and used by other implementations. + +# The algorithm used to encrypt a certificate. This can be any non-Hmac PBE +# algorithm defined in the Cipher section of the Java Security Standard +# Algorithm Names Specification. When set to "NONE", the certificate +# is not encrypted. The default value is "PBEWithSHA1AndRC2_40". +#keystore.pkcs12.certProtectionAlgorithm = PBEWithSHA1AndRC2_40 + +# The iteration count used by the PBE algorithm when encrypting a certificate. +# This value must be a positive integer. The default value is 50000. +#keystore.pkcs12.certPbeIterationCount = 50000 + +# The algorithm used to encrypt a private key or secret key. This can be +# any non-Hmac PBE algorithm defined in the Cipher section of the Java +# Security Standard Algorithm Names Specification. The value must not be "NONE". +# The default value is "PBEWithSHA1AndDESede". +#keystore.pkcs12.keyProtectionAlgorithm = PBEWithSHA1AndDESede + +# The iteration count used by the PBE algorithm when encrypting a private key +# or a secret key. This value must be a positive integer. The default value +# is 50000. +#keystore.pkcs12.keyPbeIterationCount = 50000 + +# The algorithm used to calculate the optional MacData at the end of a PKCS12 +# file. This can be any HmacPBE algorithm defined in the Mac section of the +# Java Security Standard Algorithm Names Specification. When set to "NONE", +# no Mac is generated. The default value is "HmacPBESHA1". +#keystore.pkcs12.macAlgorithm = HmacPBESHA1 + +# The iteration count used by the MacData algorithm. This value must be a +# positive integer. The default value is 100000. +#keystore.pkcs12.macIterationCount = 100000 + # # Enhanced exception message information # diff --git a/test/jdk/sun/security/pkcs12/ParamsPreferences.java b/test/jdk/sun/security/pkcs12/ParamsPreferences.java new file mode 100644 index 00000000000..6069c64957e --- /dev/null +++ b/test/jdk/sun/security/pkcs12/ParamsPreferences.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.SecurityTools; +import sun.security.util.ObjectIdentifier; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static jdk.test.lib.security.DerUtils.*; +import static sun.security.pkcs.ContentInfo.DATA_OID; +import static sun.security.pkcs.ContentInfo.ENCRYPTED_DATA_OID; +import static sun.security.x509.AlgorithmId.*; + +/* + * @test + * @bug 8076190 + * @library /test/lib + * @modules java.base/sun.security.pkcs + * java.base/sun.security.x509 + * java.base/sun.security.util + * @summary Checks the preferences order of pkcs12 params + */ +public class ParamsPreferences { + + public static final void main(String[] args) throws Exception { + int c = 0; + + // with storepass + test(c++, "-", "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndDESede_oid, 50000, + SHA_oid, 100000); + + // password-less with system property + test(c++, "keystore.pkcs12.certProtectionAlgorithm", "NONE", + "keystore.pkcs12.macAlgorithm", "NONE", + "-", "-", + null, 0, + pbeWithSHA1AndDESede_oid, 50000, + null, 0); + + // password-less with security property + test(c++, "-", + "keystore.pkcs12.certProtectionAlgorithm", "NONE", + "keystore.pkcs12.macAlgorithm", "NONE", + "-", + null, 0, + pbeWithSHA1AndDESede_oid, 50000, + null, 0); + + // back to with storepass by overriding security property with system property + test(c++, "keystore.pkcs12.certProtectionAlgorithm", "PBEWithSHA1AndDESede", + "keystore.pkcs12.macAlgorithm", "HmacPBESHA256", + "-", + "keystore.pkcs12.certProtectionAlgorithm", "NONE", + "keystore.pkcs12.macAlgorithm", "NONE", + "-", + pbeWithSHA1AndDESede_oid, 50000, + pbeWithSHA1AndDESede_oid, 50000, + SHA256_oid, 100000); + + // back to with storepass by using "" to force hardcoded default + test(c++, "keystore.pkcs12.certProtectionAlgorithm", "", + "keystore.pkcs12.keyProtectionAlgorithm", "", + "keystore.pkcs12.macAlgorithm", "", + "-", + "keystore.pkcs12.certProtectionAlgorithm", "NONE", + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "keystore.pkcs12.macAlgorithm", "NONE", + "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndDESede_oid, 50000, + SHA_oid, 100000); + + // change everything with system property + test(c++, "keystore.pkcs12.certProtectionAlgorithm", "PBEWithSHA1AndDESede", + "keystore.pkcs12.certPbeIterationCount", 3000, + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "keystore.pkcs12.keyPbeIterationCount", 4000, + "keystore.pkcs12.macAlgorithm", "HmacPBESHA256", + "keystore.pkcs12.macIterationCount", 2000, + "-", "-", + pbeWithSHA1AndDESede_oid, 3000, + pbeWithSHA1AndRC2_40_oid, 4000, + SHA256_oid, 2000); + + // change everything with security property + test(c++, "-", + "keystore.pkcs12.certProtectionAlgorithm", "PBEWithSHA1AndDESede", + "keystore.pkcs12.certPbeIterationCount", 3000, + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "keystore.pkcs12.keyPbeIterationCount", 4000, + "keystore.pkcs12.macAlgorithm", "HmacPBESHA256", + "keystore.pkcs12.macIterationCount", 2000, + "-", + pbeWithSHA1AndDESede_oid, 3000, + pbeWithSHA1AndRC2_40_oid, 4000, + SHA256_oid, 2000); + + // override security property with system property + test(c++, "keystore.pkcs12.certProtectionAlgorithm", "PBEWithSHA1AndDESede", + "keystore.pkcs12.certPbeIterationCount", 13000, + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "keystore.pkcs12.keyPbeIterationCount", 14000, + "keystore.pkcs12.macAlgorithm", "HmacPBESHA256", + "keystore.pkcs12.macIterationCount", 12000, + "-", + "keystore.pkcs12.certProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "keystore.pkcs12.certPbeIterationCount", 3000, + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndDESede", + "keystore.pkcs12.keyPbeIterationCount", 4000, + "keystore.pkcs12.macAlgorithm", "HmacPBESHA1", + "keystore.pkcs12.macIterationCount", 2000, + "-", + pbeWithSHA1AndDESede_oid, 13000, + pbeWithSHA1AndRC2_40_oid, 14000, + SHA256_oid, 12000); + + // check keyProtectionAlgorithm old behavior. Preferences of + // 4 different settings. + + test(c++, "-", + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_128", + "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndRC2_128_oid, 50000, + SHA_oid, 100000); + test(c++, "-", + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_128", + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndRC2_40_oid, 50000, + SHA_oid, 100000); + test(c++, + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC4_128", + "-", + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_128", + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndRC4_128_oid, 50000, + SHA_oid, 100000); + test(c++, + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC4_128", + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC4_40", + "-", + "keystore.PKCS12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_128", + "keystore.pkcs12.keyProtectionAlgorithm", "PBEWithSHA1AndRC2_40", + "-", + pbeWithSHA1AndRC2_40_oid, 50000, + pbeWithSHA1AndRC4_40_oid, 50000, + SHA_oid, 100000); + } + + /** + * Run once. + * + * @param args an array containing system properties and values, "-", + * security properties and values, "-", expected certPbeAlg, + * certPbeIC, keyPbeAlg, keyPbeIc, macAlg, macIC. + */ + static void test(int n, Object... args) throws Exception { + boolean isSysProp = true; + String cmd = "-keystore ks" + n + " -genkeypair -keyalg EC " + + "-alias a -dname CN=A -storepass changeit " + + "-J-Djava.security.properties=" + n + ".conf"; + List jsConf = new ArrayList<>(); + for (int i = 0; i < args.length; i++) { + if (isSysProp) { + if (args[i].equals("-")) { + isSysProp = false; + } else { + cmd += " -J-D" + args[i] + "=" + args[++i]; + } + } else { + if (args[i] == "-") { + Files.write(Path.of(n + ".conf"), jsConf); + System.out.println("--------- test starts ----------"); + System.out.println(jsConf); + SecurityTools.keytool(cmd).shouldHaveExitValue(0); + + byte[] data = Files.readAllBytes(Path.of("ks" + n)); + + // cert pbe alg + ic + if (args[i+1] == null) { + checkAlg(data, "110c10", DATA_OID); + } else { + checkAlg(data, "110c10", ENCRYPTED_DATA_OID); + checkAlg(data, "110c110110", (ObjectIdentifier)args[i+1]); + checkInt(data, "110c1101111", (int)args[i+2]); + } + + // key pbe alg + ic + checkAlg(data, "110c010c01000", (ObjectIdentifier)args[i+3]); + checkInt(data, "110c010c010011", (int)args[i+4]); + + // mac alg + ic + if (args[i+5] == null) { + shouldNotExist(data, "2"); + } else { + checkAlg(data, "2000", (ObjectIdentifier)args[i+5]); + checkInt(data, "22", (int)args[i+6]); + } + } else { + jsConf.add(args[i] + "=" + args[++i]); + } + } + } + } +} diff --git a/test/jdk/sun/security/pkcs12/ParamsTest.java b/test/jdk/sun/security/pkcs12/ParamsTest.java new file mode 100644 index 00000000000..f4cfc88641a --- /dev/null +++ b/test/jdk/sun/security/pkcs12/ParamsTest.java @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8076190 + * @library /test/lib + * @modules java.base/sun.security.pkcs + * java.base/sun.security.x509 + * java.base/sun.security.util + * @summary Customizing the generation of a PKCS12 keystore + */ + +import jdk.test.lib.Asserts; +import jdk.test.lib.SecurityTools; +import jdk.test.lib.process.OutputAnalyzer; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.Base64; +import java.util.Objects; + +import static jdk.test.lib.security.DerUtils.*; +import static sun.security.x509.AlgorithmId.*; +import static sun.security.pkcs.ContentInfo.*; + +public class ParamsTest { + + public static void main(String[] args) throws Throwable { + + // De-BASE64 textual files in ./params to `pwd` + Files.newDirectoryStream(Path.of(System.getProperty("test.src"), "params")) + .forEach(p -> { + try (InputStream is = Files.newInputStream(p); + OutputStream os = Files.newOutputStream(p.getFileName())){ + Base64.getMimeDecoder().wrap(is).transferTo(os); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + + byte[] data; + + // openssl -> keytool interop check + + // os2. no cert pbe, no mac. + check("os2", "a", null, "changeit", true, true, true); + check("os2", "a", "changeit", "changeit", true, true, true); + // You can even load it with a wrong storepass, controversial + check("os2", "a", "wrongpass", "changeit", true, true, true); + + // os3. no cert pbe, has mac. just like JKS + check("os3", "a", null, "changeit", true, true, true); + check("os3", "a", "changeit", "changeit", true, true, true); + // Cannot load with a wrong storepass, same as JKS + check("os3", "a", "wrongpass", "-", IOException.class, "-", "-"); + + // os4. non default algs + check("os4", "a", "changeit", "changeit", true, true, true); + check("os4", "a", "wrongpass", "-", IOException.class, "-", "-"); + // no storepass no cert + check("os4", "a", null, "changeit", true, false, true); + + // os5. strong non default algs + check("os5", "a", "changeit", "changeit", true, true, true); + check("os5", "a", "wrongpass", "-", IOException.class, "-", "-"); + // no storepass no cert + check("os5", "a", null, "changeit", true, false, true); + + // keytool + + // Current default pkcs12 setting + keytool("-importkeystore -srckeystore ks -srcstorepass changeit " + + "-destkeystore ksnormal -deststorepass changeit"); + data = Files.readAllBytes(Path.of("ksnormal")); + checkInt(data, "22", 100000); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 50000); // key ic + checkAlg(data, "110c10", ENCRYPTED_DATA_OID); + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 50000); // cert ic + + check("ksnormal", "a", "changeit", "changeit", true, true, true); + check("ksnormal", "a", null, "changeit", true, false, true); + check("ksnormal", "a", "wrongpass", "-", IOException.class, "-", "-"); + + // Add a new entry with password-less settings, still has a storepass + keytool("-keystore ksnormal -genkeypair -storepass changeit -alias b -dname CN=b " + + "-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE " + + "-J-Dkeystore.pkcs12.macAlgorithm=NONE"); + data = Files.readAllBytes(Path.of("ksnormal")); + checkInt(data, "22", 100000); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 50000); // key ic + checkAlg(data, "110c010c11000", pbeWithSHA1AndDESede_oid); // new key alg + checkInt(data, "110c010c110011", 50000); // new key ic + checkAlg(data, "110c10", ENCRYPTED_DATA_OID); + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 50000); // cert ic + check("ksnormal", "b", null, "changeit", true, false, true); + check("ksnormal", "b", "changeit", "changeit", true, true, true); + + // Different keypbe alg, no cert pbe and no mac + keytool("-importkeystore -srckeystore ks -srcstorepass changeit " + + "-destkeystore ksnopass -deststorepass changeit " + + "-J-Dkeystore.pkcs12.keyProtectionAlgorithm=PBEWithSHA1AndRC4_128 " + + "-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE " + + "-J-Dkeystore.pkcs12.macAlgorithm=NONE"); + data = Files.readAllBytes(Path.of("ksnopass")); + shouldNotExist(data, "2"); // no Mac + checkAlg(data, "110c010c01000", pbeWithSHA1AndRC4_128_oid); + checkInt(data, "110c010c010011", 50000); + checkAlg(data, "110c10", DATA_OID); + check("ksnopass", "a", null, "changeit", true, true, true); + check("ksnopass", "a", "changeit", "changeit", true, true, true); + check("ksnopass", "a", "wrongpass", "changeit", true, true, true); + + // Add a new entry with normal settings, still password-less + keytool("-keystore ksnopass -genkeypair -storepass changeit -alias b -dname CN=B"); + data = Files.readAllBytes(Path.of("ksnopass")); + shouldNotExist(data, "2"); // no Mac + checkAlg(data, "110c010c01000", pbeWithSHA1AndRC4_128_oid); + checkInt(data, "110c010c010011", 50000); + checkAlg(data, "110c010c11000", pbeWithSHA1AndDESede_oid); + checkInt(data, "110c010c110011", 50000); + checkAlg(data, "110c10", DATA_OID); + check("ksnopass", "a", null, "changeit", true, true, true); + check("ksnopass", "b", null, "changeit", true, true, true); + + keytool("-importkeystore -srckeystore ks -srcstorepass changeit " + + "-destkeystore ksnewic -deststorepass changeit " + + "-J-Dkeystore.pkcs12.macIterationCount=5555 " + + "-J-Dkeystore.pkcs12.certPbeIterationCount=6666 " + + "-J-Dkeystore.pkcs12.keyPbeIterationCount=7777"); + data = Files.readAllBytes(Path.of("ksnewic")); + checkInt(data, "22", 5555); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 7777); // key ic + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 6666); // cert ic + + // keypbe alg cannot be NONE + keytool("-keystore ksnewic -genkeypair -storepass changeit -alias b -dname CN=B " + + "-J-Dkeystore.pkcs12.keyProtectionAlgorithm=NONE") + .shouldContain("NONE AlgorithmParameters not available") + .shouldHaveExitValue(1); + + // new entry new keypbe alg (and default ic), else unchanged + keytool("-keystore ksnewic -genkeypair -storepass changeit -alias b -dname CN=B " + + "-J-Dkeystore.pkcs12.keyProtectionAlgorithm=PBEWithSHA1AndRC4_128"); + data = Files.readAllBytes(Path.of("ksnewic")); + checkInt(data, "22", 5555); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 7777); // key ic + checkAlg(data, "110c010c11000", pbeWithSHA1AndRC4_128_oid); // new key alg + checkInt(data, "110c010c110011", 50000); // new key ic + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 6666); // cert ic + + // Check KeyStore loading multiple keystores + KeyStore ks = KeyStore.getInstance("pkcs12"); + try (FileInputStream fis = new FileInputStream("ksnormal"); + FileOutputStream fos = new FileOutputStream("ksnormaldup")) { + ks.load(fis, "changeit".toCharArray()); + ks.store(fos, "changeit".toCharArray()); + } + data = Files.readAllBytes(Path.of("ksnormaldup")); + checkInt(data, "22", 100000); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 50000); // key ic + checkAlg(data, "110c010c11000", pbeWithSHA1AndDESede_oid); // new key alg + checkInt(data, "110c010c110011", 50000); // new key ic + checkAlg(data, "110c10", ENCRYPTED_DATA_OID); + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 50000); // cert ic + + try (FileInputStream fis = new FileInputStream("ksnopass"); + FileOutputStream fos = new FileOutputStream("ksnopassdup")) { + ks.load(fis, "changeit".toCharArray()); + ks.store(fos, "changeit".toCharArray()); + } + data = Files.readAllBytes(Path.of("ksnopassdup")); + shouldNotExist(data, "2"); // no Mac + checkAlg(data, "110c010c01000", pbeWithSHA1AndRC4_128_oid); + checkInt(data, "110c010c010011", 50000); + checkAlg(data, "110c010c11000", pbeWithSHA1AndDESede_oid); + checkInt(data, "110c010c110011", 50000); + checkAlg(data, "110c10", DATA_OID); + + try (FileInputStream fis = new FileInputStream("ksnewic"); + FileOutputStream fos = new FileOutputStream("ksnewicdup")) { + ks.load(fis, "changeit".toCharArray()); + ks.store(fos, "changeit".toCharArray()); + } + data = Files.readAllBytes(Path.of("ksnewicdup")); + checkInt(data, "22", 5555); // Mac ic + checkAlg(data, "2000", SHA_oid); // Mac alg + checkAlg(data, "110c010c01000", pbeWithSHA1AndDESede_oid); // key alg + checkInt(data, "110c010c010011", 7777); // key ic + checkAlg(data, "110c010c11000", pbeWithSHA1AndRC4_128_oid); // new key alg + checkInt(data, "110c010c110011", 50000); // new key ic + checkAlg(data, "110c110110", pbeWithSHA1AndRC2_40_oid); // cert alg + checkInt(data, "110c1101111", 6666); // cert ic + + // Check keytool behavior + + // ksnormal has password + + keytool("-list -keystore ksnormal") + .shouldContain("WARNING WARNING WARNING") + .shouldContain("Certificate chain length: 0"); + + SecurityTools.setResponse("changeit"); + keytool("-list -keystore ksnormal") + .shouldNotContain("WARNING WARNING WARNING") + .shouldContain("Certificate fingerprint"); + + // ksnopass is password-less + + keytool("-list -keystore ksnopass") + .shouldNotContain("WARNING WARNING WARNING") + .shouldContain("Certificate fingerprint"); + + // -certreq prompts for keypass + SecurityTools.setResponse("changeit"); + keytool("-certreq -alias a -keystore ksnopass") + .shouldContain("Enter key password for ") + .shouldContain("-----BEGIN NEW CERTIFICATE REQUEST-----") + .shouldHaveExitValue(0); + + // -certreq -storepass works fine + keytool("-certreq -alias a -keystore ksnopass -storepass changeit") + .shouldNotContain("Enter key password for ") + .shouldContain("-----BEGIN NEW CERTIFICATE REQUEST-----") + .shouldHaveExitValue(0); + + // -certreq -keypass also works fine + keytool("-certreq -alias a -keystore ksnopass -keypass changeit") + .shouldNotContain("Enter key password for ") + .shouldContain("-----BEGIN NEW CERTIFICATE REQUEST-----") + .shouldHaveExitValue(0); + + // -importkeystore prompts for srckeypass + SecurityTools.setResponse("changeit", "changeit"); + keytool("-importkeystore -srckeystore ksnopass " + + "-destkeystore jks3 -deststorepass changeit") + .shouldContain("Enter key password for ") + .shouldContain("Enter key password for ") + .shouldContain("2 entries successfully imported"); + + // ksnopass2 is ksnopass + 2 cert entries + + ks = KeyStore.getInstance(new File("ksnopass"), (char[])null); + ks.setCertificateEntry("aa", ks.getCertificate("a")); + ks.setCertificateEntry("bb", ks.getCertificate("b")); + try (FileOutputStream fos = new FileOutputStream("ksnopass2")) { + ks.store(fos, null); + } + + // -importkeystore prompts for srckeypass for private keys + // and no prompt for certs + SecurityTools.setResponse("changeit", "changeit"); + keytool("-importkeystore -srckeystore ksnopass2 " + + "-destkeystore jks5 -deststorepass changeit") + .shouldContain("Enter key password for ") + .shouldContain("Enter key password for ") + .shouldNotContain("Enter key password for ") + .shouldNotContain("Enter key password for ") + .shouldContain("4 entries successfully imported"); + + // ksonlycert has only cert entries + + ks.deleteEntry("a"); + ks.deleteEntry("b"); + try (FileOutputStream fos = new FileOutputStream("ksonlycert")) { + ks.store(fos, null); + } + + // -importkeystore does not prompt at all + keytool("-importkeystore -srckeystore ksonlycert " + + "-destkeystore jks6 -deststorepass changeit") + .shouldNotContain("Enter key password for ") + .shouldNotContain("Enter key password for ") + .shouldContain("2 entries successfully imported"); + + // create a new password-less keystore + keytool("-keystore ksnopass -exportcert -alias a -file a.cert -rfc"); + + // Normally storepass is prompted for + keytool("-keystore kscert1 -importcert -alias a -file a.cert -noprompt") + .shouldContain("Enter keystore password:"); + keytool("-keystore kscert2 -importcert -alias a -file a.cert -noprompt " + + "-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE") + .shouldContain("Enter keystore password:"); + keytool("-keystore kscert3 -importcert -alias a -file a.cert -noprompt " + + "-J-Dkeystore.pkcs12.macAlgorithm=NONE") + .shouldContain("Enter keystore password:"); + // ... but not if it's password-less + keytool("-keystore kscert4 -importcert -alias a -file a.cert -noprompt " + + "-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE " + + "-J-Dkeystore.pkcs12.macAlgorithm=NONE") + .shouldNotContain("Enter keystore password:"); + + // still prompt for keypass for genkeypair and certreq + SecurityTools.setResponse("changeit", "changeit"); + keytool("-keystore ksnopassnew -genkeypair -alias a -dname CN=A " + + "-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE " + + "-J-Dkeystore.pkcs12.macAlgorithm=NONE") + .shouldNotContain("Enter keystore password:") + .shouldContain("Enter key password for "); + keytool("-keystore ksnopassnew -certreq -alias a") + .shouldNotContain("Enter keystore password:") + .shouldContain("Enter key password for "); + keytool("-keystore ksnopassnew -list -v -alias a") + .shouldNotContain("Enter keystore password:") + .shouldNotContain("Enter key password for "); + + // params only read on demand + + // keyPbeIterationCount is used by -genkeypair + keytool("-keystore ksgenbadkeyic -genkeypair -alias a -dname CN=A " + + "-storepass changeit " + + "-J-Dkeystore.pkcs12.keyPbeIterationCount=abc") + .shouldContain("keyPbeIterationCount is not a number: abc") + .shouldHaveExitValue(1); + + keytool("-keystore ksnopassnew -exportcert -alias a -file a.cert"); + + // but not used by -importcert + keytool("-keystore ksimpbadkeyic -importcert -alias a -file a.cert " + + "-noprompt -storepass changeit " + + "-J-Dkeystore.pkcs12.keyPbeIterationCount=abc") + .shouldHaveExitValue(0); + + // None is used by -list + keytool("-keystore ksnormal -storepass changeit -list " + + "-J-Dkeystore.pkcs12.keyPbeIterationCount=abc " + + "-J-Dkeystore.pkcs12.certPbeIterationCount=abc " + + "-J-Dkeystore.pkcs12.macIterationCount=abc") + .shouldHaveExitValue(0); + } + + /** + * Check keystore loading and key/cert reading. + * + * @param keystore the file name of keystore + * @param alias the key/cert to read + * @param storePass store pass to try out, can be null + * @param keypass key pass to try, can not be null + * @param expectedLoad expected result of keystore loading, true if non + * null, false if null, exception class if exception + * @param expectedCert expected result of cert reading + * @param expectedKey expected result of key reading + */ + private static void check( + String keystore, + String alias, + String storePass, + String keypass, + Object expectedLoad, + Object expectedCert, + Object expectedKey) { + KeyStore ks = null; + Object actualLoad, actualCert, actualKey; + String label = keystore + "-" + alias + "-" + storePass + "-" + keypass; + try { + ks = KeyStore.getInstance(new File(keystore), + storePass == null ? null : storePass.toCharArray()); + actualLoad = ks != null; + } catch (Exception e) { + e.printStackTrace(System.out); + actualLoad = e.getClass(); + } + Asserts.assertEQ(expectedLoad, actualLoad, label + "-load"); + + // If not loaded correctly, skip cert/key reading + if (!Objects.equals(actualLoad, true)) { + return; + } + + try { + actualCert = (ks.getCertificate(alias) != null); + } catch (Exception e) { + e.printStackTrace(System.out); + actualCert = e.getClass(); + } + Asserts.assertEQ(expectedCert, actualCert, label + "-cert"); + + try { + actualKey = (ks.getKey(alias, keypass.toCharArray()) != null); + } catch (Exception e) { + e.printStackTrace(System.out); + actualKey = e.getClass(); + } + Asserts.assertEQ(expectedKey, actualKey, label + "-key"); + } + + static OutputAnalyzer keytool(String s) throws Throwable { + return SecurityTools.keytool(s); + } +} diff --git a/test/jdk/sun/security/pkcs12/params/README b/test/jdk/sun/security/pkcs12/params/README new file mode 100644 index 00000000000..0fcd17d7c05 --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/README @@ -0,0 +1,54 @@ +1. Preparing data in this directory + +mkdir tmp +cd tmp +keytool -keystore ks -genkeypair -storepass changeit -alias a -dname CN=A +openssl pkcs12 -in ks -nodes -out kandc -passin pass:changeit +openssl pkcs12 -export -in kandc -out os2 -name a -passout pass:changeit \ + -certpbe NONE -nomac +openssl pkcs12 -export -in kandc -out os3 -name a -passout pass:changeit \ + -certpbe NONE +openssl pkcs12 -export -in kandc -out os4 -name a -passout pass:changeit \ + -certpbe PBE-SHA1-RC4-128 -keypbe PBE-SHA1-RC4-128 -macalg SHA224 +openssl pkcs12 -export -in kandc -out os5 -name a -passout pass:changeit \ + -certpbe AES-256-CBC -keypbe AES-256-CBC -macalg SHA512 +for a in *; do + openssl base64 -in $a -out ../$a +done +cd .. +rm -rf tmp + +2. After running the test, we can go to the scratch directory and run the +following commands to check keytool -> openssl interoperability. +OpenSSL 1.1.0i is used here. Earlier versions might generate different info. + +( +openssl pkcs12 -in ks2 -passin pass:changeit -info -nokeys -nocerts 2> t2 || exit 20 +grep "MAC:sha1 Iteration 100000" t2 || exit 21 +grep "Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 50000" t2 || exit 23 +grep "PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 50000" t2 || exit 24 + +openssl pkcs12 -in ks22 -passin pass:changeit -info -nokeys -nocerts 2> t22 || exit 25 +diff t2 t22 || exit 26 + +openssl pkcs12 -in ks3 -passin pass:changeit -info -nokeys -nocerts && exit 30 + +openssl pkcs12 -in ks3 -passin pass:changeit -info -nokeys -nocerts -nomacver 2> t3 || exit 31 +grep "PKCS7 Encrypted data:" t3 && exit 33 +grep "Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 50000" t3 || exit 34 +grep "Shrouded Keybag: pbeWithSHA1And128BitRC4, Iteration 50000" t3 || exit 35 + +openssl pkcs12 -in ks33 -passin pass:changeit -info -nokeys -nocerts -nomacver 2> t33 || exit 36 +diff t3 t33 || exit 37 + +openssl pkcs12 -in ks4 -passin pass:changeit -info -nokeys -nocerts 2> t4 || exit 40 +grep "MAC:sha1 Iteration 5555" t4 || exit 41 +grep "Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 7777" t4 || exit 43 +grep "Shrouded Keybag: pbeWithSHA1And128BitRC4, Iteration 50000" t4 || exit 44 +grep "PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 6666" t4 || exit 45 + +openssl pkcs12 -in ks44 -passin pass:changeit -info -nokeys -nocerts 2> t44 || exit 46 +diff t4 t44 || exit 47 + +echo Succeed +) diff --git a/test/jdk/sun/security/pkcs12/params/kandc b/test/jdk/sun/security/pkcs12/params/kandc new file mode 100644 index 00000000000..27fc1f7337f --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/kandc @@ -0,0 +1,55 @@ +QmFnIEF0dHJpYnV0ZXMKICAgIGZyaWVuZGx5TmFtZTogYQogICAgbG9jYWxLZXlJ +RDogNTQgNjkgNkQgNjUgMjAgMzEgMzUgMzMgMzggMzEgMzMgMzQgMzAgMzUgMzkg +MzQgMzMgMzUgCktleSBBdHRyaWJ1dGVzOiA8Tm8gQXR0cmlidXRlcz4KLS0tLS1C +RUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUNYUUlCQURDQ0FqVUdCeXFHU000NEJB +RXdnZ0lvQW9JQkFRQ1BlVFhadWFycHY2dnRpSHJQU1ZHMjh5N0YKbmp1dk54am82 +c1NXSHo3OU5nYm5RMUdweEJnek9iZ0o1OEt1SEZPYnAwZGJoZEFScmJpMGVZZDFT +WVJwWEt3TwpqeFN6Tmdnb29pLzZKeEVLUFdLcGswVTBDYUQrYVd4R1dQaEwzU0NC +bkRjSm9CQlhzWld0elFBalBicFVoTFlwCkg1MWtqdmlEUklaM2w1enNCTFEwcHF3 +dWRlbVlYZUk5c0NrdndSR01uL3FkZ1lIbk00MjNrcmN3MTdualNWa3YKYUFtWWNo +VTVGZW85YTR0R1U4WXpSWStBT3pLa3d1RHljcEFsYms0L2lqc0lPS0hFVU9UaGpC +b3BvMzNmWHFGRAoza3RtL3dTUVB0WFBGaVBoV05TSHhnanBmeUVjMkIzS0k4dHVP +QWRsK0NMalFyNUlUQVYyT1RsZ0hOWm5BaDBBCnV2YVdwb1Y0OTkvZTUvcG55WGZI +aGU4eXNqTzY1WURBdk5WcFhRS0NBUUFXcGx4WUlFaFFjRTUxQXFPWFZ3UU4KTk5v +Nk5IakJWTlRrcGNBdEpDN2dUNWJtSGt2UWtFcTlySTgzN3JIZ256R0MwanlRUTh0 +a0w0Z0FRV0R0K2NvSgpzeUIycDV3eXBpZnlSejZSaDV1aXhPZEV2U0NCVkV5MVc0 +QXNObzBmcUQ3VWllbE9ENkJvampKQ2lseDR4SGpHCmpRVW50eHlhT3JzTEMrRXNS +R2lXT2VmVHpuVGJFQnBscWl1SDlreG9KdHMreHk5TFZabURTN1R0c0M5OGtPbWsK +bHRPbFhWTmI2L3hGMVBZWjlqODk3YnVIT1NYQzhpVGdkekVwYmFpSDdCNUhTUGgr +KzEvZXQxU0VNV3NpTXQ3bApVOTJ2QWhFckRSOEMyakNYTWlUK0o2N2FpNTFMS1NM +WnVvdmpudG5oQTZZOFVvRUx4b2kzNHUxREZ1SHZGOXZlCkJCOENIUUMzU0hOSm5u +cjF0TG00aDdKR1RETU02cUJQc2N3cmdMcGZHOW9tCi0tLS0tRU5EIFBSSVZBVEUg +S0VZLS0tLS0KQmFnIEF0dHJpYnV0ZXMKICAgIGZyaWVuZGx5TmFtZTogYQogICAg +bG9jYWxLZXlJRDogNTQgNjkgNkQgNjUgMjAgMzEgMzUgMzMgMzggMzEgMzMgMzQg +MzAgMzUgMzkgMzQgMzMgMzUgCnN1YmplY3Q9L0NOPUEKaXNzdWVyPS9DTj1BCi0t +LS0tQkVHSU4gQ0VSVElGSUNBVEUtLS0tLQpNSUlFRXpDQ0E3K2dBd0lCQWdJRWJ1 +OFlOREFOQmdsZ2hrZ0JaUU1FQXdJRkFEQU1NUW93Q0FZRFZRUURFd0ZCCk1CNFhE +VEU0TURreU9ERXhNamN6T1ZvWERURTRNVEl5TnpFeE1qY3pPVm93RERFS01BZ0dB +MVVFQXhNQlFUQ0MKQTBJd2dnSTFCZ2NxaGtqT09BUUJNSUlDS0FLQ0FRRUFqM2sx +MmJtcTZiK3I3WWg2ejBsUnR2TXV4WjQ3cnpjWQo2T3JFbGg4Ky9UWUc1ME5ScWNR +WU16bTRDZWZDcmh4VG02ZEhXNFhRRWEyNHRIbUhkVW1FYVZ5c0RvOFVzellJCktL +SXYraWNSQ2oxaXFaTkZOQW1nL21sc1JsajRTOTBnZ1p3M0NhQVFWN0dWcmMwQUl6 +MjZWSVMyS1IrZFpJNzQKZzBTR2Q1ZWM3QVMwTkthc0xuWHBtRjNpUGJBcEw4RVJq +Si82bllHQjV6T050NUszTU5lNTQwbFpMMmdKbUhJVgpPUlhxUFd1TFJsUEdNMFdQ +Z0RzeXBNTGc4bktRSlc1T1A0bzdDRGloeEZEazRZd2FLYU45MzE2aFE5NUxadjhF +CmtEN1Z6eFlqNFZqVWg4WUk2WDhoSE5nZHlpUExiamdIWmZnaTQwSytTRXdGZGpr +NVlCeldad0lkQUxyMmxxYUYKZVBmZjN1ZjZaOGwzeDRYdk1ySXp1dVdBd0x6VmFW +MENnZ0VBRnFaY1dDQklVSEJPZFFLamwxY0VEVFRhT2pSNAp3VlRVNUtYQUxTUXU0 +RStXNWg1TDBKQkt2YXlQTis2eDRKOHhndEk4a0VQTFpDK0lBRUZnN2ZuS0NiTWdk +cWVjCk1xWW44a2Mra1llYm9zVG5STDBnZ1ZSTXRWdUFMRGFOSDZnKzFJbnBUZytn +YUk0eVFvcGNlTVI0eG8wRko3Y2MKbWpxN0N3dmhMRVJvbGpubjA4NTAyeEFhWmFv +cmgvWk1hQ2JiUHNjdlMxV1pnMHUwN2JBdmZKRHBwSmJUcFYxVApXK3Y4UmRUMkdm +WS9QZTI3aHprbHd2SWs0SGN4S1cyb2grd2VSMGo0ZnZ0ZjNyZFVoREZySWpMZTVW +UGRyd0lSCkt3MGZBdG93bHpJay9pZXUyb3VkU3lraTJicUw0NTdaNFFPbVBGS0JD +OGFJdCtMdFF4Ymg3eGZiM2dPQ0FRVUEKQW9JQkFEK0syd1RoV3VyRGpZTUNYeGZy +dXJOK0drZFNFeXk5cCtkdkhJUDFrTWhybTcrRXV6LzExUVlGcGI4Vgpic0NhWWUx +ME9qWkF1WjRXSmdTbkl5R0swb2JzbjlKWkZubUdDbGlxRkVoWGJwbnhyOGxhS3Iw +dDRERytPMTF2CjVQRGh4aHd2b1VZb2ZwWTFEYjN0SHlxdytWM3RRWVA3K3RaNDRB +eW1SdTNtbktZTVZzRHd2M0x1UEdaLzJmQ0MKY2lYVEJIU3VFbzdCUDdBbjdFYkZO +K0JaQldlTlgvcjNOZm1nL0tmQjQ1OFNZMmhFYlplRW5kZUh4d204VFRORwpQaXdi +Nkx5ZE5RS0VFS003cmVFTjkwTXVsUVJMZkhVVFBWZXB5dU9QK1ZySEI3WS9lVWhI +K2RNeHp6d3pLOHJ6CjRYaEwxRFBhT1ZMdmxCSUR5VE5QZU4wV2V4bWpJVEFmTUIw +R0ExVWREZ1FXQkJUQThWK01SSXRNU3Yyb283YjgKYzVlQ0tybzdxREFOQmdsZ2hr +Z0JaUU1FQXdJRkFBTS9BREE4QWh3a0dVK2VVR0kvTFFVejMzTUk3cC9BVXd1WAo0 +SnZOVGUrUGhQZFZBaHdvUzdNMFIzbjRnSkkxU2FRdnoyTWhuR3Z1T3Q5UzZMdkRR +NWRFCi0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K diff --git a/test/jdk/sun/security/pkcs12/params/ks b/test/jdk/sun/security/pkcs12/params/ks new file mode 100644 index 00000000000..c64eb4b629a --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/ks @@ -0,0 +1,45 @@ +MIIIQQIBAzCCB/oGCSqGSIb3DQEHAaCCB+sEggfnMIIH4zCCAv8GCSqGSIb3DQEH +AaCCAvAEggLsMIIC6DCCAuQGCyqGSIb3DQEMCgECoIICmzCCApcwKQYKKoZIhvcN +AQwBAzAbBBSZfQZ+F5Za9YLcGbyXsafOUX50XwIDAMNQBIICaBh7FmOBnDoFngWz +pnK5+SzD16E8TNFxZneou1n2Nxq8MXMgfLjlVb9PSlARDU+Pj9FhRdjWqTEncKwn +5owDYujiOSGmAHih64nFHoICs34o5LAKv9l8UhfE1qUgA4iA1VdakD31N8ZGR29O +2tglXKrHE9n6f5k47mzqcPiNIgHH1KSWu143AInYTOjpEJD2YpBTzL0YxvnLbaY1 +v+PRokbHak8siO/MCNwwQBD5lJX7kVld4iMjeJvBX9pUwqfD4EDuvJo9QkHmy+GB +UBAMRBsMHwV9E832dHxh+JYveg0TI8FACnLHpmbYpCs+K69A6yOAUqfUIseLUJR4 +XSd2HZODXyLHAimJK9AQGRpGWORiRu2E/XimLo2qhPKEOl2hbi+R95hb2h2wGgr1 +RhCsAFHac7cW4r/s1HacU0JCzWJKyV76LbNHDexlGj09B47VAAAfE7zlHmUIShEN +zwQ6EUDxrK+h7wY2GS2fqcseqDvPXtxvbGjkAyfYE+6aT2g6vtd6PTrBSRt6Lzp6 +rUC0IrHXXpBb8qanvuAd+OPC4skp/hI/q7qCsKOUzRc5Xmm1FMUfJr6UeadSvpfw +V9C28zEMPcW+KdS2W7f0uvebIgUU7xj8dg27XC+C7oPhLz/pIFQ4n449GQNUo57K +WPmGeT/coO3jVk+E7uzXeFkwp2rGXQNWin44UUGGG0/S04YMRJknpRzw8sILD4d1 +N/iEazUOl35pua9+0OTFqNJzSemqO3kevgVXrsSzQCLeoB1dn4mpvqkPV87B5JOC +t3fpDVSBrcFF43qeveQ65lpbcbOoucO/h16s8w8xNjARBgkqhkiG9w0BCRQxBB4C +AGEwIQYJKoZIhvcNAQkVMRQEElRpbWUgMTUzODEzNDA1OTQzNTCCBNwGCSqGSIb3 +DQEHBqCCBM0wggTJAgEAMIIEwgYJKoZIhvcNAQcBMCkGCiqGSIb3DQEMAQYwGwQU +tPIqPBD1WiaRd01W1t6/znB2PmkCAwDDUICCBIhvxfWroewV/5cO8r24YQkMVjvs +2kgkLusWbreMScR/LE5lcLXHYAS3KMJJWfwBBKa3nvyuMiYPnuzTReSd7SxtCZtG ++EIyyf6mTUdqBTPkDduqDHqugzokHKFycsTi2YBam1ohyTOUoUOFnJeOyJ4FOVQ5 +TQOPUXgBW8s2jMm181+w0E3NXiEC+c+cPZUm2aQPLUxEYqTuJsMY6Uz+jv94hOIH +eeZHwVBy8D/3pUB56L89JBRARpIsCP+BQIaTFyopXQ8i50gdT3a6KL8O9Zzjjij8 +VLjCpLdC9wR5yY4Js/cZyER/uxl8zBroheiye5U77rw4WQrSQhn/cBoTDR0llwlU +K3IL4J22UjtTmIQlFAV8XWz7GZAVJkuJLEtuO6JjHSgO8NTnfN2T4oWaNAwdAK3S +UrJVpk4yx0+B2UokxyY0Y3FErLzM7BMq/X9Rvhs9Zwwr+ZftqXEaiYHHSEPGNGZI +Gh3P8F8EThCcyVe7yFK+0DCj3Y8jrZZLXh8e1M1wPWVay52JL1QApTfs0ucwlMLz +19KUSm13ztuCBo47OrMU1ur6a1eQZkOvRmdMxKNLLrET3sBh7ZE6SbjijCtDfYdf +k4+Q9VrO+04atyXg8Gy4vRZB/koe8oXCDgPYTTqLHNywTuhJq30Ev71D0GdiwPy7 +9urLh2ocm7neRIGsaYRXxa0U6IpT47wOYbUOz3y6Yf5yjoI3E0gWYZtuQVGRkatF +p97mJExQ9aBy1l4hqmgU4bcqBepq2fdxhVueiZD84QZqfZ5H9pRzVPjHoqzIH8wm +kmM78mlMqu8IPqny0I3zF6z+wapd0vpjpeaLItlUAJ2Eiz7d4BHKBeAPsZtPUQzr +hPtM/ao5QjLHddLqh2lauJk0Og+4Uj1UftelM6ERZPN0JXEyh+DU9hs2czTnJKlZ +BEB07/1WFPCrdj/eNe7K02Xs2kpJKiXjAWNxFNWtqDQY3U5/lAY8oY/dc6LG+iuO +yDLXD4TSJZSNrOOHKmp4TXpuMRM2tbw9m0vrweegSB6GIzUIA1MOvgsjbSgWwmhy +LoG6QriLhTXZQd+Uh6uqlCBrgXQ2K+RuIsZCZaZE64pUtK3Tl6ZwBe3POfxMCkjm +YQ/ZJ7k0IOk9lQfA6InlfSDkS7B5WHev7Fqh96GI9sUSox13El9VvbNfFDZy5lem +Ml8GTDLrlop5TRDeplHknettKqMQmpj2nopGvTn4EFSNFz8AZmEtOaptzkP5l3ar +DRgPqhxclb/4QX7c67s1l/pcR16BbiH05rxVUTclg8rB0FCo14Hi5CQF0turk5QK +ptM9kvz/VtDUpHArRz7NaFZdJuVC1IRq8dgmSi7MN7LaQ0mVIfeQ1ssHjLhIQMbA +aE8Xwij9Q5OAoNcA8Ucctqgl12/9uKfZ5lKeZnVR4DyVhjnTJ9Ounv1unagBj/Jq +6o4ibStuqfHhKhBtQkr4RXsrocJhgMhfhbUqgQRx0pWuODrpqQMuG6yTnw7ePPMt +w29mceyPdU8EoYUUPCDZdpv3giurH5E22tnRDyU0Mm1Spbe/rDA+MCEwCQYFKw4D +AhoFAAQUtavY6pX+J6lZHeGkx3Rlt6Hc8iEEFOUlujwYOLAzDd2fQcGdyL8MrGvo +AgMBhqA= diff --git a/test/jdk/sun/security/pkcs12/params/os2 b/test/jdk/sun/security/pkcs12/params/os2 new file mode 100644 index 00000000000..a11e4957abc --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/os2 @@ -0,0 +1,42 @@ +MIIHrwIBAzCCB6gGCSqGSIb3DQEHAaCCB5kEggeVMIIHkTCCBJUGCSqGSIb3DQEH +AaCCBIYEggSCMIIEfjCCBHoGCyqGSIb3DQEMCgEDoIIELzCCBCsGCiqGSIb3DQEJ +FgGgggQbBIIEFzCCBBMwggO/oAMCAQICBG7vGDQwDQYJYIZIAWUDBAMCBQAwDDEK +MAgGA1UEAxMBQTAeFw0xODA5MjgxMTI3MzlaFw0xODEyMjcxMTI3MzlaMAwxCjAI +BgNVBAMTAUEwggNCMIICNQYHKoZIzjgEATCCAigCggEBAI95Ndm5qum/q+2Ies9J +UbbzLsWeO683GOjqxJYfPv02BudDUanEGDM5uAnnwq4cU5unR1uF0BGtuLR5h3VJ +hGlcrA6PFLM2CCiiL/onEQo9YqmTRTQJoP5pbEZY+EvdIIGcNwmgEFexla3NACM9 +ulSEtikfnWSO+INEhneXnOwEtDSmrC516Zhd4j2wKS/BEYyf+p2BgeczjbeStzDX +ueNJWS9oCZhyFTkV6j1ri0ZTxjNFj4A7MqTC4PJykCVuTj+KOwg4ocRQ5OGMGimj +fd9eoUPeS2b/BJA+1c8WI+FY1IfGCOl/IRzYHcojy244B2X4IuNCvkhMBXY5OWAc +1mcCHQC69pamhXj3397n+mfJd8eF7zKyM7rlgMC81WldAoIBABamXFggSFBwTnUC +o5dXBA002jo0eMFU1OSlwC0kLuBPluYeS9CQSr2sjzfuseCfMYLSPJBDy2QviABB +YO35ygmzIHannDKmJ/JHPpGHm6LE50S9IIFUTLVbgCw2jR+oPtSJ6U4PoGiOMkKK +XHjEeMaNBSe3HJo6uwsL4SxEaJY559POdNsQGmWqK4f2TGgm2z7HL0tVmYNLtO2w +L3yQ6aSW06VdU1vr/EXU9hn2Pz3tu4c5JcLyJOB3MSltqIfsHkdI+H77X963VIQx +ayIy3uVT3a8CESsNHwLaMJcyJP4nrtqLnUspItm6i+Oe2eEDpjxSgQvGiLfi7UMW +4e8X294DggEFAAKCAQA/itsE4Vrqw42DAl8X67qzfhpHUhMsvafnbxyD9ZDIa5u/ +hLs/9dUGBaW/FW7AmmHtdDo2QLmeFiYEpyMhitKG7J/SWRZ5hgpYqhRIV26Z8a/J +Wiq9LeAxvjtdb+Tw4cYcL6FGKH6WNQ297R8qsPld7UGD+/rWeOAMpkbt5pymDFbA +8L9y7jxmf9nwgnIl0wR0rhKOwT+wJ+xGxTfgWQVnjV/69zX5oPynweOfEmNoRG2X +hJ3Xh8cJvE0zRj4sG+i8nTUChBCjO63hDfdDLpUES3x1Ez1Xqcrjj/laxwe2P3lI +R/nTMc88MyvK8+F4S9Qz2jlS75QSA8kzT3jdFnsZoyEwHzAdBgNVHQ4EFgQUwPFf +jESLTEr9qKO2/HOXgiq6O6gwDQYJYIZIAWUDBAMCBQADPwAwPAIcJBlPnlBiPy0F +M99zCO6fwFMLl+CbzU3vj4T3VQIcKEuzNEd5+ICSNUmkL89jIZxr7jrfUui7w0OX +RDE4MBEGCSqGSIb3DQEJFDEEHgIAYTAjBgkqhkiG9w0BCRUxFgQU0essNYYOWMdT +/A/ozvhbEmwKv2YwggL0BgkqhkiG9w0BBwGgggLlBIIC4TCCAt0wggLZBgsqhkiG +9w0BDAoBAqCCAo4wggKKMBwGCiqGSIb3DQEMAQMwDgQI8K+MRZ3EoKQCAggABIIC +aGUbReB6byOtQd7BAAym6y+S1O6URFnEjYs+aFVTmwRuRDE6d3xToxZUkOaVsUc5 +kR5P6ixifkd/S4yRl+t0Eqvn1yhTwR/ptTm/EL8a7RygPG3/wsSsXUCVEBvtTO3q +G+iXUmLk5FjeiOpCbccOUNTZmPXgnSfw0YYrenjr5Z0MOk4BESe+/V8rvEG71fJ7 +KRE6m1b3E8ad3mz09BnccBFdJyY0xEjwD8KJLnUDVyaopYPnvi2Z7OunsyMWUgx8 +gftqGpk5IhskIEnvgQ9NNjL2JpytbG0nVkpgtBULcKCXtPEqqweY/6m5VFAhkikX +urUiJr+svjRFqkXuv+oPJ+6o/Y4QTJSqHbavsXWEwAo+3IxyMhQwLMf/6iXfBiGL +RIrLON3s6c0AcboGCtn1nfEcaXzNrTXkFpzJSFYGBHZVlXdyptDmsMXZbJlZAPFb +2dIzx9yJHqS3AV560p30399VWSko7HmY7t+EbZH/vrdVD+Vzy2zPXFDtbu70j8C/ +RT21LAjjjrliIop/2Akhz3eOTZcEAoQNBLcNBXoIdo7HiX6KzpKvdW51lWWEcAWf +zl878rJpmIdmvCc4HDkuzcpdvxk+q6pTn5Wh5K+X1ImTwWL+C+s4xHhiNAMzc4dK +eMsmukiAW301uZkjU30vpJ2BjBwrRo+ej9s18ePviy65E9UYeforrPIkaM9lpwID +AB17QgeVuciHiw/g7HmbAacWwoqZc41eipIxqPWHlqEGYeARm0x4zb47qWwcowSO +AwlDuvRorpin25ZhiPesY1SJzFll5fAD0bxoQcry7S+2CetF7c8st3AxODARBgkq +hkiG9w0BCRQxBB4CAGEwIwYJKoZIhvcNAQkVMRYEFNHrLDWGDljHU/wP6M74WxJs +Cr9m diff --git a/test/jdk/sun/security/pkcs12/params/os3 b/test/jdk/sun/security/pkcs12/params/os3 new file mode 100644 index 00000000000..135357c7229 --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/os3 @@ -0,0 +1,43 @@ +MIIH4gIBAzCCB6gGCSqGSIb3DQEHAaCCB5kEggeVMIIHkTCCBJUGCSqGSIb3DQEH +AaCCBIYEggSCMIIEfjCCBHoGCyqGSIb3DQEMCgEDoIIELzCCBCsGCiqGSIb3DQEJ +FgGgggQbBIIEFzCCBBMwggO/oAMCAQICBG7vGDQwDQYJYIZIAWUDBAMCBQAwDDEK +MAgGA1UEAxMBQTAeFw0xODA5MjgxMTI3MzlaFw0xODEyMjcxMTI3MzlaMAwxCjAI +BgNVBAMTAUEwggNCMIICNQYHKoZIzjgEATCCAigCggEBAI95Ndm5qum/q+2Ies9J +UbbzLsWeO683GOjqxJYfPv02BudDUanEGDM5uAnnwq4cU5unR1uF0BGtuLR5h3VJ +hGlcrA6PFLM2CCiiL/onEQo9YqmTRTQJoP5pbEZY+EvdIIGcNwmgEFexla3NACM9 +ulSEtikfnWSO+INEhneXnOwEtDSmrC516Zhd4j2wKS/BEYyf+p2BgeczjbeStzDX +ueNJWS9oCZhyFTkV6j1ri0ZTxjNFj4A7MqTC4PJykCVuTj+KOwg4ocRQ5OGMGimj +fd9eoUPeS2b/BJA+1c8WI+FY1IfGCOl/IRzYHcojy244B2X4IuNCvkhMBXY5OWAc +1mcCHQC69pamhXj3397n+mfJd8eF7zKyM7rlgMC81WldAoIBABamXFggSFBwTnUC +o5dXBA002jo0eMFU1OSlwC0kLuBPluYeS9CQSr2sjzfuseCfMYLSPJBDy2QviABB +YO35ygmzIHannDKmJ/JHPpGHm6LE50S9IIFUTLVbgCw2jR+oPtSJ6U4PoGiOMkKK +XHjEeMaNBSe3HJo6uwsL4SxEaJY559POdNsQGmWqK4f2TGgm2z7HL0tVmYNLtO2w +L3yQ6aSW06VdU1vr/EXU9hn2Pz3tu4c5JcLyJOB3MSltqIfsHkdI+H77X963VIQx +ayIy3uVT3a8CESsNHwLaMJcyJP4nrtqLnUspItm6i+Oe2eEDpjxSgQvGiLfi7UMW +4e8X294DggEFAAKCAQA/itsE4Vrqw42DAl8X67qzfhpHUhMsvafnbxyD9ZDIa5u/ +hLs/9dUGBaW/FW7AmmHtdDo2QLmeFiYEpyMhitKG7J/SWRZ5hgpYqhRIV26Z8a/J +Wiq9LeAxvjtdb+Tw4cYcL6FGKH6WNQ297R8qsPld7UGD+/rWeOAMpkbt5pymDFbA +8L9y7jxmf9nwgnIl0wR0rhKOwT+wJ+xGxTfgWQVnjV/69zX5oPynweOfEmNoRG2X +hJ3Xh8cJvE0zRj4sG+i8nTUChBCjO63hDfdDLpUES3x1Ez1Xqcrjj/laxwe2P3lI +R/nTMc88MyvK8+F4S9Qz2jlS75QSA8kzT3jdFnsZoyEwHzAdBgNVHQ4EFgQUwPFf +jESLTEr9qKO2/HOXgiq6O6gwDQYJYIZIAWUDBAMCBQADPwAwPAIcJBlPnlBiPy0F +M99zCO6fwFMLl+CbzU3vj4T3VQIcKEuzNEd5+ICSNUmkL89jIZxr7jrfUui7w0OX +RDE4MBEGCSqGSIb3DQEJFDEEHgIAYTAjBgkqhkiG9w0BCRUxFgQU0essNYYOWMdT +/A/ozvhbEmwKv2YwggL0BgkqhkiG9w0BBwGgggLlBIIC4TCCAt0wggLZBgsqhkiG +9w0BDAoBAqCCAo4wggKKMBwGCiqGSIb3DQEMAQMwDgQIFvtCm+ogILcCAggABIIC +aLbDb3DKmULPLHfwvcVdp3cbM1Bcj3T/keIzwnOzdMluj8wisUEQA/U1onSgp1eZ +Hfk0TPcgd339Uevuh059GL5yFknH2VHhU6nO8Pz+OVpjab9nSBpWjv+PnlSAKWr6 +5ODx9t5TGPO5V7PBqtxDiU4YeBI6akUlroJz3lSH3dD8t3KBdi3GjnG0S4iBadrW +BGV5izRPIbaDpISAscwDInXZ4HJhWbD14/mEOyKHwAmD+NwxMhAS97SRC7N/rAJD +ACj0dQYb3MW4QqVgF2QBQmOYXq6CsrQvc8faQWpqgH2JYzquTu4vx7xFGuKlXSLU ++9hAo99NID6xYryebjMFe7sJFLXyMYLt9pWn5f72xR0PrH71EpTRQkZVIYUfnxkL +iCFwNgWyPF7NYwieUKQ+JyPq3cllK+kuViiNwEvYO4TJp4XjYMXefXFlarX2llQz +J/tu9LJu9eA9A528i7hvJ0ZFpYtZA40CWaJRlCKZqT9P/YQGiNOt31JxJtFyiEpl +i/dh49clBpibQouRKSc/uTNePJ1IyaWkgE1SwmmEz+ZSFSlhxS4Ba0+2MsRKoirC +8M6V0A16W4V2af9jVgRpIyRcRfYZBBij2Cu2k/UB/hrqxlYp3nehOC6PAVT40EwC +HO5613cu2LSJDgxEtaNMcj5Zy6KkJ3vB2BxxfdHL6Dz3uLa+8BuEpfLUidccgCgm +MQpxplgLVztIkq6HZy/koMGgv2ywV7LGLlVpKBHmKDO2yvYhr6J2rbNMsh5Bbq9i +YiZVz7TdmqY4L8rEtEuwJA2SgHUV0FhpoD56WTfPZvfYgoHhHu1hBcQxODARBgkq +hkiG9w0BCRQxBB4CAGEwIwYJKoZIhvcNAQkVMRYEFNHrLDWGDljHU/wP6M74WxJs +Cr9mMDEwITAJBgUrDgMCGgUABBRQNcC69+RQUJu5I4ode2JYzXe2KAQI1mkwkuSh +sUUCAggA diff --git a/test/jdk/sun/security/pkcs12/params/os4 b/test/jdk/sun/security/pkcs12/params/os4 new file mode 100644 index 00000000000..76ec1c6df1c --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/os4 @@ -0,0 +1,44 @@ +MIIIGwIBAzCCB9UGCSqGSIb3DQEHAaCCB8YEggfCMIIHvjCCBMkGCSqGSIb3DQEH +BqCCBLowggS2AgEAMIIErwYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQEwDgQIkluN +Qu+v+1gCAggAgIIEgr9xMS47pyB8kvlbU+/Uwh4pfbjeLm4h4FjR1GxKU0ouoct7 +cg/4S1AZfa2vjVCRxkdWLvf88eAtp96E1YVIdDT/3ZSY953eNA/xvNF2HWVJT18H +jEOuNhmVHbuMIbfmG8sm6rwN2e3xnxuCDkYWvLNTiWOcoQTmLfJIqp5J2FLj2zwN +0jApAepDE2NtEaq+edMU+3c3d7b0+n9BB32b5w1LaXzShuN2cpHOYJvkw+h32eyJ +XrjlRB8J9/4XAzyz269UM9QWdxECqBeTfd1m8PhV/9xR9QOIcur0Flv/Cw0j3sos +oMBibypXsV7GzGZKrUAIVAnhYsDB/yxxL/vPjZ8nCzl7iKc+wBNJiXIO04XNg00U +bUBOSeoGs4ns909u09+qtwQf6fCiV8VwP/h5vIGB++Kv06O9CWt20lOv9KZPqZOR +5H0ndbx60LoTsPT5FzOysOWqUNFx6wiggV9Txl38zax/VwOLA01Uq1jPDHEHQWIY +M139MTL+5P43hDBy9TOyO8uzD3eUj3/+pvoyZb2wfV7NmN5WBgP/MDnm6Jk+eFMw +6v4mXwKycIX6qsBNdTc4QAEgcHwv544eqxPiBuxerr5bySSodWjoziEtyzvgNx1f +jGqQDn7VlZlDrn6rlJ0/iX0xv4M/PVngMUezfmW+zo4998NXlurXKbA2FG/U0mqt +Ys0QGYkfoTFwHixYK4Mf7B4pwlHo3FCO+kjv+t1VZxZF/Pr8B1qflgeBJaiqH6oJ +oh1L1vdOh93VowZFUvgmx27Fb3rIUhvGh1rzfhp5OmMaoXP97TwaHLsK2c/BDwJp +cwmfaJByDcrlTAeBsNlzffD0o61ZAhYMZuGFEoyuIpm8qOcIW1dVrYe8tYP7ZTDA +FUmmoymB+6cK8wW5V5BeRmSxU2DnkBDGriEzQTtepQLgzy7LtLU8rs1mIszwTiNj +60MI6gX22taT0C8kpsH/xwKeKw+7tsyL8bk4N8zQ8h/osMdxtO0QVpxikQ3KAinj +nurVqvcqq3n0EqHwRJ+NQMwuERbbDXcRDowQSWJc2HLn8odxL18dvOpu2IQlH2DA +NtZpLqP7EZ36ebA6txlPdH2GUH7V9ZQwF+3t+NbMXrZLx93DAwdpzVDY9a96AFsE +YHd3f3ReT8TzIwB1dOrvIOPO82cIy5/OIaDa9XelY2/dRVfU4cHpNhRZSLmsQfsQ +yorPQi1baNT0GjoCDgynUvP2DWBdIyjZ442ysfNmO5MjmjYEA17ofBapc4xhsU5B ++XgyfVyfeDHNO+zMZvrdMPnXwu+A3ggaQorvQbAfV8JfVSZoyleKjTxNgx61KI3j +dQsEtLQgvAbLsI+Ku7z86HVZ7PH69i3qHtJo8s8Nw4a9QvCCgpiMqw04EQawlZY1 +aCrOsHvElFB0klIlGpMPugJ1YVgSvXtMwLgLMlAr8mQW+10uKMtrVU5Iq6SAkRDe +ff57iqXoKpNJVGsV9ZxrMT7Y5oECJvHLUWtqapsu7Xpp0/DUPcRxAfCj7ZBxEfVW +sBBDmUia+TTVYT7TJPTzMIIC7QYJKoZIhvcNAQcBoIIC3gSCAtowggLWMIIC0gYL +KoZIhvcNAQwKAQKgggKHMIICgzAcBgoqhkiG9w0BDAEBMA4ECLpLJ5EtNx41AgII +AASCAmEutLb3vdtinkV4hEXRDnRPd19WXSTOFI5g3ZLc2liyiQ3fA/gvXQihmZjp +spYf6kWBkI6+hx3AwM1Vg0FerAJAe9MnMZqZtu/pdqaxiPnbdm5lpB2FiLyrCvY+ +8cyISOPi9LRWZCsf24dUBVHJu4W+BULiZSwoakwLy7UxNclcBKrrIz3brm5UF2Xl +CMqI3N+afaHDst2n1BjwX4InnU9p2FY5Em227hdoWWni+IR8fn0yUMz2ma/kgQ2/ +ntr3ursuq27kC3haWW47kitxK2fZIyjs03gQp2sH0u0ReDIt3EswvPWgjT+EkpjW +NgXK7GyWVdjcJDciTnIBs/vvhkcZVuTgflYpFTbzRK1I1M2eXSjxmEKQ8vmA2wRr +IFzrEcMOo5pTFnUxeOfpucV2j5uD8g8Uk9rxkOwaM1q9yipf5qd5MjJBKrqBuqaW +3v9tKwCoJRTRWR+Y7SMjy2aB/Y2pRGMtmPOuUs4q81ket97Vp4R9ruIkIsEvVMg6 +hXWIhP7Or13f7Qr2Xh71Px7VJmMmfhBaXLEfJtD7kVmRAFzPK0QHYDCpLoka/7aZ +AsrRP54XCkDTeTwhFkKLJW68a4s7+bLaHjaGgjb+62/J2CulVG6KDvlo3I2/yB8P +0lWzWJdLJuRnPDPVZTB2HXKb/XJtw1MdcdvxvtzEbSM4naZ1YfYVXzT+zowq7kKk +N0sgLv357q0HsylKT2Rvs94J0ackaiVaBQCHVReSfNPRwQ2IvjvEq3AML+vt06x7 +4lXiPtNsuAnkMA7whVWTdSZTvSPGxesWIS+3kTAybMPkum7KIL8xODARBgkqhkiG +9w0BCRQxBB4CAGEwIwYJKoZIhvcNAQkVMRYEFNHrLDWGDljHU/wP6M74WxJsCr9m +MD0wLTANBglghkgBZQMEAgQFAAQcG2U041U943EvoFbDQVXR7ZMuU8LZJ4EiaB6O +owQIAiAhw9ZbovsCAggA diff --git a/test/jdk/sun/security/pkcs12/params/os5 b/test/jdk/sun/security/pkcs12/params/os5 new file mode 100644 index 00000000000..09c7a92c279 --- /dev/null +++ b/test/jdk/sun/security/pkcs12/params/os5 @@ -0,0 +1,48 @@ +MIII0gIBAzCCCGgGCSqGSIb3DQEHAaCCCFkEgghVMIIIUTCCBRIGCSqGSIb3DQEH +BqCCBQMwggT/AgEAMIIE+AYJKoZIhvcNAQcBMFcGCSqGSIb3DQEFDTBKMCkGCSqG +SIb3DQEFDDAcBAgb15a0ITFWEQICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQME +ASoEEC7w7N9MK45XaZg4OAPhmtWAggSQ2OAIm4D/rCA94AbcuQCpYxG8Td7v6cbY +bnP9twj3Cvt5muXvMV32lMj/ucXPuICt5lXdBMhHVJ8jxJq3t8GBbJbIpmG/CzXv +ImZa/Zt4TLBwKKibvaT6LHocCJAh3eRoHiXdje71KeVmu80d+ygl7w5/fnqc+FO6 +ypDx2OzcVTDMVnBdT9pD9eLCQQBxA8uvZFuY3C5GTONgE8WpvtqLHhjHLAff0T9N +B6eNiFxqP3WVzobcNmOV0H/6Vn5YUcVk7kk5YtYBbeHo5mq7hkoMKtniQiGMd8Qh +GYw6d+OPYBr+CDA/TsGApUxdqMNsdtyn83BEx/6y9BA4veWz54DU5o4PqnvV332V +ZUa3cD+4r5yfRcM5AFCEOppvK5i/3aJllCsKn4yVzHpWn6vmL/qQCZU1epgONmzJ +eCAOTPiDKkc5mJc4qj+ILIVuY+m+n/wNdWgrhr5zGzSGwHgaQMmnhCjF2BlAZL7m +neIPDSqBImCVuA3MWPerkhW9SHbIiAXmIUN/DBI/fiPlryCSN/oMujLJgogADtks +J4ml2zByChWcepayfpi+YVdIc+eNTjAqrW3iD26mnEqyWPjey+lFfvKmUffNnL46 +IMeN33WPjMLi0rmxqsPGLpK8rw81TE6qe8d4SXqgZfzV5uQFEOV/tGZ0QOuXgkc6 +YAsZlYz7QNdh9I7JhwTup/j4nPcgM5NJXvRCVq765MCzV/gdLeO2msuR/VlvIZon +P9HTzqzOkCakT0nV/bdPAMGAhZt7iprgn1Gb/XiA9GK+ejeaZfRW4YJ6oqGI/5gS +RNxdf9I5ThC9efFdPM+3WxKun4bSBjJZCBjAkRlse2nQt/ET51qAt8T1Uw0ON5ch +NoHe/ZE9MNX5/9bt6T9w86Gh/Wfzq8K/93ywlbd7fNOJm/T8HH9yY1Lm3Hg4PgES +feA3VL0JeTWnZu/ngLQ8JWRKKYjNg0BwejoKRZ3PEpnS1ZUxmjcJlgXGn2SWW99+ +j/dQgl80Tn/IJnAUBwxvDjmoWVvAGLglnNbruCWX/bjTg4cJyYVeSQ5fEHyi2pU/ ++bcvVTK9HuWE7cT9rDP4rWPRaAi4UAB9AShx3jgh/g2Va8Tqpow1hqS2eSjm+JfQ +Bk3Nh6dYDgqLW4OjCTVfRa4hzbNck5zcybY3JtC7jKjok31V87W1jPRveWgXYE0z +AZlSRwgnzMujycpXplZ9JMz9QMB7toISVs+ArjN2CZRjLCWRAwLcoKQ7D1A5S8LU +PYXk/y7ovmaSfyN1PYkaelnAuo2zI4YWDM/LL55het4Y8eCo0zFwLSxDrPz5jW8p +A4S1Du5JJ7n52RYmI9+QxwymCUOkWScpIgI/aM6p4s3xfnqGMZUQy+O0qMsczSw0 +i9IVx/C8akDjK/gMlJePYqil/WPfEUl5qAkGn9eu2/kC4XNITiM9xNBDy1d+NvSO +8CjBfDd3pOPqjqeM/dLO660ZZrsvt7LnevJQ+9pq9LeXIrcHpLJp2Oqq5o85lCn7 +/eoykT+ghu6L0OhYaIcDNMvxUAXJfVQQ0rMd+q/72VKdb2HGrB88CjCCAzcGCSqG +SIb3DQEHAaCCAygEggMkMIIDIDCCAxwGCyqGSIb3DQEMCgECoIIC0TCCAs0wVwYJ +KoZIhvcNAQUNMEowKQYJKoZIhvcNAQUMMBwECOnimmypiWZ5AgIIADAMBggqhkiG +9w0CCQUAMB0GCWCGSAFlAwQBKgQQLT9O9V8VM45JpgROXv51VgSCAnAbjtRsnqGS +hwCR6JP8T3ZpY1LUjZM7P/X0VcQ+Fq3cxHtY5Bf55+Ha8cQRGwnptlwnfgxILGIn +1yseJSkKUTDTIlMpoFfDtLCU0lNWzwhYfbajUxIesYsgFYCYn94MgJ+Vb7MWbbW+ +KxhqSGWPDicCZ6dY2zNFUt4dnxJ1NYZGS4ZpfDmdh/bW29vT++Yi1H6Be1Qd+aMj +a9+8Yb69AjnglujqOKTlzaXPb1DfnuteZKUZxqt/6TR1fh28KYxBJ6YvyDzkwhx/ +0ksy/+ItokRWZ9Bb2nmIiss352UtGEi2JOIN+QyOcvSCQCvPucW1DXg53dOhVvEZ +Q1NNKvV9w8s8ao0GotqCK6lfu1fHo2yrp5dV3p03Xxzu1jeuZL27oSaHvW6on90s +oV0djJUHHtYJOp1YWEOJOSqQsHsvPA4G9YMKx00Rl9P0aVSWTNqN96VjEzHOHyCX +lzH5asHLbsTbnvhQHmq1J7Jm3RjncZ+oJOdcvkBoKUnYbqCHJiUOM7McRIEI0VkI +0Endzm+U0z8jZxcpvAowgOf/sWC/ddr/1rNRE/BzVhmqvLfYOkIsvBwm6LpbiOgg +fV0VUHZxTSk6uwYLfNQkJ7i/NQOCAo8MGIHAMi0e5/FAAE7mN2V2HfWCQOiXjsnD +Twb9xztwa6u8tjCXLfW5sws958sxMMM23F61Q6aZcx0k+lc9VaiHgRUjiwKesZjn +E3b/mKSFEIy/9dqC5SpmIctEmoQWcxNNntSzD6WkA0EP5pw0CoAzMSW2Mzp5D6kD +/0pH6xjs9oaMmoq6SoTphNF9hsJJ/uXUSVtO8ZrKB0upHGl+Q5lwLeMxODARBgkq +hkiG9w0BCRQxBB4CAGEwIwYJKoZIhvcNAQkVMRYEFNHrLDWGDljHU/wP6M74WxJs +Cr9mMGEwUTANBglghkgBZQMEAgMFAARAjFxC6pnq5Gh874xeaWuQ+C9mmRbiqBaL +MgfxIfJj3AFVFXGlm7xigHtZGFIrkXNC5croycYgTPMOczulADAOdgQIOFtoK+zm +YOMCAggA diff --git a/test/jdk/sun/security/tools/keytool/ProbingFailure.java b/test/jdk/sun/security/tools/keytool/ProbingFailure.java index 1629a2cc717..703c13877ed 100644 --- a/test/jdk/sun/security/tools/keytool/ProbingFailure.java +++ b/test/jdk/sun/security/tools/keytool/ProbingFailure.java @@ -62,7 +62,7 @@ public class ProbingFailure { kt("-list -keystore mks") .shouldHaveExitValue(1) - .shouldContain("This keystore does not support probing"); + .shouldContain("Unrecognized keystore format"); // importkeystore kt("-importkeystore -srckeystore mks -srcstoretype MYKS -destkeystore p12") @@ -70,7 +70,7 @@ public class ProbingFailure { kt("-importkeystore -srckeystore mks -destkeystore p12a") .shouldHaveExitValue(1) - .shouldContain("This keystore does not support probing"); + .shouldContain("Unrecognized keystore format"); // in-place importkeystore kt("-importkeystore -srckeystore mks -srcstoretype MYKS -destkeystore mks -deststoretype myks") diff --git a/test/lib/jdk/test/lib/security/DerUtils.java b/test/lib/jdk/test/lib/security/DerUtils.java new file mode 100644 index 00000000000..c2efaf91503 --- /dev/null +++ b/test/lib/jdk/test/lib/security/DerUtils.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.test.lib.security; + +import jdk.test.lib.Asserts; +import sun.security.util.DerInputStream; +import sun.security.util.DerValue; +import sun.security.util.ObjectIdentifier; + +import java.io.IOException; + +public class DerUtils { + /** + * Returns a DerValue (deep) inside another DerValue. + *

+ * The location of the inner DerValue is expressed as a string, in which + * each character is a step from the outer DerValue into the inner one. + * If it's a number n, the n'th element (starting from 0) of a sequence + * is the next step. If it's 'c', the content of an OctetString parsed + * as a DerValue is the next step. Note that n cannot be bigger than 9. + *

+ * Attention: do not reuse the return value. DerValue is mutable and + * reading it advances a pointer inside. + *

+ * For example, here is a PKCS #12 file: + *

+     * 0000:0845  [] SEQUENCE
+     * 0004:0003  [0]     INTEGER 3
+     * 0007:07FE  [1]     SEQUENCE
+     * 000B:000B  [10]         OID 1.2.840.113549.1.7.1 (data)
+     * 0016:07EF  [11]         cont [0]
+     * 001A:07EB  [110]             OCTET STRING
+     * ...
+     * 
+ * and the content of OCTET string at offset 001A can be parsed as another + * DerValue which is: + *
+     * 0000:07E7  [] SEQUENCE
+     * 0004:0303  [0]     SEQUENCE
+     * 0008:000B  [00]         OID 1.2.840.113549.1.7.1 (data)
+     * ....
+     * 
+ * Then the OID is {@code innerDerValue(data, "110c00").getOID()}. + * + * @param data the outer DerValue. We choose byte[] instead of DerValue + * because DerValue is mutable and cannot be reused. + * @param location the location of the inner DerValue + * @return the inner DerValue, or null if no DerValue is at the location + * @throws IOException if an I/O error happens + */ + public static DerValue innerDerValue(byte[] data, String location) + throws IOException { + + DerValue v = new DerValue(data); + for (char step : location.toCharArray()) { + if (step == 'c') { + v = new DerValue(v.getOctetString()); + } else { + DerInputStream ins = v.getData(); + // skip n DerValue in the sequence + for (int i = 0; i < step - '0'; i++) { + ins.getDerValue(); + } + if (ins.available() > 0) { + v = ins.getDerValue(); + } else { + return null; + } + } + } + return v; + } + + /** + * Ensures that the inner DerValue is the expected ObjectIdentifier. + */ + public static void checkAlg(byte[] der, String location, + ObjectIdentifier expected) throws Exception { + Asserts.assertEQ(innerDerValue(der, location).getOID(), expected); + } + + /** + * Ensures that the inner DerValue is the expected integer. + */ + public static void checkInt(byte[] der, String location, int expected) + throws Exception { + Asserts.assertEQ(innerDerValue(der, location).getInteger(), expected); + } + + /** + * Ensures that there is no inner DerValue at the specified location. + */ + public static void shouldNotExist(byte[] der, String location) + throws Exception { + Asserts.assertTrue(innerDerValue(der, location) == null); + } +} From cf21c5ef116c136f09ac5be0d68f02553d0c7a70 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 13 Dec 2018 12:03:03 +0800 Subject: [PATCH 028/174] 8214568: Use {@systemProperty} for definitions of system properties Reviewed-by: xuelei --- .../security/auth/kerberos/package-info.java | 10 +- .../classes/org/ietf/jgss/package-info.java | 121 +++++++++++++++++ .../share/classes/org/ietf/jgss/package.html | 126 ------------------ .../sun/security/auth/login/ConfigFile.java | 6 +- .../security/auth/module/Krb5LoginModule.java | 4 +- 5 files changed, 131 insertions(+), 136 deletions(-) create mode 100644 src/java.security.jgss/share/classes/org/ietf/jgss/package-info.java delete mode 100644 src/java.security.jgss/share/classes/org/ietf/jgss/package.html diff --git a/src/java.security.jgss/share/classes/javax/security/auth/kerberos/package-info.java b/src/java.security.jgss/share/classes/javax/security/auth/kerberos/package-info.java index b30004bcffe..7b21522a585 100644 --- a/src/java.security.jgss/share/classes/javax/security/auth/kerberos/package-info.java +++ b/src/java.security.jgss/share/classes/javax/security/auth/kerberos/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -38,10 +38,10 @@ * * You can provide the name of your default realm and Key Distribution * Center (KDC) host for that realm using the system properties - * {@code java.security.krb5.realm} and {@code java.security.krb5.kdc}. - * Both properties must be set. - * Alternatively, the {@code java.security.krb5.conf} system property can - * be set to the location of an MIT style {@code krb5.conf} configuration + * {@systemProperty java.security.krb5.realm} and + * {@systemProperty java.security.krb5.kdc}. Both properties must be set. + * Alternatively, the {@systemProperty java.security.krb5.conf} system property + * can be set to the location of an MIT style {@code krb5.conf} configuration * file. If none of these system properties are set, the {@code krb5.conf} * file is searched for in an implementation-specific manner. Typically, * an implementation will first look for a {@code krb5.conf} file in diff --git a/src/java.security.jgss/share/classes/org/ietf/jgss/package-info.java b/src/java.security.jgss/share/classes/org/ietf/jgss/package-info.java new file mode 100644 index 00000000000..3f5a7e11a3e --- /dev/null +++ b/src/java.security.jgss/share/classes/org/ietf/jgss/package-info.java @@ -0,0 +1,121 @@ +/* + * 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. 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. + */ + +/** + * This package presents a framework that allows application developers to + * make use of security services like authentication, data integrity and + * data confidentiality from a variety of underlying security mechanisms + * like Kerberos, using a unified API. The security mechanisms that an + * application can + * chose to use are identified with unique object identifiers. One example + * of such a mechanism is the Kerberos v5 GSS-API mechanism (object + * identifier 1.2.840.113554.1.2.2). This mechanism is available through + * the default instance of the GSSManager class.

+ * + * The GSS-API is defined in a language independent way in + * RFC 2743. The Java + * language bindings are defined in + * RFC 2853

+ * + * An application starts out by instantiating a {@code GSSManager} + * which then serves as a factory for a security context. An application + * can use specific principal names and credentials that are also created + * using the GSSManager; or it can instantiate a + * context with system defaults. It then goes through a context + * establishment loop. Once a context is established with the + * peer, authentication is complete. Data protection such as integrity + * and confidentiality can then be obtained from this context.

+ * + * The GSS-API does not perform any communication with the peer. It merely + * produces tokens that the application must somehow transport to the + * other end. + * + *

Credential Acquisition

+ * The GSS-API itself does not dictate how an underlying mechanism + * obtains the credentials that are needed for authentication. It is + * assumed that prior to calling the GSS-API, these credentials are + * obtained and stored in a location that the mechanism provider is + * aware of. However, the default model in the Java platform will be + * that mechanism providers must obtain credentials only from the private + * or public credential sets associated with the + * {@link javax.security.auth.Subject Subject} in the + * current access control context. The Kerberos v5 + * mechanism will search for the required INITIATE and ACCEPT credentials + * ({@link javax.security.auth.kerberos.KerberosTicket KerberosTicket} and + * {@link javax.security.auth.kerberos.KerberosKey KerberosKey}) in + * the private credential set where as some other mechanism might look + * in the public set or in both. If the desired credential is not + * present in the appropriate sets of the current Subject, the GSS-API + * call must fail.

+ * + * This model has the advantage that credential management + * is simple and predictable from the applications point of view. An + * application, given the right permissions, can purge the credentials in + * the Subject or renew them using standard Java API's. If it purged + * the credentials, it would be sure that the JGSS mechanism would fail, + * or if it renewed a time based credential it would be sure that a JGSS + * mechanism would succeed.

+ * + * This model does require that a {@link + * javax.security.auth.login JAAS login} be performed in order to + * authenticate and populate a Subject that the JGSS mechanism can later + * utilize. However, applications have the ability to relax this + * restriction by means of a system property: + * {@systemProperty javax.security.auth.useSubjectCredsOnly}. By default + * this system property will be assumed to be {@code true} (even when + * it is unset) indicating that providers must only use the credentials + * that are present in the current Subject. However, if this property is + * explicitly set to false by the application, then it indicates that + * the provider is free to use any credentials cache of its choice. Such + * a credential cache might be a disk cache, an in-memory cache, or even + * just the current Subject itself. + * + *

Related Documentation

+ *

+ * For an online tutorial on using Java GSS-API, please see + * {@extLink security_guide_jgss_tutorial + * Introduction to JAAS and Java GSS-API}. + *

+ * + * + * + * @since 1.4 + * */ +package org.ietf.jgss; diff --git a/src/java.security.jgss/share/classes/org/ietf/jgss/package.html b/src/java.security.jgss/share/classes/org/ietf/jgss/package.html deleted file mode 100644 index 4c2d4cd006a..00000000000 --- a/src/java.security.jgss/share/classes/org/ietf/jgss/package.html +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - This package presents a framework that allows application developers to - make use of security services like authentication, data integrity and - data confidentiality from a variety of underlying security mechanisms - like Kerberos, using a unified API. The security mechanisms that an - application can - chose to use are identified with unique object identifiers. One example - of such a mechanism is the Kerberos v5 GSS-API mechanism (object - identifier 1.2.840.113554.1.2.2). This mechanism is available through - the default instance of the GSSManager class.

- - The GSS-API is defined in a language independent way in - RFC 2743. The Java - language bindings are defined in - RFC 2853

- - An application starts out by instantiating a GSSManager - which then serves as a factory for a security context. An application - can use specific principal names and credentials that are also created - using the GSSManager; or it can instantiate a - context with system defaults. It then goes through a context - establishment loop. Once a context is established with the - peer, authentication is complete. Data protection such as integrity - and confidentiality can then be obtained from this context.

- - The GSS-API does not perform any communication with the peer. It merely - produces tokens that the application must somehow transport to the - other end. - -

Credential Acquisition

- The GSS-API itself does not dictate how an underlying mechanism - obtains the credentials that are needed for authentication. It is - assumed that prior to calling the GSS-API, these credentials are - obtained and stored in a location that the mechanism provider is - aware of. However, the default model in the Java platform will be - that mechanism providers must obtain credentials only from the private - or public credential sets associated with the - {@link javax.security.auth.Subject Subject} in the - current access control context. The Kerberos v5 - mechanism will search for the required INITIATE and ACCEPT credentials - ({@link javax.security.auth.kerberos.KerberosTicket KerberosTicket} and - {@link javax.security.auth.kerberos.KerberosKey KerberosKey}) in - the private credential set where as some other mechanism might look - in the public set or in both. If the desired credential is not - present in the appropriate sets of the current Subject, the GSS-API - call must fail.

- - This model has the advantage that credential management - is simple and predictable from the applications point of view. An - application, given the right permissions, can purge the credentials in - the Subject or renew them using standard Java API's. If it purged - the credentials, it would be sure that the JGSS mechanism would fail, - or if it renewed a time based credential it would be sure that a JGSS - mechanism would succeed.

- - This model does require that a {@link - javax.security.auth.login JAAS login} be performed in order to - authenticate and populate a Subject that the JGSS mechanism can later - utilize. However, applications have the ability to relax this - restriction by means of a system property: - javax.security.auth.useSubjectCredsOnly. By default - this system property will be assumed to be true (even when - it is unset) indicating that providers must only use the credentials - that are present in the current Subject. However, if this property is - explicitly set to false by the application, then it indicates that - the provider is free to use any credentials cache of its choice. Such - a credential cache might be a disk cache, an in-memory cache, or even - just the current Subject itself. - -

Related Documentation

-

-For an online tutorial on using Java GSS-API, please see -{@extLink security_guide_jgss_tutorial -Introduction to JAAS and Java GSS-API}. -

- - - -@since 1.4 - - diff --git a/src/jdk.security.auth/share/classes/com/sun/security/auth/login/ConfigFile.java b/src/jdk.security.auth/share/classes/com/sun/security/auth/login/ConfigFile.java index 3e6dc7da579..2d269052ef0 100644 --- a/src/jdk.security.auth/share/classes/com/sun/security/auth/login/ConfigFile.java +++ b/src/jdk.security.auth/share/classes/com/sun/security/auth/login/ConfigFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -55,8 +55,8 @@ import java.net.URI; * each configuration. * *
  • - * The {@code java.lang.System} property - * java.security.auth.login.config + * The system property + * {@systemProperty java.security.auth.login.config} * may also be set to a {@code URL} pointing to another * login configuration file * (which is the case when a user uses the -D switch at runtime). diff --git a/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java b/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java index 62138dee284..415cd094553 100644 --- a/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java +++ b/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -84,7 +84,7 @@ import static sun.security.util.ResourcesMgr.getAuthResourceString; * by using the option {@code principal}. The principal name * can either be a simple user name, a service name such as * {@code host/mission.eng.sun.com}, or "*". The principal can also - * be set using the system property {@code sun.security.krb5.principal}. + * be set using the system property {@systemProperty sun.security.krb5.principal}. * This property is checked during login. If this property is not set, then * the principal name from the configuration is used. In the * case where the principal property is not set and the principal From 3d9ab36ca0af296733f1e030579c09bc76692b26 Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Wed, 12 Dec 2018 20:13:39 -0800 Subject: [PATCH 029/174] 8215326: Test java/util/concurrent/ConcurrentHashMap/ToArray.java hangs after j.u.c updates Reviewed-by: martin, dholmes --- .../java/util/concurrent/ForkJoinPool.java | 113 ++++++++---------- 1 file changed, 52 insertions(+), 61 deletions(-) diff --git a/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java b/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java index e9f26183665..5ff7f26b6aa 100644 --- a/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java +++ b/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java @@ -445,7 +445,8 @@ public class ForkJoinPool extends AbstractExecutorService { * if to its current value). This would be extremely costly. So * we relax it in several ways: (1) Producers only signal when * their queue is possibly empty at some point during a push - * operation. (2) Other workers propagate this signal + * operation (which requires conservatively checking size zero or + * one to cover races). (2) Other workers propagate this signal * when they find tasks in a queue with size greater than one. (3) * Workers only enqueue after scanning (see below) and not finding * any tasks. (4) Rather than CASing ctl to its current value in @@ -761,8 +762,10 @@ public class ForkJoinPool extends AbstractExecutorService { /** * The maximum number of top-level polls per worker before - * checking other queues, expressed as a bit shift. See above for - * rationale. + * checking other queues, expressed as a bit shift to, in effect, + * multiply by pool size, and then use as random value mask, so + * average bound is about poolSize*(1< task) { ForkJoinTask[] a; - int s = top, d = s - base, cap, m; + int s = top, d, cap, m; ForkJoinPool p = pool; if ((a = array) != null && (cap = a.length) > 0) { QA.setRelease(a, (m = cap - 1) & s, task); top = s + 1; - if (d == m) - growArray(false); - else if (QA.getAcquire(a, m & (s - 1)) == null && p != null) { - VarHandle.fullFence(); // was empty - p.signalWork(null); + if (((d = s - (int)BASE.getAcquire(this)) & ~1) == 0 && + p != null) { // size 0 or 1 + VarHandle.fullFence(); + p.signalWork(); } + else if (d == m) + growArray(false); } } @@ -859,16 +863,16 @@ public class ForkJoinPool extends AbstractExecutorService { final boolean lockedPush(ForkJoinTask task) { ForkJoinTask[] a; boolean signal = false; - int s = top, d = s - base, cap, m; + int s = top, b = base, cap, d; if ((a = array) != null && (cap = a.length) > 0) { - a[(m = (cap - 1)) & s] = task; + a[(cap - 1) & s] = task; top = s + 1; - if (d == m) + if (b - s + cap - 1 == 0) growArray(true); else { phase = 0; // full volatile unlock - if (a[m & (s - 1)] == null) - signal = true; // was empty + if (((s - base) & ~1) == 0) // size 0 or 1 + signal = true; } } return signal; @@ -1010,30 +1014,25 @@ public class ForkJoinPool extends AbstractExecutorService { * queue, up to bound n (to avoid infinite unfairness). */ final void topLevelExec(ForkJoinTask t, WorkQueue q, int n) { - int nstolen = 1; - for (int j = 0;;) { - if (t != null) + if (t != null && q != null) { // hoist checks + int nstolen = 1; + for (;;) { t.doExec(); - if (j++ <= n) - t = nextLocalTask(); - else { - j = 0; - t = null; - } - if (t == null) { - if (q != null && (t = q.poll()) != null) { - ++nstolen; - j = 0; - } - else if (j != 0) + if (n-- < 0) break; + else if ((t = nextLocalTask()) == null) { + if ((t = q.poll()) == null) + break; + else + ++nstolen; + } } + ForkJoinWorkerThread thread = owner; + nsteals += nstolen; + source = 0; + if (thread != null) + thread.afterTopLevelExec(); } - ForkJoinWorkerThread thread = owner; - nsteals += nstolen; - source = 0; - if (thread != null) - thread.afterTopLevelExec(); } /** @@ -1456,7 +1455,7 @@ public class ForkJoinPool extends AbstractExecutorService { if (!tryTerminate(false, false) && // possibly replace worker w != null && w.array != null) // avoid repeated failures - signalWork(null); + signalWork(); if (ex == null) // help clean on way out ForkJoinTask.helpExpungeStaleExceptions(); @@ -1466,9 +1465,8 @@ public class ForkJoinPool extends AbstractExecutorService { /** * Tries to create or release a worker if too few are running. - * @param q if non-null recheck if empty on CAS failure */ - final void signalWork(WorkQueue q) { + final void signalWork() { for (;;) { long c; int sp; WorkQueue[] ws; int i; WorkQueue v; if ((c = ctl) >= 0L) // enough workers @@ -1495,8 +1493,6 @@ public class ForkJoinPool extends AbstractExecutorService { LockSupport.unpark(vt); break; } - else if (q != null && q.isEmpty()) // no need to retry - break; } } } @@ -1617,24 +1613,19 @@ public class ForkJoinPool extends AbstractExecutorService { else if (rc <= 0 && (md & SHUTDOWN) != 0 && tryTerminate(false, false)) break; // quiescent shutdown - else if (w.phase < 0) { - if (rc <= 0 && pred != 0 && phase == (int)c) { - long nc = (UC_MASK & (c - TC_UNIT)) | (SP_MASK & pred); - long d = keepAlive + System.currentTimeMillis(); - LockSupport.parkUntil(this, d); - if (ctl == c && // drop on timeout if all idle - d - System.currentTimeMillis() <= TIMEOUT_SLOP && - CTL.compareAndSet(this, c, nc)) { - w.phase = QUIET; - break; - } - } - else { - LockSupport.park(this); - if (w.phase < 0) // one spurious wakeup check - LockSupport.park(this); + else if (rc <= 0 && pred != 0 && phase == (int)c) { + long nc = (UC_MASK & (c - TC_UNIT)) | (SP_MASK & pred); + long d = keepAlive + System.currentTimeMillis(); + LockSupport.parkUntil(this, d); + if (ctl == c && // drop on timeout if all idle + d - System.currentTimeMillis() <= TIMEOUT_SLOP && + CTL.compareAndSet(this, c, nc)) { + w.phase = QUIET; + break; } } + else if (w.phase < 0) + LockSupport.park(this); // OK if spuriously woken w.source = 0; // disable signal } } @@ -1650,8 +1641,8 @@ public class ForkJoinPool extends AbstractExecutorService { WorkQueue[] ws; int n; if ((ws = workQueues) != null && (n = ws.length) > 0 && w != null) { for (int m = n - 1, j = r & m;;) { - WorkQueue q; int b, s; - if ((q = ws[j]) != null && (s = q.top) != (b = q.base)) { + WorkQueue q; int b; + if ((q = ws[j]) != null && q.top != (b = q.base)) { int qid = q.id; ForkJoinTask[] a; int cap, k; ForkJoinTask t; if ((a = q.array) != null && (cap = a.length) > 0) { @@ -1660,10 +1651,10 @@ public class ForkJoinPool extends AbstractExecutorService { QA.compareAndSet(a, k, t, null)) { q.base = b; w.source = qid; - if (s != b && a[(cap - 1) & b] != null) - signalWork(q); // help signal if more tasks + if (q.top - b > 0) + signalWork(); w.topLevelExec(t, q, // random fairness bound - (r | (1 << TOP_BOUND_SHIFT)) & SMASK); + r & ((n << TOP_BOUND_SHIFT) - 1)); } } return true; @@ -1909,7 +1900,7 @@ public class ForkJoinPool extends AbstractExecutorService { r = ThreadLocalRandom.advanceProbe(r); else { if (q.lockedPush(task)) - signalWork(null); + signalWork(); return; } } From 017c702b8ae43b69b47ecc1091e9d4a010b7597d Mon Sep 17 00:00:00 2001 From: John Jiang Date: Thu, 13 Dec 2018 12:34:35 +0800 Subject: [PATCH 030/174] 8214937: sun/security/tools/jarsigner/warnings/NoTimestampTest.java failed due to unexpected expiration date Reviewed-by: xuelei --- .../jarsigner/warnings/NoTimestampTest.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java b/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java index d25984fec01..b2ccd6e5f9b 100644 --- a/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java +++ b/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java @@ -21,8 +21,13 @@ * questions. */ +import java.io.FileInputStream; +import java.io.InputStream; +import java.security.KeyStore; +import java.security.cert.X509Certificate; import java.util.Date; import java.util.Locale; + import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.util.JarUtils; @@ -61,16 +66,14 @@ public class NoTimestampTest extends Test { Utils.createFiles(FIRST_FILE); JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE); - // calculate certificate expiration date - Date expirationDate = new Date(System.currentTimeMillis() + VALIDITY - * 24 * 60 * 60 * 1000L); - // create key pair createAlias(CA_KEY_ALIAS); createAlias(KEY_ALIAS); issueCert(KEY_ALIAS, "-validity", Integer.toString(VALIDITY)); + Date expirationDate = getCertExpirationDate(); + // sign jar file OutputAnalyzer analyzer = jarsigner( "-J-Duser.timezone=" + timezone, @@ -114,4 +117,12 @@ public class NoTimestampTest extends Test { System.out.println("Test passed"); } + private static Date getCertExpirationDate() throws Exception { + KeyStore ks = KeyStore.getInstance("JKS"); + try (InputStream in = new FileInputStream(KEYSTORE)) { + ks.load(in, PASSWORD.toCharArray()); + } + X509Certificate cert = (X509Certificate) ks.getCertificate(KEY_ALIAS); + return cert.getNotAfter(); + } } From a2541e687bfe820521278658c092682bb82787c8 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 12 Dec 2018 21:02:46 -0800 Subject: [PATCH 031/174] 8215317: [GRAAL] unit test CheckGraalIntrinsics failed after 8213754 Fix CheckGraalIntrinsics test for new intrinsics. Reviewed-by: iveresov, never --- .../compiler/hotspot/test/CheckGraalIntrinsics.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java index 191bb3bba57..52feb6be87f 100644 --- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java +++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java @@ -374,6 +374,14 @@ public class CheckGraalIntrinsics extends GraalTest { "jdk/jfr/internal/JVM.getEventWriter()Ljava/lang/Object;"); } + if (isJDK12OrHigher()) { + add(toBeInvestigated, + "java/lang/CharacterDataLatin1.isDigit(I)Z", + "java/lang/CharacterDataLatin1.isLowerCase(I)Z", + "java/lang/CharacterDataLatin1.isUpperCase(I)Z", + "java/lang/CharacterDataLatin1.isWhitespace(I)Z"); + } + if (!config.inlineNotify()) { add(ignore, "java/lang/Object.notify()V"); } From 966aaa1f9b6de04fb65a39931d6b0769e2c859ba Mon Sep 17 00:00:00 2001 From: Ekaterina Pavlova Date: Wed, 12 Dec 2018 22:23:48 -0800 Subject: [PATCH 032/174] 8215314: [Graal] Enable org.graalvm.compiler.core.test.CountedLoopTest Reviewed-by: dlong --- test/hotspot/jtreg/ProblemList-graal.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/test/hotspot/jtreg/ProblemList-graal.txt b/test/hotspot/jtreg/ProblemList-graal.txt index 1b7f143323d..8e6076a3c6a 100644 --- a/test/hotspot/jtreg/ProblemList-graal.txt +++ b/test/hotspot/jtreg/ProblemList-graal.txt @@ -159,7 +159,6 @@ org.graalvm.compiler.hotspot.test.CompilationWrapperTest org.graalvm.compiler.replacements.test.classfile.ClassfileBytecodeProviderTest 8205081 org.graalvm.compiler.core.test.deopt.CompiledMethodTest 8202955 -org.graalvm.compiler.core.test.CountedLoopTest 8211179 org.graalvm.compiler.debug.test.DebugContextTest 8203504 org.graalvm.compiler.hotspot.test.GraalOSRTest 8206947 From 79d7ae76335956b9924ca1bc9fddb6342c20c3f0 Mon Sep 17 00:00:00 2001 From: Jamsheed Mohammed C M Date: Wed, 12 Dec 2018 23:08:01 -0800 Subject: [PATCH 033/174] 8211034: OnStackReplacePercentage option checking has bugs Fixed the constraint checks Reviewed-by: kvn --- .../share/interpreter/invocationCounter.cpp | 4 +- src/hotspot/share/oops/methodCounters.hpp | 4 +- src/hotspot/share/opto/parseHelper.cpp | 6 +-- .../flags/jvmFlagConstraintsCompiler.cpp | 43 ++++++++----------- .../whitebox/vm_flags/IntxTest.java | 15 ++++++- 5 files changed, 39 insertions(+), 33 deletions(-) diff --git a/src/hotspot/share/interpreter/invocationCounter.cpp b/src/hotspot/share/interpreter/invocationCounter.cpp index d9187bd8b2d..9bf6afb13da 100644 --- a/src/hotspot/share/interpreter/invocationCounter.cpp +++ b/src/hotspot/share/interpreter/invocationCounter.cpp @@ -153,9 +153,9 @@ void InvocationCounter::reinitialize(bool delay_overflow) { // don't need the shift by number_of_noncount_bits, but we do need to adjust // the factor by which we scale the threshold. if (ProfileInterpreter) { - InterpreterBackwardBranchLimit = (CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100; + InterpreterBackwardBranchLimit = (int)((int64_t)CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage) / 100); } else { - InterpreterBackwardBranchLimit = ((CompileThreshold * OnStackReplacePercentage) / 100) << number_of_noncount_bits; + InterpreterBackwardBranchLimit = (int)(((int64_t)CompileThreshold * OnStackReplacePercentage / 100) << number_of_noncount_bits); } assert(0 <= InterpreterBackwardBranchLimit, diff --git a/src/hotspot/share/oops/methodCounters.hpp b/src/hotspot/share/oops/methodCounters.hpp index 76e2ee36ea1..b955a089c6d 100644 --- a/src/hotspot/share/oops/methodCounters.hpp +++ b/src/hotspot/share/oops/methodCounters.hpp @@ -103,9 +103,9 @@ class MethodCounters : public Metadata { // If interpreter profiling is enabled, the backward branch limit // is compared against the method data counter rather than an invocation // counter, therefore no shifting of bits is required. - _interpreter_backward_branch_limit = (compile_threshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100; + _interpreter_backward_branch_limit = (int)((int64_t)compile_threshold * (OnStackReplacePercentage - InterpreterProfilePercentage) / 100); } else { - _interpreter_backward_branch_limit = ((compile_threshold * OnStackReplacePercentage) / 100) << InvocationCounter::count_shift; + _interpreter_backward_branch_limit = (int)(((int64_t)compile_threshold * OnStackReplacePercentage / 100) << InvocationCounter::count_shift); } _interpreter_profile_limit = ((compile_threshold * InterpreterProfilePercentage) / 100) << InvocationCounter::count_shift; _invoke_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift; diff --git a/src/hotspot/share/opto/parseHelper.cpp b/src/hotspot/share/opto/parseHelper.cpp index c16d7a1de4a..6bfa31b07a5 100644 --- a/src/hotspot/share/opto/parseHelper.cpp +++ b/src/hotspot/share/opto/parseHelper.cpp @@ -471,15 +471,15 @@ void Parse::profile_taken_branch(int target_bci, bool force_update) { if (osr_site) { ciProfileData* data = md->bci_to_data(cur_bci); assert(data != NULL && data->is_JumpData(), "need JumpData for taken branch"); - int limit = (CompileThreshold - * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100; + int limit = (int)((int64_t)CompileThreshold + * (OnStackReplacePercentage - InterpreterProfilePercentage) / 100); test_for_osr_md_counter_at(md, data, JumpData::taken_offset(), limit); } } else { // With method data update off, use the invocation counter to trigger an // OSR compilation, as done in the interpreter. if (osr_site) { - int limit = (CompileThreshold * OnStackReplacePercentage) / 100; + int limit = (int)((int64_t)CompileThreshold * OnStackReplacePercentage / 100); increment_and_test_invocation_counter(limit); } } diff --git a/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp b/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp index 49abf49aa2c..7827db916a3 100644 --- a/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp +++ b/src/hotspot/share/runtime/flags/jvmFlagConstraintsCompiler.cpp @@ -145,47 +145,42 @@ JVMFlag::Error CompileThresholdConstraintFunc(intx value, bool verbose) { } JVMFlag::Error OnStackReplacePercentageConstraintFunc(intx value, bool verbose) { - int backward_branch_limit; + int64_t max_percentage_limit = INT_MAX; + if (!ProfileInterpreter) { + max_percentage_limit = (max_percentage_limit>>InvocationCounter::count_shift); + } + max_percentage_limit = CompileThreshold == 0 ? max_percentage_limit*100 : max_percentage_limit*100/CompileThreshold; + if (ProfileInterpreter) { - if (OnStackReplacePercentage < InterpreterProfilePercentage) { + if (value < InterpreterProfilePercentage) { JVMFlag::printError(verbose, "OnStackReplacePercentage (" INTX_FORMAT ") must be " "larger than InterpreterProfilePercentage (" INTX_FORMAT ")\n", - OnStackReplacePercentage, InterpreterProfilePercentage); + value, InterpreterProfilePercentage); return JVMFlag::VIOLATES_CONSTRAINT; } - backward_branch_limit = ((CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100) - << InvocationCounter::count_shift; - - if (backward_branch_limit < 0) { + max_percentage_limit += InterpreterProfilePercentage; + if (value > max_percentage_limit) { JVMFlag::printError(verbose, - "CompileThreshold * (InterpreterProfilePercentage - OnStackReplacePercentage) / 100 = " - INTX_FORMAT " " - "must be between 0 and %d, try changing " - "CompileThreshold, InterpreterProfilePercentage, and/or OnStackReplacePercentage\n", - (CompileThreshold * (OnStackReplacePercentage - InterpreterProfilePercentage)) / 100, - INT_MAX >> InvocationCounter::count_shift); + "OnStackReplacePercentage (" INTX_FORMAT ") must be between 0 and " INT64_FORMAT "\n", + value, + max_percentage_limit); return JVMFlag::VIOLATES_CONSTRAINT; } } else { - if (OnStackReplacePercentage < 0 ) { + if (value < 0) { JVMFlag::printError(verbose, "OnStackReplacePercentage (" INTX_FORMAT ") must be " - "non-negative\n", OnStackReplacePercentage); + "non-negative\n", value); return JVMFlag::VIOLATES_CONSTRAINT; } - backward_branch_limit = ((CompileThreshold * OnStackReplacePercentage) / 100) - << InvocationCounter::count_shift; - - if (backward_branch_limit < 0) { + if (value > max_percentage_limit) { JVMFlag::printError(verbose, - "CompileThreshold * OnStackReplacePercentage / 100 = " INTX_FORMAT " " - "must be between 0 and %d, try changing " - "CompileThreshold and/or OnStackReplacePercentage\n", - (CompileThreshold * OnStackReplacePercentage) / 100, - INT_MAX >> InvocationCounter::count_shift); + "OnStackReplacePercentage (" INTX_FORMAT ") must be between 0 and " INT64_FORMAT "\n", + value, + max_percentage_limit); return JVMFlag::VIOLATES_CONSTRAINT; } } diff --git a/test/hotspot/jtreg/testlibrary_tests/whitebox/vm_flags/IntxTest.java b/test/hotspot/jtreg/testlibrary_tests/whitebox/vm_flags/IntxTest.java index 3080857a053..a606f7014af 100644 --- a/test/hotspot/jtreg/testlibrary_tests/whitebox/vm_flags/IntxTest.java +++ b/test/hotspot/jtreg/testlibrary_tests/whitebox/vm_flags/IntxTest.java @@ -34,17 +34,28 @@ * @summary testing of WB::set/getIntxVMFlag() * @author igor.ignatyev@oracle.com */ - +import jdk.test.lib.Platform; public class IntxTest { private static final String FLAG_NAME = "OnStackReplacePercentage"; private static final String FLAG_DEBUG_NAME = "InlineFrequencyCount"; - private static final Long[] TESTS = {0L, 100L, (long) Integer.MAX_VALUE}; + private static final long COMPILE_THRESHOLD = VmFlagTest.WHITE_BOX.getIntxVMFlag("CompileThreshold"); + private static final Long[] TESTS = {0L, 100L, (long)(Integer.MAX_VALUE>>3)*100L}; public static void main(String[] args) throws Exception { + find_and_set_max_osrp(); VmFlagTest.runTest(FLAG_NAME, TESTS, VmFlagTest.WHITE_BOX::setIntxVMFlag, VmFlagTest.WHITE_BOX::getIntxVMFlag); VmFlagTest.runTest(FLAG_DEBUG_NAME, VmFlagTest.WHITE_BOX::getIntxVMFlag); } + + static void find_and_set_max_osrp() { + long max_percentage_limit = (long)(Integer.MAX_VALUE>>3)*100L; + max_percentage_limit = COMPILE_THRESHOLD == 0 ? max_percentage_limit : max_percentage_limit/COMPILE_THRESHOLD; + if (Platform.is32bit() && max_percentage_limit > Integer.MAX_VALUE) { + max_percentage_limit = Integer.MAX_VALUE; + } + TESTS[2] = max_percentage_limit; + } } From 35bd56fcdfc8f36116c0d4967b2bfcb448f20476 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Thu, 13 Dec 2018 08:26:07 +0100 Subject: [PATCH 034/174] 8215243: JShell tests failing intermitently with \"Problem cleaning up the following threads:\" Do not reset closed state in the StopDetectingInputStream.write Reviewed-by: rfield --- .../jdk/internal/jshell/tool/StopDetectingInputStream.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/StopDetectingInputStream.java b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/StopDetectingInputStream.java index 578f5cf6893..4a3fc773c2d 100644 --- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/StopDetectingInputStream.java +++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/StopDetectingInputStream.java @@ -113,7 +113,7 @@ public final class StopDetectingInputStream extends InputStream { } public synchronized void write(int b) { - if (state != State.BUFFER) { + if (state == State.READ) { state = State.WAIT; } int newEnd = (end + 1) % buffer.length; From 12355f9ca82548b9155151fc2142a8206dae76a1 Mon Sep 17 00:00:00 2001 From: Jini George Date: Thu, 13 Dec 2018 13:03:26 +0530 Subject: [PATCH 035/174] 8202884: SA: Attach/detach might fail on Linux if debugee application create/destroy threads during attaching While doing a ptrace attach, do not attach to threads which are in the process of exiting or are zombies -- skip these threads. Reviewed-by: jcbeyler, ysuenaga --- .../linux/native/libsaproc/libproc_impl.c | 25 ++++ .../linux/native/libsaproc/libproc_impl.h | 5 +- .../linux/native/libsaproc/ps_proc.c | 137 ++++++++++++++---- 3 files changed, 138 insertions(+), 29 deletions(-) diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c b/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c index c19d4013596..61259b56a61 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c @@ -274,6 +274,26 @@ thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwp return newthr; } +void delete_thread_info(struct ps_prochandle* ph, thread_info* thr_to_be_removed) { + thread_info* current_thr = ph->threads; + + if (thr_to_be_removed == ph->threads) { + ph->threads = ph->threads->next; + } else { + thread_info* previous_thr; + while (current_thr && current_thr != thr_to_be_removed) { + previous_thr = current_thr; + current_thr = current_thr->next; + } + if (current_thr == NULL) { + print_error("Could not find the thread to be removed"); + return; + } + previous_thr->next = current_thr->next; + } + ph->num_threads--; + free(current_thr); +} // struct used for client data from thread_db callback struct thread_db_client_data { @@ -296,6 +316,11 @@ static int thread_db_callback(const td_thrhandle_t *th_p, void *data) { print_debug("thread_db : pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid); + if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE) { + print_debug("Skipping pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid); + return TD_OK; + } + if (ptr->callback(ptr->ph, ti.ti_tid, ti.ti_lid) != true) return TD_ERR; diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.h b/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.h index bc907a97093..2a969046367 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.h +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -113,6 +113,9 @@ typedef bool (*thread_info_callback)(struct ps_prochandle* ph, pthread_t pid, lw // reads thread info using libthread_db and calls above callback for each thread bool read_thread_info(struct ps_prochandle* ph, thread_info_callback cb); +// deletes a thread from the thread list +void delete_thread_info(struct ps_prochandle* ph, thread_info* thr); + // adds a new shared object to lib list, returns NULL on failure lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base); diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/ps_proc.c b/src/jdk.hotspot.agent/linux/native/libsaproc/ps_proc.c index a35531e621d..79e936126b9 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/ps_proc.c +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/ps_proc.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -46,6 +47,12 @@ // This file has the libproc implementation specific to live process // For core files, refer to ps_core.c +typedef enum { + ATTACH_SUCCESS, + ATTACH_FAIL, + ATTACH_THREAD_DEAD +} attach_state_t; + static inline uintptr_t align(uintptr_t ptr, size_t size) { return (ptr & ~(size - 1)); } @@ -168,9 +175,10 @@ static bool ptrace_continue(pid_t pid, int signal) { // waits until the ATTACH has stopped the process // by signal SIGSTOP -static bool ptrace_waitpid(pid_t pid) { +static attach_state_t ptrace_waitpid(pid_t pid) { int ret; int status; + errno = 0; while (true) { // Wait for debuggee to stop. ret = waitpid(pid, &status, 0); @@ -185,15 +193,15 @@ static bool ptrace_waitpid(pid_t pid) { // will go to sleep. if (WSTOPSIG(status) == SIGSTOP) { // Debuggee stopped by SIGSTOP. - return true; + return ATTACH_SUCCESS; } if (!ptrace_continue(pid, WSTOPSIG(status))) { print_error("Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status)); - return false; + return ATTACH_FAIL; } } else { - print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status); - return false; + print_debug("waitpid(): Child process %d exited/terminated (status = 0x%x)\n", pid, status); + return ATTACH_THREAD_DEAD; } } else { switch (errno) { @@ -202,29 +210,89 @@ static bool ptrace_waitpid(pid_t pid) { break; case ECHILD: print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid); - break; + return ATTACH_THREAD_DEAD; case EINVAL: - print_debug("waitpid() failed. Invalid options argument.\n"); - break; + print_error("waitpid() failed. Invalid options argument.\n"); + return ATTACH_FAIL; default: - print_debug("waitpid() failed. Unexpected error %d\n",errno); - break; + print_error("waitpid() failed. Unexpected error %d\n", errno); + return ATTACH_FAIL; } - return false; + } // else + } // while +} + +// checks the state of the thread/process specified by "pid", by reading +// in the 'State:' value from the /proc//status file. From the proc +// man page, "Current state of the process. One of "R (running)", +// "S (sleeping)", "D (disk sleep)", "T (stopped)", "T (tracing stop)", +// "Z (zombie)", or "X (dead)"." Assumes that the thread is dead if we +// don't find the status file or if the status is 'X' or 'Z'. +static bool process_doesnt_exist(pid_t pid) { + char fname[32]; + char buf[30]; + FILE *fp = NULL; + const char state_string[] = "State:"; + + sprintf(fname, "/proc/%d/status", pid); + fp = fopen(fname, "r"); + if (fp == NULL) { + print_debug("can't open /proc/%d/status file\n", pid); + // Assume the thread does not exist anymore. + return true; + } + bool found_state = false; + size_t state_len = strlen(state_string); + while (fgets(buf, sizeof(buf), fp) != NULL) { + char *state = NULL; + if (strncmp (buf, state_string, state_len) == 0) { + found_state = true; + state = buf + state_len; + // Skip the spaces + while (isspace(*state)) { + state++; + } + // A state value of 'X' indicates that the thread is dead. 'Z' + // indicates that the thread is a zombie. + if (*state == 'X' || *state == 'Z') { + fclose (fp); + return true; + } + break; } } + // If the state value is not 'X' or 'Z', the thread exists. + if (!found_state) { + // We haven't found the line beginning with 'State:'. + // Assuming the thread exists. + print_error("Could not find the 'State:' string in the /proc/%d/status file\n", pid); + } + fclose (fp); + return false; } // attach to a process/thread specified by "pid" -static bool ptrace_attach(pid_t pid, char* err_buf, size_t err_buf_len) { +static attach_state_t ptrace_attach(pid_t pid, char* err_buf, size_t err_buf_len) { + errno = 0; if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) { + if (errno == EPERM || errno == ESRCH) { + // Check if the process/thread is exiting or is a zombie + if (process_doesnt_exist(pid)) { + print_debug("Thread with pid %d does not exist\n", pid); + return ATTACH_THREAD_DEAD; + } + } char buf[200]; char* msg = strerror_r(errno, buf, sizeof(buf)); snprintf(err_buf, err_buf_len, "ptrace(PTRACE_ATTACH, ..) failed for %d: %s", pid, msg); - print_debug("%s\n", err_buf); - return false; + print_error("%s\n", err_buf); + return ATTACH_FAIL; } else { - return ptrace_waitpid(pid); + attach_state_t wait_ret = ptrace_waitpid(pid); + if (wait_ret == ATTACH_THREAD_DEAD) { + print_debug("Thread with pid %d does not exist\n", pid); + } + return wait_ret; } } @@ -378,16 +446,20 @@ JNIEXPORT struct ps_prochandle* JNICALL Pgrab(pid_t pid, char* err_buf, size_t err_buf_len, bool is_in_container) { struct ps_prochandle* ph = NULL; thread_info* thr = NULL; + attach_state_t attach_status = ATTACH_SUCCESS; if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) { - snprintf(err_buf, err_buf_len, "can't allocate memory for ps_prochandle"); - print_debug("%s\n", err_buf); - return NULL; + snprintf(err_buf, err_buf_len, "can't allocate memory for ps_prochandle"); + print_debug("%s\n", err_buf); + return NULL; } - if (ptrace_attach(pid, err_buf, err_buf_len) != true) { - free(ph); - return NULL; + if ((attach_status = ptrace_attach(pid, err_buf, err_buf_len)) != ATTACH_SUCCESS) { + if (attach_status == ATTACH_THREAD_DEAD) { + print_error("The process with pid %d does not exist.\n", pid); + } + free(ph); + return NULL; } // initialize ps_prochandle @@ -431,14 +503,23 @@ Pgrab(pid_t pid, char* err_buf, size_t err_buf_len, bool is_in_container) { // attach to the threads thr = ph->threads; + while (thr) { - // don't attach to the main thread again - if (ph->pid != thr->lwp_id && ptrace_attach(thr->lwp_id, err_buf, err_buf_len) != true) { - // even if one attach fails, we get return NULL - Prelease(ph); - return NULL; - } - thr = thr->next; + thread_info* current_thr = thr; + thr = thr->next; + // don't attach to the main thread again + if (ph->pid != current_thr->lwp_id) { + if ((attach_status = ptrace_attach(current_thr->lwp_id, err_buf, err_buf_len)) != ATTACH_SUCCESS) { + if (attach_status == ATTACH_THREAD_DEAD) { + // Remove this thread from the threads list + delete_thread_info(ph, current_thr); + } + else { + Prelease(ph); + return NULL; + } // ATTACH_THREAD_DEAD + } // !ATTACH_SUCCESS + } } return ph; } From eed637f49790ca32c106327ddb22b85fa7bf2fd7 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Thu, 13 Dec 2018 09:02:52 +0000 Subject: [PATCH 036/174] 8214696: Module class should be filtered by core reflection Reviewed-by: lancea, mchung, sundar --- .../share/classes/jdk/internal/reflect/Reflection.java | 1 + .../src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java | 3 ++- test/jdk/jdk/internal/reflect/Reflection/Filtering.java | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/java.base/share/classes/jdk/internal/reflect/Reflection.java b/src/java.base/share/classes/jdk/internal/reflect/Reflection.java index 7fd94e54e5a..492103209aa 100644 --- a/src/java.base/share/classes/jdk/internal/reflect/Reflection.java +++ b/src/java.base/share/classes/jdk/internal/reflect/Reflection.java @@ -56,6 +56,7 @@ public class Reflection { Constructor.class, ALL_MEMBERS, Field.class, ALL_MEMBERS, Method.class, ALL_MEMBERS, + Module.class, ALL_MEMBERS, System.class, Set.of("security") ); methodFilterMap = Map.of(); diff --git a/test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java b/test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java index f257c3e3ac7..c2abd79fe6e 100644 --- a/test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java +++ b/test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TestResolvedJavaType.java @@ -772,7 +772,8 @@ public class TestResolvedJavaType extends TypeUniverse { f.getDeclaringClass().equals(metaAccess.lookupJavaType(AccessibleObject.class)) || f.getDeclaringClass().equals(metaAccess.lookupJavaType(Constructor.class)) || f.getDeclaringClass().equals(metaAccess.lookupJavaType(Field.class)) || - f.getDeclaringClass().equals(metaAccess.lookupJavaType(Method.class))) { + f.getDeclaringClass().equals(metaAccess.lookupJavaType(Method.class)) || + f.getDeclaringClass().equals(metaAccess.lookupJavaType(Module.class))) { return true; } return false; diff --git a/test/jdk/jdk/internal/reflect/Reflection/Filtering.java b/test/jdk/jdk/internal/reflect/Reflection/Filtering.java index c71b5ffbaa4..2858cd83f31 100644 --- a/test/jdk/jdk/internal/reflect/Reflection/Filtering.java +++ b/test/jdk/jdk/internal/reflect/Reflection/Filtering.java @@ -61,6 +61,8 @@ public class Filtering { { Lookup.class, "allowedModes" }, { Method.class, "clazz" }, { Method.class, "modifiers" }, + { Module.class, "name" }, + { Module.class, "loader" }, { System.class, "security" }, }; } From dcb88767a777d96ee065b19d08b723c77624d77d Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 13 Dec 2018 17:28:19 +0800 Subject: [PATCH 037/174] 8213009: Refactoring existing SunMSCAPI classes Reviewed-by: valeriep --- .../classes/sun/security/mscapi/CKey.java | 103 +++++ .../mscapi/{RSAKeyPair.java => CKeyPair.java} | 23 +- .../security/mscapi/CKeyPairGenerator.java | 133 ++++++ .../mscapi/{KeyStore.java => CKeyStore.java} | 168 +++---- .../{RSAPrivateKey.java => CPrivateKey.java} | 53 +-- .../sun/security/mscapi/CPublicKey.java | 142 ++++++ .../{RSACipher.java => CRSACipher.java} | 28 +- .../{RSASignature.java => CSignature.java} | 418 +++++++++--------- .../classes/sun/security/mscapi/Key.java | 166 ------- .../classes/sun/security/mscapi/PRNG.java | 2 +- .../security/mscapi/RSAKeyPairGenerator.java | 123 ------ .../sun/security/mscapi/RSAPublicKey.java | 200 --------- .../sun/security/mscapi/SunMSCAPI.java | 55 ++- .../windows/native/libsunmscapi/security.cpp | 310 ++++++------- .../sun/security/mscapi/KeyAlgorithms.java | 80 ++++ 15 files changed, 968 insertions(+), 1036 deletions(-) create mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java rename src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/{RSAKeyPair.java => CKeyPair.java} (70%) create mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPairGenerator.java rename src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/{KeyStore.java => CKeyStore.java} (89%) rename src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/{RSAPrivateKey.java => CPrivateKey.java} (58%) create mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java rename src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/{RSACipher.java => CRSACipher.java} (95%) rename src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/{RSASignature.java => CSignature.java} (72%) delete mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/Key.java delete mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPairGenerator.java delete mode 100644 src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPublicKey.java create mode 100644 test/jdk/sun/security/mscapi/KeyAlgorithms.java diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java new file mode 100644 index 00000000000..865652e8950 --- /dev/null +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.mscapi; + +import sun.security.util.Length; + +import java.security.Key; + +/** + * The handle for a key using the Microsoft Crypto API. + * + * @see CPrivateKey + * @see CPublicKey + * + * @since 1.6 + * @author Stanley Man-Kit Ho + */ +abstract class CKey implements Key, Length { + private static final long serialVersionUID = -1088859394025049194L; + + static class NativeHandles { + + long hCryptProv = 0; + long hCryptKey = 0; + + public NativeHandles(long hCryptProv, long hCryptKey) { + this.hCryptProv = hCryptProv; + this.hCryptKey = hCryptKey; + } + + @SuppressWarnings("deprecation") + protected void finalize() throws Throwable { + try { + synchronized(this) { + cleanUp(hCryptProv, hCryptKey); + hCryptProv = 0; + hCryptKey = 0; + } + } finally { + super.finalize(); + } + } + } + + protected final NativeHandles handles; + + protected final int keyLength; + + protected final String algorithm; + + protected CKey(String algorithm, long hCryptProv, long hCryptKey, int keyLength) { + this.algorithm = algorithm; + this.handles = new NativeHandles(hCryptProv, hCryptKey); + this.keyLength = keyLength; + } + + // Native method to cleanup the key handle. + private native static void cleanUp(long hCryptProv, long hCryptKey); + + @Override + public int length() { + return keyLength; + } + + public long getHCryptKey() { + return handles.hCryptKey; + } + + public long getHCryptProvider() { + return handles.hCryptProv; + } + + public String getAlgorithm() { + return algorithm; + } + + protected native static String getContainerName(long hCryptProv); + + protected native static String getKeyType(long hCryptKey); +} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPair.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPair.java similarity index 70% rename from src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPair.java rename to src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPair.java index 0880c20d85d..81e3d4fa2b2 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPair.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPair.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,27 +30,22 @@ package sun.security.mscapi; * * @since 1.6 */ -class RSAKeyPair { +class CKeyPair { - private final RSAPrivateKey privateKey; + private final CPrivateKey privateKey; - private final RSAPublicKey publicKey; + private final CPublicKey publicKey; - /** - * Construct an RSAKeyPair object. - */ - RSAKeyPair(long hCryptProv, long hCryptKey, int keyLength) - { - Key.NativeHandles handles = new Key.NativeHandles(hCryptProv, hCryptKey); - privateKey = new RSAPrivateKey(handles, keyLength); - publicKey = new RSAPublicKey(handles, keyLength); + CKeyPair(String alg, long hCryptProv, long hCryptKey, int keyLength) { + privateKey = CPrivateKey.of(alg, hCryptProv, hCryptKey, keyLength); + publicKey = CPublicKey.of(alg, hCryptProv, hCryptKey, keyLength); } - public RSAPrivateKey getPrivate() { + public CPrivateKey getPrivate() { return privateKey; } - public RSAPublicKey getPublic() { + public CPublicKey getPublic() { return publicKey; } } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPairGenerator.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPairGenerator.java new file mode 100644 index 00000000000..84c7fdf9dbe --- /dev/null +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyPairGenerator.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.mscapi; + +import java.util.UUID; +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.RSAKeyGenParameterSpec; + +import sun.security.rsa.RSAKeyFactory; +import static sun.security.util.SecurityProviderConstants.DEF_RSA_KEY_SIZE; + +/** + * RSA keypair generator. + * + * Standard algorithm, minimum key length is 512 bit, maximum is 16,384. + * Generates a private key that is exportable. + * + * @since 1.6 + */ +public abstract class CKeyPairGenerator extends KeyPairGeneratorSpi { + + protected String keyAlg; + + public CKeyPairGenerator(String keyAlg) { + this.keyAlg = keyAlg; + } + + public static class RSA extends CKeyPairGenerator { + public RSA() { + super("RSA"); + // initialize to default in case the app does not call initialize() + initialize(DEF_RSA_KEY_SIZE, null); + } + + // Supported by Microsoft Base, Strong and Enhanced Cryptographic Providers + static final int KEY_SIZE_MIN = 512; // disallow MSCAPI min. of 384 + static final int KEY_SIZE_MAX = 16384; + + // size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX + private int keySize; + + // initialize the generator. See JCA doc + // random is always ignored + @Override + public void initialize(int keySize, SecureRandom random) { + + try { + RSAKeyFactory.checkKeyLengths(keySize, null, + KEY_SIZE_MIN, KEY_SIZE_MAX); + } catch (InvalidKeyException e) { + throw new InvalidParameterException(e.getMessage()); + } + + this.keySize = keySize; + } + + // second initialize method. See JCA doc + // random and exponent are always ignored + @Override + public void initialize(AlgorithmParameterSpec params, SecureRandom random) + throws InvalidAlgorithmParameterException { + + int tmpSize; + if (params == null) { + tmpSize = DEF_RSA_KEY_SIZE; + } else if (params instanceof RSAKeyGenParameterSpec) { + + if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) { + throw new InvalidAlgorithmParameterException + ("Exponent parameter is not supported"); + } + tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize(); + + } else { + throw new InvalidAlgorithmParameterException + ("Params must be an instance of RSAKeyGenParameterSpec"); + } + + try { + RSAKeyFactory.checkKeyLengths(tmpSize, null, + KEY_SIZE_MIN, KEY_SIZE_MAX); + } catch (InvalidKeyException e) { + throw new InvalidAlgorithmParameterException( + "Invalid Key sizes", e); + } + + this.keySize = tmpSize; + } + + // generate the keypair. See JCA doc + @Override + public KeyPair generateKeyPair() { + + try { + // Generate each keypair in a unique key container + CKeyPair keys = + generateCKeyPair(keyAlg, keySize, + "{" + UUID.randomUUID().toString() + "}"); + return new KeyPair(keys.getPublic(), keys.getPrivate()); + + } catch (KeyException e) { + throw new ProviderException(e); + } + } + + private static native CKeyPair generateCKeyPair(String alg, int keySize, + String keyContainerName) throws KeyException; + } +} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java similarity index 89% rename from src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java rename to src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java index 16e99bbfd48..5adaf676c85 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.security.AccessController; import java.security.InvalidKeyException; +import java.security.Key; import java.security.KeyStoreSpi; import java.security.KeyStoreException; import java.security.PrivilegedAction; @@ -49,31 +50,30 @@ import java.util.*; * * @since 1.6 */ -abstract class KeyStore extends KeyStoreSpi { +abstract class CKeyStore extends KeyStoreSpi { - public static final class MY extends KeyStore { + public static final class MY extends CKeyStore { public MY() { super("MY"); } } - public static final class ROOT extends KeyStore { + public static final class ROOT extends CKeyStore { public ROOT() { super("ROOT"); } } - class KeyEntry - { - private Key privateKey; + class KeyEntry { + private CKey privateKey; private X509Certificate[] certChain; private String alias; - KeyEntry(Key key, X509Certificate[] chain) { + KeyEntry(CKey key, X509Certificate[] chain) { this(null, key, chain); } - KeyEntry(String alias, Key key, X509Certificate[] chain) { + KeyEntry(String alias, CKey key, X509Certificate[] chain) { this.privateKey = key; this.certChain = chain; /* @@ -90,16 +90,14 @@ abstract class KeyStore extends KeyStoreSpi { /** * Gets the alias for the keystore entry. */ - String getAlias() - { + String getAlias() { return alias; } /** * Sets the alias for the keystore entry. */ - void setAlias(String alias) - { + void setAlias(String alias) { // TODO - set friendly name prop in cert store this.alias = alias; } @@ -107,44 +105,42 @@ abstract class KeyStore extends KeyStoreSpi { /** * Gets the private key for the keystore entry. */ - Key getPrivateKey() - { + CKey getPrivateKey() { return privateKey; } /** * Sets the private key for the keystore entry. */ - void setPrivateKey(RSAPrivateCrtKey key) - throws InvalidKeyException, KeyStoreException - { + void setRSAPrivateKey(Key k) + throws InvalidKeyException, KeyStoreException { + RSAPrivateCrtKey key = (RSAPrivateCrtKey) k; byte[] modulusBytes = key.getModulus().toByteArray(); // Adjust key length due to sign bit int keyBitLength = (modulusBytes[0] == 0) - ? (modulusBytes.length - 1) * 8 - : modulusBytes.length * 8; + ? (modulusBytes.length - 1) * 8 + : modulusBytes.length * 8; - byte[] keyBlob = generatePrivateKeyBlob( - keyBitLength, - modulusBytes, - key.getPublicExponent().toByteArray(), - key.getPrivateExponent().toByteArray(), - key.getPrimeP().toByteArray(), - key.getPrimeQ().toByteArray(), - key.getPrimeExponentP().toByteArray(), - key.getPrimeExponentQ().toByteArray(), - key.getCrtCoefficient().toByteArray()); + byte[] keyBlob = generateRSAPrivateKeyBlob( + keyBitLength, + modulusBytes, + key.getPublicExponent().toByteArray(), + key.getPrivateExponent().toByteArray(), + key.getPrimeP().toByteArray(), + key.getPrimeQ().toByteArray(), + key.getPrimeExponentP().toByteArray(), + key.getPrimeExponentQ().toByteArray(), + key.getCrtCoefficient().toByteArray()); - privateKey = storePrivateKey(Objects.requireNonNull(keyBlob), - "{" + UUID.randomUUID().toString() + "}", keyBitLength); + privateKey = storePrivateKey("RSA", Objects.requireNonNull(keyBlob), + "{" + UUID.randomUUID().toString() + "}", keyBitLength); } /** * Gets the certificate chain for the keystore entry. */ - X509Certificate[] getCertificateChain() - { + X509Certificate[] getCertificateChain() { return certChain; } @@ -152,8 +148,7 @@ abstract class KeyStore extends KeyStoreSpi { * Sets the certificate chain for the keystore entry. */ void setCertificateChain(X509Certificate[] chain) - throws CertificateException, KeyStoreException - { + throws CertificateException, KeyStoreException { for (int i = 0; i < chain.length; i++) { byte[] encoding = chain[i].getEncoded(); if (i == 0 && privateKey != null) { @@ -199,7 +194,7 @@ abstract class KeyStore extends KeyStoreSpi { */ private final String storeName; - KeyStore(String storeName) { + CKeyStore(String storeName) { // Get the compatibility mode String prop = AccessController.doPrivileged( (PrivilegedAction) () -> System.getProperty(KEYSTORE_COMPATIBILITY_MODE_PROP)); @@ -237,8 +232,7 @@ abstract class KeyStore extends KeyStoreSpi { * @exception UnrecoverableKeyException if the key cannot be recovered. */ public java.security.Key engineGetKey(String alias, char[] password) - throws NoSuchAlgorithmException, UnrecoverableKeyException - { + throws NoSuchAlgorithmException, UnrecoverableKeyException { if (alias == null) { return null; } @@ -267,8 +261,7 @@ abstract class KeyStore extends KeyStoreSpi { * alias identifies either a trusted certificate entry or a * key entry without a certificate chain). */ - public Certificate[] engineGetCertificateChain(String alias) - { + public Certificate[] engineGetCertificateChain(String alias) { if (alias == null) { return null; } @@ -297,8 +290,7 @@ abstract class KeyStore extends KeyStoreSpi { * @return the certificate, or null if the given alias does not exist or * does not contain a certificate. */ - public Certificate engineGetCertificate(String alias) - { + public Certificate engineGetCertificate(String alias) { if (alias == null) { return null; } @@ -361,8 +353,7 @@ abstract class KeyStore extends KeyStoreSpi { * some other reason. */ public void engineSetKeyEntry(String alias, java.security.Key key, - char[] password, Certificate[] chain) throws KeyStoreException - { + char[] password, Certificate[] chain) throws KeyStoreException { if (alias == null) { throw new KeyStoreException("alias must not be null"); } @@ -397,7 +388,7 @@ abstract class KeyStore extends KeyStoreSpi { entry.setAlias(alias); try { - entry.setPrivateKey((RSAPrivateCrtKey) key); + entry.setRSAPrivateKey(key); entry.setCertificateChain(xchain); } catch (CertificateException ce) { @@ -438,8 +429,7 @@ abstract class KeyStore extends KeyStoreSpi { */ public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) - throws KeyStoreException - { + throws KeyStoreException { throw new UnsupportedOperationException( "Cannot assign the encoded key to the given alias."); } @@ -459,8 +449,7 @@ abstract class KeyStore extends KeyStoreSpi { * fails for some other reason. */ public void engineSetCertificateEntry(String alias, Certificate cert) - throws KeyStoreException - { + throws KeyStoreException { if (alias == null) { throw new KeyStoreException("alias must not be null"); } @@ -502,9 +491,7 @@ abstract class KeyStore extends KeyStoreSpi { * * @exception KeyStoreException if the entry cannot be removed. */ - public void engineDeleteEntry(String alias) - throws KeyStoreException - { + public void engineDeleteEntry(String alias) throws KeyStoreException { if (alias == null) { throw new KeyStoreException("alias must not be null"); } @@ -525,10 +512,10 @@ abstract class KeyStore extends KeyStoreSpi { throw new KeyStoreException("Cannot remove entry: ", e); } } - Key privateKey = entry.getPrivateKey(); + CKey privateKey = entry.getPrivateKey(); if (privateKey != null) { destroyKeyContainer( - Key.getContainerName(privateKey.getHCryptProvider())); + CKey.getContainerName(privateKey.getHCryptProvider())); } } } @@ -541,15 +528,12 @@ abstract class KeyStore extends KeyStoreSpi { public Enumeration engineAliases() { final Iterator iter = entries.keySet().iterator(); - return new Enumeration() - { - public boolean hasMoreElements() - { + return new Enumeration() { + public boolean hasMoreElements() { return iter.hasNext(); } - public String nextElement() - { + public String nextElement() { return iter.next(); } }; @@ -659,8 +643,7 @@ abstract class KeyStore extends KeyStoreSpi { * parameter is non-null. */ public void engineStore(OutputStream stream, char[] password) - throws IOException, NoSuchAlgorithmException, CertificateException - { + throws IOException, NoSuchAlgorithmException, CertificateException { if (stream != null && !keyStoreCompatibilityMode) { throw new IOException("Keystore output stream must be null"); } @@ -698,8 +681,7 @@ abstract class KeyStore extends KeyStoreSpi { * this provider's getName method. */ public void engineLoad(InputStream stream, char[] password) - throws IOException, NoSuchAlgorithmException, CertificateException - { + throws IOException, NoSuchAlgorithmException, CertificateException { if (stream != null && !keyStoreCompatibilityMode) { throw new IOException("Keystore input stream must be null"); } @@ -753,27 +735,24 @@ abstract class KeyStore extends KeyStoreSpi { /** * Generates a certificate chain from the collection of * certificates and stores the result into a key entry. + *

    + * This method is called by native codes in security.cpp. */ private void generateCertificateChain(String alias, - Collection certCollection) - { - try - { + Collection certCollection) { + try { X509Certificate[] certChain = new X509Certificate[certCollection.size()]; int i = 0; for (Iterator iter = - certCollection.iterator(); iter.hasNext(); i++) - { + certCollection.iterator(); iter.hasNext(); i++) { certChain[i] = (X509Certificate) iter.next(); } storeWithUniqueAlias(alias, new KeyEntry(alias, null, certChain)); - } - catch (Throwable e) - { + } catch (Throwable e) { // Ignore the exception and skip this entry // TODO - throw CertificateException? } @@ -782,30 +761,25 @@ abstract class KeyStore extends KeyStoreSpi { /** * Generates RSA key and certificate chain from the private key handle, * collection of certificates and stores the result into key entries. + *

    + * This method is called by native codes in security.cpp. */ private void generateRSAKeyAndCertificateChain(String alias, - long hCryptProv, long hCryptKey, int keyLength, - Collection certCollection) - { - try - { + long hCryptProv, long hCryptKey, int keyLength, + Collection certCollection) { + try { X509Certificate[] certChain = new X509Certificate[certCollection.size()]; int i = 0; for (Iterator iter = - certCollection.iterator(); iter.hasNext(); i++) - { + certCollection.iterator(); iter.hasNext(); i++) { certChain[i] = (X509Certificate) iter.next(); } - storeWithUniqueAlias(alias, new KeyEntry(alias, - new RSAPrivateKey(new Key.NativeHandles(hCryptProv, - hCryptKey), keyLength), + CPrivateKey.of("RSA", hCryptProv, hCryptKey, keyLength), certChain)); - } - catch (Throwable e) - { + } catch (Throwable e) { // Ignore the exception and skip this entry // TODO - throw CertificateException? } @@ -813,14 +787,15 @@ abstract class KeyStore extends KeyStoreSpi { /** * Generates certificates from byte data and stores into cert collection. + *

    + * This method is called by native codes in security.cpp. * * @param data Byte data. * @param certCollection Collection of certificates. */ private void generateCertificate(byte[] data, Collection certCollection) { - try - { + try { ByteArrayInputStream bis = new ByteArrayInputStream(data); // Obtain certificate factory @@ -832,14 +807,10 @@ abstract class KeyStore extends KeyStoreSpi { Collection c = certificateFactory.generateCertificates(bis); certCollection.addAll(c); - } - catch (CertificateException e) - { + } catch (CertificateException e) { // Ignore the exception and skip this certificate // TODO - throw CertificateException? - } - catch (Throwable te) - { + } catch (Throwable te) { // Ignore the exception and skip this certificate // TODO - throw CertificateException? } @@ -848,8 +819,7 @@ abstract class KeyStore extends KeyStoreSpi { /** * Returns the name of the keystore. */ - private String getName() - { + private String getName() { return storeName; } @@ -894,7 +864,7 @@ abstract class KeyStore extends KeyStoreSpi { /** * Generates a private-key BLOB from a key's components. */ - private native byte[] generatePrivateKeyBlob( + private native byte[] generateRSAPrivateKeyBlob( int keyBitLength, byte[] modulus, byte[] publicExponent, @@ -905,6 +875,6 @@ abstract class KeyStore extends KeyStoreSpi { byte[] exponentQ, byte[] crtCoefficient) throws InvalidKeyException; - private native RSAPrivateKey storePrivateKey(byte[] keyBlob, + private native CPrivateKey storePrivateKey(String alg, byte[] keyBlob, String keyContainerName, int keySize) throws KeyStoreException; } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPrivateKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPrivateKey.java similarity index 58% rename from src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPrivateKey.java rename to src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPrivateKey.java index ca692dfa2f3..1f5134342b7 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPrivateKey.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,57 +28,42 @@ package sun.security.mscapi; import java.security.PrivateKey; /** - * The handle for an RSA private key using the Microsoft Crypto API. + * The handle for a private key using the Microsoft Crypto API. * * @author Stanley Man-Kit Ho * @since 1.6 */ -class RSAPrivateKey extends Key implements PrivateKey -{ +class CPrivateKey extends CKey implements PrivateKey { + private static final long serialVersionUID = 8113152807912338063L; - /** - * Construct an RSAPrivateKey object. - */ - RSAPrivateKey(long hCryptProv, long hCryptKey, int keyLength) - { - super(new NativeHandles(hCryptProv, hCryptKey), keyLength); + private CPrivateKey(String alg, long hCryptProv, long hCryptKey, int keyLength) { + super(alg, hCryptProv, hCryptKey, keyLength); } - /** - * Construct an RSAPrivateKey object. - */ - RSAPrivateKey(NativeHandles handles, int keyLength) - { - super(handles, keyLength); + public static CPrivateKey of(String alg, long hCryptProv, long hCryptKey, int keyLength) { + return new CPrivateKey(alg, hCryptProv, hCryptKey, keyLength); } - /** - * Returns the standard algorithm name for this key. For - * example, "RSA" would indicate that this key is a RSA key. - * See Appendix A in the - * Java Cryptography Architecture API Specification & Reference - * for information about standard algorithm names. - * - * @return the name of the algorithm associated with this key. - */ - public String getAlgorithm() - { - return "RSA"; + // this key does not support encoding + public String getFormat() { + return null; } - public String toString() - { - return "RSAPrivateKey [size=" + keyLength + " bits, type=" + + // this key does not support encoding + public byte[] getEncoded() { + return null; + } + + public String toString() { + return algorithm + "PrivateKey [size=" + keyLength + " bits, type=" + getKeyType(handles.hCryptKey) + ", container=" + getContainerName(handles.hCryptProv) + "]"; } // This class is not serializable private void writeObject(java.io.ObjectOutputStream out) - throws java.io.IOException { - + throws java.io.IOException { throw new java.io.NotSerializableException(); } } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java new file mode 100644 index 00000000000..5421e790e7b --- /dev/null +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.mscapi; + +import java.math.BigInteger; +import java.security.KeyException; +import java.security.KeyRep; +import java.security.ProviderException; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; + +import sun.security.rsa.RSAUtil.KeyType; +import sun.security.rsa.RSAPublicKeyImpl; + +/** + * The handle for an RSA public key using the Microsoft Crypto API. + * + * @since 1.6 + */ +public abstract class CPublicKey extends CKey implements PublicKey { + + private static final long serialVersionUID = -2289561342425825391L; + + protected byte[] publicKeyBlob = null; + protected byte[] encoding = null; + + public static class CRSAPublicKey extends CPublicKey implements RSAPublicKey { + + private BigInteger modulus = null; + private BigInteger exponent = null; + private static final long serialVersionUID = 12L; + + CRSAPublicKey(long hCryptProv, long hCryptKey, int keyLength) { + super("RSA", hCryptProv, hCryptKey, keyLength); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(algorithm + "PublicKey [size=").append(keyLength) + .append(" bits, type=").append(getKeyType(handles.hCryptKey)) + .append(", container=").append(getContainerName(handles.hCryptProv)) + .append("]\n modulus: ").append(getModulus()) + .append("\n public exponent: ").append(getPublicExponent()); + return sb.toString(); + } + + @Override + public BigInteger getPublicExponent() { + if (exponent == null) { + try { + publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); + exponent = new BigInteger(1, getExponent(publicKeyBlob)); + } catch (KeyException e) { + throw new ProviderException(e); + } + } + return exponent; + } + + @Override + public BigInteger getModulus() { + if (modulus == null) { + try { + publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); + modulus = new BigInteger(1, getModulus(publicKeyBlob)); + } catch (KeyException e) { + throw new ProviderException(e); + } + } + return modulus; + } + + @Override + public byte[] getEncoded() { + if (encoding == null) { + try { + encoding = RSAPublicKeyImpl.newKey(KeyType.RSA, null, + getModulus(), getPublicExponent()).getEncoded(); + } catch (KeyException e) { + // ignore + } + } + return encoding; + } + + private native byte[] getExponent(byte[] keyBlob) throws KeyException; + + private native byte[] getModulus(byte[] keyBlob) throws KeyException; + } + + public static CPublicKey of(String alg, long hCryptProv, long hCryptKey, int keyLength) { + switch (alg) { + case "RSA": + return new CRSAPublicKey(hCryptProv, hCryptKey, keyLength); + default: + throw new AssertionError("Unsupported algorithm: " + alg); + } + } + + protected CPublicKey(String alg, long hCryptProv, long hCryptKey, int keyLength) { + super(alg, hCryptProv, hCryptKey, keyLength); + } + + @Override + public String getFormat() { + return "X.509"; + } + + protected Object writeReplace() throws java.io.ObjectStreamException { + return new KeyRep(KeyRep.Type.PUBLIC, + getAlgorithm(), + getFormat(), + getEncoded()); + } + + // Returns the Microsoft CryptoAPI representation of the key. + native byte[] getPublicKeyBlob(long hCryptKey) throws KeyException; + +} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSACipher.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CRSACipher.java similarity index 95% rename from src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSACipher.java rename to src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CRSACipher.java index f6f91106c94..56a4fabca71 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSACipher.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CRSACipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,7 +39,7 @@ import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; import sun.security.util.KeyUtil; /** - * RSA cipher implementation using the Microsoft Crypto API. + * Cipher implementation using the Microsoft Crypto API. * Supports RSA en/decryption and signing/verifying using PKCS#1 v1.5 padding. * * Objects should be instantiated by calling Cipher.getInstance() using the @@ -59,7 +59,7 @@ import sun.security.util.KeyUtil; * @author Andreas Sterbenz * @author Vincent Ryan */ -public final class RSACipher extends CipherSpi { +public final class CRSACipher extends CipherSpi { // constant for an empty byte array private final static byte[] B0 = new byte[0]; @@ -93,10 +93,10 @@ public final class RSACipher extends CipherSpi { private int outputSize; // the public key, if we were initialized using a public key - private sun.security.mscapi.Key publicKey; + private CKey publicKey; // the private key, if we were initialized using a private key - private sun.security.mscapi.Key privateKey; + private CKey privateKey; // cipher parameter for TLS RSA premaster secret private AlgorithmParameterSpec spec = null; @@ -104,7 +104,7 @@ public final class RSACipher extends CipherSpi { // the source of randomness private SecureRandom random; - public RSACipher() { + public CRSACipher() { paddingType = PAD_PKCS1; } @@ -207,7 +207,7 @@ public final class RSACipher extends CipherSpi { throw new InvalidKeyException("Unknown mode: " + opmode); } - if (!(key instanceof sun.security.mscapi.Key)) { + if (!(key instanceof CKey)) { if (key instanceof java.security.interfaces.RSAPublicKey) { java.security.interfaces.RSAPublicKey rsaKey = (java.security.interfaces.RSAPublicKey) key; @@ -220,7 +220,7 @@ public final class RSACipher extends CipherSpi { // Check against the local and global values to make sure // the sizes are ok. Round up to the nearest byte. RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7), - exponent, -1, RSAKeyPairGenerator.KEY_SIZE_MAX); + exponent, -1, CKeyPairGenerator.RSA.KEY_SIZE_MAX); byte[] modulusBytes = modulus.toByteArray(); byte[] exponentBytes = exponent.toByteArray(); @@ -230,11 +230,11 @@ public final class RSACipher extends CipherSpi { ? (modulusBytes.length - 1) * 8 : modulusBytes.length * 8; - byte[] keyBlob = RSASignature.generatePublicKeyBlob( + byte[] keyBlob = CSignature.RSA.generatePublicKeyBlob( keyBitLength, modulusBytes, exponentBytes); try { - key = RSASignature.importPublicKey(keyBlob, keyBitLength); + key = CSignature.importPublicKey("RSA", keyBlob, keyBitLength); } catch (KeyStoreException e) { throw new InvalidKeyException(e); @@ -247,12 +247,12 @@ public final class RSACipher extends CipherSpi { if (key instanceof PublicKey) { mode = encrypt ? MODE_ENCRYPT : MODE_VERIFY; - publicKey = (sun.security.mscapi.Key)key; + publicKey = (CKey)key; privateKey = null; outputSize = publicKey.length() / 8; } else if (key instanceof PrivateKey) { mode = encrypt ? MODE_SIGN : MODE_DECRYPT; - privateKey = (sun.security.mscapi.Key)key; + privateKey = (CKey)key; publicKey = null; outputSize = privateKey.length() / 8; } else { @@ -417,8 +417,8 @@ public final class RSACipher extends CipherSpi { // see JCE spec protected int engineGetKeySize(Key key) throws InvalidKeyException { - if (key instanceof sun.security.mscapi.Key) { - return ((sun.security.mscapi.Key) key).length(); + if (key instanceof CKey) { + return ((CKey) key).length(); } else if (key instanceof RSAKey) { return ((RSAKey) key).getModulus().bitLength(); diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSASignature.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java similarity index 72% rename from src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSASignature.java rename to src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java index 12af76072fc..ca165b356c2 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSASignature.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java @@ -27,6 +27,7 @@ package sun.security.mscapi; import java.nio.ByteBuffer; import java.security.*; +import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.math.BigInteger; import java.security.spec.MGF1ParameterSpec; @@ -36,7 +37,8 @@ import java.util.Locale; import sun.security.rsa.RSAKeyFactory; /** - * RSA signature implementation. Supports RSA signing using PKCS#1 v1.5 padding. + * Signature implementation. Supports RSA signing using PKCS#1 v1.5 padding + * and RSASSA-PSS signing. * * Objects should be instantiated by calling Signature.getInstance() using the * following algorithm names: @@ -60,50 +62,185 @@ import sun.security.rsa.RSAKeyFactory; * @since 1.6 * @author Stanley Man-Kit Ho */ -abstract class RSASignature extends java.security.SignatureSpi -{ +abstract class CSignature extends SignatureSpi { + // private key algorithm name + protected String keyAlgorithm; + // message digest implementation we use protected MessageDigest messageDigest; // message digest name - private String messageDigestAlgorithm; + protected String messageDigestAlgorithm; // flag indicating whether the digest has been reset protected boolean needsReset; // the signing key - protected Key privateKey = null; + protected CPrivateKey privateKey = null; // the verification key - protected Key publicKey = null; + protected CPublicKey publicKey = null; /** - * Constructs a new RSASignature. Used by Raw subclass. + * Constructs a new CSignature. Used by subclasses. */ - RSASignature() { - messageDigest = null; - messageDigestAlgorithm = null; - } + CSignature(String keyName, String digestName) { - /** - * Constructs a new RSASignature. Used by subclasses. - */ - RSASignature(String digestName) { - - try { - messageDigest = MessageDigest.getInstance(digestName); - // Get the digest's canonical name - messageDigestAlgorithm = messageDigest.getAlgorithm(); - - } catch (NoSuchAlgorithmException e) { - throw new ProviderException(e); + this.keyAlgorithm = keyName; + if (digestName != null) { + try { + messageDigest = MessageDigest.getInstance(digestName); + // Get the digest's canonical name + messageDigestAlgorithm = messageDigest.getAlgorithm(); + } catch (NoSuchAlgorithmException e) { + throw new ProviderException(e); + } + } else { + messageDigest = null; + messageDigestAlgorithm = null; } - needsReset = false; } + static class RSA extends CSignature { + + public RSA(String digestAlgorithm) { + super("RSA", digestAlgorithm); + } + + // initialize for signing. See JCA doc + @Override + protected void engineInitSign(PrivateKey key) throws InvalidKeyException { + + if ((key instanceof CPrivateKey) == false) { + throw new InvalidKeyException("Key type not supported"); + } + privateKey = (CPrivateKey) key; + + // Check against the local and global values to make sure + // the sizes are ok. Round up to nearest byte. + RSAKeyFactory.checkKeyLengths(((privateKey.length() + 7) & ~7), + null, CKeyPairGenerator.RSA.KEY_SIZE_MIN, + CKeyPairGenerator.RSA.KEY_SIZE_MAX); + + this.publicKey = null; + resetDigest(); + } + + // initialize for signing. See JCA doc + @Override + protected void engineInitVerify(PublicKey key) throws InvalidKeyException { + // This signature accepts only RSAPublicKey + if ((key instanceof RSAPublicKey) == false) { + throw new InvalidKeyException("Key type not supported"); + } + + + if ((key instanceof CPublicKey) == false) { + + // convert key to MSCAPI format + java.security.interfaces.RSAPublicKey rsaKey = + (java.security.interfaces.RSAPublicKey) key; + + BigInteger modulus = rsaKey.getModulus(); + BigInteger exponent = rsaKey.getPublicExponent(); + + // Check against the local and global values to make sure + // the sizes are ok. Round up to the nearest byte. + RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7), + exponent, -1, CKeyPairGenerator.RSA.KEY_SIZE_MAX); + + byte[] modulusBytes = modulus.toByteArray(); + byte[] exponentBytes = exponent.toByteArray(); + + // Adjust key length due to sign bit + int keyBitLength = (modulusBytes[0] == 0) + ? (modulusBytes.length - 1) * 8 + : modulusBytes.length * 8; + + byte[] keyBlob = generatePublicKeyBlob( + keyBitLength, modulusBytes, exponentBytes); + + try { + publicKey = importPublicKey("RSA", keyBlob, keyBitLength); + + } catch (KeyStoreException e) { + throw new InvalidKeyException(e); + } + + } else { + publicKey = (CPublicKey) key; + } + + this.privateKey = null; + resetDigest(); + } + + /** + * Returns the signature bytes of all the data + * updated so far. + * The format of the signature depends on the underlying + * signature scheme. + * + * @return the signature bytes of the signing operation's result. + * + * @exception SignatureException if the engine is not + * initialized properly or if this signature algorithm is unable to + * process the input data provided. + */ + @Override + protected byte[] engineSign() throws SignatureException { + + byte[] hash = getDigestValue(); + + // Omit the hash OID when generating a NONEwithRSA signature + boolean noHashOID = this instanceof NONEwithRSA; + + // Sign hash using MS Crypto APIs + + byte[] result = signHash(noHashOID, hash, hash.length, + messageDigestAlgorithm, privateKey.getHCryptProvider(), + privateKey.getHCryptKey()); + + // Convert signature array from little endian to big endian + return convertEndianArray(result); + } + + /** + * Verifies the passed-in signature. + * + * @param sigBytes the signature bytes to be verified. + * + * @return true if the signature was verified, false if not. + * + * @exception SignatureException if the engine is not + * initialized properly, the passed-in signature is improperly + * encoded or of the wrong type, if this signature algorithm is unable to + * process the input data provided, etc. + */ + @Override + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException { + byte[] hash = getDigestValue(); + + return verifySignedHash(hash, hash.length, + messageDigestAlgorithm, convertEndianArray(sigBytes), + sigBytes.length, publicKey.getHCryptProvider(), + publicKey.getHCryptKey()); + } + + /** + * Generates a public-key BLOB from a key's components. + */ + // used by CRSACipher + static native byte[] generatePublicKeyBlob( + int keyBitLength, byte[] modulus, byte[] publicExponent) + throws InvalidKeyException; + + } + // Nested class for NONEwithRSA signatures - public static final class Raw extends RSASignature { + public static final class NONEwithRSA extends RSA { // the longest supported digest is 512 bits (SHA-512) private static final int RAW_RSA_MAX = 64; @@ -111,7 +248,8 @@ abstract class RSASignature extends java.security.SignatureSpi private final byte[] precomputedDigest; private int offset = 0; - public Raw() { + public NONEwithRSA() { + super(null); precomputedDigest = new byte[RAW_RSA_MAX]; } @@ -190,43 +328,43 @@ abstract class RSASignature extends java.security.SignatureSpi } } - public static final class SHA1 extends RSASignature { - public SHA1() { + public static final class SHA1withRSA extends RSA { + public SHA1withRSA() { super("SHA1"); } } - public static final class SHA256 extends RSASignature { - public SHA256() { + public static final class SHA256withRSA extends RSA { + public SHA256withRSA() { super("SHA-256"); } } - public static final class SHA384 extends RSASignature { - public SHA384() { + public static final class SHA384withRSA extends RSA { + public SHA384withRSA() { super("SHA-384"); } } - public static final class SHA512 extends RSASignature { - public SHA512() { + public static final class SHA512withRSA extends RSA { + public SHA512withRSA() { super("SHA-512"); } } - public static final class MD5 extends RSASignature { - public MD5() { + public static final class MD5withRSA extends RSA { + public MD5withRSA() { super("MD5"); } } - public static final class MD2 extends RSASignature { - public MD2() { + public static final class MD2withRSA extends RSA { + public MD2withRSA() { super("MD2"); } } - public static final class PSS extends RSASignature { + public static final class PSS extends RSA { private PSSParameterSpec pssParams = null; @@ -234,6 +372,10 @@ abstract class RSASignature extends java.security.SignatureSpi // will be used for verification if key is not from MSCAPI. private Signature fallbackSignature; + public PSS() { + super(null); + } + @Override protected void engineInitSign(PrivateKey key) throws InvalidKeyException { super.engineInitSign(key); @@ -249,9 +391,9 @@ abstract class RSASignature extends java.security.SignatureSpi this.privateKey = null; - if (key instanceof sun.security.mscapi.RSAPublicKey) { + if (key instanceof CPublicKey) { fallbackSignature = null; - publicKey = (sun.security.mscapi.RSAPublicKey) key; + publicKey = (CPublicKey) key; } else { if (fallbackSignature == null) { try { @@ -321,7 +463,7 @@ abstract class RSASignature extends java.security.SignatureSpi protected byte[] engineSign() throws SignatureException { ensureInit(); byte[] hash = getDigestValue(); - return signPssHash(hash, hash.length, + return signCngHash(hash, hash.length, pssParams.getSaltLength(), ((MGF1ParameterSpec) pssParams.getMGFParameters()).getDigestAlgorithm(), @@ -336,7 +478,7 @@ abstract class RSASignature extends java.security.SignatureSpi return fallbackSignature.verify(sigBytes); } else { byte[] hash = getDigestValue(); - return verifyPssSignedHash( + return verifyCngSignedHash( hash, hash.length, sigBytes, sigBytes.length, pssParams.getSaltLength(), @@ -454,95 +596,24 @@ abstract class RSASignature extends java.security.SignatureSpi return params; } - - /** - * Sign hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. - */ - private native static byte[] signPssHash(byte[] hash, - int hashSize, int saltLength, String hashAlgorithm, - long hCryptProv, long nCryptKey) - throws SignatureException; - - /** - * Verify a signed hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. - * This method is not used now. See {@link #fallbackSignature}. - */ - private native static boolean verifyPssSignedHash(byte[] hash, int hashSize, - byte[] signature, int signatureSize, - int saltLength, String hashAlgorithm, - long hCryptProv, long hKey) throws SignatureException; } - // initialize for signing. See JCA doc - @Override - protected void engineInitVerify(PublicKey key) - throws InvalidKeyException - { - // This signature accepts only RSAPublicKey - if ((key instanceof java.security.interfaces.RSAPublicKey) == false) { - throw new InvalidKeyException("Key type not supported"); - } + /** + * Sign hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. + */ + native static byte[] signCngHash( + byte[] hash, int hashSize, int saltLength, String hashAlgorithm, + long hCryptProv, long nCryptKey) + throws SignatureException; - java.security.interfaces.RSAPublicKey rsaKey = - (java.security.interfaces.RSAPublicKey) key; - - if ((key instanceof sun.security.mscapi.RSAPublicKey) == false) { - - // convert key to MSCAPI format - - BigInteger modulus = rsaKey.getModulus(); - BigInteger exponent = rsaKey.getPublicExponent(); - - // Check against the local and global values to make sure - // the sizes are ok. Round up to the nearest byte. - RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7), - exponent, -1, RSAKeyPairGenerator.KEY_SIZE_MAX); - - byte[] modulusBytes = modulus.toByteArray(); - byte[] exponentBytes = exponent.toByteArray(); - - // Adjust key length due to sign bit - int keyBitLength = (modulusBytes[0] == 0) - ? (modulusBytes.length - 1) * 8 - : modulusBytes.length * 8; - - byte[] keyBlob = generatePublicKeyBlob( - keyBitLength, modulusBytes, exponentBytes); - - try { - publicKey = importPublicKey(keyBlob, keyBitLength); - - } catch (KeyStoreException e) { - throw new InvalidKeyException(e); - } - - } else { - publicKey = (sun.security.mscapi.RSAPublicKey) key; - } - - this.privateKey = null; - resetDigest(); - } - - // initialize for signing. See JCA doc - @Override - protected void engineInitSign(PrivateKey key) throws InvalidKeyException - { - // This signature accepts only RSAPrivateKey - if ((key instanceof sun.security.mscapi.RSAPrivateKey) == false) { - throw new InvalidKeyException("Key type not supported"); - } - privateKey = (sun.security.mscapi.RSAPrivateKey) key; - - // Check against the local and global values to make sure - // the sizes are ok. Round up to nearest byte. - RSAKeyFactory.checkKeyLengths(((privateKey.length() + 7) & ~7), - null, RSAKeyPairGenerator.KEY_SIZE_MIN, - RSAKeyPairGenerator.KEY_SIZE_MAX); - - this.publicKey = null; - resetDigest(); - } + /** + * Verify a signed hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. + * This method is not used now. See {@link PSS#fallbackSignature}. + */ + private native static boolean verifyCngSignedHash( + byte[] hash, int hashSize, byte[] signature, int signatureSize, + int saltLength, String hashAlgorithm, + long hCryptProv, long hKey) throws SignatureException; /** * Resets the message digest if needed. @@ -575,8 +646,7 @@ abstract class RSASignature extends java.security.SignatureSpi * properly. */ @Override - protected void engineUpdate(byte b) throws SignatureException - { + protected void engineUpdate(byte b) throws SignatureException { messageDigest.update(b); needsReset = true; } @@ -594,8 +664,7 @@ abstract class RSASignature extends java.security.SignatureSpi */ @Override protected void engineUpdate(byte[] b, int off, int len) - throws SignatureException - { + throws SignatureException { messageDigest.update(b, off, len); needsReset = true; } @@ -607,47 +676,15 @@ abstract class RSASignature extends java.security.SignatureSpi * @param input the ByteBuffer */ @Override - protected void engineUpdate(ByteBuffer input) - { + protected void engineUpdate(ByteBuffer input) { messageDigest.update(input); needsReset = true; } - /** - * Returns the signature bytes of all the data - * updated so far. - * The format of the signature depends on the underlying - * signature scheme. - * - * @return the signature bytes of the signing operation's result. - * - * @exception SignatureException if the engine is not - * initialized properly or if this signature algorithm is unable to - * process the input data provided. - */ - @Override - protected byte[] engineSign() throws SignatureException { - - byte[] hash = getDigestValue(); - - // Omit the hash OID when generating a Raw signature - boolean noHashOID = this instanceof Raw; - - // Sign hash using MS Crypto APIs - - byte[] result = signHash(noHashOID, hash, hash.length, - messageDigestAlgorithm, privateKey.getHCryptProvider(), - privateKey.getHCryptKey()); - - // Convert signature array from little endian to big endian - return convertEndianArray(result); - } - /** * Convert array from big endian to little endian, or vice versa. */ - private byte[] convertEndianArray(byte[] byteArray) - { + private static byte[] convertEndianArray(byte[] byteArray) { if (byteArray == null || byteArray.length == 0) return byteArray; @@ -675,30 +712,6 @@ abstract class RSASignature extends java.security.SignatureSpi String hashAlgorithm, byte[] signature, int signatureSize, long hCryptProv, long hCryptKey) throws SignatureException; - /** - * Verifies the passed-in signature. - * - * @param sigBytes the signature bytes to be verified. - * - * @return true if the signature was verified, false if not. - * - * @exception SignatureException if the engine is not - * initialized properly, the passed-in signature is improperly - * encoded or of the wrong type, if this signature algorithm is unable to - * process the input data provided, etc. - */ - @Override - protected boolean engineVerify(byte[] sigBytes) - throws SignatureException - { - byte[] hash = getDigestValue(); - - return verifySignedHash(hash, hash.length, - messageDigestAlgorithm, convertEndianArray(sigBytes), - sigBytes.length, publicKey.getHCryptProvider(), - publicKey.getHCryptKey()); - } - /** * Sets the specified algorithm parameter to the specified * value. This method supplies a general-purpose mechanism through @@ -726,8 +739,7 @@ abstract class RSASignature extends java.security.SignatureSpi @Override @Deprecated protected void engineSetParameter(String param, Object value) - throws InvalidParameterException - { + throws InvalidParameterException { throw new InvalidParameterException("Parameter not supported"); } @@ -741,8 +753,7 @@ abstract class RSASignature extends java.security.SignatureSpi */ @Override protected void engineSetParameter(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException - { + throws InvalidAlgorithmParameterException { if (params != null) { throw new InvalidAlgorithmParameterException("No parameter accepted"); } @@ -773,8 +784,7 @@ abstract class RSASignature extends java.security.SignatureSpi @Override @Deprecated protected Object engineGetParameter(String param) - throws InvalidParameterException - { + throws InvalidParameterException { throw new InvalidParameterException("Parameter not supported"); } @@ -788,18 +798,10 @@ abstract class RSASignature extends java.security.SignatureSpi return null; } - /** - * Generates a public-key BLOB from a key's components. - */ - // used by RSACipher - static native byte[] generatePublicKeyBlob( - int keyBitLength, byte[] modulus, byte[] publicExponent) - throws InvalidKeyException; - /** * Imports a public-key BLOB. */ - // used by RSACipher - static native RSAPublicKey importPublicKey(byte[] keyBlob, int keySize) - throws KeyStoreException; + // used by CRSACipher + static native CPublicKey importPublicKey( + String alg, byte[] keyBlob, int keySize) throws KeyStoreException; } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/Key.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/Key.java deleted file mode 100644 index a36656f4521..00000000000 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/Key.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.mscapi; - -import sun.security.util.Length; - -/** - * The handle for an RSA or DSA key using the Microsoft Crypto API. - * - * @see RSAPrivateKey - * @see RSAPublicKey - * - * @since 1.6 - * @author Stanley Man-Kit Ho - */ -abstract class Key implements java.security.Key, Length -{ - private static final long serialVersionUID = -1088859394025049194L; - - static class NativeHandles { - long hCryptProv = 0; - long hCryptKey = 0; - - public NativeHandles(long hCryptProv, long hCryptKey) { - this.hCryptProv = hCryptProv; - this.hCryptKey = hCryptKey; - } - - /** - * Finalization method - */ - @SuppressWarnings("deprecation") - protected void finalize() throws Throwable - { - try { - synchronized(this) - { - cleanUp(hCryptProv, hCryptKey); - hCryptProv = 0; - hCryptKey = 0; - } - - } finally { - super.finalize(); - } - } - } - - protected NativeHandles handles; - - // Key length - protected int keyLength = 0; - - /** - * Construct a Key object. - */ - protected Key(NativeHandles handles, int keyLength) - { - this.handles = handles; - this.keyLength = keyLength; - } - - /** - * Native method to cleanup the key handle. - */ - private native static void cleanUp(long hCryptProv, long hCryptKey); - - /** - * Return bit length of the key. - */ - @Override - public int length() - { - return keyLength; - } - - - /** - * Return native HCRYPTKEY handle. - */ - public long getHCryptKey() - { - return handles.hCryptKey; - } - - /** - * Return native HCRYPTPROV handle. - */ - public long getHCryptProvider() - { - return handles.hCryptProv; - } - - /** - * Returns the standard algorithm name for this key. For - * example, "RSA" would indicate that this key is a RSA key. - * See Appendix A in the - * Java Cryptography Architecture API Specification & Reference - * for information about standard algorithm names. - * - * @return the name of the algorithm associated with this key. - */ - public abstract String getAlgorithm(); - - /** - * Returns the name of the primary encoding format of this key, - * or null if this key does not support encoding. - * The primary encoding format is - * named in terms of the appropriate ASN.1 data format, if an - * ASN.1 specification for this key exists. - * For example, the name of the ASN.1 data format for public - * keys is SubjectPublicKeyInfo, as - * defined by the X.509 standard; in this case, the returned format is - * "X.509". Similarly, - * the name of the ASN.1 data format for private keys is - * PrivateKeyInfo, - * as defined by the PKCS #8 standard; in this case, the returned format is - * "PKCS#8". - * - * @return the primary encoding format of the key. - */ - public String getFormat() - { - return null; - } - - /** - * Returns the key in its primary encoding format, or null - * if this key does not support encoding. - * - * @return the encoded key, or null if the key does not support - * encoding. - */ - public byte[] getEncoded() - { - return null; - } - - protected native static String getContainerName(long hCryptProv); - - protected native static String getKeyType(long hCryptKey); -} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/PRNG.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/PRNG.java index 61737e8f411..d7026e433f6 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/PRNG.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/PRNG.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPairGenerator.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPairGenerator.java deleted file mode 100644 index d4f509058fc..00000000000 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAKeyPairGenerator.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.mscapi; - -import java.util.UUID; -import java.security.*; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.RSAKeyGenParameterSpec; - -import sun.security.rsa.RSAKeyFactory; -import static sun.security.util.SecurityProviderConstants.DEF_RSA_KEY_SIZE; - -/** - * RSA keypair generator. - * - * Standard algorithm, minimum key length is 512 bit, maximum is 16,384. - * Generates a private key that is exportable. - * - * @since 1.6 - */ -public final class RSAKeyPairGenerator extends KeyPairGeneratorSpi { - - // Supported by Microsoft Base, Strong and Enhanced Cryptographic Providers - static final int KEY_SIZE_MIN = 512; // disallow MSCAPI min. of 384 - static final int KEY_SIZE_MAX = 16384; - - // size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX - private int keySize; - - public RSAKeyPairGenerator() { - // initialize to default in case the app does not call initialize() - initialize(DEF_RSA_KEY_SIZE, null); - } - - // initialize the generator. See JCA doc - // random is always ignored - public void initialize(int keySize, SecureRandom random) { - - try { - RSAKeyFactory.checkKeyLengths(keySize, null, - KEY_SIZE_MIN, KEY_SIZE_MAX); - } catch (InvalidKeyException e) { - throw new InvalidParameterException(e.getMessage()); - } - - this.keySize = keySize; - } - - // second initialize method. See JCA doc - // random and exponent are always ignored - public void initialize(AlgorithmParameterSpec params, SecureRandom random) - throws InvalidAlgorithmParameterException { - - int tmpSize; - if (params == null) { - tmpSize = DEF_RSA_KEY_SIZE; - } else if (params instanceof RSAKeyGenParameterSpec) { - - if (((RSAKeyGenParameterSpec) params).getPublicExponent() != null) { - throw new InvalidAlgorithmParameterException - ("Exponent parameter is not supported"); - } - tmpSize = ((RSAKeyGenParameterSpec) params).getKeysize(); - - } else { - throw new InvalidAlgorithmParameterException - ("Params must be an instance of RSAKeyGenParameterSpec"); - } - - try { - RSAKeyFactory.checkKeyLengths(tmpSize, null, - KEY_SIZE_MIN, KEY_SIZE_MAX); - } catch (InvalidKeyException e) { - throw new InvalidAlgorithmParameterException( - "Invalid Key sizes", e); - } - - this.keySize = tmpSize; - } - - // generate the keypair. See JCA doc - public KeyPair generateKeyPair() { - - try { - - // Generate each keypair in a unique key container - RSAKeyPair keys = - generateRSAKeyPair(keySize, - "{" + UUID.randomUUID().toString() + "}"); - - return new KeyPair(keys.getPublic(), keys.getPrivate()); - - } catch (KeyException e) { - throw new ProviderException(e); - } - } - - private static native RSAKeyPair generateRSAKeyPair(int keySize, - String keyContainerName) throws KeyException; -} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPublicKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPublicKey.java deleted file mode 100644 index 917d1eb7ab7..00000000000 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/RSAPublicKey.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.mscapi; - -import java.math.BigInteger; -import java.security.KeyException; -import java.security.KeyRep; -import java.security.ProviderException; - -import sun.security.rsa.RSAUtil.KeyType; -import sun.security.rsa.RSAPublicKeyImpl; - -/** - * The handle for an RSA public key using the Microsoft Crypto API. - * - * @since 1.6 - */ -class RSAPublicKey extends Key implements java.security.interfaces.RSAPublicKey -{ - private static final long serialVersionUID = -2289561342425825391L; - - private byte[] publicKeyBlob = null; - private byte[] encoding = null; - private BigInteger modulus = null; - private BigInteger exponent = null; - - /** - * Construct an RSAPublicKey object. - */ - RSAPublicKey(long hCryptProv, long hCryptKey, int keyLength) - { - super(new NativeHandles(hCryptProv, hCryptKey), keyLength); - } - - /** - * Construct an RSAPublicKey object. - */ - RSAPublicKey(NativeHandles handles, int keyLength) - { - super(handles, keyLength); - } - - /** - * Returns the standard algorithm name for this key. For - * example, "RSA" would indicate that this key is a RSA key. - * See Appendix A in the - * Java Cryptography Architecture API Specification & Reference - * for information about standard algorithm names. - * - * @return the name of the algorithm associated with this key. - */ - public String getAlgorithm() - { - return "RSA"; - } - - /** - * Returns a printable description of the key. - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - - sb.append("RSAPublicKey [size=").append(keyLength) - .append(" bits, type=").append(getKeyType(handles.hCryptKey)) - .append(", container=").append(getContainerName(handles.hCryptProv)) - .append("]\n modulus: ").append(getModulus()) - .append("\n public exponent: ").append(getPublicExponent()); - - return sb.toString(); - } - - /** - * Returns the public exponent. - */ - public BigInteger getPublicExponent() { - - if (exponent == null) { - - try { - publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); - exponent = new BigInteger(1, getExponent(publicKeyBlob)); - - } catch (KeyException e) { - throw new ProviderException(e); - } - } - - return exponent; - } - - /** - * Returns the modulus. - */ - public BigInteger getModulus() { - - if (modulus == null) { - - try { - publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); - modulus = new BigInteger(1, getModulus(publicKeyBlob)); - - } catch (KeyException e) { - throw new ProviderException(e); - } - } - - return modulus; - } - - /** - * Returns the name of the primary encoding format of this key, - * or null if this key does not support encoding. - * The primary encoding format is - * named in terms of the appropriate ASN.1 data format, if an - * ASN.1 specification for this key exists. - * For example, the name of the ASN.1 data format for public - * keys is SubjectPublicKeyInfo, as - * defined by the X.509 standard; in this case, the returned format is - * "X.509". Similarly, - * the name of the ASN.1 data format for private keys is - * PrivateKeyInfo, - * as defined by the PKCS #8 standard; in this case, the returned format is - * "PKCS#8". - * - * @return the primary encoding format of the key. - */ - public String getFormat() - { - return "X.509"; - } - - /** - * Returns the key in its primary encoding format, or null - * if this key does not support encoding. - * - * @return the encoded key, or null if the key does not support - * encoding. - */ - public byte[] getEncoded() - { - if (encoding == null) { - - try { - encoding = RSAPublicKeyImpl.newKey(KeyType.RSA, null, - getModulus(), getPublicExponent()).getEncoded(); - - } catch (KeyException e) { - // ignore - } - } - return encoding; - } - - protected Object writeReplace() throws java.io.ObjectStreamException { - return new KeyRep(KeyRep.Type.PUBLIC, - getAlgorithm(), - getFormat(), - getEncoded()); - } - - /* - * Returns the Microsoft CryptoAPI representation of the key. - */ - private native byte[] getPublicKeyBlob(long hCryptKey) throws KeyException; - - /* - * Returns the key's public exponent (in big-endian 2's complement format). - */ - private native byte[] getExponent(byte[] keyBlob) throws KeyException; - - /* - * Returns the key's modulus (in big-endian 2's complement format). - */ - private native byte[] getModulus(byte[] keyBlob) throws KeyException; -} diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java index 60f684a4bb4..9fcebc4466c 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java @@ -33,7 +33,6 @@ import java.security.InvalidParameterException; import java.security.ProviderException; import java.util.HashMap; import java.util.Arrays; -import java.util.Map; import static sun.security.util.SecurityConstants.PROVIDER_VER; @@ -86,36 +85,36 @@ public final class SunMSCAPI extends Provider { } } else if (type.equals("KeyStore")) { if (algo.equals("Windows-MY")) { - return new KeyStore.MY(); + return new CKeyStore.MY(); } else if (algo.equals("Windows-ROOT")) { - return new KeyStore.ROOT(); + return new CKeyStore.ROOT(); } } else if (type.equals("Signature")) { if (algo.equals("NONEwithRSA")) { - return new RSASignature.Raw(); + return new CSignature.NONEwithRSA(); } else if (algo.equals("SHA1withRSA")) { - return new RSASignature.SHA1(); + return new CSignature.SHA1withRSA(); } else if (algo.equals("SHA256withRSA")) { - return new RSASignature.SHA256(); + return new CSignature.SHA256withRSA(); } else if (algo.equals("SHA384withRSA")) { - return new RSASignature.SHA384(); + return new CSignature.SHA384withRSA(); } else if (algo.equals("SHA512withRSA")) { - return new RSASignature.SHA512(); + return new CSignature.SHA512withRSA(); } else if (algo.equals("MD5withRSA")) { - return new RSASignature.MD5(); + return new CSignature.MD5withRSA(); } else if (algo.equals("MD2withRSA")) { - return new RSASignature.MD2(); + return new CSignature.MD2withRSA(); } else if (algo.equals("RSASSA-PSS")) { - return new RSASignature.PSS(); + return new CSignature.PSS(); } } else if (type.equals("KeyPairGenerator")) { if (algo.equals("RSA")) { - return new RSAKeyPairGenerator(); + return new CKeyPairGenerator.RSA(); } } else if (type.equals("Cipher")) { if (algo.equals("RSA") || algo.equals("RSA/ECB/PKCS1Padding")) { - return new RSACipher(); + return new CRSACipher(); } } } catch (Exception ex) { @@ -147,47 +146,47 @@ public final class SunMSCAPI extends Provider { * Key store */ putService(new ProviderService(p, "KeyStore", - "Windows-MY", "sun.security.mscapi.KeyStore$MY")); + "Windows-MY", "sun.security.mscapi.CKeyStore$MY")); putService(new ProviderService(p, "KeyStore", - "Windows-ROOT", "sun.security.mscapi.KeyStore$ROOT")); + "Windows-ROOT", "sun.security.mscapi.CKeyStore$ROOT")); /* * Signature engines */ HashMap attrs = new HashMap<>(1); - attrs.put("SupportedKeyClasses", "sun.security.mscapi.Key"); + attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); // NONEwithRSA must be supplied with a pre-computed message digest. // Only the following digest algorithms are supported: MD5, SHA-1, // SHA-256, SHA-384, SHA-512 and a special-purpose digest // algorithm which is a concatenation of SHA-1 and MD5 digests. putService(new ProviderService(p, "Signature", - "NONEwithRSA", "sun.security.mscapi.RSASignature$Raw", + "NONEwithRSA", "sun.security.mscapi.CSignature$NONEwithRSA", null, attrs)); putService(new ProviderService(p, "Signature", - "SHA1withRSA", "sun.security.mscapi.RSASignature$SHA1", + "SHA1withRSA", "sun.security.mscapi.CSignature$SHA1withRSA", null, attrs)); putService(new ProviderService(p, "Signature", - "SHA256withRSA", "sun.security.mscapi.RSASignature$SHA256", + "SHA256withRSA", "sun.security.mscapi.CSignature$SHA256withRSA", new String[] { "1.2.840.113549.1.1.11", "OID.1.2.840.113549.1.1.11" }, attrs)); putService(new ProviderService(p, "Signature", - "SHA384withRSA", "sun.security.mscapi.RSASignature$SHA384", + "SHA384withRSA", "sun.security.mscapi.CSignature$SHA384withRSA", new String[] { "1.2.840.113549.1.1.12", "OID.1.2.840.113549.1.1.12" }, attrs)); putService(new ProviderService(p, "Signature", - "SHA512withRSA", "sun.security.mscapi.RSASignature$SHA512", + "SHA512withRSA", "sun.security.mscapi.CSignature$SHA512withRSA", new String[] { "1.2.840.113549.1.1.13", "OID.1.2.840.113549.1.1.13" }, attrs)); putService(new ProviderService(p, "Signature", - "RSASSA-PSS", "sun.security.mscapi.RSASignature$PSS", + "RSASSA-PSS", "sun.security.mscapi.CSignature$PSS", new String[] { "1.2.840.113549.1.1.10", "OID.1.2.840.113549.1.1.10" }, attrs)); putService(new ProviderService(p, "Signature", - "MD5withRSA", "sun.security.mscapi.RSASignature$MD5", + "MD5withRSA", "sun.security.mscapi.CSignature$MD5withRSA", null, attrs)); putService(new ProviderService(p, "Signature", - "MD2withRSA", "sun.security.mscapi.RSASignature$MD2", + "MD2withRSA", "sun.security.mscapi.CSignature$MD2withRSA", null, attrs)); /* @@ -196,7 +195,7 @@ public final class SunMSCAPI extends Provider { attrs.clear(); attrs.put("KeySize", "16384"); putService(new ProviderService(p, "KeyPairGenerator", - "RSA", "sun.security.mscapi.RSAKeyPairGenerator", + "RSA", "sun.security.mscapi.CKeyPairGenerator$RSA", null, attrs)); /* @@ -205,12 +204,12 @@ public final class SunMSCAPI extends Provider { attrs.clear(); attrs.put("SupportedModes", "ECB"); attrs.put("SupportedPaddings", "PKCS1PADDING"); - attrs.put("SupportedKeyClasses", "sun.security.mscapi.Key"); + attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); putService(new ProviderService(p, "Cipher", - "RSA", "sun.security.mscapi.RSACipher", + "RSA", "sun.security.mscapi.CRSACipher", null, attrs)); putService(new ProviderService(p, "Cipher", - "RSA/ECB/PKCS1Padding", "sun.security.mscapi.RSACipher", + "RSA/ECB/PKCS1Padding", "sun.security.mscapi.CRSACipher", null, attrs)); return null; } diff --git a/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp b/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp index 310a01ca711..afff2277e5e 100644 --- a/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp +++ b/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp @@ -37,13 +37,15 @@ #include #include #include -#include "sun_security_mscapi_Key.h" -#include "sun_security_mscapi_KeyStore.h" +#include "sun_security_mscapi_CKey.h" +#include "sun_security_mscapi_CKeyStore.h" #include "sun_security_mscapi_PRNG.h" -#include "sun_security_mscapi_RSACipher.h" -#include "sun_security_mscapi_RSAKeyPairGenerator.h" -#include "sun_security_mscapi_RSAPublicKey.h" -#include "sun_security_mscapi_RSASignature.h" +#include "sun_security_mscapi_CRSACipher.h" +#include "sun_security_mscapi_CKeyPairGenerator_RSA.h" +#include "sun_security_mscapi_CPublicKey.h" +#include "sun_security_mscapi_CPublicKey_CRSAPublicKey.h" +#include "sun_security_mscapi_CSignature.h" +#include "sun_security_mscapi_CSignature_RSA.h" #define OID_EKU_ANY "2.5.29.37.0" @@ -64,7 +66,7 @@ } //#define PP(fmt, ...) \ -// fprintf(stdout, "SSPI (%ld): ", __LINE__); \ +// fprintf(stdout, "MSCAPI (%ld): ", __LINE__); \ // fprintf(stdout, fmt, ##__VA_ARGS__); \ // fprintf(stdout, "\n"); \ // fflush(stdout) @@ -79,13 +81,27 @@ DEF_STATIC_JNI_OnLoad //void dump(LPSTR title, PBYTE data, DWORD len) //{ // printf("==== %s ====\n", title); -// for (DWORD i = 0; i < len; i++) { -// if (i != 0 && i % 16 == 0) { -// printf("\n"); +// for (DWORD i = 0; i < len; i+=16) { +// printf("%04x: ", i); +// for (int j = 0; j < 16; j++) { +// if (j == 8) { +// printf(" "); +// } +// if (i + j < len) { +// printf("%02X ", *(data + i + j) & 0xff); +// } else { +// printf(" "); +// } // } -// printf("%02X ", *(data + i) & 0xff); +// for (int j = 0; j < 16; j++) { +// if (i + j < len) { +// int k = *(data + i + j) & 0xff; +// if (k < 32 || k > 127) printf("."); +// else printf("%c", (char)k); +// } +// } +// printf("\n"); // } -// printf("\n"); //} /* @@ -248,7 +264,7 @@ bool GetCertificateChain(LPSTR lpszKeyUsageIdentifier, PCCERT_CONTEXT pCertConte JNIEXPORT jlong JNICALL Java_sun_security_mscapi_PRNG_getContext (JNIEnv *env, jclass clazz) { HCRYPTPROV hCryptProv = NULL; - if(::CryptAcquireContext( + if(::CryptAcquireContext( //deprecated &hCryptProv, NULL, NULL, @@ -269,7 +285,7 @@ JNIEXPORT jlong JNICALL Java_sun_security_mscapi_PRNG_getContext JNIEXPORT void JNICALL Java_sun_security_mscapi_PRNG_releaseContext (JNIEnv *env, jclass clazz, jlong ctxt) { if (ctxt) { - ::CryptReleaseContext((HCRYPTPROV)ctxt, 0); + ::CryptReleaseContext((HCRYPTPROV)ctxt, 0); //deprecated } } @@ -304,7 +320,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_PRNG_generateSeed __leave; } - if (::CryptGenRandom( + if (::CryptGenRandom( //deprecated hCryptProv, length, (BYTE *) reseedBytes) == FALSE) { @@ -330,7 +346,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_PRNG_generateSeed __leave; } - if (::CryptGenRandom( + if (::CryptGenRandom( //deprecated hCryptProv, length, (BYTE *) seedBytes) == FALSE) { @@ -359,11 +375,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_PRNG_generateSeed /* - * Class: sun_security_mscapi_KeyStore + * Class: sun_security_mscapi_CKeyStore * Method: loadKeysOrCertificateChains - * Signature: (Ljava/lang/String;Ljava/util/Collection;)V + * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateChains +JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateChains (JNIEnv *env, jobject obj, jstring jCertStoreName) { /** @@ -460,7 +476,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh else { if (bCallerFreeProv == TRUE) { - ::CryptReleaseContext(hCryptProv, NULL); + ::CryptReleaseContext(hCryptProv, NULL); // deprecated bCallerFreeProv = FALSE; } @@ -473,18 +489,18 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh else { // Private key is available - BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); + BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); //deprecated // Skip certificate if cannot find private key if (bGetUserKey == FALSE) { if (bCallerFreeProv) - ::CryptReleaseContext(hCryptProv, NULL); + ::CryptReleaseContext(hCryptProv, NULL); // deprecated continue; } // Set cipher mode to ECB DWORD dwCipherMode = CRYPT_MODE_ECB; - ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); + ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); //deprecated // If the private key is present in smart card, we may not be able to // determine the key length by using the private key handle. However, @@ -570,9 +586,8 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateCh // Determine key type: RSA or DSA DWORD dwData = CALG_RSA_KEYX; DWORD dwSize = sizeof(DWORD); - ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, + ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, //deprecated &dwSize, NULL); - if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA) { // Generate RSA certificate chain and store into cert @@ -614,18 +629,18 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_Key_cleanUp (JNIEnv *env, jclass clazz, jlong hCryptProv, jlong hCryptKey) { if (hCryptKey != NULL) - ::CryptDestroyKey((HCRYPTKEY) hCryptKey); + ::CryptDestroyKey((HCRYPTKEY) hCryptKey); // deprecated if (hCryptProv != NULL) - ::CryptReleaseContext((HCRYPTPROV) hCryptProv, NULL); + ::CryptReleaseContext((HCRYPTPROV) hCryptProv, NULL); // deprecated } /* - * Class: sun_security_mscapi_RSASignature + * Class: sun_security_mscapi_CSignature * Method: signHash * Signature: (Z[BILjava/lang/String;JJ)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signHash (JNIEnv *env, jclass clazz, jboolean noHashOID, jbyteArray jHash, jint jHashSize, jstring jHashAlgorithm, jlong hCryptProv, jlong hCryptKey) @@ -642,7 +657,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash ALG_ID algId = MapHashAlgorithm(env, jHashAlgorithm); // Acquire a hash object handle. - if (::CryptCreateHash(HCRYPTPROV(hCryptProv), algId, 0, 0, &hHash) == FALSE) + if (::CryptCreateHash(HCRYPTPROV(hCryptProv), algId, 0, 0, &hHash) == FALSE) //deprecated { // Failover to using the PROV_RSA_AES CSP @@ -651,11 +666,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash pbData[0] = '\0'; // Get name of the key container - ::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_CONTAINER, + ::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_CONTAINER, //deprecated (BYTE *)pbData, &cbData, 0); // Acquire an alternative CSP handle - if (::CryptAcquireContext(&hCryptProvAlt, LPCSTR(pbData), NULL, + if (::CryptAcquireContext(&hCryptProvAlt, LPCSTR(pbData), NULL, //deprecated PROV_RSA_AES, 0) == FALSE) { @@ -664,7 +679,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash } // Acquire a hash object handle. - if (::CryptCreateHash(HCRYPTPROV(hCryptProvAlt), algId, 0, 0, + if (::CryptCreateHash(HCRYPTPROV(hCryptProvAlt), algId, 0, 0, //deprecated &hHash) == FALSE) { ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); @@ -680,7 +695,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash env->GetByteArrayRegion(jHash, 0, jHashSize, pHashBuffer); // Set hash value in the hash object - if (::CryptSetHashParam(hHash, HP_HASHVAL, (BYTE*)pHashBuffer, NULL) == FALSE) + if (::CryptSetHashParam(hHash, HP_HASHVAL, (BYTE*)pHashBuffer, NULL) == FALSE) //deprecated { ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); __leave; @@ -691,7 +706,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash ALG_ID dwAlgId; DWORD dwAlgIdLen = sizeof(ALG_ID); - if (! ::CryptGetKeyParam((HCRYPTKEY) hCryptKey, KP_ALGID, (BYTE*)&dwAlgId, &dwAlgIdLen, 0)) { + if (! ::CryptGetKeyParam((HCRYPTKEY) hCryptKey, KP_ALGID, (BYTE*)&dwAlgId, &dwAlgIdLen, 0)) { //deprecated ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); __leave; @@ -708,7 +723,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash dwFlags = CRYPT_NOHASHOID; // omit hash OID in NONEwithRSA signature } - if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, NULL, &dwBufLen) == FALSE) + if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, NULL, &dwBufLen) == FALSE) //deprecated { ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); __leave; @@ -718,7 +733,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash if (pSignedHashBuffer == NULL) { __leave; } - if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, (BYTE*)pSignedHashBuffer, &dwBufLen) == FALSE) + if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, (BYTE*)pSignedHashBuffer, &dwBufLen) == FALSE) //deprecated { ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); __leave; @@ -741,21 +756,21 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_signHash delete [] pHashBuffer; if (hHash) - ::CryptDestroyHash(hHash); + ::CryptDestroyHash(hHash); //deprecated if (hCryptProvAlt) - ::CryptReleaseContext(hCryptProvAlt, 0); + ::CryptReleaseContext(hCryptProvAlt, 0); // deprecated } return jSignedHash; } /* - * Class: sun_security_mscapi_RSASignature_PSS - * Method: signPssHash + * Class: sun_security_mscapi_CSignature + * Method: signCngHash * Signature: ([BIILjava/lang/String;JJ)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_signPssHash +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash (JNIEnv *env, jclass clazz, jbyteArray jHash, jint jHashSize, jint saltLen, jstring jHashAlgorithm, jlong hCryptProv, jlong hCryptKey) @@ -839,11 +854,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_sign } /* - * Class: sun_security_mscapi_RSASignature + * Class: sun_security_mscapi_CSignature * Method: verifySignedHash * Signature: ([BIL/java/lang/String;[BIJJ)Z */ -JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_verifySignedHash +JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifySignedHash (JNIEnv *env, jclass clazz, jbyteArray jHash, jint jHashSize, jstring jHashAlgorithm, jbyteArray jSignedHash, jint jSignedHashSize, jlong hCryptProv, jlong hCryptKey) @@ -871,11 +886,11 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_verifySignedHas pbData[0] = '\0'; // Get name of the key container - ::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_CONTAINER, + ::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_CONTAINER, //deprecated (BYTE *)pbData, &cbData, 0); // Acquire an alternative CSP handle - if (::CryptAcquireContext(&hCryptProvAlt, LPCSTR(pbData), NULL, + if (::CryptAcquireContext(&hCryptProvAlt, LPCSTR(pbData), NULL, //deprecated PROV_RSA_AES, 0) == FALSE) { @@ -907,7 +922,7 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_verifySignedHas pSignedHashBuffer); // Set hash value in the hash object - if (::CryptSetHashParam(hHash, HP_HASHVAL, (BYTE*) pHashBuffer, NULL) + if (::CryptSetHashParam(hHash, HP_HASHVAL, (BYTE*) pHashBuffer, NULL) //deprecated == FALSE) { ThrowException(env, SIGNATURE_EXCEPTION, GetLastError()); @@ -918,7 +933,7 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_verifySignedHas // public key algorithm, so AT_SIGNATURE is used. // Verify the signature - if (::CryptVerifySignatureA(hHash, (BYTE *) pSignedHashBuffer, + if (::CryptVerifySignatureA(hHash, (BYTE *) pSignedHashBuffer, //deprecated dwSignedHashBufferLen, (HCRYPTKEY) hCryptKey, NULL, 0) == TRUE) { result = JNI_TRUE; @@ -934,26 +949,26 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_verifySignedHas delete [] pHashBuffer; if (hHash) - ::CryptDestroyHash(hHash); + ::CryptDestroyHash(hHash); //deprecated if (hCryptProvAlt) - ::CryptReleaseContext(hCryptProvAlt, 0); + ::CryptReleaseContext(hCryptProvAlt, 0); // deprecated } return result; } /* - * Class: sun_security_mscapi_RSASignature_PSS - * Method: verifyPssSignedHash + * Class: sun_security_mscapi_CSignature + * Method: verifyCngSignedHash * Signature: ([BI[BIILjava/lang/String;JJ)Z */ -JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_verifyPssSignedHash +JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifyCngSignedHash (JNIEnv *env, jclass clazz, jbyteArray jHash, jint jHashSize, jbyteArray jSignedHash, jint jSignedHashSize, jint saltLen, jstring jHashAlgorithm, - jlong hCryptProv, jlong hKey) + jlong hCryptProv, jlong hCryptKey) { jbyte* pHashBuffer = NULL; jbyte* pSignedHashBuffer = NULL; @@ -966,7 +981,7 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_verify NULL, &hk, hCryptProv, - hKey, + hCryptKey, NULL, 0)); @@ -987,17 +1002,12 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_verify BCRYPT_PSS_PADDING_INFO pssInfo; pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); pssInfo.cbSalt = saltLen; - if (pssInfo.pszAlgId == NULL) { ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, "Unrecognised hash algorithm"); __leave; } - // For RSA, the hash encryption algorithm is normally the same as the - // public key algorithm, so AT_SIGNATURE is used. - - // Verify the signature if (::NCryptVerifySignature(hk, &pssInfo, (BYTE *) pHashBuffer, jHashSize, (BYTE *) pSignedHashBuffer, jSignedHashSize, @@ -1023,12 +1033,12 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_RSASignature_00024PSS_verify } /* - * Class: sun_security_mscapi_RSAKeyPairGenerator - * Method: generateRSAKeyPair - * Signature: (ILjava/lang/String;)Lsun/security/mscapi/RSAKeyPair; + * Class: sun_security_mscapi_CKeyPairGenerator_RSA + * Method: generateCKeyPair + * Signature: (Ljava/lang/String;ILjava/lang/String;)Lsun/security/mscapi/CKeyPair; */ -JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateRSAKeyPair - (JNIEnv *env, jclass clazz, jint keySize, jstring keyContainerName) +JNIEXPORT jobject JNICALL Java_sun_security_mscapi_CKeyPairGenerator_00024RSA_generateCKeyPair + (JNIEnv *env, jclass clazz, jstring alg, jint keySize, jstring keyContainerName) { HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKeyPair; @@ -1046,7 +1056,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateR // Acquire a CSP context (create a new key container). // Prefer a PROV_RSA_AES CSP, when available, due to its support // for SHA-2-based signatures. - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, pszKeyContainerName, NULL, @@ -1055,7 +1065,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateR { // Failover to using the default CSP (PROV_RSA_FULL) - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, pszKeyContainerName, NULL, @@ -1067,8 +1077,8 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateR } } - // Generate an RSA keypair - if(::CryptGenKey( + // Generate an keypair + if(::CryptGenKey( //deprecated hCryptProv, AT_KEYEXCHANGE, dwFlags, @@ -1078,22 +1088,22 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateR __leave; } - // Get the method ID for the RSAKeyPair constructor - jclass clazzRSAKeyPair = - env->FindClass("sun/security/mscapi/RSAKeyPair"); - if (clazzRSAKeyPair == NULL) { + // Get the method ID for the CKeyPair constructor + jclass clazzCKeyPair = + env->FindClass("sun/security/mscapi/CKeyPair"); + if (clazzCKeyPair == NULL) { __leave; } - jmethodID mNewRSAKeyPair = - env->GetMethodID(clazzRSAKeyPair, "", "(JJI)V"); - if (mNewRSAKeyPair == NULL) { + jmethodID mNewCKeyPair = + env->GetMethodID(clazzCKeyPair, "", "(Ljava/lang/String;JJI)V"); + if (mNewCKeyPair == NULL) { __leave; } - // Create a new RSA keypair - keypair = env->NewObject(clazzRSAKeyPair, mNewRSAKeyPair, - (jlong) hCryptProv, (jlong) hKeyPair, keySize); + // Create a new keypair + keypair = env->NewObject(clazzCKeyPair, mNewCKeyPair, + alg, (jlong) hCryptProv, (jlong) hKeyPair, keySize); } __finally @@ -1109,18 +1119,18 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSAKeyPairGenerator_generateR } /* - * Class: sun_security_mscapi_Key + * Class: sun_security_mscapi_CKey * Method: getContainerName * Signature: (J)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_sun_security_mscapi_Key_getContainerName +JNIEXPORT jstring JNICALL Java_sun_security_mscapi_CKey_getContainerName (JNIEnv *env, jclass jclazz, jlong hCryptProv) { DWORD cbData = 256; BYTE pbData[256]; pbData[0] = '\0'; - ::CryptGetProvParam( + ::CryptGetProvParam( //deprecated (HCRYPTPROV)hCryptProv, PP_CONTAINER, (BYTE *)pbData, @@ -1131,17 +1141,17 @@ JNIEXPORT jstring JNICALL Java_sun_security_mscapi_Key_getContainerName } /* - * Class: sun_security_mscapi_Key + * Class: sun_security_mscapi_CKey * Method: getKeyType * Signature: (J)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_sun_security_mscapi_Key_getKeyType +JNIEXPORT jstring JNICALL Java_sun_security_mscapi_CKey_getKeyType (JNIEnv *env, jclass jclazz, jlong hCryptKey) { ALG_ID dwAlgId; DWORD dwAlgIdLen = sizeof(ALG_ID); - if (::CryptGetKeyParam((HCRYPTKEY) hCryptKey, KP_ALGID, (BYTE*)&dwAlgId, &dwAlgIdLen, 0)) { + if (::CryptGetKeyParam((HCRYPTKEY) hCryptKey, KP_ALGID, (BYTE*)&dwAlgId, &dwAlgIdLen, 0)) { //deprecated if (CALG_RSA_SIGN == dwAlgId) { return env->NewStringUTF("Signature"); @@ -1161,11 +1171,11 @@ JNIEXPORT jstring JNICALL Java_sun_security_mscapi_Key_getKeyType } /* - * Class: sun_security_mscapi_KeyStore + * Class: sun_security_mscapi_CKeyStore * Method: storeCertificate * Signature: (Ljava/lang/String;Ljava/lang/String;[BIJJ)V */ -JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate +JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_storeCertificate (JNIEnv *env, jobject obj, jstring jCertStoreName, jstring jCertAliasName, jbyteArray jCertEncoding, jint jCertEncodingSize, jlong hCryptProv, jlong hCryptKey) @@ -1240,7 +1250,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate DWORD dwDataLen; // Get the name of the key container - if (! ::CryptGetProvParam( + if (! ::CryptGetProvParam( //deprecated (HCRYPTPROV) hCryptProv, PP_CONTAINER, NULL, @@ -1256,7 +1266,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate __leave; } - if (! ::CryptGetProvParam( + if (! ::CryptGetProvParam( //deprecated (HCRYPTPROV) hCryptProv, PP_CONTAINER, (BYTE *) pszContainerName, @@ -1283,7 +1293,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate // Get the name of the provider - if (! ::CryptGetProvParam( + if (! ::CryptGetProvParam( //deprecated (HCRYPTPROV) hCryptProv, PP_NAME, NULL, @@ -1299,7 +1309,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate __leave; } - if (! ::CryptGetProvParam( + if (! ::CryptGetProvParam( //deprecated (HCRYPTPROV) hCryptProv, PP_NAME, (BYTE *) pszProviderName, @@ -1325,7 +1335,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate keyProviderInfo.pwszProvName = pwszProviderName; // Get and set the type of the provider - if (! ::CryptGetProvParam( + if (! ::CryptGetProvParam( //deprecated (HCRYPTPROV) hCryptProv, PP_PROVTYPE, (LPBYTE) &keyProviderInfo.dwProvType, @@ -1344,7 +1354,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate keyProviderInfo.rgProvParam = NULL; // Get the key's algorithm ID - if (! ::CryptGetKeyParam( + if (! ::CryptGetKeyParam( //deprecated (HCRYPTKEY) hCryptKey, KP_ALGID, (LPBYTE) &keyProviderInfo.dwKeySpec, @@ -1423,11 +1433,11 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_storeCertificate } /* - * Class: sun_security_mscapi_KeyStore + * Class: sun_security_mscapi_CKeyStore * Method: removeCertificate * Signature: (Ljava/lang/String;Ljava/lang/String;[BI)V */ -JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_removeCertificate +JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_removeCertificate (JNIEnv *env, jobject obj, jstring jCertStoreName, jstring jCertAliasName, jbyteArray jCertEncoding, jint jCertEncodingSize) { @@ -1539,11 +1549,11 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_removeCertificate } /* - * Class: sun_security_mscapi_KeyStore + * Class: sun_security_mscapi_CKeyStore * Method: destroyKeyContainer * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_destroyKeyContainer +JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_destroyKeyContainer (JNIEnv *env, jobject clazz, jstring keyContainerName) { HCRYPTPROV hCryptProv = NULL; @@ -1565,7 +1575,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_destroyKeyContainer } // Acquire a CSP context (to the key container). - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, pszKeyContainerName, NULL, @@ -1588,11 +1598,11 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_destroyKeyContainer } /* - * Class: sun_security_mscapi_RSACipher + * Class: sun_security_mscapi_CRSACipher * Method: encryptDecrypt * Signature: ([BIJZ)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSACipher_encryptDecrypt +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CRSACipher_encryptDecrypt (JNIEnv *env, jclass clazz, jbyteArray jData, jint jDataSize, jlong hKey, jboolean doEncrypt) { @@ -1614,7 +1624,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSACipher_encryptDecrypt if (doEncrypt == JNI_TRUE) { // encrypt - if (! ::CryptEncrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, + if (! ::CryptEncrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, //deprecated &dwDataLen, dwBufLen)) { ThrowException(env, KEY_EXCEPTION, GetLastError()); @@ -1637,7 +1647,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSACipher_encryptDecrypt } // decrypt - if (! ::CryptDecrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, + if (! ::CryptDecrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, //deprecated &dwBufLen)) { ThrowException(env, KEY_EXCEPTION, GetLastError()); @@ -1661,11 +1671,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSACipher_encryptDecrypt } /* - * Class: sun_security_mscapi_RSAPublicKey + * Class: sun_security_mscapi_CPublicKey * Method: getPublicKeyBlob * Signature: (J)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getPublicKeyBlob +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_getPublicKeyBlob (JNIEnv *env, jobject clazz, jlong hCryptKey) { jbyteArray blob = NULL; @@ -1676,7 +1686,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getPublicKeyB { // Determine the size of the blob - if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, NULL, + if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, NULL, //deprecated &dwBlobLen)) { ThrowException(env, KEY_EXCEPTION, GetLastError()); @@ -1689,7 +1699,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getPublicKeyB } // Generate key blob - if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, + if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, //deprecated pbKeyBlob, &dwBlobLen)) { ThrowException(env, KEY_EXCEPTION, GetLastError()); @@ -1712,11 +1722,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getPublicKeyB } /* - * Class: sun_security_mscapi_RSAPublicKey + * Class: sun_security_mscapi_CPublicKey_CRSAPublicKey * Method: getExponent * Signature: ([B)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getExponent +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_00024CRSAPublicKey_getExponent (JNIEnv *env, jobject clazz, jbyteArray jKeyBlob) { jbyteArray exponent = NULL; @@ -1768,11 +1778,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getExponent } /* - * Class: sun_security_mscapi_RSAPublicKey + * Class: sun_security_mscapi_CPublicKey_CRSAPublicKey * Method: getModulus * Signature: ([B)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSAPublicKey_getModulus +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_00024CRSAPublicKey_getModulus (JNIEnv *env, jobject clazz, jbyteArray jKeyBlob) { jbyteArray modulus = NULL; @@ -2041,11 +2051,11 @@ jbyteArray generateKeyBlob( } /* - * Class: sun_security_mscapi_KeyStore - * Method: generatePrivateKeyBlob + * Class: sun_security_mscapi_CKeyStore + * Method: generateRSAPrivateKeyBlob * Signature: (I[B[B[B[B[B[B[B[B)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_KeyStore_generatePrivateKeyBlob +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CKeyStore_generateRSAPrivateKeyBlob (JNIEnv *env, jobject clazz, jint jKeyBitLength, jbyteArray jModulus, @@ -2063,11 +2073,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_KeyStore_generatePrivateKe } /* - * Class: sun_security_mscapi_RSASignature + * Class: sun_security_mscapi_CSignature_RSA * Method: generatePublicKeyBlob * Signature: (I[B[B)[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_generatePublicKeyBlob +JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_00024RSA_generatePublicKeyBlob (JNIEnv *env, jclass clazz, jint jKeyBitLength, jbyteArray jModulus, @@ -2078,13 +2088,13 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_RSASignature_generatePubli } /* - * Class: sun_security_mscapi_KeyStore + * Class: sun_security_mscapi_CKeyStore * Method: storePrivateKey - * Signature: ([BLjava/lang/String;I)Lsun/security/mscapi/RSAPrivateKey; + * Signature: (Ljava/lang/String;[BLjava/lang/String;I)Lsun/security/mscapi/CPrivateKey; */ -JNIEXPORT jobject JNICALL Java_sun_security_mscapi_KeyStore_storePrivateKey - (JNIEnv *env, jobject clazz, jbyteArray keyBlob, jstring keyContainerName, - jint keySize) +JNIEXPORT jobject JNICALL Java_sun_security_mscapi_CKeyStore_storePrivateKey + (JNIEnv *env, jobject clazz, jstring alg, jbyteArray keyBlob, + jstring keyContainerName, jint keySize) { HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKey = NULL; @@ -2106,7 +2116,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_KeyStore_storePrivateKey } // Acquire a CSP context (create a new key container). - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, pszKeyContainerName, NULL, @@ -2118,7 +2128,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_KeyStore_storePrivateKey } // Import the private key - if (::CryptImportKey( + if (::CryptImportKey( //deprecated hCryptProv, pbKeyBlob, dwBlobLen, @@ -2130,22 +2140,23 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_KeyStore_storePrivateKey __leave; } - // Get the method ID for the RSAPrivateKey constructor - jclass clazzRSAPrivateKey = - env->FindClass("sun/security/mscapi/RSAPrivateKey"); - if (clazzRSAPrivateKey == NULL) { + // Get the method ID for the CPrivateKey constructor + jclass clazzCPrivateKey = + env->FindClass("sun/security/mscapi/CPrivateKey"); + if (clazzCPrivateKey == NULL) { __leave; } - jmethodID mNewRSAPrivateKey = - env->GetMethodID(clazzRSAPrivateKey, "", "(JJI)V"); - if (mNewRSAPrivateKey == NULL) { + jmethodID mNewCPrivateKey = + env->GetStaticMethodID(clazzCPrivateKey, "of", + "(Ljava/lang/String;JJI)Lsun/security/mscapi/CPrivateKey;"); + if (mNewCPrivateKey == NULL) { __leave; } - // Create a new RSA private key - privateKey = env->NewObject(clazzRSAPrivateKey, mNewRSAPrivateKey, - (jlong) hCryptProv, (jlong) hKey, keySize); + // Create a new private key + privateKey = env->CallStaticObjectMethod(clazzCPrivateKey, mNewCPrivateKey, + alg, (jlong) hCryptProv, (jlong) hKey, keySize); } __finally @@ -2165,12 +2176,12 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_KeyStore_storePrivateKey } /* - * Class: sun_security_mscapi_RSASignature + * Class: sun_security_mscapi_CSignature * Method: importPublicKey - * Signature: ([BI)Lsun/security/mscapi/RSAPublicKey; + * Signature: (Ljava/lang/String;[BI)Lsun/security/mscapi/CPublicKey; */ -JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSASignature_importPublicKey - (JNIEnv *env, jclass clazz, jbyteArray keyBlob, jint keySize) +JNIEXPORT jobject JNICALL Java_sun_security_mscapi_CSignature_importPublicKey + (JNIEnv *env, jclass clazz, jstring alg, jbyteArray keyBlob, jint keySize) { HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKey = NULL; @@ -2189,7 +2200,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSASignature_importPublicKey // Acquire a CSP context (create a new key container). // Prefer a PROV_RSA_AES CSP, when available, due to its support // for SHA-2-based signatures. - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, NULL, NULL, @@ -2198,7 +2209,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSASignature_importPublicKey { // Failover to using the default CSP (PROV_RSA_FULL) - if (::CryptAcquireContext( + if (::CryptAcquireContext( //deprecated &hCryptProv, NULL, NULL, @@ -2211,7 +2222,7 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSASignature_importPublicKey } // Import the public key - if (::CryptImportKey( + if (::CryptImportKey( //deprecated hCryptProv, pbKeyBlob, dwBlobLen, @@ -2223,22 +2234,23 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_RSASignature_importPublicKey __leave; } - // Get the method ID for the RSAPublicKey constructor - jclass clazzRSAPublicKey = - env->FindClass("sun/security/mscapi/RSAPublicKey"); - if (clazzRSAPublicKey == NULL) { + // Get the method ID for the CPublicKey constructor + jclass clazzCPublicKey = + env->FindClass("sun/security/mscapi/CPublicKey"); + if (clazzCPublicKey == NULL) { __leave; } - jmethodID mNewRSAPublicKey = - env->GetMethodID(clazzRSAPublicKey, "", "(JJI)V"); - if (mNewRSAPublicKey == NULL) { + jmethodID mNewCPublicKey = + env->GetStaticMethodID(clazzCPublicKey, "of", + "(Ljava/lang/String;JJI)Lsun/security/mscapi/CPublicKey;"); + if (mNewCPublicKey == NULL) { __leave; } - // Create a new RSA public key - publicKey = env->NewObject(clazzRSAPublicKey, mNewRSAPublicKey, - (jlong) hCryptProv, (jlong) hKey, keySize); + // Create a new public key + publicKey = env->CallStaticObjectMethod(clazzCPublicKey, mNewCPublicKey, + alg, (jlong) hCryptProv, (jlong) hKey, keySize); } __finally diff --git a/test/jdk/sun/security/mscapi/KeyAlgorithms.java b/test/jdk/sun/security/mscapi/KeyAlgorithms.java new file mode 100644 index 00000000000..7a41f88d235 --- /dev/null +++ b/test/jdk/sun/security/mscapi/KeyAlgorithms.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8213009 + * @summary Make sure SunMSCAPI keys have correct algorithm names + * @requires os.family == "windows" + * @library /test/lib + * @modules jdk.crypto.mscapi + */ + +import java.security.*; + +import jdk.test.lib.Asserts; +import jdk.test.lib.SecurityTools; + +public class KeyAlgorithms { + + private static final String ALIAS = "8213009"; + private static final String ALG = "RSA"; + + public static void main(String[] arg) throws Exception { + + SecurityTools.keytool("-genkeypair", + "-storetype", "Windows-My", + "-keyalg", ALG, + "-alias", ALIAS, + "-dname", "cn=" + ALIAS, + "-noprompt").shouldHaveExitValue(0); + + try { + test(loadKeysFromKeyStore()); + } finally { + KeyStore ks = KeyStore.getInstance("Windows-MY"); + ks.load(null, null); + ks.deleteEntry(ALIAS); + ks.store(null, null); + } + + test(generateKeys()); + } + + static KeyPair loadKeysFromKeyStore() throws Exception { + KeyStore ks = KeyStore.getInstance("Windows-MY"); + ks.load(null, null); + return new KeyPair(ks.getCertificate(ALIAS).getPublicKey(), + (PrivateKey) ks.getKey(ALIAS, null)); + } + + static KeyPair generateKeys() throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALG, "SunMSCAPI"); + return kpg.generateKeyPair(); + } + + static void test(KeyPair kp) { + Asserts.assertEQ(kp.getPrivate().getAlgorithm(), ALG); + Asserts.assertEQ(kp.getPublic().getAlgorithm(), ALG); + } +} From a438a0766c6933ec4bd6a3cee62ce76c2499cddc Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 13 Dec 2018 17:28:30 +0800 Subject: [PATCH 038/174] 8213010: Supporting keys created with certmgr.exe Reviewed-by: valeriep --- .../classes/sun/security/util/ECUtil.java | 67 ++- .../sun/security/ec/ECDSASignature.java | 79 +-- .../classes/sun/security/mscapi/CKey.java | 51 ++ .../sun/security/mscapi/CKeyStore.java | 6 +- .../sun/security/mscapi/CPublicKey.java | 90 +++- .../sun/security/mscapi/CSignature.java | 135 ++++- .../sun/security/mscapi/SunMSCAPI.java | 31 +- .../windows/native/libsunmscapi/security.cpp | 473 ++++++++++++++---- 8 files changed, 720 insertions(+), 212 deletions(-) diff --git a/src/java.base/share/classes/sun/security/util/ECUtil.java b/src/java.base/share/classes/sun/security/util/ECUtil.java index a58cfc82c00..e8f9cc1efdc 100644 --- a/src/java.base/share/classes/sun/security/util/ECUtil.java +++ b/src/java.base/share/classes/sun/security/util/ECUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,17 +26,11 @@ package sun.security.util; import java.io.IOException; - import java.math.BigInteger; - import java.security.*; - import java.security.interfaces.*; - import java.security.spec.*; - import java.util.Arrays; - import sun.security.x509.X509Key; public class ECUtil { @@ -227,5 +221,64 @@ public class ECUtil { return nameSpec.getName(); } + // Convert the concatenation R and S in into their DER encoding + public static byte[] encodeSignature(byte[] signature) throws SignatureException { + + try { + + int n = signature.length >> 1; + byte[] bytes = new byte[n]; + System.arraycopy(signature, 0, bytes, 0, n); + BigInteger r = new BigInteger(1, bytes); + System.arraycopy(signature, n, bytes, 0, n); + BigInteger s = new BigInteger(1, bytes); + + DerOutputStream out = new DerOutputStream(signature.length + 10); + out.putInteger(r); + out.putInteger(s); + DerValue result = + new DerValue(DerValue.tag_Sequence, out.toByteArray()); + + return result.toByteArray(); + + } catch (Exception e) { + throw new SignatureException("Could not encode signature", e); + } + } + + // Convert the DER encoding of R and S into a concatenation of R and S + public static byte[] decodeSignature(byte[] sig) throws SignatureException { + + try { + // Enforce strict DER checking for signatures + DerInputStream in = new DerInputStream(sig, 0, sig.length, false); + DerValue[] values = in.getSequence(2); + + // check number of components in the read sequence + // and trailing data + if ((values.length != 2) || (in.available() != 0)) { + throw new IOException("Invalid encoding for signature"); + } + + BigInteger r = values[0].getPositiveBigInteger(); + BigInteger s = values[1].getPositiveBigInteger(); + + // trim leading zeroes + byte[] rBytes = trimZeroes(r.toByteArray()); + byte[] sBytes = trimZeroes(s.toByteArray()); + int k = Math.max(rBytes.length, sBytes.length); + // r and s each occupy half the array + byte[] result = new byte[k << 1]; + System.arraycopy(rBytes, 0, result, k - rBytes.length, + rBytes.length); + System.arraycopy(sBytes, 0, result, result.length - sBytes.length, + sBytes.length); + return result; + + } catch (Exception e) { + throw new SignatureException("Invalid encoding for signature", e); + } + } + private ECUtil() {} } diff --git a/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java b/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java index 6070d22c1db..9a7a671b062 100644 --- a/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java +++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java @@ -25,9 +25,7 @@ package sun.security.ec; -import java.io.IOException; import java.nio.ByteBuffer; -import java.math.BigInteger; import java.security.*; import java.security.interfaces.*; @@ -453,7 +451,7 @@ abstract class ECDSASignature extends SignatureSpi { if (p1363Format) { return sig; } else { - return encodeSignature(sig); + return ECUtil.encodeSignature(sig); } } @@ -476,7 +474,7 @@ abstract class ECDSASignature extends SignatureSpi { if (p1363Format) { sig = signature; } else { - sig = decodeSignature(signature); + sig = ECUtil.decodeSignature(signature); } try { @@ -515,79 +513,6 @@ abstract class ECDSASignature extends SignatureSpi { return null; } - // Convert the concatenation of R and S into their DER encoding - private byte[] encodeSignature(byte[] signature) throws SignatureException { - - try { - - int n = signature.length >> 1; - byte[] bytes = new byte[n]; - System.arraycopy(signature, 0, bytes, 0, n); - BigInteger r = new BigInteger(1, bytes); - System.arraycopy(signature, n, bytes, 0, n); - BigInteger s = new BigInteger(1, bytes); - - DerOutputStream out = new DerOutputStream(signature.length + 10); - out.putInteger(r); - out.putInteger(s); - DerValue result = - new DerValue(DerValue.tag_Sequence, out.toByteArray()); - - return result.toByteArray(); - - } catch (Exception e) { - throw new SignatureException("Could not encode signature", e); - } - } - - // Convert the DER encoding of R and S into a concatenation of R and S - private byte[] decodeSignature(byte[] sig) throws SignatureException { - - try { - // Enforce strict DER checking for signatures - DerInputStream in = new DerInputStream(sig, 0, sig.length, false); - DerValue[] values = in.getSequence(2); - - // check number of components in the read sequence - // and trailing data - if ((values.length != 2) || (in.available() != 0)) { - throw new IOException("Invalid encoding for signature"); - } - - BigInteger r = values[0].getPositiveBigInteger(); - BigInteger s = values[1].getPositiveBigInteger(); - - // trim leading zeroes - byte[] rBytes = trimZeroes(r.toByteArray()); - byte[] sBytes = trimZeroes(s.toByteArray()); - int k = Math.max(rBytes.length, sBytes.length); - // r and s each occupy half the array - byte[] result = new byte[k << 1]; - System.arraycopy(rBytes, 0, result, k - rBytes.length, - rBytes.length); - System.arraycopy(sBytes, 0, result, result.length - sBytes.length, - sBytes.length); - return result; - - } catch (Exception e) { - throw new SignatureException("Invalid encoding for signature", e); - } - } - - // trim leading (most significant) zeroes from the result - private static byte[] trimZeroes(byte[] b) { - int i = 0; - while ((i < b.length - 1) && (b[i] == 0)) { - i++; - } - if (i == 0) { - return b; - } - byte[] t = new byte[b.length - i]; - System.arraycopy(b, i, t, 0, t.length); - return t; - } - /** * Signs the digest using the private key. * diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java index 865652e8950..f52075e9341 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKey.java @@ -25,9 +25,13 @@ package sun.security.mscapi; +import sun.security.util.KeyUtil; import sun.security.util.Length; +import java.math.BigInteger; import java.security.Key; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; /** * The handle for a key using the Microsoft Crypto API. @@ -100,4 +104,51 @@ abstract class CKey implements Key, Length { protected native static String getContainerName(long hCryptProv); protected native static String getKeyType(long hCryptKey); + + // This java method generates EC BLOBs for public key or private key. + // See https://docs.microsoft.com/en-us/windows/desktop/api/bcrypt/ns-bcrypt-_bcrypt_ecckey_blob + static byte[] generateECBlob(Key k) { + + int keyBitLength = KeyUtil.getKeySize(k); + int keyLen = (keyBitLength + 7) / 8; + boolean isPrivate = k instanceof ECPrivateKey; + + byte[] keyBlob = new byte[8 + keyLen * (isPrivate ? 3 : 2)]; + keyBlob[0] = 'E'; + keyBlob[1] = 'C'; + keyBlob[2] = 'S'; + if (isPrivate) { + keyBlob[3] = (byte) (keyBitLength == 256 ? '2' + : (keyBitLength == 384 ? '4' : '6')); + } else { + keyBlob[3] = (byte) (keyBitLength == 256 ? '1' + : (keyBitLength == 384 ? '3' : '5')); + } + BigInteger x; + BigInteger y; + // Fill the array in reverse order (s -> y -> x -> len) in case + // one BigInteger encoding has an extra 0 at the beginning + if (isPrivate) { + // We can keep X and Y zero and it still works + ECPrivateKey prk = (ECPrivateKey)k; + BigInteger s = prk.getS(); + byte[] bs = s.toByteArray(); + System.arraycopy( + bs, 0, + keyBlob, 8 + keyLen + keyLen + keyLen - bs.length, + bs.length); + } else { + ECPublicKey puk = (ECPublicKey)k; + x = puk.getW().getAffineX(); + y = puk.getW().getAffineY(); + byte[] by = y.toByteArray(); + System.arraycopy(by, 0, keyBlob, 8 + keyLen + keyLen - by.length, + by.length); + byte[] bx = x.toByteArray(); + System.arraycopy(bx, 0, keyBlob, 8 + keyLen - bx.length, bx.length); + } + keyBlob[4] = (byte) keyLen; + keyBlob[5] = keyBlob[6] = keyBlob[7] = 0; + return keyBlob; + } } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java index 5adaf676c85..912bc19d306 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java @@ -759,12 +759,12 @@ abstract class CKeyStore extends KeyStoreSpi { } /** - * Generates RSA key and certificate chain from the private key handle, + * Generates key and certificate chain from the private key handle, * collection of certificates and stores the result into key entries. *

    * This method is called by native codes in security.cpp. */ - private void generateRSAKeyAndCertificateChain(String alias, + private void generateKeyAndCertificateChain(boolean isRSA, String alias, long hCryptProv, long hCryptKey, int keyLength, Collection certCollection) { try { @@ -777,7 +777,7 @@ abstract class CKeyStore extends KeyStoreSpi { certChain[i] = (X509Certificate) iter.next(); } storeWithUniqueAlias(alias, new KeyEntry(alias, - CPrivateKey.of("RSA", hCryptProv, hCryptKey, keyLength), + CPrivateKey.of(isRSA ? "RSA" : "EC", hCryptProv, hCryptKey, keyLength), certChain)); } catch (Throwable e) { // Ignore the exception and skip this entry diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java index 5421e790e7b..9d95534a25b 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CPublicKey.java @@ -26,14 +26,22 @@ package sun.security.mscapi; import java.math.BigInteger; +import java.security.AlgorithmParameters; import java.security.KeyException; +import java.security.KeyFactory; import java.security.KeyRep; import java.security.ProviderException; import java.security.PublicKey; +import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.util.Arrays; import sun.security.rsa.RSAUtil.KeyType; import sun.security.rsa.RSAPublicKeyImpl; +import sun.security.util.ECKeySizeParameterSpec; /** * The handle for an RSA public key using the Microsoft Crypto API. @@ -44,9 +52,69 @@ public abstract class CPublicKey extends CKey implements PublicKey { private static final long serialVersionUID = -2289561342425825391L; - protected byte[] publicKeyBlob = null; protected byte[] encoding = null; + public static class CECPublicKey extends CPublicKey implements ECPublicKey { + + private ECPoint w = null; + private static final long serialVersionUID = 12L; + + CECPublicKey(long hCryptProv, int keyLength) { + super("EC", hCryptProv, 0, keyLength); + } + + @Override + public ECPoint getW() { + if (w == null) { + // See CKey::generateECBlob. + try { + byte[] blob = getPublicKeyBlob( + handles.hCryptProv, handles.hCryptKey); + int len = blob[8] & 0xff; + byte[] x = Arrays.copyOfRange(blob, 8, 8 + len); + byte[] y = Arrays.copyOfRange(blob, 8 + len, 8 + len + len); + w = new ECPoint(new BigInteger(1, x), new BigInteger(1, y)); + } catch (KeyException e) { + throw new ProviderException(e); + } + } + return w; + } + + @Override + public byte[] getEncoded() { + if (encoding == null) { + try { + encoding = KeyFactory.getInstance("EC").generatePublic( + new ECPublicKeySpec(getW(), getParams())) + .getEncoded(); + } catch (Exception e) { + // ignore + } + } + return encoding; + } + + @Override + public ECParameterSpec getParams() { + try { + AlgorithmParameters ap = AlgorithmParameters.getInstance("EC"); + ap.init(new ECKeySizeParameterSpec(keyLength)); + return ap.getParameterSpec(ECParameterSpec.class); + } catch (Exception e) { + throw new ProviderException(e); + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(algorithm + "PublicKey [size=").append(keyLength) + .append("]\n ECPoint: ").append(getW()) + .append("\n params: ").append(getParams()); + return sb.toString(); + } + } + public static class CRSAPublicKey extends CPublicKey implements RSAPublicKey { private BigInteger modulus = null; @@ -71,7 +139,8 @@ public abstract class CPublicKey extends CKey implements PublicKey { public BigInteger getPublicExponent() { if (exponent == null) { try { - publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); + byte[] publicKeyBlob = getPublicKeyBlob( + handles.hCryptProv, handles.hCryptKey); exponent = new BigInteger(1, getExponent(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); @@ -84,7 +153,8 @@ public abstract class CPublicKey extends CKey implements PublicKey { public BigInteger getModulus() { if (modulus == null) { try { - publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); + byte[] publicKeyBlob = getPublicKeyBlob( + handles.hCryptProv, handles.hCryptKey); modulus = new BigInteger(1, getModulus(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); @@ -111,16 +181,20 @@ public abstract class CPublicKey extends CKey implements PublicKey { private native byte[] getModulus(byte[] keyBlob) throws KeyException; } - public static CPublicKey of(String alg, long hCryptProv, long hCryptKey, int keyLength) { + public static CPublicKey of( + String alg, long hCryptProv, long hCryptKey, int keyLength) { switch (alg) { case "RSA": return new CRSAPublicKey(hCryptProv, hCryptKey, keyLength); + case "EC": + return new CECPublicKey(hCryptProv, keyLength); default: throw new AssertionError("Unsupported algorithm: " + alg); } } - protected CPublicKey(String alg, long hCryptProv, long hCryptKey, int keyLength) { + protected CPublicKey( + String alg, long hCryptProv, long hCryptKey, int keyLength) { super(alg, hCryptProv, hCryptKey, keyLength); } @@ -136,7 +210,7 @@ public abstract class CPublicKey extends CKey implements PublicKey { getEncoded()); } - // Returns the Microsoft CryptoAPI representation of the key. - native byte[] getPublicKeyBlob(long hCryptKey) throws KeyException; - + // Returns the CAPI or CNG representation of the key. + native byte[] getPublicKeyBlob(long hCryptProv, long hCryptKey) + throws KeyException; } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java index ca165b356c2..3db91b5a2ee 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CSignature.java @@ -27,6 +27,7 @@ package sun.security.mscapi; import java.nio.ByteBuffer; import java.security.*; +import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.math.BigInteger; @@ -35,10 +36,11 @@ import java.security.spec.PSSParameterSpec; import java.util.Locale; import sun.security.rsa.RSAKeyFactory; +import sun.security.util.ECUtil; +import sun.security.util.KeyUtil; /** - * Signature implementation. Supports RSA signing using PKCS#1 v1.5 padding - * and RSASSA-PSS signing. + * Signature implementation. * * Objects should be instantiated by calling Signature.getInstance() using the * following algorithm names: @@ -51,6 +53,11 @@ import sun.security.rsa.RSAKeyFactory; * . "MD5withRSA" * . "MD2withRSA" * . "RSASSA-PSS" + * . "SHA1withECDSA" + * . "SHA224withECDSA" + * . "SHA256withECDSA" + * . "SHA384withECDSA" + * . "SHA512withECDSA" * * NOTE: RSA keys must be at least 512 bits long. * @@ -112,7 +119,8 @@ abstract class CSignature extends SignatureSpi { @Override protected void engineInitSign(PrivateKey key) throws InvalidKeyException { - if ((key instanceof CPrivateKey) == false) { + if ((key instanceof CPrivateKey) == false + || !key.getAlgorithm().equalsIgnoreCase("RSA")) { throw new InvalidKeyException("Key type not supported"); } privateKey = (CPrivateKey) key; @@ -197,7 +205,6 @@ abstract class CSignature extends SignatureSpi { boolean noHashOID = this instanceof NONEwithRSA; // Sign hash using MS Crypto APIs - byte[] result = signHash(noHashOID, hash, hash.length, messageDigestAlgorithm, privateKey.getHCryptProvider(), privateKey.getHCryptKey()); @@ -364,6 +371,106 @@ abstract class CSignature extends SignatureSpi { } } + public static final class SHA1withECDSA extends ECDSA { + public SHA1withECDSA() { + super("SHA-1"); + } + } + + public static final class SHA224withECDSA extends ECDSA { + public SHA224withECDSA() { + super("SHA-224"); + } + } + + public static final class SHA256withECDSA extends ECDSA { + public SHA256withECDSA() { + super("SHA-256"); + } + } + + public static final class SHA384withECDSA extends ECDSA { + public SHA384withECDSA() { + super("SHA-384"); + } + } + + public static final class SHA512withECDSA extends ECDSA { + public SHA512withECDSA() { + super("SHA-512"); + } + } + + static class ECDSA extends CSignature { + + public ECDSA(String messageDigestAlgorithm) { + super("EC", messageDigestAlgorithm); + } + + // initialize for signing. See JCA doc + @Override + protected void engineInitSign(PrivateKey key) throws InvalidKeyException { + if ((key instanceof CPrivateKey) == false + || !key.getAlgorithm().equalsIgnoreCase("EC")) { + throw new InvalidKeyException("Key type not supported"); + } + privateKey = (CPrivateKey) key; + + this.publicKey = null; + resetDigest(); + } + + // initialize for signing. See JCA doc + @Override + protected void engineInitVerify(PublicKey key) throws InvalidKeyException { + // This signature accepts only ECPublicKey + if ((key instanceof ECPublicKey) == false) { + throw new InvalidKeyException("Key type not supported"); + } + + + if ((key instanceof CPublicKey) == false) { + try { + publicKey = importECPublicKey("EC", + CKey.generateECBlob(key), + KeyUtil.getKeySize(key)); + } catch (KeyStoreException e) { + throw new InvalidKeyException(e); + } + } else { + publicKey = (CPublicKey) key; + } + + this.privateKey = null; + resetDigest(); + } + + @Override + protected byte[] engineSign() throws SignatureException { + byte[] hash = getDigestValue(); + byte[] raw = signCngHash(0, hash, hash.length, + 0, + null, + privateKey.getHCryptProvider(), 0); + return ECUtil.encodeSignature(raw); + } + + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + byte[] hash = getDigestValue(); + sigBytes = ECUtil.decodeSignature(sigBytes); + return verifyCngSignedHash( + 0, + hash, hash.length, + sigBytes, sigBytes.length, + 0, + null, + publicKey.getHCryptProvider(), + 0 + ); + } + } + public static final class PSS extends RSA { private PSSParameterSpec pssParams = null; @@ -463,7 +570,7 @@ abstract class CSignature extends SignatureSpi { protected byte[] engineSign() throws SignatureException { ensureInit(); byte[] hash = getDigestValue(); - return signCngHash(hash, hash.length, + return signCngHash(2, hash, hash.length, pssParams.getSaltLength(), ((MGF1ParameterSpec) pssParams.getMGFParameters()).getDigestAlgorithm(), @@ -479,7 +586,7 @@ abstract class CSignature extends SignatureSpi { } else { byte[] hash = getDigestValue(); return verifyCngSignedHash( - hash, hash.length, + 2, hash, hash.length, sigBytes, sigBytes.length, pssParams.getSaltLength(), ((MGF1ParameterSpec) @@ -599,19 +706,22 @@ abstract class CSignature extends SignatureSpi { } /** - * Sign hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. + * Sign hash using CNG API with HCRYPTKEY. + * @param type 0 no padding, 1, pkcs1, 2, pss */ native static byte[] signCngHash( - byte[] hash, int hashSize, int saltLength, String hashAlgorithm, + int type, byte[] hash, + int hashSize, int saltLength, String hashAlgorithm, long hCryptProv, long nCryptKey) throws SignatureException; /** - * Verify a signed hash using CNG API with HCRYPTKEY. Used by RSASSA-PSS. - * This method is not used now. See {@link PSS#fallbackSignature}. + * Verify a signed hash using CNG API with HCRYPTKEY. + * @param type 0 no padding, 1, pkcs1, 2, pss */ private native static boolean verifyCngSignedHash( - byte[] hash, int hashSize, byte[] signature, int signatureSize, + int type, byte[] hash, int hashSize, + byte[] signature, int signatureSize, int saltLength, String hashAlgorithm, long hCryptProv, long hKey) throws SignatureException; @@ -804,4 +914,7 @@ abstract class CSignature extends SignatureSpi { // used by CRSACipher static native CPublicKey importPublicKey( String alg, byte[] keyBlob, int keySize) throws KeyStoreException; + + static native CPublicKey importECPublicKey( + String alg, byte[] keyBlob, int keySize) throws KeyStoreException; } diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java index 9fcebc4466c..4351d3105aa 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java @@ -106,6 +106,16 @@ public final class SunMSCAPI extends Provider { return new CSignature.MD2withRSA(); } else if (algo.equals("RSASSA-PSS")) { return new CSignature.PSS(); + } else if (algo.equals("SHA1withECDSA")) { + return new CSignature.SHA1withECDSA(); + } else if (algo.equals("SHA224withECDSA")) { + return new CSignature.SHA224withECDSA(); + } else if (algo.equals("SHA256withECDSA")) { + return new CSignature.SHA256withECDSA(); + } else if (algo.equals("SHA384withECDSA")) { + return new CSignature.SHA384withECDSA(); + } else if (algo.equals("SHA512withECDSA")) { + return new CSignature.SHA512withECDSA(); } } else if (type.equals("KeyPairGenerator")) { if (algo.equals("RSA")) { @@ -188,7 +198,26 @@ public final class SunMSCAPI extends Provider { putService(new ProviderService(p, "Signature", "MD2withRSA", "sun.security.mscapi.CSignature$MD2withRSA", null, attrs)); - + putService(new ProviderService(p, "Signature", + "SHA1withECDSA", "sun.security.mscapi.CSignature$SHA1withECDSA", + new String[] { "1.2.840.10045.4.1", "OID.1.2.840.10045.4.1" }, + attrs)); + putService(new ProviderService(p, "Signature", + "SHA224withECDSA", "sun.security.mscapi.CSignature$SHA224withECDSA", + new String[] { "1.2.840.10045.4.3.1", "OID.1.2.840.10045.4.3.1"}, + attrs)); + putService(new ProviderService(p, "Signature", + "SHA256withECDSA", "sun.security.mscapi.CSignature$SHA256withECDSA", + new String[] { "1.2.840.10045.4.3.2", "OID.1.2.840.10045.4.3.2"}, + attrs)); + putService(new ProviderService(p, "Signature", + "SHA384withECDSA", "sun.security.mscapi.CSignature$SHA384withECDSA", + new String[] { "1.2.840.10045.4.3.3", "OID.1.2.840.10045.4.3.3"}, + attrs)); + putService(new ProviderService(p, "Signature", + "SHA512withECDSA", "sun.security.mscapi.CSignature$SHA512withECDSA", + new String[] { "1.2.840.10045.4.3.4", "OID.1.2.840.10045.4.3.4"}, + attrs)); /* * Key Pair Generator engines */ diff --git a/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp b/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp index afff2277e5e..cf5b1a06eba 100644 --- a/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp +++ b/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp @@ -65,44 +65,53 @@ __leave; \ } -//#define PP(fmt, ...) \ -// fprintf(stdout, "MSCAPI (%ld): ", __LINE__); \ -// fprintf(stdout, fmt, ##__VA_ARGS__); \ -// fprintf(stdout, "\n"); \ -// fflush(stdout) +#define PP(fmt, ...) \ + if (trace) { \ + fprintf(stdout, "MSCAPI (%ld): ", __LINE__); \ + fprintf(stdout, fmt, ##__VA_ARGS__); \ + fprintf(stdout, "\n"); \ + fflush(stdout); \ + } extern "C" { +char* trace = getenv("CAPI_TRACE"); + /* * Declare library specific JNI_Onload entry if static build */ DEF_STATIC_JNI_OnLoad -//void dump(LPSTR title, PBYTE data, DWORD len) -//{ -// printf("==== %s ====\n", title); -// for (DWORD i = 0; i < len; i+=16) { -// printf("%04x: ", i); -// for (int j = 0; j < 16; j++) { -// if (j == 8) { -// printf(" "); -// } -// if (i + j < len) { -// printf("%02X ", *(data + i + j) & 0xff); -// } else { -// printf(" "); -// } -// } -// for (int j = 0; j < 16; j++) { -// if (i + j < len) { -// int k = *(data + i + j) & 0xff; -// if (k < 32 || k > 127) printf("."); -// else printf("%c", (char)k); -// } -// } -// printf("\n"); -// } -//} +void showProperty(NCRYPT_HANDLE hKey); + +void dump(LPSTR title, PBYTE data, DWORD len) +{ + if (trace) { + printf("==== %s ====\n", title); + for (DWORD i = 0; i < len; i+=16) { + printf("%04x: ", i); + for (int j = 0; j < 16; j++) { + if (j == 8) { + printf(" "); + } + if (i + j < len) { + printf("%02X ", *(data + i + j) & 0xff); + } else { + printf(" "); + } + } + for (int j = 0; j < 16; j++) { + if (i + j < len) { + int k = *(data + i + j) & 0xff; + if (k < 32 || k > 127) printf("."); + else printf("%c", (char)k); + } + } + printf("\n"); + } + fflush(stdout); + } +} /* * Throws an arbitrary Java exception with the given message. @@ -445,10 +454,10 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC } // Determine method ID to generate RSA certificate chain - jmethodID mGenRSAKeyAndCertChain = env->GetMethodID(clazzOfThis, - "generateRSAKeyAndCertificateChain", - "(Ljava/lang/String;JJILjava/util/Collection;)V"); - if (mGenRSAKeyAndCertChain == NULL) { + jmethodID mGenKeyAndCertChain = env->GetMethodID(clazzOfThis, + "generateKeyAndCertificateChain", + "(ZLjava/lang/String;JJILjava/util/Collection;)V"); + if (mGenKeyAndCertChain == NULL) { __leave; } @@ -457,6 +466,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC // NULL to retrieve the first certificate in the store. while (pCertContext = ::CertEnumCertificatesInStore(hCertStore, pCertContext)) { + PP("--------------------------"); // Check if private key available - client authentication certificate // must have private key available. HCRYPTPROV hCryptProv = NULL; @@ -467,10 +477,12 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC DWORD dwPublicKeyLength = 0; // First, probe it silently - if (::CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_SILENT_FLAG, NULL, + if (::CryptAcquireCertificatePrivateKey(pCertContext, + CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG | CRYPT_ACQUIRE_SILENT_FLAG, NULL, &hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE && GetLastError() != NTE_SILENT_CONTEXT) { + PP("bHasNoPrivateKey = TRUE!"); bHasNoPrivateKey = TRUE; } else @@ -481,27 +493,32 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC } // Second, acquire the key normally (not silently) - if (::CryptAcquireCertificatePrivateKey(pCertContext, 0, NULL, + if (::CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, NULL, &hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE) { + PP("bHasNoPrivateKey = TRUE!!"); bHasNoPrivateKey = TRUE; } else { - // Private key is available - BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); //deprecated + if ((dwKeySpec & CERT_NCRYPT_KEY_SPEC) == CERT_NCRYPT_KEY_SPEC) { + PP("CNG %I64d", hCryptProv); + } else { + // Private key is available + BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); //deprecated - // Skip certificate if cannot find private key - if (bGetUserKey == FALSE) { - if (bCallerFreeProv) - ::CryptReleaseContext(hCryptProv, NULL); // deprecated - continue; + // Skip certificate if cannot find private key + if (bGetUserKey == FALSE) { + if (bCallerFreeProv) + ::CryptReleaseContext(hCryptProv, NULL); // deprecated + continue; + } + + // Set cipher mode to ECB + DWORD dwCipherMode = CRYPT_MODE_ECB; + ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); //deprecated + PP("CAPI %I64d %I64d", hCryptProv, hUserKey); } - - // Set cipher mode to ECB - DWORD dwCipherMode = CRYPT_MODE_ECB; - ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); //deprecated - // If the private key is present in smart card, we may not be able to // determine the key length by using the private key handle. However, // since public/private key pairs must have the same length, we could @@ -573,6 +590,7 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC env->CallVoidMethod(obj, mGenCert, byteArray, jArrayList); } + PP("%s: %s", pszNameString, pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId); if (bHasNoPrivateKey) { // Generate certificate chain and store into cert chain @@ -583,19 +601,40 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC } else { - // Determine key type: RSA or DSA - DWORD dwData = CALG_RSA_KEYX; - DWORD dwSize = sizeof(DWORD); - ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, //deprecated - &dwSize, NULL); - if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA) - { - // Generate RSA certificate chain and store into cert - // chain collection - env->CallVoidMethod(obj, mGenRSAKeyAndCertChain, - env->NewStringUTF(pszNameString), - (jlong) hCryptProv, (jlong) hUserKey, - dwPublicKeyLength, jArrayList); + if (hUserKey) { + // Only accept RSA for CAPI + DWORD dwData = CALG_RSA_KEYX; + DWORD dwSize = sizeof(DWORD); + ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, //deprecated + &dwSize, NULL); + if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA) + { + // Generate RSA certificate chain and store into cert + // chain collection + env->CallVoidMethod(obj, mGenKeyAndCertChain, + 1, + env->NewStringUTF(pszNameString), + (jlong) hCryptProv, (jlong) hUserKey, + dwPublicKeyLength, jArrayList); + } + } else { + // Only accept EC for CNG + BYTE buffer[32]; + DWORD len = 0; + if (::NCryptGetProperty( + hCryptProv, NCRYPT_ALGORITHM_PROPERTY, + (PBYTE)buffer, 32, &len, NCRYPT_SILENT_FLAG) == ERROR_SUCCESS) { + if (buffer[0] == 'E' && buffer[2] == 'C' + && (dwPublicKeyLength == 256 + || dwPublicKeyLength == 384 + || dwPublicKeyLength == 521)) { + env->CallVoidMethod(obj, mGenKeyAndCertChain, + 0, + env->NewStringUTF(pszNameString), + (jlong) hCryptProv, 0, + dwPublicKeyLength, jArrayList); + } + } } } } @@ -603,6 +642,8 @@ JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateC // Free cert chain if (pCertChainContext) ::CertFreeCertificateChain(pCertChainContext); + } else { + PP("GetCertificateChain failed %d", GetLastError()); } } } @@ -768,10 +809,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signHash /* * Class: sun_security_mscapi_CSignature * Method: signCngHash - * Signature: ([BIILjava/lang/String;JJ)[B + * Signature: (I[BIILjava/lang/String;JJ)[B */ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash - (JNIEnv *env, jclass clazz, jbyteArray jHash, + (JNIEnv *env, jclass clazz, jint type, jbyteArray jHash, jint jHashSize, jint saltLen, jstring jHashAlgorithm, jlong hCryptProv, jlong hCryptKey) { @@ -783,13 +824,17 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash __try { - SS_CHECK(::NCryptTranslateHandle( + if (hCryptKey == 0) { + hk = (NCRYPT_KEY_HANDLE)hCryptProv; + } else { + SS_CHECK(::NCryptTranslateHandle( NULL, &hk, hCryptProv, hCryptKey, NULL, 0)); + } // Copy hash from Java to native buffer pHashBuffer = new (env) jbyte[jHashSize]; @@ -798,43 +843,66 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash } env->GetByteArrayRegion(jHash, 0, jHashSize, pHashBuffer); - BCRYPT_PSS_PADDING_INFO pssInfo; - pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); - pssInfo.cbSalt = saltLen; + VOID* param; + DWORD dwFlags; - if (pssInfo.pszAlgId == NULL) { - ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, - "Unrecognised hash algorithm"); - __leave; + switch (type) { + case 0: + param = NULL; + dwFlags = 0; + break; + case 1: + BCRYPT_PKCS1_PADDING_INFO pkcs1Info; + pkcs1Info.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); + if (pkcs1Info.pszAlgId == NULL) { + ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, + "Unrecognised hash algorithm"); + __leave; + } + param = &pkcs1Info; + dwFlags = BCRYPT_PAD_PKCS1; + break; + case 2: + BCRYPT_PSS_PADDING_INFO pssInfo; + pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); + pssInfo.cbSalt = saltLen; + if (pssInfo.pszAlgId == NULL) { + ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, + "Unrecognised hash algorithm"); + __leave; + } + param = &pssInfo; + dwFlags = BCRYPT_PAD_PSS; + break; } - DWORD dwBufLen = 0; + DWORD jSignedHashSize = 0; SS_CHECK(::NCryptSignHash( hk, - &pssInfo, + param, (BYTE*)pHashBuffer, jHashSize, - NULL, 0, &dwBufLen, - BCRYPT_PAD_PSS + NULL, 0, &jSignedHashSize, + dwFlags )); - pSignedHashBuffer = new (env) jbyte[dwBufLen]; + pSignedHashBuffer = new (env) jbyte[jSignedHashSize]; if (pSignedHashBuffer == NULL) { __leave; } SS_CHECK(::NCryptSignHash( hk, - &pssInfo, + param, (BYTE*)pHashBuffer, jHashSize, - (BYTE*)pSignedHashBuffer, dwBufLen, &dwBufLen, - BCRYPT_PAD_PSS + (BYTE*)pSignedHashBuffer, jSignedHashSize, &jSignedHashSize, + dwFlags )); // Create new byte array - jbyteArray temp = env->NewByteArray(dwBufLen); + jbyteArray temp = env->NewByteArray(jSignedHashSize); // Copy data from native buffer - env->SetByteArrayRegion(temp, 0, dwBufLen, pSignedHashBuffer); + env->SetByteArrayRegion(temp, 0, jSignedHashSize, pSignedHashBuffer); jSignedHash = temp; } @@ -846,7 +914,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash if (pHashBuffer) delete [] pHashBuffer; - if (hk != NULL) + if (hCryptKey != 0 && hk != NULL) ::NCryptFreeObject(hk); } @@ -961,10 +1029,10 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifySignedHash /* * Class: sun_security_mscapi_CSignature * Method: verifyCngSignedHash - * Signature: ([BI[BIILjava/lang/String;JJ)Z + * Signature: (I[BI[BIILjava/lang/String;JJ)Z */ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifyCngSignedHash - (JNIEnv *env, jclass clazz, + (JNIEnv *env, jclass clazz, jint type, jbyteArray jHash, jint jHashSize, jbyteArray jSignedHash, jint jSignedHashSize, jint saltLen, jstring jHashAlgorithm, @@ -977,13 +1045,17 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifyCngSignedHa __try { - SS_CHECK(::NCryptTranslateHandle( + if (hCryptKey == 0) { + hk = (NCRYPT_KEY_HANDLE)hCryptProv; + } else { + SS_CHECK(::NCryptTranslateHandle( NULL, &hk, hCryptProv, hCryptKey, NULL, 0)); + } // Copy hash and signedHash from Java to native buffer pHashBuffer = new (env) jbyte[jHashSize]; @@ -999,19 +1071,43 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifyCngSignedHa env->GetByteArrayRegion(jSignedHash, 0, jSignedHashSize, pSignedHashBuffer); - BCRYPT_PSS_PADDING_INFO pssInfo; - pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); - pssInfo.cbSalt = saltLen; - if (pssInfo.pszAlgId == NULL) { - ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, - "Unrecognised hash algorithm"); - __leave; + VOID* param; + DWORD dwFlags; + + switch (type) { + case 0: + param = NULL; + dwFlags = 0; + break; + case 1: + BCRYPT_PKCS1_PADDING_INFO pkcs1Info; + pkcs1Info.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); + if (pkcs1Info.pszAlgId == NULL) { + ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, + "Unrecognised hash algorithm"); + __leave; + } + param = &pkcs1Info; + dwFlags = NCRYPT_PAD_PKCS1_FLAG; + break; + case 2: + BCRYPT_PSS_PADDING_INFO pssInfo; + pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm); + pssInfo.cbSalt = saltLen; + if (pssInfo.pszAlgId == NULL) { + ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION, + "Unrecognised hash algorithm"); + __leave; + } + param = &pssInfo; + dwFlags = NCRYPT_PAD_PSS_FLAG; + break; } - if (::NCryptVerifySignature(hk, &pssInfo, + if (::NCryptVerifySignature(hk, param, (BYTE *) pHashBuffer, jHashSize, (BYTE *) pSignedHashBuffer, jSignedHashSize, - NCRYPT_PAD_PSS_FLAG) == ERROR_SUCCESS) + dwFlags) == ERROR_SUCCESS) { result = JNI_TRUE; } @@ -1025,13 +1121,108 @@ JNIEXPORT jboolean JNICALL Java_sun_security_mscapi_CSignature_verifyCngSignedHa if (pHashBuffer) delete [] pHashBuffer; - if (hk != NULL) + if (hCryptKey != 0 && hk != NULL) ::NCryptFreeObject(hk); } return result; } +#define DUMP_PROP(p) \ + if (::NCryptGetProperty(hKey, p, (PBYTE)buffer, 8192, &len, NCRYPT_SILENT_FLAG) == ERROR_SUCCESS) { \ + sprintf(header, "%s %ls", #p, p); \ + dump(header, buffer, len); \ + } + +#define EXPORT_BLOB(p) \ + desc.cBuffers = 0; \ + if (::NCryptExportKey(hKey, NULL, p, &desc, (PBYTE)buffer, 8192, &len, NCRYPT_SILENT_FLAG) == ERROR_SUCCESS) { \ + sprintf(header, "%s %ls (%ld)", #p, p, desc.cBuffers); \ + dump(header, buffer, len); \ + for (int i = 0; i < (int)desc.cBuffers; i++) { \ + sprintf(header, "desc %ld", desc.pBuffers[i].BufferType); \ + dump(header, (PBYTE)desc.pBuffers[i].pvBuffer, desc.pBuffers[i].cbBuffer); \ + } \ + } + +void showProperty(NCRYPT_HANDLE hKey) { + char header[100]; + BYTE buffer[8192]; + DWORD len = 9; + NCryptBufferDesc desc; + DUMP_PROP(NCRYPT_ALGORITHM_GROUP_PROPERTY); + DUMP_PROP(NCRYPT_ALGORITHM_PROPERTY); + DUMP_PROP(NCRYPT_ASSOCIATED_ECDH_KEY); + DUMP_PROP(NCRYPT_BLOCK_LENGTH_PROPERTY); + DUMP_PROP(NCRYPT_CERTIFICATE_PROPERTY); + DUMP_PROP(NCRYPT_DH_PARAMETERS_PROPERTY); + DUMP_PROP(NCRYPT_EXPORT_POLICY_PROPERTY); + DUMP_PROP(NCRYPT_IMPL_TYPE_PROPERTY); + DUMP_PROP(NCRYPT_KEY_TYPE_PROPERTY); + DUMP_PROP(NCRYPT_KEY_USAGE_PROPERTY); + DUMP_PROP(NCRYPT_LAST_MODIFIED_PROPERTY); + DUMP_PROP(NCRYPT_LENGTH_PROPERTY); + DUMP_PROP(NCRYPT_LENGTHS_PROPERTY); + DUMP_PROP(NCRYPT_MAX_NAME_LENGTH_PROPERTY); + DUMP_PROP(NCRYPT_NAME_PROPERTY); + DUMP_PROP(NCRYPT_PIN_PROMPT_PROPERTY); + DUMP_PROP(NCRYPT_PIN_PROPERTY); + DUMP_PROP(NCRYPT_PROVIDER_HANDLE_PROPERTY); + DUMP_PROP(NCRYPT_READER_PROPERTY); + DUMP_PROP(NCRYPT_ROOT_CERTSTORE_PROPERTY); + DUMP_PROP(NCRYPT_SCARD_PIN_ID); + DUMP_PROP(NCRYPT_SCARD_PIN_INFO); + DUMP_PROP(NCRYPT_SECURE_PIN_PROPERTY); + DUMP_PROP(NCRYPT_SECURITY_DESCR_PROPERTY); + DUMP_PROP(NCRYPT_SECURITY_DESCR_SUPPORT_PROPERTY); + DUMP_PROP(NCRYPT_SMARTCARD_GUID_PROPERTY); + DUMP_PROP(NCRYPT_UI_POLICY_PROPERTY); + DUMP_PROP(NCRYPT_UNIQUE_NAME_PROPERTY); + DUMP_PROP(NCRYPT_USE_CONTEXT_PROPERTY); + DUMP_PROP(NCRYPT_USE_COUNT_ENABLED_PROPERTY); + DUMP_PROP(NCRYPT_USE_COUNT_PROPERTY); + DUMP_PROP(NCRYPT_USER_CERTSTORE_PROPERTY); + DUMP_PROP(NCRYPT_VERSION_PROPERTY); + DUMP_PROP(NCRYPT_WINDOW_HANDLE_PROPERTY); + + EXPORT_BLOB(BCRYPT_DH_PRIVATE_BLOB); + EXPORT_BLOB(BCRYPT_DH_PUBLIC_BLOB); + EXPORT_BLOB(BCRYPT_DSA_PRIVATE_BLOB); + EXPORT_BLOB(BCRYPT_DSA_PUBLIC_BLOB); + EXPORT_BLOB(BCRYPT_ECCPRIVATE_BLOB); + EXPORT_BLOB(BCRYPT_ECCPUBLIC_BLOB); + EXPORT_BLOB(BCRYPT_PUBLIC_KEY_BLOB); + EXPORT_BLOB(BCRYPT_PRIVATE_KEY_BLOB); + EXPORT_BLOB(BCRYPT_RSAFULLPRIVATE_BLOB); + EXPORT_BLOB(BCRYPT_RSAPRIVATE_BLOB); + EXPORT_BLOB(BCRYPT_RSAPUBLIC_BLOB); + EXPORT_BLOB(LEGACY_DH_PRIVATE_BLOB); + EXPORT_BLOB(LEGACY_DH_PUBLIC_BLOB); + EXPORT_BLOB(LEGACY_DSA_PRIVATE_BLOB); + EXPORT_BLOB(LEGACY_DSA_PUBLIC_BLOB); + EXPORT_BLOB(LEGACY_RSAPRIVATE_BLOB); + EXPORT_BLOB(LEGACY_RSAPUBLIC_BLOB); + EXPORT_BLOB(NCRYPT_CIPHER_KEY_BLOB); + EXPORT_BLOB(NCRYPT_OPAQUETRANSPORT_BLOB); + EXPORT_BLOB(NCRYPT_PKCS7_ENVELOPE_BLOB); + //EXPORT_BLOB(NCRYPTBUFFER_CERT_BLOB); + //EXPORT_BLOB(NCRYPT_PKCS8_PRIVATE_KEY_BLOB); + BCryptBuffer bb; + bb.BufferType = NCRYPTBUFFER_PKCS_SECRET; + bb.cbBuffer = 18; + bb.pvBuffer = L"changeit"; + BCryptBufferDesc bbd; + bbd.ulVersion = 0; + bbd.cBuffers = 1; + bbd.pBuffers = &bb; + if(::NCryptExportKey(hKey, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL, + (PBYTE)buffer, 8192, &len, NCRYPT_SILENT_FLAG) == ERROR_SUCCESS) { + sprintf(header, "NCRYPT_PKCS8_PRIVATE_KEY_BLOB %ls", NCRYPT_PKCS8_PRIVATE_KEY_BLOB); + dump(header, buffer, len); + } + EXPORT_BLOB(NCRYPT_PROTECTED_KEY_BLOB); +} + /* * Class: sun_security_mscapi_CKeyPairGenerator_RSA * Method: generateCKeyPair @@ -1673,10 +1864,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CRSACipher_encryptDecrypt /* * Class: sun_security_mscapi_CPublicKey * Method: getPublicKeyBlob - * Signature: (J)[B + * Signature: (JJ)[B */ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_getPublicKeyBlob - (JNIEnv *env, jobject clazz, jlong hCryptKey) { + (JNIEnv *env, jobject clazz, jlong hCryptProv, jlong hCryptKey) { jbyteArray blob = NULL; DWORD dwBlobLen; @@ -1686,11 +1877,17 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_getPublicKeyBlo { // Determine the size of the blob - if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, NULL, //deprecated - &dwBlobLen)) { + if (hCryptKey == 0) { + SS_CHECK(::NCryptExportKey( + hCryptProv, NULL, BCRYPT_ECCPUBLIC_BLOB, + NULL, NULL, 0, &dwBlobLen, NCRYPT_SILENT_FLAG)); + } else { + if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, NULL, //deprecated + &dwBlobLen)) { - ThrowException(env, KEY_EXCEPTION, GetLastError()); - __leave; + ThrowException(env, KEY_EXCEPTION, GetLastError()); + __leave; + } } pbKeyBlob = new (env) BYTE[dwBlobLen]; @@ -1699,11 +1896,17 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CPublicKey_getPublicKeyBlo } // Generate key blob - if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, //deprecated - pbKeyBlob, &dwBlobLen)) { + if (hCryptKey == 0) { + SS_CHECK(::NCryptExportKey( + hCryptProv, NULL, BCRYPT_ECCPUBLIC_BLOB, + NULL, pbKeyBlob, dwBlobLen, &dwBlobLen, NCRYPT_SILENT_FLAG)); + } else { + if (! ::CryptExportKey((HCRYPTKEY) hCryptKey, 0, PUBLICKEYBLOB, 0, //deprecated + pbKeyBlob, &dwBlobLen)) { - ThrowException(env, KEY_EXCEPTION, GetLastError()); - __leave; + ThrowException(env, KEY_EXCEPTION, GetLastError()); + __leave; + } } // Create new byte array @@ -2175,6 +2378,66 @@ JNIEXPORT jobject JNICALL Java_sun_security_mscapi_CKeyStore_storePrivateKey return privateKey; } +/* + * Class: sun_security_mscapi_CSignature + * Method: importECPublicKey + * Signature: (Ljava/lang/String;[BI)Lsun/security/mscapi/CPublicKey; + */ +JNIEXPORT jobject JNICALL Java_sun_security_mscapi_CSignature_importECPublicKey + (JNIEnv *env, jclass clazz, jstring alg, jbyteArray keyBlob, jint keySize) +{ + BCRYPT_ALG_HANDLE hSignAlg = NULL; + NCRYPT_KEY_HANDLE hTmpKey = NULL; + DWORD dwBlobLen; + BYTE * pbKeyBlob = NULL; + jobject publicKey = NULL; + + __try + { + dwBlobLen = env->GetArrayLength(keyBlob); + if ((pbKeyBlob = (BYTE *) env->GetByteArrayElements(keyBlob, 0)) + == NULL) { + __leave; + } + dump("NCryptImportKey", pbKeyBlob, dwBlobLen); + NCRYPT_PROV_HANDLE hProv; + SS_CHECK(NCryptOpenStorageProvider( + &hProv, L"Microsoft Software Key Storage Provider", 0 )); + SS_CHECK(NCryptImportKey( + hProv, + NULL, + BCRYPT_ECCPUBLIC_BLOB, + NULL, + &hTmpKey, + pbKeyBlob, + dwBlobLen, + 0)); + NCryptFreeObject( hProv ); + // Get the method ID for the CPublicKey constructor + jclass clazzCPublicKey = + env->FindClass("sun/security/mscapi/CPublicKey"); + if (clazzCPublicKey == NULL) { + __leave; + } + + jmethodID mNewCPublicKey = + env->GetStaticMethodID(clazzCPublicKey, "of", + "(Ljava/lang/String;JJI)Lsun/security/mscapi/CPublicKey;"); + if (mNewCPublicKey == NULL) { + __leave; + } + + // Create a new public key + publicKey = env->CallStaticObjectMethod(clazzCPublicKey, mNewCPublicKey, + alg, (jlong) hTmpKey, (jlong) 0, keySize); + } + __finally + { + } + + return publicKey; +} + /* * Class: sun_security_mscapi_CSignature * Method: importPublicKey From 9048045d20228043307dff5cb608304bfe8d2043 Mon Sep 17 00:00:00 2001 From: David Griffiths Date: Thu, 13 Dec 2018 15:11:25 +0530 Subject: [PATCH 039/174] 8214226: Incorrect BCI and Line Number with jstack if the top frame is in the interpreter Read in the bcp from r13 for the top level interpreter frames Reviewed-by: jcbeyler, jgeorge --- .../LinuxAMD64JavaThreadPDAccess.java | 6 +- .../sun/jvm/hotspot/runtime/x86/X86Frame.java | 58 ++++++++++++------- 2 files changed, 43 insertions(+), 21 deletions(-) diff --git a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/linux_amd64/LinuxAMD64JavaThreadPDAccess.java b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/linux_amd64/LinuxAMD64JavaThreadPDAccess.java index 89fcb12b1a6..c097c078a25 100644 --- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/linux_amd64/LinuxAMD64JavaThreadPDAccess.java +++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/linux_amd64/LinuxAMD64JavaThreadPDAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,6 +97,10 @@ public class LinuxAMD64JavaThreadPDAccess implements JavaThreadPDAccess { } if (guesser.getPC() == null) { return new X86Frame(guesser.getSP(), guesser.getFP()); + } else if (VM.getVM().getInterpreter().contains(guesser.getPC())) { + // pass the value of R13 which contains the bcp for the top level frame + Address bcp = context.getRegisterAsAddress(AMD64ThreadContext.R13); + return new X86Frame(guesser.getSP(), guesser.getFP(), guesser.getPC(), null, bcp); } else { return new X86Frame(guesser.getSP(), guesser.getFP(), guesser.getPC()); } diff --git a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java index 65488fe96c6..3b3aa92beea 100644 --- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java +++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -95,6 +95,7 @@ public class X86Frame extends Frame { // an additional field beyond sp and pc: Address raw_fp; // frame pointer private Address raw_unextendedSP; + private Address live_bcp; private X86Frame() { } @@ -117,15 +118,29 @@ public class X86Frame extends Frame { } } - public X86Frame(Address raw_sp, Address raw_fp, Address pc) { + private void initFrame(Address raw_sp, Address raw_fp, Address pc, Address raw_unextendedSp, Address live_bcp) { this.raw_sp = raw_sp; - this.raw_unextendedSP = raw_sp; this.raw_fp = raw_fp; - this.pc = pc; + if (raw_unextendedSp == null) { + this.raw_unextendedSP = raw_sp; + } else { + this.raw_unextendedSP = raw_unextendedSp; + } + if (pc == null) { + this.pc = raw_sp.getAddressAt(-1 * VM.getVM().getAddressSize()); + } else { + this.pc = pc; + } + this.live_bcp = live_bcp; adjustUnextendedSP(); // Frame must be fully constructed before this call adjustForDeopt(); +} + + + public X86Frame(Address raw_sp, Address raw_fp, Address pc) { + initFrame(raw_sp, raw_fp, pc, null, null); if (DEBUG) { System.out.println("X86Frame(sp, fp, pc): " + this); @@ -134,14 +149,7 @@ public class X86Frame extends Frame { } public X86Frame(Address raw_sp, Address raw_fp) { - this.raw_sp = raw_sp; - this.raw_unextendedSP = raw_sp; - this.raw_fp = raw_fp; - this.pc = raw_sp.getAddressAt(-1 * VM.getVM().getAddressSize()); - adjustUnextendedSP(); - - // Frame must be fully constructed before this call - adjustForDeopt(); + initFrame(raw_sp, raw_fp, null, null, null); if (DEBUG) { System.out.println("X86Frame(sp, fp): " + this); @@ -150,20 +158,21 @@ public class X86Frame extends Frame { } public X86Frame(Address raw_sp, Address raw_unextendedSp, Address raw_fp, Address pc) { - this.raw_sp = raw_sp; - this.raw_unextendedSP = raw_unextendedSp; - this.raw_fp = raw_fp; - this.pc = pc; - adjustUnextendedSP(); - - // Frame must be fully constructed before this call - adjustForDeopt(); + initFrame(raw_sp, raw_fp, pc, raw_unextendedSp, null); if (DEBUG) { System.out.println("X86Frame(sp, unextendedSP, fp, pc): " + this); dumpStack(); } + } + public X86Frame(Address raw_sp, Address raw_fp, Address pc, Address raw_unextendedSp, Address live_bcp) { + initFrame(raw_sp, raw_fp, pc, raw_unextendedSp, live_bcp); + + if (DEBUG) { + System.out.println("X86Frame(sp, fp, pc, unextendedSP, live_bcp): " + this); + dumpStack(); + } } public Object clone() { @@ -173,6 +182,7 @@ public class X86Frame extends Frame { frame.raw_fp = raw_fp; frame.pc = pc; frame.deoptimized = deoptimized; + frame.live_bcp = live_bcp; return frame; } @@ -433,6 +443,14 @@ public class X86Frame extends Frame { // for use in a non-debugging, or reflective, system. Need to // figure out how to express this. Address bcp = addressOfInterpreterFrameBCX().getAddressAt(0); + + // If we are in the top level frame then the bcp may have been set for us. If so then let it + // take priority. If we are in a top level interpreter frame, the bcp is live in R13 (on x86) + // and not saved in the BCX stack slot. + if (live_bcp != null) { + bcp = live_bcp; + } + Address methodHandle = addressOfInterpreterFrameMethod().getAddressAt(0); Method method = (Method)Metadata.instantiateWrapperFor(methodHandle); return bcpToBci(bcp, method); From 0bdabe5e084dd94910446fb521c74d8ab709e38c Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Thu, 13 Dec 2018 11:27:37 +0000 Subject: [PATCH 040/174] 8211093: Default logging.properties sets log level for com.xyz.foo Reviewed-by: bpb, rriggs --- .../share/conf/logging.properties | 2 +- .../java/util/logging/DefaultConfigTest.java | 107 ++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 test/jdk/java/util/logging/DefaultConfigTest.java diff --git a/src/java.logging/share/conf/logging.properties b/src/java.logging/share/conf/logging.properties index 58997e5ff2f..5694bc084b5 100644 --- a/src/java.logging/share/conf/logging.properties +++ b/src/java.logging/share/conf/logging.properties @@ -60,4 +60,4 @@ java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter # For example, set the com.xyz.foo logger to only log SEVERE # messages: -com.xyz.foo.level = SEVERE +# com.xyz.foo.level = SEVERE diff --git a/test/jdk/java/util/logging/DefaultConfigTest.java b/test/jdk/java/util/logging/DefaultConfigTest.java new file mode 100644 index 00000000000..d2b4931908a --- /dev/null +++ b/test/jdk/java/util/logging/DefaultConfigTest.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8211093 + * @summary Check default configuration + * @build DefaultConfigTest + * @run main/othervm DefaultConfigTest + */ + +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +public class DefaultConfigTest { + static final java.io.PrintStream out = System.out; + public static void main(String arg[]) { + LogManager manager = LogManager.getLogManager(); + + if (!Set.of(Collections.list(manager.getLoggerNames()).toArray()) + .equals(Set.of("", "global"))) { + throw new RuntimeException("Unexpected logger name in: " + + Collections.list(manager.getLoggerNames())); + } + Logger global = Logger.getGlobal(); + Logger root = Logger.getLogger(""); + Logger foo = Logger.getLogger("com.xyz.foo"); + if (!Set.of(Collections.list(manager.getLoggerNames()).toArray()) + .equals(Set.of("", "global", "com.xyz.foo"))) { + throw new RuntimeException("Unexpected logger name in: " + + Collections.list(manager.getLoggerNames())); + } + for (Logger l : List.of(global, foo)) { + if (l.getLevel() != null) { + throw new RuntimeException("Unexpected level " + + l.getLevel() + " for " + l.getName()); + } + if (l.getHandlers().length != 0) { + throw new RuntimeException("Unexpected handlers " + + List.of(l.getHandlers()) + " for " + l.getName()); + } + for (Level level : List.of( + Level.ALL, Level.FINEST, Level.FINER, Level.FINE, Level.CONFIG)) { + if (l.isLoggable(level)) { + throw new RuntimeException("Level " + + level + " should not be loggable for " + l.getName()); + } + } + for (Level level : List.of( + Level.INFO, Level.WARNING, Level.SEVERE)) { + if (!l.isLoggable(level)) { + throw new RuntimeException("Level " + + level + " should be loggable for " + l.getName()); + } + } + } + if (root.getLevel() != Level.INFO) { + throw new RuntimeException("Unexpected level " + + root.getLevel() + " for root logger"); + } + if (root.getHandlers().length != 1) { + throw new RuntimeException("Unexpected handlers " + + List.of(root.getHandlers()) + " for root logger"); + } + if (root.getHandlers()[0].getClass() != ConsoleHandler.class) { + throw new RuntimeException("Unexpected handlers " + + List.of(root.getHandlers()) + " for root logger"); + } + if (root.getHandlers()[0].getLevel() != Level.INFO) { + throw new RuntimeException("Unexpected level " + + root.getHandlers()[0].getLevel() + " for handler " + + root.getHandlers()[0]); + } + out.println(List.of(root, global, foo).stream() + .map(Logger::getName) + .map(s -> String.format("\"%s\"", s)) + .collect(Collectors.joining(", ", + "Default configuration checked for ", + "."))); + } +} From 905d607b35c49538999032dc5635b51b21dc0aa7 Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Thu, 13 Dec 2018 08:36:10 +0100 Subject: [PATCH 041/174] 8215534: [testbug] some jfr test don't check @requires vm.hasJFR Reviewed-by: sundar, egahlin --- .../event/security/TestSecurityPropertyModificationEvent.java | 1 + test/jdk/jdk/jfr/event/security/TestTLSHandshakeEvent.java | 1 + test/jdk/jdk/jfr/event/security/TestX509CertificateEvent.java | 1 + test/jdk/jdk/jfr/event/security/TestX509ValidationEvent.java | 1 + 4 files changed, 4 insertions(+) diff --git a/test/jdk/jdk/jfr/event/security/TestSecurityPropertyModificationEvent.java b/test/jdk/jdk/jfr/event/security/TestSecurityPropertyModificationEvent.java index 0c5ec973824..ba1f3c9ed28 100644 --- a/test/jdk/jdk/jfr/event/security/TestSecurityPropertyModificationEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestSecurityPropertyModificationEvent.java @@ -38,6 +38,7 @@ import jdk.test.lib.security.JDKSecurityProperties; * @bug 8148188 * @summary Enhance the security libraries to record events of interest * @key jfr + * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.event.security.TestSecurityPropertyModificationEvent */ diff --git a/test/jdk/jdk/jfr/event/security/TestTLSHandshakeEvent.java b/test/jdk/jdk/jfr/event/security/TestTLSHandshakeEvent.java index cb42f20137d..4565e553362 100644 --- a/test/jdk/jdk/jfr/event/security/TestTLSHandshakeEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestTLSHandshakeEvent.java @@ -36,6 +36,7 @@ import jdk.test.lib.security.TestTLSHandshake; * @bug 8148188 * @summary Enhance the security libraries to record events of interest * @key jfr + * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.event.security.TestTLSHandshakeEvent */ diff --git a/test/jdk/jdk/jfr/event/security/TestX509CertificateEvent.java b/test/jdk/jdk/jfr/event/security/TestX509CertificateEvent.java index f8a56efd9f6..7d771d5ab2d 100644 --- a/test/jdk/jdk/jfr/event/security/TestX509CertificateEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestX509CertificateEvent.java @@ -38,6 +38,7 @@ import jdk.test.lib.security.TestCertificate; * @bug 8148188 * @summary Enhance the security libraries to record events of interest * @key jfr + * @requires vm.hasJFR * @library /test/lib * @run main/othervm jdk.jfr.event.security.TestX509CertificateEvent */ diff --git a/test/jdk/jdk/jfr/event/security/TestX509ValidationEvent.java b/test/jdk/jdk/jfr/event/security/TestX509ValidationEvent.java index a4e815b0bfa..14fbca926b8 100644 --- a/test/jdk/jdk/jfr/event/security/TestX509ValidationEvent.java +++ b/test/jdk/jdk/jfr/event/security/TestX509ValidationEvent.java @@ -40,6 +40,7 @@ import jdk.test.lib.security.TestCertificate; * @bug 8148188 * @summary Enhance the security libraries to record events of interest * @key jfr + * @requires vm.hasJFR * @library /test/lib * @modules jdk.jfr/jdk.jfr.events * @run main/othervm jdk.jfr.event.security.TestX509ValidationEvent From d51be0e1b362db6a55b0bf3516283bc701ade8af Mon Sep 17 00:00:00 2001 From: Michihiro Horie Date: Wed, 12 Dec 2018 12:36:53 -0500 Subject: [PATCH 042/174] 8215262: PPC64: FMA Vectorization on PPC64 Reviewed-by: mdoerr, gromero --- src/hotspot/cpu/ppc/assembler_ppc.hpp | 12 +++ src/hotspot/cpu/ppc/assembler_ppc.inline.hpp | 6 ++ src/hotspot/cpu/ppc/ppc.ad | 89 ++++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/src/hotspot/cpu/ppc/assembler_ppc.hpp b/src/hotspot/cpu/ppc/assembler_ppc.hpp index 9e5ed32b382..efad021b0ce 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.hpp @@ -539,6 +539,12 @@ class Assembler : public AbstractAssembler { XVSUBDP_OPCODE = (60u << OPCODE_SHIFT | 104u << 3), XVMULSP_OPCODE = (60u << OPCODE_SHIFT | 80u << 3), XVMULDP_OPCODE = (60u << OPCODE_SHIFT | 112u << 3), + XVMADDASP_OPCODE=(60u << OPCODE_SHIFT | 65u << 3), + XVMADDADP_OPCODE=(60u << OPCODE_SHIFT | 97u << 3), + XVMSUBASP_OPCODE=(60u << OPCODE_SHIFT | 81u << 3), + XVMSUBADP_OPCODE=(60u << OPCODE_SHIFT | 113u << 3), + XVNMSUBASP_OPCODE=(60u<< OPCODE_SHIFT | 209u << 3), + XVNMSUBADP_OPCODE=(60u<< OPCODE_SHIFT | 241u << 3), // Deliver A Random Number (introduced with POWER9) DARN_OPCODE = (31u << OPCODE_SHIFT | 755u << 1), @@ -2227,6 +2233,12 @@ class Assembler : public AbstractAssembler { inline void xvsubdp( VectorSRegister d, VectorSRegister a, VectorSRegister b); inline void xvmulsp( VectorSRegister d, VectorSRegister a, VectorSRegister b); inline void xvmuldp( VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvmaddasp(VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvmaddadp(VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvmsubasp(VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvmsubadp(VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvnmsubasp(VectorSRegister d, VectorSRegister a, VectorSRegister b); + inline void xvnmsubadp(VectorSRegister d, VectorSRegister a, VectorSRegister b); // VSX Extended Mnemonics inline void xxspltd( VectorSRegister d, VectorSRegister a, int x); diff --git a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp index 1159a219bf1..b8c912e7105 100644 --- a/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp +++ b/src/hotspot/cpu/ppc/assembler_ppc.inline.hpp @@ -790,6 +790,12 @@ inline void Assembler::xvadddp( VectorSRegister d, VectorSRegister a, VectorSReg inline void Assembler::xvsubdp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVSUBDP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } inline void Assembler::xvmulsp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMULSP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } inline void Assembler::xvmuldp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMULDP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvmaddasp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMADDASP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvmaddadp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMADDADP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvmsubasp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMSUBASP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvmsubadp( VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVMSUBADP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvnmsubasp(VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVNMSUBASP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } +inline void Assembler::xvnmsubadp(VectorSRegister d, VectorSRegister a, VectorSRegister b) { emit_int32( XVNMSUBADP_OPCODE | vsrt(d) | vsra(a) | vsrb(b)); } inline void Assembler::mtvrd( VectorRegister d, Register a) { emit_int32( MTVSRD_OPCODE | vsrt(d->to_vsr()) | ra(a)); } inline void Assembler::mfvrd( Register a, VectorRegister d) { emit_int32( MFVSRD_OPCODE | vsrt(d->to_vsr()) | ra(a)); } inline void Assembler::mtvrwz( VectorRegister d, Register a) { emit_int32( MTVSRWZ_OPCODE | vsrt(d->to_vsr()) | ra(a)); } diff --git a/src/hotspot/cpu/ppc/ppc.ad b/src/hotspot/cpu/ppc/ppc.ad index 40f8c4b223a..f9cc2c59fb0 100644 --- a/src/hotspot/cpu/ppc/ppc.ad +++ b/src/hotspot/cpu/ppc/ppc.ad @@ -2257,6 +2257,9 @@ const bool Matcher::match_rule_supported(int opcode) { return SuperwordUseVSX; case Op_PopCountVI: return (SuperwordUseVSX && UsePopCountInstruction); + case Op_FmaVF: + case Op_FmaVD: + return (SuperwordUseVSX && UseFMA); case Op_Digit: case Op_LowerCase: case Op_UpperCase: @@ -14475,6 +14478,92 @@ instruct vpopcnt4I_reg(vecX dst, vecX src) %{ ins_pipe(pipe_class_default); %} +// --------------------------------- FMA -------------------------------------- +// dst + src1 * src2 +instruct vfma4F(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVF dst (Binary src1 src2))); + predicate(n->as_Vector()->length() == 4); + + format %{ "XVMADDASP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvmaddasp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} + +// dst - src1 * src2 +instruct vfma4F_neg1(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVF dst (Binary (NegVF src1) src2))); + match(Set dst (FmaVF dst (Binary src1 (NegVF src2)))); + predicate(n->as_Vector()->length() == 4); + + format %{ "XVNMSUBASP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvnmsubasp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} + +// - dst + src1 * src2 +instruct vfma4F_neg2(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVF (NegVF dst) (Binary src1 src2))); + predicate(n->as_Vector()->length() == 4); + + format %{ "XVMSUBASP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvmsubasp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} + +// dst + src1 * src2 +instruct vfma2D(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVD dst (Binary src1 src2))); + predicate(n->as_Vector()->length() == 2); + + format %{ "XVMADDADP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvmaddadp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} + +// dst - src1 * src2 +instruct vfma2D_neg1(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVD dst (Binary (NegVD src1) src2))); + match(Set dst (FmaVD dst (Binary src1 (NegVD src2)))); + predicate(n->as_Vector()->length() == 2); + + format %{ "XVNMSUBADP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvnmsubadp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} + +// - dst + src1 * src2 +instruct vfma2D_neg2(vecX dst, vecX src1, vecX src2) %{ + match(Set dst (FmaVD (NegVD dst) (Binary src1 src2))); + predicate(n->as_Vector()->length() == 2); + + format %{ "XVMSUBADP $dst, $src1, $src2" %} + + size(4); + ins_encode %{ + __ xvmsubadp($dst$$VectorSRegister, $src1$$VectorSRegister, $src2$$VectorSRegister); + %} + ins_pipe(pipe_class_default); +%} //----------Overflow Math Instructions----------------------------------------- From 169729fe9bfe1828def21eb710392db7610e187a Mon Sep 17 00:00:00 2001 From: Christophe Phillips Date: Thu, 13 Dec 2018 10:25:50 +0100 Subject: [PATCH 043/174] 8215342: [Zero] Build fails after JDK-8200613 Reviewed-by: shade, jgeorge --- src/hotspot/os/linux/os_linux.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/hotspot/os/linux/os_linux.cpp b/src/hotspot/os/linux/os_linux.cpp index 0afbf692a17..b5fdbafaa2a 100644 --- a/src/hotspot/os/linux/os_linux.cpp +++ b/src/hotspot/os/linux/os_linux.cpp @@ -1354,9 +1354,11 @@ void os::shutdown() { void os::abort(bool dump_core, void* siginfo, const void* context) { os::shutdown(); if (dump_core) { +#if INCLUDE_CDS if (UseSharedSpaces && DumpPrivateMappingsInCore) { ClassLoader::close_jrt_image(); } +#endif #ifndef PRODUCT fdStream out(defaultStream::output_fd()); out.print_raw("Current thread is "); @@ -5075,9 +5077,11 @@ jint os::init_2(void) { set_coredump_filter(DAX_SHARED_BIT); } +#if INCLUDE_CDS if (UseSharedSpaces && DumpPrivateMappingsInCore) { set_coredump_filter(FILE_BACKED_PVT_BIT); } +#endif return JNI_OK; } From a3ca6f482ec94bb68bfec2193e6e0bdf53bf8193 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Thu, 13 Dec 2018 14:21:04 +0100 Subject: [PATCH 044/174] 8215175: Inconsistencies in JFR event metadata Reviewed-by: mgronlun --- .../jfr/leakprofiler/emitEventOperation.cpp | 2 +- src/hotspot/share/jfr/metadata/metadata.xml | 54 ++++---- src/hotspot/share/jfr/metadata/metadata.xsd | 3 +- .../jfr/periodic/jfrNetworkUtilization.cpp | 4 +- .../jdk/jfr/internal/MetadataHandler.java | 32 ++++- .../jdk/jfr/internal/PlatformRecording.java | 2 +- .../share/classes/jdk/jfr/internal/Utils.java | 55 ++++++-- .../jdk/jfr/internal/dcmd/AbstractDCmd.java | 6 +- .../jdk/jfr/internal/dcmd/DCmdCheck.java | 3 +- .../jdk/jfr/internal/dcmd/DCmdConfigure.java | 8 +- .../jdk/jfr/internal/tool/PrettyWriter.java | 44 ++++-- .../annotations/TestFormatMissingValue.java | 125 ++++++++++++++++++ 12 files changed, 271 insertions(+), 67 deletions(-) create mode 100644 test/jdk/jdk/jfr/api/metadata/annotations/TestFormatMissingValue.java diff --git a/src/hotspot/share/jfr/leakprofiler/emitEventOperation.cpp b/src/hotspot/share/jfr/leakprofiler/emitEventOperation.cpp index bc00c0af064..89aa10d2779 100644 --- a/src/hotspot/share/jfr/leakprofiler/emitEventOperation.cpp +++ b/src/hotspot/share/jfr/leakprofiler/emitEventOperation.cpp @@ -185,7 +185,7 @@ static int array_size(const oop object) { if (object->is_array()) { return arrayOop(object)->length(); } - return -1; + return min_jint; } void EmitEventOperation::write_event(const ObjectSample* sample, EdgeStore* edge_store) { diff --git a/src/hotspot/share/jfr/metadata/metadata.xml b/src/hotspot/share/jfr/metadata/metadata.xml index 83bb36c8037..b590b9b9679 100644 --- a/src/hotspot/share/jfr/metadata/metadata.xml +++ b/src/hotspot/share/jfr/metadata/metadata.xml @@ -65,19 +65,19 @@ - - - @@ -350,7 +350,7 @@ - + @@ -362,7 +362,7 @@ - + @@ -564,9 +564,9 @@ relation="SafepointId" /> - - + - @@ -647,8 +647,8 @@ - - + + @@ -663,13 +663,13 @@ - + - - + + @@ -687,7 +687,7 @@ - + @@ -741,8 +741,7 @@ + description="Module to which the package is qualifiedly exported. If null or N/A, the package is unqualifiedly exported" /> @@ -1096,7 +1095,7 @@ - + @@ -1134,13 +1133,16 @@ - - - - - - - - - + + + + + + + + + + + + diff --git a/src/hotspot/share/jfr/metadata/metadata.xsd b/src/hotspot/share/jfr/metadata/metadata.xsd index aad3ec4cbbc..4bcb9675354 100644 --- a/src/hotspot/share/jfr/metadata/metadata.xsd +++ b/src/hotspot/share/jfr/metadata/metadata.xsd @@ -107,8 +107,7 @@ - - + diff --git a/src/hotspot/share/jfr/periodic/jfrNetworkUtilization.cpp b/src/hotspot/share/jfr/periodic/jfrNetworkUtilization.cpp index 073b78fc0da..9958818061d 100644 --- a/src/hotspot/share/jfr/periodic/jfrNetworkUtilization.cpp +++ b/src/hotspot/share/jfr/periodic/jfrNetworkUtilization.cpp @@ -174,8 +174,8 @@ void JfrNetworkUtilization::send_events() { event.set_starttime(cur_time); event.set_endtime(cur_time); event.set_networkInterface(entry.id); - event.set_readRate(read_rate); - event.set_writeRate(write_rate); + event.set_readRate(8 * read_rate); + event.set_writeRate(8 * write_rate); event.commit(); } // update existing entry with new values diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataHandler.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataHandler.java index c5387f04e1c..831b4444c6d 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataHandler.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataHandler.java @@ -100,7 +100,7 @@ final class MetadataHandler extends DefaultHandler implements EntityResolver { final Map types = new LinkedHashMap<>(200); final Map xmlTypes = new HashMap<>(20); - final Map xmlContentTypes = new HashMap<>(20); + final Map> xmlContentTypes = new HashMap<>(20); final List relations = new ArrayList<>(); long eventTypeId = 255; long structTypeId = 33; @@ -148,11 +148,8 @@ final class MetadataHandler extends DefaultHandler implements EntityResolver { break; case "XmlContentType": String name = attributes.getValue("name"); - String type = attributes.getValue("annotationType"); - String value = attributes.getValue("annotationValue"); - Class annotationType = createAnnotationClass(type); - AnnotationElement ae = value == null ? new AnnotationElement(annotationType) : new AnnotationElement(annotationType, value); - xmlContentTypes.put(name, ae); + String annotation = attributes.getValue("annotation"); + xmlContentTypes.put(name, createAnnotationElements(annotation)); break; case "Relation": String n = attributes.getValue("name"); @@ -161,6 +158,27 @@ final class MetadataHandler extends DefaultHandler implements EntityResolver { } } + private List createAnnotationElements(String annotation) throws InternalError { + String[] annotations = annotation.split(","); + List annotationElements = new ArrayList<>(); + for (String a : annotations) { + a = a.trim(); + int leftParenthesis = a.indexOf("("); + if (leftParenthesis == -1) { + annotationElements.add(new AnnotationElement(createAnnotationClass(a))); + } else { + int rightParenthesis = a.lastIndexOf(")"); + if (rightParenthesis == -1) { + throw new InternalError("Expected closing parenthesis for 'XMLContentType'"); + } + String value = a.substring(leftParenthesis + 1, rightParenthesis); + String type = a.substring(0, leftParenthesis); + annotationElements.add(new AnnotationElement(createAnnotationClass(type), value)); + } + } + return annotationElements; + } + @SuppressWarnings("unchecked") private Class createAnnotationClass(String type) { try { @@ -255,7 +273,7 @@ final class MetadataHandler extends DefaultHandler implements EntityResolver { aes.add(new AnnotationElement(Unsigned.class)); } if (f.contentType != null) { - aes.add(Objects.requireNonNull(xmlContentTypes.get(f.contentType))); + aes.addAll(Objects.requireNonNull(xmlContentTypes.get(f.contentType))); } if (f.relation != null) { aes.add(Objects.requireNonNull(relationMap.get(f.relation))); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecording.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecording.java index 80d88bdd7f4..74707121d37 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecording.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecording.java @@ -123,7 +123,7 @@ public final class PlatformRecording implements AutoCloseable { options.add("maxage=" + Utils.formatTimespan(maxAge, "")); } if (maxSize != 0) { - options.add("maxsize=" + Utils.formatBytes(maxSize, "")); + options.add("maxsize=" + Utils.formatBytesCompact(maxSize)); } if (dumpOnExit) { options.add("dumponexit=true"); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java index ff148497d42..997b4bdb2a4 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java @@ -103,18 +103,53 @@ public final class Utils { } } - public static String formatBytes(long bytes, String separation) { - if (bytes == 1) { - return "1 byte"; - } - if (bytes < 1024) { - return bytes + " bytes"; - } - int exp = (int) (Math.log(bytes) / Math.log(1024)); - char bytePrefix = "kMGTPE".charAt(exp - 1); - return String.format("%.1f%s%cB", bytes / Math.pow(1024, exp), separation, bytePrefix); + // Tjis method can't handle Long.MIN_VALUE because absolute value is negative + private static String formatDataAmount(String formatter, long amount) { + int exp = (int) (Math.log(Math.abs(amount)) / Math.log(1024)); + char unitPrefix = "kMGTPE".charAt(exp - 1); + return String.format(formatter, amount / Math.pow(1024, exp), unitPrefix); } + public static String formatBytesCompact(long bytes) { + if (bytes < 1024) { + return String.valueOf(bytes); + } + return formatDataAmount("%.1f%cB", bytes); + } + + public static String formatBits(long bits) { + if (bits == 1 || bits == -1) { + return bits + " bit"; + } + if (bits < 1024 && bits > -1024) { + return bits + " bits"; + } + return formatDataAmount("%.1f %cbit", bits); + } + + public static String formatBytes(long bytes) { + if (bytes == 1 || bytes == -1) { + return bytes + " byte"; + } + if (bytes < 1024 && bytes > -1024) { + return bytes + " bytes"; + } + return formatDataAmount("%.1f %cB", bytes); + } + + public static String formatBytesPerSecond(long bytes) { + if (bytes < 1024 && bytes > -1024) { + return bytes + " byte/s"; + } + return formatDataAmount("%.1f %cB/s", bytes); + } + + public static String formatBitsPerSecond(long bits) { + if (bits < 1024 && bits > -1024) { + return bits + " bps"; + } + return formatDataAmount("%.1f %cbps", bits); + } public static String formatTimespan(Duration dValue, String separation) { if (dValue == null) { return "0"; diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/AbstractDCmd.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/AbstractDCmd.java index 15549c400b6..030a97a1bea 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/AbstractDCmd.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/AbstractDCmd.java @@ -109,7 +109,7 @@ abstract class AbstractDCmd { try { print(" "); long bytes = SecuritySupport.getFileSize(file); - printBytes(bytes, " "); + printBytes(bytes); } catch (IOException e) { // Ignore, not essential } @@ -152,8 +152,8 @@ abstract class AbstractDCmd { println(); } - protected final void printBytes(long bytes, String separation) { - print(Utils.formatBytes(bytes, separation)); + protected final void printBytes(long bytes) { + print(Utils.formatBytes(bytes)); } protected final void printTimespan(Duration timespan, String separator) { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdCheck.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdCheck.java index 7204ec12223..0cffba6a67b 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdCheck.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdCheck.java @@ -39,6 +39,7 @@ import jdk.jfr.SettingDescriptor; import jdk.jfr.internal.LogLevel; import jdk.jfr.internal.LogTag; import jdk.jfr.internal.Logger; +import jdk.jfr.internal.Utils; /** * JFR.check - invoked from native @@ -117,7 +118,7 @@ final class DCmdCheck extends AbstractDCmd { long maxSize = recording.getMaxSize(); if (maxSize != 0) { print(" maxsize="); - printBytes(maxSize, ""); + print(Utils.formatBytesCompact(maxSize)); } Duration maxAge = recording.getMaxAge(); if (maxAge != null) { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdConfigure.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdConfigure.java index 87b300219dd..f15053a7caa 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdConfigure.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdConfigure.java @@ -193,25 +193,25 @@ final class DCmdConfigure extends AbstractDCmd { private void printGlobalBufferSize() { print("Global buffer size: "); - printBytes(Options.getGlobalBufferSize(), " "); + printBytes(Options.getGlobalBufferSize()); println(); } private void printThreadBufferSize() { print("Thread buffer size: "); - printBytes(Options.getThreadBufferSize(), " "); + printBytes(Options.getThreadBufferSize()); println(); } private void printMemorySize() { print("Memory size: "); - printBytes(Options.getMemorySize(), " "); + printBytes(Options.getMemorySize()); println(); } private void printMaxChunkSize() { print("Max chunk size: "); - printBytes(Options.getMaxChunkSize(), " "); + printBytes(Options.getMaxChunkSize()); println(); } } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java index eb5260449c0..b07c5a0054e 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/PrettyWriter.java @@ -315,11 +315,7 @@ public final class PrettyWriter extends EventPrintWriter { printArray((Object[]) value); return; } - if (field.getContentType() != null) { - if (printFormatted(field, value)) { - return; - } - } + if (value instanceof Double) { Double d = (Double) value; if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY) { @@ -349,6 +345,12 @@ public final class PrettyWriter extends EventPrintWriter { } } + if (field.getContentType() != null) { + if (printFormatted(field, value)) { + return; + } + } + String text = String.valueOf(value); if (value instanceof String) { text = "\"" + text + "\""; @@ -472,7 +474,7 @@ public final class PrettyWriter extends EventPrintWriter { private boolean printFormatted(ValueDescriptor field, Object value) { if (value instanceof Duration) { Duration d = (Duration) value; - if (d.getSeconds() == Long.MIN_VALUE) { + if (d.getSeconds() == Long.MIN_VALUE && d.getNano() == 0) { println("N/A"); return true; } @@ -513,12 +515,26 @@ public final class PrettyWriter extends EventPrintWriter { if (dataAmount != null) { if (value instanceof Number) { Number n = (Number) value; - String bytes = Utils.formatBytes(n.longValue(), " "); + long amount = n.longValue(); if (field.getAnnotation(Frequency.class) != null) { - bytes += "/s"; + if (dataAmount.value().equals(DataAmount.BYTES)) { + println(Utils.formatBytesPerSecond(amount)); + return true; + } + if (dataAmount.value().equals(DataAmount.BITS)) { + println(Utils.formatBitsPerSecond(amount)); + return true; + } + } else { + if (dataAmount.value().equals(DataAmount.BYTES)) { + println(Utils.formatBytes(amount)); + return true; + } + if (dataAmount.value().equals(DataAmount.BITS)) { + println(Utils.formatBits(amount)); + return true; + } } - println(bytes); - return true; } } MemoryAddress memoryAddress = field.getAnnotation(MemoryAddress.class); @@ -529,6 +545,14 @@ public final class PrettyWriter extends EventPrintWriter { return true; } } + Frequency frequency = field.getAnnotation(Frequency.class); + if (frequency != null) { + if (value instanceof Number) { + println(value + " Hz"); + return true; + } + } + return false; } diff --git a/test/jdk/jdk/jfr/api/metadata/annotations/TestFormatMissingValue.java b/test/jdk/jdk/jfr/api/metadata/annotations/TestFormatMissingValue.java new file mode 100644 index 00000000000..975e76c11f1 --- /dev/null +++ b/test/jdk/jdk/jfr/api/metadata/annotations/TestFormatMissingValue.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. 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.jfr.api.metadata.annotations; + +import jdk.jfr.DataAmount; +import jdk.jfr.Event; +import jdk.jfr.Frequency; +import jdk.jfr.Recording; +import jdk.jfr.StackTrace; +import jdk.jfr.consumer.RecordedEvent; +import jdk.test.lib.Asserts; +import jdk.test.lib.jfr.Events; + +/** + * @test + * @key jfr + * @summary Check that event values are properly formatted and sanity check + * that extreme values don't throws exceptions + * @requires vm.hasJFR + * @library /test/lib + * @run main/othervm jdk.jfr.api.metadata.annotations.TestFormatMissingValue + */ +public class TestFormatMissingValue { + + @StackTrace(false) + static class MultiContentTypeEvent extends Event { + @DataAmount(DataAmount.BYTES) + @Frequency + long a = Long.MIN_VALUE; + + @DataAmount(DataAmount.BYTES) + @Frequency + long b = Long.MAX_VALUE; + + @DataAmount(DataAmount.BYTES) + @Frequency + int c = Integer.MIN_VALUE; + + @DataAmount(DataAmount.BYTES) + @Frequency + int d = Integer.MAX_VALUE; + + @DataAmount(DataAmount.BYTES) + @Frequency + double e = Double.NEGATIVE_INFINITY; + + @DataAmount(DataAmount.BYTES) + @Frequency + double f = Double.POSITIVE_INFINITY; + + @DataAmount(DataAmount.BYTES) + @Frequency + double g = Double.NaN; + + @DataAmount(DataAmount.BYTES) + @Frequency + float h = Float.NEGATIVE_INFINITY; + + @DataAmount(DataAmount.BYTES) + @Frequency + float i = Float.POSITIVE_INFINITY; + + @DataAmount(DataAmount.BYTES) + @Frequency + float j = Float.NaN; + } + + public static void main(String[] args) throws Exception { + try (Recording r = new Recording()) { + r.start(); + MultiContentTypeEvent m = new MultiContentTypeEvent(); + m.commit(); + r.stop(); + for (RecordedEvent e : Events.fromRecording(r)) { + String t = e.toString(); + assertContains(t, "a = N/A"); + assertContains(t, "c = N/A"); + assertContains(t, "e = N/A"); + assertContains(t, "g = N/A"); + assertContains(t, "h = N/A"); + assertContains(t, "j = N/A"); + + assertNotContains(t, "b = N/A"); + assertNotContains(t, "d = N/A"); + assertNotContains(t, "f = N/A"); + assertNotContains(t, "i = N/A"); + } + } + } + + private static void assertContains(String t, String text) { + if (!t.contains(text)) { + Asserts.fail("Expected '" + t + "' to contain text '" + text + "'"); + } + } + + private static void assertNotContains(String t, String text) { + if (t.contains(text)) { + Asserts.fail("Found unexpected value '" + text + "' in text '" + t + "'"); + } + } +} From e7722158fd7c17960676ed3742e0ef2b457568db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Gr=C3=B6nlund?= Date: Thu, 13 Dec 2018 14:36:54 +0100 Subject: [PATCH 045/174] 8215284: Reduce noise induced by periodic task getFileSize() Reviewed-by: redestad, egahlin --- src/hotspot/share/jfr/jni/jfrJniMethod.cpp | 7 +- src/hotspot/share/jfr/jni/jfrJniMethod.hpp | 3 + .../jfr/jni/jfrJniMethodRegistration.cpp | 3 +- ...kSizeNotifier.cpp => jfrChunkRotation.cpp} | 66 +++++++++++-------- ...kSizeNotifier.hpp => jfrChunkRotation.hpp} | 23 ++++--- .../recorder/service/jfrRecorderService.cpp | 8 +-- .../share/classes/jdk/jfr/internal/JVM.java | 7 ++ .../jdk/jfr/internal/PlatformRecorder.java | 16 ++--- 8 files changed, 73 insertions(+), 60 deletions(-) rename src/hotspot/share/jfr/recorder/repository/{jfrChunkSizeNotifier.cpp => jfrChunkRotation.cpp} (62%) rename src/hotspot/share/jfr/recorder/repository/{jfrChunkSizeNotifier.hpp => jfrChunkRotation.hpp} (72%) diff --git a/src/hotspot/share/jfr/jni/jfrJniMethod.cpp b/src/hotspot/share/jfr/jni/jfrJniMethod.cpp index d0e2658523c..b1b2e13626e 100644 --- a/src/hotspot/share/jfr/jni/jfrJniMethod.cpp +++ b/src/hotspot/share/jfr/jni/jfrJniMethod.cpp @@ -33,7 +33,7 @@ #include "jfr/recorder/checkpoint/jfrMetadataEvent.hpp" #include "jfr/recorder/checkpoint/types/traceid/jfrTraceId.inline.hpp" #include "jfr/recorder/repository/jfrRepository.hpp" -#include "jfr/recorder/repository/jfrChunkSizeNotifier.hpp" +#include "jfr/recorder/repository/jfrChunkRotation.hpp" #include "jfr/recorder/repository/jfrChunkWriter.hpp" #include "jfr/recorder/service/jfrOptionSet.hpp" #include "jfr/recorder/stacktrace/jfrStackTraceRepository.hpp" @@ -114,7 +114,7 @@ NO_TRANSITION(void, jfr_set_enabled(JNIEnv* env, jobject jvm, jlong event_type_i NO_TRANSITION_END NO_TRANSITION(void, jfr_set_file_notification(JNIEnv* env, jobject jvm, jlong threshold)) - JfrChunkSizeNotifier::set_chunk_size_threshold((size_t)threshold); + JfrChunkRotation::set_threshold((intptr_t)threshold); NO_TRANSITION_END NO_TRANSITION(void, jfr_set_sample_threads(JNIEnv* env, jobject jvm, jboolean sampleThreads)) @@ -173,6 +173,9 @@ NO_TRANSITION(jboolean, jfr_set_cutoff(JNIEnv* env, jobject jvm, jlong event_typ return JfrEventSetting::set_cutoff(event_type_id, cutoff_ticks) ? JNI_TRUE : JNI_FALSE; NO_TRANSITION_END +NO_TRANSITION(jboolean, jfr_should_rotate_disk(JNIEnv* env, jobject jvm)) + return JfrChunkRotation::should_rotate() ? JNI_TRUE : JNI_FALSE; +NO_TRANSITION_END /* * JVM_ENTRY_NO_ENV entries diff --git a/src/hotspot/share/jfr/jni/jfrJniMethod.hpp b/src/hotspot/share/jfr/jni/jfrJniMethod.hpp index e7d0f7fce74..7b5394a2c58 100644 --- a/src/hotspot/share/jfr/jni/jfrJniMethod.hpp +++ b/src/hotspot/share/jfr/jni/jfrJniMethod.hpp @@ -129,6 +129,9 @@ jboolean JNICALL jfr_set_cutoff(JNIEnv* env, jobject jvm, jlong event_type_id, j void JNICALL jfr_emit_old_object_samples(JNIEnv* env, jobject jvm, jlong cutoff_ticks, jboolean); +jboolean JNICALL jfr_should_rotate_disk(JNIEnv* env, jobject jvm); + + #ifdef __cplusplus } #endif diff --git a/src/hotspot/share/jfr/jni/jfrJniMethodRegistration.cpp b/src/hotspot/share/jfr/jni/jfrJniMethodRegistration.cpp index e737f290293..174126034ee 100644 --- a/src/hotspot/share/jfr/jni/jfrJniMethodRegistration.cpp +++ b/src/hotspot/share/jfr/jni/jfrJniMethodRegistration.cpp @@ -78,7 +78,8 @@ JfrJniMethodRegistration::JfrJniMethodRegistration(JNIEnv* env) { (char*)"setForceInstrumentation", (char*)"(Z)V", (void*)jfr_set_force_instrumentation, (char*)"getUnloadedEventClassCount", (char*)"()J", (void*)jfr_get_unloaded_event_classes_count, (char*)"setCutoff", (char*)"(JJ)Z", (void*)jfr_set_cutoff, - (char*)"emitOldObjectSamples", (char*)"(JZ)V", (void*)jfr_emit_old_object_samples + (char*)"emitOldObjectSamples", (char*)"(JZ)V", (void*)jfr_emit_old_object_samples, + (char*)"shouldRotateDisk", (char*)"()Z", (void*)jfr_should_rotate_disk }; const size_t method_array_length = sizeof(method) / sizeof(JNINativeMethod); diff --git a/src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.cpp b/src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.cpp similarity index 62% rename from src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.cpp rename to src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.cpp index 7631da1120d..29bcbfaa8ec 100644 --- a/src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.cpp +++ b/src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.cpp @@ -24,29 +24,15 @@ #include "precompiled.hpp" #include "jfr/jni/jfrJavaSupport.hpp" +#include "jfr/recorder/repository/jfrChunkRotation.hpp" #include "jfr/recorder/repository/jfrChunkWriter.hpp" -#include "jfr/recorder/repository/jfrChunkSizeNotifier.hpp" -size_t JfrChunkSizeNotifier::_chunk_size_threshold = 0; +static jobject chunk_monitor = NULL; +static intptr_t threshold = 0; +static bool rotate = false; -void JfrChunkSizeNotifier::set_chunk_size_threshold(size_t bytes) { - _chunk_size_threshold = bytes; -} - -size_t JfrChunkSizeNotifier::chunk_size_threshold() { - return _chunk_size_threshold; -} - -static jobject new_chunk_monitor = NULL; - -// lazy install -static jobject get_new_chunk_monitor(Thread* thread) { - static bool initialized = false; - if (initialized) { - assert(new_chunk_monitor != NULL, "invariant"); - return new_chunk_monitor; - } - assert(new_chunk_monitor == NULL, "invariant"); +static jobject install_chunk_monitor(Thread* thread) { + assert(chunk_monitor == NULL, "invariant"); // read static field HandleMark hm(thread); static const char klass[] = "jdk/jfr/internal/JVM"; @@ -55,19 +41,41 @@ static jobject get_new_chunk_monitor(Thread* thread) { JavaValue result(T_OBJECT); JfrJavaArguments field_args(&result, klass, field, signature, thread); JfrJavaSupport::get_field_global_ref(&field_args, thread); - new_chunk_monitor = result.get_jobject(); - initialized = new_chunk_monitor != NULL; - return new_chunk_monitor; + chunk_monitor = result.get_jobject(); + return chunk_monitor; } -void JfrChunkSizeNotifier::notify() { +// lazy install +static jobject get_chunk_monitor(Thread* thread) { + return chunk_monitor != NULL ? chunk_monitor : install_chunk_monitor(thread); +} + +static void notify() { Thread* const thread = Thread::current(); - JfrJavaSupport::notify_all(get_new_chunk_monitor(thread), thread); + JfrJavaSupport::notify_all(get_chunk_monitor(thread), thread); } -void JfrChunkSizeNotifier::release_monitor() { - if (new_chunk_monitor != NULL) { - JfrJavaSupport::destroy_global_jni_handle(new_chunk_monitor); - new_chunk_monitor = NULL; +void JfrChunkRotation::evaluate(const JfrChunkWriter& writer) { + assert(threshold > 0, "invariant"); + if (rotate) { + // already in progress + return; + } + assert(!rotate, "invariant"); + if (writer.size_written() > threshold) { + rotate = true; + notify(); } } + +bool JfrChunkRotation::should_rotate() { + return rotate; +} + +void JfrChunkRotation::on_rotation() { + rotate = false; +} + +void JfrChunkRotation::set_threshold(intptr_t bytes) { + threshold = bytes; +} diff --git a/src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.hpp b/src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.hpp similarity index 72% rename from src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.hpp rename to src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.hpp index ed9eac937a0..b2b0c1a15be 100644 --- a/src/hotspot/share/jfr/recorder/repository/jfrChunkSizeNotifier.hpp +++ b/src/hotspot/share/jfr/recorder/repository/jfrChunkRotation.hpp @@ -22,24 +22,23 @@ * */ -#ifndef SHARE_VM_JFR_RECORDER_REPOSITORY_JFRRCHUNKSIZENOTIFIER_HPP -#define SHARE_VM_JFR_RECORDER_REPOSITORY_JFRRCHUNKSIZENOTIFIER_HPP +#ifndef SHARE_VM_JFR_RECORDER_REPOSITORY_JFRCHUNKROTATION_HPP +#define SHARE_VM_JFR_RECORDER_REPOSITORY_JFRCHUNKROTATION_HPP #include "memory/allocation.hpp" +class JfrChunkWriter; + // // Responsible for notifications about current chunk size now exceeding threshold. -// This is a means to initiate a chunk rotation on the basis of size written. +// This is a means to initiate a chunk rotation on the basis of the size written. // -class JfrChunkSizeNotifier : AllStatic { - friend class JfrRecorder; - private: - static size_t _chunk_size_threshold; - static void release_monitor(); +class JfrChunkRotation : AllStatic { public: - static void set_chunk_size_threshold(size_t bytes); - static size_t chunk_size_threshold(); - static void notify(); + static void evaluate(const JfrChunkWriter& writer); + static void set_threshold(intptr_t bytes); + static bool should_rotate(); + static void on_rotation(); }; -#endif // SHARE_VM_JFR_RECORDER_REPOSITORY_JFRRCHUNKSIZENOTIFIER_HPP +#endif // SHARE_VM_JFR_RECORDER_REPOSITORY_JFRCHUNKROTATION_HPP diff --git a/src/hotspot/share/jfr/recorder/service/jfrRecorderService.cpp b/src/hotspot/share/jfr/recorder/service/jfrRecorderService.cpp index e9cd2114588..c0c4964aa7c 100644 --- a/src/hotspot/share/jfr/recorder/service/jfrRecorderService.cpp +++ b/src/hotspot/share/jfr/recorder/service/jfrRecorderService.cpp @@ -28,7 +28,7 @@ #include "jfr/recorder/jfrRecorder.hpp" #include "jfr/recorder/checkpoint/jfrCheckpointManager.hpp" #include "jfr/recorder/checkpoint/jfrMetadataEvent.hpp" -#include "jfr/recorder/repository/jfrChunkSizeNotifier.hpp" +#include "jfr/recorder/repository/jfrChunkRotation.hpp" #include "jfr/recorder/repository/jfrChunkWriter.hpp" #include "jfr/recorder/repository/jfrRepository.hpp" #include "jfr/recorder/service/jfrPostBox.hpp" @@ -340,6 +340,7 @@ void JfrRecorderService::prepare_for_vm_error_rotation() { void JfrRecorderService::open_new_chunk(bool vm_error) { assert(!_chunkwriter.is_valid(), "invariant"); assert(!JfrStream_lock->owned_by_self(), "invariant"); + JfrChunkRotation::on_rotation(); MutexLockerEx stream_lock(JfrStream_lock, Mutex::_no_safepoint_check_flag); if (!_repository.open_chunk(vm_error)) { assert(!_chunkwriter.is_valid(), "invariant"); @@ -535,8 +536,5 @@ void JfrRecorderService::scavenge() { } void JfrRecorderService::evaluate_chunk_size_for_rotation() { - const size_t size_written = _chunkwriter.size_written(); - if (size_written > JfrChunkSizeNotifier::chunk_size_threshold()) { - JfrChunkSizeNotifier::notify(); - } + JfrChunkRotation::evaluate(_chunkwriter); } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/JVM.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/JVM.java index d549bb1f96d..e9f6d2a9a60 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/JVM.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/JVM.java @@ -516,4 +516,11 @@ public final class JVM { * @param emitAll emit all samples in old object queue */ public native void emitOldObjectSamples(long cutoff, boolean emitAll); + + /** + * Test if a chunk rotation is warranted. + * + * @return if it is time to perform a chunk rotation + */ + public native boolean shouldRotateDisk(); } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java index 3310444fd96..7c48fc26624 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/PlatformRecorder.java @@ -427,19 +427,13 @@ public final class PlatformRecorder { } private void periodicTask() { + if (!jvm.hasNativeJFR()) { + return; + } while (true) { synchronized (this) { - if (!jvm.hasNativeJFR()) { - return; - } - if (currentChunk != null) { - try { - if (SecuritySupport.getFileSize(currentChunk.getUnfishedFile()) > Options.getMaxChunkSize()) { - rotateDisk(); - } - } catch (IOException e) { - Logger.log(JFR_SYSTEM, WARN, "Could not check file size to determine chunk rotation"); - } + if (jvm.shouldRotateDisk()) { + rotateDisk(); } } long minDelta = RequestEngine.doPeriodic(); From a85ad0aa1884ef8ef24a6d01da6e22dbce2897dc Mon Sep 17 00:00:00 2001 From: Zhengyu Gu Date: Wed, 12 Dec 2018 13:50:57 -0500 Subject: [PATCH 046/174] 8215220: Simplify Shenandoah task termination in aborted paths Reviewed-by: shade --- .../shenandoah/shenandoahConcurrentMark.cpp | 9 ++------ .../gc/shenandoah/shenandoahTaskqueue.cpp | 22 +------------------ .../gc/shenandoah/shenandoahTaskqueue.hpp | 14 ++++-------- .../gc/shenandoah/shenandoahTraversalGC.cpp | 12 +++------- 4 files changed, 10 insertions(+), 47 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahConcurrentMark.cpp b/src/hotspot/share/gc/shenandoah/shenandoahConcurrentMark.cpp index 5a9bdd238a0..01ea1f00d87 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahConcurrentMark.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahConcurrentMark.cpp @@ -939,9 +939,6 @@ void ShenandoahConcurrentMark::mark_loop_work(T* cl, jushort* live_data, uint wo q = queues->claim_next(); while (q != NULL) { if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) { - ShenandoahCancelledTerminatorTerminator tt; - ShenandoahSuspendibleThreadSetLeaver stsl(ShenandoahSuspendibleWorkers); - while (!terminator->offer_termination(&tt)); return; } @@ -965,9 +962,6 @@ void ShenandoahConcurrentMark::mark_loop_work(T* cl, jushort* live_data, uint wo */ while (true) { if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) { - ShenandoahCancelledTerminatorTerminator tt; - ShenandoahSuspendibleThreadSetLeaver stsl(ShenandoahSuspendibleWorkers); - while (!terminator->offer_termination(&tt)); return; } @@ -991,7 +985,8 @@ void ShenandoahConcurrentMark::mark_loop_work(T* cl, jushort* live_data, uint wo // Need to leave the STS here otherwise it might block safepoints. ShenandoahSuspendibleThreadSetLeaver stsl(CANCELLABLE && ShenandoahSuspendibleWorkers); ShenandoahTerminationTimingsTracker term_tracker(worker_id); - if (terminator->offer_termination()) return; + ShenandoahTerminatorTerminator tt(heap); + if (terminator->offer_termination(&tt)) return; } } } diff --git a/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.cpp b/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.cpp index 773d1bd8e1c..aeaca5cfa4d 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.cpp @@ -49,28 +49,8 @@ bool ShenandoahObjToScanQueueSet::is_empty() { return true; } -class ShenandoahOWSTTerminator: public OWSTTaskTerminator { -public: - ShenandoahOWSTTerminator(uint n_threads, TaskQueueSetSuper* queue_set) : - OWSTTaskTerminator(n_threads, queue_set){ } - -protected: - bool exit_termination(size_t tasks, TerminatorTerminator* terminator); -}; - -bool ShenandoahOWSTTerminator::exit_termination(size_t tasks, TerminatorTerminator* terminator) { - ShenandoahTerminatorTerminator* t = (ShenandoahTerminatorTerminator*)terminator; - bool force = (t != NULL) && t->should_force_termination(); - if (force) { - // Force termination : continue termination, even there are remaining tasks. - return false; - } else { - return OWSTTaskTerminator::exit_termination(tasks, terminator); - } -} - ShenandoahTaskTerminator::ShenandoahTaskTerminator(uint n_threads, TaskQueueSetSuper* queue_set) : - _terminator(new ShenandoahOWSTTerminator(n_threads, queue_set)) { } + _terminator(new OWSTTaskTerminator(n_threads, queue_set)) { } ShenandoahTaskTerminator::~ShenandoahTaskTerminator() { assert(_terminator != NULL, "Invariant"); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.hpp b/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.hpp index 790ecf72906..5dacaa957a3 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahTaskqueue.hpp @@ -306,18 +306,12 @@ public: }; class ShenandoahTerminatorTerminator : public TerminatorTerminator { +private: + ShenandoahHeap* _heap; public: + ShenandoahTerminatorTerminator(ShenandoahHeap* const heap) : _heap(heap) { } // return true, terminates immediately, even if there's remaining work left - virtual bool should_force_termination() { return false; } -}; - -class ShenandoahCancelledTerminatorTerminator : public ShenandoahTerminatorTerminator { - virtual bool should_exit_termination() { - return false; - } - virtual bool should_force_termination() { - return true; - } + virtual bool should_exit_termination() { return _heap->cancelled_gc(); } }; class ShenandoahTaskTerminator : public StackObj { diff --git a/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp b/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp index 480ff0a5ecc..ce4891f62f9 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahTraversalGC.cpp @@ -498,10 +498,6 @@ void ShenandoahTraversalGC::main_loop_work(T* cl, jushort* live_data, uint worke q = queues->claim_next(); while (q != NULL) { if (_heap->check_cancelled_gc_and_yield(sts_yield)) { - ShenandoahCancelledTerminatorTerminator tt; - ShenandoahEvacOOMScopeLeaver oom_scope_leaver; - ShenandoahSuspendibleThreadSetLeaver stsl(sts_yield && ShenandoahSuspendibleWorkers); - while (!terminator->offer_termination(&tt)); return; } @@ -547,17 +543,15 @@ void ShenandoahTraversalGC::main_loop_work(T* cl, jushort* live_data, uint worke ShenandoahEvacOOMScopeLeaver oom_scope_leaver; ShenandoahSuspendibleThreadSetLeaver stsl(sts_yield && ShenandoahSuspendibleWorkers); ShenandoahTerminationTimingsTracker term_tracker(worker_id); - if (terminator->offer_termination()) return; + ShenandoahTerminatorTerminator tt(_heap); + + if (terminator->offer_termination(&tt)) return; } } } bool ShenandoahTraversalGC::check_and_handle_cancelled_gc(ShenandoahTaskTerminator* terminator, bool sts_yield) { if (_heap->cancelled_gc()) { - ShenandoahCancelledTerminatorTerminator tt; - ShenandoahEvacOOMScopeLeaver oom_scope_leaver; - ShenandoahSuspendibleThreadSetLeaver stsl(sts_yield && ShenandoahSuspendibleWorkers); - while (! terminator->offer_termination(&tt)); return true; } return false; From ebdf83f88e5f9c1eb80043c0c8bc38f12fff69e1 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Thu, 13 Dec 2018 15:40:11 +0100 Subject: [PATCH 047/174] 8215237: jdk.jfr.Recording javadoc does not compile Reviewed-by: mgronlun --- .../share/classes/jdk/jfr/Recording.java | 2 +- .../jdk/jfr/consumer/package-info.java | 53 +++++++------------ 2 files changed, 21 insertions(+), 34 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/Recording.java b/src/jdk.jfr/share/classes/jdk/jfr/Recording.java index 26db88cf80c..cfb1d8bb1f6 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/Recording.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/Recording.java @@ -54,7 +54,7 @@ import jdk.jfr.internal.WriteableUserPath; * System.gc(); * Thread.sleep(5000); * r.stop(); - * r.copyTo(Files.createTempFile("my-recording", ".jfr")); + * r.dump(Files.createTempFile("my-recording", ".jfr")); * * * diff --git a/src/jdk.jfr/share/classes/jdk/jfr/consumer/package-info.java b/src/jdk.jfr/share/classes/jdk/jfr/consumer/package-info.java index ae864a86508..ba9b1e4833f 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/consumer/package-info.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/consumer/package-info.java @@ -29,40 +29,27 @@ * In the following example, the program prints a histogram of all method samples in a recording. *

      * 
    - *   public static void main(String[] args) {
    - *     if (args.length != 0) {
    - *       System.out.println("Must specify recording file.");
    - *       return;
    + * public static void main(String[] args) throws IOException {
    + *     if (args.length != 1) {
    + *         System.err.println("Must specify a recording file.");
    + *         return;
      *     }
    - *     try (RecordingFile f = new RecordingFile(Paths.get(args[0]))) {
    - *       Map{@literal <}String, SimpleEntry{@literal <}String, Integer{@literal >}{@literal >} histogram = new HashMap{@literal <}{@literal >}();
    - *       int total = 0;
    - *       while (f.hasMoreEvents()) {
    - *         RecordedEvent event = f.readEvent();
    - *         if (event.getEventType().getName().equals("jdk.ExecutionSample")) {
    - *           RecordedStackTrace s = event.getStackTrace();
    - *           if (s != null) {
    - *             RecordedFrame topFrame= s.getFrames().get(0);
    - *             if (topFrame.isJavaFrame())  {
    - *               RecordedMethod method = topFrame.getMethod();
    - *               String methodName = method.getType().getName() + "#" + method.getName() + " " + method.getDescriptor();
    - *               Entry entry = histogram.computeIfAbsent(methodName, u -{@literal >} new SimpleEntry{@literal <}String, Integer{@literal >}(methodName, 0));
    - *               entry.setValue(entry.getValue() + 1);
    - *               total++;
    - *             }
    - *           }
    - *         }
    - *       }
    - *       List{@literal <}SimpleEntry{@literal <}String, Integer{@literal >}{@literal >} entries = new ArrayList{@literal <}{@literal >}(histogram.values());
    - *       entries.sort((u, v) -{@literal >} v.getValue().compareTo(u.getValue()));
    - *       for (SimpleEntry{@literal <}String, Integer{@literal >} c : entries) {
    - *         System.out.printf("%2.0f%% %s\n", 100 * (float) c.getValue() / total, c.getKey());
    - *       }
    - *       System.out.println("\nSample count: " + total);
    - *     } catch (IOException ioe) {
    - *       System.out.println("Error reading file " + args[0] + ". " + ioe.getMessage());
    - *     }
    - *   }
    + *
    + *     RecordingFile.readAllEvents(Path.of(args[0])).stream()
    + *         .filter(e -> e.getEventType().getName().equals("jdk.ExecutionSample"))
    + *         .map(e -> e.getStackTrace())
    + *         .filter(s -> s != null)
    + *         .map(s -> s.getFrames().get(0))
    + *         .filter(f -> f.isJavaFrame())
    + *         .map(f -> f.getMethod())
    + *         .collect(
    + *             Collectors.groupingBy(m -> m.getType().getName() + "." + m.getName() + " " + m.getDescriptor(),
    + *             Collectors.counting()))
    + *         .entrySet()
    + *         .stream()
    + *         .sorted((a, b) -> b.getValue().compareTo(a.getValue()))
    + *         .forEach(e -> System.out.printf("%8d %s\n", e.getValue(), e.getKey()));
    + * }
      * 
      * 
    *

    From c998ead188ef16be2bc49da5ba4162ca46b1c62f Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Thu, 13 Dec 2018 16:14:07 +0100 Subject: [PATCH 048/174] 8215354: x86_32 build failures after JDK-8214074 (Ghash optimization using AVX instructions) Reviewed-by: thartmann --- src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp b/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp index 135923ea569..1c60fc50ec3 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86_aes.cpp @@ -29,6 +29,7 @@ #include "runtime/stubRoutines.hpp" #include "macroAssembler_x86.hpp" +#ifdef _LP64 // Multiply 128 x 128 bits, using 4 pclmulqdq operations void MacroAssembler::schoolbookAAD(int i, Register htbl, XMMRegister data, XMMRegister tmp0, XMMRegister tmp1, XMMRegister tmp2, XMMRegister tmp3) { @@ -319,4 +320,5 @@ void MacroAssembler::avx_ghash(Register input_state, Register htbl, vpxor(xmm1, xmm1, xmm1, Assembler::AVX_128bit); vpxor(xmm3, xmm3, xmm3, Assembler::AVX_128bit); vpxor(xmm15, xmm15, xmm15, Assembler::AVX_128bit); -} \ No newline at end of file +} +#endif // _LP64 From a3df1d618e9204da4162191c359bbc383d809b94 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Thu, 13 Dec 2018 15:31:05 +0100 Subject: [PATCH 049/174] 8215281: Use String.isEmpty() when applicable in java.base Reviewed-by: dfuchs, alanb --- .../com/sun/java/util/jar/pack/Attribute.java | 2 +- .../com/sun/java/util/jar/pack/Driver.java | 14 +++---- .../com/sun/net/ssl/KeyManagerFactory.java | 2 +- .../classes/com/sun/net/ssl/SSLContext.java | 2 +- .../com/sun/net/ssl/TrustManagerFactory.java | 2 +- .../share/classes/java/io/Console.java | 4 +- .../share/classes/java/lang/ClassLoader.java | 2 +- .../share/classes/java/lang/Integer.java | 2 +- .../share/classes/java/lang/Long.java | 2 +- .../share/classes/java/lang/Package.java | 4 +- .../share/classes/java/lang/Runtime.java | 2 +- .../share/classes/java/lang/String.java | 8 ++-- .../java/lang/VersionProps.java.template | 4 +- .../java/lang/invoke/ConstantBootstraps.java | 2 +- .../java/lang/invoke/MethodHandles.java | 2 +- .../java/lang/invoke/ProxyClassesDumper.java | 2 +- .../share/classes/java/net/HttpCookie.java | 2 +- .../share/classes/java/net/Inet6Address.java | 6 +-- .../share/classes/java/net/InetAddress.java | 4 +- .../classes/java/net/SocketPermission.java | 5 +-- src/java.base/share/classes/java/net/URI.java | 10 ++--- src/java.base/share/classes/java/net/URL.java | 8 ++-- .../classes/java/net/URLClassLoader.java | 2 +- .../share/classes/java/net/URLDecoder.java | 2 +- .../share/classes/java/net/URLPermission.java | 8 ++-- .../classes/java/net/URLStreamHandler.java | 14 +++---- .../classes/java/nio/file/LinkPermission.java | 2 +- .../security/AlgorithmParameterGenerator.java | 2 +- .../java/security/AlgorithmParameters.java | 2 +- .../share/classes/java/security/KeyStore.java | 2 +- .../classes/java/security/MessageDigest.java | 2 +- .../classes/java/security/Permission.java | 2 +- .../share/classes/java/security/Policy.java | 2 +- .../classes/java/security/SecureRandom.java | 2 +- .../share/classes/java/security/Security.java | 10 ++--- .../classes/java/security/Signature.java | 2 +- .../java/security/cert/TrustAnchor.java | 2 +- .../classes/java/text/AttributedString.java | 4 +- .../java/text/CollationElementIterator.java | 2 +- .../java/text/CompactNumberFormat.java | 4 +- .../classes/java/text/DecimalFormat.java | 12 +++--- .../java/text/DecimalFormatSymbols.java | 2 +- .../classes/java/text/MergeCollation.java | 4 +- .../classes/java/text/MessageFormat.java | 4 +- .../share/classes/java/text/PatternEntry.java | 2 +- .../classes/java/text/RBTableBuilder.java | 12 ++---- .../share/classes/java/time/ZoneId.java | 2 +- .../time/format/DateTimeFormatterBuilder.java | 6 +-- .../share/classes/java/util/Calendar.java | 2 +- .../share/classes/java/util/Locale.java | 42 +++++++++---------- .../classes/java/util/ResourceBundle.java | 20 ++++----- .../share/classes/java/util/Scanner.java | 8 ++-- .../classes/java/util/regex/Pattern.java | 4 +- .../share/classes/javax/crypto/Cipher.java | 8 ++-- .../classes/javax/crypto/SealedObject.java | 2 +- .../javax/net/ssl/SSLSocketFactory.java | 2 +- .../auth/PrivateCredentialPermission.java | 2 +- .../auth/callback/ChoiceCallback.java | 4 +- .../auth/callback/ConfirmationCallback.java | 8 ++-- .../security/auth/callback/NameCallback.java | 6 +-- .../auth/callback/PasswordCallback.java | 2 +- .../auth/callback/TextInputCallback.java | 6 +-- .../auth/callback/TextOutputCallback.java | 2 +- .../auth/login/AppConfigurationEntry.java | 2 +- .../security/auth/login/Configuration.java | 2 +- .../security/auth/login/LoginContext.java | 2 +- .../javax/security/cert/X509Certificate.java | 2 +- .../jimage/decompressor/SignatureParser.java | 2 +- .../StringSharingDecompressor.java | 2 +- .../jdk/internal/jrtfs/JrtFileSystem.java | 2 +- .../classes/jdk/internal/jrtfs/JrtPath.java | 12 +++--- .../jdk/internal/loader/ClassLoaders.java | 4 +- .../jdk/internal/loader/URLClassPath.java | 2 +- .../classes/jdk/internal/module/Checks.java | 28 +++---------- .../jdk/internal/module/ModuleBootstrap.java | 5 ++- .../jdk/internal/module/ModulePatcher.java | 2 +- .../jdk/internal/module/ModulePath.java | 4 +- .../jdk/internal/module/Resources.java | 2 +- .../internal/module/SystemModuleFinders.java | 2 +- .../internal/org/objectweb/asm/TypePath.java | 2 +- .../asm/util/CheckMethodAdapter.java | 6 +-- .../asm/util/CheckSignatureAdapter.java | 4 +- .../reflect/UnsafeFieldAccessorImpl.java | 4 +- .../jdk/internal/util/jar/JarIndex.java | 2 +- .../util/xml/PropertiesDefaultHandler.java | 2 +- .../jdk/internal/util/xml/impl/Parser.java | 2 +- .../util/xml/impl/XMLStreamWriterImpl.java | 4 +- .../classes/sun/invoke/util/BytecodeName.java | 4 +- .../sun/net/TransferProtocolClient.java | 2 +- .../classes/sun/net/ftp/impl/FtpClient.java | 10 ++--- .../sun/net/spi/DefaultProxySelector.java | 4 +- .../classes/sun/net/www/HeaderParser.java | 2 +- .../share/classes/sun/net/www/MimeEntry.java | 6 +-- .../classes/sun/net/www/MimeLauncher.java | 2 +- .../share/classes/sun/net/www/ParseUtil.java | 3 +- .../classes/sun/net/www/http/HttpClient.java | 4 +- .../www/protocol/ftp/FtpURLConnection.java | 4 +- .../www/protocol/http/AuthenticationInfo.java | 2 +- .../protocol/http/DigestAuthentication.java | 6 +-- .../www/protocol/http/HttpURLConnection.java | 2 +- .../net/www/protocol/https/HttpsClient.java | 6 +-- .../jrt/JavaRuntimeURLConnection.java | 2 +- .../share/classes/sun/nio/ch/Net.java | 10 +---- .../nio/fs/AbstractFileSystemProvider.java | 4 +- .../AbstractUserDefinedFileAttributeView.java | 2 +- .../classes/sun/security/jca/GetInstance.java | 2 +- .../sun/security/jca/ProviderConfig.java | 2 +- .../sun/security/jca/ProviderList.java | 4 +- .../sun/security/provider/ConfigFile.java | 4 +- .../sun/security/provider/PolicyParser.java | 6 +-- .../sun/security/provider/SeedGenerator.java | 2 +- .../sun/security/ssl/CertificateMessage.java | 2 +- .../classes/sun/security/ssl/ClientHello.java | 2 +- .../sun/security/ssl/DHKeyExchange.java | 2 +- .../security/ssl/SSLAlgorithmConstraints.java | 4 +- .../sun/security/ssl/SSLContextImpl.java | 18 ++++---- .../sun/security/ssl/SSLSocketImpl.java | 5 +-- .../ssl/SupportedGroupsExtension.java | 4 +- .../security/ssl/X509TrustManagerImpl.java | 8 ++-- .../classes/sun/security/tools/PathList.java | 4 +- .../util/AbstractAlgorithmConstraints.java | 2 +- .../security/util/AlgorithmDecomposer.java | 4 +- .../util/DisabledAlgorithmConstraints.java | 4 +- .../security/util/SignatureFileVerifier.java | 2 +- .../share/classes/sun/security/x509/AVA.java | 4 +- .../classes/sun/security/x509/DNSName.java | 2 +- .../sun/security/x509/IPAddressName.java | 2 +- .../share/classes/sun/security/x509/RDN.java | 8 ++-- .../classes/sun/security/x509/RFC822Name.java | 4 +- .../classes/sun/security/x509/X500Name.java | 4 +- .../sun/security/x509/X509CRLImpl.java | 4 +- .../sun/security/x509/X509CertImpl.java | 4 +- .../util/locale/InternalLocaleBuilder.java | 10 ++--- .../classes/sun/util/locale/LanguageTag.java | 14 +++---- .../sun/util/locale/LocaleMatcher.java | 8 ++-- .../classes/sun/util/locale/LocaleUtils.java | 2 +- .../util/locale/UnicodeLocaleExtension.java | 2 +- .../provider/CalendarNameProviderImpl.java | 4 +- .../provider/JRELocaleProviderAdapter.java | 2 +- .../provider/LocaleProviderAdapter.java | 2 +- .../unix/classes/java/io/UnixFileSystem.java | 4 +- .../jdk/internal/loader/FileURLMapper.java | 4 +- .../net/dns/ResolverConfigurationImpl.java | 8 ++-- .../unix/classes/sun/net/sdp/SdpProvider.java | 8 ++-- .../sun/net/www/protocol/file/Handler.java | 4 +- .../ch/UnixAsynchronousSocketChannelImpl.java | 4 +- .../classes/sun/nio/fs/UnixFileSystem.java | 5 +-- .../classes/java/io/WinNTFileSystem.java | 2 +- .../sun/net/www/protocol/file/Handler.java | 4 +- .../sun/nio/ch/FileDispatcherImpl.java | 10 +---- .../sun/nio/fs/WindowsFileAttributes.java | 3 +- .../classes/sun/nio/fs/WindowsFileStore.java | 2 +- .../classes/sun/nio/fs/WindowsFileSystem.java | 2 +- .../sun/nio/fs/WindowsLinkSupport.java | 2 +- .../classes/sun/nio/fs/WindowsPath.java | 8 ++-- 155 files changed, 340 insertions(+), 382 deletions(-) diff --git a/src/java.base/share/classes/com/sun/java/util/jar/pack/Attribute.java b/src/java.base/share/classes/com/sun/java/util/jar/pack/Attribute.java index e8ff8951716..8f2ed6a8bdf 100644 --- a/src/java.base/share/classes/com/sun/java/util/jar/pack/Attribute.java +++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/Attribute.java @@ -996,7 +996,7 @@ class Attribute implements Comparable { endp = cstr.indexOf(',', cp); if (endp < 0) endp = cstrlen; String cstr1 = cstr.substring(cp, endp); - if (cstr1.length() == 0) + if (cstr1.isEmpty()) cstr1 = "empty"; // will fail parse int value0, value1; // Check for a case range (new in 1.6). diff --git a/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java b/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java index bddaa00f621..ac04e677ffe 100644 --- a/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java +++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/Driver.java @@ -279,7 +279,7 @@ class Driver { junpack.properties().putAll(engProps); if (doRepack && newfile.equals(jarfile)) { String zipc = getZipComment(jarfile); - if (verbose && zipc.length() > 0) + if (verbose && !zipc.isEmpty()) System.out.println(MessageFormat.format(RESOURCE.getString(DriverResource.DETECTED_ZIP_COMMENT), zipc)); if (zipc.indexOf(Utils.PACK_ZIP_ARCHIVE_MARKER_COMMENT) >= 0) { System.out.println(MessageFormat.format(RESOURCE.getString(DriverResource.SKIP_FOR_REPACKED), jarfile)); @@ -552,7 +552,7 @@ class Driver { if (words.length == 0) continue loadOptmap; String opt = words[0]; words[0] = ""; // initial word is not a spec - if (opt.length() == 0 && words.length >= 1) { + if (opt.isEmpty() && words.length >= 1) { opt = words[1]; // initial "word" is empty due to leading ' ' words[1] = ""; } @@ -622,7 +622,7 @@ class Driver { switch (specop) { case '+': // + means we want an non-empty val suffix. - ok = (val.length() != 0); + ok = !val.isEmpty(); specop = spec.charAt(sidx++); break; case '*': @@ -641,10 +641,10 @@ class Driver { String specarg = spec.substring(sidx); switch (specop) { case '.': // terminate the option sequence - resultString = (specarg.length() != 0)? specarg.intern(): opt; + resultString = specarg.isEmpty() ? opt : specarg.intern(); break doArgs; case '?': // abort the option sequence - resultString = (specarg.length() != 0)? specarg.intern(): arg; + resultString = specarg.isEmpty() ? arg : specarg.intern(); isError = true; break eachSpec; case '@': // change the effective opt name @@ -655,14 +655,14 @@ class Driver { val = ""; break; case '!': // negation option - String negopt = (specarg.length() != 0)? specarg.intern(): opt; + String negopt = specarg.isEmpty() ? opt : specarg.intern(); properties.remove(negopt); properties.put(negopt, null); // leave placeholder didAction = true; break; case '$': // normal "boolean" option String boolval; - if (specarg.length() != 0) { + if (!specarg.isEmpty()) { // If there is a given spec token, store it. boolval = specarg; } else { diff --git a/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java b/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java index c79ef43c2b6..2142dd50ebb 100644 --- a/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java +++ b/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java @@ -153,7 +153,7 @@ public class KeyManagerFactory { String provider) throws NoSuchAlgorithmException, NoSuchProviderException { - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = SSLSecurity.getImpl(algorithm, "KeyManagerFactory", provider); diff --git a/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java b/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java index d23148b18f8..84cc2d1182a 100644 --- a/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java +++ b/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java @@ -109,7 +109,7 @@ public class SSLContext { public static SSLContext getInstance(String protocol, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = SSLSecurity.getImpl(protocol, "SSLContext", provider); diff --git a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java b/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java index d011ce74ed1..b580f04af34 100644 --- a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java +++ b/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java @@ -155,7 +155,7 @@ public class TrustManagerFactory { String provider) throws NoSuchAlgorithmException, NoSuchProviderException { - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = SSLSecurity.getImpl(algorithm, "TrustManagerFactory", provider); diff --git a/src/java.base/share/classes/java/io/Console.java b/src/java.base/share/classes/java/io/Console.java index c8f5fc3f9a2..9f03f5358b9 100644 --- a/src/java.base/share/classes/java/io/Console.java +++ b/src/java.base/share/classes/java/io/Console.java @@ -247,7 +247,7 @@ public final class Console implements Flushable String line = null; synchronized (writeLock) { synchronized(readLock) { - if (fmt.length() != 0) + if (!fmt.isEmpty()) pw.format(fmt, args); try { char[] ca = readline(false); @@ -319,7 +319,7 @@ public final class Console implements Flushable } IOError ioe = null; try { - if (fmt.length() != 0) + if (!fmt.isEmpty()) pw.format(fmt, args); passwd = readline(true); } catch (IOException x) { diff --git a/src/java.base/share/classes/java/lang/ClassLoader.java b/src/java.base/share/classes/java/lang/ClassLoader.java index 12cefac5357..71d4898450b 100644 --- a/src/java.base/share/classes/java/lang/ClassLoader.java +++ b/src/java.base/share/classes/java/lang/ClassLoader.java @@ -1119,7 +1119,7 @@ public abstract class ClassLoader { // true if the name is null or has the potential to be a valid binary name private boolean checkName(String name) { - if ((name == null) || (name.length() == 0)) + if ((name == null) || (name.isEmpty())) return true; if ((name.indexOf('/') != -1) || (name.charAt(0) == '[')) return false; diff --git a/src/java.base/share/classes/java/lang/Integer.java b/src/java.base/share/classes/java/lang/Integer.java index 062e8170177..5a3a1b6ba00 100644 --- a/src/java.base/share/classes/java/lang/Integer.java +++ b/src/java.base/share/classes/java/lang/Integer.java @@ -1409,7 +1409,7 @@ public final class Integer extends Number boolean negative = false; Integer result; - if (nm.length() == 0) + if (nm.isEmpty()) throw new NumberFormatException("Zero length string"); char firstChar = nm.charAt(0); // Handle sign, if present diff --git a/src/java.base/share/classes/java/lang/Long.java b/src/java.base/share/classes/java/lang/Long.java index c2c466d08a0..7cd78b04c9b 100644 --- a/src/java.base/share/classes/java/lang/Long.java +++ b/src/java.base/share/classes/java/lang/Long.java @@ -1248,7 +1248,7 @@ public final class Long extends Number boolean negative = false; Long result; - if (nm.length() == 0) + if (nm.isEmpty()) throw new NumberFormatException("Zero length string"); char firstChar = nm.charAt(0); // Handle sign, if present diff --git a/src/java.base/share/classes/java/lang/Package.java b/src/java.base/share/classes/java/lang/Package.java index c52b9f12aa9..cb17d7a1ca8 100644 --- a/src/java.base/share/classes/java/lang/Package.java +++ b/src/java.base/share/classes/java/lang/Package.java @@ -397,11 +397,11 @@ public class Package extends NamedPackage implements java.lang.reflect.Annotated public String toString() { String spec = versionInfo.specTitle; String ver = versionInfo.specVersion; - if (spec != null && spec.length() > 0) + if (spec != null && !spec.isEmpty()) spec = ", " + spec; else spec = ""; - if (ver != null && ver.length() > 0) + if (ver != null && !ver.isEmpty()) ver = ", version " + ver; else ver = ""; diff --git a/src/java.base/share/classes/java/lang/Runtime.java b/src/java.base/share/classes/java/lang/Runtime.java index 20376f49097..82108dccc39 100644 --- a/src/java.base/share/classes/java/lang/Runtime.java +++ b/src/java.base/share/classes/java/lang/Runtime.java @@ -403,7 +403,7 @@ public class Runtime { */ public Process exec(String command, String[] envp, File dir) throws IOException { - if (command.length() == 0) + if (command.isEmpty()) throw new IllegalArgumentException("Empty command"); StringTokenizer st = new StringTokenizer(command); diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index 201f3f5d804..c9634ddc7aa 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -664,7 +664,7 @@ public final class String * object. */ public int length() { - return value.length >> coder(); + return isLatin1() ? value.length : value.length >> UTF16; } /** @@ -1943,8 +1943,7 @@ public final class String * characters followed by the string argument's characters. */ public String concat(String str) { - int olen = str.length(); - if (olen == 0) { + if (str.isEmpty()) { return this; } if (coder() == str.coder()) { @@ -1956,6 +1955,7 @@ public final class String return new String(buf, coder); } int len = length(); + int olen = str.length(); byte[] buf = StringUTF16.newBytesFor(len + olen); getBytes(buf, 0, UTF16); str.getBytes(buf, len, UTF16); @@ -2316,7 +2316,7 @@ public final class String // Construct result int resultSize = list.size(); if (limit == 0) { - while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { + while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) { resultSize--; } } diff --git a/src/java.base/share/classes/java/lang/VersionProps.java.template b/src/java.base/share/classes/java/lang/VersionProps.java.template index 66035a130ae..799f35075ac 100644 --- a/src/java.base/share/classes/java/lang/VersionProps.java.template +++ b/src/java.base/share/classes/java/lang/VersionProps.java.template @@ -73,7 +73,7 @@ class VersionProps { "@@VENDOR_VERSION_STRING@@"; private static final String vendor_version = - (VENDOR_VERSION_STRING.length() > 0 + (!VENDOR_VERSION_STRING.isEmpty() ? " " + VENDOR_VERSION_STRING : ""); private static final String VENDOR = @@ -95,7 +95,7 @@ class VersionProps { props.put("java.version.date", java_version_date); props.put("java.runtime.version", java_runtime_version); props.put("java.runtime.name", java_runtime_name); - if (VENDOR_VERSION_STRING.length() > 0) + if (!VENDOR_VERSION_STRING.isEmpty()) props.put("java.vendor.version", VENDOR_VERSION_STRING); props.put("java.class.version", CLASSFILE_MAJOR_MINOR); diff --git a/src/java.base/share/classes/java/lang/invoke/ConstantBootstraps.java b/src/java.base/share/classes/java/lang/invoke/ConstantBootstraps.java index 871b87061a0..0cf01320d2b 100644 --- a/src/java.base/share/classes/java/lang/invoke/ConstantBootstraps.java +++ b/src/java.base/share/classes/java/lang/invoke/ConstantBootstraps.java @@ -103,7 +103,7 @@ public final class ConstantBootstraps { if (type != Class.class) { throw new IllegalArgumentException(); } - if (name.length() == 0 || name.length() > 1) { + if (name.length() != 1) { throw new IllegalArgumentException(String.format("not primitive: %s", name)); } diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java index 15a5b860b00..967ab01315c 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java @@ -201,7 +201,7 @@ public class MethodHandles { throw new IllegalAccessException(callerModule + " does not read " + targetModule); if (targetModule.isNamed()) { String pn = targetClass.getPackageName(); - assert pn.length() > 0 : "unnamed package cannot be in named module"; + assert !pn.isEmpty() : "unnamed package cannot be in named module"; if (!targetModule.isOpen(pn, callerModule)) throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); } diff --git a/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java b/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java index 2737bd5a4bf..f1f5ef673e0 100644 --- a/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java +++ b/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java @@ -62,7 +62,7 @@ final class ProxyClassesDumper { } try { path = path.trim(); - final Path dir = Path.of(path.length() == 0 ? "." : path); + final Path dir = Path.of(path.isEmpty() ? "." : path); AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { diff --git a/src/java.base/share/classes/java/net/HttpCookie.java b/src/java.base/share/classes/java/net/HttpCookie.java index b2ac58abcf6..e7b826f3b8f 100644 --- a/src/java.base/share/classes/java/net/HttpCookie.java +++ b/src/java.base/share/classes/java/net/HttpCookie.java @@ -149,7 +149,7 @@ public final class HttpCookie implements Cloneable { */ HttpCookie(String name, String value, String header, long creationTime) { name = name.trim(); - if (name.length() == 0 || !isToken(name) || name.charAt(0) == '$') { + if (name.isEmpty() || !isToken(name) || name.charAt(0) == '$') { throw new IllegalArgumentException("Illegal cookie name"); } diff --git a/src/java.base/share/classes/java/net/Inet6Address.java b/src/java.base/share/classes/java/net/Inet6Address.java index a8687b3ab55..ef0eb0520cd 100644 --- a/src/java.base/share/classes/java/net/Inet6Address.java +++ b/src/java.base/share/classes/java/net/Inet6Address.java @@ -433,7 +433,7 @@ class Inet6Address extends InetAddress { NetworkInterface nif) throws UnknownHostException { - if (host != null && host.length() > 0 && host.charAt(0) == '[') { + if (host != null && !host.isEmpty() && host.charAt(0) == '[') { if (host.charAt(host.length()-1) == ']') { host = host.substring(1, host.length() -1); } @@ -466,7 +466,7 @@ class Inet6Address extends InetAddress { int scope_id) throws UnknownHostException { - if (host != null && host.length() > 0 && host.charAt(0) == '[') { + if (host != null && !host.isEmpty() && host.charAt(0) == '[') { if (host.charAt(host.length()-1) == ']') { host = host.substring(1, host.length() -1); } @@ -601,7 +601,7 @@ class Inet6Address extends InetAddress { boolean scope_ifname_set = gf.get("scope_ifname_set", false); String ifname = (String)gf.get("ifname", null); - if (ifname != null && !"".equals (ifname)) { + if (ifname != null && !ifname.isEmpty()) { try { scope_ifname = NetworkInterface.getByName(ifname); if (scope_ifname == null) { diff --git a/src/java.base/share/classes/java/net/InetAddress.java b/src/java.base/share/classes/java/net/InetAddress.java index 0741e625174..6976225a460 100644 --- a/src/java.base/share/classes/java/net/InetAddress.java +++ b/src/java.base/share/classes/java/net/InetAddress.java @@ -1187,7 +1187,7 @@ class InetAddress implements java.io.Serializable { */ public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException { - if (host != null && host.length() > 0 && host.charAt(0) == '[') { + if (host != null && !host.isEmpty() && host.charAt(0) == '[') { if (host.charAt(host.length()-1) == ']') { host = host.substring(1, host.length() -1); } @@ -1301,7 +1301,7 @@ class InetAddress implements java.io.Serializable { private static InetAddress[] getAllByName(String host, InetAddress reqAddr) throws UnknownHostException { - if (host == null || host.length() == 0) { + if (host == null || host.isEmpty()) { InetAddress[] ret = new InetAddress[1]; ret[0] = impl.loopbackAddress(); return ret; diff --git a/src/java.base/share/classes/java/net/SocketPermission.java b/src/java.base/share/classes/java/net/SocketPermission.java index d0bc09470d9..0e81ba4650a 100644 --- a/src/java.base/share/classes/java/net/SocketPermission.java +++ b/src/java.base/share/classes/java/net/SocketPermission.java @@ -460,7 +460,7 @@ public final class SocketPermission extends Permission } return; } else { - if (host.length() > 0) { + if (!host.isEmpty()) { // see if we are being initialized with an IP address. char ch = host.charAt(0); if (ch == ':' || Character.digit(ch, 16) != -1) { @@ -705,8 +705,7 @@ public final class SocketPermission extends Permission .orElse(b); } - return cdomain.length() != 0 && hdomain.length() != 0 - && cdomain.equals(hdomain); + return !cdomain.isEmpty() && !hdomain.isEmpty() && cdomain.equals(hdomain); } private boolean authorized(String cname, byte[] addr) { diff --git a/src/java.base/share/classes/java/net/URI.java b/src/java.base/share/classes/java/net/URI.java index 0f784961825..5b53c9334c9 100644 --- a/src/java.base/share/classes/java/net/URI.java +++ b/src/java.base/share/classes/java/net/URI.java @@ -1959,10 +1959,8 @@ public final class URI throws URISyntaxException { if (scheme != null) { - if ((path != null) - && ((path.length() > 0) && (path.charAt(0) != '/'))) - throw new URISyntaxException(s, - "Relative path in absolute URI"); + if (path != null && !path.isEmpty() && path.charAt(0) != '/') + throw new URISyntaxException(s, "Relative path in absolute URI"); } } @@ -2163,7 +2161,7 @@ public final class URI ru.port = base.port; String cp = (child.path == null) ? "" : child.path; - if ((cp.length() > 0) && (cp.charAt(0) == '/')) { + if (!cp.isEmpty() && cp.charAt(0) == '/') { // 5.2 (5): Child path is absolute ru.path = child.path; } else { @@ -2187,7 +2185,7 @@ public final class URI // o.w., return a new URI containing the normalized path. // private static URI normalize(URI u) { - if (u.isOpaque() || (u.path == null) || (u.path.length() == 0)) + if (u.isOpaque() || u.path == null || u.path.isEmpty()) return u; String np = normalize(u.path); diff --git a/src/java.base/share/classes/java/net/URL.java b/src/java.base/share/classes/java/net/URL.java index 81279425b4c..9d4abcc3901 100644 --- a/src/java.base/share/classes/java/net/URL.java +++ b/src/java.base/share/classes/java/net/URL.java @@ -1513,7 +1513,7 @@ public final class URL implements java.io.Serializable { String ref = (String)gf.get("ref", null); int hashCode = gf.get("hashCode", -1); if (authority == null - && ((host != null && host.length() > 0) || port != -1)) { + && ((host != null && !host.isEmpty()) || port != -1)) { if (host == null) host = ""; authority = (port == -1) ? host : host + ":" + port; @@ -1560,7 +1560,7 @@ public final class URL implements java.io.Serializable { // Construct authority part if (authority == null - && ((host != null && host.length() > 0) || port != -1)) { + && ((host != null && !host.isEmpty()) || port != -1)) { if (host == null) host = ""; authority = (port == -1) ? host : host + ":" + port; @@ -1716,7 +1716,7 @@ final class UrlDeserializedState { // pre-compute length of StringBuffer int len = protocol.length() + 1; - if (authority != null && authority.length() > 0) + if (authority != null && !authority.isEmpty()) len += 2 + authority.length(); if (file != null) { len += file.length(); @@ -1726,7 +1726,7 @@ final class UrlDeserializedState { StringBuilder result = new StringBuilder(len); result.append(protocol); result.append(":"); - if (authority != null && authority.length() > 0) { + if (authority != null && !authority.isEmpty()) { result.append("//"); result.append(authority); } diff --git a/src/java.base/share/classes/java/net/URLClassLoader.java b/src/java.base/share/classes/java/net/URLClassLoader.java index 0ed1f862f4f..d7f9c86f501 100644 --- a/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/src/java.base/share/classes/java/net/URLClassLoader.java @@ -743,7 +743,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { locUrl = ((JarURLConnection)urlConnection).getJarFileURL(); } String host = locUrl.getHost(); - if (host != null && (host.length() > 0)) + if (host != null && !host.isEmpty()) p = new SocketPermission(host, SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION); } diff --git a/src/java.base/share/classes/java/net/URLDecoder.java b/src/java.base/share/classes/java/net/URLDecoder.java index 69330299673..c65272d767d 100644 --- a/src/java.base/share/classes/java/net/URLDecoder.java +++ b/src/java.base/share/classes/java/net/URLDecoder.java @@ -133,7 +133,7 @@ public class URLDecoder { * @since 1.4 */ public static String decode(String s, String enc) throws UnsupportedEncodingException { - if (enc.length() == 0) { + if (enc.isEmpty()) { throw new UnsupportedEncodingException ("URLDecoder: empty string enc parameter"); } diff --git a/src/java.base/share/classes/java/net/URLPermission.java b/src/java.base/share/classes/java/net/URLPermission.java index 5d2e3605230..16f926213a6 100644 --- a/src/java.base/share/classes/java/net/URLPermission.java +++ b/src/java.base/share/classes/java/net/URLPermission.java @@ -409,7 +409,7 @@ public final class URLPermission extends Permission { char c = methods.charAt(i); if (c == ',') { String s = b.toString(); - if (s.length() > 0) + if (!s.isEmpty()) l.add(s); b = new StringBuilder(); } else if (c == ' ' || c == '\t') { @@ -423,7 +423,7 @@ public final class URLPermission extends Permission { } } String s = b.toString(); - if (s.length() > 0) + if (!s.isEmpty()) l.add(s); return l; } @@ -448,7 +448,7 @@ public final class URLPermission extends Permission { b.append(c); } else if (c == ',') { String s = b.toString(); - if (s.length() > 0) + if (!s.isEmpty()) l.add(s); b = new StringBuilder(); capitalizeNext = true; @@ -458,7 +458,7 @@ public final class URLPermission extends Permission { } } String s = b.toString(); - if (s.length() > 0) + if (!s.isEmpty()) l.add(s); return l; } diff --git a/src/java.base/share/classes/java/net/URLStreamHandler.java b/src/java.base/share/classes/java/net/URLStreamHandler.java index 4a45a69a294..a1a0861f8a8 100644 --- a/src/java.base/share/classes/java/net/URLStreamHandler.java +++ b/src/java.base/share/classes/java/net/URLStreamHandler.java @@ -235,7 +235,7 @@ public abstract class URLStreamHandler { start = i; // If the authority is defined then the path is defined by the // spec only; See RFC 2396 Section 5.2.4. - if (authority != null && authority.length() > 0) + if (authority != null && !authority.isEmpty()) path = ""; } @@ -247,7 +247,7 @@ public abstract class URLStreamHandler { if (start < limit) { if (spec.charAt(start) == '/') { path = spec.substring(start, limit); - } else if (path != null && path.length() > 0) { + } else if (path != null && !path.isEmpty()) { isRelPath = true; int ind = path.lastIndexOf('/'); String separator = ""; @@ -483,11 +483,11 @@ public abstract class URLStreamHandler { String s; return u.getProtocol() + ':' - + (((s = u.getAuthority()) != null && s.length() > 0) + + ((s = u.getAuthority()) != null && !s.isEmpty() ? "//" + s : "") - + (((s = u.getPath()) != null) ? s : "") - + (((s = u.getQuery()) != null) ? '?' + s : "") - + (((s = u.getRef()) != null) ? '#' + s : ""); + + ((s = u.getPath()) != null ? s : "") + + ((s = u.getQuery()) != null ? '?' + s : "") + + ((s = u.getRef()) != null ? '#' + s : ""); } /** @@ -544,7 +544,7 @@ public abstract class URLStreamHandler { */ String authority = null; String userInfo = null; - if (host != null && host.length() != 0) { + if (host != null && !host.isEmpty()) { authority = (port == -1) ? host : host + ":" + port; int at = host.lastIndexOf('@'); if (at != -1) { diff --git a/src/java.base/share/classes/java/nio/file/LinkPermission.java b/src/java.base/share/classes/java/nio/file/LinkPermission.java index a7c3cc8a4ca..c8385499640 100644 --- a/src/java.base/share/classes/java/nio/file/LinkPermission.java +++ b/src/java.base/share/classes/java/nio/file/LinkPermission.java @@ -104,7 +104,7 @@ public final class LinkPermission extends BasicPermission { public LinkPermission(String name, String actions) { super(name); checkName(name); - if (actions != null && actions.length() > 0) { + if (actions != null && !actions.isEmpty()) { throw new IllegalArgumentException("actions: " + actions); } } diff --git a/src/java.base/share/classes/java/security/AlgorithmParameterGenerator.java b/src/java.base/share/classes/java/security/AlgorithmParameterGenerator.java index cc9ad853bf9..0be6b0de33a 100644 --- a/src/java.base/share/classes/java/security/AlgorithmParameterGenerator.java +++ b/src/java.base/share/classes/java/security/AlgorithmParameterGenerator.java @@ -228,7 +228,7 @@ public class AlgorithmParameterGenerator { throws NoSuchAlgorithmException, NoSuchProviderException { Objects.requireNonNull(algorithm, "null algorithm name"); - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = Security.getImpl(algorithm, "AlgorithmParameterGenerator", diff --git a/src/java.base/share/classes/java/security/AlgorithmParameters.java b/src/java.base/share/classes/java/security/AlgorithmParameters.java index a5ed953e65b..930fa09f38e 100644 --- a/src/java.base/share/classes/java/security/AlgorithmParameters.java +++ b/src/java.base/share/classes/java/security/AlgorithmParameters.java @@ -209,7 +209,7 @@ public class AlgorithmParameters { throws NoSuchAlgorithmException, NoSuchProviderException { Objects.requireNonNull(algorithm, "null algorithm name"); - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters", provider); diff --git a/src/java.base/share/classes/java/security/KeyStore.java b/src/java.base/share/classes/java/security/KeyStore.java index fb7e90fed8f..8a4435e6adf 100644 --- a/src/java.base/share/classes/java/security/KeyStore.java +++ b/src/java.base/share/classes/java/security/KeyStore.java @@ -913,7 +913,7 @@ public class KeyStore { throws KeyStoreException, NoSuchProviderException { Objects.requireNonNull(type, "null type name"); - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); try { Object[] objs = Security.getImpl(type, "KeyStore", provider); diff --git a/src/java.base/share/classes/java/security/MessageDigest.java b/src/java.base/share/classes/java/security/MessageDigest.java index 4f4987ceb46..565f4349018 100644 --- a/src/java.base/share/classes/java/security/MessageDigest.java +++ b/src/java.base/share/classes/java/security/MessageDigest.java @@ -237,7 +237,7 @@ public abstract class MessageDigest extends MessageDigestSpi { throws NoSuchAlgorithmException, NoSuchProviderException { Objects.requireNonNull(algorithm, "null algorithm name"); - if (provider == null || provider.length() == 0) + if (provider == null || provider.isEmpty()) throw new IllegalArgumentException("missing provider"); Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); if (objs[0] instanceof MessageDigest) { diff --git a/src/java.base/share/classes/java/security/Permission.java b/src/java.base/share/classes/java/security/Permission.java index 0eb0496ce3b..e1c526e7a9e 100644 --- a/src/java.base/share/classes/java/security/Permission.java +++ b/src/java.base/share/classes/java/security/Permission.java @@ -222,7 +222,7 @@ public abstract class Permission implements Guard, java.io.Serializable { */ public String toString() { String actions = getActions(); - if ((actions == null) || (actions.length() == 0)) { // OPTIONAL + if (actions == null || actions.isEmpty()) { // OPTIONAL return "(\"" + getClass().getName() + "\" \"" + name + "\")"; } else { return "(\"" + getClass().getName() + "\" \"" + name + diff --git a/src/java.base/share/classes/java/security/Policy.java b/src/java.base/share/classes/java/security/Policy.java index 54663a5a0f8..5c13529c9dc 100644 --- a/src/java.base/share/classes/java/security/Policy.java +++ b/src/java.base/share/classes/java/security/Policy.java @@ -456,7 +456,7 @@ public abstract class Policy { throws NoSuchProviderException, NoSuchAlgorithmException { Objects.requireNonNull(type, "null type name"); - if (provider == null || provider.length() == 0) { + if (provider == null || provider.isEmpty()) { throw new IllegalArgumentException("missing provider"); } diff --git a/src/java.base/share/classes/java/security/SecureRandom.java b/src/java.base/share/classes/java/security/SecureRandom.java index 254f378aac6..09ecdf1c6e6 100644 --- a/src/java.base/share/classes/java/security/SecureRandom.java +++ b/src/java.base/share/classes/java/security/SecureRandom.java @@ -942,7 +942,7 @@ public class SecureRandom extends java.util.Random { } }); - if ((property == null) || (property.length() == 0)) { + if (property == null || property.isEmpty()) { throw new NoSuchAlgorithmException( "Null/empty securerandom.strongAlgorithms Security Property"); } diff --git a/src/java.base/share/classes/java/security/Security.java b/src/java.base/share/classes/java/security/Security.java index 5a560757897..3280acd0e7d 100644 --- a/src/java.base/share/classes/java/security/Security.java +++ b/src/java.base/share/classes/java/security/Security.java @@ -649,7 +649,7 @@ public final class Security { } } - if ((candidates == null) || (candidates.isEmpty())) + if (candidates == null || candidates.isEmpty()) return null; Object[] candidatesArray = candidates.toArray(); @@ -1005,11 +1005,11 @@ public final class Security { String algName = null; String attrName = null; - if (filterValue.length() == 0) { + if (filterValue.isEmpty()) { // The filterValue is an empty string. So the filterKey // should be in the format of .. algName = filterKey.substring(algIndex + 1).trim(); - if (algName.length() == 0) { + if (algName.isEmpty()) { // There must be a algorithm or type name. throw new InvalidParameterException("Invalid filter"); } @@ -1024,7 +1024,7 @@ public final class Security { throw new InvalidParameterException("Invalid filter"); } else { attrName = filterKey.substring(attrIndex + 1).trim(); - if (attrName.length() == 0) { + if (attrName.isEmpty()) { // There is no attribute name in the filter. throw new InvalidParameterException("Invalid filter"); } @@ -1070,7 +1070,7 @@ public final class Security { **/ public static Set getAlgorithms(String serviceName) { - if ((serviceName == null) || (serviceName.length() == 0) || + if ((serviceName == null) || (serviceName.isEmpty()) || (serviceName.endsWith("."))) { return Collections.emptySet(); } diff --git a/src/java.base/share/classes/java/security/Signature.java b/src/java.base/share/classes/java/security/Signature.java index 141237ad94b..001f740f07c 100644 --- a/src/java.base/share/classes/java/security/Signature.java +++ b/src/java.base/share/classes/java/security/Signature.java @@ -360,7 +360,7 @@ public abstract class Signature extends SignatureSpi { Objects.requireNonNull(algorithm, "null algorithm name"); if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) { // exception compatibility with existing code - if ((provider == null) || (provider.length() == 0)) { + if (provider == null || provider.isEmpty()) { throw new IllegalArgumentException("missing provider"); } Provider p = Security.getProvider(provider); diff --git a/src/java.base/share/classes/java/security/cert/TrustAnchor.java b/src/java.base/share/classes/java/security/cert/TrustAnchor.java index 8b765a29ced..78ff2f04e12 100644 --- a/src/java.base/share/classes/java/security/cert/TrustAnchor.java +++ b/src/java.base/share/classes/java/security/cert/TrustAnchor.java @@ -210,7 +210,7 @@ public class TrustAnchor { if (caName == null) throw new NullPointerException("the caName parameter must be " + "non-null"); - if (caName.length() == 0) + if (caName.isEmpty()) throw new IllegalArgumentException("the caName " + "parameter must be a non-empty String"); // check if caName is formatted correctly diff --git a/src/java.base/share/classes/java/text/AttributedString.java b/src/java.base/share/classes/java/text/AttributedString.java index fc62f5c71fd..2e6e0e72ff9 100644 --- a/src/java.base/share/classes/java/text/AttributedString.java +++ b/src/java.base/share/classes/java/text/AttributedString.java @@ -85,7 +85,7 @@ public class AttributedString { text = buffer.toString(); - if (text.length() > 0) { + if (!text.isEmpty()) { // Determine the runs, creating a new run when the attributes // differ. int offset = 0; @@ -144,7 +144,7 @@ public class AttributedString { } this.text = text; - if (text.length() == 0) { + if (text.isEmpty()) { if (attributes.isEmpty()) return; throw new IllegalArgumentException("Can't add attribute to 0-length text"); diff --git a/src/java.base/share/classes/java/text/CollationElementIterator.java b/src/java.base/share/classes/java/text/CollationElementIterator.java index 9da55b26625..22d100c1a10 100644 --- a/src/java.base/share/classes/java/text/CollationElementIterator.java +++ b/src/java.base/share/classes/java/text/CollationElementIterator.java @@ -125,7 +125,7 @@ public final class CollationElementIterator CollationElementIterator(String sourceText, RuleBasedCollator owner) { this.owner = owner; ordering = owner.getTables(); - if ( sourceText.length() != 0 ) { + if (!sourceText.isEmpty()) { NormalizerBase.Mode mode = CollatorUtilities.toNormalizerMode(owner.getDecomposition()); text = new NormalizerBase(sourceText, mode); diff --git a/src/java.base/share/classes/java/text/CompactNumberFormat.java b/src/java.base/share/classes/java/text/CompactNumberFormat.java index 4094dac389a..9cb43fcc8ee 100644 --- a/src/java.base/share/classes/java/text/CompactNumberFormat.java +++ b/src/java.base/share/classes/java/text/CompactNumberFormat.java @@ -799,7 +799,7 @@ public final class CompactNumberFormat extends NumberFormat { */ private void append(StringBuffer result, String string, FieldDelegate delegate, List positions) { - if (string.length() > 0) { + if (!string.isEmpty()) { int start = result.length(); result.append(string); for (int counter = 0; counter < positions.size(); counter++) { @@ -1213,7 +1213,7 @@ public final class CompactNumberFormat extends NumberFormat { } // If no 0s are specified in a non empty pattern, it is invalid - if (pattern.length() != 0 && zeros.isEmpty()) { + if (!pattern.isEmpty() && zeros.isEmpty()) { throw new IllegalArgumentException("Invalid pattern" + " [" + pattern + "]: all patterns must include digit" + " placement 0s"); diff --git a/src/java.base/share/classes/java/text/DecimalFormat.java b/src/java.base/share/classes/java/text/DecimalFormat.java index 47bc79aa43e..d9aec1b5fc1 100644 --- a/src/java.base/share/classes/java/text/DecimalFormat.java +++ b/src/java.base/share/classes/java/text/DecimalFormat.java @@ -1113,11 +1113,9 @@ public class DecimalFormat extends NumberFormat { // Records the need for adding prefix or suffix fastPathData.positiveAffixesRequired - = (positivePrefix.length() != 0) - || (positiveSuffix.length() != 0); + = !positivePrefix.isEmpty() || !positiveSuffix.isEmpty(); fastPathData.negativeAffixesRequired - = (negativePrefix.length() != 0) - || (negativeSuffix.length() != 0); + = !negativePrefix.isEmpty() || !negativeSuffix.isEmpty(); // Creates a cached char container for result, with max possible size. int maxNbIntegralDigits = 10; @@ -2062,7 +2060,7 @@ public class DecimalFormat extends NumberFormat { Format.Field signAttribute) { int start = result.length(); - if (string.length() > 0) { + if (!string.isEmpty()) { result.append(string); for (int counter = 0, max = positions.length; counter < max; counter++) { @@ -3042,7 +3040,7 @@ public class DecimalFormat extends NumberFormat { } else { string = symbols.getCurrencySymbol(); } - if (string.length() > 0) { + if (!string.isEmpty()) { if (positions == null) { positions = new ArrayList<>(2); } @@ -3613,7 +3611,7 @@ public class DecimalFormat extends NumberFormat { } } - if (pattern.length() == 0) { + if (pattern.isEmpty()) { posPrefixPattern = posSuffixPattern = ""; setMinimumIntegerDigits(0); setMaximumIntegerDigits(MAXIMUM_INTEGER_DIGITS); diff --git a/src/java.base/share/classes/java/text/DecimalFormatSymbols.java b/src/java.base/share/classes/java/text/DecimalFormatSymbols.java index 59e68600589..acaf3bfbcf1 100644 --- a/src/java.base/share/classes/java/text/DecimalFormatSymbols.java +++ b/src/java.base/share/classes/java/text/DecimalFormatSymbols.java @@ -663,7 +663,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable { // Check for empty country string separately because it's a valid // country ID for Locale (and used for the C locale), but not a valid // ISO 3166 country code, and exceptions are expensive. - if (locale.getCountry().length() > 0) { + if (!locale.getCountry().isEmpty()) { try { currency = Currency.getInstance(locale); } catch (IllegalArgumentException e) { diff --git a/src/java.base/share/classes/java/text/MergeCollation.java b/src/java.base/share/classes/java/text/MergeCollation.java index 4e5e5a53ae0..1bfcbf018ac 100644 --- a/src/java.base/share/classes/java/text/MergeCollation.java +++ b/src/java.base/share/classes/java/text/MergeCollation.java @@ -92,7 +92,7 @@ final class MergeCollation { int i; for (i = 0; i < patterns.size(); ++i) { PatternEntry entry = patterns.get(i); - if (entry.extension.length() != 0) { + if (!entry.extension.isEmpty()) { if (extList == null) extList = new ArrayList<>(); extList.add(entry); @@ -122,7 +122,7 @@ final class MergeCollation { private final PatternEntry findLastWithNoExtension(int i) { for (--i;i >= 0; --i) { PatternEntry entry = patterns.get(i); - if (entry.extension.length() == 0) { + if (entry.extension.isEmpty()) { return entry; } } diff --git a/src/java.base/share/classes/java/text/MessageFormat.java b/src/java.base/share/classes/java/text/MessageFormat.java index 4560abd822b..e54033cb8ff 100644 --- a/src/java.base/share/classes/java/text/MessageFormat.java +++ b/src/java.base/share/classes/java/text/MessageFormat.java @@ -1330,7 +1330,7 @@ public class MessageFormat extends Format { } arg = null; } - if (arg != null && arg.length() > 0) { + if (arg != null && !arg.isEmpty()) { result.append(arg); characterIterators.add( createAttributedCharacterIterator( @@ -1476,7 +1476,7 @@ public class MessageFormat extends Format { // now get the format Format newFormat = null; - if (segments[SEG_TYPE].length() != 0) { + if (!segments[SEG_TYPE].isEmpty()) { int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS); switch (type) { case TYPE_NULL: diff --git a/src/java.base/share/classes/java/text/PatternEntry.java b/src/java.base/share/classes/java/text/PatternEntry.java index 07af4b8aaeb..3e065dff403 100644 --- a/src/java.base/share/classes/java/text/PatternEntry.java +++ b/src/java.base/share/classes/java/text/PatternEntry.java @@ -141,7 +141,7 @@ class PatternEntry { if (showWhiteSpace) toAddTo.append(' '); appendQuoted(chars,toAddTo); - if (showExtension && extension.length() != 0) { + if (showExtension && !extension.isEmpty()) { toAddTo.append('/'); appendQuoted(extension,toAddTo); } diff --git a/src/java.base/share/classes/java/text/RBTableBuilder.java b/src/java.base/share/classes/java/text/RBTableBuilder.java index 99ac56ef56d..0210112f289 100644 --- a/src/java.base/share/classes/java/text/RBTableBuilder.java +++ b/src/java.base/share/classes/java/text/RBTableBuilder.java @@ -75,13 +75,10 @@ final class RBTableBuilder { * @exception ParseException If the rules format is incorrect. */ - public void build(String pattern, int decmp) throws ParseException - { - boolean isSource = true; - int i = 0; + public void build(String pattern, int decmp) throws ParseException { String expChars; String groupChars; - if (pattern.length() == 0) + if (pattern.isEmpty()) throw new ParseException("Build rules empty.", 0); // This array maps Unicode characters to their collation ordering @@ -119,8 +116,7 @@ final class RBTableBuilder { int order = 0; // Now walk though each entry and add it to my own tables - for (i = 0; i < mPattern.getCount(); ++i) - { + for (int i = 0; i < mPattern.getCount(); ++i) { PatternEntry entry = mPattern.getItemAt(i); if (entry != null) { groupChars = entry.getChars(); @@ -140,7 +136,7 @@ final class RBTableBuilder { order = increment(entry.getStrength(), order); expChars = entry.getExtension(); - if (expChars.length() != 0) { + if (!expChars.isEmpty()) { addExpandOrder(groupChars, expChars, order); } else if (groupChars.length() > 1) { char ch = groupChars.charAt(0); diff --git a/src/java.base/share/classes/java/time/ZoneId.java b/src/java.base/share/classes/java/time/ZoneId.java index 7f4ddbd4c8b..cfde1dd9952 100644 --- a/src/java.base/share/classes/java/time/ZoneId.java +++ b/src/java.base/share/classes/java/time/ZoneId.java @@ -372,7 +372,7 @@ public abstract class ZoneId implements Serializable { public static ZoneId ofOffset(String prefix, ZoneOffset offset) { Objects.requireNonNull(prefix, "prefix"); Objects.requireNonNull(offset, "offset"); - if (prefix.length() == 0) { + if (prefix.isEmpty()) { return offset; } diff --git a/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java b/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java index ca37005fe8a..69edf0230af 100644 --- a/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java +++ b/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java @@ -1439,7 +1439,7 @@ public final class DateTimeFormatterBuilder { */ public DateTimeFormatterBuilder appendLiteral(String literal) { Objects.requireNonNull(literal, "literal"); - if (literal.length() > 0) { + if (!literal.isEmpty()) { if (literal.length() == 1) { appendInternal(new CharLiteralPrinterParser(literal.charAt(0))); } else { @@ -1832,7 +1832,7 @@ public final class DateTimeFormatterBuilder { throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern); } String str = pattern.substring(start + 1, pos); - if (str.length() == 0) { + if (str.isEmpty()) { appendLiteral('\''); } else { appendLiteral(str.replace("''", "'")); @@ -4332,7 +4332,7 @@ public final class DateTimeFormatterBuilder { this.key = k; this.value = v; this.child = child; - if (k.length() == 0){ + if (k.isEmpty()) { c0 = 0xffff; } else { c0 = key.charAt(0); diff --git a/src/java.base/share/classes/java/util/Calendar.java b/src/java.base/share/classes/java/util/Calendar.java index b53f58f48a9..60ad816b56e 100644 --- a/src/java.base/share/classes/java/util/Calendar.java +++ b/src/java.base/share/classes/java/util/Calendar.java @@ -2232,7 +2232,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable names = new HashMap<>(); for (int i = 0; i < strings.length; i++) { - if (strings[i].length() == 0) { + if (strings[i].isEmpty()) { continue; } names.put(strings[i], i); diff --git a/src/java.base/share/classes/java/util/Locale.java b/src/java.base/share/classes/java/util/Locale.java index d1f27f9df41..cb309025d7d 100644 --- a/src/java.base/share/classes/java/util/Locale.java +++ b/src/java.base/share/classes/java/util/Locale.java @@ -1396,11 +1396,11 @@ public final class Locale implements Cloneable, Serializable { */ @Override public final String toString() { - boolean l = (baseLocale.getLanguage().length() != 0); - boolean s = (baseLocale.getScript().length() != 0); - boolean r = (baseLocale.getRegion().length() != 0); - boolean v = (baseLocale.getVariant().length() != 0); - boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0); + boolean l = !baseLocale.getLanguage().isEmpty(); + boolean s = !baseLocale.getScript().isEmpty(); + boolean r = !baseLocale.getRegion().isEmpty(); + boolean v = !baseLocale.getVariant().isEmpty(); + boolean e = localeExtensions != null && !localeExtensions.getID().isEmpty(); StringBuilder result = new StringBuilder(baseLocale.getLanguage()); if (r || (l && (v || s || e))) { @@ -1504,18 +1504,18 @@ public final class Locale implements Cloneable, Serializable { StringBuilder buf = new StringBuilder(); String subtag = tag.getLanguage(); - if (subtag.length() > 0) { + if (!subtag.isEmpty()) { buf.append(LanguageTag.canonicalizeLanguage(subtag)); } subtag = tag.getScript(); - if (subtag.length() > 0) { + if (!subtag.isEmpty()) { buf.append(LanguageTag.SEP); buf.append(LanguageTag.canonicalizeScript(subtag)); } subtag = tag.getRegion(); - if (subtag.length() > 0) { + if (!subtag.isEmpty()) { buf.append(LanguageTag.SEP); buf.append(LanguageTag.canonicalizeRegion(subtag)); } @@ -1534,7 +1534,7 @@ public final class Locale implements Cloneable, Serializable { } subtag = tag.getPrivateuse(); - if (subtag.length() > 0) { + if (!subtag.isEmpty()) { if (buf.length() > 0) { buf.append(LanguageTag.SEP); } @@ -1684,7 +1684,7 @@ public final class Locale implements Cloneable, Serializable { bldr.setLanguageTag(tag); BaseLocale base = bldr.getBaseLocale(); LocaleExtensions exts = bldr.getLocaleExtensions(); - if (exts == null && base.getVariant().length() > 0) { + if (exts == null && !base.getVariant().isEmpty()) { exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(), base.getRegion(), base.getVariant()); } @@ -1917,7 +1917,7 @@ public final class Locale implements Cloneable, Serializable { * @exception NullPointerException if inLocale is null */ public String getDisplayVariant(Locale inLocale) { - if (baseLocale.getVariant().length() == 0) + if (baseLocale.getVariant().isEmpty()) return ""; LocaleResources lr = LocaleProviderAdapter @@ -1998,14 +1998,14 @@ public final class Locale implements Cloneable, Serializable { // The display name consists of a main name, followed by qualifiers. // Typically, the format is "MainName (Qualifier, Qualifier)" but this // depends on what pattern is stored in the display locale. - String mainName = null; - String[] qualifierNames = null; + String mainName; + String[] qualifierNames; // The main name is the language, or if there is no language, the script, // then if no script, the country. If there is no language/script/country // (an anomalous situation) then the display name is simply the variant's // display name. - if (languageName.length() == 0 && scriptName.length() == 0 && countryName.length() == 0) { + if (languageName.isEmpty() && scriptName.isEmpty() && countryName.isEmpty()) { if (variantNames.length == 0) { return ""; } else { @@ -2013,13 +2013,13 @@ public final class Locale implements Cloneable, Serializable { } } ArrayList names = new ArrayList<>(4); - if (languageName.length() != 0) { + if (!languageName.isEmpty()) { names.add(languageName); } - if (scriptName.length() != 0) { + if (!scriptName.isEmpty()) { names.add(scriptName); } - if (countryName.length() != 0) { + if (!countryName.isEmpty()) { names.add(countryName); } if (variantNames.length != 0) { @@ -2309,7 +2309,7 @@ public final class Locale implements Cloneable, Serializable { String variant = (String)fields.get("variant", ""); String extStr = (String)fields.get("extensions", ""); baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant); - if (extStr.length() > 0) { + if (!extStr.isEmpty()) { try { InternalLocaleBuilder bldr = new InternalLocaleBuilder(); bldr.setExtensions(extStr); @@ -2367,13 +2367,13 @@ public final class Locale implements Cloneable, Serializable { LocaleExtensions extensions = null; // Special cases for backward compatibility support if (LocaleUtils.caseIgnoreMatch(language, "ja") - && script.length() == 0 + && script.isEmpty() && LocaleUtils.caseIgnoreMatch(country, "jp") && "JP".equals(variant)) { // ja_JP_JP -> u-ca-japanese (calendar = japanese) extensions = LocaleExtensions.CALENDAR_JAPANESE; } else if (LocaleUtils.caseIgnoreMatch(language, "th") - && script.length() == 0 + && script.isEmpty() && LocaleUtils.caseIgnoreMatch(country, "th") && "TH".equals(variant)) { // th_TH_TH -> u-nu-thai (numbersystem = thai) @@ -2806,7 +2806,7 @@ public final class Locale implements Cloneable, Serializable { public Locale build() { BaseLocale baseloc = localeBuilder.getBaseLocale(); LocaleExtensions extensions = localeBuilder.getLocaleExtensions(); - if (extensions == null && baseloc.getVariant().length() > 0) { + if (extensions == null && !baseloc.getVariant().isEmpty()) { extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(), baseloc.getRegion(), baseloc.getVariant()); } diff --git a/src/java.base/share/classes/java/util/ResourceBundle.java b/src/java.base/share/classes/java/util/ResourceBundle.java index a98c84f50ef..c854402b8d5 100644 --- a/src/java.base/share/classes/java/util/ResourceBundle.java +++ b/src/java.base/share/classes/java/util/ResourceBundle.java @@ -771,8 +771,8 @@ public abstract class ResourceBundle { @Override public String toString() { String l = locale.toString(); - if (l.length() == 0) { - if (locale.getVariant().length() != 0) { + if (l.isEmpty()) { + if (!locale.getVariant().isEmpty()) { l = "__" + locale.getVariant(); } else { l = "\"\""; @@ -2903,7 +2903,7 @@ public abstract class ResourceBundle { List bokmalList = new LinkedList<>(); for (Locale l : tmpList) { bokmalList.add(l); - if (l.getLanguage().length() == 0) { + if (l.getLanguage().isEmpty()) { break; } bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(), @@ -2921,7 +2921,7 @@ public abstract class ResourceBundle { } // Special handling for Chinese else if (language.equals("zh")) { - if (script.length() == 0 && region.length() > 0) { + if (script.isEmpty() && !region.isEmpty()) { // Supply script for users who want to use zh_Hans/zh_Hant // as bundle names (recommended for Java7+) switch (region) { @@ -2944,7 +2944,7 @@ public abstract class ResourceBundle { private static List getDefaultList(String language, String script, String region, String variant) { List variants = null; - if (variant.length() > 0) { + if (!variant.isEmpty()) { variants = new LinkedList<>(); int idx = variant.length(); while (idx != -1) { @@ -2960,14 +2960,14 @@ public abstract class ResourceBundle { list.add(Locale.getInstance(language, script, region, v, null)); } } - if (region.length() > 0) { + if (!region.isEmpty()) { list.add(Locale.getInstance(language, script, region, "", null)); } - if (script.length() > 0) { + if (!script.isEmpty()) { list.add(Locale.getInstance(language, script, "", "", null)); // Special handling for Chinese if (language.equals("zh")) { - if (region.length() == 0) { + if (region.isEmpty()) { // Supply region(country) for users who still package Chinese // bundles using old convension. switch (script) { @@ -2988,11 +2988,11 @@ public abstract class ResourceBundle { list.add(Locale.getInstance(language, "", region, v, null)); } } - if (region.length() > 0) { + if (!region.isEmpty()) { list.add(Locale.getInstance(language, "", region, "", null)); } } - if (language.length() > 0) { + if (!language.isEmpty()) { list.add(Locale.getInstance(language, "", "", "", null)); } // Add root locale at the end diff --git a/src/java.base/share/classes/java/util/Scanner.java b/src/java.base/share/classes/java/util/Scanner.java index bde2ae328eb..b36d9d1ec4e 100644 --- a/src/java.base/share/classes/java/util/Scanner.java +++ b/src/java.base/share/classes/java/util/Scanner.java @@ -1297,16 +1297,16 @@ public final class Scanner implements Iterator, Closeable { nanString = "\\Q" + dfs.getNaN() + "\\E"; infinityString = "\\Q" + dfs.getInfinity() + "\\E"; positivePrefix = df.getPositivePrefix(); - if (positivePrefix.length() > 0) + if (!positivePrefix.isEmpty()) positivePrefix = "\\Q" + positivePrefix + "\\E"; negativePrefix = df.getNegativePrefix(); - if (negativePrefix.length() > 0) + if (!negativePrefix.isEmpty()) negativePrefix = "\\Q" + negativePrefix + "\\E"; positiveSuffix = df.getPositiveSuffix(); - if (positiveSuffix.length() > 0) + if (!positiveSuffix.isEmpty()) positiveSuffix = "\\Q" + positiveSuffix + "\\E"; negativeSuffix = df.getNegativeSuffix(); - if (negativeSuffix.length() > 0) + if (!negativeSuffix.isEmpty()) negativeSuffix = "\\Q" + negativeSuffix + "\\E"; // Force rebuilding and recompilation of locale dependent diff --git a/src/java.base/share/classes/java/util/regex/Pattern.java b/src/java.base/share/classes/java/util/regex/Pattern.java index 153303c7f99..92c964fdefa 100644 --- a/src/java.base/share/classes/java/util/regex/Pattern.java +++ b/src/java.base/share/classes/java/util/regex/Pattern.java @@ -1390,7 +1390,7 @@ public final class Pattern localTCNCount = 0; // if length > 0, the Pattern is lazily compiled - if (pattern.length() == 0) { + if (pattern.isEmpty()) { root = new Start(lastAccept); matchRoot = lastAccept; compiled = true; @@ -1423,7 +1423,7 @@ public final class Pattern localCount = 0; localTCNCount = 0; - if (pattern.length() > 0) { + if (!pattern.isEmpty()) { compile(); } else { root = new Start(lastAccept); diff --git a/src/java.base/share/classes/javax/crypto/Cipher.java b/src/java.base/share/classes/javax/crypto/Cipher.java index cafd629cc27..a1cf22449e3 100644 --- a/src/java.base/share/classes/javax/crypto/Cipher.java +++ b/src/java.base/share/classes/javax/crypto/Cipher.java @@ -341,7 +341,7 @@ public class Cipher { throw new NoSuchAlgorithmException("Invalid transformation " + "format:" + transformation); } - if ((parts[0] == null) || (parts[0].length() == 0)) { + if ((parts[0] == null) || (parts[0].isEmpty())) { throw new NoSuchAlgorithmException("Invalid transformation:" + "algorithm not specified-" + transformation); @@ -445,10 +445,10 @@ public class Cipher { String alg = parts[0]; String mode = parts[1]; String pad = parts[2]; - if ((mode != null) && (mode.length() == 0)) { + if ((mode != null) && (mode.isEmpty())) { mode = null; } - if ((pad != null) && (pad.length() == 0)) { + if ((pad != null) && (pad.isEmpty())) { pad = null; } @@ -634,7 +634,7 @@ public class Cipher { if ((transformation == null) || transformation.isEmpty()) { throw new NoSuchAlgorithmException("Null or empty transformation"); } - if ((provider == null) || (provider.length() == 0)) { + if ((provider == null) || (provider.isEmpty())) { throw new IllegalArgumentException("Missing provider"); } Provider p = Security.getProvider(provider); diff --git a/src/java.base/share/classes/javax/crypto/SealedObject.java b/src/java.base/share/classes/javax/crypto/SealedObject.java index f5e2a644f28..5fbf97bc874 100644 --- a/src/java.base/share/classes/javax/crypto/SealedObject.java +++ b/src/java.base/share/classes/javax/crypto/SealedObject.java @@ -337,7 +337,7 @@ public class SealedObject implements Serializable { if (key == null) { throw new NullPointerException("key is null"); } - if (provider == null || provider.length() == 0) { + if (provider == null || provider.isEmpty()) { throw new IllegalArgumentException("missing provider"); } diff --git a/src/java.base/share/classes/javax/net/ssl/SSLSocketFactory.java b/src/java.base/share/classes/javax/net/ssl/SSLSocketFactory.java index 115d686cc9e..1115c48d8f3 100644 --- a/src/java.base/share/classes/javax/net/ssl/SSLSocketFactory.java +++ b/src/java.base/share/classes/javax/net/ssl/SSLSocketFactory.java @@ -133,7 +133,7 @@ public abstract class SSLSocketFactory extends SocketFactory String s = java.security.Security.getProperty(name); if (s != null) { s = s.trim(); - if (s.length() == 0) { + if (s.isEmpty()) { s = null; } } diff --git a/src/java.base/share/classes/javax/security/auth/PrivateCredentialPermission.java b/src/java.base/share/classes/javax/security/auth/PrivateCredentialPermission.java index fdd1d017986..f183a4eb2c0 100644 --- a/src/java.base/share/classes/javax/security/auth/PrivateCredentialPermission.java +++ b/src/java.base/share/classes/javax/security/auth/PrivateCredentialPermission.java @@ -312,7 +312,7 @@ public final class PrivateCredentialPermission extends Permission { private void init(String name) { - if (name == null || name.trim().length() == 0) { + if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("invalid empty name"); } diff --git a/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java b/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java index 564a7984551..b11f8943a15 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java @@ -98,13 +98,13 @@ public class ChoiceCallback implements Callback, java.io.Serializable { public ChoiceCallback(String prompt, String[] choices, int defaultChoice, boolean multipleSelectionsAllowed) { - if (prompt == null || prompt.length() == 0 || + if (prompt == null || prompt.isEmpty() || choices == null || choices.length == 0 || defaultChoice < 0 || defaultChoice >= choices.length) throw new IllegalArgumentException(); for (int i = 0; i < choices.length; i++) { - if (choices[i] == null || choices[i].length() == 0) + if (choices[i] == null || choices[i].isEmpty()) throw new IllegalArgumentException(); } diff --git a/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java b/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java index 99bb5f8c17f..78113195ebf 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java @@ -248,7 +248,7 @@ public class ConfirmationCallback implements Callback, java.io.Serializable { throw new IllegalArgumentException(); for (int i = 0; i < options.length; i++) { - if (options[i] == null || options[i].length() == 0) + if (options[i] == null || options[i].isEmpty()) throw new IllegalArgumentException(); } @@ -294,7 +294,7 @@ public class ConfirmationCallback implements Callback, java.io.Serializable { public ConfirmationCallback(String prompt, int messageType, int optionType, int defaultOption) { - if (prompt == null || prompt.length() == 0 || + if (prompt == null || prompt.isEmpty() || messageType < INFORMATION || messageType > ERROR || optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION) throw new IllegalArgumentException(); @@ -357,14 +357,14 @@ public class ConfirmationCallback implements Callback, java.io.Serializable { public ConfirmationCallback(String prompt, int messageType, String[] options, int defaultOption) { - if (prompt == null || prompt.length() == 0 || + if (prompt == null || prompt.isEmpty() || messageType < INFORMATION || messageType > ERROR || options == null || options.length == 0 || defaultOption < 0 || defaultOption >= options.length) throw new IllegalArgumentException(); for (int i = 0; i < options.length; i++) { - if (options[i] == null || options[i].length() == 0) + if (options[i] == null || options[i].isEmpty()) throw new IllegalArgumentException(); } diff --git a/src/java.base/share/classes/javax/security/auth/callback/NameCallback.java b/src/java.base/share/classes/javax/security/auth/callback/NameCallback.java index 5c289df2c43..bda3b59382b 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/NameCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/NameCallback.java @@ -62,7 +62,7 @@ public class NameCallback implements Callback, java.io.Serializable { * or if {@code prompt} has a length of 0. */ public NameCallback(String prompt) { - if (prompt == null || prompt.length() == 0) + if (prompt == null || prompt.isEmpty()) throw new IllegalArgumentException(); this.prompt = prompt; } @@ -82,8 +82,8 @@ public class NameCallback implements Callback, java.io.Serializable { * or if {@code defaultName} has a length of 0. */ public NameCallback(String prompt, String defaultName) { - if (prompt == null || prompt.length() == 0 || - defaultName == null || defaultName.length() == 0) + if (prompt == null || prompt.isEmpty() || + defaultName == null || defaultName.isEmpty()) throw new IllegalArgumentException(); this.prompt = prompt; diff --git a/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java b/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java index 63e52fea112..0611d7f0f99 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java @@ -67,7 +67,7 @@ public class PasswordCallback implements Callback, java.io.Serializable { * if {@code prompt} has a length of 0. */ public PasswordCallback(String prompt, boolean echoOn) { - if (prompt == null || prompt.length() == 0) + if (prompt == null || prompt.isEmpty()) throw new IllegalArgumentException(); this.prompt = prompt; diff --git a/src/java.base/share/classes/javax/security/auth/callback/TextInputCallback.java b/src/java.base/share/classes/javax/security/auth/callback/TextInputCallback.java index 0fea6a3c7d6..ccaf11b5470 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/TextInputCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/TextInputCallback.java @@ -63,7 +63,7 @@ public class TextInputCallback implements Callback, java.io.Serializable { * or if {@code prompt} has a length of 0. */ public TextInputCallback(String prompt) { - if (prompt == null || prompt.length() == 0) + if (prompt == null || prompt.isEmpty()) throw new IllegalArgumentException(); this.prompt = prompt; } @@ -83,8 +83,8 @@ public class TextInputCallback implements Callback, java.io.Serializable { * or if {@code defaultText} has a length of 0. */ public TextInputCallback(String prompt, String defaultText) { - if (prompt == null || prompt.length() == 0 || - defaultText == null || defaultText.length() == 0) + if (prompt == null || prompt.isEmpty() || + defaultText == null || defaultText.isEmpty()) throw new IllegalArgumentException(); this.prompt = prompt; diff --git a/src/java.base/share/classes/javax/security/auth/callback/TextOutputCallback.java b/src/java.base/share/classes/javax/security/auth/callback/TextOutputCallback.java index ba4551e3880..57f9278af17 100644 --- a/src/java.base/share/classes/javax/security/auth/callback/TextOutputCallback.java +++ b/src/java.base/share/classes/javax/security/auth/callback/TextOutputCallback.java @@ -74,7 +74,7 @@ public class TextOutputCallback implements Callback, java.io.Serializable { public TextOutputCallback(int messageType, String message) { if ((messageType != INFORMATION && messageType != WARNING && messageType != ERROR) || - message == null || message.length() == 0) + message == null || message.isEmpty()) throw new IllegalArgumentException(); this.messageType = messageType; diff --git a/src/java.base/share/classes/javax/security/auth/login/AppConfigurationEntry.java b/src/java.base/share/classes/javax/security/auth/login/AppConfigurationEntry.java index f567b3be871..2084e4e3f8c 100644 --- a/src/java.base/share/classes/javax/security/auth/login/AppConfigurationEntry.java +++ b/src/java.base/share/classes/javax/security/auth/login/AppConfigurationEntry.java @@ -75,7 +75,7 @@ public class AppConfigurationEntry { LoginModuleControlFlag controlFlag, Map options) { - if (loginModuleName == null || loginModuleName.length() == 0 || + if (loginModuleName == null || loginModuleName.isEmpty() || (controlFlag != LoginModuleControlFlag.REQUIRED && controlFlag != LoginModuleControlFlag.REQUISITE && controlFlag != LoginModuleControlFlag.SUFFICIENT && diff --git a/src/java.base/share/classes/javax/security/auth/login/Configuration.java b/src/java.base/share/classes/javax/security/auth/login/Configuration.java index e08bf3eb3d7..067b94cc398 100644 --- a/src/java.base/share/classes/javax/security/auth/login/Configuration.java +++ b/src/java.base/share/classes/javax/security/auth/login/Configuration.java @@ -418,7 +418,7 @@ public abstract class Configuration { throws NoSuchProviderException, NoSuchAlgorithmException { Objects.requireNonNull(type, "null type name"); - if (provider == null || provider.length() == 0) { + if (provider == null || provider.isEmpty()) { throw new IllegalArgumentException("missing provider"); } diff --git a/src/java.base/share/classes/javax/security/auth/login/LoginContext.java b/src/java.base/share/classes/javax/security/auth/login/LoginContext.java index deaf3aac426..820cb159318 100644 --- a/src/java.base/share/classes/javax/security/auth/login/LoginContext.java +++ b/src/java.base/share/classes/javax/security/auth/login/LoginContext.java @@ -300,7 +300,7 @@ public class LoginContext { public CallbackHandler run() throws Exception { String defaultHandler = java.security.Security.getProperty (DEFAULT_HANDLER); - if (defaultHandler == null || defaultHandler.length() == 0) + if (defaultHandler == null || defaultHandler.isEmpty()) return null; Class c = Class.forName( defaultHandler, true, diff --git a/src/java.base/share/classes/javax/security/cert/X509Certificate.java b/src/java.base/share/classes/javax/security/cert/X509Certificate.java index 232134037b6..f4fecae131a 100644 --- a/src/java.base/share/classes/javax/security/cert/X509Certificate.java +++ b/src/java.base/share/classes/javax/security/cert/X509Certificate.java @@ -210,7 +210,7 @@ public abstract class X509Certificate extends Certificate { * under JDK1.1. */ String className = X509Provider; - if (className == null || className.length() == 0) { + if (className == null || className.isEmpty()) { // shouldn't happen, but assume corrupted properties file // provide access to sun implementation className = "com.sun.security.cert.internal.x509.X509V1CertImpl"; diff --git a/src/java.base/share/classes/jdk/internal/jimage/decompressor/SignatureParser.java b/src/java.base/share/classes/jdk/internal/jimage/decompressor/SignatureParser.java index a9a1df29c33..9b65995f61f 100644 --- a/src/java.base/share/classes/jdk/internal/jimage/decompressor/SignatureParser.java +++ b/src/java.base/share/classes/jdk/internal/jimage/decompressor/SignatureParser.java @@ -60,7 +60,7 @@ public class SignatureParser { switch (c) { case 'L': { String pkg = arguments.get(arg_index); - if(pkg.length() > 0) { + if(!pkg.isEmpty()) { out.append(pkg).append("/"); } arg_index+=1; diff --git a/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java b/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java index 1284a3f129f..807f8e2adf2 100644 --- a/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java +++ b/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java @@ -168,7 +168,7 @@ public class StringSharingDecompressor implements ResourceDecompressor { int index = indices.get(argIndex); argIndex += 1; String pkg = reader.getString(index); - if (pkg.length() > 0) { + if (!pkg.isEmpty()) { pkg = pkg + "/"; byte[] encoded = getEncoded(pkg); buffer = safeAdd(buffer, encoded); diff --git a/src/java.base/share/classes/jdk/internal/jrtfs/JrtFileSystem.java b/src/java.base/share/classes/jdk/internal/jrtfs/JrtFileSystem.java index 6a75ff53112..4eaa4712f48 100644 --- a/src/java.base/share/classes/jdk/internal/jrtfs/JrtFileSystem.java +++ b/src/java.base/share/classes/jdk/internal/jrtfs/JrtFileSystem.java @@ -123,7 +123,7 @@ class JrtFileSystem extends FileSystem { StringBuilder sb = new StringBuilder(); sb.append(first); for (String path : more) { - if (path.length() > 0) { + if (!path.isEmpty()) { if (sb.length() > 0) { sb.append('/'); } diff --git a/src/java.base/share/classes/jdk/internal/jrtfs/JrtPath.java b/src/java.base/share/classes/jdk/internal/jrtfs/JrtPath.java index 81ef3b9af2a..39a22f640fe 100644 --- a/src/java.base/share/classes/jdk/internal/jrtfs/JrtPath.java +++ b/src/java.base/share/classes/jdk/internal/jrtfs/JrtPath.java @@ -88,7 +88,7 @@ final class JrtPath implements Path { @Override public final JrtPath getFileName() { - if (path.length() == 0) + if (path.isEmpty()) return this; if (path.length() == 1 && path.charAt(0) == '/') return null; @@ -210,7 +210,7 @@ final class JrtPath implements Path { if (o.equals(this)) { return new JrtPath(jrtfs, "", true); } - if (path.length() == 0) { + if (path.isEmpty()) { return o; } if (jrtfs != o.jrtfs || isAbsolute() != o.isAbsolute()) { @@ -262,16 +262,16 @@ final class JrtPath implements Path { @Override public final boolean isAbsolute() { - return path.length() > 0 && path.charAt(0) == '/'; + return !path.isEmpty() && path.charAt(0) == '/'; } @Override public final JrtPath resolve(Path other) { final JrtPath o = checkPath(other); - if (this.path.length() == 0 || o.isAbsolute()) { + if (this.path.isEmpty() || o.isAbsolute()) { return o; } - if (o.path.length() == 0) { + if (o.path.isEmpty()) { return this; } StringBuilder sb = new StringBuilder(path.length() + o.path.length() + 1); @@ -301,7 +301,7 @@ final class JrtPath implements Path { } int off = op.length(); if (off == 0) { - return tp.length() == 0; + return tp.isEmpty(); } // check match is on name boundary return tp.length() == off || tp.charAt(off) == '/' || diff --git a/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java b/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java index 5dfdba5e7d7..cde32e9788a 100644 --- a/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java +++ b/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java @@ -59,7 +59,7 @@ public class ClassLoaders { // -Xbootclasspath/a or -javaagent with Boot-Class-Path attribute String append = VM.getSavedProperty("jdk.boot.class.path.append"); BOOT_LOADER = - new BootClassLoader((append != null && append.length() > 0) + new BootClassLoader((append != null && !append.isEmpty()) ? new URLClassPath(append, true) : null); PLATFORM_LOADER = new PlatformClassLoader(BOOT_LOADER); @@ -70,7 +70,7 @@ public class ClassLoaders { // contrary, we drop this historic interpretation of the empty // string and instead treat it as unspecified. String cp = System.getProperty("java.class.path"); - if (cp == null || cp.length() == 0) { + if (cp == null || cp.isEmpty()) { String initialModuleName = System.getProperty("jdk.module.main"); cp = (initialModuleName == null) ? "" : null; } diff --git a/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java b/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java index 1dc4acd65b7..8bc63890415 100644 --- a/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java +++ b/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java @@ -190,7 +190,7 @@ public class URLClassPath { String element = (next == -1) ? cp.substring(off) : cp.substring(off, next); - if (element.length() > 0 || !skipEmptyElements) { + if (!element.isEmpty() || !skipEmptyElements) { URL url = toFileURL(element); if (url != null) path.add(url); } diff --git a/src/java.base/share/classes/jdk/internal/module/Checks.java b/src/java.base/share/classes/jdk/internal/module/Checks.java index 4d772df129a..3b7dd137225 100644 --- a/src/java.base/share/classes/jdk/internal/module/Checks.java +++ b/src/java.base/share/classes/jdk/internal/module/Checks.java @@ -62,22 +62,6 @@ public final class Checks { return name; } - /** - * Returns {@code true} if the given name is a legal module name. - */ - public static boolean isModuleName(String name) { - int next; - int off = 0; - while ((next = name.indexOf('.', off)) != -1) { - String id = name.substring(off, next); - if (!isJavaIdentifier(id)) - return false; - off = next+1; - } - String last = name.substring(off); - return isJavaIdentifier(last); - } - /** * Checks a name to ensure that it's a legal package name. * @@ -181,20 +165,20 @@ public final class Checks { } /** - * Returns true if the given char sequence is a legal Java identifier, + * Returns true if the given string is a legal Java identifier, * otherwise false. */ - private static boolean isJavaIdentifier(CharSequence cs) { - if (cs.length() == 0 || RESERVED.contains(cs)) + private static boolean isJavaIdentifier(String str) { + if (str.isEmpty() || RESERVED.contains(str)) return false; - int first = Character.codePointAt(cs, 0); + int first = Character.codePointAt(str, 0); if (!Character.isJavaIdentifierStart(first)) return false; int i = Character.charCount(first); - while (i < cs.length()) { - int cp = Character.codePointAt(cs, i); + while (i < str.length()) { + int cp = Character.codePointAt(str, i); if (!Character.isJavaIdentifierPart(cp)) return false; i += Character.charCount(cp); diff --git a/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java b/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java index b9138935435..de2d3e22929 100644 --- a/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java +++ b/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java @@ -604,7 +604,8 @@ public final class ModuleBootstrap { Set modules = new HashSet<>(); while (value != null) { for (String s : value.split(",")) { - if (s.length() > 0) modules.add(s); + if (!s.isEmpty()) + modules.add(s); } index++; value = getAndRemoveProperty(prefix + index); @@ -895,7 +896,7 @@ public final class ModuleBootstrap { List values = map.computeIfAbsent(key, k -> new ArrayList<>()); int ntargets = 0; for (String s : rhs.split(regex)) { - if (s.length() > 0) { + if (!s.isEmpty()) { values.add(s); ntargets++; } diff --git a/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java b/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java index 8571765f0d7..9a2817d7288 100644 --- a/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java +++ b/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java @@ -552,7 +552,7 @@ public final class ModulePatcher { public Stream list() throws IOException { return Files.walk(dir, Integer.MAX_VALUE) .map(f -> Resources.toResourceName(dir, f)) - .filter(s -> s.length() > 0); + .filter(s -> !s.isEmpty()); } } diff --git a/src/java.base/share/classes/jdk/internal/module/ModulePath.java b/src/java.base/share/classes/jdk/internal/module/ModulePath.java index c92ac32eea4..0718336093b 100644 --- a/src/java.base/share/classes/jdk/internal/module/ModulePath.java +++ b/src/java.base/share/classes/jdk/internal/module/ModulePath.java @@ -546,7 +546,7 @@ public class ModulePath implements ModuleFinder { = new BufferedReader(new InputStreamReader(in, "UTF-8")); String cn; while ((cn = nextLine(reader)) != null) { - if (cn.length() > 0) { + if (!cn.isEmpty()) { String pn = packageName(cn); if (!packages.contains(pn)) { String msg = "Provider class " + cn + " not in module"; @@ -599,7 +599,7 @@ public class ModulePath implements ModuleFinder { mn = Patterns.REPEATING_DOTS.matcher(mn).replaceAll("."); // drop leading dots - if (mn.length() > 0 && mn.charAt(0) == '.') + if (!mn.isEmpty() && mn.charAt(0) == '.') mn = Patterns.LEADING_DOTS.matcher(mn).replaceAll(""); // drop trailing dots diff --git a/src/java.base/share/classes/jdk/internal/module/Resources.java b/src/java.base/share/classes/jdk/internal/module/Resources.java index d224d1aba84..924f262d776 100644 --- a/src/java.base/share/classes/jdk/internal/module/Resources.java +++ b/src/java.base/share/classes/jdk/internal/module/Resources.java @@ -78,7 +78,7 @@ public final class Resources { String s = dir.relativize(file) .toString() .replace(File.separatorChar, '/'); - if (s.length() > 0 && Files.isDirectory(file)) + if (!s.isEmpty() && Files.isDirectory(file)) s += "/"; return s; } diff --git a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java index 945292d8614..14eba5aceef 100644 --- a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java +++ b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java @@ -83,7 +83,7 @@ public final class SystemModuleFinders { if (value == null) { USE_FAST_PATH = true; } else { - USE_FAST_PATH = (value.length() > 0) && !Boolean.parseBoolean(value); + USE_FAST_PATH = !value.isEmpty() && !Boolean.parseBoolean(value); } } diff --git a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/TypePath.java b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/TypePath.java index ae588db91a5..964d84a9d36 100644 --- a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/TypePath.java +++ b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/TypePath.java @@ -147,7 +147,7 @@ public final class TypePath { * @return the corresponding TypePath object, or {@literal null} if the path is empty. */ public static TypePath fromString(final String typePath) { - if (typePath == null || typePath.length() == 0) { + if (typePath == null || typePath.isEmpty()) { return null; } int typePathLength = typePath.length(); diff --git a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckMethodAdapter.java b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckMethodAdapter.java index 7c22c8c237c..4bc3fa520ac 100644 --- a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckMethodAdapter.java +++ b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckMethodAdapter.java @@ -1314,7 +1314,7 @@ public class CheckMethodAdapter extends MethodVisitor { * @param message the message to use in case of error. */ static void checkMethodIdentifier(final int version, final String name, final String message) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IllegalArgumentException(INVALID + message + MUST_NOT_BE_NULL_OR_EMPTY); } if ((version & 0xFFFF) >= Opcodes.V1_5) { @@ -1347,7 +1347,7 @@ public class CheckMethodAdapter extends MethodVisitor { * @param message the message to use in case of error. */ static void checkInternalName(final int version, final String name, final String message) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IllegalArgumentException(INVALID + message + MUST_NOT_BE_NULL_OR_EMPTY); } if (name.charAt(0) == '[') { @@ -1457,7 +1457,7 @@ public class CheckMethodAdapter extends MethodVisitor { * @param descriptor the string to be checked. */ static void checkMethodDescriptor(final int version, final String descriptor) { - if (descriptor == null || descriptor.length() == 0) { + if (descriptor == null || descriptor.isEmpty()) { throw new IllegalArgumentException("Invalid method descriptor (must not be null or empty)"); } if (descriptor.charAt(0) != '(' || descriptor.length() < 3) { diff --git a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckSignatureAdapter.java b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckSignatureAdapter.java index f67eeee1b6f..dc26b37f255 100644 --- a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckSignatureAdapter.java +++ b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/util/CheckSignatureAdapter.java @@ -365,7 +365,7 @@ public class CheckSignatureAdapter extends SignatureVisitor { } private void checkClassName(final String name, final String message) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IllegalArgumentException(INVALID + message + " (must not be null or empty)"); } for (int i = 0; i < name.length(); ++i) { @@ -377,7 +377,7 @@ public class CheckSignatureAdapter extends SignatureVisitor { } private void checkIdentifier(final String name, final String message) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IllegalArgumentException(INVALID + message + " (must not be null or empty)"); } for (int i = 0; i < name.length(); ++i) { diff --git a/src/java.base/share/classes/jdk/internal/reflect/UnsafeFieldAccessorImpl.java b/src/java.base/share/classes/jdk/internal/reflect/UnsafeFieldAccessorImpl.java index d75db5374cb..1c6fd0046a5 100644 --- a/src/java.base/share/classes/jdk/internal/reflect/UnsafeFieldAccessorImpl.java +++ b/src/java.base/share/classes/jdk/internal/reflect/UnsafeFieldAccessorImpl.java @@ -151,10 +151,10 @@ abstract class UnsafeFieldAccessorImpl extends FieldAccessorImpl { if (isFinal) err += " final"; err += " " + field.getType().getName() + " field " + getQualifiedFieldName() + " to "; - if (attemptedValue.length() > 0) { + if (!attemptedValue.isEmpty()) { err += "(" + attemptedType + ")" + attemptedValue; } else { - if (attemptedType.length() > 0) + if (!attemptedType.isEmpty()) err += attemptedType; else err += "null value"; diff --git a/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java b/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java index f0d14a886a5..d41b09f5fce 100644 --- a/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java +++ b/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java @@ -291,7 +291,7 @@ public class JarIndex { while((line = br.readLine()) != null && !line.endsWith(".jar")); for(;line != null; line = br.readLine()) { - if (line.length() == 0) + if (line.isEmpty()) continue; if (line.endsWith(".jar")) { diff --git a/src/java.base/share/classes/jdk/internal/util/xml/PropertiesDefaultHandler.java b/src/java.base/share/classes/jdk/internal/util/xml/PropertiesDefaultHandler.java index ff4d9ea17c8..3df193734d4 100644 --- a/src/java.base/share/classes/jdk/internal/util/xml/PropertiesDefaultHandler.java +++ b/src/java.base/share/classes/jdk/internal/util/xml/PropertiesDefaultHandler.java @@ -103,7 +103,7 @@ public class PropertiesDefaultHandler extends DefaultHandler { writer.writeStartDocument(); writer.writeDTD(PROPS_DTD_DECL); writer.writeStartElement(ELEMENT_ROOT); - if (comment != null && comment.length() > 0) { + if (comment != null && !comment.isEmpty()) { writer.writeStartElement(ELEMENT_COMMENT); writer.writeCharacters(comment); writer.writeEndElement(); diff --git a/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java b/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java index 3182abacd7d..b50b1293fb7 100644 --- a/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java +++ b/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java @@ -1591,7 +1591,7 @@ public abstract class Parser { str = name(false); // PI target name may not be empty string [#2.6] // PI target name 'XML' is reserved [#2.6] - if ((str.length() == 0) + if ((str.isEmpty()) || (mXml.name.equals(str.toLowerCase()) == true)) { panic(FAULT); } diff --git a/src/java.base/share/classes/jdk/internal/util/xml/impl/XMLStreamWriterImpl.java b/src/java.base/share/classes/jdk/internal/util/xml/impl/XMLStreamWriterImpl.java index fb4dde6be17..20a3af833a2 100644 --- a/src/java.base/share/classes/jdk/internal/util/xml/impl/XMLStreamWriterImpl.java +++ b/src/java.base/share/classes/jdk/internal/util/xml/impl/XMLStreamWriterImpl.java @@ -205,7 +205,7 @@ public class XMLStreamWriterImpl implements XMLStreamWriter { * @throws XMLStreamException */ public void writeStartElement(String localName) throws XMLStreamException { - if (localName == null || localName.length() == 0) { + if (localName == null || localName.isEmpty()) { throw new XMLStreamException("Local Name cannot be null or empty"); } @@ -420,7 +420,7 @@ public class XMLStreamWriterImpl implements XMLStreamWriter { } private void writeXMLContent(String content) throws XMLStreamException { - if ((content != null) && (content.length() > 0)) { + if (content != null && !content.isEmpty()) { writeXMLContent(content, _escapeCharacters, // boolean = escapeChars false); // false = escapeDoubleQuotes diff --git a/src/java.base/share/classes/sun/invoke/util/BytecodeName.java b/src/java.base/share/classes/sun/invoke/util/BytecodeName.java index 26b4076213d..8ba6840f1b8 100644 --- a/src/java.base/share/classes/sun/invoke/util/BytecodeName.java +++ b/src/java.base/share/classes/sun/invoke/util/BytecodeName.java @@ -451,7 +451,7 @@ public class BytecodeName { * @return true if the name is non-empty and all of its characters are safe */ public static boolean isSafeBytecodeName(String s) { - if (s.length() == 0) return false; + if (s.isEmpty()) return false; // check occurrences of each DANGEROUS char for (char xc : DANGEROUS_CHARS_A) { if (xc == ESCAPE_C) continue; // not really that dangerous @@ -476,7 +476,7 @@ public class BytecodeName { } private static String mangle(String s) { - if (s.length() == 0) + if (s.isEmpty()) return NULL_ESCAPE; // build this lazily, when we first need an escape: diff --git a/src/java.base/share/classes/sun/net/TransferProtocolClient.java b/src/java.base/share/classes/sun/net/TransferProtocolClient.java index daa929ad3ef..e0b866e68cc 100644 --- a/src/java.base/share/classes/sun/net/TransferProtocolClient.java +++ b/src/java.base/share/classes/sun/net/TransferProtocolClient.java @@ -76,7 +76,7 @@ public class TransferProtocolClient extends NetworkClient { System.out.print(response); } - if (response.length() == 0) { + if (response.isEmpty()) { code = -1; } else { try { diff --git a/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java b/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java index cce643a1b09..5cf7f30d7cf 100644 --- a/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java +++ b/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java @@ -433,7 +433,7 @@ public class FtpClient extends sun.net.ftp.FtpClient { logger.finest("Server [" + serverAddr + "] --> " + response); } - if (response.length() == 0) { + if (response.isEmpty()) { code = -1; } else { try { @@ -1049,7 +1049,7 @@ public class FtpClient extends sun.net.ftp.FtpClient { if (!isConnected()) { throw new sun.net.ftp.FtpProtocolException("Not connected yet", FtpReplyCode.BAD_SEQUENCE); } - if (user == null || user.length() == 0) { + if (user == null || user.isEmpty()) { throw new IllegalArgumentException("User name can't be null or empty"); } tryLogin(user, password); @@ -1088,7 +1088,7 @@ public class FtpClient extends sun.net.ftp.FtpClient { if (!isConnected()) { throw new sun.net.ftp.FtpProtocolException("Not connected yet", FtpReplyCode.BAD_SEQUENCE); } - if (user == null || user.length() == 0) { + if (user == null || user.isEmpty()) { throw new IllegalArgumentException("User name can't be null or empty"); } tryLogin(user, password); @@ -1152,7 +1152,7 @@ public class FtpClient extends sun.net.ftp.FtpClient { * @exception FtpProtocolException */ public sun.net.ftp.FtpClient changeDirectory(String remoteDirectory) throws sun.net.ftp.FtpProtocolException, IOException { - if (remoteDirectory == null || "".equals(remoteDirectory)) { + if (remoteDirectory == null || remoteDirectory.isEmpty()) { throw new IllegalArgumentException("directory can't be null or empty"); } @@ -1738,7 +1738,7 @@ public class FtpClient extends sun.net.ftp.FtpClient { * @throws IOException if an error occurs during the transmission. */ public long getSize(String path) throws sun.net.ftp.FtpProtocolException, IOException { - if (path == null || path.length() == 0) { + if (path == null || path.isEmpty()) { throw new IllegalArgumentException("path can't be null or empty"); } issueCommandCheck("SIZE " + path); diff --git a/src/java.base/share/classes/sun/net/spi/DefaultProxySelector.java b/src/java.base/share/classes/sun/net/spi/DefaultProxySelector.java index 2f726c6817c..75a226ae7e0 100644 --- a/src/java.base/share/classes/sun/net/spi/DefaultProxySelector.java +++ b/src/java.base/share/classes/sun/net/spi/DefaultProxySelector.java @@ -238,7 +238,7 @@ public class DefaultProxySelector extends ProxySelector { if (phost != null && phost.length() != 0) break; } - if (phost == null || phost.length() == 0) { + if (phost == null || phost.isEmpty()) { /** * No system property defined for that * protocol. Let's check System Proxy @@ -267,7 +267,7 @@ public class DefaultProxySelector extends ProxySelector { nprop.hostsSource = null; nprop.pattern = null; } - } else if (nphosts.length() != 0) { + } else if (!nphosts.isEmpty()) { // add the required default patterns // but only if property no set. If it // is empty, leave empty. diff --git a/src/java.base/share/classes/sun/net/www/HeaderParser.java b/src/java.base/share/classes/sun/net/www/HeaderParser.java index f9db1df64de..a4b2ab50497 100644 --- a/src/java.base/share/classes/sun/net/www/HeaderParser.java +++ b/src/java.base/share/classes/sun/net/www/HeaderParser.java @@ -226,7 +226,7 @@ public class HeaderParser { for (int i=0; k.hasNext(); i++) { String key = k.next(); String val = findValue (i); - if (val != null && "".equals (val)) { + if (val != null && val.isEmpty()) { val = null; } sb.append(" {").append(key).append(val == null ? "" : "," + val) diff --git a/src/java.base/share/classes/sun/net/www/MimeEntry.java b/src/java.base/share/classes/sun/net/www/MimeEntry.java index 44b7c49b3fa..5690db0fb78 100644 --- a/src/java.base/share/classes/sun/net/www/MimeEntry.java +++ b/src/java.base/share/classes/sun/net/www/MimeEntry.java @@ -201,9 +201,7 @@ public class MimeEntry implements Cloneable { } private boolean isStarred(String typeName) { - return (typeName != null) - && (typeName.length() > 0) - && (typeName.endsWith("/*")); + return typeName != null && typeName.endsWith("/*"); } /** @@ -300,7 +298,7 @@ public class MimeEntry implements Cloneable { } String extensions = getExtensionsAsList(); - if (extensions.length() > 0) { + if (!extensions.isEmpty()) { sj.add("file_extensions=" + extensions); } diff --git a/src/java.base/share/classes/sun/net/www/MimeLauncher.java b/src/java.base/share/classes/sun/net/www/MimeLauncher.java index a2cfefab33c..452e3a1e4d0 100644 --- a/src/java.base/share/classes/sun/net/www/MimeLauncher.java +++ b/src/java.base/share/classes/sun/net/www/MimeLauncher.java @@ -162,7 +162,7 @@ class MimeLauncher extends Thread { location the application. If a valid path is not found, it returns false else true. */ private boolean findExecutablePath(String str) { - if (str == null || str.length() == 0) { + if (str == null || str.isEmpty()) { return false; } diff --git a/src/java.base/share/classes/sun/net/www/ParseUtil.java b/src/java.base/share/classes/sun/net/www/ParseUtil.java index 9ff0c2a4f6c..92f2965b136 100644 --- a/src/java.base/share/classes/sun/net/www/ParseUtil.java +++ b/src/java.base/share/classes/sun/net/www/ParseUtil.java @@ -536,8 +536,7 @@ public final class ParseUtil { throws URISyntaxException { if (scheme != null) { - if ((path != null) - && ((path.length() > 0) && (path.charAt(0) != '/'))) + if (path != null && !path.isEmpty() && path.charAt(0) != '/') throw new URISyntaxException(s, "Relative path in absolute URI"); } diff --git a/src/java.base/share/classes/sun/net/www/http/HttpClient.java b/src/java.base/share/classes/sun/net/www/http/HttpClient.java index 57d734e5166..8b1a81a6df1 100644 --- a/src/java.base/share/classes/sun/net/www/http/HttpClient.java +++ b/src/java.base/share/classes/sun/net/www/http/HttpClient.java @@ -603,7 +603,7 @@ public class HttpClient extends NetworkClient { StringBuilder result = new StringBuilder(128); result.append(url.getProtocol()); result.append(":"); - if (url.getAuthority() != null && url.getAuthority().length() > 0) { + if (url.getAuthority() != null && !url.getAuthority().isEmpty()) { result.append("//"); result.append(url.getAuthority()); } @@ -619,7 +619,7 @@ public class HttpClient extends NetworkClient { } else { fileName = url.getFile(); - if ((fileName == null) || (fileName.length() == 0)) { + if ((fileName == null) || (fileName.isEmpty())) { fileName = "/"; } else if (fileName.charAt(0) == '?') { /* HTTP/1.1 spec says in 5.1.2. about Request-URI: diff --git a/src/java.base/share/classes/sun/net/www/protocol/ftp/FtpURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/ftp/FtpURLConnection.java index 6abb4de2778..228af24e81d 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/ftp/FtpURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/ftp/FtpURLConnection.java @@ -341,7 +341,7 @@ public class FtpURLConnection extends URLConnection { path.charAt(0) == '/') { path = path.substring(1); } - if (path == null || path.length() == 0) { + if (path == null || path.isEmpty()) { path = "./"; } if (!path.endsWith("/")) { @@ -555,7 +555,7 @@ public class FtpURLConnection extends URLConnection { } decodePath(url.getPath()); - if (filename == null || filename.length() == 0) { + if (filename == null || filename.isEmpty()) { throw new IOException("illegal filename for a PUT"); } try { diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java index 725a1f89880..5aa670fded9 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java @@ -248,7 +248,7 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone this.realm = realm; String urlPath = url.getPath(); - if (urlPath.length() == 0) + if (urlPath.isEmpty()) this.path = urlPath; else { this.path = reducePath (urlPath); diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java b/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java index 7d49792b099..077a95e3d47 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java @@ -279,7 +279,7 @@ class DigestAuthentication extends AuthenticationInfo { if (s == null || !s.equals("true")) return false; String newNonce = p.findValue ("nonce"); - if (newNonce == null || "".equals(newNonce)) { + if (newNonce == null || newNonce.isEmpty()) { return false; } params.setNonce (newNonce); @@ -323,7 +323,7 @@ class DigestAuthentication extends AuthenticationInfo { + authMethod.substring(1).toLowerCase(); } String algorithm = p.findValue("algorithm"); - if (algorithm == null || "".equals(algorithm)) { + if (algorithm == null || algorithm.isEmpty()) { algorithm = "MD5"; // The default, accoriding to rfc2069 } params.setAlgorithm (algorithm); @@ -451,7 +451,7 @@ class DigestAuthentication extends AuthenticationInfo { } /* Check if there is a nextnonce field */ String nextnonce = p.findValue ("nextnonce"); - if (nextnonce != null && ! "".equals(nextnonce)) { + if (nextnonce != null && !nextnonce.isEmpty()) { params.setNonce (nextnonce); } diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index ad728fb3da1..16e548dc588 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -3026,7 +3026,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { // Filtering only if there is a cookie handler. [Assumption: the // cookie handler will store/retrieve the HttpOnly cookies] - if (cookieHandler == null || value.length() == 0) + if (cookieHandler == null || value.isEmpty()) return value; JavaNetHttpCookieAccess access = diff --git a/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java b/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java index 06c0e491465..50cdc97cdfd 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -143,7 +143,7 @@ final class HttpsClient extends HttpClient String cipherString = GetPropertyAction.privilegedGetProperty("https.cipherSuites"); - if (cipherString == null || "".equals(cipherString)) { + if (cipherString == null || cipherString.isEmpty()) { ciphers = null; } else { StringTokenizer tokenizer; @@ -167,7 +167,7 @@ final class HttpsClient extends HttpClient String protocolString = GetPropertyAction.privilegedGetProperty("https.protocols"); - if (protocolString == null || "".equals(protocolString)) { + if (protocolString == null || protocolString.isEmpty()) { protocols = null; } else { StringTokenizer tokenizer; @@ -187,7 +187,7 @@ final class HttpsClient extends HttpClient private String getUserAgent() { String userAgent = GetPropertyAction.privilegedGetProperty("https.agent"); - if (userAgent == null || userAgent.length() == 0) { + if (userAgent == null || userAgent.isEmpty()) { userAgent = "JSSE"; } return userAgent; diff --git a/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java index c7446082edd..29dac993a8d 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java @@ -66,7 +66,7 @@ public class JavaRuntimeURLConnection extends URLConnection { JavaRuntimeURLConnection(URL url) throws IOException { super(url); String path = url.getPath(); - if (path.length() == 0 || path.charAt(0) != '/') + if (path.isEmpty() || path.charAt(0) != '/') throw new MalformedURLException(url + " missing path or /"); if (path.length() == 1) { this.module = null; diff --git a/src/java.base/share/classes/sun/nio/ch/Net.java b/src/java.base/share/classes/sun/nio/ch/Net.java index 856efce30b9..fe8b12670e2 100644 --- a/src/java.base/share/classes/sun/nio/ch/Net.java +++ b/src/java.base/share/classes/sun/nio/ch/Net.java @@ -403,14 +403,8 @@ public class Net { public static boolean isFastTcpLoopbackRequested() { String loopbackProp = GetPropertyAction - .privilegedGetProperty("jdk.net.useFastTcpLoopback"); - boolean enable; - if ("".equals(loopbackProp)) { - enable = true; - } else { - enable = Boolean.parseBoolean(loopbackProp); - } - return enable; + .privilegedGetProperty("jdk.net.useFastTcpLoopback", "false"); + return loopbackProp.isEmpty() ? true : Boolean.parseBoolean(loopbackProp); } // -- Socket operations -- diff --git a/src/java.base/share/classes/sun/nio/fs/AbstractFileSystemProvider.java b/src/java.base/share/classes/sun/nio/fs/AbstractFileSystemProvider.java index 0e325414f5d..679f5857132 100644 --- a/src/java.base/share/classes/sun/nio/fs/AbstractFileSystemProvider.java +++ b/src/java.base/share/classes/sun/nio/fs/AbstractFileSystemProvider.java @@ -73,7 +73,7 @@ public abstract class AbstractFileSystemProvider extends FileSystemProvider { throws IOException { String[] s = split(attribute); - if (s[0].length() == 0) + if (s[0].isEmpty()) throw new IllegalArgumentException(attribute); DynamicFileAttributeView view = getFileAttributeView(file, s[0], options); if (view == null) @@ -86,7 +86,7 @@ public abstract class AbstractFileSystemProvider extends FileSystemProvider { throws IOException { String[] s = split(attributes); - if (s[0].length() == 0) + if (s[0].isEmpty()) throw new IllegalArgumentException(attributes); DynamicFileAttributeView view = getFileAttributeView(file, s[0], options); if (view == null) diff --git a/src/java.base/share/classes/sun/nio/fs/AbstractUserDefinedFileAttributeView.java b/src/java.base/share/classes/sun/nio/fs/AbstractUserDefinedFileAttributeView.java index 3886aa1b114..a349b08ccf6 100644 --- a/src/java.base/share/classes/sun/nio/fs/AbstractUserDefinedFileAttributeView.java +++ b/src/java.base/share/classes/sun/nio/fs/AbstractUserDefinedFileAttributeView.java @@ -83,7 +83,7 @@ abstract class AbstractUserDefinedFileAttributeView names = list(); break; } else { - if (name.length() == 0) + if (name.isEmpty()) throw new IllegalArgumentException(); names.add(name); } diff --git a/src/java.base/share/classes/sun/security/jca/GetInstance.java b/src/java.base/share/classes/sun/security/jca/GetInstance.java index a5e5602dc4d..fd513c47edb 100644 --- a/src/java.base/share/classes/sun/security/jca/GetInstance.java +++ b/src/java.base/share/classes/sun/security/jca/GetInstance.java @@ -75,7 +75,7 @@ public class GetInstance { public static Service getService(String type, String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { - if ((provider == null) || (provider.length() == 0)) { + if (provider == null || provider.isEmpty()) { throw new IllegalArgumentException("missing provider"); } Provider p = Providers.getProviderList().getProvider(provider); diff --git a/src/java.base/share/classes/sun/security/jca/ProviderConfig.java b/src/java.base/share/classes/sun/security/jca/ProviderConfig.java index 2f52c8b2ca8..ffa06f51fb5 100644 --- a/src/java.base/share/classes/sun/security/jca/ProviderConfig.java +++ b/src/java.base/share/classes/sun/security/jca/ProviderConfig.java @@ -114,7 +114,7 @@ final class ProviderConfig { } private boolean hasArgument() { - return argument.length() != 0; + return !argument.isEmpty(); } // should we try to load this provider? diff --git a/src/java.base/share/classes/sun/security/jca/ProviderList.java b/src/java.base/share/classes/sun/security/jca/ProviderList.java index 68597c891b2..5b17366d5de 100644 --- a/src/java.base/share/classes/sun/security/jca/ProviderList.java +++ b/src/java.base/share/classes/sun/security/jca/ProviderList.java @@ -175,7 +175,7 @@ public final class ProviderList { while ((entry = Security.getProperty("security.provider." + i)) != null) { entry = entry.trim(); - if (entry.length() == 0) { + if (entry.isEmpty()) { System.err.println("invalid entry for " + "security.provider." + i); break; @@ -200,7 +200,7 @@ public final class ProviderList { // Load config entries for use when getInstance is called entry = Security.getProperty("jdk.security.provider.preferred"); - if (entry != null && (entry = entry.trim()).length() > 0) { + if (entry != null && !(entry = entry.trim()).isEmpty()) { String[] entries = entry.split(","); if (ProviderList.preferredPropList == null) { ProviderList.preferredPropList = new PreferredList(); diff --git a/src/java.base/share/classes/sun/security/provider/ConfigFile.java b/src/java.base/share/classes/sun/security/provider/ConfigFile.java index 450a4292cff..080a44f8c89 100644 --- a/src/java.base/share/classes/sun/security/provider/ConfigFile.java +++ b/src/java.base/share/classes/sun/security/provider/ConfigFile.java @@ -626,7 +626,7 @@ public final class ConfigFile extends Configuration { return url.openStream(); } catch (Exception e) { String file = url.getPath(); - if (url.getHost().length() > 0) { // For Windows UNC + if (!url.getHost().isEmpty()) { // For Windows UNC file = "//" + url.getHost() + file; } if (debugConfig != null) { @@ -651,7 +651,7 @@ public final class ConfigFile extends Configuration { return value; } String s = PropertyExpander.expand(value); - if (s == null || s.length() == 0) { + if (s == null || s.isEmpty()) { throw ioException( "Configuration.Error.Line.line.system.property.value.expanded.to.empty.value", linenum, value); diff --git a/src/java.base/share/classes/sun/security/provider/PolicyParser.java b/src/java.base/share/classes/sun/security/provider/PolicyParser.java index 017f667698f..3edb35a3a9f 100644 --- a/src/java.base/share/classes/sun/security/provider/PolicyParser.java +++ b/src/java.base/share/classes/sun/security/provider/PolicyParser.java @@ -391,9 +391,9 @@ public class PolicyParser { out.print("keystore \""); out.print(keyStoreUrlString); out.print('"'); - if (keyStoreType != null && keyStoreType.length() > 0) + if (keyStoreType != null && !keyStoreType.isEmpty()) out.print(", \"" + keyStoreType + "\""); - if (keyStoreProvider != null && keyStoreProvider.length() > 0) + if (keyStoreProvider != null && !keyStoreProvider.isEmpty()) out.print(", \"" + keyStoreProvider + "\""); out.println(";"); out.println(); @@ -446,7 +446,7 @@ public class PolicyParser { String alias = aliases.nextToken().trim(); if (alias.equals(",")) cctr++; - else if (alias.length() > 0) + else if (!alias.isEmpty()) actr++; } if (actr <= cctr) diff --git a/src/java.base/share/classes/sun/security/provider/SeedGenerator.java b/src/java.base/share/classes/sun/security/provider/SeedGenerator.java index ac3a9f86a1a..d4360724ac7 100644 --- a/src/java.base/share/classes/sun/security/provider/SeedGenerator.java +++ b/src/java.base/share/classes/sun/security/provider/SeedGenerator.java @@ -113,7 +113,7 @@ abstract class SeedGenerator { + "generator: " + e.toString()); } } - } else if (egdSource.length() != 0) { + } else if (!egdSource.isEmpty()) { try { instance = new URLSeedGenerator(egdSource); if (debug != null) { diff --git a/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java b/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java index c68c9c530b1..b0d82dadbf4 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java +++ b/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java @@ -440,7 +440,7 @@ final class CertificateMessage { // It is not necessary to check the certificate update if // endpoint identification is enabled. String identityAlg = chc.sslConfig.identificationProtocol; - if ((identityAlg == null || identityAlg.length() == 0) && + if ((identityAlg == null || identityAlg.isEmpty()) && !isIdentityEquivalent(x509Certs[0], chc.reservedServerCerts[0])) { chc.conContext.fatal(Alert.BAD_CERTIFICATE, diff --git a/src/java.base/share/classes/sun/security/ssl/ClientHello.java b/src/java.base/share/classes/sun/security/ssl/ClientHello.java index ba4456207b2..96bbef5db59 100644 --- a/src/java.base/share/classes/sun/security/ssl/ClientHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ClientHello.java @@ -491,7 +491,7 @@ final class ClientHello { // It is fine to move on with abbreviate handshake if // endpoint identification is enabled. String identityAlg = chc.sslConfig.identificationProtocol; - if ((identityAlg == null || identityAlg.length() == 0)) { + if (identityAlg == null || identityAlg.isEmpty()) { if (isEmsAvailable) { if (!session.useExtendedMasterSecret) { // perform full handshake instead diff --git a/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java index 2318c53200b..8bc3e95bcac 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java @@ -253,7 +253,7 @@ final class DHKeyExchange { static { String property = GetPropertyAction.privilegedGetProperty( "jdk.tls.ephemeralDHKeySize"); - if (property == null || property.length() == 0) { + if (property == null || property.isEmpty()) { useLegacyEphemeralDHKeys = false; useSmartEphemeralDHKeys = false; customizedDHKeySize = -1; diff --git a/src/java.base/share/classes/sun/security/ssl/SSLAlgorithmConstraints.java b/src/java.base/share/classes/sun/security/ssl/SSLAlgorithmConstraints.java index dc206d07398..f6d1e3575af 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLAlgorithmConstraints.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLAlgorithmConstraints.java @@ -237,7 +237,7 @@ final class SSLAlgorithmConstraints implements AlgorithmConstraints { public boolean permits(Set primitives, String algorithm, AlgorithmParameters parameters) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { throw new IllegalArgumentException( "No algorithm name specified"); } @@ -276,7 +276,7 @@ final class SSLAlgorithmConstraints implements AlgorithmConstraints { public final boolean permits(Set primitives, String algorithm, Key key, AlgorithmParameters parameters) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { throw new IllegalArgumentException( "No algorithm name specified"); } diff --git a/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java index 5fb11e701fe..6482c7a323f 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java @@ -436,7 +436,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { "System property " + propertyName + " is set to '" + property + "'"); } - if (property != null && property.length() != 0) { + if (property != null && !property.isEmpty()) { // remove double quote marks from beginning/end of the property if (property.length() > 1 && property.charAt(0) == '"' && property.charAt(property.length() - 1) == '"') { @@ -444,7 +444,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { } } - if (property != null && property.length() != 0) { + if (property != null && !property.isEmpty()) { String[] cipherSuiteNames = property.split(","); Collection cipherSuites = new ArrayList<>(cipherSuiteNames.length); @@ -845,7 +845,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { return; } - if (property.length() != 0) { + if (!property.isEmpty()) { // remove double quote marks from beginning/end of the property if (property.length() > 1 && property.charAt(0) == '"' && property.charAt(property.length() - 1) == '"') { @@ -853,7 +853,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { } } - if (property.length() != 0) { + if (!property.isEmpty()) { String[] protocols = property.split(","); for (int i = 0; i < protocols.length; i++) { protocols[i] = protocols[i].trim(); @@ -1109,7 +1109,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { KeyStore ks = null; char[] passwd = null; try { - if (defaultKeyStore.length() != 0 && + if (!defaultKeyStore.isEmpty() && !NONE.equals(defaultKeyStore)) { fs = AccessController.doPrivileged( new PrivilegedExceptionAction() { @@ -1121,7 +1121,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { } String defaultKeyStorePassword = props.get("keyStorePasswd"); - if (defaultKeyStorePassword.length() != 0) { + if (!defaultKeyStorePassword.isEmpty()) { passwd = defaultKeyStorePassword.toCharArray(); } @@ -1132,7 +1132,7 @@ public abstract class SSLContextImpl extends SSLContextSpi { if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) { SSLLogger.finest("init keystore"); } - if (defaultKeyStoreProvider.length() == 0) { + if (defaultKeyStoreProvider.isEmpty()) { ks = KeyStore.getInstance(defaultKeyStoreType); } else { ks = KeyStore.getInstance(defaultKeyStoreType, @@ -1561,7 +1561,7 @@ final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager // check endpoint identity String identityAlg = sslSocket.getSSLParameters(). getEndpointIdentificationAlgorithm(); - if (identityAlg != null && identityAlg.length() != 0) { + if (identityAlg != null && !identityAlg.isEmpty()) { String hostname = session.getPeerHost(); X509TrustManagerImpl.checkIdentity( hostname, chain[0], identityAlg); @@ -1601,7 +1601,7 @@ final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager // check endpoint identity String identityAlg = engine.getSSLParameters(). getEndpointIdentificationAlgorithm(); - if (identityAlg != null && identityAlg.length() != 0) { + if (identityAlg != null && !identityAlg.isEmpty()) { String hostname = session.getPeerHost(); X509TrustManagerImpl.checkIdentity( hostname, chain[0], identityAlg); diff --git a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java index ffd397e2bcc..0a19de26169 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java @@ -1203,7 +1203,7 @@ public final class SSLSocketImpl synchronized void doneConnect() throws IOException { // In server mode, it is not necessary to set host and serverNames. // Otherwise, would require a reverse DNS lookup to get the hostname. - if ((peerHost == null) || (peerHost.length() == 0)) { + if (peerHost == null || peerHost.isEmpty()) { boolean useNameService = trustNameService && conContext.sslConfig.isClientMode; useImplicitHost(useNameService); @@ -1238,8 +1238,7 @@ public final class SSLSocketImpl JavaNetInetAddressAccess jna = SharedSecrets.getJavaNetInetAddressAccess(); String originalHostname = jna.getOriginalHostName(inetAddress); - if ((originalHostname != null) && - (originalHostname.length() != 0)) { + if (originalHostname != null && !originalHostname.isEmpty()) { this.peerHost = originalHostname; if (conContext.sslConfig.serverNames.isEmpty() && diff --git a/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java b/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java index ad17f1a4e90..b1c11a66ea7 100644 --- a/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java @@ -483,7 +483,7 @@ final class SupportedGroupsExtension { // default groups and preferences will be used. String property = GetPropertyAction .privilegedGetProperty("jdk.tls.namedGroups"); - if (property != null && property.length() != 0) { + if (property != null && !property.isEmpty()) { // remove double quote marks from beginning/end of the property if (property.length() > 1 && property.charAt(0) == '"' && property.charAt(property.length() - 1) == '"') { @@ -492,7 +492,7 @@ final class SupportedGroupsExtension { } ArrayList groupList; - if (property != null && property.length() != 0) { + if (property != null && !property.isEmpty()) { String[] groups = property.split(","); groupList = new ArrayList<>(groups.length); for (String group : groups) { diff --git a/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java b/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java index dfdb54b6dea..a891c53894b 100644 --- a/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java @@ -148,7 +148,7 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager "null or zero-length certificate chain"); } - if (authType == null || authType.length() == 0) { + if (authType == null || authType.isEmpty()) { throw new IllegalArgumentException( "null or zero-length authentication type"); } @@ -229,7 +229,7 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager // check endpoint identity String identityAlg = sslSocket.getSSLParameters(). getEndpointIdentificationAlgorithm(); - if (identityAlg != null && identityAlg.length() != 0) { + if (identityAlg != null && !identityAlg.isEmpty()) { checkIdentity(session, trustedChain[0], identityAlg, isClient, getRequestedServerNames(socket), chainsToPublicCA); } @@ -287,7 +287,7 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager // check endpoint identity String identityAlg = engine.getSSLParameters(). getEndpointIdentificationAlgorithm(); - if (identityAlg != null && identityAlg.length() != 0) { + if (identityAlg != null && !identityAlg.isEmpty()) { checkIdentity(session, trustedChain[0], identityAlg, isClient, getRequestedServerNames(engine), chainsToPublicCA); } @@ -448,7 +448,7 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager private static void checkIdentity(String hostname, X509Certificate cert, String algorithm, boolean chainsToPublicCA) throws CertificateException { - if (algorithm != null && algorithm.length() != 0) { + if (algorithm != null && !algorithm.isEmpty()) { // if IPv6 strip off the "[]" if ((hostname != null) && hostname.startsWith("[") && hostname.endsWith("]")) { diff --git a/src/java.base/share/classes/sun/security/tools/PathList.java b/src/java.base/share/classes/sun/security/tools/PathList.java index 1bd9cb76e41..69caeaf90f9 100644 --- a/src/java.base/share/classes/sun/security/tools/PathList.java +++ b/src/java.base/share/classes/sun/security/tools/PathList.java @@ -46,9 +46,9 @@ public class PathList { * @return the resulting path */ public static String appendPath(String pathTo, String pathFrom) { - if (pathTo == null || pathTo.length() == 0) { + if (pathTo == null || pathTo.isEmpty()) { return pathFrom; - } else if (pathFrom == null || pathFrom.length() == 0) { + } else if (pathFrom == null || pathFrom.isEmpty()) { return pathTo; } else { return pathTo + File.pathSeparator + pathFrom; diff --git a/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java b/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java index 2f7bc0c16af..bc021411f0c 100644 --- a/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java +++ b/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java @@ -75,7 +75,7 @@ public abstract class AbstractAlgorithmConstraints static boolean checkAlgorithm(String[] algorithms, String algorithm, AlgorithmDecomposer decomposer) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { throw new IllegalArgumentException("No algorithm name specified"); } diff --git a/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java b/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java index 4e1e6241dc5..ee97d461ac1 100644 --- a/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java +++ b/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java @@ -80,7 +80,7 @@ public class AlgorithmDecomposer { * Please override the method if need to support more name pattern. */ public Set decompose(String algorithm) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { return new HashSet<>(); } @@ -167,7 +167,7 @@ public class AlgorithmDecomposer { * message digest algorithm name to avoid overly complicated checking. */ public static Set decomposeOneHash(String algorithm) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { return new HashSet<>(); } diff --git a/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java b/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java index 4c50289532e..60699404070 100644 --- a/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java +++ b/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java @@ -135,7 +135,7 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { public final boolean permits(Set primitives, String algorithm, Key key, AlgorithmParameters parameters) { - if (algorithm == null || algorithm.length() == 0) { + if (algorithm == null || algorithm.isEmpty()) { throw new IllegalArgumentException("No algorithm name specified"); } @@ -188,7 +188,7 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { } // check the signature algorithm with parameters - if (algorithm != null && algorithm.length() != 0) { + if (algorithm != null && !algorithm.isEmpty()) { if (!permits(primitives, algorithm, parameters)) { return false; } diff --git a/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java b/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java index 35b06aa554c..4342c655cee 100644 --- a/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java +++ b/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java @@ -423,7 +423,7 @@ public class SignatureFileVerifier { // This means we have an error in finding weak algorithms, run in // debug mode to see permittedAlgs map's values. - if (w.length() == 0) { + if (w.isEmpty()) { return "Unknown Algorithm(s)"; } diff --git a/src/java.base/share/classes/sun/security/x509/AVA.java b/src/java.base/share/classes/sun/security/x509/AVA.java index e7c94521d43..107189bc47c 100644 --- a/src/java.base/share/classes/sun/security/x509/AVA.java +++ b/src/java.base/share/classes/sun/security/x509/AVA.java @@ -1245,7 +1245,7 @@ class AVAKeyword { } boolean number = false; - if (keyword.length() != 0) { + if (!keyword.isEmpty()) { char ch = keyword.charAt(0); if ((ch >= '0') && (ch <= '9')) { number = true; @@ -1285,7 +1285,7 @@ class AVAKeyword { return ak.keyword; } } else { - if (keywordString.length() == 0) { + if (keywordString.isEmpty()) { throw new IllegalArgumentException("keyword cannot be empty"); } keywordString = keywordString.trim(); diff --git a/src/java.base/share/classes/sun/security/x509/DNSName.java b/src/java.base/share/classes/sun/security/x509/DNSName.java index f0b8c27576a..5ddce75833b 100644 --- a/src/java.base/share/classes/sun/security/x509/DNSName.java +++ b/src/java.base/share/classes/sun/security/x509/DNSName.java @@ -72,7 +72,7 @@ public class DNSName implements GeneralNameInterface { * @throws IOException if the name is not a valid DNSName subjectAltName */ public DNSName(String name) throws IOException { - if (name == null || name.length() == 0) + if (name == null || name.isEmpty()) throw new IOException("DNSName must not be null or empty"); if (name.contains(" ")) throw new IOException("DNSName with blank components is not permitted"); diff --git a/src/java.base/share/classes/sun/security/x509/IPAddressName.java b/src/java.base/share/classes/sun/security/x509/IPAddressName.java index 50f045758be..f9451744059 100644 --- a/src/java.base/share/classes/sun/security/x509/IPAddressName.java +++ b/src/java.base/share/classes/sun/security/x509/IPAddressName.java @@ -125,7 +125,7 @@ public class IPAddressName implements GeneralNameInterface { */ public IPAddressName(String name) throws IOException { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IOException("IPAddress cannot be null or empty"); } if (name.charAt(name.length() - 1) == '/') { diff --git a/src/java.base/share/classes/sun/security/x509/RDN.java b/src/java.base/share/classes/sun/security/x509/RDN.java index 2ee060930db..f73dc813aa4 100644 --- a/src/java.base/share/classes/sun/security/x509/RDN.java +++ b/src/java.base/share/classes/sun/security/x509/RDN.java @@ -121,7 +121,7 @@ public class RDN { * Plus sign is a separator */ String avaString = name.substring(avaOffset, nextPlus); - if (avaString.length() == 0) { + if (avaString.isEmpty()) { throw new IOException("empty AVA in RDN \"" + name + "\""); } @@ -141,7 +141,7 @@ public class RDN { // parse last or only AVA String avaString = name.substring(avaOffset); - if (avaString.length() == 0) { + if (avaString.isEmpty()) { throw new IOException("empty AVA in RDN \"" + name + "\""); } AVA ava = new AVA(new StringReader(avaString), keywordMap); @@ -199,7 +199,7 @@ public class RDN { * Plus sign is a separator */ String avaString = name.substring(avaOffset, nextPlus); - if (avaString.length() == 0) { + if (avaString.isEmpty()) { throw new IOException("empty AVA in RDN \"" + name + "\""); } @@ -217,7 +217,7 @@ public class RDN { // parse last or only AVA String avaString = name.substring(avaOffset); - if (avaString.length() == 0) { + if (avaString.isEmpty()) { throw new IOException("empty AVA in RDN \"" + name + "\""); } AVA ava = new AVA(new StringReader(avaString), AVA.RFC2253, keywordMap); diff --git a/src/java.base/share/classes/sun/security/x509/RFC822Name.java b/src/java.base/share/classes/sun/security/x509/RFC822Name.java index 8644254e5b5..916b1beeecb 100644 --- a/src/java.base/share/classes/sun/security/x509/RFC822Name.java +++ b/src/java.base/share/classes/sun/security/x509/RFC822Name.java @@ -79,12 +79,12 @@ public class RFC822Name implements GeneralNameInterface * @throws IOException if name is not valid */ public void parseName(String name) throws IOException { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { throw new IOException("RFC822Name may not be null or empty"); } // See if domain is a valid domain name String domain = name.substring(name.indexOf('@')+1); - if (domain.length() == 0) { + if (domain.isEmpty()) { throw new IOException("RFC822Name may not end with @"); } else { //An RFC822 NameConstraint could start with a ., although diff --git a/src/java.base/share/classes/sun/security/x509/X500Name.java b/src/java.base/share/classes/sun/security/x509/X500Name.java index 6d5bf78cd9d..5d26140d1a8 100644 --- a/src/java.base/share/classes/sun/security/x509/X500Name.java +++ b/src/java.base/share/classes/sun/security/x509/X500Name.java @@ -865,7 +865,7 @@ public class X500Name implements GeneralNameInterface, Principal { */ private void parseDN(String input, Map keywordMap) throws IOException { - if (input == null || input.length() == 0) { + if (input == null || input.isEmpty()) { names = new RDN[0]; return; } @@ -937,7 +937,7 @@ public class X500Name implements GeneralNameInterface, Principal { } private void parseRFC2253DN(String dnString) throws IOException { - if (dnString.length() == 0) { + if (dnString.isEmpty()) { names = new RDN[0]; return; } diff --git a/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java b/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java index 8a53ba85728..5570be6f144 100644 --- a/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java +++ b/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java @@ -370,7 +370,7 @@ public class X509CRLImpl extends X509CRL implements DerEncoder { throw new CRLException("Uninitialized CRL"); } Signature sigVerf = null; - if (sigProvider.length() == 0) { + if (sigProvider.isEmpty()) { sigVerf = Signature.getInstance(sigAlgId.getName()); } else { sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider); @@ -495,7 +495,7 @@ public class X509CRLImpl extends X509CRL implements DerEncoder { if (readOnly) throw new CRLException("cannot over-write existing CRL"); Signature sigEngine = null; - if ((provider == null) || (provider.length() == 0)) + if (provider == null || provider.isEmpty()) sigEngine = Signature.getInstance(algorithm); else sigEngine = Signature.getInstance(algorithm, provider); diff --git a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java index 30dcd1db685..52cbe71e88f 100644 --- a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java +++ b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java @@ -429,7 +429,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { } // Verify the signature ... Signature sigVerf = null; - if (sigProvider.length() == 0) { + if (sigProvider.isEmpty()) { sigVerf = Signature.getInstance(algId.getName()); } else { sigVerf = Signature.getInstance(algId.getName(), sigProvider); @@ -598,7 +598,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { throw new CertificateEncodingException( "cannot over-write existing certificate"); Signature sigEngine = null; - if ((provider == null) || (provider.length() == 0)) + if (provider == null || provider.isEmpty()) sigEngine = Signature.getInstance(algorithm); else sigEngine = Signature.getInstance(algorithm, provider); diff --git a/src/java.base/share/classes/sun/util/locale/InternalLocaleBuilder.java b/src/java.base/share/classes/sun/util/locale/InternalLocaleBuilder.java index b5e0fb47865..a3bf018f03c 100644 --- a/src/java.base/share/classes/sun/util/locale/InternalLocaleBuilder.java +++ b/src/java.base/share/classes/sun/util/locale/InternalLocaleBuilder.java @@ -331,7 +331,7 @@ public final class InternalLocaleBuilder { done.add(key); } } - if (privateuse != null && privateuse.length() > 0) { + if (privateuse != null && !privateuse.isEmpty()) { // privateuse string contains prefix, e.g. "x-abc-def" if (extensions == null) { extensions = new HashMap<>(1); @@ -406,19 +406,19 @@ public final class InternalLocaleBuilder { // Validate base locale fields before updating internal state. // LocaleExtensions always store validated/canonicalized values, // so no checks are necessary. - if (language.length() > 0 && !LanguageTag.isLanguage(language)) { + if (!language.isEmpty() && !LanguageTag.isLanguage(language)) { throw new LocaleSyntaxException("Ill-formed language: " + language); } - if (script.length() > 0 && !LanguageTag.isScript(script)) { + if (!script.isEmpty() && !LanguageTag.isScript(script)) { throw new LocaleSyntaxException("Ill-formed script: " + script); } - if (region.length() > 0 && !LanguageTag.isRegion(region)) { + if (!region.isEmpty() && !LanguageTag.isRegion(region)) { throw new LocaleSyntaxException("Ill-formed region: " + region); } - if (variant.length() > 0) { + if (!variant.isEmpty()) { int errIdx = checkVariants(variant, BaseLocale.SEP); if (errIdx != -1) { throw new LocaleSyntaxException("Ill-formed variant: " + variant, errIdx); diff --git a/src/java.base/share/classes/sun/util/locale/LanguageTag.java b/src/java.base/share/classes/sun/util/locale/LanguageTag.java index 3fd7f7dbe5e..a2d745794ab 100644 --- a/src/java.base/share/classes/sun/util/locale/LanguageTag.java +++ b/src/java.base/share/classes/sun/util/locale/LanguageTag.java @@ -212,7 +212,7 @@ public class LanguageTag { if (!itr.isDone() && !sts.isError()) { String s = itr.current(); sts.errorIndex = itr.currentStart(); - if (s.length() == 0) { + if (s.isEmpty()) { sts.errorMsg = "Empty subtag"; } else { sts.errorMsg = "Invalid subtag: " + s; @@ -454,7 +454,7 @@ public class LanguageTag { variant = ""; } - if (variant.length() > 0) { + if (!variant.isEmpty()) { List variants = null; StringTokenIterator varitr = new StringTokenIterator(variant, BaseLocale.SEP); while (!varitr.isDone()) { @@ -527,7 +527,7 @@ public class LanguageTag { tag.privateuse = privateuse; } - if (tag.language.length() == 0 && (hasSubtag || privateuse == null)) { + if (tag.language.isEmpty() && (hasSubtag || privateuse == null)) { // use lang "und" when 1) no language is available AND // 2) any of other subtags other than private use are available or // no private use tag is available @@ -712,18 +712,18 @@ public class LanguageTag { public String toString() { StringBuilder sb = new StringBuilder(); - if (language.length() > 0) { + if (!language.isEmpty()) { sb.append(language); for (String extlang : extlangs) { sb.append(SEP).append(extlang); } - if (script.length() > 0) { + if (!script.isEmpty()) { sb.append(SEP).append(script); } - if (region.length() > 0) { + if (!region.isEmpty()) { sb.append(SEP).append(region); } @@ -735,7 +735,7 @@ public class LanguageTag { sb.append(SEP).append(extension); } } - if (privateuse.length() > 0) { + if (!privateuse.isEmpty()) { if (sb.length() > 0) { sb.append(SEP); } diff --git a/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java b/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java index 4dbec843ea7..7ec5ab6709f 100644 --- a/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java +++ b/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java @@ -402,7 +402,7 @@ public final class LocaleMatcher { } String rangeForRegex = range.replace("*", "\\p{Alnum}*"); - while (rangeForRegex.length() > 0) { + while (!rangeForRegex.isEmpty()) { for (String tag : tags) { // change to lowercase for case-insensitive matching String lowerCaseTag = tag.toLowerCase(Locale.ROOT); @@ -437,7 +437,7 @@ public final class LocaleMatcher { } String rangeForRegex = range.replace("*", "\\p{Alnum}*"); - while (rangeForRegex.length() > 0) { + while (!rangeForRegex.isEmpty()) { if (tag.matches(rangeForRegex)) { return true; } @@ -591,7 +591,7 @@ public final class LocaleMatcher { private static String[] getEquivalentsForLanguage(String range) { String r = range; - while (r.length() > 0) { + while (!r.isEmpty()) { if (LocaleEquivalentMaps.singleEquivMap.containsKey(r)) { String equiv = LocaleEquivalentMaps.singleEquivMap.get(r); // Return immediately for performance if the first matching @@ -680,7 +680,7 @@ public final class LocaleMatcher { String r = range; boolean hasEquivalent = false; - while (r.length() > 0) { + while (!r.isEmpty()) { if (keyMap.containsKey(r)) { hasEquivalent = true; List equivalents = map.get(keyMap.get(r)); diff --git a/src/java.base/share/classes/sun/util/locale/LocaleUtils.java b/src/java.base/share/classes/sun/util/locale/LocaleUtils.java index ead48fc2493..264c50086cc 100644 --- a/src/java.base/share/classes/sun/util/locale/LocaleUtils.java +++ b/src/java.base/share/classes/sun/util/locale/LocaleUtils.java @@ -207,7 +207,7 @@ public final class LocaleUtils { } static boolean isEmpty(String str) { - return str == null || str.length() == 0; + return str == null || str.isEmpty(); } static boolean isEmpty(Set set) { diff --git a/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java b/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java index 51a723aea25..634932e9e19 100644 --- a/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java +++ b/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java @@ -80,7 +80,7 @@ public class UnicodeLocaleExtension extends Extension { String value = keyword.getValue(); sj.add(key); - if (value.length() > 0) { + if (!value.isEmpty()) { sj.add(value); } } diff --git a/src/java.base/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java b/src/java.base/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java index c04babb38b0..fe8b95b7882 100644 --- a/src/java.base/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java +++ b/src/java.base/share/classes/sun/util/locale/provider/CalendarNameProviderImpl.java @@ -117,7 +117,7 @@ public class CalendarNameProviderImpl extends CalendarNameProvider implements Av } name = strings[value]; // If name is empty in standalone, try its `format' style. - if (name.length() == 0 + if (name.isEmpty() && (style == SHORT_STANDALONE || style == LONG_STANDALONE || style == NARROW_STANDALONE)) { name = getDisplayName(calendarType, field, value, @@ -183,7 +183,7 @@ public class CalendarNameProviderImpl extends CalendarNameProvider implements Av String name = strings[i]; // Ignore any empty string (some standalone month names // are not defined) - if (name.length() == 0) { + if (name.isEmpty()) { continue; } map.put(name, base + i); diff --git a/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java b/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java index 6fcdf8d9509..89005429700 100644 --- a/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java +++ b/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java @@ -503,7 +503,7 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R */ String supportedLocaleString = createSupportedLocaleString("AvailableLocales"); - if (supportedLocaleString.length() == 0) { + if (supportedLocaleString.isEmpty()) { throw new InternalError("No available locales for JRE"); } diff --git a/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java b/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java index d99b48dcd7b..751aa120830 100644 --- a/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java +++ b/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java @@ -121,7 +121,7 @@ public abstract class LocaleProviderAdapter { List typeList = new ArrayList<>(); // Check user specified adapter preference - if (order != null && order.length() != 0) { + if (order != null && !order.isEmpty()) { String[] types = order.split(","); for (String type : types) { type = type.trim().toUpperCase(Locale.ROOT); diff --git a/src/java.base/unix/classes/java/io/UnixFileSystem.java b/src/java.base/unix/classes/java/io/UnixFileSystem.java index 47c4601ec8e..4e718961710 100644 --- a/src/java.base/unix/classes/java/io/UnixFileSystem.java +++ b/src/java.base/unix/classes/java/io/UnixFileSystem.java @@ -98,7 +98,7 @@ class UnixFileSystem extends FileSystem { } public int prefixLength(String pathname) { - if (pathname.length() == 0) return 0; + if (pathname.isEmpty()) return 0; return (pathname.charAt(0) == '/') ? 1 : 0; } @@ -249,7 +249,7 @@ class UnixFileSystem extends FileSystem { public int getBooleanAttributes(File f) { int rv = getBooleanAttributes0(f); String name = f.getName(); - boolean hidden = (name.length() > 0) && (name.charAt(0) == '.'); + boolean hidden = !name.isEmpty() && name.charAt(0) == '.'; return rv | (hidden ? BA_HIDDEN : 0); } diff --git a/src/java.base/unix/classes/jdk/internal/loader/FileURLMapper.java b/src/java.base/unix/classes/jdk/internal/loader/FileURLMapper.java index b422bdc11de..6507b2961b9 100644 --- a/src/java.base/unix/classes/jdk/internal/loader/FileURLMapper.java +++ b/src/java.base/unix/classes/jdk/internal/loader/FileURLMapper.java @@ -59,9 +59,9 @@ public class FileURLMapper { return path; } String host = url.getHost(); - if (host == null || "".equals(host) || "localhost".equalsIgnoreCase (host)) { + if (host == null || host.isEmpty() || "localhost".equalsIgnoreCase(host)) { path = url.getFile(); - path = ParseUtil.decode (path); + path = ParseUtil.decode(path); } return path; } diff --git a/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java b/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java index 46fd008681e..5036465d46d 100644 --- a/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java +++ b/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java @@ -68,14 +68,14 @@ public class ResolverConfigurationImpl String line; while ((line = in.readLine()) != null) { int maxvalues = maxperkeyword; - if (line.length() == 0) + if (line.isEmpty()) continue; if (line.charAt(0) == '#' || line.charAt(0) == ';') continue; if (!line.startsWith(keyword)) continue; String value = line.substring(keyword.length()); - if (value.length() == 0) + if (value.isEmpty()) continue; if (value.charAt(0) != ' ' && value.charAt(0) != '\t') continue; @@ -181,7 +181,7 @@ public class ResolverConfigurationImpl // LOCALDOMAIN has absolute priority on Solaris String localDomain = localDomain0(); - if (localDomain != null && localDomain.length() > 0) { + if (localDomain != null && !localDomain.isEmpty()) { sl = new LinkedList<>(); sl.add(localDomain); return sl; @@ -211,7 +211,7 @@ public class ResolverConfigurationImpl sl = new LinkedList<>(); String domain = fallbackDomain0(); - if (domain != null && domain.length() > 0) { + if (domain != null && !domain.isEmpty()) { sl.add(domain); } diff --git a/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java b/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java index 6cc4b0094b9..c082bb6f02c 100644 --- a/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java +++ b/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java @@ -77,7 +77,7 @@ public class SdpProvider extends NetHooks.Provider { String logfile = props.getProperty("com.sun.sdp.debug"); if (logfile != null) { out = System.out; - if (logfile.length() > 0) { + if (!logfile.isEmpty()) { try { out = new PrintStream(logfile); } catch (IOException ignore) { } @@ -167,9 +167,9 @@ public class SdpProvider extends NetHooks.Provider { result[1] = all ? MAX_PORT : result[0]; } else { String low = s.substring(0, pos); - if (low.length() == 0) low = "*"; + if (low.isEmpty()) low = "*"; String high = s.substring(pos+1); - if (high.length() == 0) high = "*"; + if (high.isEmpty()) high = "*"; result[0] = low.equals("*") ? 0 : Integer.parseInt(low); result[1] = high.equals("*") ? MAX_PORT : Integer.parseInt(high); } @@ -199,7 +199,7 @@ public class SdpProvider extends NetHooks.Provider { String line = scanner.nextLine().trim(); // skip blank lines and comments - if (line.length() == 0 || line.charAt(0) == '#') + if (line.isEmpty() || line.charAt(0) == '#') continue; // must have 3 fields diff --git a/src/java.base/unix/classes/sun/net/www/protocol/file/Handler.java b/src/java.base/unix/classes/sun/net/www/protocol/file/Handler.java index 6336256aa79..5892517e938 100644 --- a/src/java.base/unix/classes/sun/net/www/protocol/file/Handler.java +++ b/src/java.base/unix/classes/sun/net/www/protocol/file/Handler.java @@ -127,9 +127,9 @@ public class Handler extends URLStreamHandler { */ String s1 = u1.getHost(); String s2 = u2.getHost(); - if ("localhost".equalsIgnoreCase(s1) && ( s2 == null || "".equals(s2))) + if ("localhost".equalsIgnoreCase(s1) && (s2 == null || s2.isEmpty())) return true; - if ("localhost".equalsIgnoreCase(s2) && ( s1 == null || "".equals(s1))) + if ("localhost".equalsIgnoreCase(s2) && (s1 == null || s1.isEmpty())) return true; return super.hostsEqual(u1, u2); } diff --git a/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java b/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java index 63ba292f228..ef0735fcba2 100644 --- a/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java +++ b/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java @@ -49,8 +49,8 @@ class UnixAsynchronousSocketChannelImpl static { String propValue = GetPropertyAction.privilegedGetProperty( "sun.nio.ch.disableSynchronousRead", "false"); - disableSynchronousRead = (propValue.length() == 0) ? - true : Boolean.valueOf(propValue); + disableSynchronousRead = propValue.isEmpty() ? + true : Boolean.parseBoolean(propValue); } private final Port port; diff --git a/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java b/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java index 96225f08d6f..f3a98bdfced 100644 --- a/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java +++ b/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java @@ -58,8 +58,7 @@ abstract class UnixFileSystem // default directory. String propValue = GetPropertyAction .privilegedGetProperty("sun.nio.fs.chdirAllowed", "false"); - boolean chdirAllowed = (propValue.length() == 0) ? - true : Boolean.valueOf(propValue); + boolean chdirAllowed = propValue.isEmpty() ? true : Boolean.parseBoolean(propValue); if (chdirAllowed) { this.needToResolveAgainstDefaultDirectory = true; } else { @@ -269,7 +268,7 @@ abstract class UnixFileSystem StringBuilder sb = new StringBuilder(); sb.append(first); for (String segment: more) { - if (segment.length() > 0) { + if (!segment.isEmpty()) { if (sb.length() > 0) sb.append('/'); sb.append(segment); diff --git a/src/java.base/windows/classes/java/io/WinNTFileSystem.java b/src/java.base/windows/classes/java/io/WinNTFileSystem.java index c97d8dcda6b..1b3b84c5052 100644 --- a/src/java.base/windows/classes/java/io/WinNTFileSystem.java +++ b/src/java.base/windows/classes/java/io/WinNTFileSystem.java @@ -64,7 +64,7 @@ class WinNTFileSystem extends FileSystem { } private String slashify(String p) { - if ((p.length() > 0) && (p.charAt(0) != slash)) return slash + p; + if (!p.isEmpty() && p.charAt(0) != slash) return slash + p; else return p; } diff --git a/src/java.base/windows/classes/sun/net/www/protocol/file/Handler.java b/src/java.base/windows/classes/sun/net/www/protocol/file/Handler.java index abdf791a9d6..c9ace58f968 100644 --- a/src/java.base/windows/classes/sun/net/www/protocol/file/Handler.java +++ b/src/java.base/windows/classes/sun/net/www/protocol/file/Handler.java @@ -145,9 +145,9 @@ public class Handler extends URLStreamHandler { */ String s1 = u1.getHost(); String s2 = u2.getHost(); - if ("localhost".equalsIgnoreCase(s1) && ( s2 == null || "".equals(s2))) + if ("localhost".equalsIgnoreCase(s1) && (s2 == null || s2.isEmpty())) return true; - if ("localhost".equalsIgnoreCase(s2) && ( s1 == null || "".equals(s1))) + if ("localhost".equalsIgnoreCase(s2) && (s1 == null || s1.isEmpty())) return true; return super.hostsEqual(u1, u2); } diff --git a/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java b/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java index e79c7eec3f0..6379ebf4e1d 100644 --- a/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java +++ b/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java @@ -141,14 +141,8 @@ class FileDispatcherImpl extends FileDispatcher { static boolean isFastFileTransferRequested() { String fileTransferProp = GetPropertyAction - .privilegedGetProperty("jdk.nio.enableFastFileTransfer"); - boolean enable; - if ("".equals(fileTransferProp)) { - enable = true; - } else { - enable = Boolean.parseBoolean(fileTransferProp); - } - return enable; + .privilegedGetProperty("jdk.nio.enableFastFileTransfer", "false"); + return fileTransferProp.isEmpty() ? true : Boolean.parseBoolean(fileTransferProp); } static { diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java b/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java index bba794e21a7..62ba3716df0 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java @@ -116,8 +116,7 @@ class WindowsFileAttributes static { String propValue = GetPropertyAction.privilegedGetProperty( "sun.nio.fs.ensureAccurateMetadata", "false"); - ensureAccurateMetadata = (propValue.length() == 0) ? - true : Boolean.valueOf(propValue); + ensureAccurateMetadata = propValue.isEmpty() ? true : Boolean.parseBoolean(propValue); } // attributes diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsFileStore.java b/src/java.base/windows/classes/sun/nio/fs/WindowsFileStore.java index 9e74c6ed107..4dd90c714da 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsFileStore.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsFileStore.java @@ -52,7 +52,7 @@ class WindowsFileStore // file store "display name" is the volume name if available String vol = volInfo.volumeName(); - if (vol.length() > 0) { + if (!vol.isEmpty()) { this.displayName = vol; } else { // TBD - should we map all types? Does this need to be localized? diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystem.java b/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystem.java index b07d50a0fc8..e9a65218163 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystem.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystem.java @@ -218,7 +218,7 @@ class WindowsFileSystem StringBuilder sb = new StringBuilder(); sb.append(first); for (String segment: more) { - if (segment.length() > 0) { + if (!segment.isEmpty()) { if (sb.length() > 0) sb.append('\\'); sb.append(segment); diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsLinkSupport.java b/src/java.base/windows/classes/sun/nio/fs/WindowsLinkSupport.java index 70fde0eb49d..3746c8b1db5 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsLinkSupport.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsLinkSupport.java @@ -329,7 +329,7 @@ class WindowsLinkSupport { // remove special prefix String target = stripPrefix(new String(name)); - if (target.length() == 0) { + if (target.isEmpty()) { throw new IOException("Symbolic link target is invalid"); } return target; diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java b/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java index f4d70f94ad5..4500c733a34 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java @@ -243,7 +243,7 @@ class WindowsPath implements Path { // relative to default directory String remaining = path.substring(root.length()); String defaultDirectory = getFileSystem().defaultDirectory(); - if (remaining.length() == 0) { + if (remaining.isEmpty()) { return defaultDirectory; } else if (defaultDirectory.endsWith("\\")) { return defaultDirectory + remaining; @@ -299,7 +299,7 @@ class WindowsPath implements Path { // -- Path operations -- private boolean isEmpty() { - return path.length() == 0; + return path.isEmpty(); } private WindowsPath emptyPath() { @@ -340,7 +340,7 @@ class WindowsPath implements Path { @Override public WindowsPath getRoot() { - if (root.length() == 0) + if (root.isEmpty()) return null; return new WindowsPath(getFileSystem(), type, root, root); } @@ -556,7 +556,7 @@ class WindowsPath implements Path { // corner case - all names removed if (remaining == 0) { - return (root.length() == 0) ? emptyPath() : getRoot(); + return root.isEmpty() ? emptyPath() : getRoot(); } // re-constitute the path from the remaining names. From 650f3fc11340071d684d5a0077fbd737bb8a325c Mon Sep 17 00:00:00 2001 From: Vicente Romero Date: Thu, 13 Dec 2018 10:35:09 -0500 Subject: [PATCH 050/174] 8215300: additional changes to constants API Reviewed-by: goetz --- .../share/classes/java/lang/Double.java | 4 +- .../share/classes/java/lang/Float.java | 4 +- .../share/classes/java/lang/Integer.java | 4 +- .../share/classes/java/lang/Long.java | 4 +- .../share/classes/java/lang/String.java | 4 +- .../classes/java/lang/constant/ClassDesc.java | 40 ++++++++++++++----- .../classes/java/lang/constant/Constable.java | 5 ++- .../java/lang/constant/ConstantUtils.java | 1 + .../java/lang/constant/package-info.java | 4 +- .../java/lang/invoke/TypeDescriptor.java | 3 +- .../classes/java/lang/invoke/VarHandle.java | 24 +++++++++++ .../jdk/java/lang/constant/ClassDescTest.java | 23 +++++++++++ 12 files changed, 96 insertions(+), 24 deletions(-) diff --git a/src/java.base/share/classes/java/lang/Double.java b/src/java.base/share/classes/java/lang/Double.java index 1ae2380495e..f18f8ce1959 100644 --- a/src/java.base/share/classes/java/lang/Double.java +++ b/src/java.base/share/classes/java/lang/Double.java @@ -1077,8 +1077,8 @@ public final class Double extends Number } /** - * Returns a nominal descriptor for this instance, which is the instance - * itself. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, which is the instance itself. * * @return an {@link Optional} describing the {@linkplain Double} instance * @since 12 diff --git a/src/java.base/share/classes/java/lang/Float.java b/src/java.base/share/classes/java/lang/Float.java index 9712c1a10e1..96953bb8c83 100644 --- a/src/java.base/share/classes/java/lang/Float.java +++ b/src/java.base/share/classes/java/lang/Float.java @@ -989,8 +989,8 @@ public final class Float extends Number } /** - * Returns a nominal descriptor for this instance, which is the instance - * itself. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, which is the instance itself. * * @return an {@link Optional} describing the {@linkplain Float} instance * @since 12 diff --git a/src/java.base/share/classes/java/lang/Integer.java b/src/java.base/share/classes/java/lang/Integer.java index 5a3a1b6ba00..6aebaadd0d0 100644 --- a/src/java.base/share/classes/java/lang/Integer.java +++ b/src/java.base/share/classes/java/lang/Integer.java @@ -1838,8 +1838,8 @@ public final class Integer extends Number } /** - * Returns a nominal descriptor for this instance, which is the instance - * itself. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, which is the instance itself. * * @return an {@link Optional} describing the {@linkplain Integer} instance * @since 12 diff --git a/src/java.base/share/classes/java/lang/Long.java b/src/java.base/share/classes/java/lang/Long.java index 7cd78b04c9b..790e4deb675 100644 --- a/src/java.base/share/classes/java/lang/Long.java +++ b/src/java.base/share/classes/java/lang/Long.java @@ -1967,8 +1967,8 @@ public final class Long extends Number } /** - * Returns a nominal descriptor for this instance, which is the instance - * itself. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, which is the instance itself. * * @return an {@link Optional} describing the {@linkplain Long} instance * @since 12 diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index c9634ddc7aa..9251e6c0895 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -3545,8 +3545,8 @@ public final class String } /** - * Returns a nominal descriptor for this instance, which is the instance - * itself. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, which is the instance itself. * * @return an {@link Optional} describing the {@linkplain String} instance * @since 12 diff --git a/src/java.base/share/classes/java/lang/constant/ClassDesc.java b/src/java.base/share/classes/java/lang/constant/ClassDesc.java index 00081362c7c..53dd1a451ca 100644 --- a/src/java.base/share/classes/java/lang/constant/ClassDesc.java +++ b/src/java.base/share/classes/java/lang/constant/ClassDesc.java @@ -112,13 +112,13 @@ public interface ClassDesc * * A field type descriptor string for a non-array type is either * a one-letter code corresponding to a primitive type - * ({@code J,I,C,S,B,D,F,Z,V}), or the letter {@code L}, followed - * by the fully qualified binary name of a class, followed by {@code ;}. - * A field type descriptor for an array type is the character {@code [} + * ({@code "J", "I", "C", "S", "B", "D", "F", "Z", "V"}), or the letter {@code "L"}, followed + * by the fully qualified binary name of a class, followed by {@code ";"}. + * A field type descriptor for an array type is the character {@code "["} * followed by the field descriptor for the component type. Examples of - * valid type descriptor strings include {@code Ljava/lang/String;}, {@code I}, - * {@code [I}, {@code V}, {@code [Ljava/lang/String;}, etc. - * for more detail. + * valid type descriptor strings include {@code "Ljava/lang/String;"}, {@code "I"}, + * {@code "[I"}, {@code "V"}, {@code "[Ljava/lang/String;"}, etc. + * See JVMS 4.3.2 ("Field Descriptors") for more detail. * * @param descriptor a field descriptor string * @return a {@linkplain ClassDesc} describing the desired class @@ -126,9 +126,15 @@ public interface ClassDesc * @throws IllegalArgumentException if the name string is not in the * correct format * @jvms 4.3.2 Field Descriptors + * @jvms 4.4.1 The CONSTANT_Class_info Structure */ static ClassDesc ofDescriptor(String descriptor) { requireNonNull(descriptor); + int depth = ConstantUtils.arrayDepth(descriptor); + if (depth > ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS) { + throw new IllegalArgumentException(String.format("Cannot create an array type descriptor with more than %d dimensions", + ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS)); + } return (descriptor.length() == 1) ? new PrimitiveClassDescImpl(descriptor) : new ReferenceClassDescImpl(descriptor); @@ -139,8 +145,15 @@ public interface ClassDesc * is described by this {@linkplain ClassDesc}. * * @return a {@linkplain ClassDesc} describing the array type + * @throws IllegalStateException if the resulting {@linkplain ClassDesc} would have an array rank of greater than 255 + * @jvms 4.4.1 The CONSTANT_Class_info Structure */ default ClassDesc arrayType() { + int depth = ConstantUtils.arrayDepth(descriptorString()); + if (depth >= ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS) { + throw new IllegalStateException(String.format("Cannot create an array type descriptor with more than %d dimensions", + ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS)); + } return arrayType(1); } @@ -150,11 +163,14 @@ public interface ClassDesc * * @param rank the rank of the array * @return a {@linkplain ClassDesc} describing the array type - * @throws IllegalArgumentException if the rank is zero or negative + * @throws IllegalArgumentException if the rank is less than zero or if the rank of the resulting array type is + * greater than 255 + * @jvms 4.4.1 The CONSTANT_Class_info Structure */ default ClassDesc arrayType(int rank) { - if (rank <= 0) - throw new IllegalArgumentException("rank: " + rank); + int currentDepth = ConstantUtils.arrayDepth(descriptorString()); + if (rank <= 0 || currentDepth + rank > ConstantUtils.MAX_ARRAY_TYPE_DESC_DIMENSIONS) + throw new IllegalArgumentException("rank: " + currentDepth + rank); return ClassDesc.ofDescriptor("[".repeat(rank) + descriptorString()); } @@ -162,6 +178,12 @@ public interface ClassDesc * Returns a {@linkplain ClassDesc} for a nested class of the class or * interface type described by this {@linkplain ClassDesc}. * + * @apiNote + * + * Example: If descriptor {@code d} describes the class {@code java.util.Map}, a + * descriptor for the class {@code java.util.Map.Entry} could be obtained + * by {@code d.nested("Entry")}. + * * @param nestedName the unqualified name of the nested class * @return a {@linkplain ClassDesc} describing the nested class * @throws NullPointerException if any argument is {@code null} diff --git a/src/java.base/share/classes/java/lang/constant/Constable.java b/src/java.base/share/classes/java/lang/constant/Constable.java index 2e12183fb6a..64525be9daf 100644 --- a/src/java.base/share/classes/java/lang/constant/Constable.java +++ b/src/java.base/share/classes/java/lang/constant/Constable.java @@ -65,8 +65,9 @@ import java.util.Optional; */ public interface Constable { /** - * Returns a nominal descriptor for this instance, if one can be - * constructed, or an empty {@link Optional} if one cannot be constructed. + * Returns an {@link Optional} containing the nominal descriptor for this + * instance, if one can be constructed, or an empty {@link Optional} + * if one cannot be constructed. * * @return An {@link Optional} containing the resulting nominal descriptor, * or an empty {@link Optional} if one cannot be constructed. diff --git a/src/java.base/share/classes/java/lang/constant/ConstantUtils.java b/src/java.base/share/classes/java/lang/constant/ConstantUtils.java index a758a948c0d..3000029a0c4 100644 --- a/src/java.base/share/classes/java/lang/constant/ConstantUtils.java +++ b/src/java.base/share/classes/java/lang/constant/ConstantUtils.java @@ -37,6 +37,7 @@ class ConstantUtils { /** an empty constant descriptor */ public static final ConstantDesc[] EMPTY_CONSTANTDESC = new ConstantDesc[0]; static final Constable[] EMPTY_CONSTABLE = new Constable[0]; + static final int MAX_ARRAY_TYPE_DESC_DIMENSIONS = 255; private static final Set pointyNames = Set.of("", ""); diff --git a/src/java.base/share/classes/java/lang/constant/package-info.java b/src/java.base/share/classes/java/lang/constant/package-info.java index f786e643085..9bc978e44a1 100644 --- a/src/java.base/share/classes/java/lang/constant/package-info.java +++ b/src/java.base/share/classes/java/lang/constant/package-info.java @@ -49,7 +49,7 @@ * storing the value in a constant pool entry, or reconstituting the value given * a class loading context. Every {@link java.lang.constant.ConstantDesc} * knows how to resolve itself -- compute the value that it describes -- - * via {@link java.lang.constant.ConstantDesc#resolveConstantDesc(java.lang.invoke.MethodHandles.Lookup)}. + * via {@link java.lang.constant.ConstantDesc#resolveConstantDesc(java.lang.invoke.MethodHandles.Lookup) ConstantDesc.resolveConstantDesc}. * This allows an API which accepts {@link java.lang.constant.ConstantDesc} * objects to evaluate them reflectively, provided that the classes and methods * referenced in their nominal description are present and accessible. @@ -68,7 +68,7 @@ * When a bytecode-reading API encounters a constant pool entry, it can * convert it to the appropriate type of nominal descriptor. For dynamic * constants, bytecode-reading APIs may wish to use the factory - * {@link java.lang.constant.DynamicConstantDesc#ofCanonical(DirectMethodHandleDesc, java.lang.String, ClassDesc, ConstantDesc[])}, + * {@link java.lang.constant.DynamicConstantDesc#ofCanonical(DirectMethodHandleDesc, java.lang.String, ClassDesc, ConstantDesc[]) DynamicConstantDesc.ofCanonical}, * which will inspect the bootstrap and, for well-known bootstraps, return * a more specific subtype of {@link java.lang.constant.DynamicConstantDesc}, such as * {@link java.lang.Enum.EnumDesc}. diff --git a/src/java.base/share/classes/java/lang/invoke/TypeDescriptor.java b/src/java.base/share/classes/java/lang/invoke/TypeDescriptor.java index 5caf622bf6f..b5349df2c3b 100644 --- a/src/java.base/share/classes/java/lang/invoke/TypeDescriptor.java +++ b/src/java.base/share/classes/java/lang/invoke/TypeDescriptor.java @@ -61,7 +61,8 @@ public interface TypeDescriptor { boolean isArray(); /** - * Does this field descriptor describe a primitive type? + * Does this field descriptor describe a primitive type (including void.) + * * @return whether this field descriptor describes a primitive type */ boolean isPrimitive(); diff --git a/src/java.base/share/classes/java/lang/invoke/VarHandle.java b/src/java.base/share/classes/java/lang/invoke/VarHandle.java index f647448e9bc..1d1fdf95224 100644 --- a/src/java.base/share/classes/java/lang/invoke/VarHandle.java +++ b/src/java.base/share/classes/java/lang/invoke/VarHandle.java @@ -1864,6 +1864,16 @@ public abstract class VarHandle implements Constable { } } + /** + * Compare this {@linkplain VarHandle} with another object for equality. + * Two {@linkplain VarHandle}s are considered equal if they both describe the + * same instance field, both describe the same static field, both describe + * array elements for arrays with the same component type, or both describe + * the same component of an off-heap structure. + * + * @param o the other object + * @return Whether this {@linkplain VarHandle} is equal to the other object + */ @Override public final boolean equals(Object o) { if (this == o) return true; @@ -1883,6 +1893,12 @@ public abstract class VarHandle implements Constable { abstract int internalHashCode(); + /** + * Returns a compact textual description of this {@linkplain VarHandle}, + * including the type of variable described, and a description of its coordinates. + * + * @return A compact textual description of this {@linkplain VarHandle} + */ @Override public final String toString() { return String.format("VarHandle[varType=%s, coord=%s]", @@ -2272,6 +2288,14 @@ public abstract class VarHandle implements Constable { } } + /** + * Returns a compact textual description of this constant description. + * For a field {@linkplain VarHandle}, includes the owner, name, and type + * of the field, and whether it is static; for an array {@linkplain VarHandle}, + * the name of the component type. + * + * @return A compact textual description of this descriptor + */ @Override public String toString() { switch (kind) { diff --git a/test/jdk/java/lang/constant/ClassDescTest.java b/test/jdk/java/lang/constant/ClassDescTest.java index d1d0d9b3d42..7b90291039d 100644 --- a/test/jdk/java/lang/constant/ClassDescTest.java +++ b/test/jdk/java/lang/constant/ClassDescTest.java @@ -244,6 +244,29 @@ public class ClassDescTest extends SymbolicDescTest { testBadNestedClasses(ClassDesc.ofDescriptor(p.descriptor), "any"); testBadNestedClasses(ClassDesc.ofDescriptor(p.descriptor), "any", "other"); } + + ClassDesc stringDesc = ClassDesc.ofDescriptor("Ljava/lang/String;"); + ClassDesc stringArrDesc = stringDesc.arrayType(255); + try { + ClassDesc arrGreaterThan255 = stringArrDesc.arrayType(); + fail("can't create an array type descriptor with more than 255 dimensions"); + } catch (IllegalStateException e) { + // good + } + String descWith255ArrayDims = new String(new char[255]).replace('\0', '['); + try { + ClassDesc arrGreaterThan255 = ClassDesc.ofDescriptor(descWith255ArrayDims + "[Ljava/lang/String;"); + fail("can't create an array type descriptor with more than 255 dimensions"); + } catch (IllegalArgumentException e) { + // good + } + try { + ClassDesc arrWith255Dims = ClassDesc.ofDescriptor(descWith255ArrayDims + "Ljava/lang/String;"); + arrWith255Dims.arrayType(1); + fail("can't create an array type descriptor with more than 255 dimensions"); + } catch (IllegalArgumentException e) { + // good + } } private void testBadNestedClasses(ClassDesc cr, String firstNestedName, String... moreNestedNames) { From 2278601b7c4a5e42ff09fd4ed44a54cb01795cb7 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Thu, 13 Dec 2018 16:45:24 +0100 Subject: [PATCH 051/174] 8181143: Introduce diagnostic flag to abort VM on too long VM operations Reviewed-by: rkennke, zgu, dholmes, stuefe, rehn --- src/hotspot/share/runtime/globals.hpp | 7 ++ src/hotspot/share/runtime/vmThread.cpp | 52 ++++++++++++ src/hotspot/share/runtime/vmThread.hpp | 23 ++++++ .../TestAbortOnVMOperationTimeout.java | 81 +++++++++++++++++++ 4 files changed, 163 insertions(+) create mode 100644 test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java diff --git a/src/hotspot/share/runtime/globals.hpp b/src/hotspot/share/runtime/globals.hpp index 64c4078aa41..8a9a592e95a 100644 --- a/src/hotspot/share/runtime/globals.hpp +++ b/src/hotspot/share/runtime/globals.hpp @@ -501,6 +501,13 @@ define_pd_global(uint64_t,MaxRAM, 1ULL*G); diagnostic(bool, AbortVMOnSafepointTimeout, false, \ "Abort upon failure to reach safepoint (see SafepointTimeout)") \ \ + diagnostic(bool, AbortVMOnVMOperationTimeout, false, \ + "Abort upon failure to complete VM operation promptly") \ + \ + diagnostic(intx, AbortVMOnVMOperationTimeoutDelay, 1000, \ + "Delay in milliseconds for option AbortVMOnVMOperationTimeout") \ + range(0, max_intx) \ + \ /* 50 retries * (5 * current_retry_count) millis = ~6.375 seconds */ \ /* typically, at most a few retries are needed */ \ product(intx, SuspendRetryCount, 50, \ diff --git a/src/hotspot/share/runtime/vmThread.cpp b/src/hotspot/share/runtime/vmThread.cpp index 418ff2112e3..c0667686f38 100644 --- a/src/hotspot/share/runtime/vmThread.cpp +++ b/src/hotspot/share/runtime/vmThread.cpp @@ -28,6 +28,7 @@ #include "jfr/jfrEvents.hpp" #include "jfr/support/jfrThreadId.hpp" #include "logging/log.hpp" +#include "logging/logStream.hpp" #include "logging/logConfiguration.hpp" #include "memory/resourceArea.hpp" #include "oops/method.hpp" @@ -197,6 +198,32 @@ void VMOperationQueue::oops_do(OopClosure* f) { drain_list_oops_do(f); } +//------------------------------------------------------------------------------------------------------------------ +// Timeout machinery + +void VMOperationTimeoutTask::task() { + assert(AbortVMOnVMOperationTimeout, "only if enabled"); + if (is_armed()) { + jlong delay = (os::javaTimeMillis() - _arm_time); + if (delay > AbortVMOnVMOperationTimeoutDelay) { + fatal("VM operation took too long: " SIZE_FORMAT " ms (timeout: " SIZE_FORMAT " ms)", + delay, AbortVMOnVMOperationTimeoutDelay); + } + } +} + +bool VMOperationTimeoutTask::is_armed() { + return OrderAccess::load_acquire(&_armed) != 0; +} + +void VMOperationTimeoutTask::arm() { + _arm_time = os::javaTimeMillis(); + OrderAccess::release_store_fence(&_armed, 1); +} + +void VMOperationTimeoutTask::disarm() { + OrderAccess::release_store_fence(&_armed, 0); +} //------------------------------------------------------------------------------------------------------------------ // Implementation of VMThread stuff @@ -209,12 +236,28 @@ VM_Operation* VMThread::_cur_vm_operation = NULL; VMOperationQueue* VMThread::_vm_queue = NULL; PerfCounter* VMThread::_perf_accumulated_vm_operation_time = NULL; const char* VMThread::_no_op_reason = NULL; +VMOperationTimeoutTask* VMThread::_timeout_task = NULL; void VMThread::create() { assert(vm_thread() == NULL, "we can only allocate one VMThread"); _vm_thread = new VMThread(); + if (AbortVMOnVMOperationTimeout) { + // Make sure we call the timeout task frequently enough, but not too frequent. + // Try to make the interval 10% of the timeout delay, so that we miss the timeout + // by those 10% at max. Periodic task also expects it to fit min/max intervals. + size_t interval = (size_t)AbortVMOnVMOperationTimeoutDelay / 10; + interval = interval / PeriodicTask::interval_gran * PeriodicTask::interval_gran; + interval = MAX2(interval, PeriodicTask::min_interval); + interval = MIN2(interval, PeriodicTask::max_interval); + + _timeout_task = new VMOperationTimeoutTask(interval); + _timeout_task->enroll(); + } else { + assert(_timeout_task == NULL, "sanity"); + } + // Create VM operation queue _vm_queue = new VMOperationQueue(); guarantee(_vm_queue != NULL, "just checking"); @@ -492,6 +535,11 @@ void VMThread::loop() { _vm_queue->set_drain_list(safepoint_ops); // ensure ops can be scanned SafepointSynchronize::begin(); + + if (_timeout_task != NULL) { + _timeout_task->arm(); + } + evaluate_operation(_cur_vm_operation); // now process all queued safepoint ops, iteratively draining // the queue until there are none left @@ -533,6 +581,10 @@ void VMThread::loop() { _vm_queue->set_drain_list(NULL); + if (_timeout_task != NULL) { + _timeout_task->disarm(); + } + // Complete safepoint synchronization SafepointSynchronize::end(); diff --git a/src/hotspot/share/runtime/vmThread.hpp b/src/hotspot/share/runtime/vmThread.hpp index 0a85e22ae7c..ebeb63363dc 100644 --- a/src/hotspot/share/runtime/vmThread.hpp +++ b/src/hotspot/share/runtime/vmThread.hpp @@ -27,6 +27,7 @@ #include "runtime/perfData.hpp" #include "runtime/thread.hpp" +#include "runtime/task.hpp" #include "runtime/vmOperations.hpp" // @@ -84,6 +85,26 @@ class VMOperationQueue : public CHeapObj { }; +// VM operation timeout handling: warn or abort the VM when VM operation takes +// too long. Periodic tasks do not participate in safepoint protocol, and therefore +// can fire when application threads are stopped. + +class VMOperationTimeoutTask : public PeriodicTask { +private: + volatile int _armed; + jlong _arm_time; + +public: + VMOperationTimeoutTask(size_t interval_time) : + PeriodicTask(interval_time), _armed(0), _arm_time(0) {} + + virtual void task(); + + bool is_armed(); + void arm(); + void disarm(); +}; + // // A single VMThread (the primordial thread) spawns all other threads // and is itself used by other threads to offload heavy vm operations @@ -101,6 +122,8 @@ class VMThread: public NamedThread { static const char* _no_op_reason; + static VMOperationTimeoutTask* _timeout_task; + static bool no_op_safepoint_needed(bool check_time); void evaluate_operation(VM_Operation* op); diff --git a/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java b/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java new file mode 100644 index 00000000000..9a32f8f7757 --- /dev/null +++ b/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2018, Red Hat, Inc. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.*; +import jdk.test.lib.process.*; + +/* + * @test TestAbortOnVMOperationTimeout + * @bug 8181143 + * @summary Check abort on VM timeout is working + * @library /test/lib + * @modules java.base/jdk.internal.misc + * java.management + */ + +public class TestAbortOnVMOperationTimeout { + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + Object[] arr = new Object[10_000_000]; + for (int i = 0; i < arr.length; i++) { + arr[i] = new Object(); + } + return; + } + + // These should definitely pass: more than a minute is enough for Serial to act. + // The values are deliberately non-round to trip off periodic task granularity. + for (int delay : new int[]{63423, 12388131}) { + testWith(delay, true); + } + + // These should fail: Serial is not very fast. Traversing 10M objects in 5 ms + // means less than 0.5 ns per object, which is not doable. + for (int delay : new int[]{0, 1, 5}) { + testWith(delay, false); + } + } + + public static void testWith(int delay, boolean shouldPass) throws Exception { + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+AbortVMOnVMOperationTimeout", + "-XX:AbortVMOnVMOperationTimeoutDelay=" + delay, + "-Xmx256m", + "-XX:+UseSerialGC", + "-XX:-CreateCoredumpOnCrash", + "TestAbortOnVMOperationTimeout", + "foo" + ); + + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + if (shouldPass) { + output.shouldHaveExitValue(0); + } else { + output.shouldMatch("VM operation took too long"); + output.shouldNotHaveExitValue(0); + } + } +} + From 2880b1bb0666d3f2c79ce42abe4e02813c81f93c Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Thu, 13 Dec 2018 16:45:26 +0100 Subject: [PATCH 052/174] 8215356: Disable x86_32 Shenandoah build to avoid hotspot/tier1 failures Reviewed-by: rkennke --- make/autoconf/hotspot.m4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/autoconf/hotspot.m4 b/make/autoconf/hotspot.m4 index 10b0056a2ce..ce9bab6923e 100644 --- a/make/autoconf/hotspot.m4 +++ b/make/autoconf/hotspot.m4 @@ -327,7 +327,7 @@ AC_DEFUN_ONCE([HOTSPOT_SETUP_JVM_FEATURES], # Only enable Shenandoah on supported arches AC_MSG_CHECKING([if shenandoah can be built]) - if test "x$OPENJDK_TARGET_CPU_ARCH" = "xx86" || test "x$OPENJDK_TARGET_CPU" = "xaarch64" ; then + if test "x$OPENJDK_TARGET_CPU" = "xx86_64" || test "x$OPENJDK_TARGET_CPU" = "xaarch64" ; then AC_MSG_RESULT([yes]) else DISABLED_JVM_FEATURES="$DISABLED_JVM_FEATURES shenandoahgc" From f32dc1764c28fd29c186baefb839b13ae31830ab Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Thu, 13 Dec 2018 17:01:15 +0100 Subject: [PATCH 053/174] Added tag jdk-13+0 for changeset cc4098b3bc10 --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 479d7b40b59..2c406b49be8 100644 --- a/.hgtags +++ b/.hgtags @@ -526,3 +526,4 @@ dc1f9dec2018a37fedba47d8a2aedef99faaec64 jdk-12+19 f8fb0c86f2b3d24294d39c5685a628e1beb14ba7 jdk-12+21 732bec44c89e8b93a38296bf690f97b7230c5b6d jdk-12+22 eef755718cb24813031a842bbfc716a6cea18e9a jdk-12+23 +cc4098b3bc10d1c390384289025fea7b0d4b9e93 jdk-13+0 From b5f0eec3d80bfa5a52679341dff22e54e82b5a76 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Thu, 13 Dec 2018 19:06:11 +0100 Subject: [PATCH 054/174] 8205626: Start of release updates for JDK 13 8205393: Add SourceVersion.RELEASE_13 8205394: Add source 13 and target 13 to javac 8205645: Bump maximum recognized class file version to 57 for JDK 13 8214825: Update preview language features for start of JDK 13 Reviewed-by: erikj, alanb, mchung, mcimadamore, dholmes, smarks, jjg --- make/autoconf/version-numbers | 8 ++++---- make/common/SetupJavaCompilers.gmk | 4 ++-- .../share/classfile/classFileParser.cpp | 2 ++ .../com/sun/java/util/jar/pack/Constants.java | 6 +++++- .../jdk/internal/module/ModuleInfo.java | 2 +- .../org/objectweb/asm/ClassReader.java | 2 +- .../internal/org/objectweb/asm/Opcodes.java | 1 + .../javax/lang/model/SourceVersion.java | 15 +++++++++++++-- .../util/AbstractAnnotationValueVisitor9.java | 4 ++-- .../model/util/AbstractElementVisitor9.java | 4 ++-- .../lang/model/util/AbstractTypeVisitor9.java | 4 ++-- .../lang/model/util/ElementKindVisitor9.java | 4 ++-- .../javax/lang/model/util/ElementScanner9.java | 4 ++-- .../util/SimpleAnnotationValueVisitor9.java | 4 ++-- .../lang/model/util/SimpleElementVisitor9.java | 4 ++-- .../lang/model/util/SimpleTypeVisitor9.java | 4 ++-- .../lang/model/util/TypeKindVisitor9.java | 4 ++-- .../com/sun/tools/javac/code/Source.java | 16 +++++++++++----- .../com/sun/tools/javac/jvm/ClassFile.java | 3 ++- .../com/sun/tools/javac/jvm/Profile.java | 6 +++--- .../com/sun/tools/javac/jvm/Target.java | 5 ++++- .../javac/processing/PrintingProcessor.java | 2 +- .../replacements/classfile/Classfile.java | 2 +- .../classes/com/sun/tools/jdeprscan/Main.java | 2 +- .../sun/tools/java/RuntimeConstants.java | 2 +- test/jaxp/TEST.ROOT | 2 +- test/jdk/TEST.ROOT | 2 +- .../lang/module/ClassFileVersionsTest.java | 7 ++++++- test/langtools/TEST.ROOT | 2 +- .../tools/javac/6330997/T6330997.java | 4 ++-- .../tools/javac/ConditionalWithVoid.java | 2 +- .../tools/javac/RawStringLiteralLang.java | 2 +- .../tools/javac/RawStringLiteralLangAPI.java | 6 +++--- test/langtools/tools/javac/api/T6395981.java | 4 ++-- .../javac/classfiles/ClassVersionChecker.java | 3 ++- .../diags/examples/BreakAmbiguousTarget.java | 2 +- .../diags/examples/BreakExprNotImmediate.java | 2 +- .../diags/examples/BreakMissingValue.java | 2 +- .../examples/BreakOutsideSwitchExpression.java | 2 +- .../ContinueOutsideSwitchExpression.java | 2 +- .../IncompatibleTypesInSwitchExpression.java | 2 +- .../diags/examples/MultipleCaseLabels.java | 2 +- .../javac/diags/examples/NotExhaustive.java | 2 +- .../diags/examples/PreviewFeatureUse.java | 2 +- .../javac/diags/examples/PreviewFilename.java | 2 +- .../examples/PreviewFilenameAdditional.java | 2 +- .../examples/PreviewPlural/PreviewPlural.java | 2 +- .../javac/diags/examples/RawStringLiteral.java | 2 +- .../ReturnOutsideSwitchExpression.java | 2 +- .../diags/examples/RuleCompletesNormally.java | 2 +- .../SwitchCaseUnexpectedStatement.java | 2 +- .../SwitchExpressionCompletesNormally.java | 2 +- .../diags/examples/SwitchExpressionEmpty.java | 2 +- .../SwitchExpressionTargetCantBeVoid.java | 2 +- .../diags/examples/SwitchExpressions.java | 2 +- .../diags/examples/SwitchMixingCaseTypes.java | 2 +- .../javac/diags/examples/SwitchRules.java | 2 +- .../javac/expswitch/ExpSwitchNestingTest.java | 8 +++++--- .../lambda/BadSwitchExpressionLambda.java | 2 +- .../lib/JavacTestingAbstractProcessor.java | 18 +++++++++--------- .../tools/javac/parser/JavacParserTest.java | 2 +- .../javac/preview/classReaderTest/Client.java | 4 ++-- .../classReaderTest/Client.nopreview.out | 2 +- .../preview/classReaderTest/Client.preview.out | 2 +- .../javac/profiles/ProfileOptionTest.java | 1 + .../javac/switchexpr/BlockExpression.java | 2 +- .../switchexpr/BooleanNumericNonNumeric.java | 2 +- .../tools/javac/switchexpr/BreakTest.java | 2 +- test/langtools/tools/javac/switchexpr/CRT.java | 2 +- .../javac/switchexpr/DefiniteAssignment1.java | 2 +- .../javac/switchexpr/DefiniteAssignment2.java | 2 +- .../tools/javac/switchexpr/EmptySwitch.java | 2 +- .../javac/switchexpr/ExhaustiveEnumSwitch.java | 2 +- .../javac/switchexpr/ExpressionSwitch.java | 2 +- .../switchexpr/ExpressionSwitchBreaks1.java | 2 +- .../switchexpr/ExpressionSwitchBreaks2.java | 2 +- .../javac/switchexpr/ExpressionSwitchBugs.java | 2 +- .../switchexpr/ExpressionSwitchBugsInGen.java | 2 +- .../ExpressionSwitchCodeFromJLS.java | 2 +- .../javac/switchexpr/ExpressionSwitchDA.java | 2 +- .../switchexpr/ExpressionSwitchEmbedding.java | 2 +- .../ExpressionSwitchFallThrough.java | 2 +- .../ExpressionSwitchFallThrough1.java | 2 +- .../javac/switchexpr/ExpressionSwitchFlow.java | 2 +- .../ExpressionSwitchInExpressionSwitch.java | 2 +- .../switchexpr/ExpressionSwitchInfer.java | 2 +- .../ExpressionSwitchIntersectionTypes.java | 2 +- .../ExpressionSwitchNotExhaustive.java | 2 +- .../ExpressionSwitchUnreachable.java | 2 +- .../javac/switchexpr/ParseIncomplete.java | 2 +- .../tools/javac/switchexpr/ParserRecovery.java | 2 +- .../SwitchExpressionIsNotAConstant.java | 2 +- .../SwitchExpressionScopesIsolated.java | 2 +- .../SwitchExpressionSimpleVisitorTest.java | 2 +- .../tools/javac/switchexpr/TryCatch.java | 2 +- .../tools/javac/switchextra/CaseTest.java | 2 +- .../switchextra/MultipleLabelsExpression.java | 2 +- .../switchextra/MultipleLabelsStatement.java | 2 +- .../javac/switchextra/RuleParsingTest.java | 2 +- .../switchextra/SwitchArrowBrokenConstant.java | 2 +- .../switchextra/SwitchStatementArrow.java | 2 +- .../switchextra/SwitchStatementBroken.java | 2 +- .../switchextra/SwitchStatementBroken2.java | 2 +- .../SwitchStatementScopesIsolated.java | 2 +- .../tools/javac/versions/Versions.java | 12 +++++++++--- test/nashorn/TEST.ROOT | 2 +- 106 files changed, 183 insertions(+), 140 deletions(-) diff --git a/make/autoconf/version-numbers b/make/autoconf/version-numbers index 57b551acac0..762c5528635 100644 --- a/make/autoconf/version-numbers +++ b/make/autoconf/version-numbers @@ -25,17 +25,17 @@ # Default version numbers to use unless overridden by configure -DEFAULT_VERSION_FEATURE=12 +DEFAULT_VERSION_FEATURE=13 DEFAULT_VERSION_INTERIM=0 DEFAULT_VERSION_UPDATE=0 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2019-03-19 -DEFAULT_VERSION_CLASSFILE_MAJOR=56 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" +DEFAULT_VERSION_DATE=2019-09-17 +DEFAULT_VERSION_CLASSFILE_MAJOR=57 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 -DEFAULT_ACCEPTABLE_BOOT_VERSIONS="11 12" +DEFAULT_ACCEPTABLE_BOOT_VERSIONS="11 12 13" LAUNCHER_NAME=openjdk PRODUCT_NAME=OpenJDK diff --git a/make/common/SetupJavaCompilers.gmk b/make/common/SetupJavaCompilers.gmk index f66a8e319db..7c85408cfb3 100644 --- a/make/common/SetupJavaCompilers.gmk +++ b/make/common/SetupJavaCompilers.gmk @@ -72,7 +72,7 @@ $(eval $(call SetupJavaCompiler,GENERATE_OLDBYTECODE, \ $(eval $(call SetupJavaCompiler,GENERATE_JDKBYTECODE, \ JVM := $(JAVA_JAVAC), \ JAVAC := $(NEW_JAVAC), \ - FLAGS := -source 12 -target 12 --doclint-format html5 \ + FLAGS := -source 13 -target 13 --doclint-format html5 \ -encoding ascii -XDignore.symbol.file=true $(JAVAC_WARNINGS), \ SERVER_DIR := $(SJAVAC_SERVER_DIR), \ SERVER_JVM := $(SJAVAC_SERVER_JAVA))) @@ -82,7 +82,7 @@ $(eval $(call SetupJavaCompiler,GENERATE_JDKBYTECODE, \ $(eval $(call SetupJavaCompiler,GENERATE_JDKBYTECODE_NOWARNINGS, \ JVM := $(JAVA_JAVAC), \ JAVAC := $(NEW_JAVAC), \ - FLAGS := -source 12 -target 12 \ + FLAGS := -source 13 -target 13 \ -encoding ascii -XDignore.symbol.file=true $(DISABLE_WARNINGS), \ SERVER_DIR := $(SJAVAC_SERVER_DIR), \ SERVER_JVM := $(SJAVAC_SERVER_JAVA))) diff --git a/src/hotspot/share/classfile/classFileParser.cpp b/src/hotspot/share/classfile/classFileParser.cpp index 4484da997c7..18a3f4877df 100644 --- a/src/hotspot/share/classfile/classFileParser.cpp +++ b/src/hotspot/share/classfile/classFileParser.cpp @@ -119,6 +119,8 @@ #define JAVA_12_VERSION 56 +#define JAVA_13_VERSION 57 + void ClassFileParser::set_class_bad_constant_seen(short bad_constant) { assert((bad_constant == 19 || bad_constant == 20) && _major_version >= JAVA_9_VERSION, "Unexpected bad constant pool entry"); diff --git a/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java b/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java index 96e64c1d8fe..d178f02d80b 100644 --- a/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java +++ b/src/java.base/share/classes/com/sun/java/util/jar/pack/Constants.java @@ -50,6 +50,7 @@ class Constants { 1.10 to 1.10.X 54,0 1.11 to 1.11.X 55,0 1.12 to 1.12.X 56,0 + 1.13 to 1.13.X 57,0 */ public static final Package.Version JAVA_MIN_CLASS_VERSION = @@ -79,6 +80,9 @@ class Constants { public static final Package.Version JAVA12_MAX_CLASS_VERSION = Package.Version.of(56, 00); + public static final Package.Version JAVA13_MAX_CLASS_VERSION = + Package.Version.of(57, 00); + public static final int JAVA_PACKAGE_MAGIC = 0xCAFED00D; public static final Package.Version JAVA5_PACKAGE_VERSION = @@ -95,7 +99,7 @@ class Constants { // upper limit, should point to the latest class version public static final Package.Version JAVA_MAX_CLASS_VERSION = - JAVA12_MAX_CLASS_VERSION; + JAVA13_MAX_CLASS_VERSION; // upper limit should point to the latest package version, for version info!. public static final Package.Version MAX_PACKAGE_VERSION = diff --git a/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java b/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java index 9b20502bc4f..2a10a8952f8 100644 --- a/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java +++ b/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java @@ -63,7 +63,7 @@ import static jdk.internal.module.ClassFileConstants.*; public final class ModuleInfo { private final int JAVA_MIN_SUPPORTED_VERSION = 53; - private final int JAVA_MAX_SUPPORTED_VERSION = 56; + private final int JAVA_MAX_SUPPORTED_VERSION = 57; private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess(); diff --git a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java index 845e3b89182..5d2833e012b 100644 --- a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java +++ b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java @@ -210,7 +210,7 @@ public class ClassReader { b = classFileBuffer; // Check the class' major_version. This field is after the magic and minor_version fields, which // use 4 and 2 bytes respectively. - if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V12) { + if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V13) { throw new IllegalArgumentException( "Unsupported class file major version " + readShort(classFileOffset + 6)); } diff --git a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Opcodes.java b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Opcodes.java index e1095c535be..0fb28cacd11 100644 --- a/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Opcodes.java +++ b/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Opcodes.java @@ -95,6 +95,7 @@ public interface Opcodes { int V10 = 0 << 16 | 54; int V11 = 0 << 16 | 55; int V12 = 0 << 16 | 56; + int V13 = 0 << 16 | 57; /** * Version flag indicating that the class is using 'preview' features. diff --git a/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java b/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java index c1cb262dd25..aa2a8e780c2 100644 --- a/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java +++ b/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java @@ -59,6 +59,7 @@ public enum SourceVersion { * 10: local-variable type inference (var) * 11: local-variable syntax for lambda parameters * 12: TBD + * 13: TBD */ /** @@ -183,7 +184,15 @@ public enum SourceVersion { * * @since 12 */ - RELEASE_12; + RELEASE_12, + + /** + * The version recognized by the Java Platform, Standard Edition + * 13. + * + * @since 13 + */ + RELEASE_13; // Note that when adding constants for newer releases, the // behavior of latest() and latestSupported() must be updated too. @@ -194,7 +203,7 @@ public enum SourceVersion { * @return the latest source version that can be modeled */ public static SourceVersion latest() { - return RELEASE_12; + return RELEASE_13; } private static final SourceVersion latestSupported = getLatestSupported(); @@ -204,6 +213,8 @@ public enum SourceVersion { String specVersion = System.getProperty("java.specification.version"); switch (specVersion) { + case "13": + return RELEASE_13; case "12": return RELEASE_12; case "11": diff --git a/src/java.compiler/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor9.java index 7bd239bdb78..da18c3fc82e 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor9.java @@ -32,7 +32,7 @@ import javax.annotation.processing.SupportedSourceVersion; /** * A skeletal visitor for annotation values with default behavior * appropriate for source versions {@link SourceVersion#RELEASE_9 - * RELEASE_9} through {@link SourceVersion#RELEASE_12 RELEASE_12}. + * RELEASE_9} through {@link SourceVersion#RELEASE_13 RELEASE_13}. * *

    WARNING: The {@code AnnotationValueVisitor} interface * implemented by this class may have methods added to it in the @@ -59,7 +59,7 @@ import javax.annotation.processing.SupportedSourceVersion; * @see AbstractAnnotationValueVisitor8 * @since 9 */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public abstract class AbstractAnnotationValueVisitor9 extends AbstractAnnotationValueVisitor8 { /** diff --git a/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java index f5d69c227bc..d8d5df0b605 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java @@ -34,7 +34,7 @@ import static javax.lang.model.SourceVersion.*; /** * A skeletal visitor of program elements with default behavior * appropriate for source versions {@link SourceVersion#RELEASE_9 - * RELEASE_9} through {@link SourceVersion#RELEASE_12 RELEASE_12}. + * RELEASE_9} through {@link SourceVersion#RELEASE_13 RELEASE_13}. * *

    WARNING: The {@code ElementVisitor} interface * implemented by this class may have methods added to it in the @@ -65,7 +65,7 @@ import static javax.lang.model.SourceVersion.*; * @since 9 * @spec JPMS */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public abstract class AbstractElementVisitor9 extends AbstractElementVisitor8 { /** * Constructor for concrete subclasses to call. diff --git a/src/java.compiler/share/classes/javax/lang/model/util/AbstractTypeVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/AbstractTypeVisitor9.java index 65d6c209703..a85ec879bd8 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/AbstractTypeVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/AbstractTypeVisitor9.java @@ -33,7 +33,7 @@ import static javax.lang.model.SourceVersion.*; /** * A skeletal visitor of types with default behavior appropriate for * source versions {@link SourceVersion#RELEASE_9 RELEASE_9} through - * {@link SourceVersion#RELEASE_12 RELEASE_12}. + * {@link SourceVersion#RELEASE_13 RELEASE_13}. * *

    WARNING: The {@code TypeVisitor} interface implemented * by this class may have methods added to it in the future to @@ -63,7 +63,7 @@ import static javax.lang.model.SourceVersion.*; * @see AbstractTypeVisitor8 * @since 9 */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public abstract class AbstractTypeVisitor9 extends AbstractTypeVisitor8 { /** * Constructor for concrete subclasses to call. diff --git a/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java index 5b209645c37..02a74d9e4e2 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java @@ -34,7 +34,7 @@ import javax.lang.model.SourceVersion; * A visitor of program elements based on their {@linkplain * ElementKind kind} with default behavior appropriate for source * versions {@link SourceVersion#RELEASE_9 RELEASE_9} through {@link - * SourceVersion#RELEASE_12 RELEASE_12}. + * SourceVersion#RELEASE_13 RELEASE_13}. * * For {@linkplain * Element elements} Xyz that may have more than one @@ -80,7 +80,7 @@ import javax.lang.model.SourceVersion; * @since 9 * @spec JPMS */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class ElementKindVisitor9 extends ElementKindVisitor8 { /** * Constructor for concrete subclasses; uses {@code null} for the diff --git a/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java b/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java index 3a1ecc5a9c9..a399e3a2702 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java @@ -34,7 +34,7 @@ import static javax.lang.model.SourceVersion.*; /** * A scanning visitor of program elements with default behavior * appropriate for source versions {@link SourceVersion#RELEASE_9 - * RELEASE_9} through {@link SourceVersion#RELEASE_12 RELEASE_12}. + * RELEASE_9} through {@link SourceVersion#RELEASE_13 RELEASE_13}. * * The visitXyz methods in this * class scan their component elements by calling {@code scan} on @@ -92,7 +92,7 @@ import static javax.lang.model.SourceVersion.*; * @since 9 * @spec JPMS */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class ElementScanner9 extends ElementScanner8 { /** * Constructor for concrete subclasses; uses {@code null} for the diff --git a/src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor9.java index 0bfb7f31041..ca1fabea66f 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor9.java @@ -32,7 +32,7 @@ import static javax.lang.model.SourceVersion.*; /** * A simple visitor for annotation values with default behavior * appropriate for source versions {@link SourceVersion#RELEASE_9 - * RELEASE_9} through {@link SourceVersion#RELEASE_12 RELEASE_12}. + * RELEASE_9} through {@link SourceVersion#RELEASE_13 RELEASE_13}. * * Visit methods call {@link #defaultAction * defaultAction} passing their arguments to {@code defaultAction}'s @@ -68,7 +68,7 @@ import static javax.lang.model.SourceVersion.*; * @see SimpleAnnotationValueVisitor8 * @since 9 */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class SimpleAnnotationValueVisitor9 extends SimpleAnnotationValueVisitor8 { /** * Constructor for concrete subclasses; uses {@code null} for the diff --git a/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java index 8228addc15e..2d9218603fa 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java @@ -33,7 +33,7 @@ import static javax.lang.model.SourceVersion.*; /** * A simple visitor of program elements with default behavior * appropriate for source versions {@link SourceVersion#RELEASE_9 - * RELEASE_9} through {@link SourceVersion#RELEASE_12 RELEASE_12}. + * RELEASE_9} through {@link SourceVersion#RELEASE_13 RELEASE_13}. * * Visit methods corresponding to {@code RELEASE_9} and earlier * language constructs call {@link #defaultAction defaultAction}, @@ -73,7 +73,7 @@ import static javax.lang.model.SourceVersion.*; * @since 9 * @spec JPMS */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class SimpleElementVisitor9 extends SimpleElementVisitor8 { /** * Constructor for concrete subclasses; uses {@code null} for the diff --git a/src/java.compiler/share/classes/javax/lang/model/util/SimpleTypeVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/SimpleTypeVisitor9.java index 8420e20a800..b1e719747b3 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/SimpleTypeVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/SimpleTypeVisitor9.java @@ -33,7 +33,7 @@ import static javax.lang.model.SourceVersion.*; /** * A simple visitor of types with default behavior appropriate for * source versions {@link SourceVersion#RELEASE_9 RELEASE_9} through - * {@link SourceVersion#RELEASE_12 RELEASE_12}. + * {@link SourceVersion#RELEASE_13 RELEASE_13}. * * Visit methods corresponding to {@code RELEASE_9} and earlier * language constructs call {@link #defaultAction defaultAction}, @@ -73,7 +73,7 @@ import static javax.lang.model.SourceVersion.*; * @see SimpleTypeVisitor8 * @since 9 */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class SimpleTypeVisitor9 extends SimpleTypeVisitor8 { /** * Constructor for concrete subclasses; uses {@code null} for the diff --git a/src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor9.java b/src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor9.java index e0c55a85e5b..83f91cb32da 100644 --- a/src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor9.java +++ b/src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor9.java @@ -34,7 +34,7 @@ import static javax.lang.model.SourceVersion.*; * A visitor of types based on their {@linkplain TypeKind kind} with * default behavior appropriate for source versions {@link * SourceVersion#RELEASE_9 RELEASE_9} through {@link - * SourceVersion#RELEASE_12 RELEASE_12}. + * SourceVersion#RELEASE_13 RELEASE_13}. * * For {@linkplain * TypeMirror types} Xyz that may have more than one @@ -77,7 +77,7 @@ import static javax.lang.model.SourceVersion.*; * @see TypeKindVisitor8 * @since 9 */ -@SupportedSourceVersion(RELEASE_12) +@SupportedSourceVersion(RELEASE_13) public class TypeKindVisitor9 extends TypeKindVisitor8 { /** * Constructor for concrete subclasses to call; uses {@code null} diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java index 269b6f6e63a..9832f731200 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java @@ -85,7 +85,10 @@ public enum Source { JDK11("11"), /** 12 covers the to be determined language features that will be added in JDK 12. */ - JDK12("12"); + JDK12("12"), + + /** 13 covers the to be determined language features that will be added in JDK 13. */ + JDK13("13"); private static final Context.Key sourceKey = new Context.Key<>(); @@ -136,6 +139,7 @@ public enum Source { } public Target requiredTarget() { + if (this.compareTo(JDK13) >= 0) return Target.JDK1_13; if (this.compareTo(JDK12) >= 0) return Target.JDK1_12; if (this.compareTo(JDK11) >= 0) return Target.JDK1_11; if (this.compareTo(JDK10) >= 0) return Target.JDK1_10; @@ -182,10 +186,10 @@ public enum Source { LOCAL_VARIABLE_TYPE_INFERENCE(JDK10), VAR_SYNTAX_IMPLICIT_LAMBDAS(JDK11, Fragments.FeatureVarSyntaxInImplicitLambda, DiagKind.PLURAL), IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES(JDK1_2, JDK8), - SWITCH_MULTIPLE_CASE_LABELS(JDK12, Fragments.FeatureMultipleCaseLabels, DiagKind.PLURAL), - SWITCH_RULE(JDK12, Fragments.FeatureSwitchRules, DiagKind.PLURAL), - SWITCH_EXPRESSION(JDK12, Fragments.FeatureSwitchExpressions, DiagKind.PLURAL), - RAW_STRING_LITERALS(JDK12, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL); + SWITCH_MULTIPLE_CASE_LABELS(JDK13, Fragments.FeatureMultipleCaseLabels, DiagKind.PLURAL), + SWITCH_RULE(JDK13, Fragments.FeatureSwitchRules, DiagKind.PLURAL), + SWITCH_EXPRESSION(JDK13, Fragments.FeatureSwitchExpressions, DiagKind.PLURAL), + RAW_STRING_LITERALS(JDK13, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL); enum DiagKind { NORMAL, @@ -270,6 +274,8 @@ public enum Source { return RELEASE_11; case JDK12: return RELEASE_12; + case JDK13: + return RELEASE_13; default: return null; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassFile.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassFile.java index a8b5774baf9..4897902d3de 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassFile.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassFile.java @@ -116,7 +116,8 @@ public class ClassFile { V53(53, 0), // JDK 1.9: modules, indy string concat V54(54, 0), // JDK 10 V55(55, 0), // JDK 11: constant dynamic, nest mates - V56(56, 0); // JDK 12 + V56(56, 0), // JDK 12 + V57(57, 0); // JDK 13 Version(int major, int minor) { this.major = major; this.minor = minor; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java index 69bb38125ef..f0c41348705 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java @@ -40,9 +40,9 @@ import static com.sun.tools.javac.main.Option.PROFILE; * deletion without notice. */ public enum Profile { - COMPACT1("compact1", 1, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12), - COMPACT2("compact2", 2, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12), - COMPACT3("compact3", 3, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12), + COMPACT1("compact1", 1, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12, Target.JDK1_13), + COMPACT2("compact2", 2, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12, Target.JDK1_13), + COMPACT3("compact3", 3, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10, Target.JDK1_11, Target.JDK1_12, Target.JDK1_13), DEFAULT { @Override diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java index 50ce888ea0d..c5bd79811c4 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java @@ -70,7 +70,10 @@ public enum Target { JDK1_11("11", 55, 0), /** JDK 12. */ - JDK1_12("12", 56, 0); + JDK1_12("12", 56, 0), + + /** JDK 13. */ + JDK1_13("13", 57, 0); private static final Context.Key targetKey = new Context.Key<>(); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java index b26e6cf52bb..dd12d26f94b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java @@ -55,7 +55,7 @@ import com.sun.tools.javac.util.StringUtils; * deletion without notice. */ @SupportedAnnotationTypes("*") -@SupportedSourceVersion(SourceVersion.RELEASE_12) +@SupportedSourceVersion(SourceVersion.RELEASE_13) public class PrintingProcessor extends AbstractProcessor { PrintWriter writer; diff --git a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/classfile/Classfile.java b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/classfile/Classfile.java index cfafa7de5c9..a671c6ef9e6 100644 --- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/classfile/Classfile.java +++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/classfile/Classfile.java @@ -49,7 +49,7 @@ public class Classfile { private final List codeAttributes; private static final int MAJOR_VERSION_JAVA_MIN = 51; // JDK7 - private static final int MAJOR_VERSION_JAVA_MAX = 56; // JDK12 + private static final int MAJOR_VERSION_JAVA_MAX = 57; // JDK13 private static final int MAGIC = 0xCAFEBABE; /** diff --git a/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java b/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java index d4603466489..7fc54ae9e4a 100644 --- a/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java +++ b/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java @@ -106,7 +106,7 @@ public class Main implements DiagnosticListener { // Keep these updated manually until there's a compiler API // that allows querying of supported releases. final Set releasesWithoutForRemoval = Set.of("6", "7", "8"); - final Set releasesWithForRemoval = Set.of("9", "10", "11", "12"); + final Set releasesWithForRemoval = Set.of("9", "10", "11", "12", "13"); final Set validReleases; { diff --git a/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java b/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java index 851e823713b..f6856ba708a 100644 --- a/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java +++ b/src/jdk.rmic/share/classes/sun/tools/java/RuntimeConstants.java @@ -67,7 +67,7 @@ public interface RuntimeConstants { /* Class File Constants */ int JAVA_MAGIC = 0xcafebabe; int JAVA_MIN_SUPPORTED_VERSION = 45; - int JAVA_MAX_SUPPORTED_VERSION = 56; + int JAVA_MAX_SUPPORTED_VERSION = 57; int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0; /* Generate class file version for 1.1 by default */ diff --git a/test/jaxp/TEST.ROOT b/test/jaxp/TEST.ROOT index 6414d1335bf..e9525b912b3 100644 --- a/test/jaxp/TEST.ROOT +++ b/test/jaxp/TEST.ROOT @@ -23,7 +23,7 @@ modules=java.xml groups=TEST.groups # Minimum jtreg version -requiredVersion=4.2 b12 +requiredVersion=4.2 b13 # Path to libraries in the topmost test directory. This is needed so @library # does not need ../../ notation to reach them diff --git a/test/jdk/TEST.ROOT b/test/jdk/TEST.ROOT index 588dec4e8f8..15be645fbf4 100644 --- a/test/jdk/TEST.ROOT +++ b/test/jdk/TEST.ROOT @@ -49,7 +49,7 @@ requires.properties= \ release.implementor # Minimum jtreg version -requiredVersion=4.2 b12 +requiredVersion=4.2 b13 # Path to libraries in the topmost test directory. This is needed so @library # does not need ../../ notation to reach them diff --git a/test/jdk/java/lang/module/ClassFileVersionsTest.java b/test/jdk/java/lang/module/ClassFileVersionsTest.java index e0fa0214023..7b6e606eaab 100644 --- a/test/jdk/java/lang/module/ClassFileVersionsTest.java +++ b/test/jdk/java/lang/module/ClassFileVersionsTest.java @@ -56,6 +56,7 @@ public class ClassFileVersionsTest { { 54, 0, Set.of() }, // JDK 10 { 55, 0, Set.of() }, // JDK 11 { 56, 0, Set.of() }, // JDK 12 + { 57, 0, Set.of() }, // JDK 13 }; } @@ -79,7 +80,11 @@ public class ClassFileVersionsTest { { 56, 0, Set.of(TRANSITIVE) }, { 56, 0, Set.of(STATIC, TRANSITIVE) }, - { 57, 0, Set.of()}, // JDK 13 + { 57, 0, Set.of(STATIC) }, // JDK 13 + { 57, 0, Set.of(TRANSITIVE) }, + { 57, 0, Set.of(STATIC, TRANSITIVE) }, + + { 58, 0, Set.of()}, // JDK 14 }; } diff --git a/test/langtools/TEST.ROOT b/test/langtools/TEST.ROOT index e1170445b25..f9dcfd9e360 100644 --- a/test/langtools/TEST.ROOT +++ b/test/langtools/TEST.ROOT @@ -15,7 +15,7 @@ keys=intermittent randomness groups=TEST.groups # Minimum jtreg version -requiredVersion=4.2 b12 +requiredVersion=4.2 b13 # Use new module options useNewOptions=true diff --git a/test/langtools/tools/javac/6330997/T6330997.java b/test/langtools/tools/javac/6330997/T6330997.java index ee79299f9c1..297d448c24e 100644 --- a/test/langtools/tools/javac/6330997/T6330997.java +++ b/test/langtools/tools/javac/6330997/T6330997.java @@ -32,8 +32,8 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util * @clean T1 T2 - * @compile -source 11 -target 12 T1.java - * @compile -source 11 -target 12 T2.java + * @compile -source 12 -target 13 T1.java + * @compile -source 12 -target 13 T2.java * @run main/othervm T6330997 */ diff --git a/test/langtools/tools/javac/ConditionalWithVoid.java b/test/langtools/tools/javac/ConditionalWithVoid.java index 50e0aa2c9e2..93a918d1c1c 100644 --- a/test/langtools/tools/javac/ConditionalWithVoid.java +++ b/test/langtools/tools/javac/ConditionalWithVoid.java @@ -4,7 +4,7 @@ * @summary The compiler was allowing void types in its parsing of conditional expressions. * @author tball * - * @compile/fail/ref=ConditionalWithVoid.out --enable-preview -source 12 -XDrawDiagnostics ConditionalWithVoid.java + * @compile/fail/ref=ConditionalWithVoid.out --enable-preview -source 13 -XDrawDiagnostics ConditionalWithVoid.java */ public class ConditionalWithVoid { public void test(Object o, String s) { diff --git a/test/langtools/tools/javac/RawStringLiteralLang.java b/test/langtools/tools/javac/RawStringLiteralLang.java index c142182dd45..3589095b82e 100644 --- a/test/langtools/tools/javac/RawStringLiteralLang.java +++ b/test/langtools/tools/javac/RawStringLiteralLang.java @@ -24,7 +24,7 @@ /* * @test * @summary Unit tests for Raw String Literal language changes - * @compile --enable-preview -source 12 -encoding utf8 RawStringLiteralLang.java + * @compile --enable-preview -source 13 -encoding utf8 RawStringLiteralLang.java * @run main/othervm --enable-preview RawStringLiteralLang */ diff --git a/test/langtools/tools/javac/RawStringLiteralLangAPI.java b/test/langtools/tools/javac/RawStringLiteralLangAPI.java index 0dcee4cc273..7707525c49f 100644 --- a/test/langtools/tools/javac/RawStringLiteralLangAPI.java +++ b/test/langtools/tools/javac/RawStringLiteralLangAPI.java @@ -130,7 +130,7 @@ public class RawStringLiteralLangAPI { new JavacTask(TOOLBOX) .sources(code) .classpath(".") - .options("--enable-preview", "-source", "12") + .options("--enable-preview", "-source", "13") .run(); String output = new JavaTask(TOOLBOX) .vmOptions("--enable-preview") @@ -153,7 +153,7 @@ public class RawStringLiteralLangAPI { String output = new JavacTask(TOOLBOX) .sources(source) .classpath(".") - .options("--enable-preview", "-source", "12", "-encoding", "utf8") + .options("--enable-preview", "-source", "13", "-encoding", "utf8") .run() .writeAll() .getOutput(Task.OutputKind.DIRECT); @@ -170,7 +170,7 @@ public class RawStringLiteralLangAPI { String errors = new JavacTask(TOOLBOX) .sources(source) .classpath(".") - .options("-XDrawDiagnostics", "--enable-preview", "-source", "12", "-encoding", "utf8") + .options("-XDrawDiagnostics", "--enable-preview", "-source", "13", "-encoding", "utf8") .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); diff --git a/test/langtools/tools/javac/api/T6395981.java b/test/langtools/tools/javac/api/T6395981.java index 60b63dba3a6..60c4526dcd9 100644 --- a/test/langtools/tools/javac/api/T6395981.java +++ b/test/langtools/tools/javac/api/T6395981.java @@ -23,7 +23,7 @@ /* * @test - * @bug 6395981 6458819 7025784 8028543 8028544 8193291 8193292 8193292 + * @bug 6395981 6458819 7025784 8028543 8028544 8193291 8193292 8193292 8205393 * @summary JavaCompilerTool and Tool must specify version of JLS and JVMS * @author Peter von der Ah\u00e9 * @modules java.compiler @@ -31,7 +31,7 @@ * @run main/fail T6395981 * @run main/fail T6395981 RELEASE_3 RELEASE_5 RELEASE_6 * @run main/fail T6395981 RELEASE_0 RELEASE_1 RELEASE_2 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6 - * @run main T6395981 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6 RELEASE_7 RELEASE_8 RELEASE_9 RELEASE_10 RELEASE_11 RELEASE_12 + * @run main T6395981 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6 RELEASE_7 RELEASE_8 RELEASE_9 RELEASE_10 RELEASE_11 RELEASE_12 RELEASE_13 */ import java.util.EnumSet; diff --git a/test/langtools/tools/javac/classfiles/ClassVersionChecker.java b/test/langtools/tools/javac/classfiles/ClassVersionChecker.java index e17bdc079f0..346441c9e6f 100644 --- a/test/langtools/tools/javac/classfiles/ClassVersionChecker.java +++ b/test/langtools/tools/javac/classfiles/ClassVersionChecker.java @@ -47,7 +47,8 @@ public class ClassVersionChecker { NINE("9", 53), TEN("10", 54), ELEVEN("11", 55), - TWELVE("12", 56); + TWELVE("12", 56), + THIRTEEN("13", 57); private Version(String release, int classFileVer) { this.release = release; diff --git a/test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java b/test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java index f5c63912eef..c28960a8fbb 100644 --- a/test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java +++ b/test/langtools/tools/javac/diags/examples/BreakAmbiguousTarget.java @@ -24,7 +24,7 @@ // key: compiler.err.break.ambiguous.target // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class BreakAmbiguousTarget { void m(int i, int j) { diff --git a/test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java b/test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java index a7e29e64c02..0eb1ab3799e 100644 --- a/test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java +++ b/test/langtools/tools/javac/diags/examples/BreakExprNotImmediate.java @@ -33,7 +33,7 @@ // key: compiler.note.preview.filename // key: compiler.note.preview.recompile // key: compiler.note.note -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 // run: backdoor class BreakExprNotImmediate { diff --git a/test/langtools/tools/javac/diags/examples/BreakMissingValue.java b/test/langtools/tools/javac/diags/examples/BreakMissingValue.java index 36346ccd2bd..0ea668ba305 100644 --- a/test/langtools/tools/javac/diags/examples/BreakMissingValue.java +++ b/test/langtools/tools/javac/diags/examples/BreakMissingValue.java @@ -24,7 +24,7 @@ // key: compiler.err.break.missing.value // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class BreakMissingValue { int t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/BreakOutsideSwitchExpression.java b/test/langtools/tools/javac/diags/examples/BreakOutsideSwitchExpression.java index 3012e900842..f980c5e4720 100644 --- a/test/langtools/tools/javac/diags/examples/BreakOutsideSwitchExpression.java +++ b/test/langtools/tools/javac/diags/examples/BreakOutsideSwitchExpression.java @@ -24,7 +24,7 @@ // key: compiler.err.break.outside.switch.expression // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class BreakOutsideSwitchExpression { int t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/ContinueOutsideSwitchExpression.java b/test/langtools/tools/javac/diags/examples/ContinueOutsideSwitchExpression.java index 6cd8738c626..f5d1d278dcc 100644 --- a/test/langtools/tools/javac/diags/examples/ContinueOutsideSwitchExpression.java +++ b/test/langtools/tools/javac/diags/examples/ContinueOutsideSwitchExpression.java @@ -24,7 +24,7 @@ // key: compiler.err.continue.outside.switch.expression // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class ContinueOutsideSwitchExpression { int t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/IncompatibleTypesInSwitchExpression.java b/test/langtools/tools/javac/diags/examples/IncompatibleTypesInSwitchExpression.java index d182a36d21f..bba166c3eb1 100644 --- a/test/langtools/tools/javac/diags/examples/IncompatibleTypesInSwitchExpression.java +++ b/test/langtools/tools/javac/diags/examples/IncompatibleTypesInSwitchExpression.java @@ -26,7 +26,7 @@ // key: compiler.misc.inconvertible.types // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class IncompatibleTypesInSwitchExpression { diff --git a/test/langtools/tools/javac/diags/examples/MultipleCaseLabels.java b/test/langtools/tools/javac/diags/examples/MultipleCaseLabels.java index 469bf03f137..0db0884115c 100644 --- a/test/langtools/tools/javac/diags/examples/MultipleCaseLabels.java +++ b/test/langtools/tools/javac/diags/examples/MultipleCaseLabels.java @@ -23,7 +23,7 @@ // key: compiler.misc.feature.multiple.case.labels // key: compiler.warn.preview.feature.use.plural -// options: --enable-preview -source 12 -Xlint:preview +// options: --enable-preview -source 13 -Xlint:preview class MultipleCaseLabels { void m(int i) { diff --git a/test/langtools/tools/javac/diags/examples/NotExhaustive.java b/test/langtools/tools/javac/diags/examples/NotExhaustive.java index 008bffbeb77..846bc9cdeb5 100644 --- a/test/langtools/tools/javac/diags/examples/NotExhaustive.java +++ b/test/langtools/tools/javac/diags/examples/NotExhaustive.java @@ -24,7 +24,7 @@ // key: compiler.err.not.exhaustive // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class NotExhaustive { int t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/PreviewFeatureUse.java b/test/langtools/tools/javac/diags/examples/PreviewFeatureUse.java index c1d669d4c81..3dbb2270c4e 100644 --- a/test/langtools/tools/javac/diags/examples/PreviewFeatureUse.java +++ b/test/langtools/tools/javac/diags/examples/PreviewFeatureUse.java @@ -25,7 +25,7 @@ //key: compiler.warn.preview.feature.use.plural //key: compiler.misc.feature.diamond //key: compiler.misc.feature.lambda -//options: -Xlint:preview -XDforcePreview -source 12 --enable-preview +//options: -Xlint:preview -XDforcePreview -source 13 --enable-preview import java.util.ArrayList; diff --git a/test/langtools/tools/javac/diags/examples/PreviewFilename.java b/test/langtools/tools/javac/diags/examples/PreviewFilename.java index cb112127942..04edcdf8715 100644 --- a/test/langtools/tools/javac/diags/examples/PreviewFilename.java +++ b/test/langtools/tools/javac/diags/examples/PreviewFilename.java @@ -23,7 +23,7 @@ // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: -XDforcePreview -source 12 --enable-preview +// options: -XDforcePreview -source 13 --enable-preview import java.util.ArrayList; import java.util.List; diff --git a/test/langtools/tools/javac/diags/examples/PreviewFilenameAdditional.java b/test/langtools/tools/javac/diags/examples/PreviewFilenameAdditional.java index 98b9bce94cb..3d5430de389 100644 --- a/test/langtools/tools/javac/diags/examples/PreviewFilenameAdditional.java +++ b/test/langtools/tools/javac/diags/examples/PreviewFilenameAdditional.java @@ -24,7 +24,7 @@ // key: compiler.note.preview.filename.additional // key: compiler.warn.preview.feature.use // key: compiler.misc.feature.diamond -// options: -Xlint:preview -Xmaxwarns 1 -XDforcePreview -source 12 --enable-preview +// options: -Xlint:preview -Xmaxwarns 1 -XDforcePreview -source 13 --enable-preview import java.util.ArrayList; diff --git a/test/langtools/tools/javac/diags/examples/PreviewPlural/PreviewPlural.java b/test/langtools/tools/javac/diags/examples/PreviewPlural/PreviewPlural.java index 43d46cf4b5a..e9b92af8ded 100644 --- a/test/langtools/tools/javac/diags/examples/PreviewPlural/PreviewPlural.java +++ b/test/langtools/tools/javac/diags/examples/PreviewPlural/PreviewPlural.java @@ -23,7 +23,7 @@ // key: compiler.note.preview.plural // key: compiler.note.preview.recompile -// options: -XDforcePreview -source 12 --enable-preview +// options: -XDforcePreview -source 13 --enable-preview import java.util.ArrayList; diff --git a/test/langtools/tools/javac/diags/examples/RawStringLiteral.java b/test/langtools/tools/javac/diags/examples/RawStringLiteral.java index f6b7b23b22f..287d6ff7e59 100644 --- a/test/langtools/tools/javac/diags/examples/RawStringLiteral.java +++ b/test/langtools/tools/javac/diags/examples/RawStringLiteral.java @@ -24,7 +24,7 @@ // key: compiler.err.unicode.backtick // key: compiler.misc.feature.raw.string.literals // key: compiler.warn.preview.feature.use.plural -// options: --enable-preview -source 12 -Xlint:preview +// options: --enable-preview -source 13 -Xlint:preview class RawStringLiteral { String m() { diff --git a/test/langtools/tools/javac/diags/examples/ReturnOutsideSwitchExpression.java b/test/langtools/tools/javac/diags/examples/ReturnOutsideSwitchExpression.java index 44cda310627..9811287efc9 100644 --- a/test/langtools/tools/javac/diags/examples/ReturnOutsideSwitchExpression.java +++ b/test/langtools/tools/javac/diags/examples/ReturnOutsideSwitchExpression.java @@ -24,7 +24,7 @@ // key: compiler.err.return.outside.switch.expression // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class ReturnOutsideSwitchExpression { int t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/RuleCompletesNormally.java b/test/langtools/tools/javac/diags/examples/RuleCompletesNormally.java index 65d600c314a..bb876ac9de2 100644 --- a/test/langtools/tools/javac/diags/examples/RuleCompletesNormally.java +++ b/test/langtools/tools/javac/diags/examples/RuleCompletesNormally.java @@ -24,7 +24,7 @@ // key: compiler.err.rule.completes.normally // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class RuleCompletesNormally { public String convert(int i) { diff --git a/test/langtools/tools/javac/diags/examples/SwitchCaseUnexpectedStatement.java b/test/langtools/tools/javac/diags/examples/SwitchCaseUnexpectedStatement.java index b21f8351312..d3509b0756b 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchCaseUnexpectedStatement.java +++ b/test/langtools/tools/javac/diags/examples/SwitchCaseUnexpectedStatement.java @@ -24,7 +24,7 @@ // key: compiler.err.switch.case.unexpected.statement // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class ReturnOutsideSwitchExpression { void t(int i) { diff --git a/test/langtools/tools/javac/diags/examples/SwitchExpressionCompletesNormally.java b/test/langtools/tools/javac/diags/examples/SwitchExpressionCompletesNormally.java index 607aa2bb277..f3fef28165a 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchExpressionCompletesNormally.java +++ b/test/langtools/tools/javac/diags/examples/SwitchExpressionCompletesNormally.java @@ -24,7 +24,7 @@ // key: compiler.err.switch.expression.completes.normally // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class SwitchExpressionCompletesNormally { public String convert(int i) { diff --git a/test/langtools/tools/javac/diags/examples/SwitchExpressionEmpty.java b/test/langtools/tools/javac/diags/examples/SwitchExpressionEmpty.java index baa0d72d105..61c1d43cc04 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchExpressionEmpty.java +++ b/test/langtools/tools/javac/diags/examples/SwitchExpressionEmpty.java @@ -24,7 +24,7 @@ // key: compiler.err.switch.expression.empty // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class BreakOutsideSwitchExpression { String t(E e) { diff --git a/test/langtools/tools/javac/diags/examples/SwitchExpressionTargetCantBeVoid.java b/test/langtools/tools/javac/diags/examples/SwitchExpressionTargetCantBeVoid.java index daaaa6c579d..96a52cdcf87 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchExpressionTargetCantBeVoid.java +++ b/test/langtools/tools/javac/diags/examples/SwitchExpressionTargetCantBeVoid.java @@ -26,7 +26,7 @@ // key: compiler.misc.switch.expression.target.cant.be.void // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class SwitchExpressionTargetCantBeVoid { diff --git a/test/langtools/tools/javac/diags/examples/SwitchExpressions.java b/test/langtools/tools/javac/diags/examples/SwitchExpressions.java index a4a68774893..e386b651bd0 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchExpressions.java +++ b/test/langtools/tools/javac/diags/examples/SwitchExpressions.java @@ -23,7 +23,7 @@ // key: compiler.misc.feature.switch.expressions // key: compiler.warn.preview.feature.use.plural -// options: --enable-preview -source 12 -Xlint:preview +// options: --enable-preview -source 13 -Xlint:preview class SwitchExpressions { int m(int i) { diff --git a/test/langtools/tools/javac/diags/examples/SwitchMixingCaseTypes.java b/test/langtools/tools/javac/diags/examples/SwitchMixingCaseTypes.java index 5326077aea8..dcfcbbf0fc4 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchMixingCaseTypes.java +++ b/test/langtools/tools/javac/diags/examples/SwitchMixingCaseTypes.java @@ -24,7 +24,7 @@ // key: compiler.err.switch.mixing.case.types // key: compiler.note.preview.filename // key: compiler.note.preview.recompile -// options: --enable-preview -source 12 +// options: --enable-preview -source 13 class SwitchMixingCaseTypes { diff --git a/test/langtools/tools/javac/diags/examples/SwitchRules.java b/test/langtools/tools/javac/diags/examples/SwitchRules.java index b4e12d6d8b2..fe99b8366bd 100644 --- a/test/langtools/tools/javac/diags/examples/SwitchRules.java +++ b/test/langtools/tools/javac/diags/examples/SwitchRules.java @@ -23,7 +23,7 @@ // key: compiler.misc.feature.switch.rules // key: compiler.warn.preview.feature.use.plural -// options: --enable-preview -source 12 -Xlint:preview +// options: --enable-preview -source 13 -Xlint:preview class SwitchExpressions { void m(int i) { diff --git a/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java b/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java index 9af46a3cce3..84270313db0 100644 --- a/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java +++ b/test/langtools/tools/javac/expswitch/ExpSwitchNestingTest.java @@ -75,6 +75,8 @@ public class ExpSwitchNestingTest extends JavacTemplateTestBase { } } + private static String[] PREVIEW_OPTIONS = {"--enable-preview", "-source", "13"}; + private void program(String... constructs) { String s = "class C { static boolean cond = false; static int x = 0; void m() { # } }"; for (String c : constructs) @@ -84,7 +86,7 @@ public class ExpSwitchNestingTest extends JavacTemplateTestBase { private void assertOK(String... constructs) { reset(); - addCompileOptions("--enable-preview", "-source", "12"); + addCompileOptions(PREVIEW_OPTIONS); program(constructs); try { compile(); @@ -97,7 +99,7 @@ public class ExpSwitchNestingTest extends JavacTemplateTestBase { private void assertOKWithWarning(String warning, String... constructs) { reset(); - addCompileOptions("--enable-preview", "-source", "12"); + addCompileOptions(PREVIEW_OPTIONS); program(constructs); try { compile(); @@ -110,7 +112,7 @@ public class ExpSwitchNestingTest extends JavacTemplateTestBase { private void assertFail(String expectedDiag, String... constructs) { reset(); - addCompileOptions("--enable-preview", "-source", "12"); + addCompileOptions(PREVIEW_OPTIONS); program(constructs); try { compile(); diff --git a/test/langtools/tools/javac/lambda/BadSwitchExpressionLambda.java b/test/langtools/tools/javac/lambda/BadSwitchExpressionLambda.java index 3a1bd06f67f..14fe01726d7 100644 --- a/test/langtools/tools/javac/lambda/BadSwitchExpressionLambda.java +++ b/test/langtools/tools/javac/lambda/BadSwitchExpressionLambda.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Adding switch expressions - * @compile/fail/ref=BadSwitchExpressionLambda.out -XDrawDiagnostics --enable-preview -source 12 BadSwitchExpressionLambda.java + * @compile/fail/ref=BadSwitchExpressionLambda.out -XDrawDiagnostics --enable-preview -source 13 BadSwitchExpressionLambda.java */ class BadSwitchExpressionLambda { diff --git a/test/langtools/tools/javac/lib/JavacTestingAbstractProcessor.java b/test/langtools/tools/javac/lib/JavacTestingAbstractProcessor.java index 59db96f4539..9e28eca5695 100644 --- a/test/langtools/tools/javac/lib/JavacTestingAbstractProcessor.java +++ b/test/langtools/tools/javac/lib/JavacTestingAbstractProcessor.java @@ -110,7 +110,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { * corresponding platform visitor type. */ - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static abstract class AbstractAnnotationValueVisitor extends AbstractAnnotationValueVisitor9 { /** @@ -121,7 +121,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static abstract class AbstractElementVisitor extends AbstractElementVisitor9 { /** * Constructor for concrete subclasses to call. @@ -131,7 +131,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static abstract class AbstractTypeVisitor extends AbstractTypeVisitor9 { /** * Constructor for concrete subclasses to call. @@ -141,7 +141,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class ElementKindVisitor extends ElementKindVisitor9 { /** * Constructor for concrete subclasses; uses {@code null} for the @@ -162,7 +162,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class ElementScanner extends ElementScanner9 { /** * Constructor for concrete subclasses; uses {@code null} for the @@ -181,7 +181,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class SimpleAnnotationValueVisitor extends SimpleAnnotationValueVisitor9 { /** * Constructor for concrete subclasses; uses {@code null} for the @@ -202,7 +202,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class SimpleElementVisitor extends SimpleElementVisitor9 { /** * Constructor for concrete subclasses; uses {@code null} for the @@ -223,7 +223,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class SimpleTypeVisitor extends SimpleTypeVisitor9 { /** * Constructor for concrete subclasses; uses {@code null} for the @@ -244,7 +244,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor { } } - @SupportedSourceVersion(RELEASE_12) + @SupportedSourceVersion(RELEASE_13) public static class TypeKindVisitor extends TypeKindVisitor9 { /** * Constructor for concrete subclasses to call; uses {@code null} diff --git a/test/langtools/tools/javac/parser/JavacParserTest.java b/test/langtools/tools/javac/parser/JavacParserTest.java index 8e7eddd2016..6844282258f 100644 --- a/test/langtools/tools/javac/parser/JavacParserTest.java +++ b/test/langtools/tools/javac/parser/JavacParserTest.java @@ -1096,7 +1096,7 @@ public class JavacParserTest extends TestCase { String expectedErrors = "Test.java:1:178: compiler.err.switch.case.unexpected.statement\n"; StringWriter out = new StringWriter(); JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(out, fm, null, - Arrays.asList("-XDrawDiagnostics", "--enable-preview", "-source", "12"), + Arrays.asList("-XDrawDiagnostics", "--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(code))); CompilationUnitTree cut = ct.parse().iterator().next(); diff --git a/test/langtools/tools/javac/preview/classReaderTest/Client.java b/test/langtools/tools/javac/preview/classReaderTest/Client.java index e8a05ba89b5..4c122887033 100644 --- a/test/langtools/tools/javac/preview/classReaderTest/Client.java +++ b/test/langtools/tools/javac/preview/classReaderTest/Client.java @@ -2,9 +2,9 @@ * @test /nodynamiccopyright/ * @bug 8199194 * @summary smoke test for --enabled-preview classreader support - * @compile -XDforcePreview --enable-preview -source 12 Bar.java + * @compile -XDforcePreview --enable-preview -source 13 Bar.java * @compile/fail/ref=Client.nopreview.out -Xlint:preview -XDrawDiagnostics Client.java - * @compile/fail/ref=Client.preview.out -Werror -Xlint:preview -XDrawDiagnostics --enable-preview -source 12 Client.java + * @compile/fail/ref=Client.preview.out -Werror -Xlint:preview -XDrawDiagnostics --enable-preview -source 13 Client.java */ public class Client { diff --git a/test/langtools/tools/javac/preview/classReaderTest/Client.nopreview.out b/test/langtools/tools/javac/preview/classReaderTest/Client.nopreview.out index bd201c2ce54..05f9b25b304 100644 --- a/test/langtools/tools/javac/preview/classReaderTest/Client.nopreview.out +++ b/test/langtools/tools/javac/preview/classReaderTest/Client.nopreview.out @@ -1,2 +1,2 @@ -- compiler.err.preview.feature.disabled.classfile: Bar.class, 12 +- compiler.err.preview.feature.disabled.classfile: Bar.class, 13 1 error diff --git a/test/langtools/tools/javac/preview/classReaderTest/Client.preview.out b/test/langtools/tools/javac/preview/classReaderTest/Client.preview.out index 2bfaffd4450..d4c86919361 100644 --- a/test/langtools/tools/javac/preview/classReaderTest/Client.preview.out +++ b/test/langtools/tools/javac/preview/classReaderTest/Client.preview.out @@ -1,4 +1,4 @@ -- compiler.warn.preview.feature.use.classfile: Bar.class, 12 +- compiler.warn.preview.feature.use.classfile: Bar.class, 13 - compiler.err.warnings.and.werror 1 error 1 warning diff --git a/test/langtools/tools/javac/profiles/ProfileOptionTest.java b/test/langtools/tools/javac/profiles/ProfileOptionTest.java index b5cb452583c..67cb0487ce7 100644 --- a/test/langtools/tools/javac/profiles/ProfileOptionTest.java +++ b/test/langtools/tools/javac/profiles/ProfileOptionTest.java @@ -151,6 +151,7 @@ public class ProfileOptionTest { case JDK1_10: case JDK1_11: case JDK1_12: + case JDK1_13: if (p == Profile.DEFAULT) break; if (ise == null) diff --git a/test/langtools/tools/javac/switchexpr/BlockExpression.java b/test/langtools/tools/javac/switchexpr/BlockExpression.java index a6d300a63d1..0534ccb180c 100644 --- a/test/langtools/tools/javac/switchexpr/BlockExpression.java +++ b/test/langtools/tools/javac/switchexpr/BlockExpression.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Verify rule cases with expression statements and throw statements work. - * @compile --enable-preview -source 12 BlockExpression.java + * @compile --enable-preview -source 13 BlockExpression.java * @run main/othervm --enable-preview BlockExpression */ diff --git a/test/langtools/tools/javac/switchexpr/BooleanNumericNonNumeric.java b/test/langtools/tools/javac/switchexpr/BooleanNumericNonNumeric.java index 1df8861c957..2f5aac13fce 100644 --- a/test/langtools/tools/javac/switchexpr/BooleanNumericNonNumeric.java +++ b/test/langtools/tools/javac/switchexpr/BooleanNumericNonNumeric.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify the type of a conditional expression with nested switch expression is computed properly - * @compile/fail/ref=BooleanNumericNonNumeric.out -XDrawDiagnostics --enable-preview -source 12 BooleanNumericNonNumeric.java + * @compile/fail/ref=BooleanNumericNonNumeric.out -XDrawDiagnostics --enable-preview -source 13 BooleanNumericNonNumeric.java */ public class BooleanNumericNonNumeric { diff --git a/test/langtools/tools/javac/switchexpr/BreakTest.java b/test/langtools/tools/javac/switchexpr/BreakTest.java index 7eca3a805de..ea8b22580e5 100644 --- a/test/langtools/tools/javac/switchexpr/BreakTest.java +++ b/test/langtools/tools/javac/switchexpr/BreakTest.java @@ -66,7 +66,7 @@ public class BreakTest { StringWriter out = new StringWriter(); JavacTask ct = (JavacTask) tool.getTask(out, null, noErrors, - List.of("-XDdev", "--enable-preview", "-source", "12"), null, + List.of("-XDdev", "--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(CODE))); List labels = new ArrayList<>(); new TreePathScanner() { diff --git a/test/langtools/tools/javac/switchexpr/CRT.java b/test/langtools/tools/javac/switchexpr/CRT.java index 630e9c257ce..efaf656d822 100644 --- a/test/langtools/tools/javac/switchexpr/CRT.java +++ b/test/langtools/tools/javac/switchexpr/CRT.java @@ -151,7 +151,7 @@ public class CRT { new JavacTask(tb) .options("-Xjcov", "--enable-preview", - "-source", "12") + "-source", "13") .outdir(classes) .sources("public class Test {\n" + code + diff --git a/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java b/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java index c7c0fbfdb36..d58c23bbb59 100644 --- a/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java +++ b/test/langtools/tools/javac/switchexpr/DefiniteAssignment1.java @@ -25,7 +25,7 @@ * @test * @bug 8214031 * @summary Verify that definite assignment when true works (legal code) - * @compile --enable-preview --source 12 DefiniteAssignment1.java + * @compile --enable-preview --source 13 DefiniteAssignment1.java * @run main/othervm --enable-preview DefiniteAssignment1 */ public class DefiniteAssignment1 { diff --git a/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java b/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java index 7c7e9db6500..706b83d5ab8 100644 --- a/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java +++ b/test/langtools/tools/javac/switchexpr/DefiniteAssignment2.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8214031 * @summary Verify that definite assignment when true works (illegal code) - * @compile/fail/ref=DefiniteAssignment2.out --enable-preview --source 12 -XDrawDiagnostics DefiniteAssignment2.java + * @compile/fail/ref=DefiniteAssignment2.out --enable-preview --source 13 -XDrawDiagnostics DefiniteAssignment2.java */ public class DefiniteAssignment2 { diff --git a/test/langtools/tools/javac/switchexpr/EmptySwitch.java b/test/langtools/tools/javac/switchexpr/EmptySwitch.java index f1e169fb314..bf26578ea1b 100644 --- a/test/langtools/tools/javac/switchexpr/EmptySwitch.java +++ b/test/langtools/tools/javac/switchexpr/EmptySwitch.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Verify than an empty switch expression is rejected. - * @compile/fail/ref=EmptySwitch.out --enable-preview -source 12 -XDrawDiagnostics EmptySwitch.java + * @compile/fail/ref=EmptySwitch.out --enable-preview -source 13 -XDrawDiagnostics EmptySwitch.java */ public class EmptySwitch { diff --git a/test/langtools/tools/javac/switchexpr/ExhaustiveEnumSwitch.java b/test/langtools/tools/javac/switchexpr/ExhaustiveEnumSwitch.java index 3f13f98bc5f..bbe728a5300 100644 --- a/test/langtools/tools/javac/switchexpr/ExhaustiveEnumSwitch.java +++ b/test/langtools/tools/javac/switchexpr/ExhaustiveEnumSwitch.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Verify that an switch expression over enum can be exhaustive without default. - * @compile --enable-preview -source 12 ExhaustiveEnumSwitch.java + * @compile --enable-preview -source 13 ExhaustiveEnumSwitch.java * @compile ExhaustiveEnumSwitchExtra.java * @run main/othervm --enable-preview ExhaustiveEnumSwitch */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java index 283ec3a5989..67c0fbb61d7 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitch.java @@ -3,7 +3,7 @@ * @bug 8206986 * @summary Check expression switch works. * @compile/fail/ref=ExpressionSwitch-old.out -source 9 -Xlint:-options -XDrawDiagnostics ExpressionSwitch.java - * @compile --enable-preview -source 12 ExpressionSwitch.java + * @compile --enable-preview -source 13 ExpressionSwitch.java * @run main/othervm --enable-preview ExpressionSwitch */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java index 3b5774805c3..198350e8862 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks1.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Verify behavior of various kinds of breaks. - * @compile --enable-preview -source 12 ExpressionSwitchBreaks1.java + * @compile --enable-preview -source 13 ExpressionSwitchBreaks1.java * @run main/othervm --enable-preview ExpressionSwitchBreaks1 */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java index 056ba32bc45..66e9023b4ef 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBreaks2.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Check behavior for invalid breaks. - * @compile/fail/ref=ExpressionSwitchBreaks2.out -XDrawDiagnostics --enable-preview -source 12 ExpressionSwitchBreaks2.java + * @compile/fail/ref=ExpressionSwitchBreaks2.out -XDrawDiagnostics --enable-preview -source 13 ExpressionSwitchBreaks2.java */ public class ExpressionSwitchBreaks2 { diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java index b768a163869..873f9d1b59a 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugs.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 8214114 8214529 * @summary Verify various corner cases with nested switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchBugs.java + * @compile --enable-preview -source 13 ExpressionSwitchBugs.java * @run main/othervm --enable-preview ExpressionSwitchBugs */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugsInGen.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugsInGen.java index a2a175a04d5..9dd0c5e4b63 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugsInGen.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchBugsInGen.java @@ -25,7 +25,7 @@ * @test * @bug 8214031 * @summary Verify various corner cases with nested switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchBugsInGen.java + * @compile --enable-preview -source 13 ExpressionSwitchBugsInGen.java * @run main/othervm --enable-preview ExpressionSwitchBugsInGen */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchCodeFromJLS.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchCodeFromJLS.java index 95b53fcaa05..f9564bafc86 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchCodeFromJLS.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchCodeFromJLS.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Check switch expressions - * @compile --enable-preview -source 12 ExpressionSwitchCodeFromJLS.java + * @compile --enable-preview -source 13 ExpressionSwitchCodeFromJLS.java * @run main/othervm --enable-preview ExpressionSwitchCodeFromJLS */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java index 7e54f3f1732..9815b27dd48 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchDA.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Check definite (un)assignment for in switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchDA.java + * @compile --enable-preview -source 13 ExpressionSwitchDA.java * @run main/othervm --enable-preview ExpressionSwitchDA */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java index d70ef7ead4e..997b69ce927 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchEmbedding.java @@ -25,7 +25,7 @@ * @test * @bug 8214031 8214114 * @summary Verify switch expressions embedded in various statements work properly. - * @compile --enable-preview -source 12 ExpressionSwitchEmbedding.java + * @compile --enable-preview -source 13 ExpressionSwitchEmbedding.java * @run main/othervm --enable-preview ExpressionSwitchEmbedding */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java index 4c1635e332a..f51e51ad9a0 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Check fall through in switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchFallThrough.java + * @compile --enable-preview -source 13 ExpressionSwitchFallThrough.java * @run main/othervm --enable-preview ExpressionSwitchFallThrough */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java index 18f11035599..2f60e88c7e5 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFallThrough1.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Check fall through in switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchFallThrough1.java + * @compile --enable-preview -source 13 ExpressionSwitchFallThrough1.java * @run main/othervm --enable-preview ExpressionSwitchFallThrough1 */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java index 31734f2c81b..f5cd71af5cb 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchFlow.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8212982 * @summary Verify a compile-time error is produced if switch expression does not provide a value - * @compile/fail/ref=ExpressionSwitchFlow.out --enable-preview -source 12 -XDrawDiagnostics ExpressionSwitchFlow.java + * @compile/fail/ref=ExpressionSwitchFlow.out --enable-preview -source 13 -XDrawDiagnostics ExpressionSwitchFlow.java */ public class ExpressionSwitchFlow { diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java index a4602c17658..6d57ffa16ea 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInExpressionSwitch.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Check switch expressions embedded in switch expressions. - * @compile --enable-preview -source 12 ExpressionSwitchInExpressionSwitch.java + * @compile --enable-preview -source 13 ExpressionSwitchInExpressionSwitch.java * @run main/othervm --enable-preview ExpressionSwitchInExpressionSwitch */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java index ea854b4c4f2..8b6d32535eb 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchInfer.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Check types inferred for switch expressions. - * @compile/fail/ref=ExpressionSwitchInfer.out -XDrawDiagnostics --enable-preview -source 12 ExpressionSwitchInfer.java + * @compile/fail/ref=ExpressionSwitchInfer.out -XDrawDiagnostics --enable-preview -source 13 ExpressionSwitchInfer.java */ import java.util.ArrayList; diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchIntersectionTypes.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchIntersectionTypes.java index 516ae2357ab..a1f13b83d76 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchIntersectionTypes.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchIntersectionTypes.java @@ -25,7 +25,7 @@ * @test * @bug 8206986 * @summary Verify behavior when an intersection type is inferred for switch expression. - * @compile --enable-preview -source 12 ExpressionSwitchIntersectionTypes.java + * @compile --enable-preview -source 13 ExpressionSwitchIntersectionTypes.java * @run main/othervm --enable-preview ExpressionSwitchIntersectionTypes */ diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java index 42107b2c5a0..8f4ea2e80c6 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchNotExhaustive.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify behavior of not exhaustive switch expressions. - * @compile/fail/ref=ExpressionSwitchNotExhaustive.out -XDrawDiagnostics --enable-preview -source 12 ExpressionSwitchNotExhaustive.java + * @compile/fail/ref=ExpressionSwitchNotExhaustive.out -XDrawDiagnostics --enable-preview -source 13 ExpressionSwitchNotExhaustive.java */ public class ExpressionSwitchNotExhaustive { diff --git a/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java b/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java index 769e3dd0fbf..978e49e1088 100644 --- a/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java +++ b/test/langtools/tools/javac/switchexpr/ExpressionSwitchUnreachable.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify reachability in switch expressions. - * @compile/fail/ref=ExpressionSwitchUnreachable.out -XDrawDiagnostics --enable-preview -source 12 ExpressionSwitchUnreachable.java + * @compile/fail/ref=ExpressionSwitchUnreachable.out -XDrawDiagnostics --enable-preview -source 13 ExpressionSwitchUnreachable.java */ public class ExpressionSwitchUnreachable { diff --git a/test/langtools/tools/javac/switchexpr/ParseIncomplete.java b/test/langtools/tools/javac/switchexpr/ParseIncomplete.java index 2463560c1bb..159ba634d96 100644 --- a/test/langtools/tools/javac/switchexpr/ParseIncomplete.java +++ b/test/langtools/tools/javac/switchexpr/ParseIncomplete.java @@ -67,7 +67,7 @@ public class ParseIncomplete { StringWriter out = new StringWriter(); try { JavacTask ct = (JavacTask) tool.getTask(out, null, noErrors, - List.of("-XDdev", "--enable-preview", "-source", "12"), null, + List.of("-XDdev", "--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(code))); ct.parse().iterator().next(); } catch (Throwable t) { diff --git a/test/langtools/tools/javac/switchexpr/ParserRecovery.java b/test/langtools/tools/javac/switchexpr/ParserRecovery.java index 261c1a8a31c..7c197c288b8 100644 --- a/test/langtools/tools/javac/switchexpr/ParserRecovery.java +++ b/test/langtools/tools/javac/switchexpr/ParserRecovery.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify the parser handles broken input gracefully. - * @compile/fail/ref=ParserRecovery.out -XDrawDiagnostics --enable-preview -source 12 ParserRecovery.java + * @compile/fail/ref=ParserRecovery.out -XDrawDiagnostics --enable-preview -source 13 ParserRecovery.java */ public class ParserRecovery { diff --git a/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java b/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java index d7f9b6844c8..1cae5e7ade9 100644 --- a/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java +++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java @@ -26,7 +26,7 @@ * @bug 8214113 * @summary Verify the switch expression's type does not have a constant attached, * and so the switch expression is not elided. - * @compile --enable-preview --source 12 SwitchExpressionIsNotAConstant.java + * @compile --enable-preview --source 13 SwitchExpressionIsNotAConstant.java * @run main/othervm --enable-preview SwitchExpressionIsNotAConstant */ public class SwitchExpressionIsNotAConstant { diff --git a/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java b/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java index cdd79721aee..295a1dc9119 100644 --- a/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java +++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionScopesIsolated.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify that scopes in rule cases are isolated. - * @compile/fail/ref=SwitchExpressionScopesIsolated.out -XDrawDiagnostics --enable-preview -source 12 SwitchExpressionScopesIsolated.java + * @compile/fail/ref=SwitchExpressionScopesIsolated.out -XDrawDiagnostics --enable-preview -source 13 SwitchExpressionScopesIsolated.java */ public class SwitchExpressionScopesIsolated { diff --git a/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java b/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java index b61bbdae4fb..4df450874c6 100644 --- a/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java +++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionSimpleVisitorTest.java @@ -89,7 +89,7 @@ public class SwitchExpressionSimpleVisitorTest { StringWriter out = new StringWriter(); JavacTask ct = (JavacTask) tool.getTask(out, null, noErrors, - List.of("--enable-preview", "-source", "12"), null, + List.of("--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(code))); return ct.parse().iterator().next(); } diff --git a/test/langtools/tools/javac/switchexpr/TryCatch.java b/test/langtools/tools/javac/switchexpr/TryCatch.java index 459a9712592..768292b3b5d 100644 --- a/test/langtools/tools/javac/switchexpr/TryCatch.java +++ b/test/langtools/tools/javac/switchexpr/TryCatch.java @@ -25,7 +25,7 @@ * @test * @bug 8214114 * @summary Verify try-catch inside a switch expression works properly. - * @compile --enable-preview -source 12 TryCatch.java + * @compile --enable-preview -source 13 TryCatch.java * @run main/othervm --enable-preview TryCatch */ public class TryCatch { diff --git a/test/langtools/tools/javac/switchextra/CaseTest.java b/test/langtools/tools/javac/switchextra/CaseTest.java index 358cd5c5817..99315e79213 100644 --- a/test/langtools/tools/javac/switchextra/CaseTest.java +++ b/test/langtools/tools/javac/switchextra/CaseTest.java @@ -136,7 +136,7 @@ public class CaseTest { StringWriter out = new StringWriter(); JavacTask ct = (JavacTask) tool.getTask(out, null, noErrors, - List.of("-XDdev", "--enable-preview", "-source", "12"), null, + List.of("-XDdev", "--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(code))); return ct.parse().iterator().next(); } diff --git a/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java b/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java index 862b6fe5a46..170da1b3375 100644 --- a/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java +++ b/test/langtools/tools/javac/switchextra/MultipleLabelsExpression.java @@ -3,7 +3,7 @@ * @bug 8206986 * @summary Verify cases with multiple labels work properly. * @compile/fail/ref=MultipleLabelsExpression-old.out -source 9 -Xlint:-options -XDrawDiagnostics MultipleLabelsExpression.java - * @compile --enable-preview -source 12 MultipleLabelsExpression.java + * @compile --enable-preview -source 13 MultipleLabelsExpression.java * @run main/othervm --enable-preview MultipleLabelsExpression */ diff --git a/test/langtools/tools/javac/switchextra/MultipleLabelsStatement.java b/test/langtools/tools/javac/switchextra/MultipleLabelsStatement.java index 8e29daeb6f1..b674e92b960 100644 --- a/test/langtools/tools/javac/switchextra/MultipleLabelsStatement.java +++ b/test/langtools/tools/javac/switchextra/MultipleLabelsStatement.java @@ -3,7 +3,7 @@ * @bug 8206986 * @summary Verify cases with multiple labels work properly. * @compile/fail/ref=MultipleLabelsStatement-old.out -source 9 -Xlint:-options -XDrawDiagnostics MultipleLabelsStatement.java - * @compile --enable-preview -source 12 MultipleLabelsStatement.java + * @compile --enable-preview -source 13 MultipleLabelsStatement.java * @run main/othervm --enable-preview MultipleLabelsStatement */ diff --git a/test/langtools/tools/javac/switchextra/RuleParsingTest.java b/test/langtools/tools/javac/switchextra/RuleParsingTest.java index bb9d7787802..afdaa929edc 100644 --- a/test/langtools/tools/javac/switchextra/RuleParsingTest.java +++ b/test/langtools/tools/javac/switchextra/RuleParsingTest.java @@ -94,7 +94,7 @@ public class RuleParsingTest { StringWriter out = new StringWriter(); JavacTask ct = (JavacTask) tool.getTask(out, null, noErrors, - List.of("--enable-preview", "-source", "12"), null, + List.of("--enable-preview", "-source", "13"), null, Arrays.asList(new MyFileObject(code.toString()))); CompilationUnitTree cut = ct.parse().iterator().next(); Trees trees = Trees.instance(ct); diff --git a/test/langtools/tools/javac/switchextra/SwitchArrowBrokenConstant.java b/test/langtools/tools/javac/switchextra/SwitchArrowBrokenConstant.java index fddbde2819f..e1cec5ac34d 100644 --- a/test/langtools/tools/javac/switchextra/SwitchArrowBrokenConstant.java +++ b/test/langtools/tools/javac/switchextra/SwitchArrowBrokenConstant.java @@ -3,7 +3,7 @@ * @bug 8206986 * @summary Verify reasonable errors are produced when neither ':' nor '->' * is found are the expression of a case - * @compile/fail/ref=SwitchArrowBrokenConstant.out -source 12 --enable-preview -Xlint:-preview -XDrawDiagnostics SwitchArrowBrokenConstant.java + * @compile/fail/ref=SwitchArrowBrokenConstant.out -source 13 --enable-preview -Xlint:-preview -XDrawDiagnostics SwitchArrowBrokenConstant.java */ public class SwitchArrowBrokenConstant { diff --git a/test/langtools/tools/javac/switchextra/SwitchStatementArrow.java b/test/langtools/tools/javac/switchextra/SwitchStatementArrow.java index 8c004fa1a22..599adacc97f 100644 --- a/test/langtools/tools/javac/switchextra/SwitchStatementArrow.java +++ b/test/langtools/tools/javac/switchextra/SwitchStatementArrow.java @@ -3,7 +3,7 @@ * @bug 8206986 * @summary Verify rule cases work properly. * @compile/fail/ref=SwitchStatementArrow-old.out -source 9 -Xlint:-options -XDrawDiagnostics SwitchStatementArrow.java - * @compile --enable-preview -source 12 SwitchStatementArrow.java + * @compile --enable-preview -source 13 SwitchStatementArrow.java * @run main/othervm --enable-preview SwitchStatementArrow */ diff --git a/test/langtools/tools/javac/switchextra/SwitchStatementBroken.java b/test/langtools/tools/javac/switchextra/SwitchStatementBroken.java index 53493397e15..6882c2d0e1e 100644 --- a/test/langtools/tools/javac/switchextra/SwitchStatementBroken.java +++ b/test/langtools/tools/javac/switchextra/SwitchStatementBroken.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify that rule and ordinary cases cannot be mixed. - * @compile/fail/ref=SwitchStatementBroken.out -XDrawDiagnostics --enable-preview -source 12 SwitchStatementBroken.java + * @compile/fail/ref=SwitchStatementBroken.out -XDrawDiagnostics --enable-preview -source 13 SwitchStatementBroken.java */ public class SwitchStatementBroken { diff --git a/test/langtools/tools/javac/switchextra/SwitchStatementBroken2.java b/test/langtools/tools/javac/switchextra/SwitchStatementBroken2.java index 5cc466c2710..8bb6bc018ef 100644 --- a/test/langtools/tools/javac/switchextra/SwitchStatementBroken2.java +++ b/test/langtools/tools/javac/switchextra/SwitchStatementBroken2.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify that not allowed types of statements cannot be used in rule case. - * @compile/fail/ref=SwitchStatementBroken2.out -XDrawDiagnostics --enable-preview -source 12 SwitchStatementBroken2.java + * @compile/fail/ref=SwitchStatementBroken2.out -XDrawDiagnostics --enable-preview -source 13 SwitchStatementBroken2.java */ public class SwitchStatementBroken2 { diff --git a/test/langtools/tools/javac/switchextra/SwitchStatementScopesIsolated.java b/test/langtools/tools/javac/switchextra/SwitchStatementScopesIsolated.java index b00fdf82df4..896a4d9ca3b 100644 --- a/test/langtools/tools/javac/switchextra/SwitchStatementScopesIsolated.java +++ b/test/langtools/tools/javac/switchextra/SwitchStatementScopesIsolated.java @@ -2,7 +2,7 @@ * @test /nodynamiccopyright/ * @bug 8206986 * @summary Verify that scopes in rule cases are isolated. - * @compile/fail/ref=SwitchStatementScopesIsolated.out -XDrawDiagnostics --enable-preview -source 12 SwitchStatementScopesIsolated.java + * @compile/fail/ref=SwitchStatementScopesIsolated.out -XDrawDiagnostics --enable-preview -source 13 SwitchStatementScopesIsolated.java */ public class SwitchStatementScopesIsolated { diff --git a/test/langtools/tools/javac/versions/Versions.java b/test/langtools/tools/javac/versions/Versions.java index 60e8e540525..c95e5c6d256 100644 --- a/test/langtools/tools/javac/versions/Versions.java +++ b/test/langtools/tools/javac/versions/Versions.java @@ -69,9 +69,9 @@ public class Versions { Set.of("1.2", "1.3", "1.4", "1.5", "1.6"); public static final Set VALID_SOURCES = - Set.of("1.7", "1.8", "1.9", "1.10", "11", "12"); + Set.of("1.7", "1.8", "1.9", "1.10", "11", "12", "13"); - public static final String LATEST_MAJOR_VERSION = "56.0"; + public static final String LATEST_MAJOR_VERSION = "57.0"; static enum SourceTarget { SEVEN(true, "51.0", "7", Versions::checksrc17), @@ -79,7 +79,8 @@ public class Versions { NINE(true, "53.0", "9", Versions::checksrc19), TEN(true, "54.0", "10", Versions::checksrc110), ELEVEN(false, "55.0", "11", Versions::checksrc111), - TWELVE(false, "56.0", "12", Versions::checksrc112); + TWELVE(false, "56.0", "12", Versions::checksrc112), + THIRTEEN(false, "57.0", "13", Versions::checksrc113); private final boolean dotOne; private final String classFileVer; @@ -293,6 +294,11 @@ public class Versions { checksrc111(args); } + protected void checksrc113(String... args) { + printargs("checksrc113", args); + checksrc111(args); + } + protected void pass(String... args) { printargs("pass", args); diff --git a/test/nashorn/TEST.ROOT b/test/nashorn/TEST.ROOT index 557a3c72a05..e4489382dcf 100644 --- a/test/nashorn/TEST.ROOT +++ b/test/nashorn/TEST.ROOT @@ -8,7 +8,7 @@ keys=intermittent randomness groups=TEST.groups # Minimum jtreg version -requiredVersion=4.2 b12 +requiredVersion=4.2 b13 # Use new module options useNewOptions=true From 4452b80affc95523c988d5b96ec81a38606627bb Mon Sep 17 00:00:00 2001 From: Adam Farley Date: Thu, 13 Dec 2018 11:05:22 -0800 Subject: [PATCH 055/174] 8215217: OpenJDK source has too many swear words Reviewed-by: smarks, shade, rriggs, lancea, prr, joehw --- .../share/classes/com/sun/media/sound/SoftChannel.java | 2 +- .../com/sun/org/apache/xalan/internal/xsltc/dom/BitArray.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftChannel.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftChannel.java index 4f7fad6bacc..4cf3c30f71d 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftChannel.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftChannel.java @@ -1472,7 +1472,7 @@ public final class SoftChannel implements MidiChannel, ModelDirectedPlayer { } for (int controller : co_midi_nrpn_nrpn.keySet()) nrpnChange(controller, 0); - rpnChange(0, 2 << 7); // Bitch Bend sensitivity + rpnChange(0, 2 << 7); // Pitch Bend sensitivity rpnChange(1, 64 << 7); // Channel fine tunning rpnChange(2, 64 << 7); // Channel Coarse Tuning rpnChange(5, 64); // Modulation Depth, +/- 50 cent diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/BitArray.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/BitArray.java index b218a921402..260169ba109 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/BitArray.java +++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/dom/BitArray.java @@ -133,7 +133,7 @@ public class BitArray implements Externalizable { * This method returns the Nth bit that is set in the bit array. The * current position is cached in the following 4 variables and will * help speed up a sequence of next() call in an index iterator. This - * method is a mess, but it is fast and it works, so don't fuck with it. + * method is a mess, but it is fast and it works, so don't change it. */ private int _pos = Integer.MAX_VALUE; private int _node = 0; From f03df8356b2cbb87ebbece3fca9afa68ca630de1 Mon Sep 17 00:00:00 2001 From: Leonid Mesnik Date: Thu, 13 Dec 2018 14:16:21 -0800 Subject: [PATCH 056/174] 8215369: Jcstress pollute /var/tmp with temporary files Reviewed-by: iignatyev, mseledtsov --- .../applications/jcstress/JcstressRunner.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java b/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java index eaebb4cbdd5..e5d3df3dc0f 100644 --- a/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java +++ b/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java @@ -89,6 +89,11 @@ public class JcstressRunner { private static String[] getCmd(String[] args) { List extraFlags = new ArrayList<>(); + // java.io.tmpdir is set for both harness and forked VM so temporary files + // created like this File.createTempFile("jcstress", "stdout"); + // don't pollute temporary directories + extraFlags.add("-Djava.io.tmpdir=" + System.getProperty("user.dir")); + // add jar with jcstress tests and harness to CP extraFlags.add("-cp"); extraFlags.add(System.getProperty("java.class.path") @@ -97,16 +102,11 @@ public class JcstressRunner { extraFlags.add(MAIN_CLASS); - String[] javaOpts = Utils.getTestJavaOpts(); - // disable flags auto-detection - if (0 == javaOpts.length) { + extraFlags.add("--jvmArgs"); + extraFlags.add("-Djava.io.tmpdir=" + System.getProperty("user.dir")); + for (String jvmArg : Utils.getTestJavaOpts()) { extraFlags.add("--jvmArgs"); - extraFlags.add(""); - } else { - for (String jvmArg : Utils.getTestJavaOpts()) { - extraFlags.add("--jvmArgs"); - extraFlags.add(jvmArg); - } + extraFlags.add(jvmArg); } String[] result = new String[extraFlags.size() + args.length]; From 165c644cf8219c5d27d7ae2befe42c4ab85c22f8 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Thu, 13 Dec 2018 23:25:00 +0100 Subject: [PATCH 057/174] 8215362: JFR GTest JfrTestNetworkUtilization fails Reviewed-by: mgronlun --- .../gtest/jfr/test_networkUtilization.cpp | 18 ++--- .../runtime/TestNetworkUtilizationEvent.java | 78 +++++++++---------- 2 files changed, 47 insertions(+), 49 deletions(-) diff --git a/test/hotspot/gtest/jfr/test_networkUtilization.cpp b/test/hotspot/gtest/jfr/test_networkUtilization.cpp index b654365d2f9..19d6a6e2c27 100644 --- a/test/hotspot/gtest/jfr/test_networkUtilization.cpp +++ b/test/hotspot/gtest/jfr/test_networkUtilization.cpp @@ -258,7 +258,7 @@ TEST_VM_F(JfrTestNetworkUtilization, RequestFunctionBasic) { JfrNetworkUtilization::send_events(); ASSERT_EQ(1u, MockEventNetworkUtilization::committed.size()); MockEventNetworkUtilization& e = MockEventNetworkUtilization::committed[0]; - EXPECT_EQ(5, e.readRate); + EXPECT_EQ(40, e.readRate); EXPECT_EQ(0, e.writeRate); EXPECT_STREQ("eth0", e.iface.c_str()); } @@ -282,16 +282,16 @@ TEST_VM_F(JfrTestNetworkUtilization, RequestFunctionMultiple) { const MockEventNetworkUtilization& eth1_event = MockEventNetworkUtilization::get_committed("eth1"); const MockEventNetworkUtilization& ppp0_event = MockEventNetworkUtilization::get_committed("ppp0"); - EXPECT_EQ(5, eth0_event.readRate); + EXPECT_EQ(40, eth0_event.readRate); EXPECT_EQ(0, eth0_event.writeRate); EXPECT_STREQ("eth0", eth0_event.iface.c_str()); - EXPECT_EQ(50, eth1_event.readRate); + EXPECT_EQ(400, eth1_event.readRate); EXPECT_EQ(0, eth1_event.writeRate); EXPECT_STREQ("eth1", eth1_event.iface.c_str()); EXPECT_EQ(0, ppp0_event.readRate); - EXPECT_EQ(25, ppp0_event.writeRate); + EXPECT_EQ(200, ppp0_event.writeRate); EXPECT_STREQ("ppp0", ppp0_event.iface.c_str()); } @@ -310,11 +310,11 @@ TEST_VM_F(JfrTestNetworkUtilization, InterfaceRemoved) { const MockEventNetworkUtilization& eth0_event = MockEventNetworkUtilization::get_committed("eth0"); const MockEventNetworkUtilization& eth1_event = MockEventNetworkUtilization::get_committed("eth1"); - EXPECT_EQ(5, eth0_event.readRate); + EXPECT_EQ(40, eth0_event.readRate); EXPECT_EQ(0, eth0_event.writeRate); EXPECT_STREQ("eth0", eth0_event.iface.c_str()); - EXPECT_EQ(10, eth1_event.readRate); + EXPECT_EQ(80, eth1_event.readRate); EXPECT_EQ(0, eth1_event.writeRate); EXPECT_STREQ("eth1", eth1_event.iface.c_str()); @@ -327,7 +327,7 @@ TEST_VM_F(JfrTestNetworkUtilization, InterfaceRemoved) { ASSERT_EQ(1u, MockEventNetworkUtilization::committed.size()); const MockEventNetworkUtilization& eth1_event_v2 = MockEventNetworkUtilization::get_committed("eth1"); - EXPECT_EQ(5, eth1_event_v2.readRate); + EXPECT_EQ(40, eth1_event_v2.readRate); EXPECT_EQ(0, eth1_event_v2.writeRate); EXPECT_STREQ("eth1", eth1_event_v2.iface.c_str()); } @@ -343,7 +343,7 @@ TEST_VM_F(JfrTestNetworkUtilization, InterfaceReset) { JfrNetworkUtilization::send_events(); ASSERT_EQ(1u, MockEventNetworkUtilization::committed.size()); const MockEventNetworkUtilization& event = MockEventNetworkUtilization::committed[0]; - EXPECT_EQ(5, event.readRate); + EXPECT_EQ(40, event.readRate); EXPECT_EQ(0, event.writeRate); EXPECT_STREQ("eth0", event.iface.c_str()); @@ -360,7 +360,7 @@ TEST_VM_F(JfrTestNetworkUtilization, InterfaceReset) { JfrNetworkUtilization::send_events(); ASSERT_EQ(1u, MockEventNetworkUtilization::committed.size()); const MockEventNetworkUtilization& event_v2 = MockEventNetworkUtilization::committed[0]; - EXPECT_EQ(5, event_v2.readRate); + EXPECT_EQ(40, event_v2.readRate); EXPECT_EQ(0, event_v2.writeRate); EXPECT_STREQ("eth0", event_v2.iface.c_str()); } diff --git a/test/jdk/jdk/jfr/event/runtime/TestNetworkUtilizationEvent.java b/test/jdk/jdk/jfr/event/runtime/TestNetworkUtilizationEvent.java index 857ce41acb4..73dba80b91d 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestNetworkUtilizationEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestNetworkUtilizationEvent.java @@ -25,6 +25,13 @@ package jdk.jfr.event.runtime; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import jdk.jfr.Recording; import jdk.jfr.consumer.RecordedEvent; import jdk.test.lib.Asserts; @@ -32,17 +39,6 @@ import jdk.test.lib.Platform; import jdk.test.lib.jfr.EventNames; import jdk.test.lib.jfr.Events; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; - -import static java.util.stream.Collectors.averagingLong; -import static java.util.stream.Collectors.groupingBy; - /** * @test * @key jfr @@ -56,21 +52,17 @@ public class TestNetworkUtilizationEvent { private static final long packetSendCount = 100; public static void main(String[] args) throws Throwable { - testSimple(); - } - static void testSimple() throws Throwable { - - Instant start = Instant.now(); Recording recording = new Recording(); - recording.enable(EventNames.NetworkUtilization); + recording.enable(EventNames.NetworkUtilization).with("period", "endChunk"); recording.start(); DatagramSocket socket = new DatagramSocket(); String msg = "hello!"; byte[] buf = msg.getBytes(); - - // Send a few packets both to the loopback address as well to an external + forceEndChunk(); + // Send a few packets both to the loopback address as well to an + // external DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLoopbackAddress(), 12345); for (int i = 0; i < packetSendCount; ++i) { socket.send(packet); @@ -79,32 +71,38 @@ public class TestNetworkUtilizationEvent { for (int i = 0; i < packetSendCount; ++i) { socket.send(packet); } - - // Now there should have been traffic on at least two different interfaces + forceEndChunk(); + socket.close(); + // Now there should have been traffic on at least two different + // interfaces recording.stop(); - Duration runtime = Duration.between(start, Instant.now()); + + Set networkInterfaces = new HashSet<>(); List events = Events.fromRecording(recording); - - // Calculate the average write rate for each interface - Map writeRates = events.stream() - .collect(groupingBy(e -> Events.assertField(e, "networkInterface").getValue(), - averagingLong(e -> Events.assertField(e, "writeRate").getValue()))); - - // Our test packets should have generated at least this much traffic per second - long expectedTraffic = (buf.length * packetSendCount) / Math.max(1, runtime.toSeconds()); - - // Count the number of interfaces that have seen at least our test traffic - long interfacesWithTraffic = writeRates.values().stream() - .filter(d -> d >= expectedTraffic) - .count(); + Events.hasEvents(events); + for (RecordedEvent event : events) { + System.out.println(event); + Events.assertField(event, "writeRate").atLeast(0L).atMost(1000L * Integer.MAX_VALUE); + Events.assertField(event, "readRate").atLeast(0L).atMost(1000L * Integer.MAX_VALUE); + Events.assertField(event, "networkInterface").notNull(); + if (event.getLong("writeRate") > 0) { + networkInterfaces.add(event.getString("networkInterface")); + } + } if (Platform.isWindows() || Platform.isSolaris()) { - // Windows and Solaris do not track statistics for the loopback interface - Asserts.assertGreaterThanOrEqual(writeRates.size(), 1); - Asserts.assertGreaterThanOrEqual(interfacesWithTraffic, Long.valueOf(1)); + // Windows and Solaris do not track statistics for the loopback + // interface + Asserts.assertGreaterThanOrEqual(networkInterfaces.size(), 1); } else { - Asserts.assertGreaterThanOrEqual(writeRates.size(), 2); - Asserts.assertGreaterThanOrEqual(interfacesWithTraffic, Long.valueOf(2)); + Asserts.assertGreaterThanOrEqual(networkInterfaces.size(), 2); } } + + private static void forceEndChunk() { + try(Recording r = new Recording()) { + r.start(); + r.stop(); + } + } } From b83df1e1fcd6bc13b078c53825792dbc63ade210 Mon Sep 17 00:00:00 2001 From: Martin Doerr Date: Fri, 14 Dec 2018 09:59:08 +0100 Subject: [PATCH 058/174] 8214352: C1: Unnecessary "compilation bailout: block join failed" with JVMTI Invalidate Phi functions for conflicting types and avoid bailout. Reviewed-by: kvn, iveresov --- src/hotspot/share/c1/c1_Instruction.cpp | 13 ++++++++++--- src/hotspot/share/c1/c1_LIRGenerator.cpp | 2 +- src/hotspot/share/c1/c1_LinearScan.cpp | 6 +++--- src/hotspot/share/c1/c1_ValueStack.hpp | 6 +++--- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/hotspot/share/c1/c1_Instruction.cpp b/src/hotspot/share/c1/c1_Instruction.cpp index 74b14b70264..ee3be899a55 100644 --- a/src/hotspot/share/c1/c1_Instruction.cpp +++ b/src/hotspot/share/c1/c1_Instruction.cpp @@ -827,9 +827,16 @@ bool BlockBegin::try_merge(ValueStack* new_state) { for_each_local_value(existing_state, index, existing_value) { Value new_value = new_state->local_at(index); if (new_value == NULL || new_value->type()->tag() != existing_value->type()->tag()) { - // The old code invalidated the phi function here - // Because dead locals are replaced with NULL, this is a very rare case now, so simply bail out - return false; // BAILOUT in caller + Phi* existing_phi = existing_value->as_Phi(); + if (existing_phi == NULL) { + return false; // BAILOUT in caller + } + // Invalidate the phi function here. This case is very rare except for + // JVMTI capability "can_access_local_variables". + // In really rare cases we will bail out in LIRGenerator::move_to_phi. + existing_phi->make_illegal(); + existing_state->invalidate_local(index); + TRACE_PHI(tty->print_cr("invalidating local %d because of type mismatch", index)); } } diff --git a/src/hotspot/share/c1/c1_LIRGenerator.cpp b/src/hotspot/share/c1/c1_LIRGenerator.cpp index ccd56c35faf..d29be5e22cf 100644 --- a/src/hotspot/share/c1/c1_LIRGenerator.cpp +++ b/src/hotspot/share/c1/c1_LIRGenerator.cpp @@ -1113,7 +1113,7 @@ void LIRGenerator::do_ExceptionObject(ExceptionObject* x) { // no moves are created for phi functions at the begin of exception // handlers, so assign operands manually here for_each_phi_fun(block(), phi, - operand_for_instruction(phi)); + if (!phi->is_illegal()) { operand_for_instruction(phi); }); LIR_Opr thread_reg = getThreadPointer(); __ move_wide(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT), diff --git a/src/hotspot/share/c1/c1_LinearScan.cpp b/src/hotspot/share/c1/c1_LinearScan.cpp index 05e7647c69a..8bd1e0fc3b9 100644 --- a/src/hotspot/share/c1/c1_LinearScan.cpp +++ b/src/hotspot/share/c1/c1_LinearScan.cpp @@ -574,7 +574,7 @@ void LinearScan::compute_local_live_sets() { // Phi functions at the begin of an exception handler are // implicitly defined (= killed) at the beginning of the block. for_each_phi_fun(block, phi, - live_kill.set_bit(phi->operand()->vreg_number()) + if (!phi->is_illegal()) { live_kill.set_bit(phi->operand()->vreg_number()); } ); } @@ -1904,7 +1904,7 @@ void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_r // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately for_each_phi_fun(block, phi, - resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver) + if (!phi->is_illegal()) { resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver); } ); if (move_resolver.has_mappings()) { @@ -1978,7 +1978,7 @@ void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, M // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately for_each_phi_fun(block, phi, - resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver) + if (!phi->is_illegal()) { resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver); } ); if (move_resolver.has_mappings()) { diff --git a/src/hotspot/share/c1/c1_ValueStack.hpp b/src/hotspot/share/c1/c1_ValueStack.hpp index e7de5f5389d..c58a9f59b7a 100644 --- a/src/hotspot/share/c1/c1_ValueStack.hpp +++ b/src/hotspot/share/c1/c1_ValueStack.hpp @@ -299,7 +299,7 @@ class ValueStack: public CompilationResourceObj { } -// Macro definition for simple iteration of all phif functions of a block, i.e all +// Macro definition for simple iteration of all phi functions of a block, i.e all // phi functions of the ValueStack where the block matches. // Use the following code pattern to iterate all phi functions of a block: // @@ -315,7 +315,7 @@ class ValueStack: public CompilationResourceObj { Value value; \ { \ for_each_stack_value(cur_state, cur_index, value) { \ - Phi* v_phi = value->as_Phi(); \ + Phi* v_phi = value->as_Phi(); \ if (v_phi != NULL && v_phi->block() == v_block) { \ v_code; \ } \ @@ -323,7 +323,7 @@ class ValueStack: public CompilationResourceObj { } \ { \ for_each_local_value(cur_state, cur_index, value) { \ - Phi* v_phi = value->as_Phi(); \ + Phi* v_phi = value->as_Phi(); \ if (v_phi != NULL && v_phi->block() == v_block) { \ v_code; \ } \ From 1d7662e42873d375f7ff182c2d2daf8671d617e4 Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Fri, 14 Dec 2018 13:30:21 +0000 Subject: [PATCH 059/174] 8214077: test java/io/File/SetLastModified.java fails on ARM32 Replace uses of stat with stat64 in java.base Reviewed-by: alanb --- .../native/libjava/ProcessHandleImpl_linux.c | 4 ++-- .../unix/native/libjava/TimeZone_md.c | 20 ++++++++++++------- .../unix/native/libjava/UnixFileSystem_md.c | 17 ++++++++-------- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c b/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c index 7792569aba2..991849697dd 100644 --- a/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c +++ b/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c @@ -138,13 +138,13 @@ void os_getCmdlineAndUserInfo(JNIEnv *env, jobject jinfo, pid_t pid) { char *args = NULL; jstring cmdexe = NULL; char fn[32]; - struct stat stat_buf; + struct stat64 stat_buf; /* * Stat /proc/ to get the user id */ snprintf(fn, sizeof fn, "/proc/%d", pid); - if (stat(fn, &stat_buf) == 0) { + if (stat64(fn, &stat_buf) == 0) { unix_getUserInfo(env, jinfo, stat_buf.st_uid); JNU_CHECK_EXCEPTION(env); } diff --git a/src/java.base/unix/native/libjava/TimeZone_md.c b/src/java.base/unix/native/libjava/TimeZone_md.c index 9d7f07b38f8..edef4f9db70 100644 --- a/src/java.base/unix/native/libjava/TimeZone_md.c +++ b/src/java.base/unix/native/libjava/TimeZone_md.c @@ -56,6 +56,12 @@ #define fileclose fclose #endif +#if defined(_ALLBSD_SOURCE) +#define stat64 stat +#define lstat64 lstat +#define fstat64 fstat +#endif + #if defined(__linux__) || defined(_ALLBSD_SOURCE) static const char *ETC_TIMEZONE_FILE = "/etc/timezone"; static const char *ZONEINFO_DIR = "/usr/share/zoneinfo"; @@ -115,7 +121,7 @@ static char * findZoneinfoFile(char *buf, size_t size, const char *dir) { DIR *dirp = NULL; - struct stat statbuf; + struct stat64 statbuf; struct dirent *dp = NULL; char *pathname = NULL; int fd = -1; @@ -156,7 +162,7 @@ findZoneinfoFile(char *buf, size_t size, const char *dir) if (pathname == NULL) { break; } - RESTARTABLE(stat(pathname, &statbuf), res); + RESTARTABLE(stat64(pathname, &statbuf), res); if (res == -1) { break; } @@ -219,7 +225,7 @@ findZoneinfoFile(char *buf, size_t size, const char *dir) static char * getPlatformTimeZoneID() { - struct stat statbuf; + struct stat64 statbuf; char *tz = NULL; FILE *fp; int fd; @@ -256,7 +262,7 @@ getPlatformTimeZoneID() /* * Next, try /etc/localtime to find the zone ID. */ - RESTARTABLE(lstat(DEFAULT_ZONEINFO_FILE, &statbuf), res); + RESTARTABLE(lstat64(DEFAULT_ZONEINFO_FILE, &statbuf), res); if (res == -1) { return NULL; } @@ -296,7 +302,7 @@ getPlatformTimeZoneID() return NULL; } - RESTARTABLE(fstat(fd, &statbuf), res); + RESTARTABLE(fstat64(fd, &statbuf), res); if (res == -1) { (void) close(fd); return NULL; @@ -557,7 +563,7 @@ cleanupScf(scf_handle_t *h, static char * getSolarisDefaultZoneID() { char *tz = NULL; - struct stat statbuf; + struct stat64 statbuf; size_t size; char *buf; int fd; @@ -597,7 +603,7 @@ getSolarisDefaultZoneID() { } cleanupScf(h, snap, inst, pg, prop, val, tz); - RESTARTABLE(stat(DEFAULT_ZONEINFO_FILE, &statbuf), res); + RESTARTABLE(stat64(DEFAULT_ZONEINFO_FILE, &statbuf), res); if (res == -1) { return NULL; } diff --git a/src/java.base/unix/native/libjava/UnixFileSystem_md.c b/src/java.base/unix/native/libjava/UnixFileSystem_md.c index aa3fb92f8e7..55387a40b32 100644 --- a/src/java.base/unix/native/libjava/UnixFileSystem_md.c +++ b/src/java.base/unix/native/libjava/UnixFileSystem_md.c @@ -69,6 +69,7 @@ #if defined(_ALLBSD_SOURCE) #ifndef MACOSX #define statvfs64 statvfs + #define stat64 stat #endif #endif @@ -121,8 +122,8 @@ Java_java_io_UnixFileSystem_canonicalize0(JNIEnv *env, jobject this, static jboolean statMode(const char *path, int *mode) { - struct stat sb; - if (stat(path, &sb) == 0) { + struct stat64 sb; + if (stat64(path, &sb) == 0) { *mode = sb.st_mode; return JNI_TRUE; } @@ -229,8 +230,8 @@ Java_java_io_UnixFileSystem_getLastModifiedTime(JNIEnv *env, jobject this, jlong rv = 0; WITH_FIELD_PLATFORM_STRING(env, file, ids.path, path) { - struct stat sb; - if (stat(path, &sb) == 0) { + struct stat64 sb; + if (stat64(path, &sb) == 0) { #if defined(_AIX) rv = (jlong)sb.st_mtime * 1000; rv += (jlong)sb.st_mtime_n / 1000000; @@ -254,8 +255,8 @@ Java_java_io_UnixFileSystem_getLength(JNIEnv *env, jobject this, jlong rv = 0; WITH_FIELD_PLATFORM_STRING(env, file, ids.path, path) { - struct stat sb; - if (stat(path, &sb) == 0) { + struct stat64 sb; + if (stat64(path, &sb) == 0) { rv = sb.st_size; } } END_PLATFORM_STRING(env, path); @@ -408,9 +409,9 @@ Java_java_io_UnixFileSystem_setLastModifiedTime(JNIEnv *env, jobject this, jboolean rv = JNI_FALSE; WITH_FIELD_PLATFORM_STRING(env, file, ids.path, path) { - struct stat sb; + struct stat64 sb; - if (stat(path, &sb) == 0) { + if (stat64(path, &sb) == 0) { struct timeval tv[2]; /* Preserve access time */ From a9d7e075e54f5480a499cad5936b05c680303fe6 Mon Sep 17 00:00:00 2001 From: Jean Christophe Beyler Date: Fri, 14 Dec 2018 10:51:09 -0800 Subject: [PATCH 060/174] 8215329: Modify ZGC requirement for HeapMonitorThreadTest.java Modify the requirement to be tested Reviewed-by: amenkov, pliden, sspitsyn --- .../jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java index 31e38e1e646..52d3b22b7ff 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java @@ -30,7 +30,7 @@ package MyPackage; * @summary Verifies the JVMTI Heap Monitor Thread information sanity. * @compile HeapMonitorThreadTest.java * @run main/othervm/native -Xmx512m -agentlib:HeapMonitorTest MyPackage.HeapMonitorThreadTest - * @requires !vm.gc.Z + * @requires vm.gc != "Z" */ import java.util.List; From d1951aa97cecbf6852e49bf1610f54feca9a2ec5 Mon Sep 17 00:00:00 2001 From: Lance Andersen Date: Fri, 14 Dec 2018 14:17:22 -0500 Subject: [PATCH 061/174] 8215372: Incorrect nio/file/DirectoryStream/Basic.java tests for validating the use of a glob Reviewed-by: alanb --- test/jdk/java/nio/file/DirectoryStream/Basic.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/test/jdk/java/nio/file/DirectoryStream/Basic.java b/test/jdk/java/nio/file/DirectoryStream/Basic.java index ecc66e4ca5f..77a550f2b22 100644 --- a/test/jdk/java/nio/file/DirectoryStream/Basic.java +++ b/test/jdk/java/nio/file/DirectoryStream/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,14 +73,18 @@ public class Basic { private PathMatcher matcher = dir.getFileSystem().getPathMatcher("glob:f*"); public boolean accept(Path file) { - return matcher.matches(file); + return matcher.matches(file.getFileName()); } }; + + found = false; try (DirectoryStream ds = newDirectoryStream(dir, filter)) { for (Path entry: ds) { - if (!entry.getFileName().equals(foo)) - throw new RuntimeException("entry not expected"); + if (entry.getFileName().equals(foo)) + found = true; } + if (!found) + throw new RuntimeException(String.format("Error: entry: %s was not found", foo)); } // check filtering: z* should not match any files @@ -88,7 +92,7 @@ public class Basic { private PathMatcher matcher = dir.getFileSystem().getPathMatcher("glob:z*"); public boolean accept(Path file) { - return matcher.matches(file); + return matcher.matches(file.getFileName()); } }; try (DirectoryStream ds = newDirectoryStream(dir, filter)) { From f3657753d634a4c1feeef45ab95046b9e0ed8089 Mon Sep 17 00:00:00 2001 From: Jean Christophe Beyler Date: Fri, 14 Dec 2018 13:13:06 -0800 Subject: [PATCH 062/174] 8201655: Add thread-enabled support for the Heap Sampling Added thread-enabled support Reviewed-by: amenkov, sspitsyn --- src/hotspot/share/prims/jvmti.xml | 2 +- .../share/prims/jvmtiEventController.cpp | 3 +- src/hotspot/share/prims/jvmtiExport.cpp | 13 +- ...ava => HeapMonitorThreadDisabledTest.java} | 36 ++-- .../jvmti/HeapMonitor/libHeapMonitorTest.c | 169 +++++++----------- 5 files changed, 100 insertions(+), 123 deletions(-) rename test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/{HeapMonitorEventsForTwoThreadsTest.java => HeapMonitorThreadDisabledTest.java} (53%) diff --git a/src/hotspot/share/prims/jvmti.xml b/src/hotspot/share/prims/jvmti.xml index 71d3c06cd79..51fb8567134 100644 --- a/src/hotspot/share/prims/jvmti.xml +++ b/src/hotspot/share/prims/jvmti.xml @@ -13595,7 +13595,7 @@ myInit() { + id="SampledObjectAlloc" const="JVMTI_EVENT_SAMPLED_OBJECT_ALLOC" filtered="thread" num="86" since="11"> Sent when an allocated object is sampled. By default, the sampling interval is set to 512KB. The sampling is semi-random to avoid diff --git a/src/hotspot/share/prims/jvmtiEventController.cpp b/src/hotspot/share/prims/jvmtiEventController.cpp index 23bac8d29b1..700572e35ae 100644 --- a/src/hotspot/share/prims/jvmtiEventController.cpp +++ b/src/hotspot/share/prims/jvmtiEventController.cpp @@ -96,7 +96,8 @@ static const jlong EXCEPTION_BITS = EXCEPTION_THROW_BIT | EXCEPTION_CATCH_BIT; static const jlong INTERP_EVENT_BITS = SINGLE_STEP_BIT | METHOD_ENTRY_BIT | METHOD_EXIT_BIT | FRAME_POP_BIT | FIELD_ACCESS_BIT | FIELD_MODIFICATION_BIT; static const jlong THREAD_FILTERED_EVENT_BITS = INTERP_EVENT_BITS | EXCEPTION_BITS | MONITOR_BITS | - BREAKPOINT_BIT | CLASS_LOAD_BIT | CLASS_PREPARE_BIT | THREAD_END_BIT; + BREAKPOINT_BIT | CLASS_LOAD_BIT | CLASS_PREPARE_BIT | THREAD_END_BIT | + SAMPLED_OBJECT_ALLOC_BIT; static const jlong NEED_THREAD_LIFE_EVENTS = THREAD_FILTERED_EVENT_BITS | THREAD_START_BIT; static const jlong EARLY_EVENT_BITS = CLASS_FILE_LOAD_HOOK_BIT | CLASS_LOAD_BIT | CLASS_PREPARE_BIT | VM_START_BIT | VM_INIT_BIT | VM_DEATH_BIT | NATIVE_METHOD_BIND_BIT | diff --git a/src/hotspot/share/prims/jvmtiExport.cpp b/src/hotspot/share/prims/jvmtiExport.cpp index 12347decc8a..64e4f5226a8 100644 --- a/src/hotspot/share/prims/jvmtiExport.cpp +++ b/src/hotspot/share/prims/jvmtiExport.cpp @@ -2567,6 +2567,11 @@ void JvmtiExport::post_vm_object_alloc(JavaThread *thread, oop object) { } void JvmtiExport::post_sampled_object_alloc(JavaThread *thread, oop object) { + JvmtiThreadState *state = thread->jvmti_thread_state(); + if (state == NULL) { + return; + } + EVT_TRIG_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, ("[%s] Trg sampled object alloc triggered", JvmtiTrace::safe_get_thread_name(thread))); @@ -2575,14 +2580,16 @@ void JvmtiExport::post_sampled_object_alloc(JavaThread *thread, oop object) { } HandleMark hm(thread); Handle h(thread, object); - JvmtiEnvIterator it; - for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) { - if (env->is_enabled(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC)) { + + JvmtiEnvThreadStateIterator it(state); + for (JvmtiEnvThreadState* ets = it.first(); ets != NULL; ets = it.next(ets)) { + if (ets->is_enabled(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC)) { EVT_TRACE(JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, ("[%s] Evt sampled object alloc sent %s", JvmtiTrace::safe_get_thread_name(thread), object == NULL ? "NULL" : object->klass()->external_name())); + JvmtiEnv *env = ets->get_env(); JvmtiObjectAllocEventMark jem(thread, h()); JvmtiJavaThreadEventTransition jet(thread); jvmtiEventSampledObjectAlloc callback = env->callbacks()->SampledObjectAlloc; diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorEventsForTwoThreadsTest.java b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadDisabledTest.java similarity index 53% rename from test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorEventsForTwoThreadsTest.java rename to test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadDisabledTest.java index c6c4d34c9bc..84025b2a700 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorEventsForTwoThreadsTest.java +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadDisabledTest.java @@ -27,24 +27,40 @@ package MyPackage; /** * @test * @build Frame HeapMonitor ThreadInformation - * @summary Ensures the JVMTI Heap Monitor is not thread enable (test to change when it becomes so) - * @compile HeapMonitorEventsForTwoThreadsTest.java - * @run main/othervm/native -agentlib:HeapMonitorTest MyPackage.HeapMonitorEventsForTwoThreadsTest + * @summary Verifies the JVMTI Heap Monitor Thread can disable events for a given thread. + * @compile HeapMonitorThreadDisabledTest.java + * @run main/othervm/native -Xmx512m -agentlib:HeapMonitorTest MyPackage.HeapMonitorThreadDisabledTest */ import java.util.List; -public class HeapMonitorEventsForTwoThreadsTest { - public native static boolean checkSamples(); +public class HeapMonitorThreadDisabledTest { + private native static void enableSamplingEvents(Thread thread); + private native static boolean checkThreadSamplesOnlyFrom(Thread thread); public static void main(String[] args) { - final int numThreads = 24; + final int numThreads = 4; List threadList = ThreadInformation.createThreadList(numThreads); - Thread firstThread = threadList.get(0).getThread(); - Thread secondThread = threadList.get(1).getThread(); - if (HeapMonitor.enableSamplingEventsForTwoThreads(firstThread, secondThread)) { - throw new RuntimeException("Sampling event is thread enabled, that is unexpected."); + // Sample at a interval of 8k. + HeapMonitor.setSamplingInterval(1 << 13); + + // Only enable the sampling for a given thread. + Thread thread = threadList.get(0).getThread(); + enableSamplingEvents(thread); + + System.err.println("Starting threads"); + ThreadInformation.startThreads(threadList); + ThreadInformation.waitForThreads(threadList); + System.err.println("Waited for threads"); + + // Only have the samples for a given thread should be captured. + if (!checkThreadSamplesOnlyFrom(thread)) { + throw new RuntimeException( + "Problem with checkSamples: got no events from the expected thread"); } + + // Now inform each thread we are done and wait for them to be done. + ThreadInformation.stopThreads(threadList); } } diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c index 2df6a77150b..e41e322233d 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c @@ -720,101 +720,86 @@ jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { #define MAX_THREADS 500 typedef struct ThreadStats { - int number_threads; + int thread_count; int counts[MAX_THREADS]; - int not_helper_counts[MAX_THREADS]; - int index[MAX_THREADS]; - jthread threads[MAX_THREADS]; - - int method_resolution_problem; + char* threads[MAX_THREADS]; } ThreadStats; static ThreadStats thread_stats; -static void add_thread_count(jthread thread, int lock, int helper) { - int i; +JNIEXPORT jboolean JNICALL +Java_MyPackage_HeapMonitorThreadDisabledTest_checkThreadSamplesOnlyFrom( + JNIEnv* env, jclass cls, jthread thread) { jvmtiThreadInfo info; - const char* name; - char* end; - int idx; - int err; + jvmtiError err; + char* expected_name; + int found_thread = FALSE; - if (lock) { - event_storage_lock(&global_event_storage); + err = (*jvmti)->GetThreadInfo(jvmti, thread, &info); + expected_name = info.name; + + if (err != JVMTI_ERROR_NONE) { + fprintf(stderr, "Failed to get thread information\n"); + return FALSE; } - for (i = 0; i < thread_stats.number_threads; i++) { - if (thread_stats.threads[i] == thread) { - if (helper) { - thread_stats.counts[i]++; - } else { - thread_stats.not_helper_counts[i]++; - } + if (thread_stats.thread_count != 1) { + fprintf(stderr, "Wrong thread number: %d (expected 1)\n", + thread_stats.thread_count); + return FALSE; + } - if (lock) { - event_storage_unlock(&global_event_storage); - } + if (strcmp(expected_name, thread_stats.threads[0]) != 0) { + fprintf(stderr, "Unexpected thread name: '%s' (expected '%s')\n", + thread_stats.threads[0], expected_name); + return FALSE; + } + + return TRUE; +} + +static void add_thread_count(jthread thread) { + int i; + jvmtiThreadInfo info; + jvmtiError err; + + err = (*jvmti)->GetThreadInfo(jvmti, thread, &info); + if (err != JVMTI_ERROR_NONE) { + fprintf(stderr, "Thread info for %p failed, ignoring thread count\n", + thread); + return; + } + + event_storage_lock(&global_event_storage); + for (i = 0; i < thread_stats.thread_count; i++) { + if (!strcmp(thread_stats.threads[i], info.name)) { + thread_stats.counts[i]++; + event_storage_unlock(&global_event_storage); return; } } - thread_stats.threads[thread_stats.number_threads] = thread; + thread_stats.threads[thread_stats.thread_count] = info.name; + thread_stats.counts[thread_stats.thread_count]++; + thread_stats.thread_count++; + event_storage_unlock(&global_event_storage); +} - err = (*jvmti)->GetThreadInfo(jvmti, thread, &info); - if (err != JVMTI_ERROR_NONE) { - if (lock) { - event_storage_unlock(&global_event_storage); - } - - // Just to have it accounted as an error... - info.name = "Allocator99"; - } - - if (!strstr(info.name, "Allocator")) { - if (lock) { - event_storage_unlock(&global_event_storage); - } - - // Just to have it accounted as an error... - info.name = "Allocator98"; - } - - name = info.name + 9; - end = NULL; - idx = strtol(name, &end, 0); - - if (*end == '\0') { - if (helper) { - thread_stats.counts[thread_stats.number_threads]++; - } else { - thread_stats.not_helper_counts[thread_stats.number_threads]++; - } - - thread_stats.index[thread_stats.number_threads] = idx; - thread_stats.number_threads++; - } else { - fprintf(stderr, "Problem with thread name...: %p %s\n", thread, name); - } - - if (PRINT_OUT) { - fprintf(stderr, "Added %s - %p - %d - lock: %d\n", info.name, thread, idx, lock); - } - - if (lock) { - event_storage_unlock(&global_event_storage); - } +JNIEXPORT void JNICALL +Java_MyPackage_HeapMonitorThreadDisabledTest_enableSamplingEvents( + JNIEnv* env, jclass cls, jthread thread) { + fprintf(stderr, "Enabling for %p\n", thread); + check_error((*jvmti)->SetEventNotificationMode( + jvmti, JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, thread), + "Set event notifications for a single thread"); } static void print_thread_stats() { int i; event_storage_lock(&global_event_storage); - fprintf(stderr, "Method resolution problem: %d\n", thread_stats.method_resolution_problem); fprintf(stderr, "Thread count:\n"); - for (i = 0; i < thread_stats.number_threads; i++) { - fprintf(stderr, "\t%p: %d: %d - %d\n", thread_stats.threads[i], - thread_stats.index[i], - thread_stats.counts[i], - thread_stats.not_helper_counts[i]); + for (i = 0; i < thread_stats.thread_count; i++) { + fprintf(stderr, "\t%s: %d\n", thread_stats.threads[i], thread_stats.counts[i]); } event_storage_unlock(&global_event_storage); } @@ -826,7 +811,7 @@ void JNICALL SampledObjectAlloc(jvmtiEnv *jvmti_env, jobject object, jclass object_klass, jlong size) { - add_thread_count(thread, 1, 1); + add_thread_count(thread); if (event_storage_get_compaction_required(&global_event_storage)) { event_storage_compact(&global_event_storage, jni_env); @@ -864,29 +849,6 @@ static int enable_notifications() { "Set event notifications"); } -static int enable_notifications_for_two_threads(jthread first, jthread second) { - if (check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL), - "Set event notifications")) { - return 0; - } - - if (check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, first), - "Set event notifications")) { - return 0; - } - - // Second thread should fail. - if (check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, second), - "Set event notifications")) { - return 0; - } - - return 1; -} - static jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { jint res; @@ -970,14 +932,6 @@ Java_MyPackage_HeapMonitor_enableSamplingEvents(JNIEnv* env, jclass cls) { enable_notifications(); } -JNIEXPORT jboolean JNICALL -Java_MyPackage_HeapMonitor_enableSamplingEventsForTwoThreads(JNIEnv* env, - jclass cls, - jthread first, - jthread second) { - return enable_notifications_for_two_threads(first, second); -} - JNIEXPORT void JNICALL Java_MyPackage_HeapMonitor_disableSamplingEvents(JNIEnv* env, jclass cls) { check_error((*jvmti)->SetEventNotificationMode( @@ -1130,10 +1084,9 @@ typedef struct sThreadsFound { JNIEXPORT jboolean JNICALL Java_MyPackage_HeapMonitorThreadTest_checkSamples(JNIEnv* env, jclass cls, jint num_threads) { - print_thread_stats(); // Ensure we got stacks from at least num_threads. - return thread_stats.number_threads >= num_threads; + return thread_stats.thread_count >= num_threads; } JNIEXPORT From 945e9400ce8f83aad47775734d0cf875cac276a7 Mon Sep 17 00:00:00 2001 From: Doug Simon Date: Fri, 14 Dec 2018 16:52:17 -0800 Subject: [PATCH 063/174] 8215319: jck lang/INTF/intf049/intf04901 fails in Graal as JIT mode with -Xcomp and AOTed Graal Reviewed-by: iveresov, never, dlong --- .../org/graalvm/compiler/java/BytecodeParser.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java index 482d12a5183..48adfc457a4 100644 --- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java +++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java @@ -4195,7 +4195,6 @@ public class BytecodeParser implements GraphBuilderContext { handleIllegalNewInstance(resolvedType); return; } - maybeEagerlyInitialize(resolvedType); ClassInitializationPlugin classInitializationPlugin = graphBuilderConfig.getPlugins().getClassInitializationPlugin(); @@ -4509,7 +4508,6 @@ public class BytecodeParser implements GraphBuilderContext { } ResolvedJavaType holder = resolvedField.getDeclaringClass(); - maybeEagerlyInitialize(holder); ClassInitializationPlugin classInitializationPlugin = this.graphBuilderConfig.getPlugins().getClassInitializationPlugin(); if (classInitializationPlugin != null) { classInitializationPlugin.apply(this, holder, this::createCurrentFrameState); @@ -4545,16 +4543,20 @@ public class BytecodeParser implements GraphBuilderContext { private ResolvedJavaField resolveStaticFieldAccess(JavaField field, ValueNode value) { if (field instanceof ResolvedJavaField) { ResolvedJavaField resolvedField = (ResolvedJavaField) field; - if (resolvedField.getDeclaringClass().isInitialized() || graphBuilderConfig.getPlugins().getClassInitializationPlugin() != null) { + ResolvedJavaType resolvedType = resolvedField.getDeclaringClass(); + maybeEagerlyInitialize(resolvedType); + + if (resolvedType.isInitialized() || graphBuilderConfig.getPlugins().getClassInitializationPlugin() != null) { return resolvedField; } + /* * Static fields have initialization semantics but may be safely accessed under certain * conditions while the class is being initialized. Executing in the clinit or init of - * classes which are subtypes of the field holder are sure to be running in a context - * where the access is safe. + * subclasses (but not implementers) of the field holder are sure to be running in a + * context where the access is safe. */ - if (resolvedField.getDeclaringClass().isAssignableFrom(method.getDeclaringClass())) { + if (!resolvedType.isInterface() && resolvedType.isAssignableFrom(method.getDeclaringClass())) { if (method.isClassInitializer() || method.isConstructor()) { return resolvedField; } @@ -4588,7 +4590,6 @@ public class BytecodeParser implements GraphBuilderContext { ClassInitializationPlugin classInitializationPlugin = this.graphBuilderConfig.getPlugins().getClassInitializationPlugin(); ResolvedJavaType holder = resolvedField.getDeclaringClass(); - maybeEagerlyInitialize(holder); if (classInitializationPlugin != null) { Supplier stateBefore = () -> { JavaKind[] pushedSlotKinds = {field.getJavaKind()}; From 811c84ba6868a7e82445a5eb66664249c9d1955e Mon Sep 17 00:00:00 2001 From: Leo Korinth Date: Mon, 17 Dec 2018 11:37:40 +0100 Subject: [PATCH 064/174] 8214946: G1: Initialize all class members on construction Reviewed-by: kbarrett, tschatzl --- src/hotspot/share/gc/g1/dirtyCardQueue.cpp | 4 +++- src/hotspot/share/gc/g1/g1CardCounts.cpp | 2 +- src/hotspot/share/gc/g1/g1CollectedHeap.cpp | 2 +- src/hotspot/share/gc/g1/g1HeapVerifier.cpp | 6 +----- src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp | 5 +++-- src/hotspot/share/gc/g1/heapRegion.cpp | 4 +++- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/hotspot/share/gc/g1/dirtyCardQueue.cpp b/src/hotspot/share/gc/g1/dirtyCardQueue.cpp index 0ca4da4db83..361db1ed444 100644 --- a/src/hotspot/share/gc/g1/dirtyCardQueue.cpp +++ b/src/hotspot/share/gc/g1/dirtyCardQueue.cpp @@ -137,7 +137,9 @@ DirtyCardQueueSet::DirtyCardQueueSet(bool notify_when_complete) : PtrQueueSet(notify_when_complete), _shared_dirty_card_queue(this, true /* permanent */), _free_ids(NULL), - _processed_buffers_mut(0), _processed_buffers_rs_thread(0) + _processed_buffers_mut(0), + _processed_buffers_rs_thread(0), + _cur_par_buffer_node(NULL) { _all_active = true; } diff --git a/src/hotspot/share/gc/g1/g1CardCounts.cpp b/src/hotspot/share/gc/g1/g1CardCounts.cpp index 5e4ef3d5bae..d3621e5d62f 100644 --- a/src/hotspot/share/gc/g1/g1CardCounts.cpp +++ b/src/hotspot/share/gc/g1/g1CardCounts.cpp @@ -58,7 +58,7 @@ void G1CardCounts::clear_range(size_t from_card_num, size_t to_card_num) { } G1CardCounts::G1CardCounts(G1CollectedHeap *g1h): - _listener(), _g1h(g1h), _card_counts(NULL), _reserved_max_card_num(0) { + _listener(), _g1h(g1h), _ct(NULL), _card_counts(NULL), _reserved_max_card_num(0), _ct_bot(NULL) { _listener.set_cardcounts(this); } diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp index 6347287d608..ed4ba755480 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp @@ -4287,7 +4287,7 @@ class G1FreeHumongousRegionClosure : public HeapRegionClosure { public: G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) : - _free_region_list(free_region_list), _humongous_objects_reclaimed(0), _humongous_regions_reclaimed(0), _freed_bytes(0) { + _free_region_list(free_region_list), _proxy_set(NULL), _humongous_objects_reclaimed(0), _humongous_regions_reclaimed(0), _freed_bytes(0) { } virtual bool do_heap_region(HeapRegion* r) { diff --git a/src/hotspot/share/gc/g1/g1HeapVerifier.cpp b/src/hotspot/share/gc/g1/g1HeapVerifier.cpp index 52c8b5c02db..bdbca22c5ed 100644 --- a/src/hotspot/share/gc/g1/g1HeapVerifier.cpp +++ b/src/hotspot/share/gc/g1/g1HeapVerifier.cpp @@ -337,10 +337,6 @@ void G1HeapVerifier::verify_ready_for_archiving() { } class VerifyArchivePointerRegionClosure: public HeapRegionClosure { -private: - G1CollectedHeap* _g1h; -public: - VerifyArchivePointerRegionClosure(G1CollectedHeap* g1h) { } virtual bool do_heap_region(HeapRegion* r) { if (r->is_archive()) { VerifyObjectInArchiveRegionClosure verify_oop_pointers(r, false); @@ -352,7 +348,7 @@ public: void G1HeapVerifier::verify_archive_regions() { G1CollectedHeap* g1h = G1CollectedHeap::heap(); - VerifyArchivePointerRegionClosure cl(NULL); + VerifyArchivePointerRegionClosure cl; g1h->heap_region_iterate(&cl); } diff --git a/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp b/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp index f993ca3ac43..764637bfc9a 100644 --- a/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp +++ b/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,7 +40,8 @@ G1YoungRemSetSamplingThread::G1YoungRemSetSamplingThread() : "G1YoungRemSetSamplingThread monitor", true, Monitor::_safepoint_check_never), - _last_periodic_gc_attempt_s(os::elapsedTime()) { + _last_periodic_gc_attempt_s(os::elapsedTime()), + _vtime_accum(0) { set_name("G1 Young RemSet Sampling"); create_and_start(); } diff --git a/src/hotspot/share/gc/g1/heapRegion.cpp b/src/hotspot/share/gc/g1/heapRegion.cpp index bca744ff027..ff2cf2465af 100644 --- a/src/hotspot/share/gc/g1/heapRegion.cpp +++ b/src/hotspot/share/gc/g1/heapRegion.cpp @@ -877,8 +877,10 @@ void G1ContiguousSpace::object_iterate(ObjectClosure* blk) { } G1ContiguousSpace::G1ContiguousSpace(G1BlockOffsetTable* bot) : + _top(NULL), _bot_part(bot, this), - _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true) + _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true), + _pre_dummy_top(NULL) { } From aef52a6e3a3f071f309e1011c3eb40b88fd45fbc Mon Sep 17 00:00:00 2001 From: Lin Zang Date: Tue, 11 Dec 2018 10:23:15 -0800 Subject: [PATCH 065/174] 8215228: Use a constant hash table size in order to enable compiler optimization Remove a field from KlassInfoTable to allow compiler optimizations Reviewed-by: phh, aph --- src/hotspot/share/memory/heapInspection.cpp | 14 ++++++-------- src/hotspot/share/memory/heapInspection.hpp | 1 - 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/hotspot/share/memory/heapInspection.cpp b/src/hotspot/share/memory/heapInspection.cpp index 0bfd49ad054..b51ba6269c5 100644 --- a/src/hotspot/share/memory/heapInspection.cpp +++ b/src/hotspot/share/memory/heapInspection.cpp @@ -168,14 +168,12 @@ public: KlassInfoTable::KlassInfoTable(bool add_all_classes) { _size_of_instances_in_words = 0; - _size = 0; _ref = (HeapWord*) Universe::boolArrayKlassObj(); _buckets = (KlassInfoBucket*) AllocateHeap(sizeof(KlassInfoBucket) * _num_buckets, mtInternal, CURRENT_PC, AllocFailStrategy::RETURN_NULL); if (_buckets != NULL) { - _size = _num_buckets; - for (int index = 0; index < _size; index++) { + for (int index = 0; index < _num_buckets; index++) { _buckets[index].initialize(); } if (add_all_classes) { @@ -187,11 +185,11 @@ KlassInfoTable::KlassInfoTable(bool add_all_classes) { KlassInfoTable::~KlassInfoTable() { if (_buckets != NULL) { - for (int index = 0; index < _size; index++) { + for (int index = 0; index < _num_buckets; index++) { _buckets[index].empty(); } FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets); - _size = 0; + _buckets = NULL; } } @@ -200,7 +198,7 @@ uint KlassInfoTable::hash(const Klass* p) { } KlassInfoEntry* KlassInfoTable::lookup(Klass* k) { - uint idx = hash(k) % _size; + uint idx = hash(k) % _num_buckets; assert(_buckets != NULL, "Allocation failure should have been caught"); KlassInfoEntry* e = _buckets[idx].lookup(k); // Lookup may fail if this is a new klass for which we @@ -227,8 +225,8 @@ bool KlassInfoTable::record_instance(const oop obj) { } void KlassInfoTable::iterate(KlassInfoClosure* cic) { - assert(_size == 0 || _buckets != NULL, "Allocation failure should have been caught"); - for (int index = 0; index < _size; index++) { + assert(_buckets != NULL, "Allocation failure should have been caught"); + for (int index = 0; index < _num_buckets; index++) { _buckets[index].iterate(cic); } } diff --git a/src/hotspot/share/memory/heapInspection.hpp b/src/hotspot/share/memory/heapInspection.hpp index 5031b99d091..dfeb73eee19 100644 --- a/src/hotspot/share/memory/heapInspection.hpp +++ b/src/hotspot/share/memory/heapInspection.hpp @@ -234,7 +234,6 @@ class KlassInfoBucket: public CHeapObj { class KlassInfoTable: public StackObj { private: - int _size; static const int _num_buckets = 20011; size_t _size_of_instances_in_words; From 5fad1ca25cc0b08dd292aaf162c2cbd1b105f0ab Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 13 Dec 2018 10:08:22 -0800 Subject: [PATCH 066/174] 8215366: Code quality improvements in com.sun.tools.javac.code.TypeAnnotations Reviewed-by: mcimadamore, wmdietl, bsrbnd --- .../sun/tools/javac/code/TypeAnnotations.java | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java index 47f9a0295c3..ba99c18c4b8 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java @@ -427,6 +427,10 @@ public class TypeAnnotations { if (annotations.isEmpty()) { return type; } + // All annotations share the same position + for (TypeCompound tc : annotations) { + Assert.check(tc.position == pos); + } if (type.hasTag(TypeTag.ARRAY)) return rewriteArrayType((ArrayType)type, annotations, pos); @@ -522,10 +526,7 @@ public class TypeAnnotations { if (depth.nonEmpty()) { // Only need to change the annotation positions // if they are on an enclosed type. - // All annotations share the same position; modify the first one. - Attribute.TypeCompound a = annotations.get(0); - TypeAnnotationPosition p = a.position; - p.location = p.location.appendList(depth.toList()); + pos.location = pos.location.appendList(depth.toList()); } Type ret = typeWithAnnotations(type, enclTy, annotations); @@ -583,11 +584,7 @@ public class TypeAnnotations { tomodify.elemtype = elemType; // Update positions - for (TypeCompound tc : annotations) { - if (tc.position == null) - tc.position = pos; - tc.position.location = loc; - } + pos.location = loc; return res; } @@ -1396,16 +1393,6 @@ public class TypeAnnotations { scan(tree.elems); } - - private void findTypeCompoundPosition(JCTree tree, JCTree frame, List annotations) { - if (!annotations.isEmpty()) { - final TypeAnnotationPosition p = - resolveFrame(tree, frame, frames, currentLambda, 0, new ListBuffer<>()); - for (TypeCompound tc : annotations) - tc.position = p; - } - } - private void findPosition(JCTree tree, JCTree frame, List annotations) { if (!annotations.isEmpty()) { From bbfc4b795696dec22e2fd7332efc4be5cb930c30 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 13 Dec 2018 11:05:40 -0800 Subject: [PATCH 067/174] 8215368: Make Check.checkOverride call diagnosticPositionFor lazily Reviewed-by: mcimadamore, vromero --- .../share/classes/com/sun/tools/javac/comp/Check.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 9d2153db1a7..a1ffe632b3d 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -26,6 +26,7 @@ package com.sun.tools.javac.comp; import java.util.*; +import java.util.function.Supplier; import javax.tools.JavaFileManager; @@ -1797,7 +1798,7 @@ public class Check { if (!isDeprecatedOverrideIgnorable(other, origin)) { Lint prevLint = setLint(lint.augment(m)); try { - checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other); + checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other); } finally { setLint(prevLint); } @@ -3259,10 +3260,14 @@ public class Check { } void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) { + checkDeprecated(() -> pos, other, s); + } + + void checkDeprecated(Supplier pos, final Symbol other, final Symbol s) { if ( (s.isDeprecatedForRemoval() || s.isDeprecated() && !other.isDeprecated()) && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)) { - deferredLintHandler.report(() -> warnDeprecated(pos, s)); + deferredLintHandler.report(() -> warnDeprecated(pos.get(), s)); } } From 888057a89f4e39d6778e534b97f6df67de5e3f12 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Tue, 18 Dec 2018 10:26:15 +0000 Subject: [PATCH 068/174] 8215449: Several tests failing when jtreg run with -vmoption:--illegal-access=deny Reviewed-by: redestad, mchung, jjg --- test/jdk/java/net/URL/RacyHandler.java | 3 ++- .../java/util/Locale/LocaleProvidersRun.java | 1 + .../platform/CanHandleClassFilesTest.java | 23 +++++++++++++++++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/test/jdk/java/net/URL/RacyHandler.java b/test/jdk/java/net/URL/RacyHandler.java index 1255465d68b..6067e1e8bf8 100644 --- a/test/jdk/java/net/URL/RacyHandler.java +++ b/test/jdk/java/net/URL/RacyHandler.java @@ -32,6 +32,7 @@ import java.util.concurrent.CountDownLatch; * @test * @bug 8213942 * @summary URLStreamHandler initialization race + * @modules java.base/java.net:open * @run main/othervm RacyHandler * @run main/othervm RacyHandler * @run main/othervm RacyHandler @@ -110,4 +111,4 @@ public class RacyHandler { return null; } } -} \ No newline at end of file +} diff --git a/test/jdk/java/util/Locale/LocaleProvidersRun.java b/test/jdk/java/util/Locale/LocaleProvidersRun.java index dc8aead183b..6cb041847eb 100644 --- a/test/jdk/java/util/Locale/LocaleProvidersRun.java +++ b/test/jdk/java/util/Locale/LocaleProvidersRun.java @@ -156,6 +156,7 @@ public class LocaleProvidersRun { launcher.addToolArg("-cp") .addToolArg(Utils.TEST_CLASS_PATH) .addToolArg("-Djava.locale.providers=" + prefList) + .addToolArg("--add-exports=java.base/sun.util.locale.provider=ALL-UNNAMED") .addToolArg("LocaleProviders") .addToolArg(methodName) .addToolArg(param1) diff --git a/test/langtools/tools/javac/platform/CanHandleClassFilesTest.java b/test/langtools/tools/javac/platform/CanHandleClassFilesTest.java index 12be99b4eb7..fbbe22c30a6 100644 --- a/test/langtools/tools/javac/platform/CanHandleClassFilesTest.java +++ b/test/langtools/tools/javac/platform/CanHandleClassFilesTest.java @@ -26,8 +26,11 @@ * @bug 8207954 * @summary Verify that CreateSymbols can handle classfiles from the current release. * @library /tools/lib /tools/javac/lib - * @modules jdk.compiler/com.sun.tools.javac.api + * @modules jdk.compiler/com.sun.tools.javac.api:+open * jdk.compiler/com.sun.tools.javac.main + * jdk.compiler/com.sun.tools.javac.jvm:+open + * jdk.compiler/com.sun.tools.javac.util:+open + * jdk.jdeps/com.sun.tools.classfile:+open * @build toolbox.ToolBox toolbox.JavacTask toolbox.Task * @run main CanHandleClassFilesTest */ @@ -36,6 +39,7 @@ import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Stream; import javax.tools.StandardLocation; @@ -93,8 +97,16 @@ public class CanHandleClassFilesTest { } }; + // open the non-exported packages needed by CreateSymbols to its module + Module targetModule = cl.getUnnamedModule(); + Stream.of("jdk.compiler/com.sun.tools.javac.api", + "jdk.compiler/com.sun.tools.javac.jvm", + "jdk.compiler/com.sun.tools.javac.util", + "jdk.jdeps/com.sun.tools.classfile") + .forEach(p -> open(p, targetModule)); + var createSymbolsClass = Class.forName("build.tools.symbolgenerator.CreateSymbols", false, cl); - var main = createSymbolsClass.getDeclaredMethod("main", String[].class); + var main = createSymbolsClass.getMethod("main", String[].class); var symbols = targetDir.resolve("symbols"); try (Writer w = Files.newBufferedWriter(symbols)) {} @@ -112,4 +124,11 @@ public class CanHandleClassFilesTest { } } + void open(String moduleAndPackage, Module target) { + String[] s = moduleAndPackage.split("/"); + var moduleName = s[0]; + var packageName = s[1]; + ModuleLayer.boot().findModule(moduleName).orElseThrow().addOpens(packageName, target); + } + } From cc65367331a06748c526aa4d806436f28b275b39 Mon Sep 17 00:00:00 2001 From: Gary Adams Date: Tue, 18 Dec 2018 07:33:07 -0500 Subject: [PATCH 069/174] 8051349: nsk/jvmti/scenarios/sampling/SP06/sp06t003 fails in nightly Reviewed-by: dholmes, sspitsyn, cjplummer, jcbeyler --- test/hotspot/jtreg/ProblemList.txt | 1 - .../scenarios/sampling/SP02/sp02t003/sp02t003.cpp | 7 ++++--- .../nsk/jvmti/scenarios/sampling/SP06/sp06t001.java | 12 +++++++++++- .../scenarios/sampling/SP06/sp06t003/sp06t003.cpp | 9 +++++---- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index 1b68703e0f0..7817ad9e964 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -187,7 +187,6 @@ vmTestbase/nsk/jvmti/ResourceExhausted/resexhausted003/TestDescription.java 6606 vmTestbase/nsk/jvmti/ResourceExhausted/resexhausted004/TestDescription.java 7013634,6606767 generic-all vmTestbase/nsk/jvmti/ThreadStart/threadstart001/TestDescription.java 8016181 generic-all vmTestbase/nsk/jvmti/scenarios/extension/EX03/ex03t001/TestDescription.java 8173658 generic-all -vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/TestDescription.java 8051349 generic-all vmTestbase/nsk/jvmti/AttachOnDemand/attach034/TestDescription.java 8042145 generic-all vmTestbase/nsk/jvmti/AttachOnDemand/attach045/TestDescription.java 8202971 generic-all vmTestbase/nsk/jvmti/unit/heap/HeapWalkTests/TestDescription.java 8016181 generic-all diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp index 5d739617ba6..84978a09f47 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp @@ -310,7 +310,8 @@ static int checkThreads(int suspended, const char* kind) { (long)frameStack[j].location); /* query frame location */ if (!NSK_JVMTI_VERIFY( - jvmti->GetFrameLocation(threadsDesc[i].thread, j, &qMethod, &qLocation))) { + jvmti->GetFrameLocation(threadsDesc[i].thread, j, &qMethod, &qLocation)) + && (suspended == NSK_TRUE)) { nsk_jvmti_setFailStatus(); continue; } @@ -318,8 +319,8 @@ static int checkThreads(int suspended, const char* kind) { NSK_DISPLAY2(" queried: method: %p, location: %ld\n", (void*)qMethod, (long)qLocation); - /* check frame equalaty */ - if (frameStack[j].method != qMethod) { + /* check frame equality */ + if ((suspended == NSK_TRUE) && (frameStack[j].method != qMethod)) { NSK_COMPLAIN6("Different method in stack frame #%d for %s thread #%d (%s):\n" "# GetStackTrace(): %p\n" "# GetFrameLocation(): %p\n", diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t001.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t001.java index 918a759b713..13009b7a318 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t001.java @@ -268,6 +268,7 @@ class sp06t001ThreadSleeping extends sp06t001Thread { class sp06t001ThreadRunningInterrupted extends sp06t001Thread { private Object waitingMonitor = new Object(); + volatile boolean interruptReady = false; public sp06t001ThreadRunningInterrupted(String name, Log log) { super(name, log); @@ -275,8 +276,9 @@ class sp06t001ThreadRunningInterrupted extends sp06t001Thread { public void testedMethod(boolean simulate, int i) { if (!simulate) { + interruptReady = true; synchronized (waitingMonitor) { - // wait on watingMonitor until interrupted + // wait on waitingMonitor until interrupted try { waitingMonitor.wait(); } catch (InterruptedException ignore) { @@ -303,6 +305,14 @@ class sp06t001ThreadRunningInterrupted extends sp06t001Thread { public boolean checkReady() { // interrupt thread on wait() + // delay until testMethod is ready + while (!interruptReady) { + try { + sleep(1000); + } catch (InterruptedException ie) { + // ignored + } + } synchronized (waitingMonitor) { interrupt(); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp index 96109fdab87..1e6768ed89d 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp @@ -333,7 +333,8 @@ static int checkThreads(int suspended, const char* kind0) { (long)frameStack[j].location); /* query frame location */ if (!NSK_JVMTI_VERIFY( - jvmti->GetFrameLocation(threadsDesc[i].thread, j, &qMethod, &qLocation))) { + jvmti->GetFrameLocation(threadsDesc[i].thread, j, &qMethod, &qLocation)) + && (suspended == NSK_TRUE)) { nsk_jvmti_setFailStatus(); continue; } @@ -341,8 +342,8 @@ static int checkThreads(int suspended, const char* kind0) { NSK_DISPLAY2(" queried: method: 0x%p, location: %ld\n", (void*)qMethod, (long)qLocation); - /* check frame equalaty */ - if (frameStack[j].method != qMethod) { + /* check frame equality */ + if ((suspended == NSK_TRUE) && (frameStack[j].method != qMethod)) { NSK_COMPLAIN6("Different method in stack frame #%d for %s thread #%d (%s):\n" "# GetStackTrace(): 0x%p\n" "# GetFrameLocation(): 0x%p\n", @@ -350,7 +351,7 @@ static int checkThreads(int suspended, const char* kind0) { (void*)frameStack[j].method, (void*)qMethod); nsk_jvmti_setFailStatus(); } - if (frameStack[j].location != qLocation) { + if ((suspended == NSK_TRUE) && (frameStack[j].location != qLocation)) { NSK_COMPLAIN6("Different location in stack frame #%d for %s thread #%d (%s):\n" "# GetStackTrace(): %ld\n" "# GetFrameLocation(): %ld\n", From 8b6b63b38b6f2ffdded8c3c05eaf5a05eb07e2f6 Mon Sep 17 00:00:00 2001 From: Vicente Romero Date: Tue, 18 Dec 2018 16:22:46 -0500 Subject: [PATCH 070/174] 8207224: Javac compiles source code despite illegal use of unchecked conversions Reviewed-by: mcimadamore, darcy --- .../com/sun/tools/javac/code/Source.java | 3 +- .../com/sun/tools/javac/code/Types.java | 11 ++++++-- .../T8207224/ReturnTypeSubstitutableTest.java | 28 +++++++++++++++++++ .../T8207224/ReturnTypeSubstitutableTest.out | 2 ++ 4 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java create mode 100644 test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java index 9832f731200..93f8c280b8c 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java @@ -189,7 +189,8 @@ public enum Source { SWITCH_MULTIPLE_CASE_LABELS(JDK13, Fragments.FeatureMultipleCaseLabels, DiagKind.PLURAL), SWITCH_RULE(JDK13, Fragments.FeatureSwitchRules, DiagKind.PLURAL), SWITCH_EXPRESSION(JDK13, Fragments.FeatureSwitchExpressions, DiagKind.PLURAL), - RAW_STRING_LITERALS(JDK13, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL); + RAW_STRING_LITERALS(JDK13, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL), + RETURN_TYPE_SUBSTITUTABLE_SAME_TYPE(JDK13); enum DiagKind { NORMAL, diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java index 15cdeb5b713..f779a769cb5 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java @@ -91,6 +91,7 @@ public class Types { final Names names; final boolean allowDefaultMethods; final boolean mapCapturesToBounds; + final boolean returnTypeSustitutableSameType; final Check chk; final Enter enter; JCDiagnostic.Factory diags; @@ -114,6 +115,7 @@ public class Types { Source source = Source.instance(context); allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source); mapCapturesToBounds = Feature.MAP_CAPTURES_TO_BOUNDS.allowedInSource(source); + returnTypeSustitutableSameType = Feature.RETURN_TYPE_SUBSTITUTABLE_SAME_TYPE.allowedInSource(source); chk = Check.instance(context); enter = Enter.instance(context); capturedName = names.fromString(""); @@ -4235,8 +4237,13 @@ public class Types { return covariantReturnType(r1.getReturnType(), r2res, warner); if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner)) return true; - if (!isSubtype(r1.getReturnType(), erasure(r2res))) - return false; + if (returnTypeSustitutableSameType) { + if (!isSameType(r1.getReturnType(), erasure(r2res))) + return false; + } else { + if (!isSubtype(r1.getReturnType(), erasure(r2res))) + return false; + } warner.warn(LintCategory.UNCHECKED); return true; } diff --git a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java new file mode 100644 index 00000000000..1a4708548af --- /dev/null +++ b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java @@ -0,0 +1,28 @@ +/* + * @test /nodynamiccopyright/ + * @bug 8207224 + * @summary Javac compiles source code despite illegal use of unchecked conversions + * @compile/fail/ref=ReturnTypeSubstitutableTest.out -XDrawDiagnostics ReturnTypeSubstitutableTest.java + * @compile -source 12 ReturnTypeSubstitutableTest.java + */ + +class ReturnTypeSubstitutableTest { + abstract class AbstractDemo { + protected abstract Response test(Request request); + } + + abstract interface AbstractResult {} + + abstract interface SimpleResult extends AbstractResult {} + + class Result1 implements SimpleResult {} + + class OtherResult implements AbstractResult {} + + public class SimpleDemo extends AbstractDemo { + @Override + protected SimpleResult test(AbstractResult request) { + return null; + } + } +} diff --git a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out new file mode 100644 index 00000000000..4a9c5594402 --- /dev/null +++ b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out @@ -0,0 +1,2 @@ +ReturnTypeSubstitutableTest.java:24:32: compiler.err.override.incompatible.ret: (compiler.misc.cant.override: test(ReturnTypeSubstitutableTest.AbstractResult), ReturnTypeSubstitutableTest.SimpleDemo, test(Request), ReturnTypeSubstitutableTest.AbstractDemo), ReturnTypeSubstitutableTest.SimpleResult, Response +1 error From 556d79b518b0c3ac7fcf12a852b3b778605d4129 Mon Sep 17 00:00:00 2001 From: Pengfei Li Date: Tue, 18 Dec 2018 16:50:35 +0000 Subject: [PATCH 071/174] 8212043: Add floating-point Math.min/max intrinsics Floating-point Math.min() and Math.max() intrinsics are enabled on AArch64 platform Reviewed-by: adinn, aph --- src/hotspot/cpu/aarch64/aarch64.ad | 57 +++++++++++++++++++ src/hotspot/cpu/aarch64/assembler_aarch64.hpp | 4 ++ src/hotspot/share/adlc/formssel.cpp | 2 +- src/hotspot/share/classfile/vmSymbols.cpp | 4 ++ src/hotspot/share/classfile/vmSymbols.hpp | 5 ++ src/hotspot/share/opto/addnode.hpp | 48 ++++++++++++++++ src/hotspot/share/opto/c2compiler.cpp | 12 ++++ src/hotspot/share/opto/classes.hpp | 4 ++ src/hotspot/share/opto/library_call.cpp | 43 ++++++++++++++ src/hotspot/share/opto/type.cpp | 20 +++++++ src/hotspot/share/opto/type.hpp | 4 ++ src/hotspot/share/runtime/vmStructs.cpp | 4 ++ .../share/classes/java/lang/Math.java | 4 ++ .../share/classes/java/lang/StrictMath.java | 4 ++ 14 files changed, 214 insertions(+), 1 deletion(-) diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index 9ba919947b8..c55f7121291 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -12601,6 +12601,63 @@ instruct mnsubD_reg_reg(vRegD dst, vRegD src1, vRegD src2, vRegD src3, immD0 zer %} +// Math.max(FF)F +instruct maxF_reg_reg(vRegF dst, vRegF src1, vRegF src2) %{ + match(Set dst (MaxF src1 src2)); + + format %{ "fmaxs $dst, $src1, $src2" %} + ins_encode %{ + __ fmaxs(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + + ins_pipe(fp_dop_reg_reg_s); +%} + +// Math.min(FF)F +instruct minF_reg_reg(vRegF dst, vRegF src1, vRegF src2) %{ + match(Set dst (MinF src1 src2)); + + format %{ "fmins $dst, $src1, $src2" %} + ins_encode %{ + __ fmins(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + + ins_pipe(fp_dop_reg_reg_s); +%} + +// Math.max(DD)D +instruct maxD_reg_reg(vRegD dst, vRegD src1, vRegD src2) %{ + match(Set dst (MaxD src1 src2)); + + format %{ "fmaxd $dst, $src1, $src2" %} + ins_encode %{ + __ fmaxd(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + + ins_pipe(fp_dop_reg_reg_d); +%} + +// Math.min(DD)D +instruct minD_reg_reg(vRegD dst, vRegD src1, vRegD src2) %{ + match(Set dst (MinD src1 src2)); + + format %{ "fmind $dst, $src1, $src2" %} + ins_encode %{ + __ fmind(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + + ins_pipe(fp_dop_reg_reg_d); +%} + + instruct divF_reg_reg(vRegF dst, vRegF src1, vRegF src2) %{ match(Set dst (DivF src1 src2)); diff --git a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp index 09c7cd240f4..1dbdf2bf79e 100644 --- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp @@ -1826,12 +1826,16 @@ public: INSN(fdivs, 0b000, 0b00, 0b0001); INSN(fadds, 0b000, 0b00, 0b0010); INSN(fsubs, 0b000, 0b00, 0b0011); + INSN(fmaxs, 0b000, 0b00, 0b0100); + INSN(fmins, 0b000, 0b00, 0b0101); INSN(fnmuls, 0b000, 0b00, 0b1000); INSN(fmuld, 0b000, 0b01, 0b0000); INSN(fdivd, 0b000, 0b01, 0b0001); INSN(faddd, 0b000, 0b01, 0b0010); INSN(fsubd, 0b000, 0b01, 0b0011); + INSN(fmaxd, 0b000, 0b01, 0b0100); + INSN(fmind, 0b000, 0b01, 0b0101); INSN(fnmuld, 0b000, 0b01, 0b1000); #undef INSN diff --git a/src/hotspot/share/adlc/formssel.cpp b/src/hotspot/share/adlc/formssel.cpp index f1996c27f03..855385b1ab9 100644 --- a/src/hotspot/share/adlc/formssel.cpp +++ b/src/hotspot/share/adlc/formssel.cpp @@ -3801,7 +3801,7 @@ void MatchNode::count_commutative_op(int& count) { "AddVB","AddVS","AddVI","AddVL","AddVF","AddVD", "AndI","AndL", "AndV", - "MaxI","MinI", + "MaxI","MinI","MaxF","MinF","MaxD","MinD", "MulI","MulL","MulF","MulD", "MulVS","MulVI","MulVL","MulVF","MulVD", "OrI","OrL", diff --git a/src/hotspot/share/classfile/vmSymbols.cpp b/src/hotspot/share/classfile/vmSymbols.cpp index b8b56e4a84d..aa2bbe406c8 100644 --- a/src/hotspot/share/classfile/vmSymbols.cpp +++ b/src/hotspot/share/classfile/vmSymbols.cpp @@ -580,6 +580,10 @@ bool vmIntrinsics::is_disabled_by_flags(vmIntrinsics::ID id) { case vmIntrinsics::_max: case vmIntrinsics::_floatToIntBits: case vmIntrinsics::_doubleToLongBits: + case vmIntrinsics::_maxF: + case vmIntrinsics::_minF: + case vmIntrinsics::_maxD: + case vmIntrinsics::_minD: if (!InlineMathNatives) return true; break; case vmIntrinsics::_fmaD: diff --git a/src/hotspot/share/classfile/vmSymbols.hpp b/src/hotspot/share/classfile/vmSymbols.hpp index 0e0b77aca1c..371613b3117 100644 --- a/src/hotspot/share/classfile/vmSymbols.hpp +++ b/src/hotspot/share/classfile/vmSymbols.hpp @@ -748,6 +748,7 @@ do_class(java_lang_StrictMath, "java/lang/StrictMath") \ do_signature(double2_double_signature, "(DD)D") \ do_signature(double3_double_signature, "(DDD)D") \ + do_signature(float2_float_signature, "(FF)F") \ do_signature(float3_float_signature, "(FFF)F") \ do_signature(int2_int_signature, "(II)I") \ do_signature(long2_long_signature, "(JJ)J") \ @@ -794,6 +795,10 @@ do_intrinsic(_subtractExactL, java_lang_Math, subtractExact_name, long2_long_signature, F_S) \ do_intrinsic(_fmaD, java_lang_Math, fma_name, double3_double_signature, F_S) \ do_intrinsic(_fmaF, java_lang_Math, fma_name, float3_float_signature, F_S) \ + do_intrinsic(_maxF, java_lang_Math, max_name, float2_float_signature, F_S) \ + do_intrinsic(_minF, java_lang_Math, min_name, float2_float_signature, F_S) \ + do_intrinsic(_maxD, java_lang_Math, max_name, double2_double_signature, F_S) \ + do_intrinsic(_minD, java_lang_Math, min_name, double2_double_signature, F_S) \ \ do_intrinsic(_floatToRawIntBits, java_lang_Float, floatToRawIntBits_name, float_int_signature, F_S) \ do_name( floatToRawIntBits_name, "floatToRawIntBits") \ diff --git a/src/hotspot/share/opto/addnode.hpp b/src/hotspot/share/opto/addnode.hpp index 8166050d228..f3e94fc695c 100644 --- a/src/hotspot/share/opto/addnode.hpp +++ b/src/hotspot/share/opto/addnode.hpp @@ -249,4 +249,52 @@ public: virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); }; +//------------------------------MaxFNode--------------------------------------- +// Maximum of 2 floats. +class MaxFNode : public MaxNode { +public: + MaxFNode(Node *in1, Node *in2) : MaxNode(in1, in2) {} + virtual int Opcode() const; + virtual const Type *add_ring(const Type*, const Type*) const { return Type::FLOAT; } + virtual const Type *add_id() const { return TypeF::NEG_INF; } + virtual const Type *bottom_type() const { return Type::FLOAT; } + virtual uint ideal_reg() const { return Op_RegF; } +}; + +//------------------------------MinFNode--------------------------------------- +// Minimum of 2 floats. +class MinFNode : public MaxNode { +public: + MinFNode(Node *in1, Node *in2) : MaxNode(in1, in2) {} + virtual int Opcode() const; + virtual const Type *add_ring(const Type*, const Type*) const { return Type::FLOAT; } + virtual const Type *add_id() const { return TypeF::POS_INF; } + virtual const Type *bottom_type() const { return Type::FLOAT; } + virtual uint ideal_reg() const { return Op_RegF; } +}; + +//------------------------------MaxDNode--------------------------------------- +// Maximum of 2 doubles. +class MaxDNode : public MaxNode { +public: + MaxDNode(Node *in1, Node *in2) : MaxNode(in1, in2) {} + virtual int Opcode() const; + virtual const Type *add_ring(const Type*, const Type*) const { return Type::DOUBLE; } + virtual const Type *add_id() const { return TypeD::NEG_INF; } + virtual const Type *bottom_type() const { return Type::DOUBLE; } + virtual uint ideal_reg() const { return Op_RegD; } +}; + +//------------------------------MinDNode--------------------------------------- +// Minimum of 2 doubles. +class MinDNode : public MaxNode { +public: + MinDNode(Node *in1, Node *in2) : MaxNode(in1, in2) {} + virtual int Opcode() const; + virtual const Type *add_ring(const Type*, const Type*) const { return Type::DOUBLE; } + virtual const Type *add_id() const { return TypeD::POS_INF; } + virtual const Type *bottom_type() const { return Type::DOUBLE; } + virtual uint ideal_reg() const { return Op_RegD; } +}; + #endif // SHARE_VM_OPTO_ADDNODE_HPP diff --git a/src/hotspot/share/opto/c2compiler.cpp b/src/hotspot/share/opto/c2compiler.cpp index 0b2ff2b190a..527a3b2cafc 100644 --- a/src/hotspot/share/opto/c2compiler.cpp +++ b/src/hotspot/share/opto/c2compiler.cpp @@ -440,6 +440,18 @@ bool C2Compiler::is_intrinsic_supported(const methodHandle& method, bool is_virt case vmIntrinsics::_isWhitespace: if (!Matcher::match_rule_supported(Op_Whitespace)) return false; break; + case vmIntrinsics::_maxF: + if (!Matcher::match_rule_supported(Op_MaxF)) return false; + break; + case vmIntrinsics::_minF: + if (!Matcher::match_rule_supported(Op_MinF)) return false; + break; + case vmIntrinsics::_maxD: + if (!Matcher::match_rule_supported(Op_MaxD)) return false; + break; + case vmIntrinsics::_minD: + if (!Matcher::match_rule_supported(Op_MinD)) return false; + break; case vmIntrinsics::_hashCode: case vmIntrinsics::_identityHashCode: case vmIntrinsics::_getClass: diff --git a/src/hotspot/share/opto/classes.hpp b/src/hotspot/share/opto/classes.hpp index 8f5f9f6eeb2..6a2384168ad 100644 --- a/src/hotspot/share/opto/classes.hpp +++ b/src/hotspot/share/opto/classes.hpp @@ -202,6 +202,8 @@ macro(LoopLimit) macro(Mach) macro(MachProj) macro(MulAddS2I) +macro(MaxD) +macro(MaxF) macro(MaxI) macro(MemBarAcquire) macro(LoadFence) @@ -214,6 +216,8 @@ macro(MemBarReleaseLock) macro(MemBarVolatile) macro(MemBarStoreStore) macro(MergeMem) +macro(MinD) +macro(MinF) macro(MinI) macro(ModD) macro(ModF) diff --git a/src/hotspot/share/opto/library_call.cpp b/src/hotspot/share/opto/library_call.cpp index 60d97657b00..733dcb2f46b 100644 --- a/src/hotspot/share/opto/library_call.cpp +++ b/src/hotspot/share/opto/library_call.cpp @@ -325,6 +325,7 @@ class LibraryCallKit : public GraphKit { bool inline_vectorizedMismatch(); bool inline_fma(vmIntrinsics::ID id); bool inline_character_compare(vmIntrinsics::ID id); + bool inline_fp_min_max(vmIntrinsics::ID id); bool inline_profileBoolean(); bool inline_isCompileConstant(); @@ -874,6 +875,12 @@ bool LibraryCallKit::try_to_inline(int predicate) { case vmIntrinsics::_isWhitespace: return inline_character_compare(intrinsic_id()); + case vmIntrinsics::_maxF: + case vmIntrinsics::_minF: + case vmIntrinsics::_maxD: + case vmIntrinsics::_minD: + return inline_fp_min_max(intrinsic_id()); + default: // If you get here, it may be that someone has added a new intrinsic // to the list in vmSymbols.hpp without implementing it here. @@ -6588,6 +6595,42 @@ bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) { return true; } +//------------------------------inline_fp_min_max------------------------------ +bool LibraryCallKit::inline_fp_min_max(vmIntrinsics::ID id) { + Node *a = NULL; + Node *b = NULL; + Node *n = NULL; + switch (id) { + case vmIntrinsics::_maxF: + case vmIntrinsics::_minF: + assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each."); + a = argument(0); + b = argument(1); + break; + case vmIntrinsics::_maxD: + case vmIntrinsics::_minD: + assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each."); + a = round_double_node(argument(0)); + b = round_double_node(argument(2)); + break; + default: + fatal_unexpected_iid(id); + break; + } + if (a->is_Con() || b->is_Con()) { + return false; + } + switch (id) { + case vmIntrinsics::_maxF: n = new MaxFNode(a, b); break; + case vmIntrinsics::_minF: n = new MinFNode(a, b); break; + case vmIntrinsics::_maxD: n = new MaxDNode(a, b); break; + case vmIntrinsics::_minD: n = new MinDNode(a, b); break; + default: fatal_unexpected_iid(id); break; + } + set_result(_gvn.transform(n)); + return true; +} + bool LibraryCallKit::inline_profileBoolean() { Node* counts = argument(1); const TypeAryPtr* ary = NULL; diff --git a/src/hotspot/share/opto/type.cpp b/src/hotspot/share/opto/type.cpp index 73b319fa8e3..35f796ecb9b 100644 --- a/src/hotspot/share/opto/type.cpp +++ b/src/hotspot/share/opto/type.cpp @@ -416,6 +416,18 @@ int Type::uhash( const Type *const t ) { #define SMALLINT ((juint)3) // a value too insignificant to consider widening +static double pos_dinf() { + union { int64_t i; double d; } v; + v.i = CONST64(0x7ff0000000000000); + return v.d; +} + +static float pos_finf() { + union { int32_t i; float f; } v; + v.i = 0x7f800000; + return v.f; +} + //--------------------------Initialize_shared---------------------------------- void Type::Initialize_shared(Compile* current) { // This method does not need to be locked because the first system @@ -445,9 +457,13 @@ void Type::Initialize_shared(Compile* current) { TypeF::ZERO = TypeF::make(0.0); // Float 0 (positive zero) TypeF::ONE = TypeF::make(1.0); // Float 1 + TypeF::POS_INF = TypeF::make(pos_finf()); + TypeF::NEG_INF = TypeF::make(-pos_finf()); TypeD::ZERO = TypeD::make(0.0); // Double 0 (positive zero) TypeD::ONE = TypeD::make(1.0); // Double 1 + TypeD::POS_INF = TypeD::make(pos_dinf()); + TypeD::NEG_INF = TypeD::make(-pos_dinf()); TypeInt::MINUS_1 = TypeInt::make(-1); // -1 TypeInt::ZERO = TypeInt::make( 0); // 0 @@ -1087,6 +1103,8 @@ void Type::typerr( const Type *t ) const { // Convenience common pre-built types. const TypeF *TypeF::ZERO; // Floating point zero const TypeF *TypeF::ONE; // Floating point one +const TypeF *TypeF::POS_INF; // Floating point positive infinity +const TypeF *TypeF::NEG_INF; // Floating point negative infinity //------------------------------make------------------------------------------- // Create a float constant @@ -1195,6 +1213,8 @@ bool TypeF::empty(void) const { // Convenience common pre-built types. const TypeD *TypeD::ZERO; // Floating point zero const TypeD *TypeD::ONE; // Floating point one +const TypeD *TypeD::POS_INF; // Floating point positive infinity +const TypeD *TypeD::NEG_INF; // Floating point negative infinity //------------------------------make------------------------------------------- const TypeD *TypeD::make(double d) { diff --git a/src/hotspot/share/opto/type.hpp b/src/hotspot/share/opto/type.hpp index 105e28344db..63728a2ac30 100644 --- a/src/hotspot/share/opto/type.hpp +++ b/src/hotspot/share/opto/type.hpp @@ -483,6 +483,8 @@ public: // Convenience common pre-built types. static const TypeF *ZERO; // positive zero only static const TypeF *ONE; + static const TypeF *POS_INF; + static const TypeF *NEG_INF; #ifndef PRODUCT virtual void dump2( Dict &d, uint depth, outputStream *st ) const; #endif @@ -510,6 +512,8 @@ public: // Convenience common pre-built types. static const TypeD *ZERO; // positive zero only static const TypeD *ONE; + static const TypeD *POS_INF; + static const TypeD *NEG_INF; #ifndef PRODUCT virtual void dump2( Dict &d, uint depth, outputStream *st ) const; #endif diff --git a/src/hotspot/share/runtime/vmStructs.cpp b/src/hotspot/share/runtime/vmStructs.cpp index caf8ea844a7..47304c45794 100644 --- a/src/hotspot/share/runtime/vmStructs.cpp +++ b/src/hotspot/share/runtime/vmStructs.cpp @@ -1516,6 +1516,10 @@ typedef PaddedEnd PaddedObjectMonitor; declare_c2_type(MaxNode, AddNode) \ declare_c2_type(MaxINode, MaxNode) \ declare_c2_type(MinINode, MaxNode) \ + declare_c2_type(MaxFNode, MaxNode) \ + declare_c2_type(MinFNode, MaxNode) \ + declare_c2_type(MaxDNode, MaxNode) \ + declare_c2_type(MinDNode, MaxNode) \ declare_c2_type(StartNode, MultiNode) \ declare_c2_type(StartOSRNode, StartNode) \ declare_c2_type(ParmNode, ProjNode) \ diff --git a/src/java.base/share/classes/java/lang/Math.java b/src/java.base/share/classes/java/lang/Math.java index dffce353746..e4c95299315 100644 --- a/src/java.base/share/classes/java/lang/Math.java +++ b/src/java.base/share/classes/java/lang/Math.java @@ -1460,6 +1460,7 @@ public final class Math { * @param b another argument. * @return the larger of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static float max(float a, float b) { if (a != a) return a; // a is NaN @@ -1486,6 +1487,7 @@ public final class Math { * @param b another argument. * @return the larger of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static double max(double a, double b) { if (a != a) return a; // a is NaN @@ -1541,6 +1543,7 @@ public final class Math { * @param b another argument. * @return the smaller of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static float min(float a, float b) { if (a != a) return a; // a is NaN @@ -1567,6 +1570,7 @@ public final class Math { * @param b another argument. * @return the smaller of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static double min(double a, double b) { if (a != a) return a; // a is NaN diff --git a/src/java.base/share/classes/java/lang/StrictMath.java b/src/java.base/share/classes/java/lang/StrictMath.java index 6ff35ebd79a..313d120d929 100644 --- a/src/java.base/share/classes/java/lang/StrictMath.java +++ b/src/java.base/share/classes/java/lang/StrictMath.java @@ -1154,6 +1154,7 @@ public final class StrictMath { * @param b another argument. * @return the larger of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static float max(float a, float b) { return Math.max(a, b); } @@ -1172,6 +1173,7 @@ public final class StrictMath { * @param b another argument. * @return the larger of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static double max(double a, double b) { return Math.max(a, b); } @@ -1219,6 +1221,7 @@ public final class StrictMath { * @param b another argument. * @return the smaller of {@code a} and {@code b.} */ + @HotSpotIntrinsicCandidate public static float min(float a, float b) { return Math.min(a, b); } @@ -1237,6 +1240,7 @@ public final class StrictMath { * @param b another argument. * @return the smaller of {@code a} and {@code b}. */ + @HotSpotIntrinsicCandidate public static double min(double a, double b) { return Math.min(a, b); } From e4b1f82bbde60105c4901d0d4dee804553e0a359 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Wed, 19 Dec 2018 10:30:43 +0100 Subject: [PATCH 072/174] 8215411: some GetByteArrayElements calls miss corresponding Release Reviewed-by: dholmes, jcbeyler --- .../macosx/native/libosxsecurity/KeystoreImpl.m | 8 +++++--- .../native/libattach/VirtualMachineImpl.c | 5 ++--- .../windows/native/libsaproc/sawindbg.cpp | 16 +++++++++++----- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m index e678bce28de..b7b084381fd 100644 --- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m +++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -578,13 +578,15 @@ JNF_COCOA_ENTER(env); cssmPerror("_addItemToKeychain: SecKeychainItemImport", err); } - (*env)->ReleaseByteArrayElements(env, rawDataObj, rawData, JNI_ABORT); - if (createdItems != NULL) { CFRelease(createdItems); } errOut: + if (rawData) { + (*env)->ReleaseByteArrayElements(env, rawDataObj, rawData, JNI_ABORT); + } + if (passwordStrRef) CFRelease(passwordStrRef); if (passwordChars) { // clear the password and release diff --git a/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c b/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c index bf0b21138f9..a21ce9fa73b 100644 --- a/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c +++ b/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c @@ -457,12 +457,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_enqueue if (pCode == NULL) { JNU_ThrowIOExceptionWithLastError(env, "VirtualAllocEx failed"); VirtualFreeEx(hProcess, pData, 0, MEM_RELEASE); + (*env)->ReleaseByteArrayElements(env, stub, stubCode, JNI_ABORT); return; } WriteProcessMemory( hProcess, (LPVOID)pCode, (LPCVOID)stubCode, (SIZE_T)stubLen, NULL ); - if (isCopy) { - (*env)->ReleaseByteArrayElements(env, stub, stubCode, JNI_ABORT); - } + (*env)->ReleaseByteArrayElements(env, stub, stubCode, JNI_ABORT); /* * Create thread in target process to execute code diff --git a/src/jdk.hotspot.agent/windows/native/libsaproc/sawindbg.cpp b/src/jdk.hotspot.agent/windows/native/libsaproc/sawindbg.cpp index 3252e602682..eda86c63e69 100644 --- a/src/jdk.hotspot.agent/windows/native/libsaproc/sawindbg.cpp +++ b/src/jdk.hotspot.agent/windows/native/libsaproc/sawindbg.cpp @@ -722,19 +722,25 @@ JNIEXPORT jbyteArray JNICALL Java_sun_jvm_hotspot_debugger_windbg_WindbgDebugger IDebugDataSpaces* ptrIDebugDataSpaces = (IDebugDataSpaces*) env->GetLongField(obj, ptrIDebugDataSpaces_ID); - CHECK_EXCEPTION_(0); + if (env->ExceptionOccurred()) { + env->ReleaseByteArrayElements(byteArray, bytePtr, JNI_ABORT); + return 0; + } ULONG bytesRead; if (ptrIDebugDataSpaces->ReadVirtual((ULONG64) address, (PVOID) bytePtr, (ULONG)numBytes, &bytesRead) != S_OK) { - THROW_NEW_DEBUGGER_EXCEPTION_("Windbg Error: ReadVirtual failed!", 0); - } - - if (bytesRead != numBytes) { + env->ReleaseByteArrayElements(byteArray, bytePtr, JNI_ABORT); + throwNewDebuggerException(env, "Windbg Error: ReadVirtual failed!"); return 0; } + if (bytesRead != numBytes) { + env->ReleaseByteArrayElements(byteArray, bytePtr, JNI_ABORT); + return 0; + } env->ReleaseByteArrayElements(byteArray, bytePtr, 0); + CHECK_EXCEPTION_(0); return byteArray; From 206ea259ecdea652c35f50dcf07a954c09a75421 Mon Sep 17 00:00:00 2001 From: Christoph Langer Date: Wed, 19 Dec 2018 10:36:16 +0000 Subject: [PATCH 073/174] 8215472: (zipfs) Cleanups in implementation classes of jdk.zipfs and tests Reviewed-by: redestad, lancea --- .../classes/jdk/nio/zipfs/JarFileSystem.java | 1 - .../jdk/nio/zipfs/JarFileSystemProvider.java | 18 ++--- .../share/classes/jdk/nio/zipfs/ZipCoder.java | 7 +- .../classes/jdk/nio/zipfs/ZipConstants.java | 4 +- .../jdk/nio/zipfs/ZipDirectoryStream.java | 12 ++- .../jdk/nio/zipfs/ZipFileAttributeView.java | 23 +++--- .../jdk/nio/zipfs/ZipFileAttributes.java | 6 +- .../classes/jdk/nio/zipfs/ZipFileStore.java | 15 ++-- .../classes/jdk/nio/zipfs/ZipFileSystem.java | 73 ++++++++++--------- .../jdk/nio/zipfs/ZipFileSystemProvider.java | 28 +++---- .../share/classes/jdk/nio/zipfs/ZipInfo.java | 10 ++- .../share/classes/jdk/nio/zipfs/ZipPath.java | 35 ++++++--- .../share/classes/jdk/nio/zipfs/ZipUtils.java | 7 +- test/jdk/java/util/zip/zip.java | 31 ++++---- 14 files changed, 134 insertions(+), 136 deletions(-) diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java index 356b4e4440c..ec138e471f3 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java @@ -48,7 +48,6 @@ import java.util.jar.Manifest; * * @author Steve Drach */ - class JarFileSystem extends ZipFileSystem { private Function lookup; diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java index e6495b157da..4df2938860a 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,21 +25,13 @@ package jdk.nio.zipfs; -import java.nio.file.*; -import java.nio.file.spi.*; -import java.nio.file.attribute.*; -import java.nio.file.spi.FileSystemProvider; - import java.net.URI; -import java.io.IOException; import java.net.URISyntaxException; -import java.nio.channels.FileChannel; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.nio.file.Paths; -class JarFileSystemProvider extends ZipFileSystemProvider -{ +class JarFileSystemProvider extends ZipFileSystemProvider { @Override public String getScheme() { diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipCoder.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipCoder.java index ea5ca6a4f63..9589b460a41 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipCoder.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipCoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -34,15 +34,14 @@ import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.Arrays; -import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; /** * Utility class for zipfile name and comment decoding and encoding * - * @author Xueming Shen + * @author Xueming Shen */ - class ZipCoder { static class UTF8 extends ZipCoder { diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java index 45eb4567f49..5023220c185 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,10 +26,8 @@ package jdk.nio.zipfs; /** - * * @author Xueming Shen */ - class ZipConstants { /* * Compression methods diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java index a4875d415a7..ae1909a85f4 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,19 +25,18 @@ package jdk.nio.zipfs; -import java.nio.file.DirectoryStream; +import java.io.IOException; import java.nio.file.ClosedDirectoryStreamException; +import java.nio.file.DirectoryStream; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.util.Iterator; import java.util.NoSuchElementException; -import java.io.IOException; /** * - * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal + * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal */ - class ZipDirectoryStream implements DirectoryStream { private final ZipFileSystem zipfs; @@ -70,8 +69,8 @@ class ZipDirectoryStream implements DirectoryStream { } catch (IOException e) { throw new IllegalStateException(e); } + return new Iterator() { - private Path next; @Override public boolean hasNext() { if (isClosed) @@ -97,5 +96,4 @@ class ZipDirectoryStream implements DirectoryStream { public synchronized void close() throws IOException { isClosed = true; } - } diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java index 6d479f02a0e..cedde307ad4 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,17 +25,17 @@ package jdk.nio.zipfs; -import java.nio.file.attribute.*; import java.io.IOException; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.FileAttributeView; +import java.nio.file.attribute.FileTime; import java.util.LinkedHashMap; import java.util.Map; -/* - * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal +/** + * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal */ - -class ZipFileAttributeView implements BasicFileAttributeView -{ +class ZipFileAttributeView implements BasicFileAttributeView { private static enum AttrID { size, creationTime, @@ -85,8 +85,7 @@ class ZipFileAttributeView implements BasicFileAttributeView return isZipView ? "zip" : "basic"; } - public ZipFileAttributes readAttributes() throws IOException - { + public ZipFileAttributes readAttributes() throws IOException { return path.getAttributes(); } @@ -104,11 +103,11 @@ class ZipFileAttributeView implements BasicFileAttributeView { try { if (AttrID.valueOf(attribute) == AttrID.lastModifiedTime) - setTimes ((FileTime)value, null, null); + setTimes((FileTime)value, null, null); if (AttrID.valueOf(attribute) == AttrID.lastAccessTime) - setTimes (null, (FileTime)value, null); + setTimes(null, (FileTime)value, null); if (AttrID.valueOf(attribute) == AttrID.creationTime) - setTimes (null, null, (FileTime)value); + setTimes(null, null, (FileTime)value); return; } catch (IllegalArgumentException x) {} throw new UnsupportedOperationException("'" + attribute + diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributes.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributes.java index 5cc6ef3b951..f5e465b96c5 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributes.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -28,10 +28,10 @@ package jdk.nio.zipfs; import java.nio.file.attribute.BasicFileAttributes; /** + * The attributes of a file stored in a zip file. * - * @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal + * @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal */ - interface ZipFileAttributes extends BasicFileAttributes { public long compressedSize(); public long crc(); diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileStore.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileStore.java index 9f789709a02..531c667a65d 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileStore.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,21 +26,17 @@ package jdk.nio.zipfs; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.FileStore; import java.nio.file.FileSystems; +import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileStoreAttributeView; -import java.nio.file.attribute.BasicFileAttributeView; -import java.util.Formatter; -/* - * - * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal +/** + * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal */ - class ZipFileStore extends FileStore { private final ZipFileSystem zfs; @@ -76,7 +72,6 @@ class ZipFileStore extends FileStore { } @Override - @SuppressWarnings("unchecked") public V getFileStoreAttributeView(Class type) { if (type == null) throw new NullPointerException(); diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java index 868277b7b02..c3f3bc9ed4c 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -29,17 +29,22 @@ import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; -import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; -import java.nio.channels.*; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.channels.WritableByteChannel; import java.nio.file.*; -import java.nio.file.attribute.*; -import java.nio.file.spi.*; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileTime; +import java.nio.file.attribute.UserPrincipalLookupService; +import java.nio.file.spi.FileSystemProvider; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; @@ -49,25 +54,30 @@ import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Pattern; import java.util.zip.CRC32; -import java.util.zip.Inflater; import java.util.zip.Deflater; -import java.util.zip.InflaterInputStream; import java.util.zip.DeflaterOutputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; import java.util.zip.ZipException; -import static java.lang.Boolean.*; + +import static java.lang.Boolean.TRUE; +import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static java.nio.file.StandardOpenOption.APPEND; +import static java.nio.file.StandardOpenOption.CREATE; +import static java.nio.file.StandardOpenOption.CREATE_NEW; +import static java.nio.file.StandardOpenOption.READ; +import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; +import static java.nio.file.StandardOpenOption.WRITE; import static jdk.nio.zipfs.ZipConstants.*; import static jdk.nio.zipfs.ZipUtils.*; -import static java.nio.file.StandardOpenOption.*; -import static java.nio.file.StandardCopyOption.*; /** * A FileSystem built on a zip file * * @author Xueming Shen */ - class ZipFileSystem extends FileSystem { - private final ZipFileSystemProvider provider; private final Path zfpath; final ZipCoder zc; @@ -79,15 +89,15 @@ class ZipFileSystem extends FileSystem { private final boolean useTempFile; // use a temp file for newOS, default // is to use BAOS for better performance private static final boolean isWindows = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("os.name") - .startsWith("Windows")); + (PrivilegedAction)() -> System.getProperty("os.name") + .startsWith("Windows")); private final boolean forceEnd64; private final int defaultMethod; // METHOD_STORED if "noCompression=true" // METHOD_DEFLATED otherwise ZipFileSystem(ZipFileSystemProvider provider, Path zfpath, - Map env) throws IOException + Map env) throws IOException { // default encoding for name/comment String nameEncoding = env.containsKey("encoding") ? @@ -269,12 +279,12 @@ class ZipFileSystem extends FileSystem { } if (!streams.isEmpty()) { // unlock and close all remaining streams Set copy = new HashSet<>(streams); - for (InputStream is: copy) + for (InputStream is : copy) is.close(); } beginWrite(); // lock and sync try { - AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + AccessController.doPrivileged((PrivilegedExceptionAction)() -> { sync(); return null; }); ch.close(); // close the ch just in case no update @@ -296,7 +306,7 @@ class ZipFileSystem extends FileSystem { IOException ioe = null; synchronized (tmppaths) { - for (Path p: tmppaths) { + for (Path p : tmppaths) { try { AccessController.doPrivileged( (PrivilegedExceptionAction)() -> Files.deleteIfExists(p)); @@ -521,7 +531,7 @@ class ZipFileSystem extends FileSystem { boolean hasCreate = false; boolean hasAppend = false; boolean hasTruncate = false; - for (OpenOption opt: options) { + for (OpenOption opt : options) { if (opt == READ) throw new IllegalArgumentException("READ not allowed"); if (opt == CREATE_NEW) @@ -1455,6 +1465,7 @@ class ZipFileSystem extends FileSystem { e.size = def.getBytesRead(); e.csize = def.getBytesWritten(); e.crc = crc.getValue(); + releaseDeflater(def); } } @@ -1477,7 +1488,7 @@ class ZipFileSystem extends FileSystem { // TBD: wrap to hook close() // streams.add(eis); return eis; - } else { // untouced CEN or COPY + } else { // untouched CEN or COPY eis = new EntryInputStream(e, ch); } if (e.method == METHOD_DEFLATED) { @@ -1539,14 +1550,12 @@ class ZipFileSystem extends FileSystem { // point to a new channel after sync() private long pos; // current position within entry data protected long rem; // number of remaining bytes within entry - protected final long size; // uncompressed size of this entry EntryInputStream(Entry e, SeekableByteChannel zfch) throws IOException { this.zfch = zfch; rem = e.csize; - size = e.size; pos = e.locoff; if (pos == -1) { Entry e2 = getEntry(e.name); @@ -1613,10 +1622,6 @@ class ZipFileSystem extends FileSystem { return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem; } - public long size() { - return size; - } - public void close() { rem = 0; streams.remove(this); @@ -1672,7 +1677,7 @@ class ZipFileSystem extends FileSystem { // List of available Deflater objects for compression private final List deflaters = new ArrayList<>(); - // Gets an deflater from the list of available deflaters or allocates + // Gets a deflater from the list of available deflaters or allocates // a new one. private Deflater getDeflater() { synchronized (deflaters) { @@ -1985,9 +1990,7 @@ class ZipFileSystem extends FileSystem { return this; } - int writeCEN(OutputStream os) throws IOException - { - int written = CENHDR; + int writeCEN(OutputStream os) throws IOException { int version0 = version(); long csize0 = csize; long size0 = size; @@ -2101,9 +2104,7 @@ class ZipFileSystem extends FileSystem { ///////////////////// LOC ////////////////////// int writeLOC(OutputStream os) throws IOException { - writeInt(os, LOCSIG); // LOC header signature - int version = version(); - + int version0 = version(); byte[] zname = isdir ? toDirectoryPath(name) : name; int nlen = (zname != null) ? zname.length - 1 : 0; // [0] is slash int elen = (extra != null) ? extra.length : 0; @@ -2112,8 +2113,9 @@ class ZipFileSystem extends FileSystem { int elen64 = 0; int elenEXTT = 0; int elenNTFS = 0; + writeInt(os, LOCSIG); // LOC header signature if ((flag & FLAG_DATADESCR) != 0) { - writeShort(os, version()); // version needed to extract + writeShort(os, version0); // version needed to extract writeShort(os, flag); // general purpose bit flag writeShort(os, method); // compression method // last modification time @@ -2128,7 +2130,7 @@ class ZipFileSystem extends FileSystem { elen64 = 20; //headid(2) + size(2) + size(8) + csize(8) writeShort(os, 45); // ver 4.5 for zip64 } else { - writeShort(os, version()); // version needed to extract + writeShort(os, version0); // version needed to extract } writeShort(os, flag); // general purpose bit flag writeShort(os, method); // compression method @@ -2430,7 +2432,6 @@ class ZipFileSystem extends FileSystem { // structure. // A possible solution is to build the node tree ourself as // implemented below. - private IndexNode root; // default time stamp for pseudo entries private long zfsDefaultTimeStamp = System.currentTimeMillis(); diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java index fbac86510ad..1364e6b9530 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java @@ -25,28 +25,31 @@ package jdk.nio.zipfs; -import java.io.*; -import java.nio.channels.*; -import java.nio.file.*; -import java.nio.file.DirectoryStream.Filter; -import java.nio.file.attribute.*; -import java.nio.file.spi.FileSystemProvider; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.*; +import java.nio.file.DirectoryStream.Filter; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileAttributeView; +import java.nio.file.spi.FileSystemProvider; import java.util.HashMap; import java.util.Map; import java.util.Set; -import java.util.zip.ZipException; import java.util.concurrent.ExecutorService; +import java.util.zip.ZipException; -/* - * - * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal +/** + * @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal */ - public class ZipFileSystemProvider extends FileSystemProvider { - private final Map filesystems = new HashMap<>(); public ZipFileSystemProvider() {} @@ -202,7 +205,6 @@ public class ZipFileSystemProvider extends FileSystemProvider { } @Override - @SuppressWarnings("unchecked") public V getFileAttributeView(Path path, Class type, LinkOption... options) { diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipInfo.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipInfo.java index 05b08a3d443..e23943afe7b 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipInfo.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -28,15 +28,17 @@ package jdk.nio.zipfs; import java.nio.file.Paths; import java.util.Collections; import java.util.Map; + import static jdk.nio.zipfs.ZipConstants.*; -import static jdk.nio.zipfs.ZipUtils.*; +import static jdk.nio.zipfs.ZipUtils.dosToJavaTime; +import static jdk.nio.zipfs.ZipUtils.unixToJavaTime; +import static jdk.nio.zipfs.ZipUtils.winToJavaTime; /** * Print all loc and cen headers of the ZIP file * - * @author Xueming Shen + * @author Xueming Shen */ - public class ZipInfo { public static void main(String[] args) throws Throwable { diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipPath.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipPath.java index 2c72362a15b..acdd666acbd 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipPath.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,22 +25,36 @@ package jdk.nio.zipfs; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URI; -import java.nio.channels.*; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; import java.nio.file.*; import java.nio.file.DirectoryStream.Filter; -import java.nio.file.attribute.*; -import java.util.*; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileTime; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Set; + import static java.nio.charset.StandardCharsets.UTF_8; -import static java.nio.file.StandardOpenOption.*; -import static java.nio.file.StandardCopyOption.*; +import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static java.nio.file.StandardOpenOption.CREATE; +import static java.nio.file.StandardOpenOption.READ; +import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; +import static java.nio.file.StandardOpenOption.WRITE; /** - * - * @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal + * @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal */ - final class ZipPath implements Path { private final ZipFileSystem zfs; @@ -522,7 +536,6 @@ final class ZipPath implements Path { private byte[] normalize(String path, int off, int len) { StringBuilder to = new StringBuilder(len); to.append(path, 0, off); - int m = off; char prevC = 0; while (off < len) { char c = path.charAt(off++); diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipUtils.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipUtils.java index d03dd71d425..4e4b9479fd9 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipUtils.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -33,14 +33,12 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.Date; -import java.util.regex.PatternSyntaxException; import java.util.concurrent.TimeUnit; +import java.util.regex.PatternSyntaxException; /** - * * @author Xueming Shen */ - class ZipUtils { /* @@ -155,7 +153,6 @@ class ZipUtils { ldt.getSecond() >> 1) & 0xffffffffL; } - // used to adjust values between Windows and java epoch private static final long WINDOWS_EPOCH_IN_MICROSECONDS = -11644473600000000L; public static final long winToJavaTime(long wtime) { diff --git a/test/jdk/java/util/zip/zip.java b/test/jdk/java/util/zip/zip.java index 41c49783c8e..c21d70b818a 100644 --- a/test/jdk/java/util/zip/zip.java +++ b/test/jdk/java/util/zip/zip.java @@ -23,9 +23,14 @@ import java.io.*; import java.nio.charset.Charset; -import java.util.*; -import java.util.zip.*; import java.text.MessageFormat; +import java.util.*; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; /** * A stripped-down version of Jar tool with a "-encoding" option to @@ -39,9 +44,9 @@ public class zip { String[] files; Charset cs = Charset.forName("UTF-8"); - Map entryMap = new HashMap(); - Set entries = new LinkedHashSet(); - List paths = new ArrayList(); + Map entryMap = new HashMap<>(); + Set entries = new LinkedHashSet<>(); + List paths = new ArrayList<>(); CRC32 crc32 = new CRC32(); /* @@ -330,15 +335,13 @@ public class zip { } } - boolean update(InputStream in, OutputStream out) throws IOException - { + boolean update(InputStream in, OutputStream out) throws IOException { try (ZipInputStream zis = new ZipInputStream(in, cs); ZipOutputStream zos = new ZipOutputStream(out, cs)) { ZipEntry e = null; byte[] buf = new byte[1024]; int n = 0; - boolean updateOk = true; // put the old entries first, replace if necessary while ((e = zis.getNextEntry()) != null) { @@ -367,11 +370,11 @@ public class zip { } // add the remaining new files - for (File f: entries) { + for (File f : entries) { addFile(zos, f); } } - return updateOk; + return true; } private String entryName(String name) { @@ -479,6 +482,8 @@ public class zip { Set newDirSet() { return new HashSet() { + private static final long serialVersionUID = 4547977575248028254L; + public boolean add(ZipEntry e) { return (e == null || super.add(e)); }}; @@ -520,7 +525,6 @@ public class zip { Enumeration zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry e = zes.nextElement(); - InputStream is; if (files == null) { dirs.add(extractFile(zf.getInputStream(e), e)); } else { @@ -533,8 +537,8 @@ public class zip { } } } + updateLastModifiedTime(dirs); } - updateLastModifiedTime(dirs); } ZipEntry extractFile(InputStream is, ZipEntry e) throws IOException { @@ -727,7 +731,7 @@ public class zip { st.commentChar('#'); st.quoteChar('"'); st.quoteChar('\''); - while (st.nextToken() != st.TT_EOF) { + while (st.nextToken() != StreamTokenizer.TT_EOF) { args.add(st.sval); } r.close(); @@ -738,4 +742,3 @@ public class zip { System.exit(z.run(args) ? 0 : 1); } } - From d6738d66006fb513f7843bee670d9b808fa8ac6c Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Wed, 19 Dec 2018 11:48:34 +0100 Subject: [PATCH 074/174] 8213402: [Testbug] java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest creates an invalid nest relationship The failing tests are refactored to make the custom logger finder class a top-level class. Reviewed-by: dholmes, mchung --- .../BaseDefaultLoggerFinderTest.java | 53 +-- .../BaseLoggerFinder.java | 68 ++++ .../CustomSystemClassLoader.java | 24 +- .../services/java.lang.System$LoggerFinder | 2 +- .../BaseLoggerBridgeTest.java | 27 +- .../BaseLoggerFinder.java | 47 +++ .../CustomSystemClassLoader.java | 16 +- .../services/java.lang.System$LoggerFinder | 2 +- .../BaseLoggerFinder.java | 50 +++ .../BasePlatformLoggerTest.java | 23 +- .../CustomSystemClassLoader.java | 14 +- .../services/java.lang.System$LoggerFinder | 2 +- .../CustomSystemClassLoader.java | 57 +-- .../LoggerBridgeTest/LogProducerFinder.java | 52 +++ .../LoggerBridgeTest/LoggerBridgeTest.java | 381 +++++++++--------- .../services/java.lang.System$LoggerFinder | 2 +- .../BaseLoggerFinder.java | 62 +++ .../BaseLoggerFinder2.java | 39 ++ .../CustomSystemClassLoader.java | 24 +- .../LoggerFinderLoaderTest.java | 57 +-- .../services/java.lang.System$LoggerFinder | 4 +- .../CustomSystemClassLoader.java | 12 +- .../LogProducerFinder.java | 59 +++ .../services/java.lang.System$LoggerFinder | 2 +- .../PlatformLoggerBridgeTest.java | 380 +++++++++-------- 25 files changed, 841 insertions(+), 618 deletions(-) create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseLoggerFinder.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerFinder.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BaseLoggerFinder.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LogProducerFinder.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder2.java create mode 100644 test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/LogProducerFinder.java diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseDefaultLoggerFinderTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseDefaultLoggerFinderTest.java index 57c48daf484..abb71e79d66 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseDefaultLoggerFinderTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseDefaultLoggerFinderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ import sun.util.logging.PlatformLogger; * implementation. * @modules java.base/sun.util.logging * java.base/jdk.internal.logger - * @build AccessSystemLogger BaseDefaultLoggerFinderTest CustomSystemClassLoader + * @build AccessSystemLogger BaseDefaultLoggerFinderTest CustomSystemClassLoader BaseLoggerFinder * @run driver AccessSystemLogger * @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader BaseDefaultLoggerFinderTest NOSECURITY * @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader BaseDefaultLoggerFinderTest NOPERMISSIONS @@ -97,7 +97,7 @@ public class BaseDefaultLoggerFinderTest { static { try { providerClass = new Class[] { - ClassLoader.getSystemClassLoader().loadClass("BaseDefaultLoggerFinderTest$BaseLoggerFinder"), + ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder"), }; } catch (ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); @@ -120,43 +120,6 @@ public class BaseDefaultLoggerFinderTest { PlatformLogger.Bridge asPlatformLoggerBridge(Logger logger); } - public static class BaseLoggerFinder extends DefaultLoggerFinder implements TestLoggerFinder { - - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - public BaseLoggerFinder() { - if (fails.get()) { - throw new RuntimeException("Simulate exception while loading provider"); - } - } - - @Override - public void setLevel(Logger logger, Level level, Module caller) { - PrivilegedAction pa = () -> { - setLevel(logger, PlatformLogger.toPlatformLevel(level), caller); - return null; - }; - AccessController.doPrivileged(pa); - } - - @Override - public void setLevel(Logger logger, PlatformLogger.Level level, Module caller) { - PrivilegedAction pa = () -> demandLoggerFor(logger.getName(), caller); - Logger impl = AccessController.doPrivileged(pa); - SimpleConsoleLogger.class.cast(impl) - .getLoggerConfiguration() - .setPlatformLevel(level); - } - - @Override - public PlatformLogger.Bridge asPlatformLoggerBridge(Logger logger) { - PrivilegedAction pa = () -> - PlatformLogger.Bridge.convert(logger); - return AccessController.doPrivileged(pa); - } - - } - public static class MyBundle extends ResourceBundle { final ConcurrentHashMap map = new ConcurrentHashMap<>(); @@ -477,7 +440,7 @@ public class BaseDefaultLoggerFinderTest { System.out.println("\n*** Without Security Manager\n"); System.out.println(TestLoggerFinder.conf.get()); provider = getLoggerFinder(expectedClass); - if (!provider.getClass().getName().equals("BaseDefaultLoggerFinderTest$BaseLoggerFinder")) { + if (!provider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + provider.getClass().getName()); } test(provider, true); @@ -498,7 +461,7 @@ public class BaseDefaultLoggerFinderTest { try { allowControl.get().set(true); provider = getLoggerFinder(expectedClass); - if (!provider.getClass().getName().equals("BaseDefaultLoggerFinderTest$BaseLoggerFinder")) { + if (!provider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + provider.getClass().getName()); } } finally { @@ -516,7 +479,7 @@ public class BaseDefaultLoggerFinderTest { try { allowControl.get().set(true); provider = getLoggerFinder(expectedClass); - if (!provider.getClass().getName().equals("BaseDefaultLoggerFinderTest$BaseLoggerFinder")) { + if (!provider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + provider.getClass().getName()); } test(provider, true); @@ -532,7 +495,7 @@ public class BaseDefaultLoggerFinderTest { try { allowControl.get().set(true); provider = getLoggerFinder(expectedClass); - if (!provider.getClass().getName().equals("BaseDefaultLoggerFinderTest$BaseLoggerFinder")) { + if (!provider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + provider.getClass().getName()); } test(provider, CustomLoggerWrapper::new, true); @@ -550,7 +513,7 @@ public class BaseDefaultLoggerFinderTest { try { allowControl.get().set(true); provider = getLoggerFinder(expectedClass); - if (!provider.getClass().getName().equals("BaseDefaultLoggerFinderTest$BaseLoggerFinder")) { + if (!provider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + provider.getClass().getName()); } test(provider, ReflectionLoggerWrapper::new, true); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseLoggerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseLoggerFinder.java new file mode 100644 index 00000000000..72357619cf8 --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/BaseLoggerFinder.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.internal.logger.DefaultLoggerFinder; +import jdk.internal.logger.SimpleConsoleLogger; +import sun.util.logging.PlatformLogger; + +import java.lang.System.Logger; +import java.lang.System.Logger.Level; +import java.security.AccessController; +import java.security.PrivilegedAction; + +public class BaseLoggerFinder extends DefaultLoggerFinder + implements BaseDefaultLoggerFinderTest.TestLoggerFinder { + + public BaseLoggerFinder() { + if (fails.get()) { + throw new RuntimeException("Simulate exception while loading provider"); + } + } + + @Override + public void setLevel(Logger logger, Level level, Module caller) { + PrivilegedAction pa = () -> { + setLevel(logger, PlatformLogger.toPlatformLevel(level), caller); + return null; + }; + AccessController.doPrivileged(pa); + } + + @Override + public void setLevel(Logger logger, PlatformLogger.Level level, Module caller) { + PrivilegedAction pa = () -> demandLoggerFor(logger.getName(), caller); + Logger impl = AccessController.doPrivileged(pa); + SimpleConsoleLogger.class.cast(impl) + .getLoggerConfiguration() + .setPlatformLevel(level); + } + + @Override + public PlatformLogger.Bridge asPlatformLoggerBridge(Logger logger) { + PrivilegedAction pa = () -> + PlatformLogger.Bridge.convert(logger); + return AccessController.doPrivileged(pa); + } + +} + diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/CustomSystemClassLoader.java index c948b0b58b1..05efeee406d 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/CustomSystemClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** @@ -48,8 +49,8 @@ public class CustomSystemClassLoader extends ClassLoader { final List finderClassNames = - Arrays.asList("BaseDefaultLoggerFinderTest$BaseLoggerFinder"); - final Map> finderClasses = new HashMap<>(); + Arrays.asList("BaseLoggerFinder"); + final Map> finderClasses = new ConcurrentHashMap<>(); Class testLoggerFinderClass; public CustomSystemClassLoader() { @@ -61,9 +62,14 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + Class finderClass = finderClasses.get(name); + if (finderClass != null) return finderClass; + final Object obj = getClassLoadingLock(name); synchronized(obj) { - if (finderClasses.get(name) != null) return finderClasses.get(name); + finderClasses.get(name); + if (finderClass != null) return finderClass; + if (testLoggerFinderClass == null) { // Hack: we load testLoggerFinderClass to get its code source. // we can't use this.getClass() since we are in the boot. @@ -76,7 +82,7 @@ public class CustomSystemClassLoader extends ClassLoader { byte[] b = Files.readAllBytes(file.toPath()); Permissions perms = new Permissions(); perms.add(new AllPermission()); - Class finderClass = defineClass( + finderClass = defineClass( name, b, 0, b.length, new ProtectionDomain( this.getClass().getProtectionDomain().getCodeSource(), perms)); @@ -94,9 +100,13 @@ public class CustomSystemClassLoader extends ClassLoader { } } + private static boolean matches(String prefix, String name) { + return prefix.equals(name) || name.startsWith(prefix + "$"); + } + @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (finderClassNames.contains(name)) { + if (finderClassNames.stream().anyMatch(n -> matches(n, name))) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); @@ -108,7 +118,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { - if (finderClassNames.contains(name)) { + if (finderClassNames.stream().anyMatch(n -> matches(n, name))) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/META-INF/services/java.lang.System$LoggerFinder index 843cae617f1..fecd6622497 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseDefaultLoggerFinderTest/META-INF/services/java.lang.System$LoggerFinder @@ -1 +1 @@ -BaseDefaultLoggerFinderTest$BaseLoggerFinder +BaseLoggerFinder diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerBridgeTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerBridgeTest.java index 98ecc69e3d1..f179f35838e 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerBridgeTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerBridgeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ import java.util.stream.Stream; * Tests a naive implementation of System.Logger, and in particular * the default mapping provided by PlatformLogger.Bridge. * @modules java.base/sun.util.logging java.base/jdk.internal.logger - * @build CustomSystemClassLoader BaseLoggerBridgeTest + * @build CustomSystemClassLoader BaseLoggerFinder BaseLoggerBridgeTest * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BaseLoggerBridgeTest NOSECURITY * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BaseLoggerBridgeTest NOPERMISSIONS * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BaseLoggerBridgeTest WITHPERMISSIONS @@ -94,7 +94,7 @@ public class BaseLoggerBridgeTest { static final Class providerClass; static { try { - providerClass = ClassLoader.getSystemClassLoader().loadClass("BaseLoggerBridgeTest$BaseLoggerFinder"); + providerClass = ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder"); } catch (ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); } @@ -336,33 +336,12 @@ public class BaseLoggerBridgeTest { log(LogEvent.of(isLoggable(level), name, level, thrown, msgSupplier)); } - - } public Logger getLogger(String name, Module caller); public Logger getLocalizedLogger(String name, ResourceBundle bundle, Module caller); } - public static class BaseLoggerFinder extends LoggerFinder implements TestLoggerFinder { - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - @Override - public Logger getLogger(String name, Module caller) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - PrivilegedAction pa = () -> caller.getClassLoader(); - ClassLoader callerLoader = AccessController.doPrivileged(pa); - if (callerLoader == null) { - return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } else { - return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } - } - } - static PlatformLogger.Bridge convert(Logger logger) { boolean old = allowAll.get().get(); allowAccess.get().set(true); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerFinder.java new file mode 100644 index 00000000000..09a449f9f29 --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/BaseLoggerFinder.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.lang.System.LoggerFinder; +import java.lang.System.Logger; + +public class BaseLoggerFinder extends LoggerFinder + implements BaseLoggerBridgeTest.TestLoggerFinder { + static final RuntimePermission LOGGERFINDER_PERMISSION = + new RuntimePermission("loggerFinder"); + + @Override + public Logger getLogger(String name, Module caller) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(LOGGERFINDER_PERMISSION); + } + PrivilegedAction pa = () -> caller.getClassLoader(); + ClassLoader callerLoader = AccessController.doPrivileged(pa); + if (callerLoader == null) { + return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); + } else { + return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); + } + } +} diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/CustomSystemClassLoader.java index f903b43dba2..d38618e2d9b 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/CustomSystemClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,7 @@ import java.nio.file.Files; import java.security.AllPermission; import java.security.Permissions; import java.security.ProtectionDomain; - +import java.util.concurrent.ConcurrentHashMap; /** * A custom ClassLoader to load the concrete LoggerFinder class @@ -39,7 +39,7 @@ import java.security.ProtectionDomain; public class CustomSystemClassLoader extends ClassLoader { - Class finderClass = null; + private final ConcurrentHashMap> classes = new ConcurrentHashMap<>(); public CustomSystemClassLoader() { super(); @@ -50,8 +50,13 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + Class finderClass = classes.get(name); + if (finderClass != null) return finderClass; + final Object obj = getClassLoadingLock(name); + synchronized(obj) { + finderClass = classes.get(name); if (finderClass != null) return finderClass; URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); @@ -66,6 +71,7 @@ public class CustomSystemClassLoader extends ClassLoader { this.getClass().getProtectionDomain().getCodeSource(), perms)); System.out.println("Loaded " + name); + classes.put(name, finderClass); return finderClass; } catch (Throwable ex) { ex.printStackTrace(); @@ -80,7 +86,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (name.endsWith("$BaseLoggerFinder")) { + if (name.equals("BaseLoggerFinder") || name.startsWith("BaseLoggerFinder$")) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); @@ -92,7 +98,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { - if (name.endsWith("$BaseLoggerFinder")) { + if (name.equals("BaseLoggerFinder") || name.startsWith("BaseLoggerFinder$")) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder index 4fc04019eb7..fecd6622497 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BaseLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder @@ -1 +1 @@ -BaseLoggerBridgeTest$BaseLoggerFinder +BaseLoggerFinder diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BaseLoggerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BaseLoggerFinder.java new file mode 100644 index 00000000000..affb060d9ba --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BaseLoggerFinder.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.lang.System.Logger; +import java.lang.System.LoggerFinder; +import java.security.AccessController; +import java.security.PrivilegedAction; + +public class BaseLoggerFinder extends LoggerFinder + implements BasePlatformLoggerTest.TestLoggerFinder { + + public static final RuntimePermission LOGGERFINDER_PERMISSION = + new RuntimePermission("loggerFinder"); + + @Override + public Logger getLogger(String name, Module caller) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(LOGGERFINDER_PERMISSION); + } + PrivilegedAction pa = () -> caller.getClassLoader(); + ClassLoader callerLoader = AccessController.doPrivileged(pa); + if (callerLoader == null) { + return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); + } else { + return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); + } + } +} + diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BasePlatformLoggerTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BasePlatformLoggerTest.java index af15a51eba3..a1de8208661 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BasePlatformLoggerTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/BasePlatformLoggerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ import sun.util.logging.PlatformLogger; * Tests a naive implementation of System.Logger, and in particular * the default mapping provided by PlatformLogger. * @modules java.base/sun.util.logging - * @build CustomSystemClassLoader BasePlatformLoggerTest + * @build CustomSystemClassLoader BaseLoggerFinder BasePlatformLoggerTest * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BasePlatformLoggerTest NOSECURITY * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BasePlatformLoggerTest NOPERMISSIONS * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader BasePlatformLoggerTest WITHPERMISSIONS @@ -90,7 +90,7 @@ public class BasePlatformLoggerTest { static final Class providerClass; static { try { - providerClass = ClassLoader.getSystemClassLoader().loadClass("BasePlatformLoggerTest$BaseLoggerFinder"); + providerClass = ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder"); } catch (ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); } @@ -330,23 +330,6 @@ public class BasePlatformLoggerTest { public Logger getLogger(String name, Module caller); } - public static class BaseLoggerFinder extends LoggerFinder implements TestLoggerFinder { - @Override - public Logger getLogger(String name, Module caller) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - PrivilegedAction pa = () -> caller.getClassLoader(); - ClassLoader callerLoader = AccessController.doPrivileged(pa); - if (callerLoader == null) { - return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } else { - return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } - } - } - static PlatformLogger getPlatformLogger(String name) { boolean old = allowAccess.get().get(); allowAccess.get().set(true); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/CustomSystemClassLoader.java index f903b43dba2..56f0c38f00e 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/CustomSystemClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.nio.file.Files; import java.security.AllPermission; import java.security.Permissions; import java.security.ProtectionDomain; +import java.util.concurrent.ConcurrentHashMap; /** @@ -39,7 +40,7 @@ import java.security.ProtectionDomain; public class CustomSystemClassLoader extends ClassLoader { - Class finderClass = null; + private final ConcurrentHashMap> classes = new ConcurrentHashMap<>(); public CustomSystemClassLoader() { super(); @@ -50,8 +51,12 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + Class finderClass = classes.get(name); + if (finderClass != null) return finderClass; + final Object obj = getClassLoadingLock(name); synchronized(obj) { + finderClass = classes.get(name); if (finderClass != null) return finderClass; URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); @@ -66,6 +71,7 @@ public class CustomSystemClassLoader extends ClassLoader { this.getClass().getProtectionDomain().getCodeSource(), perms)); System.out.println("Loaded " + name); + classes.put(name, finderClass); return finderClass; } catch (Throwable ex) { ex.printStackTrace(); @@ -80,7 +86,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (name.endsWith("$BaseLoggerFinder")) { + if (name.endsWith("BaseLoggerFinder") || name.startsWith("BaseLoggerFinder$")) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); @@ -92,7 +98,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { - if (name.endsWith("$BaseLoggerFinder")) { + if (name.endsWith("BaseLoggerFinder") || name.startsWith("BaseLoggerFinder$")) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/META-INF/services/java.lang.System$LoggerFinder index 7ce6e966935..fecd6622497 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/BasePlatformLoggerTest/META-INF/services/java.lang.System$LoggerFinder @@ -1 +1 @@ -BasePlatformLoggerTest$BaseLoggerFinder +BaseLoggerFinder diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/CustomSystemClassLoader.java index 0c68ff89e93..a68fd9daa87 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/CustomSystemClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.nio.file.Files; import java.security.AllPermission; import java.security.Permissions; import java.security.ProtectionDomain; +import java.util.concurrent.ConcurrentHashMap; /** @@ -39,8 +40,7 @@ import java.security.ProtectionDomain; public class CustomSystemClassLoader extends ClassLoader { - Class loggerFinderClass = null; -// Class loggerImplClass = null; + private final ConcurrentHashMap> classes = new ConcurrentHashMap<>(); public CustomSystemClassLoader() { super(); @@ -51,8 +51,13 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + + Class loggerFinderClass = classes.get(name); + if (loggerFinderClass != null) return loggerFinderClass; + final Object obj = getClassLoadingLock(name); synchronized(obj) { + loggerFinderClass = classes.get(name); if (loggerFinderClass != null) return loggerFinderClass; URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); @@ -66,6 +71,7 @@ public class CustomSystemClassLoader extends ClassLoader { name, b, 0, b.length, new ProtectionDomain( this.getClass().getProtectionDomain().getCodeSource(), perms)); + classes.put(name, loggerFinderClass); System.out.println("Loaded " + name); return loggerFinderClass; } catch (Throwable ex) { @@ -78,61 +84,22 @@ public class CustomSystemClassLoader extends ClassLoader { } } } -// private Class defineLoggerImplClass(String name) -// throws ClassNotFoundException { -// final Object obj = getClassLoadingLock(name); -// synchronized(obj) { -// if (loggerImplClass != null) return loggerImplClass; -// -// URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); -// File file = new File(url.getPath(), name+".class"); -// if (file.canRead()) { -// try { -// byte[] b = Files.readAllBytes(file.toPath()); -// Permissions perms = new Permissions(); -// perms.add(new AllPermission()); -// loggerImplClass = defineClass( -// name, b, 0, b.length, new ProtectionDomain( -// this.getClass().getProtectionDomain().getCodeSource(), -// perms)); -// System.out.println("Loaded " + name); -// return loggerImplClass; -// } catch (Throwable ex) { -// ex.printStackTrace(); -// throw new ClassNotFoundException(name, ex); -// } -// } else { -// throw new ClassNotFoundException(name, -// new IOException(file.toPath() + ": can't read")); -// } -// } -// } -// + @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (name.endsWith("$LogProducerFinder")) { + if (name.equals("LogProducerFinder") || name.startsWith("LogProducerFinder$")) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); } return c; } -// if (name.endsWith("$LogProducerFinder$LoggerImpl")) { -// Class c = defineLoggerImplClass(name); -// if (resolve) { -// resolveClass(c); -// } -// return c; -// } return super.loadClass(name, resolve); } @Override protected Class findClass(String name) throws ClassNotFoundException { -// if (name.endsWith("$LogProducerFinder$LoggerImpl")) { -// return defineLoggerImplClass(name); -// } - if (name.endsWith("$$LogProducerFinder")) { + if (name.equals("LogProducerFinder") || name.startsWith("LogProducerFinder$")) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LogProducerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LogProducerFinder.java new file mode 100644 index 00000000000..0be9a1e848d --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LogProducerFinder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.lang.System.Logger; +import java.lang.System.LoggerFinder; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.concurrent.ConcurrentHashMap; + +public class LogProducerFinder extends LoggerFinder { + + public static final RuntimePermission LOGGERFINDER_PERMISSION = + new RuntimePermission("loggerFinder"); + final ConcurrentHashMap system = new ConcurrentHashMap<>(); + final ConcurrentHashMap user = new ConcurrentHashMap<>(); + + @Override + public Logger getLogger(String name, Module caller) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(LOGGERFINDER_PERMISSION); + } + PrivilegedAction pa = () -> caller.getClassLoader(); + ClassLoader callerLoader = AccessController.doPrivileged(pa); + if (callerLoader == null) { + return system.computeIfAbsent(name, (n) -> new LoggerBridgeTest.LoggerImpl(n)); + } else { + return user.computeIfAbsent(name, (n) -> new LoggerBridgeTest.LoggerImpl(n)); + } + } +} + diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LoggerBridgeTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LoggerBridgeTest.java index bd70d541a45..99678cd3323 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LoggerBridgeTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/LoggerBridgeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,13 +23,11 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessControlException; -import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; -import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.Arrays; import java.util.Collections; @@ -48,7 +46,6 @@ import java.util.logging.Handler; import java.util.logging.LogRecord; import java.lang.System.LoggerFinder; import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.util.stream.Stream; import sun.util.logging.PlatformLogger; @@ -61,7 +58,7 @@ import sun.util.logging.PlatformLogger; * @modules java.base/sun.util.logging * java.base/jdk.internal.logger * java.logging - * @build CustomSystemClassLoader LoggerBridgeTest + * @build CustomSystemClassLoader LogProducerFinder LoggerBridgeTest * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader LoggerBridgeTest NOSECURITY * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader LoggerBridgeTest NOPERMISSIONS * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader LoggerBridgeTest WITHPERMISSIONS @@ -231,204 +228,188 @@ public class LoggerBridgeTest { static { try { // Preload classes before the security manager is on. - providerClass = ClassLoader.getSystemClassLoader().loadClass("LoggerBridgeTest$LogProducerFinder"); + providerClass = ClassLoader.getSystemClassLoader().loadClass("LogProducerFinder"); ((LoggerFinder)providerClass.newInstance()).getLogger("foo", providerClass.getModule()); } catch (Exception ex) { throw new ExceptionInInitializerError(ex); } } - public static class LogProducerFinder extends LoggerFinder { - final ConcurrentHashMap system = new ConcurrentHashMap<>(); - final ConcurrentHashMap user = new ConcurrentHashMap<>(); + public static class LoggerImpl implements System.Logger, PlatformLogger.Bridge { + private final String name; + private PlatformLogger.Level level = PlatformLogger.Level.INFO; + private PlatformLogger.Level OFF = PlatformLogger.Level.OFF; + private PlatformLogger.Level FINE = PlatformLogger.Level.FINE; + private PlatformLogger.Level FINER = PlatformLogger.Level.FINER; + private PlatformLogger.Level FINEST = PlatformLogger.Level.FINEST; + private PlatformLogger.Level CONFIG = PlatformLogger.Level.CONFIG; + private PlatformLogger.Level INFO = PlatformLogger.Level.INFO; + private PlatformLogger.Level WARNING = PlatformLogger.Level.WARNING; + private PlatformLogger.Level SEVERE = PlatformLogger.Level.SEVERE; - public class LoggerImpl implements Logger, PlatformLogger.Bridge { - private final String name; - private sun.util.logging.PlatformLogger.Level level = sun.util.logging.PlatformLogger.Level.INFO; - private sun.util.logging.PlatformLogger.Level OFF = sun.util.logging.PlatformLogger.Level.OFF; - private sun.util.logging.PlatformLogger.Level FINE = sun.util.logging.PlatformLogger.Level.FINE; - private sun.util.logging.PlatformLogger.Level FINER = sun.util.logging.PlatformLogger.Level.FINER; - private sun.util.logging.PlatformLogger.Level FINEST = sun.util.logging.PlatformLogger.Level.FINEST; - private sun.util.logging.PlatformLogger.Level CONFIG = sun.util.logging.PlatformLogger.Level.CONFIG; - private sun.util.logging.PlatformLogger.Level INFO = sun.util.logging.PlatformLogger.Level.INFO; - private sun.util.logging.PlatformLogger.Level WARNING = sun.util.logging.PlatformLogger.Level.WARNING; - private sun.util.logging.PlatformLogger.Level SEVERE = sun.util.logging.PlatformLogger.Level.SEVERE; - - public LoggerImpl(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isLoggable(Level level) { - return this.level != OFF && this.level.intValue() <= level.getSeverity(); - } - - @Override - public void log(Level level, ResourceBundle bundle, - String key, Throwable thrown) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(Level level, ResourceBundle bundle, - String format, Object... params) { - throw new UnsupportedOperationException(); - } - - void log(LogEvent event) { - eventQueue.add(event); - } - - @Override - public void log(Level level, Supplier msgSupplier) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(Level level, Supplier msgSupplier, - Throwable thrown) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, null, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msgSupplier, null, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg, - Object... params) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, null, params)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg, - Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, thrown, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, Throwable thrown, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msgSupplier, thrown, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, null, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msgSupplier, null, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg, Object... params) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, null, params)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg, Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, thrown, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, Throwable thrown, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msgSupplier, thrown, (Object[])null)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, ResourceBundle bundle, String msg, - Object... params) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, bundle, msg, null, params)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, - String msg, Object... params) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, bundle, msg, null, params)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, ResourceBundle bundle, String msg, - Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, bundle, msg, thrown, (Object[])null)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, - String msg, Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, bundle, msg, thrown, (Object[])null)); - } - - @Override - public boolean isLoggable(sun.util.logging.PlatformLogger.Level level) { - return this.level != OFF && level.intValue() - >= this.level.intValue(); - } - - @Override - public boolean isEnabled() { - return this.level != OFF; - } + public LoggerImpl(String name) { + this.name = name; + } + public void configureLevel(PlatformLogger.Level level) { + this.level = level; } @Override - public Logger getLogger(String name, Module caller) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - PrivilegedAction pa = () -> caller.getClassLoader(); - ClassLoader callerLoader = AccessController.doPrivileged(pa); - if (callerLoader == null) { - return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } else { - return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } + public String getName() { + return name; } + + @Override + public boolean isLoggable(Level level) { + return this.level != OFF && this.level.intValue() <= level.getSeverity(); + } + + @Override + public void log(Level level, ResourceBundle bundle, + String key, Throwable thrown) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(Level level, ResourceBundle bundle, + String format, Object... params) { + throw new UnsupportedOperationException(); + } + + void log(LogEvent event) { + eventQueue.add(event); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(Level level, Supplier msgSupplier, + Throwable thrown) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(PlatformLogger.Level level, String msg) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, null, (Object[]) null)); + } + + @Override + public void log(PlatformLogger.Level level, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msgSupplier, null, (Object[]) null)); + } + + @Override + public void log(PlatformLogger.Level level, String msg, + Object... params) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, null, params)); + } + + @Override + public void log(PlatformLogger.Level level, String msg, + Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, thrown, (Object[]) null)); + } + + @Override + public void log(PlatformLogger.Level level, Throwable thrown, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msgSupplier, thrown, (Object[]) null)); + } + + @Override + public void logp(PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, null, (Object[]) null)); + } + + @Override + public void logp(PlatformLogger.Level level, String sourceClass, + String sourceMethod, Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msgSupplier, null, (Object[]) null)); + } + + @Override + public void logp(PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg, Object... params) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, null, params)); + } + + @Override + public void logp(PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg, Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, thrown, (Object[]) null)); + } + + @Override + public void logp(PlatformLogger.Level level, String sourceClass, + String sourceMethod, Throwable thrown, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msgSupplier, thrown, (Object[]) null)); + } + + @Override + public void logrb(PlatformLogger.Level level, String sourceClass, + String sourceMethod, ResourceBundle bundle, String msg, + Object... params) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, bundle, msg, null, params)); + } + + @Override + public void logrb(PlatformLogger.Level level, ResourceBundle bundle, + String msg, Object... params) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, bundle, msg, null, params)); + } + + @Override + public void logrb(PlatformLogger.Level level, String sourceClass, + String sourceMethod, ResourceBundle bundle, String msg, + Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, bundle, msg, thrown, (Object[]) null)); + } + + @Override + public void logrb(PlatformLogger.Level level, ResourceBundle bundle, + String msg, Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, bundle, msg, thrown, (Object[]) null)); + } + + @Override + public boolean isLoggable(PlatformLogger.Level level) { + return this.level != OFF && level.intValue() + >= this.level.intValue(); + } + + @Override + public boolean isEnabled() { + return this.level != OFF; + } + } static ClassLoader getClassLoader(Module m) { @@ -675,14 +656,14 @@ public class LoggerBridgeTest { } - final LogProducerFinder.LoggerImpl appSink; - final LogProducerFinder.LoggerImpl sysSink; + final LoggerImpl appSink; + final LoggerImpl sysSink; boolean old = allowControl.get().get(); allowControl.get().set(true); try { - appSink = LogProducerFinder.LoggerImpl.class.cast( + appSink = LoggerImpl.class.cast( provider.getLogger("foo", LoggerBridgeTest.class.getModule())); - sysSink = LogProducerFinder.LoggerImpl.class.cast( + sysSink = LoggerImpl.class.cast( provider.getLogger("foo", Thread.class.getModule())); } finally { allowControl.get().set(old); @@ -739,20 +720,20 @@ public class LoggerBridgeTest { } } - static void setLevel( LogProducerFinder.LoggerImpl sink, + static void setLevel(LoggerImpl sink, sun.util.logging.PlatformLogger.Level loggerLevel) { - sink.level = loggerLevel; + sink.configureLevel(loggerLevel); } - // Calls the methods defined on LogProducer and verify the - // parameters received by the underlying LogProducerFinder.LoggerImpl + // Calls the methods defined on PlatformLogger.Bridge and verify the + // parameters received by the underlying LoggerImpl // logger. private static void testLogger(LoggerFinder provider, Map loggerDescMap, String name, ResourceBundle loggerBundle, PlatformLogger.Bridge logger, - LogProducerFinder.LoggerImpl sink) { + LoggerImpl sink) { System.out.println("Testing " + loggerDescMap.get(logger) + "[" + logger + "]"); final sun.util.logging.PlatformLogger.Level OFF = sun.util.logging.PlatformLogger.Level.OFF; diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder index 8abf57e2bac..205129c504f 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder @@ -1 +1 @@ -LoggerBridgeTest$LogProducerFinder +LogProducerFinder diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder.java new file mode 100644 index 00000000000..2b265733178 --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.internal.logger.SimpleConsoleLogger; + +import java.lang.System.Logger; +import java.lang.System.LoggerFinder; +import java.security.AccessController; +import java.security.PrivilegedAction; + +public class BaseLoggerFinder extends LoggerFinder + implements LoggerFinderLoaderTest.TestLoggerFinder { + + static final RuntimePermission LOGGERFINDER_PERMISSION = + new RuntimePermission("loggerFinder"); + + public BaseLoggerFinder() { + if (fails.get()) { + throw new RuntimeException("Simulate exception while loading provider"); + } + } + + Logger createSimpleLogger(String name) { + PrivilegedAction pa = () -> SimpleConsoleLogger.makeSimpleLogger(name); + return AccessController.doPrivileged(pa); + } + + @Override + public Logger getLogger(String name, Module caller) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(LOGGERFINDER_PERMISSION); + } + PrivilegedAction pa = () -> caller.getClassLoader(); + ClassLoader callerLoader = AccessController.doPrivileged(pa); + if (callerLoader == null) { + return system.computeIfAbsent(name, (n) -> new LoggerImpl(n, createSimpleLogger(name))); + } else { + return user.computeIfAbsent(name, (n) -> new LoggerImpl(n, createSimpleLogger(name))); + } + } +} diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder2.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder2.java new file mode 100644 index 00000000000..7765d510431 --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/BaseLoggerFinder2.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.lang.System.Logger; +import java.lang.System.LoggerFinder; +import java.util.ServiceConfigurationError; + +public class BaseLoggerFinder2 extends LoggerFinder + implements LoggerFinderLoaderTest.TestLoggerFinder { + + public BaseLoggerFinder2() { + throw new ServiceConfigurationError("Should not come here"); + } + + @Override + public Logger getLogger(String name, Module caller) { + throw new ServiceConfigurationError("Should not come here"); + } +} diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/CustomSystemClassLoader.java index 7e3db8b7dab..3eb23ed618c 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/CustomSystemClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** @@ -48,9 +49,8 @@ public class CustomSystemClassLoader extends ClassLoader { final List finderClassNames = - Arrays.asList("LoggerFinderLoaderTest$BaseLoggerFinder", - "LoggerFinderLoaderTest$BaseLoggerFinder2"); - final Map> finderClasses = new HashMap<>(); + Arrays.asList("BaseLoggerFinder", "BaseLoggerFinder2"); + final Map> finderClasses = new ConcurrentHashMap<>(); Class testLoggerFinderClass; public CustomSystemClassLoader() { @@ -62,9 +62,13 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + Class finderClass = finderClasses.get(name); + if (finderClass != null) return finderClass; + final Object obj = getClassLoadingLock(name); synchronized(obj) { - if (finderClasses.get(name) != null) return finderClasses.get(name); + finderClass = finderClasses.get(name); + if (finderClass != null) return finderClass; if (testLoggerFinderClass == null) { // Hack: we load testLoggerFinderClass to get its code source. // we can't use this.getClass() since we are in the boot. @@ -77,7 +81,7 @@ public class CustomSystemClassLoader extends ClassLoader { byte[] b = Files.readAllBytes(file.toPath()); Permissions perms = new Permissions(); perms.add(new AllPermission()); - Class finderClass = defineClass( + finderClass = defineClass( name, b, 0, b.length, new ProtectionDomain( this.getClass().getProtectionDomain().getCodeSource(), perms)); @@ -95,9 +99,13 @@ public class CustomSystemClassLoader extends ClassLoader { } } + private static boolean matches(String prefix, String name) { + return prefix.equals(name) || name.startsWith(prefix + "$"); + } + @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (finderClassNames.contains(name)) { + if (finderClassNames.stream().anyMatch(n -> matches(n, name))) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); @@ -109,7 +117,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { - if (finderClassNames.contains(name)) { + if (finderClassNames.stream().anyMatch(n -> matches(n, name))) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/LoggerFinderLoaderTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/LoggerFinderLoaderTest.java index 65763715f29..c6ef5c97953 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/LoggerFinderLoaderTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/LoggerFinderLoaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,7 +63,7 @@ import jdk.internal.logger.SimpleConsoleLogger; * DefaultLoggerFinder and SimpleConsoleLogger implementation. * @modules java.base/sun.util.logging * java.base/jdk.internal.logger - * @build AccessSystemLogger LoggerFinderLoaderTest CustomSystemClassLoader + * @build AccessSystemLogger LoggerFinderLoaderTest CustomSystemClassLoader BaseLoggerFinder BaseLoggerFinder2 * @run driver AccessSystemLogger * @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader LoggerFinderLoaderTest NOSECURITY * @run main/othervm -Xbootclasspath/a:boot -Djava.system.class.loader=CustomSystemClassLoader LoggerFinderLoaderTest NOPERMISSIONS @@ -118,8 +118,8 @@ public class LoggerFinderLoaderTest { static { try { providerClass = new Class[] { - ClassLoader.getSystemClassLoader().loadClass("LoggerFinderLoaderTest$BaseLoggerFinder"), - ClassLoader.getSystemClassLoader().loadClass("LoggerFinderLoaderTest$BaseLoggerFinder2") + ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder"), + ClassLoader.getSystemClassLoader().loadClass("BaseLoggerFinder2") }; } catch (ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); @@ -171,51 +171,6 @@ public class LoggerFinderLoaderTest { public Logger getLocalizedLogger(String name, ResourceBundle bundle, Module caller); } - public static class BaseLoggerFinder extends LoggerFinder implements TestLoggerFinder { - - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - public BaseLoggerFinder() { - if (fails.get()) { - throw new RuntimeException("Simulate exception while loading provider"); - } - } - - System.Logger createSimpleLogger(String name) { - PrivilegedAction pa = () -> SimpleConsoleLogger.makeSimpleLogger(name); - return AccessController.doPrivileged(pa); - } - - - @Override - public Logger getLogger(String name, Module caller) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - PrivilegedAction pa = () -> caller.getClassLoader(); - ClassLoader callerLoader = AccessController.doPrivileged(pa); - if (callerLoader == null) { - return system.computeIfAbsent(name, (n) -> new LoggerImpl(n, createSimpleLogger(name))); - } else { - return user.computeIfAbsent(name, (n) -> new LoggerImpl(n, createSimpleLogger(name))); - } - } - } - - public static class BaseLoggerFinder2 extends LoggerFinder implements TestLoggerFinder { - - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - public BaseLoggerFinder2() { - throw new ServiceConfigurationError("Should not come here"); - } - @Override - public Logger getLogger(String name, Module caller) { - throw new ServiceConfigurationError("Should not come here"); - } - } - public static class MyBundle extends ResourceBundle { final ConcurrentHashMap map = new ConcurrentHashMap<>(); @@ -270,7 +225,7 @@ public class LoggerFinderLoaderTest { throw new RuntimeException("Expected message not found. Error stream contained: " + warning); } if (TestLoggerFinder.fails.get()) { - if (!warning.contains("java.util.ServiceConfigurationError: java.lang.System$LoggerFinder: Provider LoggerFinderLoaderTest$BaseLoggerFinder could not be instantiated")) { + if (!warning.contains("java.util.ServiceConfigurationError: java.lang.System$LoggerFinder: Provider BaseLoggerFinder could not be instantiated")) { throw new RuntimeException("Expected message not found. Error stream contained: " + warning); } } else if (singleton) { @@ -425,7 +380,7 @@ public class LoggerFinderLoaderTest { ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader()); Iterator iterator = serviceLoader.iterator(); Object firstProvider = iterator.next(); - if (!firstProvider.getClass().getName().equals("LoggerFinderLoaderTest$BaseLoggerFinder")) { + if (!firstProvider.getClass().getName().equals("BaseLoggerFinder")) { throw new RuntimeException("Unexpected provider: " + firstProvider.getClass().getName()); } if (!iterator.hasNext()) { diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/META-INF/services/java.lang.System$LoggerFinder index 39a1084640c..a622df6dc7b 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/LoggerFinderLoaderTest/META-INF/services/java.lang.System$LoggerFinder @@ -1,3 +1,3 @@ -LoggerFinderLoaderTest$BaseLoggerFinder -LoggerFinderLoaderTest$BaseLoggerFinder2 +BaseLoggerFinder +BaseLoggerFinder2 diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/CustomSystemClassLoader.java b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/CustomSystemClassLoader.java index b0730fb0828..27ea8fe9c5b 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/CustomSystemClassLoader.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/CustomSystemClassLoader.java @@ -28,6 +28,8 @@ import java.nio.file.Files; import java.security.AllPermission; import java.security.Permissions; import java.security.ProtectionDomain; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** @@ -39,7 +41,7 @@ import java.security.ProtectionDomain; public class CustomSystemClassLoader extends ClassLoader { - Class loggerFinderClass = null; + final ConcurrentHashMap> classes = new ConcurrentHashMap<>(); public CustomSystemClassLoader() { super(); @@ -50,8 +52,11 @@ public class CustomSystemClassLoader extends ClassLoader { private Class defineFinderClass(String name) throws ClassNotFoundException { + Class loggerFinderClass = classes.get(name); + if (loggerFinderClass != null) return loggerFinderClass; final Object obj = getClassLoadingLock(name); synchronized(obj) { + loggerFinderClass = classes.get(name); if (loggerFinderClass != null) return loggerFinderClass; URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); @@ -66,6 +71,7 @@ public class CustomSystemClassLoader extends ClassLoader { this.getClass().getProtectionDomain().getCodeSource(), perms)); System.out.println("Loaded " + name); + classes.put(name, loggerFinderClass); return loggerFinderClass; } catch (Throwable ex) { ex.printStackTrace(); @@ -80,7 +86,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (name.endsWith("$LogProducerFinder")) { + if (name.equals("LogProducerFinder") || name.startsWith("LogProducerFinder$")) { Class c = defineFinderClass(name); if (resolve) { resolveClass(c); @@ -92,7 +98,7 @@ public class CustomSystemClassLoader extends ClassLoader { @Override protected Class findClass(String name) throws ClassNotFoundException { - if (name.endsWith("$$LogProducerFinder")) { + if (name.equals("LogProducerFinder") || name.startsWith("LogProducerFinder$")) { return defineFinderClass(name); } return super.findClass(name); diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/LogProducerFinder.java b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/LogProducerFinder.java new file mode 100644 index 00000000000..e1ff75cc834 --- /dev/null +++ b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/LogProducerFinder.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Queue; +import java.util.ResourceBundle; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import java.lang.System.LoggerFinder; +import java.lang.System.Logger; + +public class LogProducerFinder extends LoggerFinder { + + static final RuntimePermission LOGGERFINDER_PERMISSION = + new RuntimePermission("loggerFinder"); + final ConcurrentHashMap + system = new ConcurrentHashMap<>(); + final ConcurrentHashMap + user = new ConcurrentHashMap<>(); + + private static PlatformLoggerBridgeTest.LoggerImpl newLoggerImpl(String name) { + return new PlatformLoggerBridgeTest.LoggerImpl(name); + } + + @Override + public Logger getLogger(String name, Module caller) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(LOGGERFINDER_PERMISSION); + } + PrivilegedAction pa = () -> caller.getClassLoader(); + ClassLoader callerLoader = AccessController.doPrivileged(pa); + if (callerLoader == null) { + return system.computeIfAbsent(name, (n) -> newLoggerImpl(n)); + } else { + return user.computeIfAbsent(name, (n) -> newLoggerImpl(n)); + } + } +} diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder index a686921e3be..205129c504f 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder +++ b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/META-INF/services/java.lang.System$LoggerFinder @@ -1 +1 @@ -PlatformLoggerBridgeTest$LogProducerFinder +LogProducerFinder diff --git a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/PlatformLoggerBridgeTest.java b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/PlatformLoggerBridgeTest.java index c409c22a1a3..6b4f4bf4d8e 100644 --- a/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/PlatformLoggerBridgeTest.java +++ b/test/jdk/java/lang/System/LoggerFinder/internal/PlatformLoggerBridgeTest/PlatformLoggerBridgeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,7 +58,7 @@ import sun.util.logging.PlatformLogger; * backend whose loggers implement PlatformLogger.Bridge. * @modules java.base/sun.util.logging * java.logging - * @build CustomSystemClassLoader PlatformLoggerBridgeTest + * @build CustomSystemClassLoader LogProducerFinder PlatformLoggerBridgeTest * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader PlatformLoggerBridgeTest NOSECURITY * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader PlatformLoggerBridgeTest NOPERMISSIONS * @run main/othervm -Djava.system.class.loader=CustomSystemClassLoader PlatformLoggerBridgeTest WITHPERMISSIONS @@ -89,19 +89,19 @@ public class PlatformLoggerBridgeTest { } }; + public static final Queue eventQueue = new ArrayBlockingQueue<>(128); + static final Class providerClass; static { try { // Preload classes before the security manager is on. - providerClass = ClassLoader.getSystemClassLoader().loadClass("PlatformLoggerBridgeTest$LogProducerFinder"); + providerClass = ClassLoader.getSystemClassLoader().loadClass("LogProducerFinder"); ((LoggerFinder)providerClass.newInstance()).getLogger("foo", providerClass.getModule()); } catch (Exception ex) { throw new ExceptionInInitializerError(ex); } } - public static final Queue eventQueue = new ArrayBlockingQueue<>(128); - public static final class LogEvent implements Cloneable { public LogEvent() { @@ -234,200 +234,182 @@ public class PlatformLoggerBridgeTest { } - public static class LogProducerFinder extends LoggerFinder { - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - final ConcurrentHashMap system = new ConcurrentHashMap<>(); - final ConcurrentHashMap user = new ConcurrentHashMap<>(); - - public class LoggerImpl implements Logger, PlatformLogger.Bridge { - private final String name; - private sun.util.logging.PlatformLogger.Level level = sun.util.logging.PlatformLogger.Level.INFO; - private sun.util.logging.PlatformLogger.Level OFF = sun.util.logging.PlatformLogger.Level.OFF; - private sun.util.logging.PlatformLogger.Level FINE = sun.util.logging.PlatformLogger.Level.FINE; - private sun.util.logging.PlatformLogger.Level FINER = sun.util.logging.PlatformLogger.Level.FINER; - private sun.util.logging.PlatformLogger.Level FINEST = sun.util.logging.PlatformLogger.Level.FINEST; - private sun.util.logging.PlatformLogger.Level CONFIG = sun.util.logging.PlatformLogger.Level.CONFIG; - private sun.util.logging.PlatformLogger.Level INFO = sun.util.logging.PlatformLogger.Level.INFO; - private sun.util.logging.PlatformLogger.Level WARNING = sun.util.logging.PlatformLogger.Level.WARNING; - private sun.util.logging.PlatformLogger.Level SEVERE = sun.util.logging.PlatformLogger.Level.SEVERE; - - public LoggerImpl(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isLoggable(Level level) { - return this.level != OFF && this.level.intValue() <= level.getSeverity(); - } - - @Override - public void log(Level level, ResourceBundle bundle, - String key, Throwable thrown) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(Level level, ResourceBundle bundle, - String format, Object... params) { - throw new UnsupportedOperationException(); - } - - void log(LogEvent event) { - eventQueue.add(event); - } - - @Override - public void log(Level level, Supplier msgSupplier) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(Level level, Supplier msgSupplier, - Throwable thrown) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, null, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msgSupplier, null, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg, - Object... params) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, null, params)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, String msg, - Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msg, thrown, (Object[])null)); - } - - @Override - public void log(sun.util.logging.PlatformLogger.Level level, Throwable thrown, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, null, msgSupplier, thrown, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, null, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msgSupplier, null, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg, Object... params) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, null, params)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, String msg, Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msg, thrown, (Object[])null)); - } - - @Override - public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, Throwable thrown, - Supplier msgSupplier) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, null, msgSupplier, thrown, (Object[])null)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, ResourceBundle bundle, String msg, - Object... params) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, bundle, msg, null, params)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, - String msg, Object... params) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, bundle, msg, null, params)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, - String sourceMethod, ResourceBundle bundle, String msg, - Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, - sourceClass, sourceMethod, - level, bundle, msg, thrown, (Object[])null)); - } - - @Override - public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, - String msg, Throwable thrown) { - log(LogEvent.of(isLoggable(level), name, null, null, - level, bundle, msg, thrown, (Object[])null)); - } - - @Override - public boolean isLoggable(sun.util.logging.PlatformLogger.Level level) { - return this.level != OFF && level.intValue() - >= this.level.intValue(); - } - - @Override - public boolean isEnabled() { - return this.level != OFF; - } + public static class LoggerImpl implements System.Logger, PlatformLogger.Bridge { + private final String name; + private sun.util.logging.PlatformLogger.Level level = sun.util.logging.PlatformLogger.Level.INFO; + private sun.util.logging.PlatformLogger.Level OFF = sun.util.logging.PlatformLogger.Level.OFF; + private sun.util.logging.PlatformLogger.Level FINE = sun.util.logging.PlatformLogger.Level.FINE; + private sun.util.logging.PlatformLogger.Level FINER = sun.util.logging.PlatformLogger.Level.FINER; + private sun.util.logging.PlatformLogger.Level FINEST = sun.util.logging.PlatformLogger.Level.FINEST; + private sun.util.logging.PlatformLogger.Level CONFIG = sun.util.logging.PlatformLogger.Level.CONFIG; + private sun.util.logging.PlatformLogger.Level INFO = sun.util.logging.PlatformLogger.Level.INFO; + private sun.util.logging.PlatformLogger.Level WARNING = sun.util.logging.PlatformLogger.Level.WARNING; + private sun.util.logging.PlatformLogger.Level SEVERE = sun.util.logging.PlatformLogger.Level.SEVERE; + public LoggerImpl(String name) { + this.name = name; + } + public void configureLevel(sun.util.logging.PlatformLogger.Level level) { + this.level = level; } @Override - public Logger getLogger(String name, Module caller) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - PrivilegedAction pa = () -> caller.getClassLoader(); - ClassLoader callerLoader = AccessController.doPrivileged(pa); - if (callerLoader == null) { - return system.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } else { - return user.computeIfAbsent(name, (n) -> new LoggerImpl(n)); - } + public String getName() { + return name; } + + @Override + public boolean isLoggable(Level level) { + return this.level != OFF && this.level.intValue() <= level.getSeverity(); + } + + @Override + public void log(Level level, ResourceBundle bundle, + String key, Throwable thrown) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(Level level, ResourceBundle bundle, + String format, Object... params) { + throw new UnsupportedOperationException(); + } + + void log(PlatformLoggerBridgeTest.LogEvent event) { + eventQueue.add(event); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(Level level, Supplier msgSupplier, + Throwable thrown) { + throw new UnsupportedOperationException(); + } + + @Override + public void log(sun.util.logging.PlatformLogger.Level level, String msg) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, null, (Object[]) null)); + } + + @Override + public void log(sun.util.logging.PlatformLogger.Level level, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msgSupplier, null, (Object[]) null)); + } + + @Override + public void log(sun.util.logging.PlatformLogger.Level level, String msg, + Object... params) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, null, params)); + } + + @Override + public void log(sun.util.logging.PlatformLogger.Level level, String msg, + Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msg, thrown, (Object[]) null)); + } + + @Override + public void log(sun.util.logging.PlatformLogger.Level level, Throwable thrown, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, null, msgSupplier, thrown, (Object[]) null)); + } + + @Override + public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, null, (Object[]) null)); + } + + @Override + public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msgSupplier, null, (Object[]) null)); + } + + @Override + public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg, Object... params) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, null, params)); + } + + @Override + public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, String msg, Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msg, thrown, (Object[]) null)); + } + + @Override + public void logp(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, Throwable thrown, + Supplier msgSupplier) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, null, msgSupplier, thrown, (Object[]) null)); + } + + @Override + public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, ResourceBundle bundle, String msg, + Object... params) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, bundle, msg, null, params)); + } + + @Override + public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, + String msg, Object... params) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, bundle, msg, null, params)); + } + + @Override + public void logrb(sun.util.logging.PlatformLogger.Level level, String sourceClass, + String sourceMethod, ResourceBundle bundle, String msg, + Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, + sourceClass, sourceMethod, + level, bundle, msg, thrown, (Object[]) null)); + } + + @Override + public void logrb(sun.util.logging.PlatformLogger.Level level, ResourceBundle bundle, + String msg, Throwable thrown) { + log(LogEvent.of(isLoggable(level), name, null, null, + level, bundle, msg, thrown, (Object[]) null)); + } + + @Override + public boolean isLoggable(sun.util.logging.PlatformLogger.Level level) { + return this.level != OFF && level.intValue() + >= this.level.intValue(); + } + + @Override + public boolean isEnabled() { + return this.level != OFF; + } + + } static final sun.util.logging.PlatformLogger.Level[] julLevels = { @@ -593,11 +575,11 @@ public class PlatformLoggerBridgeTest { System.out.println("Got expected exception for system logger: " + acx); } - final LogProducerFinder.LoggerImpl sysSink; + final LoggerImpl sysSink; boolean old = allowControl.get().get(); allowControl.get().set(true); try { - sysSink = LogProducerFinder.LoggerImpl.class.cast( + sysSink = LoggerImpl.class.cast( provider.getLogger("foo", Thread.class.getModule())); } finally { allowControl.get().set(old); @@ -647,20 +629,20 @@ public class PlatformLoggerBridgeTest { } } - static void setLevel( LogProducerFinder.LoggerImpl sink, + static void setLevel(LoggerImpl sink, sun.util.logging.PlatformLogger.Level loggerLevel) { - sink.level = loggerLevel; + sink.configureLevel(loggerLevel); } // Calls the methods defined on LogProducer and verify the - // parameters received by the underlying LogProducerFinder.LoggerImpl + // parameters received by the underlying LoggerImpl // logger. private static void testLogger(LoggerFinder provider, Map loggerDescMap, String name, ResourceBundle loggerBundle, PlatformLogger logger, - LogProducerFinder.LoggerImpl sink) { + LoggerImpl sink) { System.out.println("Testing " + loggerDescMap.get(logger) + " [" + logger +"]"); final sun.util.logging.PlatformLogger.Level OFF = sun.util.logging.PlatformLogger.Level.OFF; From e93939f85148a762604ad57508c7f58ffca9282d Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Wed, 19 Dec 2018 11:45:54 +0000 Subject: [PATCH 075/174] 8209414: AArch64: method handle invocation does not respect JVMTI interp_only mode Reviewed-by: adinn --- src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp b/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp index 00fc6ad2a82..c103496f91a 100644 --- a/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp @@ -105,8 +105,8 @@ void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register meth // compiled code in threads for which the event is enabled. Check here for // interp_only_mode if these events CAN be enabled. - __ ldrb(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset())); - __ cbnz(rscratch1, run_compiled_code); + __ ldrw(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset())); + __ cbzw(rscratch1, run_compiled_code); __ ldr(rscratch1, Address(method, Method::interpreter_entry_offset())); __ br(rscratch1); __ BIND(run_compiled_code); From f398c3dcd212d71f75e52c838f9c757f51937dbb Mon Sep 17 00:00:00 2001 From: Vicente Romero Date: Wed, 19 Dec 2018 14:02:19 -0500 Subject: [PATCH 076/174] 8215625: javax/sql/testng/util/xxxxx.java tests compilation failed after JDK-8207224 Reviewed-by: mcimadamore --- .../com/sun/tools/javac/code/Source.java | 3 +- .../com/sun/tools/javac/code/Types.java | 11 ++------ .../T8207224/ReturnTypeSubstitutableTest.java | 28 ------------------- .../T8207224/ReturnTypeSubstitutableTest.out | 2 -- 4 files changed, 3 insertions(+), 41 deletions(-) delete mode 100644 test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java delete mode 100644 test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java index 93f8c280b8c..9832f731200 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java @@ -189,8 +189,7 @@ public enum Source { SWITCH_MULTIPLE_CASE_LABELS(JDK13, Fragments.FeatureMultipleCaseLabels, DiagKind.PLURAL), SWITCH_RULE(JDK13, Fragments.FeatureSwitchRules, DiagKind.PLURAL), SWITCH_EXPRESSION(JDK13, Fragments.FeatureSwitchExpressions, DiagKind.PLURAL), - RAW_STRING_LITERALS(JDK13, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL), - RETURN_TYPE_SUBSTITUTABLE_SAME_TYPE(JDK13); + RAW_STRING_LITERALS(JDK13, Fragments.FeatureRawStringLiterals, DiagKind.PLURAL); enum DiagKind { NORMAL, diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java index f779a769cb5..15cdeb5b713 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java @@ -91,7 +91,6 @@ public class Types { final Names names; final boolean allowDefaultMethods; final boolean mapCapturesToBounds; - final boolean returnTypeSustitutableSameType; final Check chk; final Enter enter; JCDiagnostic.Factory diags; @@ -115,7 +114,6 @@ public class Types { Source source = Source.instance(context); allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source); mapCapturesToBounds = Feature.MAP_CAPTURES_TO_BOUNDS.allowedInSource(source); - returnTypeSustitutableSameType = Feature.RETURN_TYPE_SUBSTITUTABLE_SAME_TYPE.allowedInSource(source); chk = Check.instance(context); enter = Enter.instance(context); capturedName = names.fromString(""); @@ -4237,13 +4235,8 @@ public class Types { return covariantReturnType(r1.getReturnType(), r2res, warner); if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner)) return true; - if (returnTypeSustitutableSameType) { - if (!isSameType(r1.getReturnType(), erasure(r2res))) - return false; - } else { - if (!isSubtype(r1.getReturnType(), erasure(r2res))) - return false; - } + if (!isSubtype(r1.getReturnType(), erasure(r2res))) + return false; warner.warn(LintCategory.UNCHECKED); return true; } diff --git a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java deleted file mode 100644 index 1a4708548af..00000000000 --- a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * @test /nodynamiccopyright/ - * @bug 8207224 - * @summary Javac compiles source code despite illegal use of unchecked conversions - * @compile/fail/ref=ReturnTypeSubstitutableTest.out -XDrawDiagnostics ReturnTypeSubstitutableTest.java - * @compile -source 12 ReturnTypeSubstitutableTest.java - */ - -class ReturnTypeSubstitutableTest { - abstract class AbstractDemo { - protected abstract Response test(Request request); - } - - abstract interface AbstractResult {} - - abstract interface SimpleResult extends AbstractResult {} - - class Result1 implements SimpleResult {} - - class OtherResult implements AbstractResult {} - - public class SimpleDemo extends AbstractDemo { - @Override - protected SimpleResult test(AbstractResult request) { - return null; - } - } -} diff --git a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out b/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out deleted file mode 100644 index 4a9c5594402..00000000000 --- a/test/langtools/tools/javac/T8207224/ReturnTypeSubstitutableTest.out +++ /dev/null @@ -1,2 +0,0 @@ -ReturnTypeSubstitutableTest.java:24:32: compiler.err.override.incompatible.ret: (compiler.misc.cant.override: test(ReturnTypeSubstitutableTest.AbstractResult), ReturnTypeSubstitutableTest.SimpleDemo, test(Request), ReturnTypeSubstitutableTest.AbstractDemo), ReturnTypeSubstitutableTest.SimpleResult, Response -1 error From 135d5dc27924ea5b1bae14b1658fa46fe18e84f4 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Wed, 19 Dec 2018 11:44:57 -0800 Subject: [PATCH 077/174] 8183912: java.math.BigDecimal.movePointLeft() should return this if called with zero argument Reviewed-by: rriggs --- src/java.base/share/classes/java/math/BigDecimal.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/java.base/share/classes/java/math/BigDecimal.java b/src/java.base/share/classes/java/math/BigDecimal.java index 646c556ee6c..bb3c1e3f47e 100644 --- a/src/java.base/share/classes/java/math/BigDecimal.java +++ b/src/java.base/share/classes/java/math/BigDecimal.java @@ -2871,6 +2871,8 @@ public class BigDecimal extends Number implements Comparable { * @throws ArithmeticException if scale overflows. */ public BigDecimal movePointLeft(int n) { + if (n == 0) return this; + // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale + n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); @@ -2893,6 +2895,8 @@ public class BigDecimal extends Number implements Comparable { * @throws ArithmeticException if scale overflows. */ public BigDecimal movePointRight(int n) { + if (n == 0) return this; + // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale - n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); From a4d4c07f7b8e9994078b8e108da73a2ea50a3d18 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Wed, 19 Dec 2018 14:08:08 -0800 Subject: [PATCH 078/174] 8215425: vmTestbase/nsk/jvmti/PopFrame should provide more detailed output Reviewed-by: sspitsyn, jcbeyler --- .../nsk/jvmti/PopFrame/popframe001.java | 50 +++----- .../PopFrame/popframe001/popframe001.cpp | 39 +++--- .../nsk/jvmti/PopFrame/popframe002.java | 71 +++++------ .../PopFrame/popframe002/popframe002.cpp | 22 ++-- .../nsk/jvmti/PopFrame/popframe003.java | 43 +++---- .../PopFrame/popframe003/popframe003.cpp | 38 +++--- .../nsk/jvmti/PopFrame/popframe003p.java | 35 +++--- .../nsk/jvmti/PopFrame/popframe004.java | 78 +++--------- .../PopFrame/popframe004/TestDescription.java | 2 +- .../PopFrame/popframe004/popframe004.cpp | 116 +++++++++--------- .../nsk/jvmti/PopFrame/popframe005.java | 89 +++++--------- 11 files changed, 210 insertions(+), 373 deletions(-) diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001.java index fcdeb10d3c9..62b93ade12a 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001.java @@ -39,7 +39,6 @@ public class popframe001 { static final int FAILED = 2; static final int JCK_STATUS_BASE = 95; - static boolean DEBUG_MODE = false; static volatile boolean popFdone = false; static volatile int totRes = PASSED; private PrintStream out; @@ -58,9 +57,9 @@ public class popframe001 { } } - native static int doPopFrame(int vrb, popFrameCls popFrameClsThr); - native static int suspThread(int vrb, popFrameCls popFrameClsThr); - native static int resThread(int vrb, popFrameCls popFrameClsThr); + native static int doPopFrame(popFrameCls popFrameClsThr); + native static int suspThread(popFrameCls popFrameClsThr); + native static int resThread(popFrameCls popFrameClsThr); public static void main(String[] argv) { argv = nsk.share.jvmti.JVMTITest.commonInit(argv); @@ -76,10 +75,6 @@ public class popframe001 { int retValue = 0; this.out = out; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-v")) // verbose mode - DEBUG_MODE = true; - } popFrameClsThr = new popFrameCls("Tested Thread"); startingBarrier = new Wicket(); @@ -90,35 +85,26 @@ public class popframe001 { synchronized (barrier) { } - if (DEBUG_MODE) { - out.println("Going to suspend the thread..."); - retValue = suspThread(1, popFrameClsThr); - } else - retValue = suspThread(0, popFrameClsThr); + out.println("Going to suspend the thread..."); + retValue = suspThread(popFrameClsThr); if (retValue != PASSED) { out.println("TEST: failed to suspend thread"); return FAILED; } // pop a frame of the child thread - if (DEBUG_MODE) { - out.println("Going to pop a frame..."); - retValue = doPopFrame(1, popFrameClsThr); - } else - retValue = doPopFrame(0, popFrameClsThr); + out.println("Going to pop a frame..."); + retValue = doPopFrame(popFrameClsThr); popFdone = true; popFrameClsThr.letItGo(); if (retValue != PASSED) { out.println("TEST: failed to pop frame"); - resThread(0, popFrameClsThr); + resThread(popFrameClsThr); return FAILED; } - if (DEBUG_MODE) { - out.println("Going to resume the thread..."); - retValue = resThread(1, popFrameClsThr); - } else - retValue = resThread(0, popFrameClsThr); + out.println("Going to resume the thread..."); + retValue = resThread(popFrameClsThr); if (retValue != PASSED) { out.println("TEST: failed to resume thread"); return FAILED; @@ -143,30 +129,22 @@ public class popframe001 { public void run() { activeMethod(); - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): exiting..."); + out.println("popFrameCls (" + this + "): exiting..."); } public void activeMethod() { boolean compl = true; // complain in a finally block if (popframe001.popFdone) { // popping has been done - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): enter activeMethod() after popping"); + out.println("popFrameCls (" + this + "): enter activeMethod() after popping"); return; } try { // notify the main thread synchronized (popframe001.barrier) { - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): notifying main thread"); + out.println("popFrameCls (" + this + "): notifying main thread"); popframe001.startingBarrier.unlock(); - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): inside activeMethod()"); + out.println("popFrameCls (" + this + "): inside activeMethod()"); } // loop until the main thread pops us int i = 0; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001/popframe001.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001/popframe001.cpp index 27cabcc85a8..4d3332c2079 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001/popframe001.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe001/popframe001.cpp @@ -77,52 +77,41 @@ MethodExit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thr, } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe001_suspThread(JNIEnv *env, - jclass cls, jint vrb, jobject susThr) { - jvmtiError err; - +Java_nsk_jvmti_PopFrame_popframe001_suspThread(JNIEnv *env, jclass cls, jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) - printf(">>>>>>>> Invoke SuspendThread()\n"); - err = jvmti->SuspendThread(susThr); + printf(">>>>>>>> Invoke SuspendThread()\n"); + jvmtiError err = jvmti->SuspendThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call SuspendThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) - printf("<<<<<<<< SuspendThread() is successfully done\n"); + printf("<<<<<<<< SuspendThread() is successfully done\n"); return PASSED; } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe001_resThread(JNIEnv *env, - jclass cls, jint vrb, jobject susThr) { - jvmtiError err; - +Java_nsk_jvmti_PopFrame_popframe001_resThread(JNIEnv *env, jclass cls, jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) - printf(">>>>>>>> Invoke ResumeThread()\n"); - err = jvmti->ResumeThread(susThr); + printf(">>>>>>>> Invoke ResumeThread()\n"); + jvmtiError err = jvmti->ResumeThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call ResumeThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) - printf("<<<<<<<< ResumeThread() is successfully done\n"); + printf("<<<<<<<< ResumeThread() is successfully done\n"); return PASSED; } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe001_doPopFrame(JNIEnv *env, - jclass cls, jint vrb, jobject frameThr) { +Java_nsk_jvmti_PopFrame_popframe001_doPopFrame(JNIEnv *env, jclass cls, jobject frameThr) { jvmtiError err; if (!caps.can_pop_frame || !caps.can_suspend) { @@ -145,8 +134,7 @@ Java_nsk_jvmti_PopFrame_popframe001_doPopFrame(JNIEnv *env, tot_result = STATUS_FAILED; } - if (vrb == 1) - printf(">>>>>>>> Invoke PopFrame()\n"); + printf(">>>>>>>> Invoke PopFrame()\n"); set_watch_ev(1); /* watch JVMTI events */ err = jvmti->PopFrame(frameThr); @@ -155,17 +143,18 @@ Java_nsk_jvmti_PopFrame_popframe001_doPopFrame(JNIEnv *env, err, TranslateError(err)); printf("\tFor more info about this error see the JVMTI spec.\n"); tot_result = STATUS_FAILED; - } - else if (vrb == 1) + } else { printf("Check #1 PASSED: PopFrame() is successfully done\n"); + } set_watch_ev(0); /* ignore again JVMTI events */ if (gen_ev) { printf("TEST FAILED: %d JVMTI events were generated by the function PopFrame()\n", gen_ev); tot_result = STATUS_FAILED; - } else if (vrb == 1) + } else { printf("Check #2 PASSED: No JVMTI events were generated by the function PopFrame()\n"); + } return(tot_result); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002.java index 19ab82958bc..92091f3a27c 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002.java @@ -46,7 +46,6 @@ public class popframe002 { static final int FAILED = 2; static final int JCK_STATUS_BASE = 95; - static boolean DEBUG_MODE = false; static volatile boolean popFdone = false; static volatile int totRes = PASSED; private PrintStream out; @@ -65,6 +64,10 @@ public class popframe002 { } } + // t_case: + // 1 - PopFrame for NULL thread + // 2 - PopFrame for invalid thread (not Thread object) + // 3 - PopFrame for non-suspended thread native static int doPopFrame(int t_case, popFrameCls popFrameClsThr); public static void main(String[] argv) { @@ -81,16 +84,12 @@ public class popframe002 { int retValue = 0; this.out = out; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-v")) // verbose mode - DEBUG_MODE = true; - } popFrameClsThr = new popFrameCls(); synchronized (barrier) { // force a child thread to pause synchronized(readi) { popFrameClsThr.start(); // start the child thread -// wait until the thread will enter into a necessary method + // wait until the thread will enter into a necessary method try { readi.wait(); // wait for the child readiness } catch (Exception e) { @@ -100,53 +99,45 @@ public class popframe002 { } } -/* check that if PopFrame() would be invoked with NULL pointer to - the thread, it will return the error JVMTI_ERROR_NULL_POINTER */ - if (DEBUG_MODE) - totRes = retValue = doPopFrame(1, popFrameClsThr); - else - totRes = retValue = doPopFrame(0, popFrameClsThr); - if (DEBUG_MODE && retValue == PASSED) + /* check that if PopFrame() would be invoked with NULL pointer to + the thread, it will return the error JVMTI_ERROR_NULL_POINTER */ + totRes = retValue = doPopFrame(1, popFrameClsThr); + if (retValue == PASSED) { out.println("Check #1 PASSED:\n" + - "\tPopFrame(), being invoked with NULL pointer " + - "to the thread,\n" + - "\treturned the appropriate error JVMTI_ERROR_NULL_POINTER"); + "\tPopFrame(), being invoked with NULL pointer " + + "to the thread,\n" + + "\treturned the appropriate error JVMTI_ERROR_NULL_POINTER"); + } -/* check that if the thread, whose top frame is to be popped, - is invalid, the PopFrame() will return the error - JVMTI_ERROR_INVALID_THREAD */ - if (DEBUG_MODE) - retValue = doPopFrame(3, popFrameClsThr); - else - retValue = doPopFrame(2, popFrameClsThr); + /* check that if the thread, whose top frame is to be popped, + is invalid, the PopFrame() will return the error + JVMTI_ERROR_INVALID_THREAD */ + retValue = doPopFrame(2, popFrameClsThr); if (retValue == FAILED) { popFdone = true; totRes = FAILED; - } else - if (DEBUG_MODE && retValue == PASSED) - out.println("Check #3 PASSED:\n" + + } else { + out.println("Check #2 PASSED:\n" + "\tPopFrame(), being invoked with " + "the invalid thread,\n" + "\treturned the appropriate error " + "JVMTI_ERROR_INVALID_THREAD"); + } -/* check that if the thread, whose top frame is to be popped, - has not been suspended, the PopFrame() will return the error - JVMTI_ERROR_THREAD_NOT_SUSPENDED */ - if (DEBUG_MODE) - retValue = doPopFrame(5, popFrameClsThr); - else - retValue = doPopFrame(4, popFrameClsThr); + /* check that if the thread, whose top frame is to be popped, + has not been suspended, the PopFrame() will return the error + JVMTI_ERROR_THREAD_NOT_SUSPENDED */ + retValue = doPopFrame(3, popFrameClsThr); if (retValue == FAILED) { popFdone = true; totRes = FAILED; - } else - if (DEBUG_MODE && retValue == PASSED) - out.println("Check #5 PASSED:\n" + + } else { + out.println("Check #3 PASSED:\n" + "\tPopFrame(), being invoked with " + "the non suspended thread,\n" + "\treturned the appropriate error " + "JVMTI_ERROR_THREAD_NOT_SUSPENDED"); + } } return totRes; @@ -159,17 +150,13 @@ public class popframe002 { if (popframe002.popFdone) { // popping has been done out.println("TEST FAILED: frame with popFrameCls.run() was popped"); popframe002.totRes = FAILED; - } - else { + } else { synchronized(readi) { readi.notify(); // notify the main thread } } - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): inside run()"); try { -// pause here and get the main thread a chance to run + // pause here and get the main thread a chance to run synchronized (popframe002.barrier) {} compl = false; } catch (Exception e) { diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002/popframe002.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002/popframe002.cpp index bffd80dc065..429af71866a 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002/popframe002.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe002/popframe002.cpp @@ -102,13 +102,10 @@ Java_nsk_jvmti_PopFrame_popframe002_doPopFrame(JNIEnv *env, } switch (t_case) { -/* NULL pointer to the thread in debug mode */ + /* NULL pointer to the thread*/ case 1: printf("\nInvoke PopFrame() with NULL pointer to a thread...\n"); fflush(stdout); - // fallthrough -/* NULL pointer to the thread */ - case 0: set_watch_ev(1); /* watch JVMTI events */ err = (jvmti->PopFrame(NULL)); /* explode the bomb */ if (err != JVMTI_ERROR_INVALID_THREAD) { @@ -118,13 +115,10 @@ Java_nsk_jvmti_PopFrame_popframe002_doPopFrame(JNIEnv *env, tot_result = STATUS_FAILED; } break; -/* invalid thread in debug mode */ - case 3: + /* invalid thread */ + case 2: printf("\nInvoke PopFrame() for an invalid thread...\n"); fflush(stdout); - // fallthrough -/* invalid thread */ - case 2: set_watch_ev(1); /* watch JVMTI events */ err = (jvmti->PopFrame(cls)); /* explode the bomb */ set_watch_ev(0); /* ignore again JVMTI events */ @@ -135,13 +129,10 @@ Java_nsk_jvmti_PopFrame_popframe002_doPopFrame(JNIEnv *env, tot_result = STATUS_FAILED; } break; -/* non suspended thread in debug mode */ - case 5: + /* non suspended thread */ + case 3: printf("\nInvoke PopFrame() for a non suspended thread...\n"); fflush(stdout); - // fallthrough -/* non suspended thread */ - case 4: set_watch_ev(1); /* watch JVMTI events */ err = (jvmti->PopFrame(frameThr)); /* explode the bomb */ set_watch_ev(0); /* ignore again JVMTI events */ @@ -152,6 +143,9 @@ Java_nsk_jvmti_PopFrame_popframe002_doPopFrame(JNIEnv *env, tot_result = STATUS_FAILED; } break; + default: + printf("\nTEST ERROR: unexpected case: %lld\n", (long long)t_case); + } if (gen_ev) { diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003.java index ef625e7f75e..5a14ec0e463 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003.java @@ -41,7 +41,6 @@ public class popframe003 { public static final int FAILED = 2; static final int JCK_STATUS_BASE = 95; - public static boolean DEBUG_MODE = false; private popframe003p popFrameClsThr; static { @@ -55,9 +54,9 @@ public class popframe003 { } } - native static int doPopFrame(int vrb, popframe003p popFrameClsThr); - native static int suspThread(int vrb, popframe003p popFrameClsThr); - native static int resThread(int vrb, popframe003p popFrameClsThr); + native static int doPopFrame(popframe003p popFrameClsThr); + native static int suspThread(popframe003p popFrameClsThr); + native static int resThread(popframe003p popFrameClsThr); public static void main(String[] argv) { argv = nsk.share.jvmti.JVMTITest.commonInit(argv); @@ -72,12 +71,7 @@ public class popframe003 { private int runIt(String argv[], PrintStream out) { int retValue = 0; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-v")) // verbose mode - DEBUG_MODE = true; - } - - popFrameClsThr = new popframe003p("Tested Thread", out, DEBUG_MODE); + popFrameClsThr = new popframe003p("Tested Thread", out); // start the child thread popFrameClsThr.start(); popFrameClsThr.startingBarrier.waitFor(); @@ -85,36 +79,27 @@ public class popframe003 { synchronized (popFrameClsThr.barrier) { } - if (DEBUG_MODE) { - out.println("Going to suspend the thread..."); - retValue = suspThread(1, popFrameClsThr); - } else - retValue = suspThread(0, popFrameClsThr); + out.println("Going to suspend the thread..."); + retValue = suspThread(popFrameClsThr); if (retValue != PASSED) { out.println("TEST: failed to suspend thread"); return FAILED; } // pop the frame - if (DEBUG_MODE) { - out.println("Going to pop a frame..."); - retValue = doPopFrame(1, popFrameClsThr); - } else - retValue = doPopFrame(0, popFrameClsThr); + out.println("Going to pop a frame..."); + retValue = doPopFrame(popFrameClsThr); popFrameClsThr.popFrameHasBeenDone(); if (retValue != PASSED) { out.println("TEST: failed to pop frame"); - resThread(0, popFrameClsThr); + resThread(popFrameClsThr); return FAILED; } - if (DEBUG_MODE) { - out.println("Going to resume the thread..."); - retValue = resThread(1, popFrameClsThr); - } else - retValue = resThread(0, popFrameClsThr); + out.println("Going to resume the thread..."); + retValue = resThread(popFrameClsThr); if (retValue != PASSED) { out.println("TEST: failed to resume thread"); return FAILED; @@ -147,10 +132,10 @@ public class popframe003 { "\t\tbooleanPubStatGlFld=" + popframe003p.booleanPubStatGlFld + "\texpected: true\n" + "\t\tstrPubStatGlFld=\"" + popframe003p.strPubStatGlFld + "\"\texpected: \"sttc glbl fld\""); return FAILED; - } - else if (DEBUG_MODE) + } else { out.println("Check #6 PASSED: changes for the static fields of a class,\n" + - "\twhich have been made in the popped frame's method, remained\n"); + "\twhich have been made in the popped frame's method, remained\n"); + } return popframe003p.totRes; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003/popframe003.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003/popframe003.cpp index 84f7720bc3c..f956c01f3aa 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003/popframe003.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003/popframe003.cpp @@ -77,53 +77,42 @@ MethodExit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thr, } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe003_suspThread(JNIEnv *env, - jclass cls, jint vrb, jobject susThr) { - jvmtiError err; - +Java_nsk_jvmti_PopFrame_popframe003_suspThread(JNIEnv *env, jclass cls, jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) - printf(">>>>>>>> Invoke SuspendThread()\n"); - err = jvmti->SuspendThread(susThr); + printf(">>>>>>>> Invoke SuspendThread()\n"); + jvmtiError err = jvmti->SuspendThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call SuspendThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) - printf("<<<<<<<< SuspendThread() is successfully done\n"); + printf("<<<<<<<< SuspendThread() is successfully done\n"); return PASSED; } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe003_resThread(JNIEnv *env, jclass cls, jint vrb, - jobject susThr) { - jvmtiError err; - +Java_nsk_jvmti_PopFrame_popframe003_resThread(JNIEnv *env, jclass cls, jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) - printf(">>>>>>>> Invoke ResumeThread()\n"); - err = jvmti->ResumeThread(susThr); + printf(">>>>>>>> Invoke ResumeThread()\n"); + jvmtiError err = jvmti->ResumeThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call ResumeThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) - printf("<<<<<<<< ResumeThread() is successfully done\n"); + printf("<<<<<<<< ResumeThread() is successfully done\n"); return PASSED; } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe003_doPopFrame(JNIEnv *env, jclass cls, jint vrb, - jobject frameThr) { +Java_nsk_jvmti_PopFrame_popframe003_doPopFrame(JNIEnv *env, jclass cls, jobject frameThr) { jvmtiError err; if (!caps.can_pop_frame || !caps.can_suspend) { @@ -146,8 +135,7 @@ Java_nsk_jvmti_PopFrame_popframe003_doPopFrame(JNIEnv *env, jclass cls, jint vrb tot_result = STATUS_FAILED; } - if (vrb == 1) - printf(">>>>>>>> Invoke PopFrame()\n"); + printf(">>>>>>>> Invoke PopFrame()\n"); set_watch_ev(1); /* watch JVMTI events */ err = jvmti->PopFrame(frameThr); @@ -157,16 +145,18 @@ Java_nsk_jvmti_PopFrame_popframe003_doPopFrame(JNIEnv *env, jclass cls, jint vrb printf("\tFor more info about this error see the JVMTI spec.\n"); tot_result = STATUS_FAILED; } - else if (vrb == 1) + else { printf("Check #1 PASSED: PopFrame() is successfully done\n"); + } set_watch_ev(0); /* ignore again JVMTI events */ if (gen_ev) { printf("TEST FAILED: %d JVMTI events were generated by the function PopFrame()\n", gen_ev); tot_result = STATUS_FAILED; - } else if (vrb == 1) + } else { printf("Check #2 PASSED: No JVMTI events were generated by the function PopFrame()\n"); + } return(tot_result); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003p.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003p.java index 694e947aae3..111bfbf4224 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003p.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe003p.java @@ -34,7 +34,6 @@ public class popframe003p extends Thread { static final int FAILED = 2; private PrintStream out; - private boolean DEBUG_MODE; public static volatile int totRes = PASSED; public static Object barrier = new Object(); @@ -76,10 +75,9 @@ public class popframe003p extends Thread { private popFrameCls popframeCls; - popframe003p(String name, PrintStream out, boolean verbose) { + popframe003p(String name, PrintStream out) { super(name); this.out = out; - DEBUG_MODE = verbose; startingBarrier = new Wicket(); popframeCls = new popFrameCls(); } @@ -124,10 +122,11 @@ public class popframe003p extends Thread { "\t\tbooleanPubGlFld=" + booleanPubGlFld + "\texpected: true\n" + "\t\tstrPubGlFld=\"" + strPubGlFld + "\"\texpected: null\n"); totRes = FAILED; - } else if (DEBUG_MODE) + } else { out.println("Check #5 PASSED: changes for the instance fields of a class,\n" + - "\twhich have been made in the popped frame's method, remained\n" + - "popframe003p (" + this + "): exiting..."); + "\twhich have been made in the popped frame's method, remained\n" + + "popframe003p (" + this + "): exiting..."); + } } class popFrameCls { @@ -149,9 +148,7 @@ public class popframe003p extends Thread { boolean compl = true; if (popFrameHasBeenDone) { // popping has been done - if (DEBUG_MODE) - out.println("popframe003p (" + this + - "): enter activeMeth() after popping"); + out.println("popframe003p (" + this + "): enter activeMeth() after popping"); /* check that any changes for the arguments, * which occurred in the called method, remain */ @@ -162,9 +159,10 @@ public class popframe003p extends Thread { "\tcurrent argument values: i=" + i + " l=" + l + " d=" + d + " c='" + c + "'\n"); totRes = FAILED; - } else if (DEBUG_MODE) + } else { out.println("Check #3 PASSED: changes for the arguments of " + - "the popped frame's method, remained\n"); + "the popped frame's method, remained\n"); + } /* check that any changes for the class fields, * which occurred in the called method, remain */ @@ -185,10 +183,11 @@ public class popframe003p extends Thread { "\t\tbooleanPubFld=" + booleanPubFld + "\texpected: false\n" + "\t\tstrPubFld=\"" + strPubFld + "\"\texpected: \"static fld\"\n"); totRes = FAILED; - } else if (DEBUG_MODE) + } else { out.println("Check #4 PASSED: changes for the fields of an inner class,\n" + - "\twhich have been made in the popped frame's method, remained\n" + - "popframe003p (" + this + "): exiting...\n"); + "\twhich have been made in the popped frame's method, remained\n" + + "popframe003p (" + this + "): exiting...\n"); + } return; } @@ -248,13 +247,9 @@ public class popframe003p extends Thread { try { // notify the main thread about readiness synchronized (barrier) { - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): notifying main thread"); + out.println("popFrameCls (" + this + "): notifying main thread"); startingBarrier.unlock(); - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): inside activeMethod()"); + out.println("popFrameCls (" + this + "): inside activeMethod()"); } // loop until the main thread pops us int ii = 0; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java index c584c946777..f45b7a3d5b4 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java @@ -26,7 +26,7 @@ package nsk.jvmti.PopFrame; import java.io.*; /** - * This test checks that a method's frame can be popped by the JVMTI + * This test checks that a method's frame can not be popped by the JVMTI * function PopFrame(): *

  • with intermediate native frames, and a thread, from which * the PopFrame() was called, is different than the current thread @@ -41,7 +41,6 @@ public class popframe004 { public static final int FAILED = 2; static final int JCK_STATUS_BASE = 95; - static boolean DEBUG_MODE = false; static volatile boolean popFdone = false; static volatile boolean popF2done = false; static volatile int totRes = PASSED; @@ -60,8 +59,8 @@ public class popframe004 { } } - native void nativeMeth(int vrb, popFrameCls popFrameClsThr); - native static int doPopFrame(int t_case, Thread popFrameClsThr); + native void nativeMeth(popFrameCls popFrameClsThr); + native static int doPopFrame(boolean otherThread, Thread popFrameClsThr); native static int getResult(); public static void main(String[] argv) { @@ -78,29 +77,22 @@ public class popframe004 { int retValue = 0; this.out = out; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-v")) // verbose mode - DEBUG_MODE = true; - } PipedInputStream pipeIn = new PipedInputStream(); popFrameClsThr = new popFrameCls(pipeIn); synchronized (barrier) { // force a child thread to pause popFrameClsThr.start(); // start a separate thread -// wait until the thread will enter into a necessary method + // wait until the thread will enter into a necessary method try { int _byte = pipeIn.read(); } catch (IOException e) { out.println("TEST FAILED: reading from a pipe: caught " + e); return FAILED; } -// pop the frame + // pop the frame if (popFrameClsThr.isAlive()) { - if (DEBUG_MODE) { - out.println("Going to pop the frame..."); - retValue=doPopFrame(1, popFrameClsThr); - } else - retValue=doPopFrame(0, popFrameClsThr); + out.println("Going to pop the frame on other thread..."); + retValue = doPopFrame(true, popFrameClsThr); popFdone = true; if (retValue != PASSED) return FAILED; @@ -125,23 +117,17 @@ public class popframe004 { totRes = FAILED; } - if (DEBUG_MODE) { - out.println("Going to pop the native frame..."); - totRes=doPopFrame(5, Thread.currentThread()); - } else - totRes=doPopFrame(4, Thread.currentThread()); - + out.println("Going to pop the native frame on the current thread..."); + totRes = doPopFrame(false, Thread.currentThread()); if (totRes != PASSED) return FAILED; else return getResult(); } class popFrameCls extends Thread { - private PipedInputStream pipeIn; private PipedOutputStream pipeOut; popFrameCls(PipedInputStream pipeIn) { - this.pipeIn = pipeIn; try { pipeOut = new PipedOutputStream(pipeIn); } catch (IOException e) { @@ -152,63 +138,31 @@ public class popframe004 { } public void run() { - if (DEBUG_MODE) - nativeMeth(1, popFrameClsThr); - else nativeMeth(0, popFrameClsThr); - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): exiting..."); + nativeMeth(popFrameClsThr); + out.println("popFrameCls (" + this + "): exiting..."); } public void activeMethod() { int retVal = FAILED; boolean compl = true; - if (popframe004.popFdone) { // popping has been done - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): enter activeMethod() after popping"); -// test case #2: popping from the current thread - if (!popframe004.popF2done) { - popframe004.popF2done = true; - if (DEBUG_MODE) { - out.println("popFrameCls (" + this + - "): going to pop a frame from the current thread..."); - retVal = doPopFrame(3, popFrameClsThr); - } else - retVal = doPopFrame(2, popFrameClsThr); - if (retVal != PASSED) - popframe004.totRes = FAILED; - } - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): leaving activeMethod()..."); - return; - } try { pipeOut.write(123); // notify the main thread - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): inside activeMethod()"); -// pause here until the main thread suspends us + out.println("popFrameCls (" + this + "): inside activeMethod()"); + // pause here until the main thread suspends us synchronized (popframe004.barrier) { while (true) { - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): looping..."); + out.println("popFrameCls (" + this + "): looping..."); if (popframe004.popFdone) { // popping has been done // popping has not to be done due to native frame - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): exiting activeMethod()..."); + out.println("popFrameCls (" + this + "): exiting activeMethod()..."); compl = false; return; } } } } catch (Exception e) { - out.println("FAILURE: popFrameCls (" + this + - "): caught " + e); + out.println("FAILURE: popFrameCls (" + this + "): caught " + e); popframe004.totRes = FAILED; compl = false; } finally { diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/TestDescription.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/TestDescription.java index f9173be8351..7b1dc42ef9b 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/TestDescription.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/TestDescription.java @@ -29,7 +29,7 @@ * VM Testbase keywords: [quick, jpda, jvmti, noras] * VM Testbase readme: * DESCRIPTION - * This test checks that a method's frame can be popped by + * This test checks that a method's frame can not be popped by * the JVMTI function PopFrame(): * - with intermediate native frames, and a thread, from which * the PopFrame() was called, is different than the current thread; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/popframe004.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/popframe004.cpp index 4c1f07fa71d..e455659d1f8 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/popframe004.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004/popframe004.cpp @@ -77,68 +77,64 @@ MethodExit(jvmtiEnv *jvmti_env, JNIEnv *env, jthread thr, jvmti->RawMonitorExit(watch_ev_monitor); } -int suspThread(jint vrb, jobject susThr) { - jvmtiError err; - +int suspThread(jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) { - printf(">>>>>>>> Invoke SuspendThread()\n"); - fflush(stdout); - } - err = jvmti->SuspendThread(susThr); + printf(">>>>>>>> Invoke SuspendThread()\n"); + fflush(stdout); + + jvmtiError err = jvmti->SuspendThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call SuspendThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) { - printf("<<<<<<<< SuspendThread() is successfully done\n"); - fflush(stdout); - } + printf("<<<<<<<< SuspendThread() is successfully done\n"); + fflush(stdout); + return PASSED; } -int resThread(jint vrb, jobject susThr) { - jvmtiError err; - +int resThread(jobject susThr) { if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (vrb == 1) { - printf(">>>>>>>> Invoke ResumeThread()\n"); - fflush(stdout); - } - err = jvmti->ResumeThread(susThr); + printf(">>>>>>>> Invoke ResumeThread()\n"); + fflush(stdout); + + jvmtiError err = jvmti->ResumeThread(susThr); if (err != JVMTI_ERROR_NONE) { printf("%s: Failed to call ResumeThread(): error=%d: %s\n", __FILE__, err, TranslateError(err)); return JNI_ERR; } - if (vrb == 1) { - printf("<<<<<<<< ResumeThread() is successfully done\n"); - fflush(stdout); - } + + printf("<<<<<<<< ResumeThread() is successfully done\n"); + fflush(stdout); + return PASSED; } JNIEXPORT jint JNICALL -Java_nsk_jvmti_PopFrame_popframe004_doPopFrame(JNIEnv *env, jclass cls, jint t_case, +Java_nsk_jvmti_PopFrame_popframe004_doPopFrame(JNIEnv *env, jclass cls, jboolean otherThread, jobject frameThr) { jvmtiError err; - if (popDone) return PASSED; + if (popDone) { + return PASSED; + } if (!caps.can_pop_frame || !caps.can_suspend) { return PASSED; } - if (t_case <= 1) /* we are in a different thread */ - if (suspThread(t_case, frameThr) != PASSED) + if (otherThread) { /* we are in a different thread */ + if (suspThread(frameThr) != PASSED) return STATUS_FAILED; + } err = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_METHOD_EXIT, frameThr); @@ -156,26 +152,29 @@ Java_nsk_jvmti_PopFrame_popframe004_doPopFrame(JNIEnv *env, jclass cls, jint t_c tot_result = STATUS_FAILED; } - if (t_case & 1) { - printf(">>>>>>>> Invoke PopFrame()\n"); - fflush(stdout); - } + printf(">>>>>>>> Invoke PopFrame()\n"); + fflush(stdout); set_watch_ev(1); /* watch JVMTI events */ err = jvmti->PopFrame(frameThr); - if (err == JVMTI_ERROR_NONE) { - printf("Check #%d FAILED: PopFrame() was unexpectedly done\n", t_case); + switch (err) { + case JVMTI_ERROR_NONE: + printf("Check FAILED: PopFrame() was unexpectedly done\n"); tot_result = STATUS_FAILED; - } else if (err != JVMTI_ERROR_NO_MORE_FRAMES && - err != JVMTI_ERROR_OPAQUE_FRAME) { - printf("Check #%d FAILED: PopFrame() returned unexpected error %d: %s\n", - t_case, err, TranslateError(err)); + break; + case JVMTI_ERROR_NO_MORE_FRAMES: + case JVMTI_ERROR_OPAQUE_FRAME: + case JVMTI_ERROR_THREAD_NOT_SUSPENDED: + printf("Check PASSED: PopFrame() failed as expected with %d: %s\n", + err, TranslateError(err)); + fflush(stdout); + break; + default: + printf("Check FAILED: PopFrame() returned unexpected error %d: %s\n", + err, TranslateError(err)); printf("\tFor more info about this error please refer to the JVMTI spec.\n"); tot_result = STATUS_FAILED; - } else if (t_case & 1) { - printf("Check #%d PASSED: PopFrame() failed as expected with %d: %s\n", - t_case, err, TranslateError(err)); - fflush(stdout); + break; } set_watch_ev(0); /* ignore again JVMTI events */ @@ -183,15 +182,16 @@ Java_nsk_jvmti_PopFrame_popframe004_doPopFrame(JNIEnv *env, jclass cls, jint t_c printf("TEST FAILED: %d JVMTI events were generated by the function PopFrame()\n", gen_ev); tot_result = STATUS_FAILED; - } else if (t_case & 1) { - printf("Check #%d PASSED: No JVMTI events were generated by the function PopFrame()\n", - t_case+1); + } else { + printf("Check PASSED: No JVMTI events were generated by the function PopFrame()\n"); fflush(stdout); } - if (t_case <= 1) /* we are in a different thread */ - return resThread(t_case, frameThr); - else popDone = 1; /* stop looping */ + if (otherThread) { /* we are in a different thread */ + return resThread(frameThr); + } else { + popDone = 1; /* stop looping */ + } return PASSED; } @@ -276,8 +276,7 @@ Java_nsk_jvmti_PopFrame_popframe004_getResult(JNIEnv *env, jclass cls) { return (tot_result); } -void nativeMeth2(JNIEnv *env, jobject obj, jint vrb, - jobject frameThr) { +void nativeMeth2(JNIEnv *env, jobject obj, jobject frameThr) { jclass cls = env->GetObjectClass(frameThr); jmethodID mid = NULL; @@ -287,21 +286,16 @@ void nativeMeth2(JNIEnv *env, jobject obj, jint vrb, tot_result = STATUS_FAILED; return; } - if (vrb == 1) { - printf("nativeMeth2(): calling the Java activeMethod()\n"); - fflush(stdout); - } + printf("nativeMeth2(): calling the Java activeMethod()\n"); + fflush(stdout); env->CallVoidMethod(frameThr, mid); } JNIEXPORT void JNICALL -Java_nsk_jvmti_PopFrame_popframe004_nativeMeth(JNIEnv *env, jobject obj, jint vrb, - jobject frameThr) { - if (vrb == 1) { - printf("nativeMeth(): calling the native nativeMeth2()\n"); - fflush(stdout); - } - nativeMeth2(env, obj, vrb, frameThr); +Java_nsk_jvmti_PopFrame_popframe004_nativeMeth(JNIEnv *env, jobject obj, jobject frameThr) { + printf("nativeMeth(): calling the native nativeMeth2()\n"); + fflush(stdout); + nativeMeth2(env, obj, frameThr); } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe005.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe005.java index 0ad1be953c7..bd73a34543d 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe005.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe005.java @@ -37,7 +37,6 @@ import java.io.PrintStream; public class popframe005 { static final int WAIT_TIME = 2000; - static boolean DEBUG_MODE = false; static volatile int testedStep = 0; /* 0- action no yet started 1- a frame is to be popped 2- checking monitors state @@ -78,19 +77,15 @@ public class popframe005 { Object lockObj[] = new Object[2]; this.out = out; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-v")) // verbose mode - DEBUG_MODE = true; - } lockObj[0] = new Object(); lockObj[1] = new Object(); - startGuarantee = new Wicket("startGuarantee", 1, (DEBUG_MODE ? System.out : null)); - finishGuarantee = new Wicket("finishGuarantee", 1, (DEBUG_MODE ? System.out : null)); + startGuarantee = new Wicket("startGuarantee", 1, System.out); + finishGuarantee = new Wicket("finishGuarantee", 1, System.out); allThreadsStoppedGuarantee = - new Wicket("allThreadsStoppedGuarantee", 3, (DEBUG_MODE ? System.out : null)); + new Wicket("allThreadsStoppedGuarantee", 3, System.out); // start a thread whose top frame is to be popped popFrameClsThr = new popFrameCls("Tested Thread", lockObj); @@ -109,20 +104,16 @@ public class popframe005 { // pause until the first thread exit notification-block allThreadsStoppedGuarantee.waitFor(); synchronized (allThreadsStoppedBarrier) { - if (DEBUG_MODE) { - out.println("Passed barrier in main thread"); - out.flush(); - } + out.println("Passed barrier in main thread"); + out.flush(); } /////////////////////// popping a frame //////////////////////// testedStep = 1; - if (DEBUG_MODE) { - out.println("State transition: testedStep: 0->1"); - out.println("Going to pop the frame..."); - out.flush(); - } + out.println("State transition: testedStep: 0->1"); + out.println("Going to pop the frame..."); + out.flush(); boolean retValue = doPopFrame(popFrameClsThr); @@ -133,10 +124,8 @@ public class popframe005 { ///////////////////// check monitors state ///////////////////// testedStep = 2; - if (DEBUG_MODE) { - out.println("State transition: testedStep: 1->2"); - out.flush(); - } + out.println("State transition: testedStep: 1->2"); + out.flush(); if (!popFrameClsThr.isAlive()) { out.println("TEST FAILURE: thread with the method's popped frame is dead"); @@ -146,8 +135,7 @@ public class popframe005 { try { objWaiterThr2.join(WAIT_TIME); } catch (InterruptedException e) { - if (DEBUG_MODE) - out.println("Joining the objWaiterThr2's thread: caught " + e); + out.println("Joining the objWaiterThr2's thread: caught " + e); } if (objWaiterThr2.isAlive()) { // objWaiterThr2 should be dead @@ -158,10 +146,8 @@ public class popframe005 { try { objWaiterThr1.join(WAIT_TIME); } catch (InterruptedException e) { - if (DEBUG_MODE) { - out.println("Joining the objWaiterThr1's thread: caught " + e); - out.flush(); - } + out.println("Joining the objWaiterThr1's thread: caught " + e); + out.flush(); } if (!objWaiterThr1.isAlive()) { // objWaiterThr2 should be alive out.println("TEST FAILED: Lock acquired by a frame, different from the popped one,\n" @@ -172,10 +158,8 @@ public class popframe005 { /////////////////////// finish the test /////////////////////// testedStep = 3; - if (DEBUG_MODE) { - out.println("State transition: testedStep: 2->3"); - out.flush(); - } + out.println("State transition: testedStep: 2->3"); + out.flush(); finishGuarantee.unlock(); @@ -209,29 +193,22 @@ public class popframe005 { synchronized(lockObj[0]) { activeMethod(); } - if (DEBUG_MODE) - out.println("popFrameCls (" + this + - "): exiting..."); out.flush(); + out.println("popFrameCls (" + this + "): exiting..."); + out.flush(); } public void activeMethod() { boolean compl = true; if (popframe005.testedStep != 0) { // popping has been done - if (DEBUG_MODE) { - out.println("popFrameCls (" + this + - "): enter activeMethod() after popping"); - out.flush(); - } + out.println("popFrameCls (" + this + "): enter activeMethod() after popping"); + out.flush(); // wait for checking monitors state by the main thread finishGuarantee.waitFor(); - if (DEBUG_MODE) { - out.println("popFrameCls (" + this + - "): leaving activeMethod()"); - out.flush(); - } + out.println("popFrameCls (" + this + "): leaving activeMethod()"); + out.flush(); return; } @@ -239,10 +216,8 @@ public class popframe005 { try { synchronized(lockObj[1]) { synchronized(allThreadsStoppedBarrier) { - if (DEBUG_MODE) { - out.println("popFrameCls (" + this + "): inside activeMethod()"); - out.flush(); - } + out.println("popFrameCls (" + this + "): inside activeMethod()"); + out.flush(); // notify the main thread startGuarantee.unlock(); @@ -301,12 +276,10 @@ public class popframe005 { public void run() { // notify the main thread synchronized(allThreadsStoppedBarrier) { - if (DEBUG_MODE) { - out.println("objWaiter(" + this + - "): waiting for a lockObj" + objIdent + - "'s monitor; testedStep=" + testedStep); - out.flush(); - } + out.println("objWaiter(" + this + + "): waiting for a lockObj" + objIdent + + "'s monitor; testedStep=" + testedStep); + out.flush(); allThreadsStoppedGuarantee.unlock(); } @@ -317,17 +290,15 @@ public class popframe005 { out.println("TEST FAILED: the lockObj" + objIdent + "'s monitor became free too early"); result = Consts.TEST_FAILED; - } else if (DEBUG_MODE) { + } else { out.println("Check PASSED: objWaiter(" + this + "): enter the lockObj" + objIdent + "'s monitor"); out.flush(); } } - if (DEBUG_MODE) { - out.println("objWaiter (" + this + "): exiting..."); - out.flush(); - } + out.println("objWaiter (" + this + "): exiting..."); + out.flush(); } catch (Exception e) { out.println("TEST FAILURE: objWaiter (" + this + "): caught " + e); } From 316924a7bdb522d89b8b2033b8ee8a92721c4c2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Per=20Lid=C3=A9n?= Date: Wed, 19 Dec 2018 23:40:05 +0100 Subject: [PATCH 079/174] 8215492: Rename INTERNAL_EMPTY to something less "internal" Reviewed-by: kbarrett, coleenp --- .../share/gc/shared/barrierSetConfig.hpp | 4 ++-- src/hotspot/share/oops/access.cpp | 2 +- src/hotspot/share/oops/access.hpp | 12 ++++++------ src/hotspot/share/oops/accessBackend.hpp | 8 ++++---- src/hotspot/share/oops/accessDecorators.hpp | 18 ++++++++++-------- src/hotspot/share/runtime/jniHandles.cpp | 2 +- .../share/runtime/jniHandles.inline.hpp | 4 ++-- 7 files changed, 26 insertions(+), 24 deletions(-) diff --git a/src/hotspot/share/gc/shared/barrierSetConfig.hpp b/src/hotspot/share/gc/shared/barrierSetConfig.hpp index d61adb75b10..dd66c39e369 100644 --- a/src/hotspot/share/gc/shared/barrierSetConfig.hpp +++ b/src/hotspot/share/gc/shared/barrierSetConfig.hpp @@ -48,11 +48,11 @@ #ifdef SUPPORT_BARRIER_ON_PRIMITIVES #define ACCESS_PRIMITIVE_SUPPORT INTERNAL_BT_BARRIER_ON_PRIMITIVES #else -#define ACCESS_PRIMITIVE_SUPPORT INTERNAL_EMPTY +#define ACCESS_PRIMITIVE_SUPPORT DECORATORS_NONE #endif #ifdef SUPPORT_NOT_TO_SPACE_INVARIANT -#define ACCESS_TO_SPACE_INVARIANT_SUPPORT INTERNAL_EMPTY +#define ACCESS_TO_SPACE_INVARIANT_SUPPORT DECORATORS_NONE #else #define ACCESS_TO_SPACE_INVARIANT_SUPPORT INTERNAL_BT_TO_SPACE_INVARIANT #endif diff --git a/src/hotspot/share/oops/access.cpp b/src/hotspot/share/oops/access.cpp index 5234f44e192..0a97632e0c1 100644 --- a/src/hotspot/share/oops/access.cpp +++ b/src/hotspot/share/oops/access.cpp @@ -32,5 +32,5 @@ template struct RuntimeDispatch::value, T, barrier_type> namespace AccessInternal { - INSTANTIATE_HPP_ACCESS(INTERNAL_EMPTY, oop, BARRIER_EQUALS); + INSTANTIATE_HPP_ACCESS(DECORATORS_NONE, oop, BARRIER_EQUALS); } diff --git a/src/hotspot/share/oops/access.hpp b/src/hotspot/share/oops/access.hpp index 149392bc9e5..6508810f85c 100644 --- a/src/hotspot/share/oops/access.hpp +++ b/src/hotspot/share/oops/access.hpp @@ -92,7 +92,7 @@ // access.inline.hpp. The accesses that are allowed through the access.hpp file // must be instantiated in access.cpp using the INSTANTIATE_HPP_ACCESS macro. -template +template class Access: public AllStatic { // This function asserts that if an access gets passed in a decorator outside // of the expected_decorators, then something is wrong. It additionally checks @@ -272,7 +272,7 @@ public: } static oop resolve(oop obj) { - verify_decorators(); + verify_decorators(); return AccessInternal::resolve(obj); } @@ -284,21 +284,21 @@ public: // Helper for performing raw accesses (knows only of memory ordering // atomicity decorators as well as compressed oops) -template +template class RawAccess: public Access {}; // Helper for performing normal accesses on the heap. These accesses // may resolve an accessor on a GC barrier set -template +template class HeapAccess: public Access {}; // Helper for performing normal accesses in roots. These accesses // may resolve an accessor on a GC barrier set -template +template class NativeAccess: public Access {}; // Helper for array access. -template +template class ArrayAccess: public HeapAccess { typedef HeapAccess AccessT; public: diff --git a/src/hotspot/share/oops/accessBackend.hpp b/src/hotspot/share/oops/accessBackend.hpp index 108d8acb1eb..1128fe91355 100644 --- a/src/hotspot/share/oops/accessBackend.hpp +++ b/src/hotspot/share/oops/accessBackend.hpp @@ -1192,7 +1192,7 @@ namespace AccessInternal { DecayedT decayed_value = value; const DecoratorSet expanded_decorators = DecoratorFixup::value ? - INTERNAL_CONVERT_COMPRESSED_OOP : INTERNAL_EMPTY)>::value; + INTERNAL_CONVERT_COMPRESSED_OOP : DECORATORS_NONE)>::value; PreRuntimeDispatch::store_at(base, offset, decayed_value); } @@ -1221,7 +1221,7 @@ namespace AccessInternal { // Potentially remember if we need compressed oop awareness const DecoratorSet expanded_decorators = DecoratorFixup::value ? - INTERNAL_CONVERT_COMPRESSED_OOP : INTERNAL_EMPTY)>::value; + INTERNAL_CONVERT_COMPRESSED_OOP : DECORATORS_NONE)>::value; return PreRuntimeDispatch::load_at(base, offset); } @@ -1253,7 +1253,7 @@ namespace AccessInternal { // Potentially remember that we need compressed oop awareness const DecoratorSet final_decorators = expanded_decorators | (HasDecorator::value ? - INTERNAL_CONVERT_COMPRESSED_OOP : INTERNAL_EMPTY); + INTERNAL_CONVERT_COMPRESSED_OOP : DECORATORS_NONE); return PreRuntimeDispatch::atomic_cmpxchg_at(new_decayed_value, base, offset, compare_decayed_value); } @@ -1278,7 +1278,7 @@ namespace AccessInternal { // atomic_xchg is only available in SEQ_CST flavour. const DecoratorSet expanded_decorators = DecoratorFixup::value ? - INTERNAL_CONVERT_COMPRESSED_OOP : INTERNAL_EMPTY)>::value; + INTERNAL_CONVERT_COMPRESSED_OOP : DECORATORS_NONE)>::value; return PreRuntimeDispatch::atomic_xchg_at(new_decayed_value, base, offset); } diff --git a/src/hotspot/share/oops/accessDecorators.hpp b/src/hotspot/share/oops/accessDecorators.hpp index 0d595034776..33a74d6bfd3 100644 --- a/src/hotspot/share/oops/accessDecorators.hpp +++ b/src/hotspot/share/oops/accessDecorators.hpp @@ -43,12 +43,14 @@ typedef uint64_t DecoratorSet; template struct HasDecorator: public IntegralConstant {}; +// == General Decorators == +// * DECORATORS_NONE: This is the name for the empty decorator set (in absence of other decorators). +const DecoratorSet DECORATORS_NONE = UCONST64(0); + // == Internal Decorators - do not use == -// * INTERNAL_EMPTY: This is the name for the empty decorator set (in absence of other decorators). // * INTERNAL_CONVERT_COMPRESSED_OOPS: This is an oop access that will require converting an oop // to a narrowOop or vice versa, if UseCompressedOops is known to be set. // * INTERNAL_VALUE_IS_OOP: Remember that the involved access is on oop rather than primitive. -const DecoratorSet INTERNAL_EMPTY = UCONST64(0); const DecoratorSet INTERNAL_CONVERT_COMPRESSED_OOP = UCONST64(1) << 1; const DecoratorSet INTERNAL_VALUE_IS_OOP = UCONST64(1) << 2; @@ -231,13 +233,13 @@ namespace AccessInternal { // If no reference strength has been picked, then strong will be picked static const DecoratorSet ref_strength_default = input_decorators | (((ON_DECORATOR_MASK & input_decorators) == 0 && (INTERNAL_VALUE_IS_OOP & input_decorators) != 0) ? - ON_STRONG_OOP_REF : INTERNAL_EMPTY); + ON_STRONG_OOP_REF : DECORATORS_NONE); // If no memory ordering has been picked, unordered will be picked static const DecoratorSet memory_ordering_default = ref_strength_default | - ((MO_DECORATOR_MASK & ref_strength_default) == 0 ? MO_UNORDERED : INTERNAL_EMPTY); + ((MO_DECORATOR_MASK & ref_strength_default) == 0 ? MO_UNORDERED : DECORATORS_NONE); // If no barrier strength has been picked, normal will be used static const DecoratorSet barrier_strength_default = memory_ordering_default | - ((AS_DECORATOR_MASK & memory_ordering_default) == 0 ? AS_NORMAL : INTERNAL_EMPTY); + ((AS_DECORATOR_MASK & memory_ordering_default) == 0 ? AS_NORMAL : DECORATORS_NONE); static const DecoratorSet value = barrier_strength_default | BT_BUILDTIME_DECORATORS; }; @@ -247,13 +249,13 @@ namespace AccessInternal { // If no reference strength has been picked, then strong will be picked DecoratorSet ref_strength_default = input_decorators | (((ON_DECORATOR_MASK & input_decorators) == 0 && (INTERNAL_VALUE_IS_OOP & input_decorators) != 0) ? - ON_STRONG_OOP_REF : INTERNAL_EMPTY); + ON_STRONG_OOP_REF : DECORATORS_NONE); // If no memory ordering has been picked, unordered will be picked DecoratorSet memory_ordering_default = ref_strength_default | - ((MO_DECORATOR_MASK & ref_strength_default) == 0 ? MO_UNORDERED : INTERNAL_EMPTY); + ((MO_DECORATOR_MASK & ref_strength_default) == 0 ? MO_UNORDERED : DECORATORS_NONE); // If no barrier strength has been picked, normal will be used DecoratorSet barrier_strength_default = memory_ordering_default | - ((AS_DECORATOR_MASK & memory_ordering_default) == 0 ? AS_NORMAL : INTERNAL_EMPTY); + ((AS_DECORATOR_MASK & memory_ordering_default) == 0 ? AS_NORMAL : DECORATORS_NONE); DecoratorSet value = barrier_strength_default | BT_BUILDTIME_DECORATORS; return value; } diff --git a/src/hotspot/share/runtime/jniHandles.cpp b/src/hotspot/share/runtime/jniHandles.cpp index a165e1e1948..913547b4f15 100644 --- a/src/hotspot/share/runtime/jniHandles.cpp +++ b/src/hotspot/share/runtime/jniHandles.cpp @@ -152,7 +152,7 @@ jobject JNIHandles::make_weak_global(Handle obj, AllocFailType alloc_failmode) { oop JNIHandles::resolve_external_guard(jobject handle) { oop result = NULL; if (handle != NULL) { - result = resolve_impl<0 /* decorators */, true /* external_guard */>(handle); + result = resolve_impl(handle); } return result; } diff --git a/src/hotspot/share/runtime/jniHandles.inline.hpp b/src/hotspot/share/runtime/jniHandles.inline.hpp index 43e284196c0..7d97bd1564a 100644 --- a/src/hotspot/share/runtime/jniHandles.inline.hpp +++ b/src/hotspot/share/runtime/jniHandles.inline.hpp @@ -68,7 +68,7 @@ inline oop JNIHandles::resolve_impl(jobject handle) { inline oop JNIHandles::resolve(jobject handle) { oop result = NULL; if (handle != NULL) { - result = resolve_impl<0 /* decorators */, false /* external_guard */>(handle); + result = resolve_impl(handle); } return result; } @@ -89,7 +89,7 @@ inline bool JNIHandles::is_same_object(jobject handle1, jobject handle2) { inline oop JNIHandles::resolve_non_null(jobject handle) { assert(handle != NULL, "JNI handle should not be null"); - oop result = resolve_impl<0 /* decorators */, false /* external_guard */>(handle); + oop result = resolve_impl(handle); assert(result != NULL, "NULL read from jni handle"); return result; } From 595fcb59bce0e1012358d9fcb8a206d9a50654d4 Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Thu, 20 Dec 2018 02:51:01 +0100 Subject: [PATCH 080/174] Added tag jdk-13+1 for changeset 11033c4ada54 --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 3b375a02166..e4872d1ead2 100644 --- a/.hgtags +++ b/.hgtags @@ -528,3 +528,4 @@ f8fb0c86f2b3d24294d39c5685a628e1beb14ba7 jdk-12+21 eef755718cb24813031a842bbfc716a6cea18e9a jdk-12+23 cc4098b3bc10d1c390384289025fea7b0d4b9e93 jdk-13+0 7d4397b43fa305806160785a4c7210600d59581a jdk-12+24 +11033c4ada542f9c9a873314b6ecf60af19e8256 jdk-13+1 From 994ab71870838978b242d5737fa01565b1caef23 Mon Sep 17 00:00:00 2001 From: Robbin Ehn Date: Thu, 20 Dec 2018 10:05:19 +0100 Subject: [PATCH 081/174] 8214180: Need better granularity for sleeping Reviewed-by: eosterlund, dcubed, dholmes --- src/hotspot/os/aix/os_aix.cpp | 17 ----------- src/hotspot/os/bsd/os_bsd.cpp | 16 ---------- src/hotspot/os/linux/os_linux.cpp | 37 ++++++----------------- src/hotspot/os/posix/os_posix.cpp | 15 +++++++++ src/hotspot/os/solaris/os_solaris.cpp | 10 ------ src/hotspot/os/windows/os_windows.cpp | 37 +++++++++++++++++++++++ src/hotspot/share/runtime/os.hpp | 1 + src/hotspot/share/utilities/spinYield.cpp | 7 +++-- src/hotspot/share/utilities/spinYield.hpp | 5 ++- 9 files changed, 71 insertions(+), 74 deletions(-) diff --git a/src/hotspot/os/aix/os_aix.cpp b/src/hotspot/os/aix/os_aix.cpp index ecd9ec4c009..b5ac60e433d 100644 --- a/src/hotspot/os/aix/os_aix.cpp +++ b/src/hotspot/os/aix/os_aix.cpp @@ -2602,23 +2602,6 @@ size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { return ::pread(fd, buf, nBytes, offset); } -void os::naked_short_sleep(jlong ms) { - struct timespec req; - - assert(ms < 1000, "Un-interruptable sleep, short time use only"); - req.tv_sec = 0; - if (ms > 0) { - req.tv_nsec = (ms % 1000) * 1000000; - } - else { - req.tv_nsec = 1; - } - - nanosleep(&req, NULL); - - return; -} - // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... diff --git a/src/hotspot/os/bsd/os_bsd.cpp b/src/hotspot/os/bsd/os_bsd.cpp index 2ba1bae954b..4cea30d5b68 100644 --- a/src/hotspot/os/bsd/os_bsd.cpp +++ b/src/hotspot/os/bsd/os_bsd.cpp @@ -2225,22 +2225,6 @@ size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { RESTARTABLE_RETURN_INT(::pread(fd, buf, nBytes, offset)); } -void os::naked_short_sleep(jlong ms) { - struct timespec req; - - assert(ms < 1000, "Un-interruptable sleep, short time use only"); - req.tv_sec = 0; - if (ms > 0) { - req.tv_nsec = (ms % 1000) * 1000000; - } else { - req.tv_nsec = 1; - } - - nanosleep(&req, NULL); - - return; -} - // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... diff --git a/src/hotspot/os/linux/os_linux.cpp b/src/hotspot/os/linux/os_linux.cpp index b5fdbafaa2a..072b8f1a79c 100644 --- a/src/hotspot/os/linux/os_linux.cpp +++ b/src/hotspot/os/linux/os_linux.cpp @@ -4033,33 +4033,6 @@ size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { return ::pread(fd, buf, nBytes, offset); } -// Short sleep, direct OS call. -// -// Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee -// sched_yield(2) will actually give up the CPU: -// -// * Alone on this pariticular CPU, keeps running. -// * Before the introduction of "skip_buddy" with "compat_yield" disabled -// (pre 2.6.39). -// -// So calling this with 0 is an alternative. -// -void os::naked_short_sleep(jlong ms) { - struct timespec req; - - assert(ms < 1000, "Un-interruptable sleep, short time use only"); - req.tv_sec = 0; - if (ms > 0) { - req.tv_nsec = (ms % 1000) * 1000000; - } else { - req.tv_nsec = 1; - } - - nanosleep(&req, NULL); - - return; -} - // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... @@ -4072,6 +4045,16 @@ bool os::dont_yield() { return DontYieldALot; } +// Linux CFS scheduler (since 2.6.23) does not guarantee sched_yield(2) will +// actually give up the CPU. Since skip buddy (v2.6.28): +// +// * Sets the yielding task as skip buddy for current CPU's run queue. +// * Picks next from run queue, if empty, picks a skip buddy (can be the yielding task). +// * Clears skip buddies for this run queue (yielding task no longer a skip buddy). +// +// An alternative is calling os::naked_short_nanosleep with a small number to avoid +// getting re-scheduled immediately. +// void os::naked_yield() { sched_yield(); } diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp index 5a43787eee9..17679bf4f03 100644 --- a/src/hotspot/os/posix/os_posix.cpp +++ b/src/hotspot/os/posix/os_posix.cpp @@ -695,6 +695,21 @@ int os::sleep(Thread* thread, jlong millis, bool interruptible) { } } +void os::naked_short_nanosleep(jlong ns) { + struct timespec req; + assert(ns > -1 && ns < NANOUNITS, "Un-interruptable sleep, short time use only"); + req.tv_sec = 0; + req.tv_nsec = ns; + ::nanosleep(&req, NULL); + return; +} + +void os::naked_short_sleep(jlong ms) { + assert(ms < MILLIUNITS, "Un-interruptable sleep, short time use only"); + os::naked_short_nanosleep(ms * (NANOUNITS / MILLIUNITS)); + return; +} + //////////////////////////////////////////////////////////////////////////////// // interrupt support diff --git a/src/hotspot/os/solaris/os_solaris.cpp b/src/hotspot/os/solaris/os_solaris.cpp index c2fddc3d045..43a5492021d 100644 --- a/src/hotspot/os/solaris/os_solaris.cpp +++ b/src/hotspot/os/solaris/os_solaris.cpp @@ -2871,16 +2871,6 @@ size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) { return res; } -void os::naked_short_sleep(jlong ms) { - assert(ms < 1000, "Un-interruptable sleep, short time use only"); - - // usleep is deprecated and removed from POSIX, in favour of nanosleep, but - // Solaris requires -lrt for this. - usleep((ms * 1000)); - - return; -} - // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... diff --git a/src/hotspot/os/windows/os_windows.cpp b/src/hotspot/os/windows/os_windows.cpp index 17365abc40c..c3660678281 100644 --- a/src/hotspot/os/windows/os_windows.cpp +++ b/src/hotspot/os/windows/os_windows.cpp @@ -3512,6 +3512,43 @@ void os::naked_short_sleep(jlong ms) { Sleep(ms); } +void os::naked_short_nanosleep(jlong ns) { + assert(ns > -1 && ns < NANOUNITS, "Un-interruptable sleep, short time use only"); + LARGE_INTEGER hundreds_nanos = { 0 }; + HANDLE wait_timer = ::CreateWaitableTimer(NULL /* attributes*/, + true /* manual reset */, + NULL /* name */ ); + if (wait_timer == NULL) { + log_warning(os)("Failed to CreateWaitableTimer: %u", GetLastError()); + return; + } + + // We need a minimum of one hundred nanos. + ns = ns > 100 ? ns : 100; + + // Round ns to the nearst hundred of nanos. + // Negative values indicate relative time. + hundreds_nanos.QuadPart = -((ns + 50) / 100); + + if (::SetWaitableTimer(wait_timer /* handle */, + &hundreds_nanos /* due time */, + 0 /* period */, + NULL /* comp func */, + NULL /* comp func args */, + FALSE /* resume */)) { + DWORD res = ::WaitForSingleObject(wait_timer /* handle */, INFINITE /* timeout */); + if (res != WAIT_OBJECT_0) { + if (res == WAIT_FAILED) { + log_warning(os)("Failed to WaitForSingleObject: %u", GetLastError()); + } else { + log_warning(os)("Unexpected return from WaitForSingleObject: %s", + res == WAIT_ABANDONED ? "WAIT_ABANDONED" : "WAIT_TIMEOUT"); + } + } + } + ::CloseHandle(wait_timer /* handle */); +} + // Sleep forever; naked call to OS-specific sleep; use with CAUTION void os::infinite_sleep() { while (true) { // sleep forever ... diff --git a/src/hotspot/share/runtime/os.hpp b/src/hotspot/share/runtime/os.hpp index 72a6e1f3fc1..bc5f768cb71 100644 --- a/src/hotspot/share/runtime/os.hpp +++ b/src/hotspot/share/runtime/os.hpp @@ -474,6 +474,7 @@ class os: AllStatic { // Ignores Thread.interrupt() (so keep it short). // ms = 0, will sleep for the least amount of time allowed by the OS. static void naked_short_sleep(jlong ms); + static void naked_short_nanosleep(jlong ns); static void infinite_sleep(); // never returns, use with CAUTION static void naked_yield () ; static OSReturn set_priority(Thread* thread, ThreadPriority priority); diff --git a/src/hotspot/share/utilities/spinYield.cpp b/src/hotspot/share/utilities/spinYield.cpp index 17e4db54c14..59fecc4677d 100644 --- a/src/hotspot/share/utilities/spinYield.cpp +++ b/src/hotspot/share/utilities/spinYield.cpp @@ -27,12 +27,13 @@ #include "utilities/ostream.hpp" #include "utilities/spinYield.hpp" -SpinYield::SpinYield(uint spin_limit, uint yield_limit) : +SpinYield::SpinYield(uint spin_limit, uint yield_limit, uint sleep_ns) : _sleep_time(), _spins(0), _yields(0), _spin_limit(os::is_MP() ? spin_limit : 0), - _yield_limit(yield_limit) + _yield_limit(yield_limit), + _sleep_ns(sleep_ns) {} void SpinYield::yield_or_sleep() { @@ -41,7 +42,7 @@ void SpinYield::yield_or_sleep() { os::naked_yield(); } else { Ticks sleep_start = Ticks::now(); - os::naked_short_sleep(1); + os::naked_short_nanosleep(_sleep_ns); _sleep_time += Ticks::now() - sleep_start; } } diff --git a/src/hotspot/share/utilities/spinYield.hpp b/src/hotspot/share/utilities/spinYield.hpp index 7176e0ef232..1c1845d2931 100644 --- a/src/hotspot/share/utilities/spinYield.hpp +++ b/src/hotspot/share/utilities/spinYield.hpp @@ -39,16 +39,19 @@ class SpinYield : public StackObj { uint _yields; uint _spin_limit; uint _yield_limit; + uint _sleep_ns; void yield_or_sleep(); public: static const uint default_spin_limit = 4096; static const uint default_yield_limit = 64; + static const uint default_sleep_ns = 1000; // spin_limit is ignored (treated as zero) when !os::is_MP(). explicit SpinYield(uint spin_limit = default_spin_limit, - uint yield_limit = default_yield_limit); + uint yield_limit = default_yield_limit, + uint sleep_ns = default_sleep_ns); // Perform next round of delay. void wait() { From 3cda678c2b4e5dc98e1392d483e8b4cf85eaf166 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Mon, 17 Dec 2018 13:47:22 +0100 Subject: [PATCH 082/174] 8215296: do not disable c99 on Solaris Reviewed-by: dholmes, ihse --- make/autoconf/flags-cflags.m4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/autoconf/flags-cflags.m4 b/make/autoconf/flags-cflags.m4 index 76101ccbe53..f960e16a19e 100644 --- a/make/autoconf/flags-cflags.m4 +++ b/make/autoconf/flags-cflags.m4 @@ -559,7 +559,7 @@ AC_DEFUN([FLAGS_SETUP_CFLAGS_HELPER], TOOLCHAIN_CFLAGS="-errshort=tags" TOOLCHAIN_CFLAGS_JDK="-mt $TOOLCHAIN_FLAGS" - TOOLCHAIN_CFLAGS_JDK_CONLY="-xc99=%none -xCC -Xa -W0,-noglobal $TOOLCHAIN_CFLAGS" # C only + TOOLCHAIN_CFLAGS_JDK_CONLY="-xCC -Xa -W0,-noglobal $TOOLCHAIN_CFLAGS" # C only TOOLCHAIN_CFLAGS_JDK_CXXONLY="-features=no%except -norunpath -xnolib" # CXX only TOOLCHAIN_CFLAGS_JVM="-template=no%extdef -features=no%split_init \ -library=stlport4 -mt -features=no%except $TOOLCHAIN_FLAGS" From 265abce7fbd67e3bfdabba30ba8a2a394120cf29 Mon Sep 17 00:00:00 2001 From: Harold Seigel Date: Thu, 20 Dec 2018 08:43:23 -0500 Subject: [PATCH 083/174] 8205505: Expire and remove remaining support for commercial features Remove the unneeded options and their tests and update the JCMD documentation. Reviewed-by: dholmes, coleenp, erikj --- make/nb_native/nbproject/configurations.xml | 22 ---------- .../share/classfile/systemDictionary.cpp | 1 - src/hotspot/share/runtime/arguments.cpp | 6 --- src/hotspot/share/runtime/arguments_ext.hpp | 40 ------------------- .../share/services/diagnosticCommand.hpp | 1 - .../share/services/diagnosticCommand_ext.hpp | 30 -------------- 6 files changed, 100 deletions(-) delete mode 100644 src/hotspot/share/runtime/arguments_ext.hpp delete mode 100644 src/hotspot/share/services/diagnosticCommand_ext.hpp diff --git a/make/nb_native/nbproject/configurations.xml b/make/nb_native/nbproject/configurations.xml index 161c34f05b4..263756d71d3 100644 --- a/make/nb_native/nbproject/configurations.xml +++ b/make/nb_native/nbproject/configurations.xml @@ -2538,7 +2538,6 @@ arguments.cpp arguments.hpp arguments_ext.cpp - arguments_ext.hpp atomic.hpp basicLock.cpp basicLock.hpp @@ -2702,7 +2701,6 @@ diagnosticArgument.hpp diagnosticCommand.cpp diagnosticCommand.hpp - diagnosticCommand_ext.hpp diagnosticFramework.cpp diagnosticFramework.hpp dtraceAttacher.cpp @@ -13687,11 +13685,6 @@ tool="1" flavor2="0"> - - - - - - - - nOptions; index++) { const JavaVMOption* option = args->options + index; - if (ArgumentsExt::process_options(option)) { - continue; - } if (match_option(option, "-XX:Flags=", &tail)) { Arguments::set_jvm_flags_file(tail); continue; @@ -3813,8 +3809,6 @@ jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) { UNSUPPORTED_OPTION(AllocateHeapAt); #endif - ArgumentsExt::report_unsupported_options(); - #ifndef PRODUCT if (TraceBytecodesAt != 0) { TraceBytecodes = true; diff --git a/src/hotspot/share/runtime/arguments_ext.hpp b/src/hotspot/share/runtime/arguments_ext.hpp deleted file mode 100644 index 743af71ea7d..00000000000 --- a/src/hotspot/share/runtime/arguments_ext.hpp +++ /dev/null @@ -1,40 +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. - * - */ - -#ifndef SHARE_VM_RUNTIME_ARGUMENTS_EXT_HPP -#define SHARE_VM_RUNTIME_ARGUMENTS_EXT_HPP - -#include "memory/allocation.hpp" -#include "runtime/arguments.hpp" - -class ArgumentsExt: AllStatic { -public: - // The argument processing extension. Returns true if there is - // no additional parsing needed in Arguments::parse() for the option. - // Otherwise returns false. - static inline bool process_options(const JavaVMOption *option) { return false; } - static inline void report_unsupported_options() { } -}; - -#endif // SHARE_VM_RUNTIME_ARGUMENTS_EXT_HPP diff --git a/src/hotspot/share/services/diagnosticCommand.hpp b/src/hotspot/share/services/diagnosticCommand.hpp index 45bb2a32107..a52bbbb3ee0 100644 --- a/src/hotspot/share/services/diagnosticCommand.hpp +++ b/src/hotspot/share/services/diagnosticCommand.hpp @@ -34,7 +34,6 @@ #include "runtime/vmThread.hpp" #include "services/diagnosticArgument.hpp" #include "services/diagnosticCommand.hpp" -#include "services/diagnosticCommand_ext.hpp" #include "services/diagnosticFramework.hpp" #include "utilities/macros.hpp" #include "utilities/ostream.hpp" diff --git a/src/hotspot/share/services/diagnosticCommand_ext.hpp b/src/hotspot/share/services/diagnosticCommand_ext.hpp deleted file mode 100644 index b571655380b..00000000000 --- a/src/hotspot/share/services/diagnosticCommand_ext.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - */ - -#ifndef SHARE_VM_SERVICES_DIAGNOSTICCOMMAND_EXT_HPP -#define SHARE_VM_SERVICES_DIAGNOSTICCOMMAND_EXT_HPP - -#undef HAVE_EXTRA_DCMD - -#endif // SHARE_VM_SERVICES_DIAGNOSTICCOMMAND_HPP From 1cd847d6d12b4459d175eef677ca26fb240b0539 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 7 Dec 2018 16:56:53 -0800 Subject: [PATCH 084/174] 8198526: getAnnotatedOwnerType does not handle static nested classes correctly Reviewed-by: jfranck --- .../annotation/AnnotatedTypeFactory.java | 24 +++-- .../reflect/annotation/TypeAnnotation.java | 22 ++--- .../GetAnnotatedNestedSuperclass.java | 96 +++++++++++++++++++ .../GetAnnotatedOwnerType.java | 58 +++++++++++ 4 files changed, 182 insertions(+), 18 deletions(-) create mode 100644 test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedNestedSuperclass.java diff --git a/src/java.base/share/classes/sun/reflect/annotation/AnnotatedTypeFactory.java b/src/java.base/share/classes/sun/reflect/annotation/AnnotatedTypeFactory.java index 47f7b94132b..64f50ba456e 100644 --- a/src/java.base/share/classes/sun/reflect/annotation/AnnotatedTypeFactory.java +++ b/src/java.base/share/classes/sun/reflect/annotation/AnnotatedTypeFactory.java @@ -100,12 +100,15 @@ public final class AnnotatedTypeFactory { if (clz.getEnclosingClass() == null) return addTo; if (Modifier.isStatic(clz.getModifiers())) - return nestingForType(clz.getEnclosingClass(), addTo); + return addTo; return nestingForType(clz.getEnclosingClass(), addTo.pushInner()); } else if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType)type; if (t.getOwnerType() == null) return addTo; + if (t.getRawType() instanceof Class + && Modifier.isStatic(((Class) t.getRawType()).getModifiers())) + return addTo; return nestingForType(t.getOwnerType(), addTo.pushInner()); } return addTo; @@ -193,14 +196,18 @@ public final class AnnotatedTypeFactory { if (!(type instanceof Class)) throw new IllegalStateException("Can't compute owner"); - Class inner = (Class)type; - Class owner = inner.getDeclaringClass(); + Class nested = (Class)type; + Class owner = nested.getDeclaringClass(); if (owner == null) // top-level, local or anonymous return null; - if (inner.isPrimitive() || inner == Void.TYPE) + if (nested.isPrimitive() || nested == Void.TYPE) return null; - LocationInfo outerLoc = nestingForType(owner, getLocation().popAllLocations((byte)1)); + LocationInfo outerLoc = getLocation().popLocation((byte)1); + if (outerLoc == null) { + return buildAnnotatedType(owner, LocationInfo.BASE_LOCATION, + EMPTY_TYPE_ANNOTATION_ARRAY, EMPTY_TYPE_ANNOTATION_ARRAY, getDecl()); + } TypeAnnotation[]all = getTypeAnnotations(); List l = new ArrayList<>(all.length); @@ -445,7 +452,12 @@ public final class AnnotatedTypeFactory { Type owner = getParameterizedType().getOwnerType(); if (owner == null) return null; - LocationInfo outerLoc = nestingForType(owner, getLocation().popAllLocations((byte)1)); + + LocationInfo outerLoc = getLocation().popLocation((byte)1); + if (outerLoc == null) { + return buildAnnotatedType(owner, LocationInfo.BASE_LOCATION, + EMPTY_TYPE_ANNOTATION_ARRAY, EMPTY_TYPE_ANNOTATION_ARRAY, getDecl()); + } TypeAnnotation[]all = getTypeAnnotations(); List l = new ArrayList<>(all.length); diff --git a/src/java.base/share/classes/sun/reflect/annotation/TypeAnnotation.java b/src/java.base/share/classes/sun/reflect/annotation/TypeAnnotation.java index 5a5f5b5cb51..1c593c5d53b 100644 --- a/src/java.base/share/classes/sun/reflect/annotation/TypeAnnotation.java +++ b/src/java.base/share/classes/sun/reflect/annotation/TypeAnnotation.java @@ -187,19 +187,17 @@ public final class TypeAnnotation { return new LocationInfo(newDepth, res); } - /** Pop a series of locations matching {@code tag}. Stop poping as soon as a non-matching tag is found. */ - public LocationInfo popAllLocations(byte tag) { - LocationInfo l = this; - int newDepth = l.depth; - while(newDepth > 0 && l.locations[newDepth - 1].tag == tag) { - newDepth--; + /** + * Pops a location matching {@code tag}, or returns {@code null} + * if no matching location was found. + */ + public LocationInfo popLocation(byte tag) { + if (depth == 0 || locations[depth - 1].tag != tag) { + return null; } - if (newDepth != l.depth) { - Location[] res = new Location[newDepth]; - System.arraycopy(this.locations, 0, res, 0, newDepth); - return new LocationInfo(newDepth, res); - } else - return l; + Location[] res = new Location[depth - 1]; + System.arraycopy(locations, 0, res, 0, depth - 1); + return new LocationInfo(depth - 1, res); } public TypeAnnotation[] filter(TypeAnnotation[] ta) { diff --git a/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedNestedSuperclass.java b/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedNestedSuperclass.java new file mode 100644 index 00000000000..a667a2e2c23 --- /dev/null +++ b/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedNestedSuperclass.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2018, 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 8066967 8198526 + * @summary Class.getAnnotatedSuperclass() does not correctly extract annotations + */ + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.AnnotatedParameterizedType; +import java.lang.reflect.AnnotatedType; +import java.util.Arrays; +import java.util.Objects; + +public class GetAnnotatedNestedSuperclass { + + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + @interface A {} + + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + @interface B {} + + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + @interface C {} + + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + @interface D {} + + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + @interface E {} + + static class X {} + + static class Y extends @A X<@B P1, @C P2, @D Class<@E P1>> {} + + public static void main(String[] args) throws Exception { + AnnotatedType x = Y.class.getAnnotatedSuperclass(); + assertEquals(Arrays.toString(x.getAnnotations()), "[@GetAnnotatedNestedSuperclass$A()]"); + AnnotatedParameterizedType xpt = (AnnotatedParameterizedType) x; + { + AnnotatedType arg = xpt.getAnnotatedActualTypeArguments()[0]; + assertEquals( + Arrays.toString(arg.getAnnotations()), "[@GetAnnotatedNestedSuperclass$B()]"); + } + { + AnnotatedType arg = xpt.getAnnotatedActualTypeArguments()[1]; + assertEquals( + Arrays.toString(arg.getAnnotations()), "[@GetAnnotatedNestedSuperclass$C()]"); + } + { + AnnotatedType arg = xpt.getAnnotatedActualTypeArguments()[2]; + assertEquals( + Arrays.toString(arg.getAnnotations()), "[@GetAnnotatedNestedSuperclass$D()]"); + AnnotatedType nestedArg = + ((AnnotatedParameterizedType) arg).getAnnotatedActualTypeArguments()[0]; + assertEquals( + Arrays.toString(nestedArg.getAnnotations()), + "[@GetAnnotatedNestedSuperclass$E()]"); + } + } + + private static void assertEquals(Object expected, Object actual) { + if (!Objects.equals(expected, actual)) { + throw new AssertionError("expected: " + expected + "; actual=" + actual); + } + } +} diff --git a/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedOwnerType.java b/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedOwnerType.java index d88a49e8beb..c4a722baa68 100644 --- a/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedOwnerType.java +++ b/test/jdk/java/lang/annotation/typeAnnotations/GetAnnotatedOwnerType.java @@ -42,6 +42,9 @@ public class GetAnnotatedOwnerType { public @TA("non-generic") GetAnnotatedOwnerTypeAuxilliary . @TB("non-generic") Inner nonGeneric; public @TA("non-generic") GetAnnotatedOwnerTypeAuxilliary . @TB("generic") InnerGeneric innerGeneric; public @TA("non-generic") GetAnnotatedOwnerTypeAuxilliary . @TB("raw") InnerGeneric innerRaw; + public GetAnnotatedOwnerTypeAuxilliary . @TB("non-generic") Nested nestedNonGeneric; + public GetAnnotatedOwnerTypeAuxilliary . @TB("generic") NestedGeneric nestedGeneric; + public GetAnnotatedOwnerTypeAuxilliary . @TB("raw") NestedGeneric nestedRaw; public Object anonymous = new Object() {}; public @TA("array") Dummy[] dummy; public @TA("wildcard") GetAnnotatedOwnerType wildcard; @@ -58,6 +61,9 @@ public class GetAnnotatedOwnerType { testNonGeneric(); testInnerGeneric(); testInnerRaw(); + testNestedNonGeneric(); + testNestedGeneric(); + testNestedRaw(); testLocalClass(); testAnonymousClass(); @@ -155,6 +161,54 @@ public class GetAnnotatedOwnerType { + outer.getAnnotations().length); } + public static void testNestedNonGeneric() throws Exception { + Field f = GetAnnotatedOwnerType.class.getField("nestedNonGeneric"); + + // make sure inner is correctly annotated + AnnotatedType inner = f.getAnnotatedType(); + Asserts.assertEquals(inner.getAnnotation(TB.class).value(), "non-generic"); + Asserts.assertTrue(inner.getAnnotations().length == 1, "expecting one (1) annotation, got: " + + inner.getAnnotations().length); + + // make sure owner is correctly annotated, on the correct type + AnnotatedType outer = inner.getAnnotatedOwnerType(); + Asserts.assertEquals(outer.getType(), ((Class)f.getGenericType()).getEnclosingClass()); + Asserts.assertTrue(outer.getAnnotations().length == 0, "expecting no annotations, got: " + + outer.getAnnotations().length); + } + + public static void testNestedGeneric() throws Exception { + Field f = GetAnnotatedOwnerType.class.getField("nestedGeneric"); + + // make sure inner is correctly annotated + AnnotatedType inner = f.getAnnotatedType(); + Asserts.assertEquals(inner.getAnnotation(TB.class).value(), "generic"); + Asserts.assertTrue(inner.getAnnotations().length == 1, "expecting one (1) annotation, got: " + + inner.getAnnotations().length); + + // make sure owner is correctly annotated, on the correct type + AnnotatedType outer = inner.getAnnotatedOwnerType(); + Asserts.assertEquals(outer.getType(), ((ParameterizedType) f.getGenericType()).getOwnerType()); + Asserts.assertTrue(outer.getAnnotations().length == 0, "expecting no annotations, got: " + + outer.getAnnotations().length); + } + + public static void testNestedRaw() throws Exception { + Field f = GetAnnotatedOwnerType.class.getField("nestedRaw"); + + // make sure inner is correctly annotated + AnnotatedType inner = f.getAnnotatedType(); + Asserts.assertEquals(inner.getAnnotation(TB.class).value(), "raw"); + Asserts.assertTrue(inner.getAnnotations().length == 1, "expecting one (1) annotation, got: " + + inner.getAnnotations().length); + + // make sure owner is correctly annotated, on the correct type + AnnotatedType outer = inner.getAnnotatedOwnerType(); + Asserts.assertEquals(outer.getType(), ((Class)f.getGenericType()).getEnclosingClass()); + Asserts.assertTrue(outer.getAnnotations().length == 0, "expecting no annotations, got: " + + outer.getAnnotations().length); + } + public static void testLocalClass() throws Exception { class ALocalClass {} class OneMore { @@ -279,4 +333,8 @@ class GetAnnotatedOwnerTypeAuxilliary { class Inner {} class InnerGeneric {} + + static class Nested {} + + static class NestedGeneric {} } From 884c808e83b5d9c3199768d714f22a4bb558dccb Mon Sep 17 00:00:00 2001 From: Pavel Rappo Date: Fri, 14 Dec 2018 19:49:03 +0000 Subject: [PATCH 085/174] 8215292: Back out changes for node- and link- local ipv6 multicast address Reviewed-by: chegar, alanb --- .../unix/native/libnet/net_util_md.c | 12 +- .../net/MulticastSocket/PromiscuousIPv6.java | 162 ------------ .../DatagramChannel/PromiscuousIPv6.java | 230 ------------------ 3 files changed, 3 insertions(+), 401 deletions(-) delete mode 100644 test/jdk/java/net/MulticastSocket/PromiscuousIPv6.java delete mode 100644 test/jdk/java/nio/channels/DatagramChannel/PromiscuousIPv6.java diff --git a/src/java.base/unix/native/libnet/net_util_md.c b/src/java.base/unix/native/libnet/net_util_md.c index 86df4978257..5a2473d630c 100644 --- a/src/java.base/unix/native/libnet/net_util_md.c +++ b/src/java.base/unix/native/libnet/net_util_md.c @@ -803,12 +803,8 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, #ifdef __linux__ /* - * On Linux if we are connecting to a - * - * - link-local address - * - multicast interface-local or link-local address - * - * we need to specify the interface in the scope_id. + * On Linux if we are connecting to a link-local address + * we need to specify the interface in the scope_id (2.4 kernel only) * * If the scope was cached then we use the cached value. If not cached but * specified in the Inet6Address we use that, but we first check if the @@ -818,9 +814,7 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, * we try to determine a value from the routing table. In all these * cases the used value is cached for further use. */ - if (IN6_IS_ADDR_LINKLOCAL(&sa->sa6.sin6_addr) - || IN6_IS_ADDR_MC_NODELOCAL(&sa->sa6.sin6_addr) - || IN6_IS_ADDR_MC_LINKLOCAL(&sa->sa6.sin6_addr)) { + if (IN6_IS_ADDR_LINKLOCAL(&sa->sa6.sin6_addr)) { unsigned int cached_scope_id = 0, scope_id = 0; if (ia6_cachedscopeidID) { diff --git a/test/jdk/java/net/MulticastSocket/PromiscuousIPv6.java b/test/jdk/java/net/MulticastSocket/PromiscuousIPv6.java deleted file mode 100644 index 4e22dfef2cb..00000000000 --- a/test/jdk/java/net/MulticastSocket/PromiscuousIPv6.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - -/* - * @test - * @bug 8210493 - * @requires os.family == "linux" - * @library /test/lib - * @build jdk.test.lib.NetworkConfiguration - * PromiscuousIPv6 - * @run main PromiscuousIPv6 - */ -import jdk.test.lib.NetworkConfiguration; -import jtreg.SkippedException; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; -import java.net.SocketTimeoutException; - -import static java.lang.System.out; - -/* - * This test was created as a copy of the Promiscuous test and adapted for - * IPv6 node-local and link-local multicast addresses on Linux. - */ -public class PromiscuousIPv6 { - - static final int TIMEOUT = 5 * 1000; // 5 secs - static int id = 1000; - - static void receive(DatagramSocket mc, boolean datagramExpected, int id) - throws IOException - { - byte[] ba = new byte[100]; - DatagramPacket p = new DatagramPacket(ba, ba.length); - try { - mc.receive(p); - int recvId = Integer.parseInt( - new String(p.getData(), 0, p.getLength(), "UTF-8")); - if (datagramExpected) { - if (recvId != id) - throw new RuntimeException("Unexpected id, got " + recvId - + ", expected: " + id); - out.printf("Received message as expected, %s\n", p.getAddress()); - } else { - throw new RuntimeException("Unexpected message received, " - + p.getAddress()); - } - } catch (SocketTimeoutException e) { - if (datagramExpected) - throw new RuntimeException("Expected message not received, " - + e.getMessage()); - else - out.printf("Message not received, as expected\n"); - } - } - - static void test(InetAddress group1, InetAddress group2) - throws IOException - { - try (MulticastSocket mc1 = new MulticastSocket(new InetSocketAddress(group1, 0)); - MulticastSocket mc2 = new MulticastSocket(new InetSocketAddress(group2, mc1.getLocalPort())); - DatagramSocket ds = new DatagramSocket()) { - - final int port = mc1.getLocalPort(); - out.printf("Using port: %d\n", port); - - mc1.setSoTimeout(TIMEOUT); - mc2.setSoTimeout(TIMEOUT); - int nextId = id; - byte[] msg = Integer.toString(nextId).getBytes("UTF-8"); - DatagramPacket p = new DatagramPacket(msg, msg.length); - p.setAddress(group1); - p.setPort(port); - - mc1.joinGroup(group1); - out.printf("mc1 joined the MC group: %s\n", group1); - mc2.joinGroup(group2); - out.printf("mc2 joined the MC group: %s\n", group2); - - out.printf("Sending datagram to: %s/%d\n", group1, port); - ds.send(p); - - // the packet should be received by mc1 only - receive(mc1, true, nextId); - receive(mc2, false, 0); - - nextId = ++id; - msg = Integer.toString(nextId).getBytes("UTF-8"); - p = new DatagramPacket(msg, msg.length); - p.setAddress(group2); - p.setPort(port); - - out.printf("Sending datagram to: %s/%d\n", group2, port); - ds.send(p); - - // the packet should be received by mc2 only - receive(mc2, true, nextId); - receive(mc1, false, 0); - - mc1.leaveGroup(group1); - mc2.leaveGroup(group2); - } - } - - public static void main(String args[]) throws IOException { - String os = System.getProperty("os.name"); - - if (!os.equals("Linux")) { - throw new SkippedException("This test should be run only on Linux"); - } else { - String osVersion = System.getProperty("os.version"); - String prefix = "3.10.0"; - if (osVersion.startsWith(prefix)) { - throw new SkippedException( - String.format("The behavior under test is known NOT to work on '%s' kernels", prefix)); - } - } - - NetworkConfiguration.printSystemConfiguration(System.out); - - if (NetworkConfiguration.probe() - .ip6MulticastInterfaces() - .findAny() - .isEmpty()) { - throw new SkippedException( - "No IPv6 interfaces that support multicast found"); - } - - InetAddress interfaceLocal1 = InetAddress.getByName("ff11::2.3.4.5"); - InetAddress interfaceLocal2 = InetAddress.getByName("ff11::6.7.8.9"); - test(interfaceLocal1, interfaceLocal2); - - InetAddress linkLocal1 = InetAddress.getByName("ff12::2.3.4.5"); - InetAddress linkLocal2 = InetAddress.getByName("ff12::6.7.8.9"); - test(linkLocal1, linkLocal2); - } -} diff --git a/test/jdk/java/nio/channels/DatagramChannel/PromiscuousIPv6.java b/test/jdk/java/nio/channels/DatagramChannel/PromiscuousIPv6.java deleted file mode 100644 index 38da9eba039..00000000000 --- a/test/jdk/java/nio/channels/DatagramChannel/PromiscuousIPv6.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - -/* - * @test - * @bug 8210493 - * @requires os.family == "linux" - * @library /test/lib - * @build jdk.test.lib.NetworkConfiguration - * PromiscuousIPv6 - * @run main PromiscuousIPv6 - * @key randomness - */ - -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.net.*; -import static java.net.StandardProtocolFamily.*; -import java.util.*; -import java.io.IOException; -import java.util.stream.Collectors; - -import jdk.test.lib.NetworkConfiguration; -import jtreg.SkippedException; - -/* - * This test was created as a copy of the Promiscuous test and adapted for - * IPv6 node-local and link-local multicast addresses on Linux. - */ -public class PromiscuousIPv6 { - - static final Random rand = new Random(); - - static final ProtocolFamily UNSPEC = () -> "UNSPEC"; - - /** - * Sends a datagram to the given multicast group - */ - static int sendDatagram(NetworkInterface nif, - InetAddress group, - int port) - throws IOException - { - ProtocolFamily family = (group instanceof Inet6Address) ? - StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; - DatagramChannel dc = DatagramChannel.open(family) - .setOption(StandardSocketOptions.IP_MULTICAST_IF, nif); - int id = rand.nextInt(); - byte[] msg = Integer.toString(id).getBytes("UTF-8"); - ByteBuffer buf = ByteBuffer.wrap(msg); - System.out.format("Send message -> group %s (id=0x%x)\n", - group.getHostAddress(), id); - dc.send(buf, new InetSocketAddress(group, port)); - dc.close(); - return id; - } - - /** - * Wait (with timeout) for datagram. The {@code datagramExpected} - * parameter indicates whether a datagram is expected, and if - * {@code true} then {@code id} is the identifier in the payload. - */ - static void receiveDatagram(DatagramChannel dc, - String name, - boolean datagramExpected, - int id) - throws IOException - { - System.out.println("Checking if received by " + name); - - Selector sel = Selector.open(); - dc.configureBlocking(false); - dc.register(sel, SelectionKey.OP_READ); - ByteBuffer buf = ByteBuffer.allocateDirect(100); - - try { - for (;;) { - System.out.println("Waiting to receive message"); - sel.select(5*1000); - SocketAddress sa = dc.receive(buf); - - // no datagram received - if (sa == null) { - if (datagramExpected) { - throw new RuntimeException("Expected message not received"); - } - System.out.println("No message received (correct)"); - return; - } - - // datagram received - - InetAddress sender = ((InetSocketAddress)sa).getAddress(); - buf.flip(); - byte[] bytes = new byte[buf.remaining()]; - buf.get(bytes); - String s = new String(bytes, "UTF-8"); - int receivedId = -1; - try { - receivedId = Integer.parseInt(s); - System.out.format("Received message from %s (id=0x%x)\n", - sender, receivedId); - } catch (NumberFormatException x) { - System.out.format("Received message from %s (msg=%s)\n", sender, s); - } - - if (!datagramExpected) { - if (receivedId == id) - throw new RuntimeException("Message not expected"); - System.out.println("Message ignored (has wrong id)"); - } else { - if (receivedId == id) { - System.out.println("Message expected"); - return; - } - System.out.println("Message ignored (wrong sender)"); - } - - sel.selectedKeys().clear(); - buf.rewind(); - } - } finally { - sel.close(); - } - } - - static void test(ProtocolFamily family, - NetworkInterface nif, - InetAddress group1, - InetAddress group2) - throws IOException - { - - System.out.format("%nTest family=%s%n", family.name()); - - DatagramChannel dc1 = (family == UNSPEC) ? - DatagramChannel.open() : DatagramChannel.open(family); - DatagramChannel dc2 = (family == UNSPEC) ? - DatagramChannel.open() : DatagramChannel.open(family); - - try { - dc1.setOption(StandardSocketOptions.SO_REUSEADDR, true); - dc2.setOption(StandardSocketOptions.SO_REUSEADDR, true); - - dc1.bind(new InetSocketAddress(group1, 0)); - int port = dc1.socket().getLocalPort(); - dc2.bind(new InetSocketAddress(group2, port)); - - System.out.format("dc1 joining [%s]:%d @ %s\n", - group1.getHostAddress(), port, nif.getName()); - System.out.format("dc2 joining [%s]:%d @ %s\n", - group2.getHostAddress(), port, nif.getName()); - - dc1.join(group1, nif); - dc2.join(group2, nif); - - int id = sendDatagram(nif, group1, port); - - receiveDatagram(dc1, "dc1", true, id); - receiveDatagram(dc2, "dc2", false, id); - - id = sendDatagram(nif, group2, port); - - receiveDatagram(dc1, "dc1", false, id); - receiveDatagram(dc2, "dc2", true, id); - - } finally { - dc1.close(); - dc2.close(); - } - } - - public static void main(String[] args) throws IOException { - - String os = System.getProperty("os.name"); - - if (!os.equals("Linux")) { - throw new SkippedException("This test should be run only on Linux"); - } else { - String osVersion = System.getProperty("os.version"); - String prefix = "3.10.0"; - if (osVersion.startsWith(prefix)) { - throw new SkippedException( - String.format("The behavior under test is known NOT to work on '%s' kernels", prefix)); - } - } - - NetworkConfiguration.printSystemConfiguration(System.out); - - InetAddress interfaceLocal1 = InetAddress.getByName("ff11::2.3.4.5"); - InetAddress interfaceLocal2 = InetAddress.getByName("ff11::6.7.8.9"); - - InetAddress linkLocal1 = InetAddress.getByName("ff12::2.3.4.5"); - InetAddress linkLocal2 = InetAddress.getByName("ff12::6.7.8.9"); - - // get local network configuration to use - NetworkConfiguration config = NetworkConfiguration.probe(); - boolean foundAtLeastOne = false; - for (NetworkInterface nif: config.ip6MulticastInterfaces() - .collect(Collectors.toList())) { - foundAtLeastOne = true; - test(INET6, nif, interfaceLocal1, interfaceLocal2); - test(INET6, nif, linkLocal1, linkLocal2); - } - if (!foundAtLeastOne) { - throw new SkippedException( - "No IPv6 interfaces that support multicast found"); - } - } -} From 516a3b3ec11e7af8a0620b87e8e0d29f9fb38f05 Mon Sep 17 00:00:00 2001 From: Doug Simon Date: Fri, 14 Dec 2018 17:32:16 -0800 Subject: [PATCH 086/174] 8215319: jck lang/INTF/intf049/intf04901 fails in Graal as JIT mode with -Xcomp and AOTed Graal Reviewed-by: iveresov, never, dlong --- .../org/graalvm/compiler/java/BytecodeParser.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java index 482d12a5183..48adfc457a4 100644 --- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java +++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.java/src/org/graalvm/compiler/java/BytecodeParser.java @@ -4195,7 +4195,6 @@ public class BytecodeParser implements GraphBuilderContext { handleIllegalNewInstance(resolvedType); return; } - maybeEagerlyInitialize(resolvedType); ClassInitializationPlugin classInitializationPlugin = graphBuilderConfig.getPlugins().getClassInitializationPlugin(); @@ -4509,7 +4508,6 @@ public class BytecodeParser implements GraphBuilderContext { } ResolvedJavaType holder = resolvedField.getDeclaringClass(); - maybeEagerlyInitialize(holder); ClassInitializationPlugin classInitializationPlugin = this.graphBuilderConfig.getPlugins().getClassInitializationPlugin(); if (classInitializationPlugin != null) { classInitializationPlugin.apply(this, holder, this::createCurrentFrameState); @@ -4545,16 +4543,20 @@ public class BytecodeParser implements GraphBuilderContext { private ResolvedJavaField resolveStaticFieldAccess(JavaField field, ValueNode value) { if (field instanceof ResolvedJavaField) { ResolvedJavaField resolvedField = (ResolvedJavaField) field; - if (resolvedField.getDeclaringClass().isInitialized() || graphBuilderConfig.getPlugins().getClassInitializationPlugin() != null) { + ResolvedJavaType resolvedType = resolvedField.getDeclaringClass(); + maybeEagerlyInitialize(resolvedType); + + if (resolvedType.isInitialized() || graphBuilderConfig.getPlugins().getClassInitializationPlugin() != null) { return resolvedField; } + /* * Static fields have initialization semantics but may be safely accessed under certain * conditions while the class is being initialized. Executing in the clinit or init of - * classes which are subtypes of the field holder are sure to be running in a context - * where the access is safe. + * subclasses (but not implementers) of the field holder are sure to be running in a + * context where the access is safe. */ - if (resolvedField.getDeclaringClass().isAssignableFrom(method.getDeclaringClass())) { + if (!resolvedType.isInterface() && resolvedType.isAssignableFrom(method.getDeclaringClass())) { if (method.isClassInitializer() || method.isConstructor()) { return resolvedField; } @@ -4588,7 +4590,6 @@ public class BytecodeParser implements GraphBuilderContext { ClassInitializationPlugin classInitializationPlugin = this.graphBuilderConfig.getPlugins().getClassInitializationPlugin(); ResolvedJavaType holder = resolvedField.getDeclaringClass(); - maybeEagerlyInitialize(holder); if (classInitializationPlugin != null) { Supplier stateBefore = () -> { JavaKind[] pushedSlotKinds = {field.getJavaKind()}; From e44207a9f6741c54240f0b90b9b7d57cd35eb0c7 Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Fri, 14 Dec 2018 17:51:02 -0800 Subject: [PATCH 087/174] 8213782: NullPointerException in sun.security.ssl.OutputRecord.changeWriteCiphers Reviewed-by: ascarpino --- .../sun/security/ssl/ChangeCipherSpec.java | 18 +++++ .../classes/sun/security/ssl/Finished.java | 73 ++++++++++++++----- .../classes/sun/security/ssl/KeyUpdate.java | 18 +++++ .../classes/sun/security/ssl/ServerHello.java | 60 ++++++++++++--- 4 files changed, 140 insertions(+), 29 deletions(-) diff --git a/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java b/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java index 937859f8c98..2983cf615ab 100644 --- a/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java +++ b/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java @@ -105,6 +105,14 @@ final class ChangeCipherSpec { throw new SSLException("Algorithm missing: ", gse); } + if (writeCipher == null) { + hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + ncs + + ") and protocol version (" + hc.negotiatedProtocol + ")"); + + return null; + } + if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine("Produced ChangeCipherSpec message"); } @@ -195,6 +203,16 @@ final class ChangeCipherSpec { // unlikely throw new SSLException("Algorithm missing: ", gse); } + + if (readCipher == null) { + hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + hc.negotiatedCipherSuite + + ") and protocol version (" + hc.negotiatedProtocol + + ")"); + + return; + } + tc.inputRecord.changeReadCiphers(readCipher); } else { throw new UnsupportedOperationException("Not supported."); diff --git a/src/java.base/share/classes/sun/security/ssl/Finished.java b/src/java.base/share/classes/sun/security/ssl/Finished.java index 351a6b92d49..47a071027b4 100644 --- a/src/java.base/share/classes/sun/security/ssl/Finished.java +++ b/src/java.base/share/classes/sun/security/ssl/Finished.java @@ -118,7 +118,7 @@ final class Finished { } catch (IOException ioe) { context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Failed to generate verify_data", ioe); - return; // make the compiler happy + return; } if (!MessageDigest.isEqual(myVerifyData, verifyData)) { context.conContext.fatal(Alert.ILLEGAL_PARAMETER, @@ -681,7 +681,7 @@ final class Finished { // unlikely chc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return null; // make the compiler happy + return null; } SSLTrafficKeyDerivation kdg = @@ -691,7 +691,7 @@ final class Finished { chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return null; // make the compiler happy + return null; } try { @@ -713,6 +713,15 @@ final class Finished { chc.negotiatedProtocol, writeKey, writeIv, chc.sslContext.getSecureRandom()); + if (writeCipher == null) { + chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + chc.negotiatedCipherSuite + + ") and protocol version (" + chc.negotiatedProtocol + + ")"); + + return null; + } + chc.baseWriteSecret = writeSecret; chc.conContext.outputRecord.changeWriteCiphers( writeCipher, false); @@ -720,15 +729,16 @@ final class Finished { } catch (GeneralSecurityException gse) { chc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return null; // make the compiler happy + return null; } // The resumption master secret is stored in the session so // it can be used after the handshake is completed. SSLSecretDerivation sd = ((SSLSecretDerivation) kd).forContext(chc); SecretKey resumptionMasterSecret = sd.deriveKey( - "TlsResumptionMasterSecret", null); - chc.handshakeSession.setResumptionMasterSecret(resumptionMasterSecret); + "TlsResumptionMasterSecret", null); + chc.handshakeSession.setResumptionMasterSecret( + resumptionMasterSecret); chc.conContext.conSession = chc.handshakeSession.finish(); chc.conContext.protocolVersion = chc.negotiatedProtocol; @@ -764,7 +774,7 @@ final class Finished { // unlikely shc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return null; // make the compiler happy + return null; } SSLTrafficKeyDerivation kdg = @@ -774,7 +784,7 @@ final class Finished { shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return null; // make the compiler happy + return null; } // derive salt secret @@ -810,6 +820,15 @@ final class Finished { shc.negotiatedProtocol, writeKey, writeIv, shc.sslContext.getSecureRandom()); + if (writeCipher == null) { + shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + shc.negotiatedCipherSuite + + ") and protocol version (" + shc.negotiatedProtocol + + ")"); + + return null; + } + shc.baseWriteSecret = writeSecret; shc.conContext.outputRecord.changeWriteCiphers( writeCipher, false); @@ -819,7 +838,7 @@ final class Finished { } catch (GeneralSecurityException gse) { shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return null; // make the compiler happy + return null; } /* @@ -894,7 +913,7 @@ final class Finished { // unlikely chc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return; // make the compiler happy + return; } SSLTrafficKeyDerivation kdg = @@ -904,7 +923,7 @@ final class Finished { chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return; // make the compiler happy + return; } // save the session @@ -947,6 +966,15 @@ final class Finished { chc.negotiatedProtocol, readKey, readIv, chc.sslContext.getSecureRandom()); + if (readCipher == null) { + chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + chc.negotiatedCipherSuite + + ") and protocol version (" + chc.negotiatedProtocol + + ")"); + + return; + } + chc.baseReadSecret = readSecret; chc.conContext.inputRecord.changeReadCiphers(readCipher); @@ -955,7 +983,7 @@ final class Finished { } catch (GeneralSecurityException gse) { chc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return; // make the compiler happy + return; } // @@ -1005,7 +1033,7 @@ final class Finished { // unlikely shc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return; // make the compiler happy + return; } SSLTrafficKeyDerivation kdg = @@ -1015,7 +1043,7 @@ final class Finished { shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return; // make the compiler happy + return; } // save the session @@ -1044,20 +1072,31 @@ final class Finished { shc.negotiatedProtocol, readKey, readIv, shc.sslContext.getSecureRandom()); + if (readCipher == null) { + shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + shc.negotiatedCipherSuite + + ") and protocol version (" + shc.negotiatedProtocol + + ")"); + + return; + } + shc.baseReadSecret = readSecret; shc.conContext.inputRecord.changeReadCiphers(readCipher); // The resumption master secret is stored in the session so // it can be used after the handshake is completed. shc.handshakeHash.update(); - SSLSecretDerivation sd = ((SSLSecretDerivation)kd).forContext(shc); + SSLSecretDerivation sd = + ((SSLSecretDerivation)kd).forContext(shc); SecretKey resumptionMasterSecret = sd.deriveKey( "TlsResumptionMasterSecret", null); - shc.handshakeSession.setResumptionMasterSecret(resumptionMasterSecret); + shc.handshakeSession.setResumptionMasterSecret( + resumptionMasterSecret); } catch (GeneralSecurityException gse) { shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return; // make the compiler happy + return; } // update connection context diff --git a/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java b/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java index b24d166f361..8477e69db48 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java @@ -223,6 +223,16 @@ final class KeyUpdate { Authenticator.valueOf(hc.conContext.protocolVersion), hc.conContext.protocolVersion, key, ivSpec, hc.sslContext.getSecureRandom()); + + if (rc == null) { + hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + hc.negotiatedCipherSuite + + ") and protocol version (" + hc.negotiatedProtocol + + ")"); + + return; + } + rc.baseSecret = nplus1; hc.conContext.inputRecord.changeReadCiphers(rc); if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { @@ -303,6 +313,14 @@ final class KeyUpdate { return null; } + if (wc == null) { + hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + hc.negotiatedCipherSuite + + ") and protocol version (" + hc.negotiatedProtocol + ")"); + + return null; + } + // Output the handshake message and change the write cipher. // // The KeyUpdate handshake message SHALL be delivered in the diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHello.java b/src/java.base/share/classes/sun/security/ssl/ServerHello.java index ca764f5129a..a8a38a9dfb8 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHello.java @@ -296,7 +296,7 @@ final class ServerHello { shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - return null; // make the compiler happy + return null; } shc.negotiatedCipherSuite = credentials.cipherSuite; shc.handshakeKeyExchange = credentials.keyExchange; @@ -461,7 +461,7 @@ final class ServerHello { shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - return null; // make the compiler happy. + return null; } private static final class KeyExchangeProperties { @@ -526,7 +526,7 @@ final class ServerHello { if (cipherSuite == null) { shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - return null; // make the compiler happy + return null; } shc.negotiatedCipherSuite = cipherSuite; shc.handshakeSession.setSuite(cipherSuite); @@ -594,7 +594,7 @@ final class ServerHello { // unlikely shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not negotiated key shares"); - return null; // make the compiler happy + return null; } SSLKeyDerivation handshakeKD = ke.createKeyDerivation(shc); @@ -608,7 +608,7 @@ final class ServerHello { shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return null; // make the compiler happy + return null; } SSLKeyDerivation kd = @@ -636,7 +636,16 @@ final class ServerHello { // unlikely shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return null; // make the compiler happy + return null; + } + + if (readCipher == null) { + shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + shc.negotiatedCipherSuite + + ") and protocol version (" + shc.negotiatedProtocol + + ")"); + + return null; } shc.baseReadSecret = readSecret; @@ -664,7 +673,16 @@ final class ServerHello { // unlikely shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return null; // make the compiler happy + return null; + } + + if (writeCipher == null) { + shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + shc.negotiatedCipherSuite + + ") and protocol version (" + shc.negotiatedProtocol + + ")"); + + return null; } shc.baseWriteSecret = writeSecret; @@ -748,7 +766,7 @@ final class ServerHello { if (cipherSuite == null) { shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common for hello retry request"); - return null; // make the compiler happy + return null; } ServerHelloMessage hhrm = new ServerHelloMessage(shc, @@ -1244,7 +1262,7 @@ final class ServerHello { // unlikely chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not negotiated key shares"); - return; // make the compiler happy + return; } SSLKeyDerivation handshakeKD = ke.createKeyDerivation(chc); @@ -1257,7 +1275,7 @@ final class ServerHello { chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return; // make the compiler happy + return; } SSLKeyDerivation secretKD = @@ -1286,7 +1304,16 @@ final class ServerHello { // unlikely chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return; // make the compiler happy + return; + } + + if (readCipher == null) { + chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + chc.negotiatedCipherSuite + + ") and protocol version (" + chc.negotiatedProtocol + + ")"); + + return; } chc.baseReadSecret = readSecret; @@ -1314,7 +1341,16 @@ final class ServerHello { // unlikely chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return; // make the compiler happy + return; + } + + if (writeCipher == null) { + chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + "Illegal cipher suite (" + chc.negotiatedCipherSuite + + ") and protocol version (" + chc.negotiatedProtocol + + ")"); + + return; } chc.baseWriteSecret = writeSecret; From 3933c8477bf3712a5a391e3a5416dc0d50d9cbe8 Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Fri, 14 Dec 2018 19:39:39 -0800 Subject: [PATCH 088/174] 8214339: SSLSocketImpl erroneously wraps SocketException Reviewed-by: ascarpino, jnimeh --- .../share/classes/sun/security/ssl/Alert.java | 16 +- .../sun/security/ssl/KeyShareExtension.java | 4 +- .../security/ssl/PreSharedKeyExtension.java | 43 +- .../sun/security/ssl/TransportContext.java | 8 + .../net/ssl/templates/SSLContextTemplate.java | 518 ++++++++++++++++++ .../SSLSocketImpl/SSLExceptionForIOIssue.java | 162 ++++++ 6 files changed, 726 insertions(+), 25 deletions(-) create mode 100644 test/jdk/javax/net/ssl/templates/SSLContextTemplate.java create mode 100644 test/jdk/sun/security/ssl/SSLSocketImpl/SSLExceptionForIOIssue.java diff --git a/src/java.base/share/classes/sun/security/ssl/Alert.java b/src/java.base/share/classes/sun/security/ssl/Alert.java index a8370822e14..09bcfd5afc7 100644 --- a/src/java.base/share/classes/sun/security/ssl/Alert.java +++ b/src/java.base/share/classes/sun/security/ssl/Alert.java @@ -122,11 +122,17 @@ enum Alert { reason = (cause != null) ? cause.getMessage() : ""; } - SSLException ssle = (this == UNEXPECTED_MESSAGE) ? - new SSLProtocolException(reason) : - (handshakeOnly ? - new SSLHandshakeException(reason) : - new SSLException(reason)); + SSLException ssle; + if ((cause != null) && (cause instanceof IOException)) { + ssle = new SSLException(reason); + } else if ((this == UNEXPECTED_MESSAGE)) { + ssle = new SSLProtocolException(reason); + } else if (handshakeOnly) { + ssle = new SSLHandshakeException(reason); + } else { + ssle = new SSLException(reason); + } + if (cause != null) { ssle.initCause(cause); } diff --git a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java index ac44f2af50e..83dab2cdf3c 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java @@ -823,8 +823,8 @@ final class KeyShareExtension { } if (selectedGroup == null) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, - new IOException("No common named group")); + shc.conContext.fatal( + Alert.UNEXPECTED_MESSAGE, "No common named group"); return null; // make the complier happy } diff --git a/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java b/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java index 413b934038a..dc313a8cc72 100644 --- a/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java @@ -171,7 +171,7 @@ final class PreSharedKeyExtension { int getIdsEncodedLength() { int idEncodedLength = 0; - for(PskIdentity curId : identities) { + for (PskIdentity curId : identities) { idEncodedLength += curId.getEncodedLength(); } @@ -194,7 +194,7 @@ final class PreSharedKeyExtension { byte[] buffer = new byte[encodedLength]; ByteBuffer m = ByteBuffer.wrap(buffer); Record.putInt16(m, idsEncodedLength); - for(PskIdentity curId : identities) { + for (PskIdentity curId : identities) { curId.writeEncoded(m); } Record.putInt16(m, bindersEncodedLength); @@ -538,12 +538,12 @@ final class PreSharedKeyExtension { } SecretKey psk = pskOpt.get(); - SecretKey binderKey = deriveBinderKey(psk, session); + SecretKey binderKey = deriveBinderKey(shc, psk, session); byte[] computedBinder = - computeBinder(binderKey, session, pskBinderHash); + computeBinder(shc, binderKey, session, pskBinderHash); if (!Arrays.equals(binder, computedBinder)) { shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, - "Incorect PSK binder value"); + "Incorect PSK binder value"); } } @@ -687,13 +687,14 @@ final class PreSharedKeyExtension { ageMillis + chc.resumingSession.getTicketAgeAdd(); identities.add(new PskIdentity(chc.pskIdentity, obfuscatedAge)); - SecretKey binderKey = deriveBinderKey(psk, chc.resumingSession); + SecretKey binderKey = + deriveBinderKey(chc, psk, chc.resumingSession); ClientHelloMessage clientHello = (ClientHelloMessage)message; CHPreSharedKeySpec pskPrototype = createPskPrototype( chc.resumingSession.getSuite().hashAlg.hashLength, identities); HandshakeHash pskBinderHash = chc.handshakeHash.copy(); - byte[] binder = computeBinder(binderKey, pskBinderHash, + byte[] binder = computeBinder(chc, binderKey, pskBinderHash, chc.resumingSession, chc, clientHello, pskPrototype); List binders = new ArrayList<>(); @@ -717,7 +718,8 @@ final class PreSharedKeyExtension { } } - private static byte[] computeBinder(SecretKey binderKey, + private static byte[] computeBinder( + HandshakeContext context, SecretKey binderKey, SSLSessionImpl session, HandshakeHash pskBinderHash) throws IOException { @@ -726,10 +728,11 @@ final class PreSharedKeyExtension { pskBinderHash.update(); byte[] digest = pskBinderHash.digest(); - return computeBinder(binderKey, session, digest); + return computeBinder(context, binderKey, session, digest); } - private static byte[] computeBinder(SecretKey binderKey, + private static byte[] computeBinder( + HandshakeContext context, SecretKey binderKey, HandshakeHash hash, SSLSessionImpl session, HandshakeContext ctx, ClientHello.ClientHelloMessage hello, CHPreSharedKeySpec pskPrototype) throws IOException { @@ -745,10 +748,11 @@ final class PreSharedKeyExtension { hash.update(); byte[] digest = hash.digest(); - return computeBinder(binderKey, session, digest); + return computeBinder(context, binderKey, session, digest); } - private static byte[] computeBinder(SecretKey binderKey, + private static byte[] computeBinder(HandshakeContext context, + SecretKey binderKey, SSLSessionImpl session, byte[] digest) throws IOException { try { CipherSuite.HashAlg hashAlg = session.getSuite().hashAlg; @@ -766,15 +770,17 @@ final class PreSharedKeyExtension { hmac.init(finishedKey); return hmac.doFinal(digest); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { - throw new IOException(ex); + context.conContext.fatal(Alert.INTERNAL_ERROR, ex); + return null; // fatal() always throws, make the compiler happy. } } catch (GeneralSecurityException ex) { - throw new IOException(ex); + context.conContext.fatal(Alert.INTERNAL_ERROR, ex); + return null; // fatal() always throws, make the compiler happy. } } - private static SecretKey deriveBinderKey(SecretKey psk, - SSLSessionImpl session) throws IOException { + private static SecretKey deriveBinderKey(HandshakeContext context, + SecretKey psk, SSLSessionImpl session) throws IOException { try { CipherSuite.HashAlg hashAlg = session.getSuite().hashAlg; HKDF hkdf = new HKDF(hashAlg.name); @@ -788,7 +794,8 @@ final class PreSharedKeyExtension { return hkdf.expand(earlySecret, hkdfInfo, hashAlg.hashLength, "TlsBinderKey"); } catch (GeneralSecurityException ex) { - throw new IOException(ex); + context.conContext.fatal(Alert.INTERNAL_ERROR, ex); + return null; // fatal() always throws, make the compiler happy. } } @@ -844,7 +851,7 @@ final class PreSharedKeyExtension { if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine( - "Resuming session: ", chc.resumingSession); + "Resuming session: ", chc.resumingSession); } } } diff --git a/src/java.base/share/classes/sun/security/ssl/TransportContext.java b/src/java.base/share/classes/sun/security/ssl/TransportContext.java index 09aed6802e6..811610daa33 100644 --- a/src/java.base/share/classes/sun/security/ssl/TransportContext.java +++ b/src/java.base/share/classes/sun/security/ssl/TransportContext.java @@ -328,6 +328,8 @@ class TransportContext implements ConnectionContext { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { SSLLogger.warning("Fatal: input record closure failed", ioe); } + + closeReason.addSuppressed(ioe); } // invalidate the session @@ -353,6 +355,8 @@ class TransportContext implements ConnectionContext { SSLLogger.warning( "Fatal: failed to send fatal alert " + alert, ioe); } + + closeReason.addSuppressed(ioe); } } @@ -363,6 +367,8 @@ class TransportContext implements ConnectionContext { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { SSLLogger.warning("Fatal: output record closure failed", ioe); } + + closeReason.addSuppressed(ioe); } // terminate the handshake context @@ -377,6 +383,8 @@ class TransportContext implements ConnectionContext { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { SSLLogger.warning("Fatal: transport closure failed", ioe); } + + closeReason.addSuppressed(ioe); } finally { isBroken = true; } diff --git a/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java b/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java new file mode 100644 index 00000000000..65e599bc251 --- /dev/null +++ b/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java @@ -0,0 +1,518 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// Please run in othervm mode. SunJSSE does not support dynamic system +// properties, no way to re-use system properties in samevm/agentvm mode. +// + +import java.io.ByteArrayInputStream; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +/** + * SSLContext template to speed up JSSE tests. + */ +public interface SSLContextTemplate { + /* + * Create an instance of SSLContext for client use. + */ + default SSLContext createClientSSLContext() throws Exception { + return createSSLContext(trustedCertStrs, + endEntityCertStrs, endEntityPrivateKeys, + endEntityPrivateKeyAlgs, + endEntityPrivateKeyNames, + getClientContextParameters()); + } + + /* + * Create an instance of SSLContext for server use. + */ + default SSLContext createServerSSLContext() throws Exception { + return createSSLContext(trustedCertStrs, + endEntityCertStrs, endEntityPrivateKeys, + endEntityPrivateKeyAlgs, + endEntityPrivateKeyNames, + getServerContextParameters()); + } + + /* + * The parameters used to configure SSLContext. + */ + static final class ContextParameters { + final String contextProtocol; + final String tmAlgorithm; + final String kmAlgorithm; + + ContextParameters(String contextProtocol, + String tmAlgorithm, String kmAlgorithm) { + + this.contextProtocol = contextProtocol; + this.tmAlgorithm = tmAlgorithm; + this.kmAlgorithm = kmAlgorithm; + } + } + + /* + * Get the client side parameters of SSLContext. + */ + default ContextParameters getClientContextParameters() { + return new ContextParameters("TLS", "PKIX", "NewSunX509"); + } + + /* + * Get the server side parameters of SSLContext. + */ + default ContextParameters getServerContextParameters() { + return new ContextParameters("TLS", "PKIX", "NewSunX509"); + } + + /* + * ======================================= + * Certificates and keys used in the test. + */ + // Trusted certificates. + final static String[] trustedCertStrs = { + // SHA256withECDSA, curve prime256v1 + // Validity + // Not Before: May 22 07:18:16 2018 GMT + // Not After : May 17 07:18:16 2038 GMT + // Subject Key Identifier: + // 60:CF:BD:73:FF:FA:1A:30:D2:A4:EC:D3:49:71:46:EF:1A:35:A0:86 + "-----BEGIN CERTIFICATE-----\n" + + "MIIBvjCCAWOgAwIBAgIJAIvFG6GbTroCMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTAeFw0xODA1MjIwNzE4MTZaFw0zODA1MTcwNzE4MTZaMDsxCzAJBgNVBAYTAlVT\n" + + "MQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZjZTBZ\n" + + "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABBz1WeVb6gM2mh85z3QlvaB/l11b5h0v\n" + + "LIzmkC3DKlVukZT+ltH2Eq1oEkpXuf7QmbM0ibrUgtjsWH3mULfmcWmjUDBOMB0G\n" + + "A1UdDgQWBBRgz71z//oaMNKk7NNJcUbvGjWghjAfBgNVHSMEGDAWgBRgz71z//oa\n" + + "MNKk7NNJcUbvGjWghjAMBgNVHRMEBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQCG\n" + + "6wluh1r2/T6L31mZXRKf9JxeSf9pIzoLj+8xQeUChQIhAJ09wAi1kV8yePLh2FD9\n" + + "2YEHlSQUAbwwqCDEVB5KxaqP\n" + + "-----END CERTIFICATE-----", + // -----BEGIN PRIVATE KEY----- + // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg/HcHdoLJCdq3haVd + // XZTSKP00YzM3xX97l98vGL/RI1KhRANCAAQc9VnlW+oDNpofOc90Jb2gf5ddW+Yd + // LyyM5pAtwypVbpGU/pbR9hKtaBJKV7n+0JmzNIm61ILY7Fh95lC35nFp + // -----END PRIVATE KEY----- + + // SHA256withRSA, 2048 bits + // Validity + // Not Before: May 22 07:18:16 2018 GMT + // Not After : May 17 07:18:16 2038 GMT + // Subject Key Identifier: + // 0D:DD:93:C9:FE:4B:BD:35:B7:E8:99:78:90:FB:DB:5A:3D:DB:15:4C + "-----BEGIN CERTIFICATE-----\n" + + "MIIDSTCCAjGgAwIBAgIJAI4ZF3iy8zG+MA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + + "BAYTAlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2Vy\n" + + "aXZjZTAeFw0xODA1MjIwNzE4MTZaFw0zODA1MTcwNzE4MTZaMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALpMcY7aWieXDEM1/YJf\n" + + "JW27b4nRIFZyEYhEloyGsKTuQiiQjc8cqRZFNXe2vwziDB4IyTEl0Hjl5QF6ZaQE\n" + + "huPzzwvQm1pv64KrRXrmj3FisQK8B5OWLty9xp6xDqsaMRoyObLK+oIb20T5fSlE\n" + + "evmo1vYjnh8CX0Yzx5Gr5ye6YSEHQvYOWEws8ad17OlyToR2KMeC8w4qo6rs59pW\n" + + "g7Mxn9vo22ImDzrtAbTbXbCias3xlE0Bp0h5luyf+5U4UgksoL9B9r2oP4GrLNEV\n" + + "oJk57t8lwaR0upiv3CnS8LcJELpegZub5ggqLY8ZPYFQPjlK6IzLOm6rXPgZiZ3m\n" + + "RL0CAwEAAaNQME4wHQYDVR0OBBYEFA3dk8n+S701t+iZeJD721o92xVMMB8GA1Ud\n" + + "IwQYMBaAFA3dk8n+S701t+iZeJD721o92xVMMAwGA1UdEwQFMAMBAf8wDQYJKoZI\n" + + "hvcNAQELBQADggEBAJTRC3rKUUhVH07/1+stUungSYgpM08dY4utJq0BDk36BbmO\n" + + "0AnLDMbkwFdHEoqF6hQIfpm7SQTmXk0Fss6Eejm8ynYr6+EXiRAsaXOGOBCzF918\n" + + "/RuKOzqABfgSU4UBKECLM5bMfQTL60qx+HdbdVIpnikHZOFfmjCDVxoHsGyXc1LW\n" + + "Jhkht8IGOgc4PMGvyzTtRFjz01kvrVQZ75aN2E0GQv6dCxaEY0i3ypSzjUWAKqDh\n" + + "3e2OLwUSvumcdaxyCdZAOUsN6pDBQ+8VRG7KxnlRlY1SMEk46QgQYLbPDe/+W/yH\n" + + "ca4PejicPeh+9xRAwoTpiE2gulfT7Lm+fVM7Ruc=\n" + + "-----END CERTIFICATE-----", + + // -----BEGIN PRIVATE KEY----- + // MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC6THGO2lonlwxD + // Nf2CXyVtu2+J0SBWchGIRJaMhrCk7kIokI3PHKkWRTV3tr8M4gweCMkxJdB45eUB + // emWkBIbj888L0Jtab+uCq0V65o9xYrECvAeTli7cvcaesQ6rGjEaMjmyyvqCG9tE + // +X0pRHr5qNb2I54fAl9GM8eRq+cnumEhB0L2DlhMLPGndezpck6EdijHgvMOKqOq + // 7OfaVoOzMZ/b6NtiJg867QG0212womrN8ZRNAadIeZbsn/uVOFIJLKC/Qfa9qD+B + // qyzRFaCZOe7fJcGkdLqYr9wp0vC3CRC6XoGbm+YIKi2PGT2BUD45SuiMyzpuq1z4 + // GYmd5kS9AgMBAAECggEAFHSoU2MuWwJ+2jJnb5U66t2V1bAcuOE1g5zkWvG/G5z9 + // rq6Qo5kmB8f5ovdx6tw3MGUOklLwnRXBG3RxDJ1iokz3AvkY1clMNsDPlDsUrQKF + // JSO4QUBQTPSZhnsyfR8XHSU+qJ8Y+ohMfzpVv95BEoCzebtXdVgxVegBlcEmVHo2 + // kMmkRN+bYNsr8eb2r+b0EpyumS39ZgKYh09+cFb78y3T6IFMGcVJTP6nlGBFkmA/ + // 25pYeCF2tSki08qtMJZQAvKfw0Kviibk7ZxRbJqmc7B1yfnOEHP6ftjuvKl2+RP/ + // +5P5f8CfIP6gtA0LwSzAqQX/hfIKrGV5j0pCqrD0kQKBgQDeNR6Xi4sXVq79lihO + // a1bSeV7r8yoQrS8x951uO+ox+UIZ1MsAULadl7zB/P0er92p198I9M/0Jth3KBuS + // zj45mucvpiiGvmQlMKMEfNq4nN7WHOu55kufPswQB2mR4J3xmwI+4fM/nl1zc82h + // De8JSazRldJXNhfx0RGFPmgzbwKBgQDWoVXrXLbCAn41oVnWB8vwY9wjt92ztDqJ + // HMFA/SUohjePep9UDq6ooHyAf/Lz6oE5NgeVpPfTDkgvrCFVKnaWdwALbYoKXT2W + // 9FlyJox6eQzrtHAacj3HJooXWuXlphKSizntfxj3LtMR9BmrmRJOfK+SxNOVJzW2 + // +MowT20EkwKBgHmpB8jdZBgxI7o//m2BI5Y1UZ1KE5vx1kc7VXzHXSBjYqeV9FeF + // 2ZZLP9POWh/1Fh4pzTmwIDODGT2UPhSQy0zq3O0fwkyT7WzXRknsuiwd53u/dejg + // iEL2NPAJvulZ2+AuiHo5Z99LK8tMeidV46xoJDDUIMgTG+UQHNGhK5gNAoGAZn/S + // Cn7SgMC0CWSvBHnguULXZO9wH1wZAFYNLL44OqwuaIUFBh2k578M9kkke7woTmwx + // HxQTjmWpr6qimIuY6q6WBN8hJ2Xz/d1fwhYKzIp20zHuv5KDUlJjbFfqpsuy3u1C + // kts5zwI7pr1ObRbDGVyOdKcu7HI3QtR5qqyjwaUCgYABo7Wq6oHva/9V34+G3Goh + // 63bYGUnRw2l5BD11yhQv8XzGGZFqZVincD8gltNThB0Dc/BI+qu3ky4YdgdZJZ7K + // z51GQGtaHEbrHS5caV79yQ8QGY5mUVH3E+VXSxuIqb6pZq2DH4sTAEFHyncddmOH + // zoXBInYwRG9KE/Bw5elhUw== + // -----END PRIVATE KEY----- + + + // SHA256withDSA, 2048 bits + // Validity + // Not Before: May 22 07:18:18 2018 GMT + // Not After : May 17 07:18:18 2038 GMT + // Subject Key Identifier: + // 76:66:9E:F7:3B:DD:45:E5:3B:D9:72:3C:3F:F0:54:39:86:31:26:53 + "-----BEGIN CERTIFICATE-----\n" + + "MIIErjCCBFSgAwIBAgIJAOktYLNCbr02MAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" + + "EwJVUzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2\n" + + "Y2UwHhcNMTgwNTIyMDcxODE4WhcNMzgwNTE3MDcxODE4WjA7MQswCQYDVQQGEwJV\n" + + "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Uw\n" + + "ggNHMIICOQYHKoZIzjgEATCCAiwCggEBAO5GyPhSm0ze3LSu+gicdULLj05iOfTL\n" + + "UvZQ29sYz41zmqrLBQbdKiHqgJu2Re9sgTb5suLNjF047TOLPnU3jhPtWm2X8Xzi\n" + + "VGIcHym/Q/MeZxStt/88seqroI3WOKzIML2GcrishT+lcGrtH36Tf1+ue2Snn3PS\n" + + "WyxygNqPjllP5uUjYmFLvAf4QLMldkd/D2VxcwsHjB8y5iUZsXezc/LEhRZS/02m\n" + + "ivqlRw3AMkq/OVe/ZtxFWsP0nsfxEGdZuaUFpppGfixxFvymrB3+J51cTt+pZBDq\n" + + "D2y0DYfc+88iCs4jwHTfcDIpLb538HBjBj2rEgtQESQmB0ooD/+wsPsCIQC1bYch\n" + + "gElNtDYL3FgpLgNSUYp7gIWv9ehaC7LO2z7biQKCAQBitvFOnDkUja8NAF7lDpOV\n" + + "b5ipQ8SicBLW3kQamxhyuyxgZyy/PojZ/oPorkqW/T/A0rhnG6MssEpAtdiwVB+c\n" + + "rBYGo3bcwmExJhdOJ6dYuKFppPWhCwKMHs9npK+lqBMl8l5j58xlcFeC7ZfGf8GY\n" + + "GkhFW0c44vEQhMMbac6ZTTP4mw+1t7xJfmDMlLEyIpTXaAAk8uoVLWzQWnR40sHi\n" + + "ybvS0u3JxQkb7/y8tOOZu8qlz/YOS7lQ6UxUGX27Ce1E0+agfPphetoRAlS1cezq\n" + + "Wa7r64Ga0nkj1kwkcRqjgTiJx0NwnUXr78VAXFhVF95+O3lfqhvdtEGtkhDGPg7N\n" + + "A4IBBgACggEBAMmSHQK0w2i+iqUjOPzn0yNEZrzepLlLeQ1tqtn0xnlv5vBAeefD\n" + + "Pm9dd3tZOjufVWP7hhEz8xPobb1CS4e3vuQiv5UBfhdPL3f3l9T7JMAKPH6C9Vve\n" + + "OQXE5eGqbjsySbcmseHoYUt1WCSnSda1opX8zchX04e7DhGfE2/L9flpYEoSt8lI\n" + + "vMNjgOwvKdW3yvPt1/eBBHYNFG5gWPv/Q5KoyCtHS03uqGm4rNc/wZTIEEfd66C+\n" + + "QRaUltjOaHmtwOdDHaNqwhYZSVOip+Mo+TfyzHFREcdHLapo7ZXqbdYkRGxRR3d+\n" + + "3DfHaraJO0OKoYlPkr3JMvM/MSGR9AnZOcejUDBOMB0GA1UdDgQWBBR2Zp73O91F\n" + + "5TvZcjw/8FQ5hjEmUzAfBgNVHSMEGDAWgBR2Zp73O91F5TvZcjw/8FQ5hjEmUzAM\n" + + "BgNVHRMEBTADAQH/MAsGCWCGSAFlAwQDAgNHADBEAiBzriYE41M2y9Hy5ppkL0Qn\n" + + "dIlNc8JhXT/PHW7GDtViagIgMko8Qoj9gDGPK3+O9E8DC3wGiiF9CObM4LN387ok\n" + + "J+g=\n" + + "-----END CERTIFICATE-----" + // -----BEGIN PRIVATE KEY----- + // MIICZQIBADCCAjkGByqGSM44BAEwggIsAoIBAQDuRsj4UptM3ty0rvoInHVCy49O + // Yjn0y1L2UNvbGM+Nc5qqywUG3Soh6oCbtkXvbIE2+bLizYxdOO0ziz51N44T7Vpt + // l/F84lRiHB8pv0PzHmcUrbf/PLHqq6CN1jisyDC9hnK4rIU/pXBq7R9+k39frntk + // p59z0lsscoDaj45ZT+blI2JhS7wH+ECzJXZHfw9lcXMLB4wfMuYlGbF3s3PyxIUW + // Uv9Npor6pUcNwDJKvzlXv2bcRVrD9J7H8RBnWbmlBaaaRn4scRb8pqwd/iedXE7f + // qWQQ6g9stA2H3PvPIgrOI8B033AyKS2+d/BwYwY9qxILUBEkJgdKKA//sLD7AiEA + // tW2HIYBJTbQ2C9xYKS4DUlGKe4CFr/XoWguyzts+24kCggEAYrbxTpw5FI2vDQBe + // 5Q6TlW+YqUPEonAS1t5EGpsYcrssYGcsvz6I2f6D6K5Klv0/wNK4ZxujLLBKQLXY + // sFQfnKwWBqN23MJhMSYXTienWLihaaT1oQsCjB7PZ6SvpagTJfJeY+fMZXBXgu2X + // xn/BmBpIRVtHOOLxEITDG2nOmU0z+JsPtbe8SX5gzJSxMiKU12gAJPLqFS1s0Fp0 + // eNLB4sm70tLtycUJG+/8vLTjmbvKpc/2Dku5UOlMVBl9uwntRNPmoHz6YXraEQJU + // tXHs6lmu6+uBmtJ5I9ZMJHEao4E4icdDcJ1F6+/FQFxYVRfefjt5X6ob3bRBrZIQ + // xj4OzQQjAiEAsceWOM8do4etxp2zgnoNXV8PUUyqWhz1+0srcKV7FR4= + // -----END PRIVATE KEY----- + }; + + // End entity certificate. + final static String[] endEntityCertStrs = { + // SHA256withECDSA, curve prime256v1 + // Validity + // Not Before: May 22 07:18:16 2018 GMT + // Not After : May 17 07:18:16 2038 GMT + // Authority Key Identifier: + // 60:CF:BD:73:FF:FA:1A:30:D2:A4:EC:D3:49:71:46:EF:1A:35:A0:86 + "-----BEGIN CERTIFICATE-----\n" + + "MIIBqjCCAVCgAwIBAgIJAPLY8qZjgNRAMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTAeFw0xODA1MjIwNzE4MTZaFw0zODA1MTcwNzE4MTZaMFUxCzAJBgNVBAYTAlVT\n" + + "MQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZjZTEY\n" + + "MBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD\n" + + "QgAEb+9n05qfXnfHUb0xtQJNS4JeSi6IjOfW5NqchvKnfJey9VkJzR7QHLuOESdf\n" + + "xlR7q8YIWgih3iWLGfB+wxHiOqMjMCEwHwYDVR0jBBgwFoAUYM+9c//6GjDSpOzT\n" + + "SXFG7xo1oIYwCgYIKoZIzj0EAwIDSAAwRQIgWpRegWXMheiD3qFdd8kMdrkLxRbq\n" + + "1zj8nQMEwFTUjjQCIQDRIrAjZX+YXHN9b0SoWWLPUq0HmiFIi8RwMnO//wJIGQ==\n" + + "-----END CERTIFICATE-----", + + // SHA256withRSA, 2048 bits + // Validity + // Not Before: May 22 07:18:16 2018 GMT + // Not After : May 17 07:18:16 2038 GMT + // Authority Key Identifier: + // 0D:DD:93:C9:FE:4B:BD:35:B7:E8:99:78:90:FB:DB:5A:3D:DB:15:4C + "-----BEGIN CERTIFICATE-----\n" + + "MIIDNjCCAh6gAwIBAgIJAO2+yPcFryUTMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + + "BAYTAlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2Vy\n" + + "aXZjZTAeFw0xODA1MjIwNzE4MTZaFw0zODA1MTcwNzE4MTZaMFUxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTEYMBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOC\n" + + "AQ8AMIIBCgKCAQEAszfBobWfZIp8AgC6PiWDDavP65mSvgCXUGxACbxVNAfkLhNR\n" + + "QOsHriRB3X1Q3nvO9PetC6wKlvE9jlnDDj7D+1j1r1CHO7ms1fq8rfcQYdkanDtu\n" + + "4AlHo8v+SSWX16MIXFRYDj2VVHmyPtgbltcg4zGAuwT746FdLI94uXjJjq1IOr/v\n" + + "0VIlwE5ORWH5Xc+5Tj+oFWK0E4a4GHDgtKKhn2m72hN56/GkPKGkguP5NRS1qYYV\n" + + "/EFkdyQMOV8J1M7HaicSft4OL6eKjTrgo93+kHk+tv0Dc6cpVBnalX3TorG8QI6B\n" + + "cHj1XQd78oAlAC+/jF4pc0mwi0un49kdK9gRfQIDAQABoyMwITAfBgNVHSMEGDAW\n" + + "gBQN3ZPJ/ku9NbfomXiQ+9taPdsVTDANBgkqhkiG9w0BAQsFAAOCAQEApXS0nKwm\n" + + "Kp8gpmO2yG1rpd1+2wBABiMU4JZaTqmma24DQ3RzyS+V2TeRb29dl5oTUEm98uc0\n" + + "GPZvhK8z5RFr4YE17dc04nI/VaNDCw4y1NALXGs+AHkjoPjLyGbWpi1S+gfq2sNB\n" + + "Ekkjp6COb/cb9yiFXOGVls7UOIjnVZVd0r7KaPFjZhYh82/f4PA/A1SnIKd1+nfH\n" + + "2yk7mSJNC7Z3qIVDL8MM/jBVwiC3uNe5GPB2uwhd7k5LGAVN3j4HQQGB0Sz+VC1h\n" + + "92oi6xDa+YBva2fvHuCd8P50DDjxmp9CemC7rnZ5j8egj88w14X44Xjb/Fd/ApG9\n" + + "e57NnbT7KM+Grw==\n" + + "-----END CERTIFICATE-----", + + // SHA256withRSA, curv prime256v1 + // Validity + // Not Before: May 22 07:18:16 2018 GMT + // Not After : May 21 07:18:16 2028 GMT + // Authority Key Identifier: + // 0D:DD:93:C9:FE:4B:BD:35:B7:E8:99:78:90:FB:DB:5A:3D:DB:15:4C + "-----BEGIN CERTIFICATE-----\n" + + "MIICazCCAVOgAwIBAgIJAO2+yPcFryUUMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + + "BAYTAlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2Vy\n" + + "aXZjZTAeFw0xODA1MjIwNzE4MTZaFw0yODA1MjEwNzE4MTZaMFUxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTEYMBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0D\n" + + "AQcDQgAE59MERNTlVZ1eeps8Z3Oue5ZkgQdPtD+WIE6tj3PbIKpxGPDxvfNP959A\n" + + "yQjEK/ehWQVrCMmNoEkIzY+IIBgB06MjMCEwHwYDVR0jBBgwFoAUDd2Tyf5LvTW3\n" + + "6Jl4kPvbWj3bFUwwDQYJKoZIhvcNAQELBQADggEBAFOTVEqs70ykhZiIdrEsF1Ra\n" + + "I3B2rLvwXZk52uSltk2/bzVvewA577ZCoxQ1pL7ynkisPfBN1uVYtHjM1VA3RC+4\n" + + "+TAK78dnI7otYjWoHp5rvs4l6c/IbOspS290IlNuDUxMErEm5wxIwj+Aukx/1y68\n" + + "hOyCvHBLMY2c1LskH1MMBbDuS1aI+lnGpToi+MoYObxGcV458vxuT8+wwV8Fkpvd\n" + + "ll8IIFmeNPRv+1E+lXbES6CSNCVaZ/lFhPgdgYKleN7sfspiz50DG4dqafuEAaX5\n" + + "xaK1NWXJxTRz0ROH/IUziyuDW6jphrlgit4+3NCzp6vP9hAJQ8Vhcj0n15BKHIQ=\n" + + "-----END CERTIFICATE-----", + + // SHA256withDSA, 2048 bits + // Validity + // Not Before: May 22 07:18:20 2018 GMT + // Not After : May 17 07:18:20 2038 GMT + // Authority Key Identifier: + // 76:66:9E:F7:3B:DD:45:E5:3B:D9:72:3C:3F:F0:54:39:86:31:26:53 + "-----BEGIN CERTIFICATE-----\n" + + "MIIEnDCCBEGgAwIBAgIJAP/jh1qVhNVjMAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" + + "EwJVUzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2\n" + + "Y2UwHhcNMTgwNTIyMDcxODIwWhcNMzgwNTE3MDcxODIwWjBVMQswCQYDVQQGEwJV\n" + + "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Ux\n" + + "GDAWBgNVBAMMD1JlZ3Jlc3Npb24gVGVzdDCCA0cwggI6BgcqhkjOOAQBMIICLQKC\n" + + "AQEAmlavgoJrMcjqWRVcDE2dmWAPREgnzQvneEDef68cprDzjSwvOs5QeFyx75ib\n" + + "ado1e6jO/rW1prCGWHDD1oA/Tn4Pk3vu0nUxzvl1qATc+aJbpUU5Op0bvp6LbCsQ\n" + + "QslV9FeRh7Eb7bP6gpc/kHCBzEgC1VCK7prccXWy+t6SMOHbND3h+UbckfSaUuaV\n" + + "sVJNTD1D6GElfRj4Nmz1BGPfSYvKorwNZEU3gXwFgtDoAcGx7tcyClLpDHfqRfw/\n" + + "7yiqLyeiP7D4hl5lMNouJWDlAdMFp0FMgS3s9VDFinIcr6VtBWMTG7+4+czHAB+3\n" + + "fvrwlqNzhBn3uFHrekN/w8fNxwIhAJo7Sae1za7IMW0Q6hE5B4b+s2B/FaKPoA4E\n" + + "jtZu13B9AoIBAQCOZqLMKfvqZWUgT0PQ3QjR7dAFdd06I9Y3+TOQzZk1+j+vw/6E\n" + + "X4vFItX4gihb/u5Q9CdmpwhVGi7bvo+7+/IKeTgoQ6f5+PSug7SrWWUQ5sPwaZui\n" + + "zXZJ5nTeZDucFc2yFx0wgnjbPwiUxZklOT7xGiOMtzOTa2koCz5KuIBL+/wPKKxm\n" + + "ypo9VoY9xfbdU6LMXZv/lpD5XTM9rYHr/vUTNkukvV6Hpm0YMEWhVZKUJiqCqTqG\n" + + "XHaleOxSw6uQWB/+TznifcC7gB48UOQjCqOKf5VuwQneJLhlhU/jhRV3xtr+hLZa\n" + + "hW1wYhVi8cjLDrZFKlgEQqhB4crnJU0mJY+tA4IBBQACggEAID0ezl00/X8mv7eb\n" + + "bzovum1+DEEP7FM57k6HZEG2N3ve4CW+0m9Cd+cWPz8wkZ+M0j/Eqa6F0IdbkXEc\n" + + "Q7CuzvUyJ57xQ3L/WCgXsiS+Bh8O4Mz7GwW22CGmHqafbVv+hKBfr8MkskO6GJUt\n" + + "SUF/CVLzB4gMIvZMH26tBP2xK+i7FeEK9kT+nGdzQSZBAhFYpEVCBplHZO24/OYq\n" + + "1DNoU327nUuXIhmsfA8N0PjiWbIZIjTPwBGr9H0LpATI7DIDNcvRRvtROP+pBU9y\n" + + "fuykPkptg9C0rCM9t06bukpOSaEz/2VIQdLE8fHYFA6pHZ6CIc2+5cfvMgTPhcjz\n" + + "W2jCt6MjMCEwHwYDVR0jBBgwFoAUdmae9zvdReU72XI8P/BUOYYxJlMwCwYJYIZI\n" + + "AWUDBAMCA0gAMEUCIQCeI5fN08b9BpOaHdc3zQNGjp24FOL/RxlBLeBAorswJgIg\n" + + "JEZ8DhYxQy1O7mmZ2UIT7op6epWMB4dENjs0qWPmcKo=\n" + + "-----END CERTIFICATE-----" + }; + + // Private key in the format of PKCS#8. + final static String[] endEntityPrivateKeys = { + // + // EC private key related to cert endEntityCertStrs[0]. + // + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgn5K03bpTLjEtFQRa\n" + + "JUtx22gtmGEvvSUSQdimhGthdtihRANCAARv72fTmp9ed8dRvTG1Ak1Lgl5KLoiM\n" + + "59bk2pyG8qd8l7L1WQnNHtAcu44RJ1/GVHurxghaCKHeJYsZ8H7DEeI6", + + // + // RSA private key related to cert endEntityCertStrs[1]. + // + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzN8GhtZ9kinwC\n" + + "ALo+JYMNq8/rmZK+AJdQbEAJvFU0B+QuE1FA6weuJEHdfVDee870960LrAqW8T2O\n" + + "WcMOPsP7WPWvUIc7uazV+ryt9xBh2RqcO27gCUejy/5JJZfXowhcVFgOPZVUebI+\n" + + "2BuW1yDjMYC7BPvjoV0sj3i5eMmOrUg6v+/RUiXATk5FYfldz7lOP6gVYrQThrgY\n" + + "cOC0oqGfabvaE3nr8aQ8oaSC4/k1FLWphhX8QWR3JAw5XwnUzsdqJxJ+3g4vp4qN\n" + + "OuCj3f6QeT62/QNzpylUGdqVfdOisbxAjoFwePVdB3vygCUAL7+MXilzSbCLS6fj\n" + + "2R0r2BF9AgMBAAECggEASIkPkMCuw4WdTT44IwERus3IOIYOs2IP3BgEDyyvm4B6\n" + + "JP/iihDWKfA4zEl1Gqcni1RXMHswSglXra682J4kui02Ov+vzEeJIY37Ibn2YnP5\n" + + "ZjRT2s9GtI/S2o4hl8A/mQb2IMViFC+xKehTukhV4j5d6NPKk0XzLR7gcMjnYxwn\n" + + "l21fS6D2oM1xRG/di7sL+uLF8EXLRzfiWDNi12uQv4nwtxPKvuKhH6yzHt7YqMH0\n" + + "46pmDKDaxV4w1JdycjCb6NrCJOYZygoQobuZqOQ30UZoZsPJrtovkncFr1e+lNcO\n" + + "+aWDfOLCtTH046dEQh5oCShyXMybNlry/QHsOtHOwQKBgQDh2iIjs+FPpQy7Z3EX\n" + + "DGEvHYqPjrYO9an2KSRr1m9gzRlWYxKY46WmPKwjMerYtra0GP+TBHrgxsfO8tD2\n" + + "wUAII6sd1qup0a/Sutgf2JxVilLykd0+Ge4/Cs51tCdJ8EqDV2B6WhTewOY2EGvg\n" + + "JiKYkeNwgRX/9M9CFSAMAk0hUQKBgQDLJAartL3DoGUPjYtpJnfgGM23yAGl6G5r\n" + + "NSXDn80BiYIC1p0bG3N0xm3yAjqOtJAUj9jZbvDNbCe3GJfLARMr23legX4tRrgZ\n" + + "nEdKnAFKAKL01oM+A5/lHdkwaZI9yyv+hgSVdYzUjB8rDmzeVQzo1BT7vXypt2yV\n" + + "6O1OnUpCbQKBgA/0rzDChopv6KRcvHqaX0tK1P0rYeVQqb9ATNhpf9jg5Idb3HZ8\n" + + "rrk91BNwdVz2G5ZBpdynFl9G69rNAMJOCM4KZw5mmh4XOEq09Ivba8AHU7DbaTv3\n" + + "7QL7KnbaUWRB26HHzIMYVh0el6T+KADf8NXCiMTr+bfpfbL3dxoiF3zhAoGAbCJD\n" + + "Qse1dBs/cKYCHfkSOsI5T6kx52Tw0jS6Y4X/FOBjyqr/elyEexbdk8PH9Ar931Qr\n" + + "NKMvn8oA4iA/PRrXX7M2yi3YQrWwbkGYWYjtzrzEAdzmg+5eARKAeJrZ8/bg9l3U\n" + + "ttKaItJsDPlizn8rngy3FsJpR9aSAMK6/+wOiYkCgYEA1tZkI1rD1W9NYZtbI9BE\n" + + "qlJVFi2PBOJMKNuWdouPX3HLQ72GJSQff2BFzLTELjweVVJ0SvY4IipzpQOHQOBy\n" + + "5qh/p6izXJZh3IHtvwVBjHoEVplg1b2+I5e3jDCfqnwcQw82dW5SxOJMg1h/BD0I\n" + + "qAL3go42DYeYhu/WnECMeis=", + + // + // EC private key related to cert endEntityCertStrs[2]. + // + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGVc7hICpmp91jbYe\n" + + "nrr8nYHD37RZP3VENY+szuA7WjuhRANCAATn0wRE1OVVnV56mzxnc657lmSBB0+0\n" + + "P5YgTq2Pc9sgqnEY8PG980/3n0DJCMQr96FZBWsIyY2gSQjNj4ggGAHT", + + // + // DSA private key related to cert endEntityCertStrs[3]. + // + "MIICZQIBADCCAjoGByqGSM44BAEwggItAoIBAQCaVq+CgmsxyOpZFVwMTZ2ZYA9E\n" + + "SCfNC+d4QN5/rxymsPONLC86zlB4XLHvmJtp2jV7qM7+tbWmsIZYcMPWgD9Ofg+T\n" + + "e+7SdTHO+XWoBNz5olulRTk6nRu+notsKxBCyVX0V5GHsRvts/qClz+QcIHMSALV\n" + + "UIrumtxxdbL63pIw4ds0PeH5RtyR9JpS5pWxUk1MPUPoYSV9GPg2bPUEY99Ji8qi\n" + + "vA1kRTeBfAWC0OgBwbHu1zIKUukMd+pF/D/vKKovJ6I/sPiGXmUw2i4lYOUB0wWn\n" + + "QUyBLez1UMWKchyvpW0FYxMbv7j5zMcAH7d++vCWo3OEGfe4Uet6Q3/Dx83HAiEA\n" + + "mjtJp7XNrsgxbRDqETkHhv6zYH8Voo+gDgSO1m7XcH0CggEBAI5moswp++plZSBP\n" + + "Q9DdCNHt0AV13Toj1jf5M5DNmTX6P6/D/oRfi8Ui1fiCKFv+7lD0J2anCFUaLtu+\n" + + "j7v78gp5OChDp/n49K6DtKtZZRDmw/Bpm6LNdknmdN5kO5wVzbIXHTCCeNs/CJTF\n" + + "mSU5PvEaI4y3M5NraSgLPkq4gEv7/A8orGbKmj1Whj3F9t1Tosxdm/+WkPldMz2t\n" + + "gev+9RM2S6S9XoembRgwRaFVkpQmKoKpOoZcdqV47FLDq5BYH/5POeJ9wLuAHjxQ\n" + + "5CMKo4p/lW7BCd4kuGWFT+OFFXfG2v6EtlqFbXBiFWLxyMsOtkUqWARCqEHhyucl\n" + + "TSYlj60EIgIgLfA75+8KcKxdN8mr6gzGjQe7jPFGG42Ejhd7Q2F4wuw=" + }; + + // Private key algorithm of endEntityPrivateKeys. + final static String[] endEntityPrivateKeyAlgs = { + "EC", + "RSA", + "EC", + "DSA", + }; + + // Private key names of endEntityPrivateKeys. + static final String[] endEntityPrivateKeyNames = { + "ecdsa", + "rsa", + "ec-rsa", + "dsa", + }; + + /* + * Create an instance of SSLContext with the specified trust/key materials. + */ + private SSLContext createSSLContext( + String[] trustedMaterials, + String[] keyMaterialCerts, + String[] keyMaterialKeys, + String[] keyMaterialKeyAlgs, + String[] keyMaterialKeyNames, + ContextParameters params) throws Exception { + + KeyStore ts = null; // trust store + KeyStore ks = null; // key store + char passphrase[] = "passphrase".toCharArray(); + + // Generate certificate from cert string. + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + // Import the trused certs. + ByteArrayInputStream is; + if (trustedMaterials != null && trustedMaterials.length != 0) { + ts = KeyStore.getInstance("JKS"); + ts.load(null, null); + + Certificate[] trustedCert = + new Certificate[trustedMaterials.length]; + for (int i = 0; i < trustedMaterials.length; i++) { + String trustedCertStr = trustedMaterials[i]; + + is = new ByteArrayInputStream(trustedCertStr.getBytes()); + try { + trustedCert[i] = cf.generateCertificate(is); + } finally { + is.close(); + } + + ts.setCertificateEntry("trusted-cert-" + i, trustedCert[i]); + } + } + + // Import the key materials. + // + // Note that certification pathes bigger than one are not supported yet. + boolean hasKeyMaterials = + (keyMaterialCerts != null) && (keyMaterialCerts.length != 0) && + (keyMaterialKeys != null) && (keyMaterialKeys.length != 0) && + (keyMaterialKeyAlgs != null) && (keyMaterialKeyAlgs.length != 0) && + (keyMaterialCerts.length == keyMaterialKeys.length) && + (keyMaterialCerts.length == keyMaterialKeyAlgs.length); + if (hasKeyMaterials) { + ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + + for (int i = 0; i < keyMaterialCerts.length; i++) { + String keyCertStr = keyMaterialCerts[i]; + + // generate the private key. + PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( + Base64.getMimeDecoder().decode(keyMaterialKeys[i])); + KeyFactory kf = + KeyFactory.getInstance(keyMaterialKeyAlgs[i]); + PrivateKey priKey = kf.generatePrivate(priKeySpec); + + // generate certificate chain + is = new ByteArrayInputStream(keyCertStr.getBytes()); + Certificate keyCert = null; + try { + keyCert = cf.generateCertificate(is); + } finally { + is.close(); + } + + Certificate[] chain = new Certificate[] { keyCert }; + + // import the key entry. + ks.setKeyEntry("cert-" + keyMaterialKeyNames[i], + priKey, passphrase, chain); + } + } + + // Create an SSLContext object. + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(params.tmAlgorithm); + tmf.init(ts); + + SSLContext context = SSLContext.getInstance(params.contextProtocol); + if (hasKeyMaterials && ks != null) { + KeyManagerFactory kmf = + KeyManagerFactory.getInstance(params.kmAlgorithm); + kmf.init(ks, passphrase); + + context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + } else { + context.init(null, tmf.getTrustManagers(), null); + } + + return context; + } +} diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLExceptionForIOIssue.java b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLExceptionForIOIssue.java new file mode 100644 index 00000000000..3e626a2577c --- /dev/null +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLExceptionForIOIssue.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// Please run in othervm mode. SunJSSE does not support dynamic system +// properties, no way to re-use system properties in samevm/agentvm mode. +// + +/* + * @test + * @bug 8214339 + * @summary SSLSocketImpl erroneously wraps SocketException + * @library /javax/net/ssl/templates + * @run main/othervm SSLExceptionForIOIssue + */ + +import javax.net.ssl.*; +import java.io.*; +import java.net.InetAddress; + +public class SSLExceptionForIOIssue implements SSLContextTemplate { + + public static void main(String[] args) throws Exception { + System.err.println("==================================="); + new SSLExceptionForIOIssue().test(); + } + + private void test() throws Exception { + SSLServerSocket listenSocket = null; + SSLSocket serverSocket = null; + ClientSocket clientSocket = null; + try { + SSLServerSocketFactory serversocketfactory = + createServerSSLContext().getServerSocketFactory(); + listenSocket = + (SSLServerSocket)serversocketfactory.createServerSocket(0); + listenSocket.setNeedClientAuth(false); + listenSocket.setEnableSessionCreation(true); + listenSocket.setUseClientMode(false); + + System.err.println("Starting client"); + clientSocket = new ClientSocket(listenSocket.getLocalPort()); + clientSocket.start(); + + System.err.println("Accepting client requests"); + serverSocket = (SSLSocket)listenSocket.accept(); + + if (!clientSocket.isDone) { + System.err.println("Waiting 3 seconds for client "); + Thread.sleep(3000); + } + + System.err.println("Sending data to client ..."); + String serverData = "Hi, I am server"; + BufferedWriter os = new BufferedWriter( + new OutputStreamWriter(serverSocket.getOutputStream())); + os.write(serverData, 0, serverData.length()); + os.newLine(); + os.flush(); + } catch (SSLProtocolException | SSLHandshakeException sslhe) { + throw sslhe; + } catch (SSLException ssle) { + // the expected exception, ignore it + System.err.println("server exception: " + ssle); + } finally { + if (listenSocket != null) { + listenSocket.close(); + } + + if (serverSocket != null) { + serverSocket.close(); + } + } + + if (clientSocket != null && clientSocket.clientException != null) { + throw clientSocket.clientException; + } + } + + + + private class ClientSocket extends Thread{ + boolean isDone = false; + int serverPort = 0; + Exception clientException; + + public ClientSocket(int serverPort) { + this.serverPort = serverPort; + } + + @Override + public void run() { + SSLSocket clientSocket = null; + String clientData = "Hi, I am client"; + try { + System.err.println( + "Connecting to server at port " + serverPort); + SSLSocketFactory sslSocketFactory = + createClientSSLContext().getSocketFactory(); + clientSocket = (SSLSocket)sslSocketFactory.createSocket( + InetAddress.getLocalHost(), serverPort); + clientSocket.setSoLinger(true, 3); + clientSocket.setSoTimeout(100); + + + System.err.println("Sending data to server ..."); + + BufferedWriter os = new BufferedWriter( + new OutputStreamWriter(clientSocket.getOutputStream())); + os.write(clientData, 0, clientData.length()); + os.newLine(); + os.flush(); + + System.err.println("Reading data from server"); + BufferedReader is = new BufferedReader( + new InputStreamReader(clientSocket.getInputStream())); + String data = is.readLine(); + System.err.println("Received Data from server: " + data); + } catch (SSLProtocolException | SSLHandshakeException sslhe) { + clientException = sslhe; + System.err.println("unexpected client exception: " + sslhe); + } catch (SSLException ssle) { + // the expected exception, ignore it + System.err.println("expected client exception: " + ssle); + } catch (Exception e) { + clientException = e; + System.err.println("unexpected client exception: " + e); + } finally { + if (clientSocket != null) { + try { + clientSocket.close(); + System.err.println("client socket closed"); + } catch (IOException ioe) { + clientException = ioe; + } + } + + isDone = true; + } + } + } +} From 1af1a69fbcd3169cb8aea56ea0886a6f3c7ec091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Per=20Lid=C3=A9n?= Date: Sat, 15 Dec 2018 20:03:06 +0100 Subject: [PATCH 089/174] 8215395: Allow null oops in Dictionary and JNIHandle verification Reviewed-by: eosterlund, kbarrett, coleenp --- src/hotspot/share/classfile/dictionary.hpp | 2 +- src/hotspot/share/runtime/jniHandles.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hotspot/share/classfile/dictionary.hpp b/src/hotspot/share/classfile/dictionary.hpp index 4c0e91046c2..087b5e6c62f 100644 --- a/src/hotspot/share/classfile/dictionary.hpp +++ b/src/hotspot/share/classfile/dictionary.hpp @@ -173,7 +173,7 @@ class DictionaryEntry : public HashtableEntry { for (ProtectionDomainEntry* current = pd_set(); // accessed at a safepoint current != NULL; current = current->_next) { - guarantee(oopDesc::is_oop(current->_pd_cache->object_no_keepalive()), "Invalid oop"); + guarantee(oopDesc::is_oop_or_null(current->_pd_cache->object_no_keepalive()), "Invalid oop"); } } diff --git a/src/hotspot/share/runtime/jniHandles.cpp b/src/hotspot/share/runtime/jniHandles.cpp index 6b1692fe189..ca09c575150 100644 --- a/src/hotspot/share/runtime/jniHandles.cpp +++ b/src/hotspot/share/runtime/jniHandles.cpp @@ -318,7 +318,7 @@ void JNIHandles::print_on(outputStream* st) { class VerifyJNIHandles: public OopClosure { public: virtual void do_oop(oop* root) { - guarantee(oopDesc::is_oop(RawAccess<>::oop_load(root)), "Invalid oop"); + guarantee(oopDesc::is_oop_or_null(RawAccess<>::oop_load(root)), "Invalid oop"); } virtual void do_oop(narrowOop* root) { ShouldNotReachHere(); } }; From 2ebc9f99e5f344b19a6172ee5cab26e13a899d0d Mon Sep 17 00:00:00 2001 From: Robert Field Date: Sat, 15 Dec 2018 17:13:39 -0800 Subject: [PATCH 090/174] 8215099: jshell tool: /help representation of ctrl/meta characters inconsistent Reviewed-by: jlahoda --- .../jshell/tool/resources/l10n.properties | 206 +++++++++--------- .../jdk/jshell/ToolShiftTabTest.java | 2 +- test/langtools/jdk/jshell/ToolSimpleTest.java | 5 +- 3 files changed, 111 insertions(+), 102 deletions(-) diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties index e4cddba1142..bfb85ed6a7d 100644 --- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties +++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties @@ -187,12 +187,12 @@ jshell.console.create.method = Create method jshell.console.resolvable = \nThe identifier is resolvable in this context. jshell.console.no.candidate = \nNo candidate fully qualified names found to import. jshell.console.incomplete = \nResults may be incomplete; try again later for complete results. -jshell.console.erroneous = \nIncomplete or erroneous. A single valid expression or statement must proceed Shift- m. -jshell.console.exprstmt = \nA single valid expression or statement must proceed Shift- m. -jshell.console.empty = \nEmpty entry. A single valid expression or statement must proceed Shift- m.. +jshell.console.erroneous = \nIncomplete or erroneous. A single valid expression or statement must precede Shift+Tab m. +jshell.console.exprstmt = \nA single valid expression or statement must precede Shift+Tab m. +jshell.console.empty = \nEmpty entry. A single valid expression or statement must precede Shift+Tab m. jshell.fix.wrong.shortcut =\ -Unexpected character after Shift-Tab.\n\ +Unexpected character after Shift+Tab.\n\ Use "i" for auto-import, "v" for variable creation, or "m" for method creation.\n\ For more information see:\n\ /help shortcuts @@ -579,92 +579,92 @@ or prior commands/snippets can be retrieved from history, edited, and executed.\ This support is similar to readline/editline with simple emacs-like bindings.\n\ There are also jshell tool specific key sequences.\n\ \n\ ---- Line and history navigation ---\n\ -\n\ -Return\n\t\ - Enters the current snippet\n\ -Left-arrow or Ctrl+B\n\t\ - Moves backward one character\n\ -Right-arrow or Ctrl+F\n\t\ - Moves forward one character\n\ -Up-arrow or Ctrl+P\n\t\ - Moves up one line, backward through history\n\ -Down arrow or Ctrl+N\n\t\ - Moves down one line, forward through history\n\ -Ctrl+A\n\t\ - Moves to the beginning of the line\n\ -Ctrl+E\n\t\ - Moves to the end of the line\n\ -Meta+B\n\t\ - Moves backward one word\n\ -Meta+F\n\t\ - Moves forward one word\n\ -Ctrl+R\n\t\ +Line and history navigation:\n\ +\n\t\ +Return\n\t\t\ + Enters the current snippet\n\t\ +Left-arrow or Ctrl+B\n\t\t\ + Moves backward one character\n\t\ +Right-arrow or Ctrl+F\n\t\t\ + Moves forward one character\n\t\ +Up-arrow or Ctrl+P\n\t\t\ + Moves up one line, backward through history\n\t\ +Down arrow or Ctrl+N\n\t\t\ + Moves down one line, forward through history\n\t\ +Ctrl+A\n\t\t\ + Moves to the beginning of the line\n\t\ +Ctrl+E\n\t\t\ + Moves to the end of the line\n\t\ +Meta+B\n\t\t\ + Moves backward one word\n\t\ +Meta+F\n\t\t\ + Moves forward one word\n\t\ +Ctrl+R\n\t\t\ Search backward through history\n\ \n\ \n\ ---- Line and history basic editing ---\n\ -\n\ -Meta+Return or Ctrl+Return (depending on platform)\n\t\ - Insert a new line in snippet\n\ -Ctrl+_ (underscore may require shift key) or Ctrl+X then Ctrl+U\n\t\ - Undo edit - repeat to undo more edits\n\ -Delete\n\t\ - Deletes the character at or after the cursor, depending on the operating system\n\ -Backspace\n\t\ - Deletes the character before the cursor\n\ -Ctrl+K\n\t\ - Deletes the text from the cursor to the end of the line\n\ -Meta+D\n\t\ - Deletes the text from the cursor to the end of the word\n\ -Ctrl+W\n\t\ - Deletes the text from the cursor to the previous white space\n\ -Ctrl+Y\n\t\ - Pastes the most recently deleted text into the line\n\ -Meta+Y\n\t\ - After Ctrl+Y, Meta+Y cycles through previously deleted text\n\ -Ctrl+X then Ctrl+K\n\t\ +Line and history basic editing:\n\ +\n\t\ +Meta+Return or Ctrl+Return (depending on platform)\n\t\t\ + Insert a new line in snippet\n\t\ +Ctrl+_ (underscore may require the Shift key) or Ctrl+X then Ctrl+U\n\t\t\ + Undo edit - repeat to undo more edits\n\t\ +Delete\n\t\t\ + Deletes the character at or after the cursor, depending on the operating system\n\t\ +Backspace\n\t\t\ + Deletes the character before the cursor\n\t\ +Ctrl+K\n\t\t\ + Deletes the text from the cursor to the end of the line\n\t\ +Meta+D\n\t\t\ + Deletes the text from the cursor to the end of the word\n\t\ +Ctrl+W\n\t\t\ + Deletes the text from the cursor to the previous white space\n\t\ +Ctrl+Y\n\t\t\ + Pastes the most recently deleted text into the line\n\t\ +Meta+Y\n\t\t\ + After Ctrl+Y, Meta+Y cycles through previously deleted text\n\t\ +Ctrl+X then Ctrl+K\n\t\t\ Delete whole snippet\n\ \n\ \n\ ---- Shortcuts for jshell tool ---\n\ -\n\ +Shortcuts for jshell tool:\n\ +\n\t\ For details, see: /help shortcuts\n\ -\n\ -Tab\n\t\ - Complete Java identifier or jshell command\n\ -Shift+Tab then v\n\t\ - Convert expression to variable declaration\n\ -Shift+Tab then m\n\t\ - Convert statement to method declaration\n\ -Shift+Tab then i\n\t\ - Add imports for this identifier\n\ +\n\t\ +Tab\n\t\t\ + Complete Java identifier or jshell command\n\t\ +Shift+Tab then v\n\t\t\ + Convert expression to variable declaration\n\t\ +Shift+Tab then m\n\t\t\ + Convert statement to method declaration\n\t\ +Shift+Tab then i\n\t\t\ + Add imports for this identifier\n\t\ \n\ \n\ ---- More line and history editing ---\n\ -\n\ -Ctrl+L\n\t\ - Clear screen and reprint snippet\n\ -Ctrl+U\n\t\ - Kill whole line\n\ -Ctrl+T\n\t\ - Transpose characters\n\ -Ctrl+X then Ctrl+B\n\t\ - Navigate to matching bracket, parenthesis, ...\n\ -Ctrl+X then =\n\t\ - Enter show current character position mode\n\ -Ctrl+X then Ctrl+O\n\t\ - Toggle overwrite characters vs insert characters\n\ -Meta+C\n\t\ - Capitalize word\n\ -Meta+U\n\t\ - Convert word to uppercase\n\ -Meta+L\n\t\ - Convert word to lowercase\n\ -Meta+0 through Meta+9 then key\n\t\ +More line and history editing:\n\ +\n\t\ +Ctrl+L\n\t\t\ + Clear screen and reprint snippet\n\t\ +Ctrl+U\n\t\t\ + Kill whole line\n\t\ +Ctrl+T\n\t\t\ + Transpose characters\n\t\ +Ctrl+X then Ctrl+B\n\t\t\ + Navigate to matching bracket, parenthesis, ...\n\t\ +Ctrl+X then =\n\t\t\ + Enter show current character position mode\n\t\ +Ctrl+X then Ctrl+O\n\t\t\ + Toggle overwrite characters vs insert characters\n\t\ +Meta+C\n\t\t\ + Capitalize word\n\t\ +Meta+U\n\t\t\ + Convert word to uppercase\n\t\ +Meta+L\n\t\t\ + Convert word to lowercase\n\t\ +Meta+0 through Meta+9 then key\n\t\t\ Repeat the specified number of times\n\ \n\ -Where, for example, "Ctrl+A" means hold down the control key and press A.\n\ +Where, for example, "Ctrl+A" means hold down the Control key and press A.\n\ Where "Meta" is "Alt" on many keyboards.\n\ Line editing support is derived from JLine 3. @@ -672,26 +672,34 @@ help.shortcuts.summary = a description of keystrokes for snippet and command com information access, and automatic code generation help.shortcuts =\ Supported shortcuts include:\n\ -\n\ -\n\t\t\ +\n\t\ +Tab\n\t\t\ After entering the first few letters of a Java identifier,\n\t\t\ - a jshell tool command, or, in some cases, a jshell tool command argument,\n\t\t\ - press the key to complete the input.\n\t\t\ - If there is more than one completion, then possible completions will be shown.\n\t\t\ - Will show documentation if available and appropriate.\n\n\ -Shift- v\n\t\t\ - After a complete expression, hold down while pressing ,\n\t\t\ - then release and press "v", the expression will be converted to\n\t\t\ - a variable declaration whose type is based on the type of the expression.\n\n\ -Shift- m\n\t\t\ - After a complete expression or statement, hold down while pressing ,\n\t\t\ - then release and press "m", the expression or statement will be converted to\n\t\t\ - a method declaration. If an expression, the return type is based on the type\n\t\t\ - of the expression.\n\n\ -Shift- i\n\t\t\ - After an unresolvable identifier, hold down while pressing ,\n\t\t\ - then release and press "i", and the jshell tool will propose possible imports\n\t\t\ - which will resolve the identifier based on the content of the specified classpath. + a jshell tool command, or, in some cases, a jshell tool\n\t\t\ + command argument, press the Tab key to complete the input.\n\t\t\ + If there is more than one completion, then possible completions\n\t\t\ + will be shown.\n\t\t\ + Another Tab will show documentation if available and appropriate.\n\n\t\ +Shift+Tab then v\n\t\t\ + After a complete expression, hold down the Shift key while\n\t\t\ + pressing the Tab key, then release and press the "v" key,\n\t\t\ + the expression will be converted to a variable declaration \n\t\t\ + whose type is based on the type of the expression.\n\n\t\ +Shift+Tab then m\n\t\t\ + After a complete expression or statement, hold down the\n\t\t\ + Shift key while pressing the Tab key, then release and press\n\t\t\ + the "m" key, the expression or statement will be converted\n\t\t\ + to a method declaration. If it is an expression, the method\n\t\t\ + return type will be based on the type of the expression.\n\n\t\ +Shift+Tab then i\n\t\t\ + After an unresolvable identifier, hold down the Shift key\n\t\t\ + while pressing the Tab key, then release and press the "i" key,\n\t\t\ + and the jshell tool will propose possible imports which will\n\t\t\ + resolve the identifier based on the content of the specified\n\t\t\ + classpath. Enter the digit corresponding to the desired import,\n\t\t\ + or press the "0" key to add no imports.\n\ +\n\ +For information onother special keys see: /help keys help.context.summary = a description of the evaluation context options for /env /reload and /reset help.context =\ @@ -789,7 +797,7 @@ Startup and error snippets maybe used, e.g.: s3-s9 or e1-e4\n\ Any number of IDs or ID ranges may be used, e.g.: /3-7 s4 14-16 e2\n\ See also '/help id'.\n\ \n\ -Finally, you can search backwards through history by entering ctrl-R followed by the string to search for. +Finally, you can search backwards through history by entering Ctrl+R followed by the string to search for. help.set._retain = \ The '-retain' option saves a setting so that it is used in future sessions.\n\ diff --git a/test/langtools/jdk/jshell/ToolShiftTabTest.java b/test/langtools/jdk/jshell/ToolShiftTabTest.java index 8ed785537c0..b668ff500c1 100644 --- a/test/langtools/jdk/jshell/ToolShiftTabTest.java +++ b/test/langtools/jdk/jshell/ToolShiftTabTest.java @@ -126,7 +126,7 @@ public class ToolShiftTabTest extends UITesting { doRunTest((inputSink, out) -> { inputSink.write("123"); inputSink.write(FIX + "z"); - waitOutput(out, "Unexpected character after Shift-Tab"); + waitOutput(out, "Unexpected character after Shift\\+Tab"); }); } } diff --git a/test/langtools/jdk/jshell/ToolSimpleTest.java b/test/langtools/jdk/jshell/ToolSimpleTest.java index 86aae2b490c..cb1c964a3a8 100644 --- a/test/langtools/jdk/jshell/ToolSimpleTest.java +++ b/test/langtools/jdk/jshell/ToolSimpleTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103 8165405 8173073 8173848 8174041 8173916 8174028 8174262 8174797 8177079 8180508 8177466 8172154 8192979 8191842 8198573 8198801 8210596 8210959 + * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103 8165405 8173073 8173848 8174041 8173916 8174028 8174262 8174797 8177079 8180508 8177466 8172154 8192979 8191842 8198573 8198801 8210596 8210959 8215099 * @summary Simple jshell tool tests * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main @@ -448,7 +448,8 @@ public class ToolSimpleTest extends ReplToolTesting { test( (a) -> assertHelp(a, "/?", "/list", "/help", "/exit", "intro"), (a) -> assertHelp(a, "/help", "/list", "/help", "/exit", "intro"), - (a) -> assertHelp(a, "/help short", "shortcuts", ""), + (a) -> assertHelp(a, "/help short", "shortcuts", "Tab"), + (a) -> assertHelp(a, "/help keys", "line", "Shift", "imports", "history"), (a) -> assertHelp(a, "/? /li", "/list -all", "snippets"), (a) -> assertHelp(a, "/help /set prompt", "optionally contain '%s'", "quoted"), (a) -> assertHelp(a, "/help /help", "/help "), From 2e989366ea703f6eaa330f8a611ba01f27ef9997 Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Mon, 17 Dec 2018 08:25:57 +0100 Subject: [PATCH 091/174] 8215410: Regression test for JDK-8214994 Added a regression test for 8214994 which was fixed by accident with 8211451. Reviewed-by: kvn --- .../compiler/loopopts/TestSplitIfOpaque1.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 test/hotspot/jtreg/compiler/loopopts/TestSplitIfOpaque1.java diff --git a/test/hotspot/jtreg/compiler/loopopts/TestSplitIfOpaque1.java b/test/hotspot/jtreg/compiler/loopopts/TestSplitIfOpaque1.java new file mode 100644 index 00000000000..e1896824d05 --- /dev/null +++ b/test/hotspot/jtreg/compiler/loopopts/TestSplitIfOpaque1.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8214994 + * @summary The split-if optimization fails because an unexpected Opaque1 is encountered. + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:-BackgroundCompilation + * compiler.loopopts.TestSplitIfOpaque1 + */ + +package compiler.loopopts; + +public class TestSplitIfOpaque1 { + + static class MyClass { + int f; + MyClass(int f) { + this.f = f; + } + } + + // The inner loop is found to be a counted loop and a loop limit check + // is added by updating the Opaque1 input of the predicate template. + // This Opaque1 node is then pushed upwards to before the predicates of + // the outer loop and ends up right after the second 'if (b)'. + // The split-if optimization kicks in and splits the first predicate of + // the outer loop (an "obj != NULL" check) through the 'if (b)' region. + // We fail because the region contains an unexpected Opaque1 node. + static int test1(boolean b, int limit, MyClass obj) { + int res = 0; + MyClass notNull = new MyClass(42); + if (b) { + limit = 100; + } + if (b) { + obj = notNull; + } + for (int i = 0; i < 1000; ++i) { + res += obj.f; + for (int j = 0; j <= limit; ++j) { + // Empty + } + } + return res; + } + + // Same as test1 but triggers slightly different failure mode + static int test2(boolean b, int limit, MyClass obj, int[] array) { + int res = 0; + MyClass notNull = new MyClass(12); + if (b) { + limit = 100; + } + if (b) { + obj = notNull; + } + for (int i = 0; i < 1000; ++i) { + res += obj.f; + for (int j = 0; j <= limit; ++j) { + array[j] = j; + } + } + return res; + } + + public static void main(String[] args) { + MyClass obj = new MyClass(42); + int[] array = new int[101]; + for (int i = 0; i < 20_000; i++) { + test1(true, 50, obj); + test1(false, 100, obj); + test2(true, 50, obj, array); + test2(false, 100, obj, array); + } + } +} From 6a9c6a0392a0121db8c8e5c6d3e5637fb8db0f2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Per=20Lid=C3=A9n?= Date: Mon, 17 Dec 2018 16:55:17 +0100 Subject: [PATCH 092/174] 8215451: JNI IsSameObject should not keep objects alive Reviewed-by: eosterlund, kbarrett --- src/hotspot/share/prims/jni.cpp | 4 +--- src/hotspot/share/runtime/jniHandles.cpp | 8 +------ src/hotspot/share/runtime/jniHandles.hpp | 9 +++++-- .../share/runtime/jniHandles.inline.hpp | 24 +++++++++++++++---- .../MyPackage/HeapMonitorThreadTest.java | 1 - 5 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/hotspot/share/prims/jni.cpp b/src/hotspot/share/prims/jni.cpp index 1278f1d9f3a..00f66da0219 100644 --- a/src/hotspot/share/prims/jni.cpp +++ b/src/hotspot/share/prims/jni.cpp @@ -823,9 +823,7 @@ JNI_QUICK_ENTRY(jboolean, jni_IsSameObject(JNIEnv *env, jobject r1, jobject r2)) HOTSPOT_JNI_ISSAMEOBJECT_ENTRY(env, r1, r2); - oop a = JNIHandles::resolve(r1); - oop b = JNIHandles::resolve(r2); - jboolean ret = oopDesc::equals(a, b) ? JNI_TRUE : JNI_FALSE; + jboolean ret = JNIHandles::is_same_object(r1, r2) ? JNI_TRUE : JNI_FALSE; HOTSPOT_JNI_ISSAMEOBJECT_RETURN(ret); return ret; diff --git a/src/hotspot/share/runtime/jniHandles.cpp b/src/hotspot/share/runtime/jniHandles.cpp index ca09c575150..a165e1e1948 100644 --- a/src/hotspot/share/runtime/jniHandles.cpp +++ b/src/hotspot/share/runtime/jniHandles.cpp @@ -152,17 +152,11 @@ jobject JNIHandles::make_weak_global(Handle obj, AllocFailType alloc_failmode) { oop JNIHandles::resolve_external_guard(jobject handle) { oop result = NULL; if (handle != NULL) { - result = resolve_impl(handle); + result = resolve_impl<0 /* decorators */, true /* external_guard */>(handle); } return result; } -oop JNIHandles::resolve_jweak(jweak handle) { - assert(handle != NULL, "precondition"); - assert(is_jweak(handle), "precondition"); - return NativeAccess::oop_load(jweak_ptr(handle)); -} - bool JNIHandles::is_global_weak_cleared(jweak handle) { assert(handle != NULL, "precondition"); assert(is_jweak(handle), "not a weak handle"); diff --git a/src/hotspot/share/runtime/jniHandles.hpp b/src/hotspot/share/runtime/jniHandles.hpp index 3c6be3b6b1a..4c8c9fc1148 100644 --- a/src/hotspot/share/runtime/jniHandles.hpp +++ b/src/hotspot/share/runtime/jniHandles.hpp @@ -42,8 +42,10 @@ class JNIHandles : AllStatic { inline static oop* jobject_ptr(jobject handle); // NOT jweak! inline static oop* jweak_ptr(jobject handle); - template inline static oop resolve_impl(jobject handle); - static oop resolve_jweak(jweak handle); + template inline static oop resolve_impl(jobject handle); + + // Resolve handle into oop, without keeping the object alive + inline static oop resolve_no_keepalive(jobject handle); // This method is not inlined in order to avoid circular includes between // this header file and thread.hpp. @@ -70,6 +72,9 @@ class JNIHandles : AllStatic { // Resolve externally provided handle into oop with some guards static oop resolve_external_guard(jobject handle); + // Check for equality without keeping objects alive + static bool is_same_object(jobject handle1, jobject handle2); + // Local handles static jobject make_local(oop obj); static jobject make_local(JNIEnv* env, oop obj); // Fast version when env is known diff --git a/src/hotspot/share/runtime/jniHandles.inline.hpp b/src/hotspot/share/runtime/jniHandles.inline.hpp index d8b9c7770b1..43e284196c0 100644 --- a/src/hotspot/share/runtime/jniHandles.inline.hpp +++ b/src/hotspot/share/runtime/jniHandles.inline.hpp @@ -49,15 +49,15 @@ inline oop* JNIHandles::jweak_ptr(jobject handle) { } // external_guard is true if called from resolve_external_guard. -template +template inline oop JNIHandles::resolve_impl(jobject handle) { assert(handle != NULL, "precondition"); assert(!current_thread_in_native(), "must not be in native"); oop result; if (is_jweak(handle)) { // Unlikely - result = resolve_jweak(handle); + result = NativeAccess::oop_load(jweak_ptr(handle)); } else { - result = NativeAccess<>::oop_load(jobject_ptr(handle)); + result = NativeAccess::oop_load(jobject_ptr(handle)); // Construction of jobjects canonicalize a null value into a null // jobject, so for non-jweak the pointee should never be null. assert(external_guard || result != NULL, "Invalid JNI handle"); @@ -68,14 +68,28 @@ inline oop JNIHandles::resolve_impl(jobject handle) { inline oop JNIHandles::resolve(jobject handle) { oop result = NULL; if (handle != NULL) { - result = resolve_impl(handle); + result = resolve_impl<0 /* decorators */, false /* external_guard */>(handle); } return result; } +inline oop JNIHandles::resolve_no_keepalive(jobject handle) { + oop result = NULL; + if (handle != NULL) { + result = resolve_impl(handle); + } + return result; +} + +inline bool JNIHandles::is_same_object(jobject handle1, jobject handle2) { + oop obj1 = resolve_no_keepalive(handle1); + oop obj2 = resolve_no_keepalive(handle2); + return oopDesc::equals(obj1, obj2); +} + inline oop JNIHandles::resolve_non_null(jobject handle) { assert(handle != NULL, "JNI handle should not be null"); - oop result = resolve_impl(handle); + oop result = resolve_impl<0 /* decorators */, false /* external_guard */>(handle); assert(result != NULL, "NULL read from jni handle"); return result; } diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java index 31e38e1e646..12892dca542 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorThreadTest.java @@ -30,7 +30,6 @@ package MyPackage; * @summary Verifies the JVMTI Heap Monitor Thread information sanity. * @compile HeapMonitorThreadTest.java * @run main/othervm/native -Xmx512m -agentlib:HeapMonitorTest MyPackage.HeapMonitorThreadTest - * @requires !vm.gc.Z */ import java.util.List; From a3bb5ead7eb3fd3465e97196adfbaaa622672203 Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Mon, 17 Dec 2018 10:36:07 -0800 Subject: [PATCH 093/174] 8214512: ARM32: Jtreg test compiler/c2/Test8062950.java fails on ARM Reviewed-by: dlong, enevill, bulasevich --- src/hotspot/cpu/arm/arm.ad | 18 +++++++++++++++++- src/hotspot/cpu/arm/macroAssembler_arm.cpp | 13 +++++++++---- src/hotspot/cpu/arm/macroAssembler_arm.hpp | 10 +++++----- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/hotspot/cpu/arm/arm.ad b/src/hotspot/cpu/arm/arm.ad index 43d771ea050..49394291888 100644 --- a/src/hotspot/cpu/arm/arm.ad +++ b/src/hotspot/cpu/arm/arm.ad @@ -8945,9 +8945,10 @@ instruct partialSubtypeCheck( R0RegP index, R1RegP sub, R2RegP super, flagsRegP instruct cmpFastLock(flagsRegP pcc, iRegP object, iRegP box, iRegP scratch2, iRegP scratch ) %{ match(Set pcc (FastLock object box)); + predicate(!(UseBiasedLocking && !UseOptoBiasInlining)); effect(TEMP scratch, TEMP scratch2); - ins_cost(100); + ins_cost(DEFAULT_COST*3); format %{ "FASTLOCK $object, $box; KILL $scratch, $scratch2" %} ins_encode %{ @@ -8956,6 +8957,21 @@ instruct cmpFastLock(flagsRegP pcc, iRegP object, iRegP box, iRegP scratch2, iRe ins_pipe(long_memory_op); %} +instruct cmpFastLock_noBiasInline(flagsRegP pcc, iRegP object, iRegP box, iRegP scratch2, + iRegP scratch, iRegP scratch3) %{ + match(Set pcc (FastLock object box)); + predicate(UseBiasedLocking && !UseOptoBiasInlining); + + effect(TEMP scratch, TEMP scratch2, TEMP scratch3); + ins_cost(DEFAULT_COST*5); + + format %{ "FASTLOCK $object, $box; KILL $scratch, $scratch2, $scratch3" %} + ins_encode %{ + __ fast_lock($object$$Register, $box$$Register, $scratch$$Register, $scratch2$$Register, $scratch3$$Register); + %} + ins_pipe(long_memory_op); +%} + instruct cmpFastUnlock(flagsRegP pcc, iRegP object, iRegP box, iRegP scratch2, iRegP scratch ) %{ match(Set pcc (FastUnlock object box)); diff --git a/src/hotspot/cpu/arm/macroAssembler_arm.cpp b/src/hotspot/cpu/arm/macroAssembler_arm.cpp index 0840f584ac9..a09fa56e5a9 100644 --- a/src/hotspot/cpu/arm/macroAssembler_arm.cpp +++ b/src/hotspot/cpu/arm/macroAssembler_arm.cpp @@ -1971,7 +1971,7 @@ void MacroAssembler::resolve(DecoratorSet decorators, Register obj) { #ifdef COMPILER2 -void MacroAssembler::fast_lock(Register Roop, Register Rbox, Register Rscratch, Register Rscratch2) +void MacroAssembler::fast_lock(Register Roop, Register Rbox, Register Rscratch, Register Rscratch2, Register scratch3) { assert(VM_Version::supports_ldrex(), "unsupported, yet?"); @@ -1985,11 +1985,13 @@ void MacroAssembler::fast_lock(Register Roop, Register Rbox, Register Rscratch, Label fast_lock, done; if (UseBiasedLocking && !UseOptoBiasInlining) { - Label failed; - biased_locking_enter(Roop, Rmark, Rscratch, false, noreg, done, failed); - bind(failed); + assert(scratch3 != noreg, "need extra temporary for -XX:-UseOptoBiasInlining"); + biased_locking_enter(Roop, Rmark, Rscratch, false, scratch3, done, done); + // Fall through if lock not biased otherwise branch to done } + // Invariant: Rmark loaded below does not contain biased lock pattern + ldr(Rmark, Address(Roop, oopDesc::mark_offset_in_bytes())); tst(Rmark, markOopDesc::unlocked_value); b(fast_lock, ne); @@ -2016,6 +2018,9 @@ void MacroAssembler::fast_lock(Register Roop, Register Rbox, Register Rscratch, bind(done); + // At this point flags are set as follows: + // EQ -> Success + // NE -> Failure, branch to slow path } void MacroAssembler::fast_unlock(Register Roop, Register Rbox, Register Rscratch, Register Rscratch2) diff --git a/src/hotspot/cpu/arm/macroAssembler_arm.hpp b/src/hotspot/cpu/arm/macroAssembler_arm.hpp index 86c4f81f2bb..114246a85aa 100644 --- a/src/hotspot/cpu/arm/macroAssembler_arm.hpp +++ b/src/hotspot/cpu/arm/macroAssembler_arm.hpp @@ -371,10 +371,10 @@ public: // lock_reg and obj_reg must be loaded up with the appropriate values. // swap_reg must be supplied. // tmp_reg must be supplied. - // Optional slow case is for implementations (interpreter and C1) which branch to - // slow case directly. If slow_case is NULL, then leaves condition - // codes set (for C2's Fast_Lock node) and jumps to done label. - // Falls through for the fast locking attempt. + // Done label is branched to with condition code EQ set if the lock is + // biased and we acquired it. Slow case label is branched to with + // condition code NE set if the lock is biased but we failed to acquire + // it. Otherwise fall through. // Returns offset of first potentially-faulting instruction for null // check info (currently consumed only by C1). If // swap_reg_contains_mark is true then returns -1 as it is assumed @@ -1073,7 +1073,7 @@ public: void restore_default_fp_mode(); #ifdef COMPILER2 - void fast_lock(Register obj, Register box, Register scratch, Register scratch2); + void fast_lock(Register obj, Register box, Register scratch, Register scratch2, Register scratch3 = noreg); void fast_unlock(Register obj, Register box, Register scratch, Register scratch2); #endif From 2fa63331130ea38d984805fe57b4b2c57e60dd10 Mon Sep 17 00:00:00 2001 From: Muthusamy Chinnathambi Date: Tue, 18 Dec 2018 12:59:39 +0530 Subject: [PATCH 094/174] 8215397: jsig.c missing classpath exception Reviewed-by: dholmes --- src/java.base/unix/native/libjsig/jsig.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/java.base/unix/native/libjsig/jsig.c b/src/java.base/unix/native/libjsig/jsig.c index e0972174191..a8ab454dbe7 100644 --- a/src/java.base/unix/native/libjsig/jsig.c +++ b/src/java.base/unix/native/libjsig/jsig.c @@ -5,7 +5,9 @@ * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. + * 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 From 5a6385b363da3b5faab35a5a53f2ffe55f93c1ba Mon Sep 17 00:00:00 2001 From: Rahul Raghavan Date: Tue, 18 Dec 2018 19:13:54 +0530 Subject: [PATCH 095/174] 8211698: Crash in C2 compiled code during execution of double array heavy processing code Correctly registered new Opaque4Node in add_range_check_predicate Reviewed-by: roland, thartmann --- src/hotspot/share/opto/compile.cpp | 3 +- src/hotspot/share/opto/loopTransform.cpp | 4 +- src/hotspot/share/opto/loopnode.hpp | 2 +- src/hotspot/share/opto/node.cpp | 2 +- .../jtreg/compiler/loopopts/Test8211698.java | 57 +++++++++++++++++++ 5 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/loopopts/Test8211698.java diff --git a/src/hotspot/share/opto/compile.cpp b/src/hotspot/share/opto/compile.cpp index b113715aed9..42dc07b3b7c 100644 --- a/src/hotspot/share/opto/compile.cpp +++ b/src/hotspot/share/opto/compile.cpp @@ -3469,8 +3469,7 @@ void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& f } case Op_CmpUL: { if (!Matcher::has_match_rule(Op_CmpUL)) { - // We don't support unsigned long comparisons. Set 'max_idx_expr' - // to max_julong if < 0 to make the signed comparison fail. + // No support for unsigned long comparisons ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1)); Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos); Node* orl = new OrLNode(n->in(1), sign_bit_mask); diff --git a/src/hotspot/share/opto/loopTransform.cpp b/src/hotspot/share/opto/loopTransform.cpp index 31e362ef6c1..209acbdffe0 100644 --- a/src/hotspot/share/opto/loopTransform.cpp +++ b/src/hotspot/share/opto/loopTransform.cpp @@ -2289,9 +2289,9 @@ Node* PhaseIdealLoop::add_range_check_predicate(IdealLoopTree* loop, CountedLoop register_new_node(opaque_bol, predicate_proj); IfNode* new_iff = NULL; if (overflow) { - new_iff = new IfNode(predicate_proj, bol, PROB_MAX, COUNT_UNKNOWN); + new_iff = new IfNode(predicate_proj, opaque_bol, PROB_MAX, COUNT_UNKNOWN); } else { - new_iff = new RangeCheckNode(predicate_proj, bol, PROB_MAX, COUNT_UNKNOWN); + new_iff = new RangeCheckNode(predicate_proj, opaque_bol, PROB_MAX, COUNT_UNKNOWN); } register_control(new_iff, loop->_parent, predicate_proj); Node* iffalse = new IfFalseNode(new_iff); diff --git a/src/hotspot/share/opto/loopnode.hpp b/src/hotspot/share/opto/loopnode.hpp index bf030aed428..064ced8f9e2 100644 --- a/src/hotspot/share/opto/loopnode.hpp +++ b/src/hotspot/share/opto/loopnode.hpp @@ -302,7 +302,7 @@ public: void set_slp_max_unroll(int unroll_factor) { _slp_maximum_unroll_factor = unroll_factor; } int slp_max_unroll() const { return _slp_maximum_unroll_factor; } - virtual LoopNode* skip_strip_mined(int expect_opaq = 1); + virtual LoopNode* skip_strip_mined(int expect_skeleton = 1); OuterStripMinedLoopNode* outer_loop() const; virtual IfTrueNode* outer_loop_tail() const; virtual OuterStripMinedLoopEndNode* outer_loop_end() const; diff --git a/src/hotspot/share/opto/node.cpp b/src/hotspot/share/opto/node.cpp index 6976fc91efb..d68aa4c0dee 100644 --- a/src/hotspot/share/opto/node.cpp +++ b/src/hotspot/share/opto/node.cpp @@ -1367,7 +1367,7 @@ static void kill_dead_code( Node *dead, PhaseIterGVN *igvn ) { igvn->C->remove_range_check_cast(cast); } if (dead->Opcode() == Op_Opaque4) { - igvn->C->remove_range_check_cast(dead); + igvn->C->remove_opaque4_node(dead); } BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); bs->unregister_potential_barrier_node(dead); diff --git a/test/hotspot/jtreg/compiler/loopopts/Test8211698.java b/test/hotspot/jtreg/compiler/loopopts/Test8211698.java new file mode 100644 index 00000000000..37cf52e4648 --- /dev/null +++ b/test/hotspot/jtreg/compiler/loopopts/Test8211698.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8211698 + * @summary Crash in C2 compiled code during execution of double array heavy processing code + * + * @run main/othervm -XX:CompileOnly=Test8211698.test Test8211698 + * + */ + +public class Test8211698 { + + public static void main(String[] args) { + Test8211698 issue = new Test8211698(); + for (int i = 0; i < 10000; i++) { + issue.test(); + } + } + + public void test() { + int[] iarr1 = new int[888]; + for (int i = 5; i > 0; i--) { + for (int j = 0; j <= i - 1; j++) { + int istep = 2 * j - i; + int iadj = 0; + if (istep < 0) { + iadj = iarr1[-istep]; + } else { + iadj = iarr1[istep]; + } + } + } + } +} + From 84105b36fd8156c572523beb695685cf096eedda Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Tue, 18 Dec 2018 12:08:51 -0800 Subject: [PATCH 096/174] 8215443: The use of TransportContext.fatal() leads to bad coding style Reviewed-by: ascarpino --- .../share/classes/sun/security/ssl/Alert.java | 10 +- .../sun/security/ssl/AlpnExtension.java | 29 +++--- .../security/ssl/CertSignAlgsExtension.java | 6 +- .../sun/security/ssl/CertStatusExtension.java | 21 ++-- .../sun/security/ssl/CertificateMessage.java | 51 +++++----- .../sun/security/ssl/CertificateRequest.java | 22 ++--- .../sun/security/ssl/CertificateStatus.java | 9 +- .../sun/security/ssl/CertificateVerify.java | 68 ++++++------- .../sun/security/ssl/ChangeCipherSpec.java | 16 ++- .../classes/sun/security/ssl/ClientHello.java | 35 +++---- .../sun/security/ssl/ClientKeyExchange.java | 5 +- .../sun/security/ssl/CookieExtension.java | 9 +- .../sun/security/ssl/DHClientKeyExchange.java | 18 ++-- .../sun/security/ssl/DHKeyExchange.java | 2 +- .../sun/security/ssl/DHServerKeyExchange.java | 36 +++---- .../security/ssl/ECDHClientKeyExchange.java | 38 ++++--- .../sun/security/ssl/ECDHKeyExchange.java | 10 +- .../security/ssl/ECDHServerKeyExchange.java | 46 ++++----- .../security/ssl/ECPointFormatsExtension.java | 12 +-- .../sun/security/ssl/EncryptedExtensions.java | 2 +- .../ssl/ExtendedMasterSecretExtension.java | 22 ++--- .../classes/sun/security/ssl/Finished.java | 63 ++++-------- .../sun/security/ssl/HandshakeContext.java | 17 +--- .../sun/security/ssl/HelloRequest.java | 4 +- .../sun/security/ssl/HelloVerifyRequest.java | 4 +- .../sun/security/ssl/KeyShareExtension.java | 57 ++++------- .../classes/sun/security/ssl/KeyUpdate.java | 32 +++--- .../sun/security/ssl/MaxFragExtension.java | 23 ++--- .../sun/security/ssl/NewSessionTicket.java | 8 +- .../security/ssl/PostHandshakeContext.java | 7 +- .../security/ssl/PreSharedKeyExtension.java | 40 ++++---- .../ssl/PskKeyExchangeModesExtension.java | 5 +- .../security/ssl/RSAClientKeyExchange.java | 24 +++-- .../sun/security/ssl/RSAKeyExchange.java | 2 +- .../security/ssl/RSAServerKeyExchange.java | 21 ++-- .../sun/security/ssl/RenegoInfoExtension.java | 40 ++++---- .../sun/security/ssl/SSLEngineImpl.java | 26 +++-- .../sun/security/ssl/SSLExtensions.java | 7 +- .../sun/security/ssl/SSLSocketImpl.java | 11 ++- .../sun/security/ssl/SSLTransport.java | 10 +- .../classes/sun/security/ssl/ServerHello.java | 99 ++++++++----------- .../sun/security/ssl/ServerHelloDone.java | 2 +- .../sun/security/ssl/ServerKeyExchange.java | 5 +- .../sun/security/ssl/ServerNameExtension.java | 13 ++- .../ssl/SignatureAlgorithmsExtension.java | 16 ++- .../ssl/SupportedGroupsExtension.java | 6 +- .../ssl/SupportedVersionsExtension.java | 9 +- .../sun/security/ssl/TransportContext.java | 21 ++-- 48 files changed, 454 insertions(+), 585 deletions(-) diff --git a/src/java.base/share/classes/sun/security/ssl/Alert.java b/src/java.base/share/classes/sun/security/ssl/Alert.java index 09bcfd5afc7..4fc4d20302d 100644 --- a/src/java.base/share/classes/sun/security/ssl/Alert.java +++ b/src/java.base/share/classes/sun/security/ssl/Alert.java @@ -193,7 +193,7 @@ enum Alert { // AlertDescription description; // } Alert; if (m.remaining() != 2) { - context.fatal(Alert.ILLEGAL_PARAMETER, + throw context.fatal(Alert.ILLEGAL_PARAMETER, "Invalid Alert message: no sufficient data"); } @@ -247,14 +247,14 @@ enum Alert { if (tc.peerUserCanceled) { tc.closeOutbound(); } else if (tc.handshakeContext != null) { - tc.fatal(Alert.UNEXPECTED_MESSAGE, + throw tc.fatal(Alert.UNEXPECTED_MESSAGE, "Received close_notify during handshake"); } } else if (alert == Alert.USER_CANCELED) { if (level == Level.WARNING) { tc.peerUserCanceled = true; } else { - tc.fatal(alert, + throw tc.fatal(alert, "Received fatal close_notify alert", true, null); } } else if ((level == Level.WARNING) && (alert != null)) { @@ -269,7 +269,7 @@ enum Alert { alert != Alert.NO_CERTIFICATE || (tc.sslConfig.clientAuthType != ClientAuthType.CLIENT_AUTH_REQUESTED)) { - tc.fatal(Alert.HANDSHAKE_FAILURE, + throw tc.fatal(Alert.HANDSHAKE_FAILURE, "received handshake warning: " + alert.description); } // Otherwise, ignore the warning } // Otherwise, ignore the warning. @@ -282,7 +282,7 @@ enum Alert { diagnostic = "Received fatal alert: " + alert.description; } - tc.fatal(alert, diagnostic, true, null); + throw tc.fatal(alert, diagnostic, true, null); } } } diff --git a/src/java.base/share/classes/sun/security/ssl/AlpnExtension.java b/src/java.base/share/classes/sun/security/ssl/AlpnExtension.java index 582ea3d1b02..e62a330adaa 100644 --- a/src/java.base/share/classes/sun/security/ssl/AlpnExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/AlpnExtension.java @@ -174,7 +174,8 @@ final class AlpnExtension { SSLLogger.severe( "Application protocol name cannot be empty"); } - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Application protocol name cannot be empty"); } @@ -189,7 +190,8 @@ final class AlpnExtension { ") exceeds the size limit (" + MAX_AP_LENGTH + " bytes)"); } - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Application protocol name (" + ap + ") exceeds the size limit (" + MAX_AP_LENGTH + " bytes)"); @@ -204,7 +206,8 @@ final class AlpnExtension { ") exceed the size limit (" + MAX_AP_LIST_LENGTH + " bytes)"); } - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "The configured application protocols (" + Arrays.toString(laps) + ") exceed the size limit (" + @@ -283,8 +286,7 @@ final class AlpnExtension { try { spec = new AlpnSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -302,7 +304,7 @@ final class AlpnExtension { } if (!matched) { - shc.conContext.fatal(Alert.NO_APPLICATION_PROTOCOL, + throw shc.conContext.fatal(Alert.NO_APPLICATION_PROTOCOL, "No matching application layer protocol values"); } } // Otherwise, applicationProtocol will be set by the @@ -379,7 +381,8 @@ final class AlpnExtension { if ((shc.applicationProtocol == null) || (!shc.applicationProtocol.isEmpty() && !alps.contains(shc.applicationProtocol))) { - shc.conContext.fatal(Alert.NO_APPLICATION_PROTOCOL, + throw shc.conContext.fatal( + Alert.NO_APPLICATION_PROTOCOL, "No matching application layer protocol values"); } } @@ -391,7 +394,8 @@ final class AlpnExtension { if ((shc.applicationProtocol == null) || (!shc.applicationProtocol.isEmpty() && !alps.contains(shc.applicationProtocol))) { - shc.conContext.fatal(Alert.NO_APPLICATION_PROTOCOL, + throw shc.conContext.fatal( + Alert.NO_APPLICATION_PROTOCOL, "No matching application layer protocol values"); } } @@ -454,7 +458,7 @@ final class AlpnExtension { if (requestedAlps == null || requestedAlps.applicationProtocols == null || requestedAlps.applicationProtocols.isEmpty()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected " + SSLExtension.CH_ALPN.name + " extension"); } @@ -463,13 +467,12 @@ final class AlpnExtension { try { spec = new AlpnSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Only one application protocol is allowed. if (spec.applicationProtocols.size() != 1) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid " + SSLExtension.CH_ALPN.name + " extension: " + "Only one application protocol name " + "is allowed in ServerHello message"); @@ -478,7 +481,7 @@ final class AlpnExtension { // The respond application protocol must be one of the requested. if (!requestedAlps.applicationProtocols.containsAll( spec.applicationProtocols)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid " + SSLExtension.CH_ALPN.name + " extension: " + "Only client specified application protocol " + "is allowed in ServerHello message"); diff --git a/src/java.base/share/classes/sun/security/ssl/CertSignAlgsExtension.java b/src/java.base/share/classes/sun/security/ssl/CertSignAlgsExtension.java index ba94f0695cd..ba39722e45d 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertSignAlgsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/CertSignAlgsExtension.java @@ -153,8 +153,7 @@ final class CertSignAlgsExtension { try { spec = new SignatureSchemesSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -297,8 +296,7 @@ final class CertSignAlgsExtension { try { spec = new SignatureSchemesSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. diff --git a/src/java.base/share/classes/sun/security/ssl/CertStatusExtension.java b/src/java.base/share/classes/sun/security/ssl/CertStatusExtension.java index 2ca3eb8cb05..714cf4f6cc0 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertStatusExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/CertStatusExtension.java @@ -606,8 +606,7 @@ final class CertStatusExtension { try { spec = new CertStatusRequestSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -711,13 +710,13 @@ final class CertStatusExtension { CertStatusRequestSpec requestedCsr = (CertStatusRequestSpec) chc.handshakeExtensions.get(CH_STATUS_REQUEST); if (requestedCsr == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected status_request extension in ServerHello"); } // Parse the extension. if (buffer.hasRemaining()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid status_request extension in ServerHello message: " + "the extension data must be empty"); } @@ -964,8 +963,7 @@ final class CertStatusExtension { try { spec = new CertStatusRequestV2Spec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -1067,13 +1065,13 @@ final class CertStatusExtension { CertStatusRequestV2Spec requestedCsr = (CertStatusRequestV2Spec) chc.handshakeExtensions.get(CH_STATUS_REQUEST_V2); if (requestedCsr == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected status_request_v2 extension in ServerHello"); } // Parse the extension. if (buffer.hasRemaining()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid status_request_v2 extension in ServerHello: " + "the extension data must be empty"); } @@ -1157,10 +1155,10 @@ final class CertStatusExtension { respBytes); producedData = certResp.toByteArray(); } catch (CertificateException ce) { - shc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw shc.conContext.fatal(Alert.BAD_CERTIFICATE, "Failed to parse server certificates", ce); } catch (IOException ioe) { - shc.conContext.fatal(Alert.BAD_CERT_STATUS_RESPONSE, + throw shc.conContext.fatal(Alert.BAD_CERT_STATUS_RESPONSE, "Failed to parse certificate status response", ioe); } @@ -1188,8 +1186,7 @@ final class CertStatusExtension { try { spec = new CertStatusResponseSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.DECODE_ERROR, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.DECODE_ERROR, ioe); } if (chc.sslContext.isStaplingEnabled(true)) { diff --git a/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java b/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java index b0d82dadbf4..a38cfbfe486 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java +++ b/src/java.base/share/classes/sun/security/ssl/CertificateMessage.java @@ -111,10 +111,10 @@ final class CertificateMessage { encodedCerts.add(cert.getEncoded()); } catch (CertificateEncodingException cee) { // unlikely - handshakeContext.conContext.fatal(Alert.INTERNAL_ERROR, + throw handshakeContext.conContext.fatal( + Alert.INTERNAL_ERROR, "Could not encode certificate (" + cert.getSubjectX500Principal() + ")", cee); - break; } } @@ -127,7 +127,8 @@ final class CertificateMessage { int listLen = Record.getInt24(m); if (listLen > m.remaining()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal( + Alert.ILLEGAL_PARAMETER, "Error parsing certificate message:no sufficient data"); } if (listLen > 0) { @@ -248,10 +249,8 @@ final class CertificateMessage { } if (x509Possession == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "No expected X.509 certificate for server authentication"); - - return null; // make the compiler happy } shc.handshakeSession.setLocalPrivateKey( @@ -375,7 +374,7 @@ final class CertificateMessage { if (shc.sslConfig.clientAuthType != ClientAuthType.CLIENT_AUTH_REQUESTED) { // unexpected or require client authentication - shc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw shc.conContext.fatal(Alert.BAD_CERTIFICATE, "Empty server certificate chain"); } else { return; @@ -392,7 +391,7 @@ final class CertificateMessage { new ByteArrayInputStream(encodedCert)); } } catch (CertificateException ce) { - shc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw shc.conContext.fatal(Alert.BAD_CERTIFICATE, "Failed to parse server certificates", ce); } @@ -410,7 +409,7 @@ final class CertificateMessage { T12CertificateMessage certificateMessage) throws IOException { List encodedCerts = certificateMessage.encodedCertChain; if (encodedCerts == null || encodedCerts.isEmpty()) { - chc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw chc.conContext.fatal(Alert.BAD_CERTIFICATE, "Empty server certificate chain"); } @@ -424,7 +423,7 @@ final class CertificateMessage { new ByteArrayInputStream(encodedCert)); } } catch (CertificateException ce) { - chc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw chc.conContext.fatal(Alert.BAD_CERTIFICATE, "Failed to parse server certificates", ce); } @@ -443,7 +442,7 @@ final class CertificateMessage { if ((identityAlg == null || identityAlg.isEmpty()) && !isIdentityEquivalent(x509Certs[0], chc.reservedServerCerts[0])) { - chc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw chc.conContext.fatal(Alert.BAD_CERTIFICATE, "server certificate change is restricted " + "during renegotiation"); } @@ -639,7 +638,7 @@ final class CertificateMessage { // the certificate chain in the TLS session. chc.handshakeSession.setPeerCertificates(certs); } catch (CertificateException ce) { - chc.conContext.fatal(getCertificateAlert(chc, ce), ce); + throw chc.conContext.fatal(getCertificateAlert(chc, ce), ce); } } @@ -685,7 +684,7 @@ final class CertificateMessage { "Improper X509TrustManager implementation"); } } catch (CertificateException ce) { - shc.conContext.fatal(Alert.CERTIFICATE_UNKNOWN, ce); + throw shc.conContext.fatal(Alert.CERTIFICATE_UNKNOWN, ce); } } @@ -942,22 +941,20 @@ final class CertificateMessage { SSLPossession pos = choosePossession(shc, clientHello); if (pos == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No available authentication scheme"); - return null; // make the complier happy } if (!(pos instanceof X509Possession)) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X.509 certificate for server authentication"); } X509Possession x509Possession = (X509Possession)pos; X509Certificate[] localCerts = x509Possession.popCerts; if (localCerts == null || localCerts.length == 0) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X.509 certificate for server authentication"); - return null; // make the complier happy } // update the context @@ -969,9 +966,8 @@ final class CertificateMessage { try { cm = new T13CertificateMessage(shc, (new byte[0]), localCerts); } catch (SSLException | CertificateException ce) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Failed to produce server Certificate message", ce); - return null; // make the complier happy } // Check the OCSP stapling extensions and attempt @@ -1108,9 +1104,8 @@ final class CertificateMessage { cm = new T13CertificateMessage( chc, chc.certRequestContext, localCerts); } catch (SSLException | CertificateException ce) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Failed to produce client Certificate message", ce); - return null; } if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine("Produced client Certificate message", cm); @@ -1163,7 +1158,7 @@ final class CertificateMessage { if (certificateMessage.certEntries == null || certificateMessage.certEntries.isEmpty()) { if (shc.sslConfig.clientAuthType == CLIENT_AUTH_REQUIRED) { - shc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw shc.conContext.fatal(Alert.BAD_CERTIFICATE, "Empty client certificate chain"); } else { // optional client authentication @@ -1187,7 +1182,7 @@ final class CertificateMessage { T13CertificateMessage certificateMessage )throws IOException { if (certificateMessage.certEntries == null || certificateMessage.certEntries.isEmpty()) { - chc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw chc.conContext.fatal(Alert.BAD_CERTIFICATE, "Empty server certificate chain"); } @@ -1224,7 +1219,7 @@ final class CertificateMessage { new ByteArrayInputStream(entry.encoded)); } } catch (CertificateException ce) { - shc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw shc.conContext.fatal(Alert.BAD_CERTIFICATE, "Failed to parse server certificates", ce); } @@ -1270,7 +1265,7 @@ final class CertificateMessage { // the certificate chain in the TLS session. shc.handshakeSession.setPeerCertificates(certs); } catch (CertificateException ce) { - shc.conContext.fatal(Alert.CERTIFICATE_UNKNOWN, ce); + throw shc.conContext.fatal(Alert.CERTIFICATE_UNKNOWN, ce); } return certs; @@ -1289,7 +1284,7 @@ final class CertificateMessage { new ByteArrayInputStream(entry.encoded)); } } catch (CertificateException ce) { - chc.conContext.fatal(Alert.BAD_CERTIFICATE, + throw chc.conContext.fatal(Alert.BAD_CERTIFICATE, "Failed to parse server certificates", ce); } @@ -1326,7 +1321,7 @@ final class CertificateMessage { // the certificate chain in the TLS session. chc.handshakeSession.setPeerCertificates(certs); } catch (CertificateException ce) { - chc.conContext.fatal(getCertificateAlert(chc, ce), ce); + throw chc.conContext.fatal(getCertificateAlert(chc, ce), ce); } return certs; diff --git a/src/java.base/share/classes/sun/security/ssl/CertificateRequest.java b/src/java.base/share/classes/sun/security/ssl/CertificateRequest.java index 14f76107ca4..ba35385d7e0 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertificateRequest.java +++ b/src/java.base/share/classes/sun/security/ssl/CertificateRequest.java @@ -171,14 +171,14 @@ final class CertificateRequest { // DistinguishedName certificate_authorities<0..2^16-1>; // } CertificateRequest; if (m.remaining() < 4) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Incorrect CertificateRequest message: no sufficient data"); } this.types = Record.getBytes8(m); int listLen = Record.getInt16(m); if (listLen > m.remaining()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Incorrect CertificateRequest message:no sufficient data"); } @@ -407,7 +407,7 @@ final class CertificateRequest { this.types = ClientCertificateType.CERT_TYPES; if (signatureSchemes == null || signatureSchemes.isEmpty()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No signature algorithms specified for " + "CertificateRequest hanshake message"); } @@ -437,7 +437,7 @@ final class CertificateRequest { // certificate_authorities if (m.remaining() < 8) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "no sufficient data"); } @@ -445,14 +445,14 @@ final class CertificateRequest { // supported_signature_algorithms if (m.remaining() < 6) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "no sufficient data"); } byte[] algs = Record.getBytes16(m); if (algs == null || algs.length == 0 || (algs.length & 0x01) != 0) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "incomplete signature algorithms"); } @@ -466,14 +466,14 @@ final class CertificateRequest { // certificate_authorities if (m.remaining() < 2) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "no sufficient data"); } int listLen = Record.getInt16(m); if (listLen > m.remaining()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest message: no sufficient data"); } @@ -597,7 +597,7 @@ final class CertificateRequest { if (shc.localSupportedSignAlgs == null || shc.localSupportedSignAlgs.isEmpty()) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No supported signature algorithm"); } @@ -783,14 +783,14 @@ final class CertificateRequest { // Extension extensions<2..2^16-1>; // } CertificateRequest; if (m.remaining() < 5) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "no sufficient data"); } this.requestContext = Record.getBytes8(m); if (m.remaining() < 4) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateRequest handshake message: " + "no sufficient extensions data"); } diff --git a/src/java.base/share/classes/sun/security/ssl/CertificateStatus.java b/src/java.base/share/classes/sun/security/ssl/CertificateStatus.java index c4087aab6ed..3f457ec051b 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertificateStatus.java +++ b/src/java.base/share/classes/sun/security/ssl/CertificateStatus.java @@ -154,7 +154,8 @@ final class CertificateStatus { encodedResponses.add(respDER); encodedResponsesLen = 3 + respDER.length; } else { - handshakeContext.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw handshakeContext.conContext.fatal( + Alert.HANDSHAKE_FAILURE, "Zero-length OCSP Response"); } } else if (statusType == CertStatusRequestType.OCSP_MULTI) { @@ -172,11 +173,13 @@ final class CertificateStatus { } if (respListLen != 0) { - handshakeContext.conContext.fatal(Alert.INTERNAL_ERROR, + throw handshakeContext.conContext.fatal( + Alert.INTERNAL_ERROR, "Bad OCSP response list length"); } } else { - handshakeContext.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw handshakeContext.conContext.fatal( + Alert.HANDSHAKE_FAILURE, "Unsupported StatusResponseType: " + statusType); } messageLength = messageLength(); diff --git a/src/java.base/share/classes/sun/security/ssl/CertificateVerify.java b/src/java.base/share/classes/sun/security/ssl/CertificateVerify.java index bcc90f1796e..b5c6c9f2301 100644 --- a/src/java.base/share/classes/sun/security/ssl/CertificateVerify.java +++ b/src/java.base/share/classes/sun/security/ssl/CertificateVerify.java @@ -83,11 +83,11 @@ final class CertificateVerify { signer.update(hashes); temproary = signer.sign(); } catch (NoSuchAlgorithmException nsae) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + algorithm + ") used in CertificateVerify handshake message", nsae); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot produce CertificateVerify signature", gse); } @@ -112,7 +112,7 @@ final class CertificateVerify { // }; // } Signature; if (m.remaining() < 2) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateVerify message: no sufficient data"); } @@ -128,7 +128,7 @@ final class CertificateVerify { if (x509Credentials == null || x509Credentials.popPublicKey == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X509 credentials negotiated for CertificateVerify"); } @@ -140,15 +140,15 @@ final class CertificateVerify { shc.handshakeSession.getMasterSecret()); signer.update(hashes); if (!signer.verify(signature)) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid CertificateVerify message: invalid signature"); } } catch (NoSuchAlgorithmException nsae) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + algorithm + ") used in CertificateVerify handshake message", nsae); } catch (GeneralSecurityException gse) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify CertificateVerify signature", gse); } } @@ -327,11 +327,11 @@ final class CertificateVerify { signer.update(hashes); temproary = signer.sign(); } catch (NoSuchAlgorithmException nsae) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + algorithm + ") used in CertificateVerify handshake message", nsae); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot produce CertificateVerify signature", gse); } @@ -356,7 +356,7 @@ final class CertificateVerify { // }; // } Signature; if (m.remaining() < 2) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateVerify message: no sufficient data"); } @@ -372,7 +372,7 @@ final class CertificateVerify { if (x509Credentials == null || x509Credentials.popPublicKey == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X509 credentials negotiated for CertificateVerify"); } @@ -383,15 +383,15 @@ final class CertificateVerify { byte[] hashes = shc.handshakeHash.digest(algorithm); signer.update(hashes); if (!signer.verify(signature)) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid CertificateVerify message: invalid signature"); } } catch (NoSuchAlgorithmException nsae) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + algorithm + ") used in CertificateVerify handshake message", nsae); } catch (GeneralSecurityException gse) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify CertificateVerify signature", gse); } } @@ -570,7 +570,7 @@ final class CertificateVerify { if (signatureScheme == null) { // Unlikely, the credentials generator should have // selected the preferable signature algorithm properly. - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "No preferred signature algorithm for CertificateVerify"); } @@ -582,12 +582,12 @@ final class CertificateVerify { temproary = signer.sign(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException nsae) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message", nsae); } catch (InvalidKeyException | SignatureException ikse) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot produce CertificateVerify signature", ikse); } @@ -607,7 +607,7 @@ final class CertificateVerify { // opaque signature<0..2^16-1>; // } DigitallySigned; if (m.remaining() < 4) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateVerify message: no sufficient data"); } @@ -615,13 +615,13 @@ final class CertificateVerify { int ssid = Record.getInt16(m); this.signatureScheme = SignatureScheme.valueOf(ssid); if (signatureScheme == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature algorithm (" + ssid + ") used in CertificateVerify handshake message"); } if (!shc.localSupportedSignAlgs.contains(signatureScheme)) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message"); @@ -638,7 +638,7 @@ final class CertificateVerify { if (x509Credentials == null || x509Credentials.popPublicKey == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X509 credentials negotiated for CertificateVerify"); } @@ -649,17 +649,17 @@ final class CertificateVerify { signatureScheme.getSignature(x509Credentials.popPublicKey); signer.update(shc.handshakeHash.archived()); if (!signer.verify(signature)) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid CertificateVerify signature"); } } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException nsae) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message", nsae); } catch (InvalidKeyException | SignatureException ikse) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify CertificateVerify signature", ikse); } } @@ -871,7 +871,7 @@ final class CertificateVerify { if (signatureScheme == null) { // Unlikely, the credentials generator should have // selected the preferable signature algorithm properly. - context.conContext.fatal(Alert.INTERNAL_ERROR, + throw context.conContext.fatal(Alert.INTERNAL_ERROR, "No preferred signature algorithm for CertificateVerify"); } @@ -897,12 +897,12 @@ final class CertificateVerify { temproary = signer.sign(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException nsae) { - context.conContext.fatal(Alert.INTERNAL_ERROR, + throw context.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message", nsae); } catch (InvalidKeyException | SignatureException ikse) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot produce CertificateVerify signature", ikse); } @@ -918,7 +918,7 @@ final class CertificateVerify { // opaque signature<0..2^16-1>; // } DigitallySigned; if (m.remaining() < 4) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid CertificateVerify message: no sufficient data"); } @@ -926,13 +926,13 @@ final class CertificateVerify { int ssid = Record.getInt16(m); this.signatureScheme = SignatureScheme.valueOf(ssid); if (signatureScheme == null) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature algorithm (" + ssid + ") used in CertificateVerify handshake message"); } if (!context.localSupportedSignAlgs.contains(signatureScheme)) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message"); @@ -949,7 +949,7 @@ final class CertificateVerify { if (x509Credentials == null || x509Credentials.popPublicKey == null) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No X509 credentials negotiated for CertificateVerify"); } @@ -975,17 +975,17 @@ final class CertificateVerify { signatureScheme.getSignature(x509Credentials.popPublicKey); signer.update(contentCovered); if (!signer.verify(signature)) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid CertificateVerify signature"); } } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException nsae) { - context.conContext.fatal(Alert.INTERNAL_ERROR, + throw context.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm (" + signatureScheme.name + ") used in CertificateVerify handshake message", nsae); } catch (InvalidKeyException | SignatureException ikse) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify CertificateVerify signature", ikse); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java b/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java index 2983cf615ab..fad46fb4178 100644 --- a/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java +++ b/src/java.base/share/classes/sun/security/ssl/ChangeCipherSpec.java @@ -106,11 +106,9 @@ final class ChangeCipherSpec { } if (writeCipher == null) { - hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + ncs + ") and protocol version (" + hc.negotiatedProtocol + ")"); - - return null; } if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { @@ -144,7 +142,7 @@ final class ChangeCipherSpec { // parse if (message.remaining() != 1 || message.get() != 1) { - tc.fatal(Alert.UNEXPECTED_MESSAGE, + throw tc.fatal(Alert.UNEXPECTED_MESSAGE, "Malformed or unexpected ChangeCipherSpec message"); } if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { @@ -153,7 +151,7 @@ final class ChangeCipherSpec { // validate if (tc.handshakeContext == null) { - tc.fatal(Alert.HANDSHAKE_FAILURE, + throw tc.fatal(Alert.HANDSHAKE_FAILURE, "Unexpected ChangeCipherSpec message"); } @@ -161,7 +159,7 @@ final class ChangeCipherSpec { HandshakeContext hc = tc.handshakeContext; if (hc.handshakeKeyDerivation == null) { - tc.fatal(Alert.UNEXPECTED_MESSAGE, + throw tc.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ChangeCipherSpec message"); } @@ -205,12 +203,10 @@ final class ChangeCipherSpec { } if (readCipher == null) { - hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + hc.negotiatedCipherSuite + ") and protocol version (" + hc.negotiatedProtocol + ")"); - - return; } tc.inputRecord.changeReadCiphers(readCipher); @@ -243,7 +239,7 @@ final class ChangeCipherSpec { // parse if (message.remaining() != 1 || message.get() != 1) { - tc.fatal(Alert.UNEXPECTED_MESSAGE, + throw tc.fatal(Alert.UNEXPECTED_MESSAGE, "Malformed or unexpected ChangeCipherSpec message"); } if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { diff --git a/src/java.base/share/classes/sun/security/ssl/ClientHello.java b/src/java.base/share/classes/sun/security/ssl/ClientHello.java index 96bbef5db59..6fbac3103e5 100644 --- a/src/java.base/share/classes/sun/security/ssl/ClientHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ClientHello.java @@ -144,8 +144,8 @@ final class ClientHello { if (id == SSLExtension.CH_PRE_SHARED_KEY.id) { // ensure pre_shared_key is the last extension if (remaining > 0) { - tc.fatal(Alert.ILLEGAL_PARAMETER, - "pre_shared_key extension is not last"); + throw tc.fatal(Alert.ILLEGAL_PARAMETER, + "pre_shared_key extension is not last"); } // read only up to the IDs Record.getBytes16(m); @@ -169,7 +169,8 @@ final class ClientHello { try { sessionId.checkLength(clientVersion); } catch (SSLProtocolException ex) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, ex); + throw handshakeContext.conContext.fatal( + Alert.ILLEGAL_PARAMETER, ex); } if (isDTLS) { this.cookie = Record.getBytes8(m); @@ -179,8 +180,9 @@ final class ClientHello { byte[] encodedIds = Record.getBytes16(m); if (encodedIds.length == 0 || (encodedIds.length & 0x01) != 0) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, - "Invalid ClientHello message"); + throw handshakeContext.conContext.fatal( + Alert.ILLEGAL_PARAMETER, + "Invalid ClientHello message"); } this.cipherSuiteIds = new int[encodedIds.length >> 1]; @@ -702,7 +704,8 @@ final class ClientHello { try { chc.kickstart(); } catch (IOException ioe) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, ioe); + throw chc.conContext.fatal( + Alert.HANDSHAKE_FAILURE, ioe); } // The handshake message has been delivered. @@ -790,7 +793,7 @@ final class ClientHello { // clean up this consumer shc.handshakeConsumers.remove(SSLHandshake.CLIENT_HELLO.id); if (!shc.handshakeConsumers.isEmpty()) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "No more handshake message allowed " + "in a ClientHello flight"); } @@ -877,7 +880,7 @@ final class ClientHello { context.activeProtocols, chv); if (pv == null || pv == ProtocolVersion.NONE || pv == ProtocolVersion.SSL20Hello) { - context.conContext.fatal(Alert.PROTOCOL_VERSION, + throw context.conContext.fatal(Alert.PROTOCOL_VERSION, "Client requested protocol " + ProtocolVersion.nameOf(clientHelloVersion) + " is not enabled or supported in server context"); @@ -910,13 +913,11 @@ final class ClientHello { } // No protocol version can be negotiated. - context.conContext.fatal(Alert.PROTOCOL_VERSION, + throw context.conContext.fatal(Alert.PROTOCOL_VERSION, "The client supported protocol versions " + Arrays.toString( ProtocolVersion.toStringArray(clientSupportedVersions)) + " are not accepted by server preferences " + context.activeProtocols); - - return null; // make the compiler happy } } @@ -957,13 +958,13 @@ final class ClientHello { if (shc.conContext.isNegotiated) { if (!shc.conContext.secureRenegotiation && !HandshakeContext.allowUnsafeRenegotiation) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsafe renegotiation is not allowed"); } if (ServerHandshakeContext.rejectClientInitiatedRenego && !shc.kickstartMessageDelivered) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Client initiated renegotiation is not allowed"); } } @@ -1170,13 +1171,13 @@ final class ClientHello { handshakeProducer.produce(shc, clientHello); } else { // unlikely - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No HelloRetryRequest producer: " + shc.handshakeProducers); } if (!shc.handshakeProducers.isEmpty()) { // unlikely, but please double check. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "unknown handshake producers: " + shc.handshakeProducers); } } @@ -1264,13 +1265,13 @@ final class ClientHello { if (shc.conContext.isNegotiated) { if (!shc.conContext.secureRenegotiation && !HandshakeContext.allowUnsafeRenegotiation) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsafe renegotiation is not allowed"); } if (ServerHandshakeContext.rejectClientInitiatedRenego && !shc.kickstartMessageDelivered) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Client initiated renegotiation is not allowed"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ClientKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ClientKeyExchange.java index 8f442004450..040a604ae21 100644 --- a/src/java.base/share/classes/sun/security/ssl/ClientKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ClientKeyExchange.java @@ -68,9 +68,8 @@ final class ClientKeyExchange { } // not consumer defined. - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ClientKeyExchange handshake message."); - return null; // make the compiler happe } } @@ -105,7 +104,7 @@ final class ClientKeyExchange { } // not consumer defined. - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ClientKeyExchange handshake message."); } } diff --git a/src/java.base/share/classes/sun/security/ssl/CookieExtension.java b/src/java.base/share/classes/sun/security/ssl/CookieExtension.java index a81695fcf4a..71df50c1310 100644 --- a/src/java.base/share/classes/sun/security/ssl/CookieExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/CookieExtension.java @@ -163,8 +163,7 @@ public class CookieExtension { try { spec = new CookieSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } shc.handshakeExtensions.put(SSLExtension.CH_COOKIE, spec); @@ -201,9 +200,8 @@ public class CookieExtension { HelloCookieManager hcm = shc.sslContext.getHelloCookieManager(shc.negotiatedProtocol); if (!hcm.isCookieValid(shc, clientHello, spec.cookie)) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "unrecognized cookie"); - return; // fatal() always throws, make the compiler happy. } } } @@ -270,8 +268,7 @@ public class CookieExtension { try { spec = new CookieSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } chc.handshakeExtensions.put(SSLExtension.HRR_COOKIE, spec); diff --git a/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java index 17f3acba17b..86e2c618a95 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java @@ -87,7 +87,7 @@ final class DHClientKeyExchange { if (dhePossession == null) { // unlikely - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No DHE credentials negotiated for client key exchange"); } @@ -104,14 +104,14 @@ final class DHClientKeyExchange { (ServerHandshakeContext)handshakeContext; if (m.remaining() < 3) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid DH ClientKeyExchange message: insufficient data"); } this.y = Record.getBytes16(m); if (m.hasRemaining()) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid DH ClientKeyExchange message: unknown extra data"); } } @@ -177,7 +177,7 @@ final class DHClientKeyExchange { } if (dheCredentials == null) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No DHE credentials negotiated for client key exchange"); } @@ -202,7 +202,7 @@ final class DHClientKeyExchange { chc.negotiatedProtocol); if (ke == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } else { SSLKeyDerivation masterKD = ke.createKeyDerivation(chc); @@ -214,7 +214,7 @@ final class DHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); } else { @@ -254,7 +254,7 @@ final class DHClientKeyExchange { if (dhePossession == null) { // unlikely - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No expected DHE possessions for client key exchange"); } @@ -263,7 +263,7 @@ final class DHClientKeyExchange { shc.negotiatedProtocol); if (ke == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } @@ -310,7 +310,7 @@ final class DHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); } else { shc.handshakeKeyDerivation = diff --git a/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java index 8bc3e95bcac..a6668f816cc 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/DHKeyExchange.java @@ -438,7 +438,7 @@ final class DHKeyExchange { } if (dhePossession == null || dheCredentials == null) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No sufficient DHE key agreement parameters negotiated"); } diff --git a/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java index f12d6be3f4e..d09bf5d4a80 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/DHServerKeyExchange.java @@ -106,7 +106,7 @@ final class DHServerKeyExchange { if (dhePossession == null) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No DHE credentials negotiated for server key exchange"); } DHPublicKey publicKey = dhePossession.publicKey; @@ -132,7 +132,7 @@ final class DHServerKeyExchange { if (signatureScheme == null) { // Unlikely, the credentials generator should have // selected the preferable signature algorithm properly. - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "No preferred signature algorithm"); } try { @@ -140,7 +140,7 @@ final class DHServerKeyExchange { x509Possession.popPrivateKey); } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException nsae) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + signatureScheme.name, nsae); } @@ -151,7 +151,7 @@ final class DHServerKeyExchange { x509Possession.popPrivateKey.getAlgorithm(), x509Possession.popPrivateKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + x509Possession.popPrivateKey.getAlgorithm(), e); } @@ -163,7 +163,7 @@ final class DHServerKeyExchange { shc.serverHelloRandom.randomBytes); signature = signer.sign(); } catch (SignatureException ex) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failed to sign dhe parameters: " + x509Possession.popPrivateKey.getAlgorithm(), ex); } @@ -189,7 +189,7 @@ final class DHServerKeyExchange { new BigInteger(1, p), new BigInteger(1, p))); } catch (InvalidKeyException ike) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid DH ServerKeyExchange: invalid parameters", ike); } @@ -204,7 +204,7 @@ final class DHServerKeyExchange { if (x509Credentials == null) { // anonymous, no authentication, no signature if (m.hasRemaining()) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid DH ServerKeyExchange: unknown extra data"); } @@ -221,13 +221,13 @@ final class DHServerKeyExchange { int ssid = Record.getInt16(m); signatureScheme = SignatureScheme.valueOf(ssid); if (signatureScheme == null) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature algorithm (" + ssid + ") used in DH ServerKeyExchange handshake message"); } if (!chc.localSupportedSignAlgs.contains(signatureScheme)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsupported signature algorithm (" + signatureScheme.name + ") used in DH ServerKeyExchange handshake message"); @@ -245,11 +245,9 @@ final class DHServerKeyExchange { x509Credentials.popPublicKey); } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException nsae) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + signatureScheme.name, nsae); - - return; // make the compiler happe } } else { try { @@ -257,11 +255,9 @@ final class DHServerKeyExchange { x509Credentials.popPublicKey.getAlgorithm(), x509Credentials.popPublicKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + x509Credentials.popPublicKey.getAlgorithm(), e); - - return; // make the compiler happe } } @@ -271,11 +267,11 @@ final class DHServerKeyExchange { chc.serverHelloRandom.randomBytes); if (!signer.verify(paramsSignature)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature on DH ServerKeyExchange message"); } } catch (SignatureException ex) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify DH ServerKeyExchange signature", ex); } } @@ -535,15 +531,13 @@ final class DHServerKeyExchange { new BigInteger(1, skem.g)); publicKey = (DHPublicKey)kf.generatePublic(spec); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, "Could not generate DHPublicKey", gse); - - return; // make the compiler happy } if (!chc.algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, "DH ServerKeyExchange does not comply to " + "algorithm constraints"); } diff --git a/src/java.base/share/classes/sun/security/ssl/ECDHClientKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ECDHClientKeyExchange.java index 672aeaeca9a..4ee812f2201 100644 --- a/src/java.base/share/classes/sun/security/ssl/ECDHClientKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ECDHClientKeyExchange.java @@ -190,20 +190,20 @@ final class ECDHClientKeyExchange { } if (x509Credentials == null) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "No server certificate for ECDH client key exchange"); } PublicKey publicKey = x509Credentials.popPublicKey; if (!publicKey.getAlgorithm().equals("EC")) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Not EC server certificate for ECDH client key exchange"); } ECParameterSpec params = ((ECPublicKey)publicKey).getParams(); NamedGroup namedGroup = NamedGroup.valueOf(params); if (namedGroup == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported EC server cert for ECDH client key exchange"); } @@ -228,7 +228,7 @@ final class ECDHClientKeyExchange { chc.negotiatedProtocol); if (ke == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } else { SSLKeyDerivation masterKD = ke.createKeyDerivation(chc); @@ -240,7 +240,7 @@ final class ECDHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); } else { @@ -280,15 +280,14 @@ final class ECDHClientKeyExchange { if (x509Possession == null) { // unlikely, have been checked during cipher suite negotiation. - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "No expected EC server cert for ECDH client key exchange"); - return; // make the compiler happy } PrivateKey privateKey = x509Possession.popPrivateKey; if (!privateKey.getAlgorithm().equals("EC")) { // unlikely, have been checked during cipher suite negotiation. - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Not EC server cert for ECDH client key exchange"); } @@ -296,7 +295,7 @@ final class ECDHClientKeyExchange { NamedGroup namedGroup = NamedGroup.valueOf(params); if (namedGroup == null) { // unlikely, have been checked during cipher suite negotiation. - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported EC server cert for ECDH client key exchange"); } @@ -305,9 +304,8 @@ final class ECDHClientKeyExchange { shc.negotiatedProtocol); if (ke == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); - return; // make the compiler happy } // parse the handshake message @@ -353,7 +351,7 @@ final class ECDHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); } else { shc.handshakeKeyDerivation = @@ -387,7 +385,7 @@ final class ECDHClientKeyExchange { } if (ecdheCredentials == null) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "No ECDHE credentials negotiated for client key exchange"); } @@ -412,7 +410,7 @@ final class ECDHClientKeyExchange { chc.negotiatedProtocol); if (ke == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } else { SSLKeyDerivation masterKD = ke.createKeyDerivation(chc); @@ -424,7 +422,7 @@ final class ECDHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); } else { @@ -463,16 +461,15 @@ final class ECDHClientKeyExchange { } if (ecdhePossession == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "No expected ECDHE possessions for client key exchange"); - return; // make the compiler happy } ECParameterSpec params = ecdhePossession.publicKey.getParams(); NamedGroup namedGroup = NamedGroup.valueOf(params); if (namedGroup == null) { // unlikely, have been checked during cipher suite negotiation. - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported EC server cert for ECDHE client key exchange"); } @@ -481,9 +478,8 @@ final class ECDHClientKeyExchange { shc.negotiatedProtocol); if (ke == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); - return; // make the compiler happy } // parse the handshake message @@ -529,7 +525,7 @@ final class ECDHClientKeyExchange { SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); } else { shc.handshakeKeyDerivation = diff --git a/src/java.base/share/classes/sun/security/ssl/ECDHKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ECDHKeyExchange.java index 64423669d19..668247cd99e 100644 --- a/src/java.base/share/classes/sun/security/ssl/ECDHKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ECDHKeyExchange.java @@ -274,7 +274,7 @@ final class ECDHKeyExchange { NamedGroup ng = NamedGroup.valueOf(params); if (ng == null) { // unlikely, have been checked during cipher suite negotiation. - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported EC server cert for ECDH key exchange"); } @@ -295,7 +295,7 @@ final class ECDHKeyExchange { } if (x509Possession == null || ecdheCredentials == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No sufficient ECDHE key agreement parameters negotiated"); } @@ -327,7 +327,7 @@ final class ECDHKeyExchange { NamedGroup namedGroup = NamedGroup.valueOf(params); if (namedGroup == null) { // unlikely, should have been checked previously - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported EC server cert for ECDH key exchange"); } @@ -344,7 +344,7 @@ final class ECDHKeyExchange { } if (ecdhePossession == null || x509Credentials == null) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No sufficient ECDH key agreement parameters negotiated"); } @@ -388,7 +388,7 @@ final class ECDHKeyExchange { } if (ecdhePossession == null || ecdheCredentials == null) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No sufficient ECDHE key agreement parameters negotiated"); } diff --git a/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java index 62f660e586e..bbd9a6b3ebb 100644 --- a/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ECDHServerKeyExchange.java @@ -113,7 +113,7 @@ final class ECDHServerKeyExchange { if (ecdhePossession == null) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No ECDHE credentials negotiated for server key exchange"); } @@ -125,7 +125,7 @@ final class ECDHServerKeyExchange { this.namedGroup = NamedGroup.valueOf(params); if ((namedGroup == null) || (namedGroup.oid == null) ) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unnamed EC parameter spec: " + params); } @@ -146,7 +146,7 @@ final class ECDHServerKeyExchange { if (signatureScheme == null) { // Unlikely, the credentials generator should have // selected the preferable signature algorithm properly. - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "No preferred signature algorithm for " + x509Possession.popPrivateKey.getAlgorithm() + " key"); @@ -156,7 +156,7 @@ final class ECDHServerKeyExchange { x509Possession.popPrivateKey); } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException nsae) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + signatureScheme.name, nsae); } @@ -167,7 +167,7 @@ final class ECDHServerKeyExchange { x509Possession.popPrivateKey.getAlgorithm(), x509Possession.popPrivateKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + x509Possession.popPrivateKey.getAlgorithm(), e); } @@ -180,7 +180,7 @@ final class ECDHServerKeyExchange { namedGroup.id, publicPoint); signature = signer.sign(); } catch (SignatureException ex) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failed to sign ecdhe parameters: " + x509Possession.popPrivateKey.getAlgorithm(), ex); } @@ -199,37 +199,37 @@ final class ECDHServerKeyExchange { byte curveType = (byte)Record.getInt8(m); if (curveType != CURVE_NAMED_CURVE) { // Unlikely as only the named curves should be negotiated. - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported ECCurveType: " + curveType); } int namedGroupId = Record.getInt16(m); this.namedGroup = NamedGroup.valueOf(namedGroupId); if (namedGroup == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unknown named group ID: " + namedGroupId); } if (!SupportedGroups.isSupported(namedGroup)) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unsupported named group: " + namedGroup); } if (namedGroup.oid == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Unknown named EC curve: " + namedGroup); } ECParameterSpec parameters = JsseJce.getECParameterSpec(namedGroup.oid); if (parameters == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No supported EC parameter: " + namedGroup); } publicPoint = Record.getBytes8(m); if (publicPoint.length == 0) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Insufficient ECPoint data: " + namedGroup); } @@ -242,7 +242,7 @@ final class ECDHServerKeyExchange { new ECPublicKeySpec(point, parameters)); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException ex) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid ECPoint: " + namedGroup, ex); } @@ -259,7 +259,7 @@ final class ECDHServerKeyExchange { if (x509Credentials == null) { // anonymous, no authentication, no signature if (m.hasRemaining()) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid DH ServerKeyExchange: unknown extra data"); } this.signatureScheme = null; @@ -275,13 +275,13 @@ final class ECDHServerKeyExchange { int ssid = Record.getInt16(m); signatureScheme = SignatureScheme.valueOf(ssid); if (signatureScheme == null) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature algorithm (" + ssid + ") used in ECDH ServerKeyExchange handshake message"); } if (!chc.localSupportedSignAlgs.contains(signatureScheme)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsupported signature algorithm (" + signatureScheme.name + ") used in ECDH ServerKeyExchange handshake message"); @@ -299,11 +299,9 @@ final class ECDHServerKeyExchange { x509Credentials.popPublicKey); } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException nsae) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + signatureScheme.name, nsae); - - return; // make the compiler happe } } else { try { @@ -311,11 +309,9 @@ final class ECDHServerKeyExchange { x509Credentials.popPublicKey.getAlgorithm(), x509Credentials.popPublicKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Unsupported signature algorithm: " + x509Credentials.popPublicKey.getAlgorithm(), e); - - return; // make the compiler happe } } @@ -326,11 +322,11 @@ final class ECDHServerKeyExchange { namedGroup.id, publicPoint); if (!signer.verify(paramsSignature)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid ECDH ServerKeyExchange signature"); } } catch (SignatureException ex) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Cannot verify ECDH ServerKeyExchange signature", ex); } } @@ -546,7 +542,7 @@ final class ECDHServerKeyExchange { if (!chc.algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), skem.publicKey)) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, "ECDH ServerKeyExchange does not comply " + "to algorithm constraints"); } diff --git a/src/java.base/share/classes/sun/security/ssl/ECPointFormatsExtension.java b/src/java.base/share/classes/sun/security/ssl/ECPointFormatsExtension.java index 0986d2e87eb..f6dc7db7674 100644 --- a/src/java.base/share/classes/sun/security/ssl/ECPointFormatsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/ECPointFormatsExtension.java @@ -231,13 +231,12 @@ final class ECPointFormatsExtension { try { spec = new ECPointFormatsSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // per RFC 4492, uncompressed points must always be supported. if (!spec.hasUncompressedFormat()) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid ec_point_formats extension data: " + "peer does not support uncompressed points"); } @@ -272,7 +271,7 @@ final class ECPointFormatsExtension { ECPointFormatsSpec requestedSpec = (ECPointFormatsSpec) chc.handshakeExtensions.get(CH_EC_POINT_FORMATS); if (requestedSpec == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ec_point_formats extension in ServerHello"); } @@ -281,13 +280,12 @@ final class ECPointFormatsExtension { try { spec = new ECPointFormatsSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // per RFC 4492, uncompressed points must always be supported. if (!spec.hasUncompressedFormat()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid ec_point_formats extension data: " + "peer does not support uncompressed points"); } diff --git a/src/java.base/share/classes/sun/security/ssl/EncryptedExtensions.java b/src/java.base/share/classes/sun/security/ssl/EncryptedExtensions.java index ec631d3f1f2..0792d97248d 100644 --- a/src/java.base/share/classes/sun/security/ssl/EncryptedExtensions.java +++ b/src/java.base/share/classes/sun/security/ssl/EncryptedExtensions.java @@ -60,7 +60,7 @@ final class EncryptedExtensions { // Extension extensions<0..2^16-1>; // } EncryptedExtensions; if (m.remaining() < 2) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid EncryptedExtensions handshake message: " + "no sufficient data"); } diff --git a/src/java.base/share/classes/sun/security/ssl/ExtendedMasterSecretExtension.java b/src/java.base/share/classes/sun/security/ssl/ExtendedMasterSecretExtension.java index 85d31f344d0..7db4840996e 100644 --- a/src/java.base/share/classes/sun/security/ssl/ExtendedMasterSecretExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/ExtendedMasterSecretExtension.java @@ -172,8 +172,7 @@ final class ExtendedMasterSecretExtension { try { spec = new ExtendedMasterSecretSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (shc.isResumption && shc.resumingSession != null && @@ -232,7 +231,7 @@ final class ExtendedMasterSecretExtension { // // As if extended master extension is required for full // handshake, it MUST be used in abbreviated handshake too. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Extended Master Secret extension is required"); } @@ -242,7 +241,7 @@ final class ExtendedMasterSecretExtension { // session used the "extended_master_secret" extension // but the new ClientHello does not contain it, the // server MUST abort the abbreviated handshake. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing Extended Master Secret extension " + "on session resumption"); } else { @@ -250,7 +249,7 @@ final class ExtendedMasterSecretExtension { // original session nor the new ClientHello uses the // extension, the server SHOULD abort the handshake. if (!SSLConfiguration.allowLegacyResumption) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing Extended Master Secret extension " + "on session resumption"); } else { // Otherwise, continue with a full handshake. @@ -318,7 +317,7 @@ final class ExtendedMasterSecretExtension { ExtendedMasterSecretSpec requstedSpec = (ExtendedMasterSecretSpec) chc.handshakeExtensions.get(CH_EXTENDED_MASTER_SECRET); if (requstedSpec == null) { - chc.conContext.fatal(Alert.UNSUPPORTED_EXTENSION, + throw chc.conContext.fatal(Alert.UNSUPPORTED_EXTENSION, "Server sent the extended_master_secret " + "extension improperly"); } @@ -328,13 +327,12 @@ final class ExtendedMasterSecretExtension { try { spec = new ExtendedMasterSecretSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (chc.isResumption && chc.resumingSession != null && !chc.resumingSession.useExtendedMasterSecret) { - chc.conContext.fatal(Alert.UNSUPPORTED_EXTENSION, + throw chc.conContext.fatal(Alert.UNSUPPORTED_EXTENSION, "Server sent an unexpected extended_master_secret " + "extension on session resumption"); } @@ -364,7 +362,7 @@ final class ExtendedMasterSecretExtension { // For full handshake, if a client receives a ServerHello // without the extension, it SHOULD abort the handshake if // it does not wish to interoperate with legacy servers. - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Extended Master Secret extension is required"); } @@ -374,14 +372,14 @@ final class ExtendedMasterSecretExtension { // the "extended_master_secret" extension but the new // ServerHello does not contain the extension, the client // MUST abort the handshake. - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing Extended Master Secret extension " + "on session resumption"); } else if (SSLConfiguration.useExtendedMasterSecret && !SSLConfiguration.allowLegacyResumption && chc.negotiatedProtocol.useTLS10PlusSpec()) { // Unlikely, abbreviated handshake should be discarded. - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Extended Master Secret extension is required"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/Finished.java b/src/java.base/share/classes/sun/security/ssl/Finished.java index 47a071027b4..aabf09a290f 100644 --- a/src/java.base/share/classes/sun/security/ssl/Finished.java +++ b/src/java.base/share/classes/sun/security/ssl/Finished.java @@ -83,7 +83,7 @@ final class Finished { try { vd = vds.createVerifyData(context, false); } catch (IOException ioe) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Failed to generate verify_data", ioe); } @@ -102,7 +102,7 @@ final class Finished { } if (m.remaining() != verifyDataLen) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Inappropriate finished message: need " + verifyDataLen + " but remaining " + m.remaining() + " bytes verify_data"); } @@ -116,12 +116,11 @@ final class Finished { try { myVerifyData = vd.createVerifyData(context, true); } catch (IOException ioe) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Failed to generate verify_data", ioe); - return; } if (!MessageDigest.isEqual(myVerifyData, verifyData)) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "The Finished message cannot be verified."); } } @@ -518,7 +517,7 @@ final class Finished { // we have received ChangeCipherSpec if (hc.conContext.consumers.containsKey( ContentType.CHANGE_CIPHER_SPEC.id)) { - hc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw hc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Missing ChangeCipherSpec message"); } @@ -679,19 +678,17 @@ final class Finished { SSLKeyDerivation kd = chc.handshakeKeyDerivation; if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return null; } SSLTrafficKeyDerivation kdg = SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kdg == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return null; } try { @@ -714,12 +711,10 @@ final class Finished { chc.sslContext.getSecureRandom()); if (writeCipher == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + chc.negotiatedCipherSuite + ") and protocol version (" + chc.negotiatedProtocol + ")"); - - return null; } chc.baseWriteSecret = writeSecret; @@ -727,9 +722,8 @@ final class Finished { writeCipher, false); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return null; } // The resumption master secret is stored in the session so @@ -772,19 +766,17 @@ final class Finished { SSLKeyDerivation kd = shc.handshakeKeyDerivation; if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return null; } SSLTrafficKeyDerivation kdg = SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kdg == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return null; } // derive salt secret @@ -821,12 +813,10 @@ final class Finished { shc.sslContext.getSecureRandom()); if (writeCipher == null) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + shc.negotiatedCipherSuite + ") and protocol version (" + shc.negotiatedProtocol + ")"); - - return null; } shc.baseWriteSecret = writeSecret; @@ -836,9 +826,8 @@ final class Finished { // update the context for the following key derivation shc.handshakeKeyDerivation = secretKD; } catch (GeneralSecurityException gse) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return null; } /* @@ -911,19 +900,17 @@ final class Finished { SSLKeyDerivation kd = chc.handshakeKeyDerivation; if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return; } SSLTrafficKeyDerivation kdg = SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kdg == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return; } // save the session @@ -967,12 +954,10 @@ final class Finished { chc.sslContext.getSecureRandom()); if (readCipher == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + chc.negotiatedCipherSuite + ") and protocol version (" + chc.negotiatedProtocol + ")"); - - return; } chc.baseReadSecret = readSecret; @@ -981,9 +966,8 @@ final class Finished { // update the context for the following key derivation chc.handshakeKeyDerivation = secretKD; } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return; } // @@ -1031,19 +1015,17 @@ final class Finished { SSLKeyDerivation kd = shc.handshakeKeyDerivation; if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return; } SSLTrafficKeyDerivation kdg = SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kdg == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return; } // save the session @@ -1073,12 +1055,10 @@ final class Finished { shc.sslContext.getSecureRandom()); if (readCipher == null) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + shc.negotiatedCipherSuite + ") and protocol version (" + shc.negotiatedProtocol + ")"); - - return; } shc.baseReadSecret = readSecret; @@ -1094,9 +1074,8 @@ final class Finished { shc.handshakeSession.setResumptionMasterSecret( resumptionMasterSecret); } catch (GeneralSecurityException gse) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive application secrets", gse); - return; } // update connection context diff --git a/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java b/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java index fd7b7784a5a..a95c691b943 100644 --- a/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java +++ b/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java @@ -365,26 +365,20 @@ abstract class HandshakeContext implements ConnectionContext { // } Handshake; if (plaintext.contentType != ContentType.HANDSHAKE.id) { - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "Unexpected operation for record: " + plaintext.contentType); - - return 0; } if (plaintext.fragment == null || plaintext.fragment.remaining() < 4) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid handshake message: insufficient data"); - - return 0; } byte handshakeType = (byte)Record.getInt8(plaintext.fragment); int handshakeLen = Record.getInt24(plaintext.fragment); if (handshakeLen != plaintext.fragment.remaining()) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid handshake message: insufficient handshake body"); - - return 0; } return handshakeType; @@ -438,16 +432,15 @@ abstract class HandshakeContext implements ConnectionContext { } if (consumer == null) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected handshake message: " + SSLHandshake.nameOf(handshakeType)); - return; } try { consumer.consume(this, fragment); } catch (UnsupportedOperationException unsoe) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported handshake message: " + SSLHandshake.nameOf(handshakeType), unsoe); } diff --git a/src/java.base/share/classes/sun/security/ssl/HelloRequest.java b/src/java.base/share/classes/sun/security/ssl/HelloRequest.java index 26560fd908b..395451a01ae 100644 --- a/src/java.base/share/classes/sun/security/ssl/HelloRequest.java +++ b/src/java.base/share/classes/sun/security/ssl/HelloRequest.java @@ -59,7 +59,7 @@ final class HelloRequest { ByteBuffer m) throws IOException { super(handshakeContext); if (m.hasRemaining()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Error parsing HelloRequest message: not empty"); } } @@ -185,7 +185,7 @@ final class HelloRequest { if (!chc.kickstartMessageDelivered) { if (!chc.conContext.secureRenegotiation && !HandshakeContext.allowUnsafeRenegotiation) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsafe renegotiation is not allowed"); } diff --git a/src/java.base/share/classes/sun/security/ssl/HelloVerifyRequest.java b/src/java.base/share/classes/sun/security/ssl/HelloVerifyRequest.java index e0f673ed1a7..1417087e4bc 100644 --- a/src/java.base/share/classes/sun/security/ssl/HelloVerifyRequest.java +++ b/src/java.base/share/classes/sun/security/ssl/HelloVerifyRequest.java @@ -73,7 +73,7 @@ final class HelloVerifyRequest { // opaque cookie<0..2^8-1>; // } HelloVerifyRequest; if (m.remaining() < 3) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid HelloVerifyRequest: no sufficient data"); } @@ -186,7 +186,7 @@ final class HelloVerifyRequest { chc.handshakeConsumers.remove(SSLHandshake.SERVER_HELLO.id); } if (!chc.handshakeConsumers.isEmpty()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "No more message expected before " + "HelloVerifyRequest is processed"); } diff --git a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java index 83dab2cdf3c..c54bf66f380 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java @@ -337,8 +337,7 @@ final class KeyShareExtension { try { spec = new CHKeyShareSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } List credentials = new LinkedList<>(); @@ -610,16 +609,14 @@ final class KeyShareExtension { if (chc.clientRequestedNamedGroups == null || chc.clientRequestedNamedGroups.isEmpty()) { // No supported groups. - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected key_share extension in ServerHello"); - return; // fatal() always throws, make the compiler happy. } // Is it a supported and enabled extension? if (!chc.sslConfig.isAvailable(SSLExtension.SH_KEY_SHARE)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported key_share extension in ServerHello"); - return; // fatal() always throws, make the compiler happy. } // Parse the extension @@ -627,25 +624,22 @@ final class KeyShareExtension { try { spec = new SHKeyShareSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } KeyShareEntry keyShare = spec.serverShare; NamedGroup ng = NamedGroup.valueOf(keyShare.namedGroupId); if (ng == null || !SupportedGroups.isActivatable( chc.sslConfig.algorithmConstraints, ng)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported named group: " + NamedGroup.nameOf(keyShare.namedGroupId)); - return; // fatal() always throws, make the compiler happy. } SSLKeyExchange ke = SSLKeyExchange.valueOf(ng); if (ke == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "No key exchange for named group " + ng.name); - return; // fatal() always throws, make the compiler happy. } SSLCredentials credentials = null; @@ -657,7 +651,7 @@ final class KeyShareExtension { if (!chc.algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), ecdhec.popPublicKey)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "ECDHE key share entry does not " + "comply to algorithm constraints"); } else { @@ -665,7 +659,7 @@ final class KeyShareExtension { } } } catch (IOException | GeneralSecurityException ex) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Cannot decode named group: " + NamedGroup.nameOf(keyShare.namedGroupId)); } @@ -677,7 +671,7 @@ final class KeyShareExtension { if (!chc.algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), dhec.popPublicKey)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "DHE key share entry does not " + "comply to algorithm constraints"); } else { @@ -685,18 +679,18 @@ final class KeyShareExtension { } } } catch (IOException | GeneralSecurityException ex) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Cannot decode named group: " + NamedGroup.nameOf(keyShare.namedGroupId)); } } else { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported named group: " + NamedGroup.nameOf(keyShare.namedGroupId)); } if (credentials == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported named group: " + ng.name); } @@ -794,17 +788,15 @@ final class KeyShareExtension { // Is it a supported and enabled extension? if (!shc.sslConfig.isAvailable(SSLExtension.HRR_KEY_SHARE)) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported key_share extension in HelloRetryRequest"); - return null; // make the compiler happy. } if (shc.clientRequestedNamedGroups == null || shc.clientRequestedNamedGroups.isEmpty()) { // No supported groups. - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected key_share extension in HelloRetryRequest"); - return null; // make the compiler happy. } NamedGroup selectedGroup = null; @@ -823,9 +815,8 @@ final class KeyShareExtension { } if (selectedGroup == null) { - shc.conContext.fatal( + throw shc.conContext.fatal( Alert.UNEXPECTED_MESSAGE, "No common named group"); - return null; // make the complier happy } byte[] extdata = new byte[] { @@ -861,9 +852,8 @@ final class KeyShareExtension { // Is it a supported and enabled extension? if (!shc.sslConfig.isAvailable(SSLExtension.HRR_KEY_SHARE)) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported key_share extension in HelloRetryRequest"); - return null; // make the compiler happy. } CHKeyShareSpec spec = (CHKeyShareSpec)shc.handshakeExtensions.get( @@ -903,17 +893,15 @@ final class KeyShareExtension { // Is it a supported and enabled extension? if (!chc.sslConfig.isAvailable(SSLExtension.HRR_KEY_SHARE)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported key_share extension in HelloRetryRequest"); - return; // make the compiler happy. } if (chc.clientRequestedNamedGroups == null || chc.clientRequestedNamedGroups.isEmpty()) { // No supported groups. - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected key_share extension in HelloRetryRequest"); - return; // make the compiler happy. } // Parse the extension @@ -921,23 +909,20 @@ final class KeyShareExtension { try { spec = new HRRKeyShareSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } NamedGroup serverGroup = NamedGroup.valueOf(spec.selectedGroup); if (serverGroup == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported HelloRetryRequest selected group: " + NamedGroup.nameOf(spec.selectedGroup)); - return; // fatal() always throws, make the compiler happy. } if (!chc.clientRequestedNamedGroups.contains(serverGroup)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected HelloRetryRequest selected group: " + serverGroup.name); - return; // fatal() always throws, make the compiler happy. } // update the context diff --git a/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java b/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java index 8477e69db48..13063444ee6 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyUpdate.java @@ -78,7 +78,7 @@ final class KeyUpdate { super(context); if (m.remaining() != 1) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "KeyUpdate has an unexpected length of "+ m.remaining()); } @@ -86,7 +86,7 @@ final class KeyUpdate { byte request = m.get(); this.status = KeyUpdateRequest.valueOf(request); if (status == null) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid KeyUpdate message value: " + KeyUpdateRequest.nameOf(request)); } @@ -198,18 +198,17 @@ final class KeyUpdate { SSLTrafficKeyDerivation.valueOf(hc.conContext.protocolVersion); if (kdg == null) { // unlikely - hc.conContext.fatal(Alert.INTERNAL_ERROR, + throw hc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + hc.conContext.protocolVersion); - return; } SSLKeyDerivation skd = kdg.createKeyDerivation(hc, hc.conContext.inputRecord.readCipher.baseSecret); if (skd == null) { // unlikely - hc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return; + throw hc.conContext.fatal( + Alert.INTERNAL_ERROR, "no key derivation"); } SecretKey nplus1 = skd.deriveKey("TlsUpdateNplus1", null); @@ -225,12 +224,10 @@ final class KeyUpdate { hc.sslContext.getSecureRandom()); if (rc == null) { - hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + hc.negotiatedCipherSuite + ") and protocol version (" + hc.negotiatedProtocol + ")"); - - return; } rc.baseSecret = nplus1; @@ -239,9 +236,8 @@ final class KeyUpdate { SSLLogger.fine("KeyUpdate: read key updated"); } } catch (GeneralSecurityException gse) { - hc.conContext.fatal(Alert.INTERNAL_ERROR, + throw hc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive read secrets", gse); - return; } if (km.status == KeyUpdateRequest.REQUESTED) { @@ -281,18 +277,17 @@ final class KeyUpdate { SSLTrafficKeyDerivation.valueOf(hc.conContext.protocolVersion); if (kdg == null) { // unlikely - hc.conContext.fatal(Alert.INTERNAL_ERROR, + throw hc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + hc.conContext.protocolVersion); - return null; } SSLKeyDerivation skd = kdg.createKeyDerivation(hc, hc.conContext.outputRecord.writeCipher.baseSecret); if (skd == null) { // unlikely - hc.conContext.fatal(Alert.INTERNAL_ERROR, "no key derivation"); - return null; + throw hc.conContext.fatal( + Alert.INTERNAL_ERROR, "no key derivation"); } SecretKey nplus1 = skd.deriveKey("TlsUpdateNplus1", null); @@ -308,17 +303,14 @@ final class KeyUpdate { hc.conContext.protocolVersion, key, ivSpec, hc.sslContext.getSecureRandom()); } catch (GeneralSecurityException gse) { - hc.conContext.fatal(Alert.INTERNAL_ERROR, + throw hc.conContext.fatal(Alert.INTERNAL_ERROR, "Failure to derive write secrets", gse); - return null; } if (wc == null) { - hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw hc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + hc.negotiatedCipherSuite + ") and protocol version (" + hc.negotiatedProtocol + ")"); - - return null; } // Output the handshake message and change the write cipher. diff --git a/src/java.base/share/classes/sun/security/ssl/MaxFragExtension.java b/src/java.base/share/classes/sun/security/ssl/MaxFragExtension.java index 73428e39b10..4a3bb8181bd 100644 --- a/src/java.base/share/classes/sun/security/ssl/MaxFragExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/MaxFragExtension.java @@ -253,13 +253,12 @@ final class MaxFragExtension { try { spec = new MaxFragLenSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } MaxFragLenEnum mfle = MaxFragLenEnum.valueOf(spec.id); if (mfle == null) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "the requested maximum fragment length is other " + "than the allowed values"); } @@ -359,7 +358,7 @@ final class MaxFragExtension { MaxFragLenSpec requestedSpec = (MaxFragLenSpec) chc.handshakeExtensions.get(CH_MAX_FRAGMENT_LENGTH); if (requestedSpec == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected max_fragment_length extension in ServerHello"); } @@ -368,18 +367,17 @@ final class MaxFragExtension { try { spec = new MaxFragLenSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (spec.id != requestedSpec.id) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "The maximum fragment length response is not requested"); } MaxFragLenEnum mfle = MaxFragLenEnum.valueOf(spec.id); if (mfle == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "the requested maximum fragment length is other " + "than the allowed values"); } @@ -532,7 +530,7 @@ final class MaxFragExtension { MaxFragLenSpec requestedSpec = (MaxFragLenSpec) chc.handshakeExtensions.get(CH_MAX_FRAGMENT_LENGTH); if (requestedSpec == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected max_fragment_length extension in ServerHello"); } @@ -541,18 +539,17 @@ final class MaxFragExtension { try { spec = new MaxFragLenSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (spec.id != requestedSpec.id) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "The maximum fragment length response is not requested"); } MaxFragLenEnum mfle = MaxFragLenEnum.valueOf(spec.id); if (mfle == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "the requested maximum fragment length is other " + "than the allowed values"); } diff --git a/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java b/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java index f40bef36ce5..bf89ac48e4f 100644 --- a/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java +++ b/src/java.base/share/classes/sun/security/ssl/NewSessionTicket.java @@ -86,7 +86,7 @@ final class NewSessionTicket { // Extension extensions<0..2^16-2>; // } NewSessionTicket; if (m.remaining() < 14) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid NewSessionTicket message: no sufficient data"); } @@ -95,18 +95,18 @@ final class NewSessionTicket { this.ticketNonce = Record.getBytes8(m); if (m.remaining() < 5) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid NewSessionTicket message: no sufficient data"); } this.ticket = Record.getBytes16(m); if (ticket.length == 0) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No ticket in the NewSessionTicket handshake message"); } if (m.remaining() < 2) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid NewSessionTicket message: no sufficient data"); } diff --git a/src/java.base/share/classes/sun/security/ssl/PostHandshakeContext.java b/src/java.base/share/classes/sun/security/ssl/PostHandshakeContext.java index 1c899751a09..3b4044d8a4c 100644 --- a/src/java.base/share/classes/sun/security/ssl/PostHandshakeContext.java +++ b/src/java.base/share/classes/sun/security/ssl/PostHandshakeContext.java @@ -43,7 +43,7 @@ final class PostHandshakeContext extends HandshakeContext { super(context); if (!negotiatedProtocol.useTLS13PlusSpec()) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Post-handshake not supported in " + negotiatedProtocol.name); } @@ -63,16 +63,15 @@ final class PostHandshakeContext extends HandshakeContext { void dispatch(byte handshakeType, ByteBuffer fragment) throws IOException { SSLConsumer consumer = handshakeConsumers.get(handshakeType); if (consumer == null) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected post-handshake message: " + SSLHandshake.nameOf(handshakeType)); - return; } try { consumer.consume(this, fragment); } catch (UnsupportedOperationException unsoe) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unsupported post-handshake message: " + SSLHandshake.nameOf(handshakeType), unsoe); } diff --git a/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java b/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java index dc313a8cc72..de485e23d89 100644 --- a/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/PreSharedKeyExtension.java @@ -111,14 +111,14 @@ final class PreSharedKeyExtension { // PskBinderEntry binders<33..2^16-1>; // } OfferedPsks; if (m.remaining() < 44) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient data (length=" + m.remaining() + ")"); } int idEncodedLength = Record.getInt16(m); if (idEncodedLength < 7) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient identities (length=" + idEncodedLength + ")"); } @@ -128,7 +128,7 @@ final class PreSharedKeyExtension { while (idReadLength < idEncodedLength) { byte[] id = Record.getBytes16(m); if (id.length < 1) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient identity (length=" + id.length + ")"); } @@ -140,7 +140,7 @@ final class PreSharedKeyExtension { } if (m.remaining() < 35) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient binders data (length=" + m.remaining() + ")"); @@ -148,7 +148,7 @@ final class PreSharedKeyExtension { int bindersEncodedLen = Record.getInt16(m); if (bindersEncodedLen < 33) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient binders (length=" + bindersEncodedLen + ")"); @@ -159,7 +159,7 @@ final class PreSharedKeyExtension { while (bindersReadLength < bindersEncodedLen) { byte[] binder = Record.getBytes8(m); if (binder.length < 32) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient binder entry (length=" + binder.length + ")"); @@ -271,7 +271,7 @@ final class PreSharedKeyExtension { SHPreSharedKeySpec(HandshakeContext context, ByteBuffer m) throws IOException { if (m.remaining() < 2) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Invalid pre_shared_key extension: " + "insufficient selected_identity (length=" + m.remaining() + ")"); @@ -348,21 +348,20 @@ final class PreSharedKeyExtension { try { pskSpec = new CHPreSharedKeySpec(shc, buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // The "psk_key_exchange_modes" extension should have been loaded. if (!shc.handshakeExtensions.containsKey( SSLExtension.PSK_KEY_EXCHANGE_MODES)) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Client sent PSK but not PSK modes, or the PSK " + "extension is not the last extension"); } // error if id and binder lists are not the same length if (pskSpec.identities.size() != pskSpec.binders.size()) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "PSK extension has incorrect number of binders"); } @@ -506,7 +505,7 @@ final class PreSharedKeyExtension { SHPreSharedKeySpec shPsk = (SHPreSharedKeySpec) shc.handshakeExtensions.get(SSLExtension.SH_PRE_SHARED_KEY); if (chPsk == null || shPsk == null) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Required extensions are unavailable"); } @@ -533,7 +532,7 @@ final class PreSharedKeyExtension { HandshakeHash pskBinderHash, byte[] binder) throws IOException { Optional pskOpt = session.getPreSharedKey(); if (!pskOpt.isPresent()) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Session has no PSK"); } SecretKey psk = pskOpt.get(); @@ -542,7 +541,7 @@ final class PreSharedKeyExtension { byte[] computedBinder = computeBinder(shc, binderKey, session, pskBinderHash); if (!Arrays.equals(binder, computedBinder)) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Incorect PSK binder value"); } } @@ -770,12 +769,10 @@ final class PreSharedKeyExtension { hmac.init(finishedKey); return hmac.doFinal(digest); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { - context.conContext.fatal(Alert.INTERNAL_ERROR, ex); - return null; // fatal() always throws, make the compiler happy. + throw context.conContext.fatal(Alert.INTERNAL_ERROR, ex); } } catch (GeneralSecurityException ex) { - context.conContext.fatal(Alert.INTERNAL_ERROR, ex); - return null; // fatal() always throws, make the compiler happy. + throw context.conContext.fatal(Alert.INTERNAL_ERROR, ex); } } @@ -794,8 +791,7 @@ final class PreSharedKeyExtension { return hkdf.expand(earlySecret, hkdfInfo, hashAlg.hashLength, "TlsBinderKey"); } catch (GeneralSecurityException ex) { - context.conContext.fatal(Alert.INTERNAL_ERROR, ex); - return null; // fatal() always throws, make the compiler happy. + throw context.conContext.fatal(Alert.INTERNAL_ERROR, ex); } } @@ -834,7 +830,7 @@ final class PreSharedKeyExtension { // Is it a response of the specific request? if (!chc.handshakeExtensions.containsKey( SSLExtension.CH_PRE_SHARED_KEY)) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Server sent unexpected pre_shared_key extension"); } @@ -845,7 +841,7 @@ final class PreSharedKeyExtension { } if (shPsk.selectedIdentity != 0) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Selected identity index is not in correct range."); } diff --git a/src/java.base/share/classes/sun/security/ssl/PskKeyExchangeModesExtension.java b/src/java.base/share/classes/sun/security/ssl/PskKeyExchangeModesExtension.java index 456db23a4c1..8680c6ceeed 100644 --- a/src/java.base/share/classes/sun/security/ssl/PskKeyExchangeModesExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/PskKeyExchangeModesExtension.java @@ -201,8 +201,7 @@ final class PskKeyExchangeModesExtension { try { spec = new PskKeyExchangeModesSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -324,7 +323,7 @@ final class PskKeyExchangeModesExtension { SSLExtensionSpec spec = shc.handshakeExtensions.get(SSLExtension.CH_PRE_SHARED_KEY); if (spec != null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "pre_shared_key key extension is offered " + "without a psk_key_exchange_modes extension"); } diff --git a/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java index 912e7de6b40..de26cf91f2e 100644 --- a/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java @@ -75,7 +75,7 @@ final class RSAClientKeyExchange { super(context); if (m.remaining() < 2) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid RSA ClientKeyExchange message: insufficient data"); } @@ -167,14 +167,14 @@ final class RSAClientKeyExchange { } if (rsaCredentials == null && x509Credentials == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No RSA credentials negotiated for client key exchange"); } PublicKey publicKey = (rsaCredentials != null) ? rsaCredentials.popPublicKey : x509Credentials.popPublicKey; if (!publicKey.getAlgorithm().equals("RSA")) { // unlikely - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Not RSA public key for client key exchange"); } @@ -186,10 +186,8 @@ final class RSAClientKeyExchange { ckem = new RSAClientKeyExchangeMessage( chc, premaster, publicKey); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Cannot generate RSA premaster secret", gse); - - return null; // make the compiler happy } if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine( @@ -205,7 +203,7 @@ final class RSAClientKeyExchange { chc.negotiatedCipherSuite.keyExchange, chc.negotiatedProtocol); if (ke == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } else { SSLKeyDerivation masterKD = ke.createKeyDerivation(chc); @@ -217,7 +215,7 @@ final class RSAClientKeyExchange { SSLTrafficKeyDerivation kd = SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kd == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); } else { @@ -262,14 +260,14 @@ final class RSAClientKeyExchange { } if (rsaPossession == null && x509Possession == null) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No RSA possessions negotiated for client key exchange"); } PrivateKey privateKey = (rsaPossession != null) ? rsaPossession.popPrivateKey : x509Possession.popPrivateKey; if (!privateKey.getAlgorithm().equals("RSA")) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Not RSA private key for client key exchange"); } @@ -287,7 +285,7 @@ final class RSAClientKeyExchange { RSAPremasterSecret.decode(shc, privateKey, ckem.encrypted); shc.handshakeCredentials.add(premaster); } catch (GeneralSecurityException gse) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Cannot decode RSA premaster secret", gse); } @@ -296,7 +294,7 @@ final class RSAClientKeyExchange { shc.negotiatedCipherSuite.keyExchange, shc.negotiatedProtocol); if (ke == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key exchange type"); } else { SSLKeyDerivation masterKD = ke.createKeyDerivation(shc); @@ -308,7 +306,7 @@ final class RSAClientKeyExchange { SSLTrafficKeyDerivation kd = SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kd == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); } else { diff --git a/src/java.base/share/classes/sun/security/ssl/RSAKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/RSAKeyExchange.java index 3d73111cc41..555d9aeaf84 100644 --- a/src/java.base/share/classes/sun/security/ssl/RSAKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/RSAKeyExchange.java @@ -274,7 +274,7 @@ final class RSAKeyExchange { } if (premaster == null) { - context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw context.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No sufficient RSA key agreement parameters negotiated"); } diff --git a/src/java.base/share/classes/sun/security/ssl/RSAServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/RSAServerKeyExchange.java index 5af690a7b78..ebe82a5a6e4 100644 --- a/src/java.base/share/classes/sun/security/ssl/RSAServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/RSAServerKeyExchange.java @@ -94,7 +94,7 @@ final class RSAServerKeyExchange { signature = signer.sign(); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Failed to sign ephemeral RSA parameters", ex); } @@ -122,7 +122,7 @@ final class RSAServerKeyExchange { } if (x509Credentials == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No RSA credentials negotiated for server key exchange"); } @@ -133,12 +133,12 @@ final class RSAServerKeyExchange { chc.clientHelloRandom.randomBytes, chc.serverHelloRandom.randomBytes); if (!signer.verify(paramsSignature)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid signature of RSA ServerKeyExchange message"); } } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Failed to sign ephemeral RSA parameters", ex); } } @@ -250,12 +250,12 @@ final class RSAServerKeyExchange { return null; } else if (x509Possession == null) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No RSA certificate negotiated for server key exchange"); } else if (!"RSA".equals( x509Possession.popPrivateKey.getAlgorithm())) { // unlikely - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "No X.509 possession can be used for " + "ephemeral RSA ServerKeyExchange"); } @@ -312,15 +312,13 @@ final class RSAServerKeyExchange { new BigInteger(1, skem.exponent)); publicKey = (RSAPublicKey)kf.generatePublic(spec); } catch (GeneralSecurityException gse) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, "Could not generate RSAPublicKey", gse); - - return; // make the compiler happy } if (!chc.algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + throw chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, "RSA ServerKeyExchange does not comply to " + "algorithm constraints"); } @@ -328,7 +326,8 @@ final class RSAServerKeyExchange { // // update // - chc.handshakeCredentials.add(new EphemeralRSACredentials(publicKey)); + chc.handshakeCredentials.add( + new EphemeralRSACredentials(publicKey)); // // produce diff --git a/src/java.base/share/classes/sun/security/ssl/RenegoInfoExtension.java b/src/java.base/share/classes/sun/security/ssl/RenegoInfoExtension.java index c1e684ff733..27b978e6402 100644 --- a/src/java.base/share/classes/sun/security/ssl/RenegoInfoExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/RenegoInfoExtension.java @@ -185,12 +185,10 @@ final class RenegoInfoExtension { return null; } else { // terminate the session. - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "insecure renegotiation is not allowed"); } } - - return null; } } @@ -226,14 +224,13 @@ final class RenegoInfoExtension { try { spec = new RenegotiationInfoSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (!shc.conContext.isNegotiated) { // initial handshaking. if (spec.renegotiatedConnection.length != 0) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid renegotiation_info extension data: not empty"); } shc.conContext.secureRenegotiation = true; @@ -241,14 +238,14 @@ final class RenegoInfoExtension { if (!shc.conContext.secureRenegotiation) { // Unexpected RI extension for insecure renegotiation, // abort the handshake with a fatal handshake_failure alert. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "The renegotiation_info is present in a insecure " + "renegotiation"); } else { // verify the client_verify_data value if (!Arrays.equals(shc.conContext.clientVerifyData, spec.renegotiatedConnection)) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid renegotiation_info extension data: " + "incorrect verify data in ClientHello"); } @@ -295,7 +292,7 @@ final class RenegoInfoExtension { } if (!HandshakeContext.allowLegacyHelloMessages) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Failed to negotiate the use of secure renegotiation"); } // otherwise, allow legacy hello message @@ -307,7 +304,7 @@ final class RenegoInfoExtension { shc.conContext.secureRenegotiation = false; } else if (shc.conContext.secureRenegotiation) { // Require secure renegotiation, terminate the connection. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Inconsistent secure renegotiation indication"); } else { // renegotiation, not secure if (HandshakeContext.allowUnsafeRenegotiation) { @@ -320,7 +317,7 @@ final class RenegoInfoExtension { if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine("Terminate insecure renegotiation"); } - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsafe renegotiation is not allowed"); } } @@ -430,7 +427,7 @@ final class RenegoInfoExtension { if (requestedSpec == null && !chc.activeCipherSuites.contains( CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Missing renegotiation_info and SCSV detected in " + "ClientHello"); } @@ -440,8 +437,7 @@ final class RenegoInfoExtension { try { spec = new RenegotiationInfoSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } @@ -452,7 +448,7 @@ final class RenegoInfoExtension { // and if it is not, MUST abort the handshake (by sending // a fatal handshake_failure alert). [RFC 5746] if (spec.renegotiatedConnection.length != 0) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid renegotiation_info in ServerHello: " + "not empty renegotiated_connection"); } @@ -467,7 +463,7 @@ final class RenegoInfoExtension { int infoLen = chc.conContext.clientVerifyData.length + chc.conContext.serverVerifyData.length; if (spec.renegotiatedConnection.length != infoLen) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid renegotiation_info in ServerHello: " + "invalid renegotiated_connection length (" + spec.renegotiatedConnection.length + ")"); @@ -476,14 +472,14 @@ final class RenegoInfoExtension { byte[] cvd = chc.conContext.clientVerifyData; if (!Arrays.equals(spec.renegotiatedConnection, 0, cvd.length, cvd, 0, cvd.length)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid renegotiation_info in ServerHello: " + "unmatched client_verify_data value"); } byte[] svd = chc.conContext.serverVerifyData; if (!Arrays.equals(spec.renegotiatedConnection, cvd.length, infoLen, svd, 0, svd.length)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Invalid renegotiation_info in ServerHello: " + "unmatched server_verify_data value"); } @@ -516,7 +512,7 @@ final class RenegoInfoExtension { if (requestedSpec == null && !chc.activeCipherSuites.contains( CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Missing renegotiation_info and SCSV detected in " + "ClientHello"); } @@ -524,7 +520,7 @@ final class RenegoInfoExtension { if (!chc.conContext.isNegotiated) { // initial handshaking. if (!HandshakeContext.allowLegacyHelloMessages) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Failed to negotiate the use of secure renegotiation"); } // otherwise, allow legacy hello message @@ -536,7 +532,7 @@ final class RenegoInfoExtension { chc.conContext.secureRenegotiation = false; } else if (chc.conContext.secureRenegotiation) { // Require secure renegotiation, terminate the connection. - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Inconsistent secure renegotiation indication"); } else { // renegotiation, not secure if (HandshakeContext.allowUnsafeRenegotiation) { @@ -549,7 +545,7 @@ final class RenegoInfoExtension { if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine("Terminate insecure renegotiation"); } - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Unsafe renegotiation is not allowed"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java index a4f2b5dd247..c263caba011 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java @@ -102,10 +102,10 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { try { conContext.kickstart(); } catch (IOException ioe) { - conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw conContext.fatal(Alert.HANDSHAKE_FAILURE, "Couldn't kickstart handshaking", ioe); } catch (Exception ex) { // including RuntimeException - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "Fail to begin handshake", ex); } } @@ -137,16 +137,14 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength); } catch (SSLProtocolException spe) { // may be an unexpected handshake message - conContext.fatal(Alert.UNEXPECTED_MESSAGE, spe); + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, spe); } catch (IOException ioe) { - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "problem wrapping app data", ioe); } catch (Exception ex) { // including RuntimeException - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "Fail to wrap application data", ex); } - - return null; // make compiler happy } private SSLEngineResult writeRecord( @@ -275,9 +273,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength); } catch (SSLHandshakeException she) { // may be record sequence number overflow - conContext.fatal(Alert.HANDSHAKE_FAILURE, she); + throw conContext.fatal(Alert.HANDSHAKE_FAILURE, she); } catch (IOException e) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, e); + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, e); } if (ciphertext == null) { @@ -444,7 +442,7 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength); } catch (SSLProtocolException spe) { // may be an unexpected handshake message - conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, spe.getMessage(), spe); } catch (IOException ioe) { /* @@ -453,14 +451,12 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { * got us into this situation, so report that much back. * Our days of consuming are now over anyway. */ - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "problem unwrapping net record", ioe); } catch (Exception ex) { // including RuntimeException - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "Fail to unwrap network record", ex); } - - return null; // make compiler happy } private SSLEngineResult readRecord( @@ -721,7 +717,7 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport { if (!conContext.isInputCloseNotified && (conContext.isNegotiated || conContext.handshakeContext != null)) { - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "closing inbound before receiving peer's close_notify"); } diff --git a/src/java.base/share/classes/sun/security/ssl/SSLExtensions.java b/src/java.base/share/classes/sun/security/ssl/SSLExtensions.java index aa5ed01c7de..76c72f610af 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLExtensions.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLExtensions.java @@ -60,7 +60,8 @@ final class SSLExtensions { int extId = Record.getInt16(m); int extLen = Record.getInt16(m); if (extLen > m.remaining()) { - hm.handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw hm.handshakeContext.conContext.fatal( + Alert.ILLEGAL_PARAMETER, "Error parsing extension (" + extId + "): no sufficient data"); } @@ -86,7 +87,7 @@ final class SSLExtensions { "in the ServerHello handshake message"); } } else { - hm.handshakeContext.conContext.fatal( + throw hm.handshakeContext.conContext.fatal( Alert.UNSUPPORTED_EXTENSION, "extension (" + extId + ") should not be presented in " + handshakeType.name); @@ -102,7 +103,7 @@ final class SSLExtensions { } if (extension.handshakeType != handshakeType) { - hm.handshakeContext.conContext.fatal( + throw hm.handshakeContext.conContext.fatal( Alert.UNSUPPORTED_EXTENSION, "extension (" + extId + ") should not be " + "presented in " + handshakeType.name); diff --git a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java index 0a19de26169..1bed7ee184e 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java @@ -402,7 +402,7 @@ public final class SSLSocketImpl readHandshakeRecord(); } } catch (IOException ioe) { - conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw conContext.fatal(Alert.HANDSHAKE_FAILURE, "Couldn't kickstart handshaking", ioe); } catch (Exception oe) { // including RuntimeException handleException(oe); @@ -642,7 +642,7 @@ public final class SSLSocketImpl if (checkCloseNotify && !conContext.isInputCloseNotified && (conContext.isNegotiated || conContext.handshakeContext != null)) { - conContext.fatal(Alert.INTERNAL_ERROR, + throw conContext.fatal(Alert.INTERNAL_ERROR, "closing inbound before receiving peer's close_notify"); } @@ -982,9 +982,9 @@ public final class SSLSocketImpl conContext.outputRecord.deliver(b, off, len); } catch (SSLHandshakeException she) { // may be record sequence number overflow - conContext.fatal(Alert.HANDSHAKE_FAILURE, she); + throw conContext.fatal(Alert.HANDSHAKE_FAILURE, she); } catch (IOException e) { - conContext.fatal(Alert.UNEXPECTED_MESSAGE, e); + throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, e); } // Is the sequence number is nearly overflow, or has the key usage @@ -1309,7 +1309,8 @@ public final class SSLSocketImpl alert = Alert.INTERNAL_ERROR; } } - conContext.fatal(alert, cause); + + throw conContext.fatal(alert, cause); } private Plaintext handleEOF(EOFException eofe) throws IOException { diff --git a/src/java.base/share/classes/sun/security/ssl/SSLTransport.java b/src/java.base/share/classes/sun/security/ssl/SSLTransport.java index dd3a899ae2e..92615f4185f 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLTransport.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLTransport.java @@ -115,7 +115,7 @@ interface SSLTransport { } } - context.fatal(Alert.UNEXPECTED_MESSAGE, unsoe); + throw context.fatal(Alert.UNEXPECTED_MESSAGE, unsoe); } catch (BadPaddingException bpe) { /* * The basic SSLv3 record protection involves (optional) @@ -126,15 +126,15 @@ interface SSLTransport { Alert alert = (context.handshakeContext != null) ? Alert.HANDSHAKE_FAILURE : Alert.BAD_RECORD_MAC; - context.fatal(alert, bpe); + throw context.fatal(alert, bpe); } catch (SSLHandshakeException she) { // may be record sequence number overflow - context.fatal(Alert.HANDSHAKE_FAILURE, she); + throw context.fatal(Alert.HANDSHAKE_FAILURE, she); } catch (EOFException eofe) { // rethrow EOFException, the call will handle it if neede. throw eofe; } catch (IOException ioe) { - context.fatal(Alert.UNEXPECTED_MESSAGE, ioe); + throw context.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } if (plaintexts == null || plaintexts.length == 0) { @@ -191,7 +191,7 @@ interface SSLTransport { } if (remains > 0) { - context.fatal(Alert.INTERNAL_ERROR, + throw context.fatal(Alert.INTERNAL_ERROR, "no sufficient room in the destination buffers"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHello.java b/src/java.base/share/classes/sun/security/ssl/ServerHello.java index a8a38a9dfb8..da5dd5b17e7 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHello.java @@ -133,7 +133,7 @@ final class ServerHello { this.serverVersion = ProtocolVersion.valueOf(major, minor); if (this.serverVersion == null) { // The client should only request for known protocol versions. - context.conContext.fatal(Alert.PROTOCOL_VERSION, + throw context.conContext.fatal(Alert.PROTOCOL_VERSION, "Unsupported protocol version: " + ProtocolVersion.nameOf(major, minor)); } @@ -143,20 +143,21 @@ final class ServerHello { try { sessionId.checkLength(serverVersion.id); } catch (SSLProtocolException ex) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, ex); + throw handshakeContext.conContext.fatal( + Alert.ILLEGAL_PARAMETER, ex); } int cipherSuiteId = Record.getInt16(m); this.cipherSuite = CipherSuite.valueOf(cipherSuiteId); if (cipherSuite == null || !context.isNegotiable(cipherSuite)) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Server selected improper ciphersuite " + CipherSuite.nameOf(cipherSuiteId)); } this.compressionMethod = m.get(); if (compressionMethod != 0) { - context.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, "compression type not supported, " + compressionMethod); } @@ -293,10 +294,8 @@ final class ServerHello { KeyExchangeProperties credentials = chooseCipherSuite(shc, clientHello); if (credentials == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - - return null; } shc.negotiatedCipherSuite = credentials.cipherSuite; shc.handshakeKeyExchange = credentials.keyExchange; @@ -374,7 +373,7 @@ final class ServerHello { SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kdg == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); } else { @@ -458,10 +457,8 @@ final class ServerHello { } } - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - - return null; } private static final class KeyExchangeProperties { @@ -524,9 +521,8 @@ final class ServerHello { // negotiate the cipher suite. CipherSuite cipherSuite = chooseCipherSuite(shc, clientHello); if (cipherSuite == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common"); - return null; } shc.negotiatedCipherSuite = cipherSuite; shc.handshakeSession.setSuite(cipherSuite); @@ -592,9 +588,8 @@ final class ServerHello { SSLKeyExchange ke = shc.handshakeKeyExchange; if (ke == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not negotiated key shares"); - return null; } SSLKeyDerivation handshakeKD = ke.createKeyDerivation(shc); @@ -605,10 +600,9 @@ final class ServerHello { SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); if (kdg == null) { // unlikely - shc.conContext.fatal(Alert.INTERNAL_ERROR, + throw shc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + shc.negotiatedProtocol); - return null; } SSLKeyDerivation kd = @@ -634,18 +628,15 @@ final class ServerHello { shc.sslContext.getSecureRandom()); } catch (GeneralSecurityException gse) { // unlikely - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return null; } if (readCipher == null) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + shc.negotiatedCipherSuite + ") and protocol version (" + shc.negotiatedProtocol + ")"); - - return null; } shc.baseReadSecret = readSecret; @@ -671,18 +662,15 @@ final class ServerHello { shc.sslContext.getSecureRandom()); } catch (GeneralSecurityException gse) { // unlikely - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return null; } if (writeCipher == null) { - shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw shc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + shc.negotiatedCipherSuite + ") and protocol version (" + shc.negotiatedProtocol + ")"); - - return null; } shc.baseWriteSecret = writeSecret; @@ -764,9 +752,8 @@ final class ServerHello { CipherSuite cipherSuite = T13ServerHelloProducer.chooseCipherSuite(shc, clientHello); if (cipherSuite == null) { - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "no cipher suites in common for hello retry request"); - return null; } ServerHelloMessage hhrm = new ServerHelloMessage(shc, @@ -875,7 +862,7 @@ final class ServerHello { SSLHandshake.HELLO_VERIFY_REQUEST.id); } if (!chc.handshakeConsumers.isEmpty()) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "No more message expected before ServerHello is processed"); } @@ -913,14 +900,14 @@ final class ServerHello { } if (!chc.activeProtocols.contains(serverVersion)) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "The server selected protocol version " + serverVersion + " is not accepted by client preferences " + chc.activeProtocols); } if (!serverVersion.useTLS13PlusSpec()) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "Unexpected HelloRetryRequest for " + serverVersion.name); } @@ -965,7 +952,7 @@ final class ServerHello { } if (!chc.activeProtocols.contains(serverVersion)) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "The server selected protocol version " + serverVersion + " is not accepted by client preferences " + chc.activeProtocols); @@ -982,7 +969,7 @@ final class ServerHello { } if (serverHello.serverRandom.isVersionDowngrade(chc)) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "A potential protocol version downgrade attack"); } @@ -1025,7 +1012,7 @@ final class ServerHello { ClientHandshakeContext chc = (ClientHandshakeContext)context; ServerHelloMessage serverHello = (ServerHelloMessage)message; if (!chc.isNegotiable(serverHello.serverVersion)) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "Server chose " + serverHello.serverVersion + ", but that protocol version is not enabled or " + "not supported by the client."); @@ -1037,7 +1024,7 @@ final class ServerHello { chc.negotiatedProtocol, chc.negotiatedCipherSuite); chc.serverHelloRandom = serverHello.serverRandom; if (chc.negotiatedCipherSuite.keyExchange == null) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "TLS 1.2 or prior version does not support the " + "server cipher suite: " + chc.negotiatedCipherSuite.name); } @@ -1063,7 +1050,7 @@ final class ServerHello { // Verify that the session ciphers are unchanged. CipherSuite sessionSuite = chc.resumingSession.getSuite(); if (chc.negotiatedCipherSuite != sessionSuite) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "Server returned wrong cipher suite for session"); } @@ -1071,7 +1058,7 @@ final class ServerHello { ProtocolVersion sessionVersion = chc.resumingSession.getProtocolVersion(); if (chc.negotiatedProtocol != sessionVersion) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "Server resumed with wrong protocol version"); } @@ -1090,7 +1077,7 @@ final class ServerHello { } chc.isResumption = false; if (!chc.sslConfig.enableSessionCreation) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "New session creation is disabled"); } } @@ -1109,7 +1096,7 @@ final class ServerHello { } if (!chc.sslConfig.enableSessionCreation) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "New session creation is disabled"); } chc.handshakeSession = new SSLSessionImpl(chc, @@ -1130,7 +1117,7 @@ final class ServerHello { SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kdg == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); } else { @@ -1201,7 +1188,7 @@ final class ServerHello { ClientHandshakeContext chc = (ClientHandshakeContext)context; ServerHelloMessage serverHello = (ServerHelloMessage)message; if (serverHello.serverVersion != ProtocolVersion.TLS12) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "The ServerHello.legacy_version field is not TLS 1.2"); } @@ -1226,7 +1213,7 @@ final class ServerHello { } if (!chc.sslConfig.enableSessionCreation) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "New session creation is disabled"); } chc.handshakeSession = new SSLSessionImpl(chc, @@ -1239,7 +1226,7 @@ final class ServerHello { Optional psk = chc.resumingSession.consumePreSharedKey(); if(!psk.isPresent()) { - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "No PSK available. Unable to resume."); } @@ -1260,9 +1247,8 @@ final class ServerHello { SSLKeyExchange ke = chc.handshakeKeyExchange; if (ke == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not negotiated key shares"); - return; } SSLKeyDerivation handshakeKD = ke.createKeyDerivation(chc); @@ -1272,10 +1258,9 @@ final class ServerHello { SSLTrafficKeyDerivation.valueOf(chc.negotiatedProtocol); if (kdg == null) { // unlikely - chc.conContext.fatal(Alert.INTERNAL_ERROR, + throw chc.conContext.fatal(Alert.INTERNAL_ERROR, "Not supported key derivation: " + chc.negotiatedProtocol); - return; } SSLKeyDerivation secretKD = @@ -1302,18 +1287,15 @@ final class ServerHello { chc.sslContext.getSecureRandom()); } catch (GeneralSecurityException gse) { // unlikely - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return; } if (readCipher == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + chc.negotiatedCipherSuite + ") and protocol version (" + chc.negotiatedProtocol + ")"); - - return; } chc.baseReadSecret = readSecret; @@ -1339,18 +1321,15 @@ final class ServerHello { chc.sslContext.getSecureRandom()); } catch (GeneralSecurityException gse) { // unlikely - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Missing cipher algorithm", gse); - return; } if (writeCipher == null) { - chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw chc.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Illegal cipher suite (" + chc.negotiatedCipherSuite + ") and protocol version (" + chc.negotiatedProtocol + ")"); - - return; } chc.baseWriteSecret = writeSecret; @@ -1412,7 +1391,7 @@ final class ServerHello { ClientHandshakeContext chc = (ClientHandshakeContext)context; ServerHelloMessage helloRetryRequest = (ServerHelloMessage)message; if (helloRetryRequest.serverVersion != ProtocolVersion.TLS12) { - chc.conContext.fatal(Alert.PROTOCOL_VERSION, + throw chc.conContext.fatal(Alert.PROTOCOL_VERSION, "The HelloRetryRequest.legacy_version is not TLS 1.2"); } @@ -1442,7 +1421,7 @@ final class ServerHello { chc.initialClientHelloMsg.write(hos); } catch (IOException ioe) { // unlikely - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "Failed to construct message hash", ioe); } chc.handshakeHash.deliver(hos.toByteArray()); diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java b/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java index ed0f23bb76f..0d368f90ecc 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHelloDone.java @@ -50,7 +50,7 @@ final class ServerHelloDone { ByteBuffer m) throws IOException { super(handshakeContext); if (m.hasRemaining()) { - handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, + throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER, "Error parsing ServerHelloDone message: not empty"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java index cb5403ebd70..273bf669723 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerKeyExchange.java @@ -68,9 +68,8 @@ final class ServerKeyExchange { } // not producer defined. - shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No ServerKeyExchange handshake message can be produced."); - return null; // make the compiler happe } } @@ -107,7 +106,7 @@ final class ServerKeyExchange { } // no consumer defined. - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ServerKeyExchange handshake message."); } } diff --git a/src/java.base/share/classes/sun/security/ssl/ServerNameExtension.java b/src/java.base/share/classes/sun/security/ssl/ServerNameExtension.java index aae5f933b63..9859bf64c33 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerNameExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerNameExtension.java @@ -295,8 +295,7 @@ final class ServerNameExtension { try { spec = new CHServerNamesSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -314,7 +313,7 @@ final class ServerNameExtension { } } else { // We do not reject client without SNI extension currently. - shc.conContext.fatal(Alert.UNRECOGNIZED_NAME, + throw shc.conContext.fatal(Alert.UNRECOGNIZED_NAME, "Unrecognized server name indication"); } } else { @@ -483,13 +482,13 @@ final class ServerNameExtension { CHServerNamesSpec spec = (CHServerNamesSpec) chc.handshakeExtensions.get(CH_SERVER_NAME); if (spec == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected ServerHello server_name extension"); } // Parse the extension. if (buffer.remaining() != 0) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid ServerHello server_name extension"); } @@ -570,13 +569,13 @@ final class ServerNameExtension { CHServerNamesSpec spec = (CHServerNamesSpec) chc.handshakeExtensions.get(CH_SERVER_NAME); if (spec == null) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected EncryptedExtensions server_name extension"); } // Parse the extension. if (buffer.remaining() != 0) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, "Invalid EncryptedExtensions server_name extension"); } diff --git a/src/java.base/share/classes/sun/security/ssl/SignatureAlgorithmsExtension.java b/src/java.base/share/classes/sun/security/ssl/SignatureAlgorithmsExtension.java index 6e48134b1d1..27638b48b33 100644 --- a/src/java.base/share/classes/sun/security/ssl/SignatureAlgorithmsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SignatureAlgorithmsExtension.java @@ -238,8 +238,7 @@ final class SignatureAlgorithmsExtension { try { spec = new SignatureSchemesSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -329,7 +328,7 @@ final class SignatureAlgorithmsExtension { // We may support the server authentication other than X.509 // certificate later. if (shc.negotiatedProtocol.useTLS13PlusSpec()) { - shc.conContext.fatal(Alert.MISSING_EXTENSION, + throw shc.conContext.fatal(Alert.MISSING_EXTENSION, "No mandatory signature_algorithms extension in the " + "received CertificateRequest handshake message"); } @@ -403,10 +402,9 @@ final class SignatureAlgorithmsExtension { // handshake message in TLS 1.3. if (!shc.sslConfig.isAvailable( SSLExtension.CR_SIGNATURE_ALGORITHMS)) { - shc.conContext.fatal(Alert.MISSING_EXTENSION, + throw shc.conContext.fatal(Alert.MISSING_EXTENSION, "No available signature_algorithms extension " + "for client certificate authentication"); - return null; // make the compiler happy } // Produce the extension. @@ -454,10 +452,9 @@ final class SignatureAlgorithmsExtension { // handshake message in TLS 1.3. if (!chc.sslConfig.isAvailable( SSLExtension.CR_SIGNATURE_ALGORITHMS)) { - chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, + throw chc.conContext.fatal(Alert.HANDSHAKE_FAILURE, "No available signature_algorithms extension " + "for client certificate authentication"); - return; // make the compiler happy } // Parse the extension. @@ -465,8 +462,7 @@ final class SignatureAlgorithmsExtension { try { spec = new SignatureSchemesSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } List knownSignatureSchemes = new LinkedList<>(); @@ -545,7 +541,7 @@ final class SignatureAlgorithmsExtension { // This is a mandatory extension for CertificateRequest handshake // message in TLS 1.3. - chc.conContext.fatal(Alert.MISSING_EXTENSION, + throw chc.conContext.fatal(Alert.MISSING_EXTENSION, "No mandatory signature_algorithms extension in the " + "received CertificateRequest handshake message"); } diff --git a/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java b/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java index b1c11a66ea7..1044b6d13de 100644 --- a/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java @@ -900,8 +900,7 @@ final class SupportedGroupsExtension { try { spec = new SupportedGroupsSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -1024,8 +1023,7 @@ final class SupportedGroupsExtension { try { spec = new SupportedGroupsSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. diff --git a/src/java.base/share/classes/sun/security/ssl/SupportedVersionsExtension.java b/src/java.base/share/classes/sun/security/ssl/SupportedVersionsExtension.java index cb3f654b82c..3318910abb8 100644 --- a/src/java.base/share/classes/sun/security/ssl/SupportedVersionsExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SupportedVersionsExtension.java @@ -225,8 +225,7 @@ final class SupportedVersionsExtension { try { spec = new CHSupportedVersionsSpec(buffer); } catch (IOException ioe) { - shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw shc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -368,8 +367,7 @@ final class SupportedVersionsExtension { try { spec = new SHSupportedVersionsSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. @@ -458,8 +456,7 @@ final class SupportedVersionsExtension { try { spec = new SHSupportedVersionsSpec(buffer); } catch (IOException ioe) { - chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); - return; // fatal() always throws, make the compiler happy. + throw chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE, ioe); } // Update the context. diff --git a/src/java.base/share/classes/sun/security/ssl/TransportContext.java b/src/java.base/share/classes/sun/security/ssl/TransportContext.java index 811610daa33..e0c9fcd4543 100644 --- a/src/java.base/share/classes/sun/security/ssl/TransportContext.java +++ b/src/java.base/share/classes/sun/security/ssl/TransportContext.java @@ -148,9 +148,8 @@ class TransportContext implements ConnectionContext { ContentType ct = ContentType.valueOf(plaintext.contentType); if (ct == null) { - fatal(Alert.UNEXPECTED_MESSAGE, + throw fatal(Alert.UNEXPECTED_MESSAGE, "Unknown content type: " + plaintext.contentType); - return; } switch (ct) { @@ -164,7 +163,7 @@ class TransportContext implements ConnectionContext { protocolVersion.useTLS13PlusSpec()) { handshakeContext = new PostHandshakeContext(this); } else { - fatal(Alert.UNEXPECTED_MESSAGE, + throw fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected post-handshake message: " + SSLHandshake.nameOf(type)); } @@ -185,7 +184,7 @@ class TransportContext implements ConnectionContext { if (consumer != null) { consumer.consume(this, plaintext.fragment); } else { - fatal(Alert.UNEXPECTED_MESSAGE, + throw fatal(Alert.UNEXPECTED_MESSAGE, "Unexpected content: " + plaintext.contentType); } } @@ -250,22 +249,22 @@ class TransportContext implements ConnectionContext { } } - void fatal(Alert alert, + SSLException fatal(Alert alert, String diagnostic) throws SSLException { - fatal(alert, diagnostic, null); + return fatal(alert, diagnostic, null); } - void fatal(Alert alert, Throwable cause) throws SSLException { - fatal(alert, null, cause); + SSLException fatal(Alert alert, Throwable cause) throws SSLException { + return fatal(alert, null, cause); } - void fatal(Alert alert, + SSLException fatal(Alert alert, String diagnostic, Throwable cause) throws SSLException { - fatal(alert, diagnostic, false, cause); + return fatal(alert, diagnostic, false, cause); } // Note: close_notify is not delivered via fatal() methods. - void fatal(Alert alert, String diagnostic, + SSLException fatal(Alert alert, String diagnostic, boolean recvFatalAlert, Throwable cause) throws SSLException { // If we've already shutdown because of an error, there is nothing we // can do except rethrow the exception. From 32ea2e53435e3d0b8740f18e45514f328d2bf966 Mon Sep 17 00:00:00 2001 From: Dean Long Date: Tue, 18 Dec 2018 12:36:27 -0800 Subject: [PATCH 097/174] 8215205: javaVFrame much slower than vframeStream Reviewed-by: mchung, thartmann --- src/hotspot/share/code/scopeDesc.cpp | 12 ++++++-- src/hotspot/share/code/scopeDesc.hpp | 9 +++++- src/hotspot/share/runtime/vframe.cpp | 33 +++++++++++++++++++++ src/hotspot/share/runtime/vframe.hpp | 6 ++++ src/hotspot/share/runtime/vframe.inline.hpp | 7 +++++ src/hotspot/share/runtime/vframe_hp.cpp | 8 +++++ src/hotspot/share/runtime/vframe_hp.hpp | 3 ++ 7 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/hotspot/share/code/scopeDesc.cpp b/src/hotspot/share/code/scopeDesc.cpp index 4807f61d74c..c7d0b7d37e7 100644 --- a/src/hotspot/share/code/scopeDesc.cpp +++ b/src/hotspot/share/code/scopeDesc.cpp @@ -51,9 +51,9 @@ ScopeDesc::ScopeDesc(const CompiledMethod* code, int decode_offset, bool reexecu } -ScopeDesc::ScopeDesc(const ScopeDesc* parent) { +void ScopeDesc::initialize(const ScopeDesc* parent, int decode_offset) { _code = parent->_code; - _decode_offset = parent->_sender_decode_offset; + _decode_offset = decode_offset; _objects = parent->_objects; _reexecute = false; //reexecute only applies to the first scope _rethrow_exception = false; @@ -61,6 +61,14 @@ ScopeDesc::ScopeDesc(const ScopeDesc* parent) { decode_body(); } +ScopeDesc::ScopeDesc(const ScopeDesc* parent) { + initialize(parent, parent->_sender_decode_offset); +} + +ScopeDesc::ScopeDesc(const ScopeDesc* parent, int decode_offset) { + initialize(parent, decode_offset); +} + void ScopeDesc::decode_body() { if (decode_offset() == DebugInformationRecorder::serialized_null) { diff --git a/src/hotspot/share/code/scopeDesc.hpp b/src/hotspot/share/code/scopeDesc.hpp index d1eaaac7426..f7ed903f771 100644 --- a/src/hotspot/share/code/scopeDesc.hpp +++ b/src/hotspot/share/code/scopeDesc.hpp @@ -67,6 +67,9 @@ class ScopeDesc : public ResourceObj { // avoid a .hpp-.hpp dependency.) ScopeDesc(const CompiledMethod* code, int decode_offset, bool reexecute, bool rethrow_exception, bool return_oop); + // Direct access to scope + ScopeDesc* at_offset(int decode_offset) { return new ScopeDesc(this, decode_offset); } + // JVM state Method* method() const { return _method; } int bci() const { return _bci; } @@ -85,12 +88,16 @@ class ScopeDesc : public ResourceObj { // Returns where the scope was decoded int decode_offset() const { return _decode_offset; } + int sender_decode_offset() const { return _sender_decode_offset; } + // Tells whether sender() returns NULL bool is_top() const; private: - // Alternative constructor + void initialize(const ScopeDesc* parent, int decode_offset); + // Alternative constructors ScopeDesc(const ScopeDesc* parent); + ScopeDesc(const ScopeDesc* parent, int decode_offset); // JVM state Method* _method; diff --git a/src/hotspot/share/runtime/vframe.cpp b/src/hotspot/share/runtime/vframe.cpp index 452f48bc5cf..76de1313629 100644 --- a/src/hotspot/share/runtime/vframe.cpp +++ b/src/hotspot/share/runtime/vframe.cpp @@ -452,8 +452,10 @@ vframeStream::vframeStream(JavaThread* thread, frame top_frame, _stop_at_java_call_stub = stop_at_java_call_stub; // skip top frame, as it may not be at safepoint + _prev_frame = top_frame; _frame = top_frame.sender(&_reg_map); while (!fill_from_frame()) { + _prev_frame = _frame; _frame = _frame.sender(&_reg_map); } } @@ -534,6 +536,37 @@ void vframeStreamCommon::skip_reflection_related_frames() { } } +javaVFrame* vframeStreamCommon::asJavaVFrame() { + javaVFrame* result = NULL; + if (_mode == compiled_mode) { + guarantee(_frame.is_compiled_frame(), "expected compiled Java frame"); + + // lazy update to register map + bool update_map = true; + RegisterMap map(_thread, update_map); + frame f = _prev_frame.sender(&map); + + guarantee(f.is_compiled_frame(), "expected compiled Java frame"); + + compiledVFrame* cvf = compiledVFrame::cast(vframe::new_vframe(&f, &map, _thread)); + + guarantee(cvf->cb() == cb(), "wrong code blob"); + + // get the same scope as this stream + cvf = cvf->at_scope(_decode_offset, _vframe_id); + + guarantee(cvf->scope()->decode_offset() == _decode_offset, "wrong scope"); + guarantee(cvf->scope()->sender_decode_offset() == _sender_decode_offset, "wrong scope"); + guarantee(cvf->vframe_id() == _vframe_id, "wrong vframe"); + + result = cvf; + } else { + result = javaVFrame::cast(vframe::new_vframe(&_frame, &_reg_map, _thread)); + } + guarantee(result->method() == method(), "wrong method"); + return result; +} + #ifndef PRODUCT void vframe::print() { diff --git a/src/hotspot/share/runtime/vframe.hpp b/src/hotspot/share/runtime/vframe.hpp index 2ee93d7b948..3c723f61557 100644 --- a/src/hotspot/share/runtime/vframe.hpp +++ b/src/hotspot/share/runtime/vframe.hpp @@ -278,12 +278,16 @@ class MonitorInfo : public ResourceObj { class vframeStreamCommon : StackObj { protected: // common + frame _prev_frame; frame _frame; JavaThread* _thread; RegisterMap _reg_map; enum { interpreted_mode, compiled_mode, at_end_mode } _mode; + // For compiled_mode + int _decode_offset; int _sender_decode_offset; + int _vframe_id; // Cached information Method* _method; @@ -320,6 +324,8 @@ class vframeStreamCommon : StackObj { return (CompiledMethod*) cb(); } + javaVFrame* asJavaVFrame(); + // Frame type inline bool is_interpreted_frame() const; inline bool is_entry_frame() const; diff --git a/src/hotspot/share/runtime/vframe.inline.hpp b/src/hotspot/share/runtime/vframe.inline.hpp index e6402e3db6d..83ab8f06d2a 100644 --- a/src/hotspot/share/runtime/vframe.inline.hpp +++ b/src/hotspot/share/runtime/vframe.inline.hpp @@ -44,6 +44,7 @@ inline void vframeStreamCommon::next() { // handle general case do { + _prev_frame = _frame; _frame = _frame.sender(&_reg_map); } while (!fill_from_frame()); } @@ -59,6 +60,7 @@ inline vframeStream::vframeStream(JavaThread* thread, bool stop_at_java_call_stu _frame = _thread->last_frame(); while (!fill_from_frame()) { + _prev_frame = _frame; _frame = _frame.sender(&_reg_map); } } @@ -68,12 +70,14 @@ inline bool vframeStreamCommon::fill_in_compiled_inlined_sender() { return false; } fill_from_compiled_frame(_sender_decode_offset); + ++_vframe_id; return true; } inline void vframeStreamCommon::fill_from_compiled_frame(int decode_offset) { _mode = compiled_mode; + _decode_offset = decode_offset; // Range check to detect ridiculous offsets. if (decode_offset == DebugInformationRecorder::serialized_null || @@ -118,6 +122,8 @@ inline void vframeStreamCommon::fill_from_compiled_frame(int decode_offset) { inline void vframeStreamCommon::fill_from_compiled_native_frame() { _mode = compiled_mode; _sender_decode_offset = DebugInformationRecorder::serialized_null; + _decode_offset = DebugInformationRecorder::serialized_null; + _vframe_id = 0; _method = nm()->method(); _bci = 0; } @@ -187,6 +193,7 @@ inline bool vframeStreamCommon::fill_from_frame() { decode_offset = pc_desc->scope_decode_offset(); } fill_from_compiled_frame(decode_offset); + _vframe_id = 0; } return true; } diff --git a/src/hotspot/share/runtime/vframe_hp.cpp b/src/hotspot/share/runtime/vframe_hp.cpp index 3f4bfd44217..fcc3e7bae31 100644 --- a/src/hotspot/share/runtime/vframe_hp.cpp +++ b/src/hotspot/share/runtime/vframe_hp.cpp @@ -252,6 +252,14 @@ compiledVFrame::compiledVFrame(const frame* fr, const RegisterMap* reg_map, Java guarantee(_scope != NULL, "scope must be present"); } +compiledVFrame* compiledVFrame::at_scope(int decode_offset, int vframe_id) { + if (scope()->decode_offset() != decode_offset) { + ScopeDesc* scope = this->scope()->at_offset(decode_offset); + return new compiledVFrame(frame_pointer(), register_map(), thread(), scope, vframe_id); + } + assert(_vframe_id == vframe_id, "wrong frame id"); + return this; +} bool compiledVFrame::is_top() const { // FIX IT: Remove this when new native stubs are in place diff --git a/src/hotspot/share/runtime/vframe_hp.hpp b/src/hotspot/share/runtime/vframe_hp.hpp index ab7db10549e..522c097514b 100644 --- a/src/hotspot/share/runtime/vframe_hp.hpp +++ b/src/hotspot/share/runtime/vframe_hp.hpp @@ -72,6 +72,9 @@ class compiledVFrame: public javaVFrame { // Returns the scopeDesc ScopeDesc* scope() const { return _scope; } + // Return the compiledVFrame for the desired scope + compiledVFrame* at_scope(int decode_offset, int vframe_id); + // Returns SynchronizationEntryBCI or bci() (used for synchronization) int raw_bci() const; From d1597bb1cbd8a213bb73bf1efb3db0584b40e7dc Mon Sep 17 00:00:00 2001 From: Dean Long Date: Tue, 18 Dec 2018 12:45:07 -0800 Subject: [PATCH 098/174] 8214329: SwingMark SubMenus 9% regression in 12-b19 on Linux client Reviewed-by: thartmann, mullan --- src/hotspot/share/prims/jvm.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/prims/jvm.cpp b/src/hotspot/share/prims/jvm.cpp index 429f2d7d469..26772e6294a 100644 --- a/src/hotspot/share/prims/jvm.cpp +++ b/src/hotspot/share/prims/jvm.cpp @@ -1230,11 +1230,10 @@ JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls)) oop protection_domain = NULL; // Iterate through Java frames - RegisterMap reg_map(thread); - javaVFrame *vf = thread->last_java_vframe(®_map); - for (; vf != NULL; vf = vf->java_sender()) { + vframeStream vfst(thread); + for(; !vfst.at_end(); vfst.next()) { // get method of frame - Method* method = vf->method(); + Method* method = vfst.method(); // stop at the first privileged frame if (method->method_holder() == SystemDictionary::AccessController_klass() && @@ -1243,9 +1242,7 @@ JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls)) // this frame is privileged is_privileged = true; - javaVFrame *priv = vf; // executePrivileged - javaVFrame *caller_fr = priv->java_sender(); // doPrivileged - caller_fr = caller_fr->java_sender(); // caller + javaVFrame *priv = vfst.asJavaVFrame(); // executePrivileged StackValueCollection* locals = priv->locals(); privileged_context = locals->obj_at(1); From ad47b4c4cc15a12dc467c7910602218399b2b387 Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Tue, 18 Dec 2018 15:18:44 -0800 Subject: [PATCH 099/174] 8209333: Socket reset issue for TLS 1.3 socket close Reviewed-by: jnimeh --- .../sun/security/ssl/SSLConfiguration.java | 2 - .../sun/security/ssl/SSLSocketImpl.java | 31 +++- .../security/ssl/SSLSocketInputRecord.java | 13 ++ .../SSLSocketBruceForceClose.java | 147 ++++++++++++++++ .../ssl/SSLSocketImpl/SSLSocketClose.java | 159 ++++++++++++++++++ 5 files changed, 349 insertions(+), 3 deletions(-) create mode 100644 test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketBruceForceClose.java create mode 100644 test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketClose.java diff --git a/src/java.base/share/classes/sun/security/ssl/SSLConfiguration.java b/src/java.base/share/classes/sun/security/ssl/SSLConfiguration.java index be717717331..bd3dd3cb1b5 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLConfiguration.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLConfiguration.java @@ -29,8 +29,6 @@ import java.security.AccessControlContext; import java.security.AccessController; import java.security.AlgorithmConstraints; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; diff --git a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java index 1bed7ee184e..b60a84d4636 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java @@ -608,7 +608,12 @@ public final class SSLSocketImpl } } else { if (!conContext.isInboundClosed()) { - conContext.inputRecord.close(); + try (conContext.inputRecord) { + // Try the best to use up the input records and close the + // socket gracefully, without impact the performance too + // much. + appInput.deplete(); + } } if ((autoClose || !isLayered()) && !super.isInputShutdown()) { @@ -907,6 +912,30 @@ public final class SSLSocketImpl return false; } + + /** + * Try the best to use up the input records so as to close the + * socket gracefully, without impact the performance too much. + */ + private synchronized void deplete() { + if (!conContext.isInboundClosed()) { + if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) { + return; + } + + SSLSocketInputRecord socketInputRecord = + (SSLSocketInputRecord)conContext.inputRecord; + try { + socketInputRecord.deplete( + conContext.isNegotiated && (getSoTimeout() > 0)); + } catch (IOException ioe) { + if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { + SSLLogger.warning( + "input stream close depletion failed", ioe); + } + } + } + } } @Override diff --git a/src/java.base/share/classes/sun/security/ssl/SSLSocketInputRecord.java b/src/java.base/share/classes/sun/security/ssl/SSLSocketInputRecord.java index 7a4bbac91dc..57524dc4d64 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLSocketInputRecord.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLSocketInputRecord.java @@ -463,4 +463,17 @@ final class SSLSocketInputRecord extends InputRecord implements SSLRecord { return n; } + + // Try to use up the input stream without impact the performance too much. + void deplete(boolean tryToRead) throws IOException { + int remaining = is.available(); + if (tryToRead && (remaining == 0)) { + // try to wait and read one byte if no buffered input + is.read(); + } + + while ((remaining = is.available()) != 0) { + is.skip(remaining); + } + } } diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketBruceForceClose.java b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketBruceForceClose.java new file mode 100644 index 00000000000..b220a3d434b --- /dev/null +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketBruceForceClose.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// Please run in othervm mode. SunJSSE does not support dynamic system +// properties, no way to re-use system properties in samevm/agentvm mode. +// + +/* + * @test + * @bug 8209333 + * @summary Socket reset issue for TLS 1.3 socket close + * @library /javax/net/ssl/templates + * @run main/othervm SSLSocketBruceForceClose + */ + +import javax.net.ssl.*; +import java.io.*; +import java.net.InetAddress; + +public class SSLSocketBruceForceClose implements SSLContextTemplate { + + public static void main(String[] args) throws Exception { + for (int i = 0; i<= 10; i++) { + System.err.println("==================================="); + System.err.println("loop " + i); + System.err.println("==================================="); + new SSLSocketBruceForceClose().test(); + } + } + + private void test() throws Exception { + SSLServerSocket listenSocket = null; + SSLSocket serverSocket = null; + ClientSocket clientSocket = null; + try { + SSLServerSocketFactory serversocketfactory = + createServerSSLContext().getServerSocketFactory(); + listenSocket = + (SSLServerSocket)serversocketfactory.createServerSocket(0); + listenSocket.setNeedClientAuth(false); + listenSocket.setEnableSessionCreation(true); + listenSocket.setUseClientMode(false); + + + System.err.println("Starting client"); + clientSocket = new ClientSocket(listenSocket.getLocalPort()); + clientSocket.start(); + + System.err.println("Accepting client requests"); + serverSocket = (SSLSocket) listenSocket.accept(); + + System.err.println("Reading data from client"); + BufferedReader serverReader = new BufferedReader( + new InputStreamReader(serverSocket.getInputStream())); + String data = serverReader.readLine(); + System.err.println("Received data from client: " + data); + + System.err.println("Reading more data from client"); + data = serverReader.readLine(); + System.err.println("Received data from client: " + data); + } finally { + if (listenSocket != null) { + listenSocket.close(); + } + + if (serverSocket != null) { + serverSocket.close(); + } + } + + if (clientSocket != null && clientSocket.clientException != null) { + throw clientSocket.clientException; + } + } + + private class ClientSocket extends Thread{ + int serverPort = 0; + Exception clientException; + + public ClientSocket(int serverPort) { + this.serverPort = serverPort; + } + + @Override + public void run() { + SSLSocket clientSocket = null; + String clientData = "Hi, I am client"; + try { + System.err.println( + "Connecting to server at port " + serverPort); + SSLSocketFactory sslSocketFactory = + createClientSSLContext().getSocketFactory(); + clientSocket = (SSLSocket)sslSocketFactory.createSocket( + InetAddress.getLocalHost(), serverPort); + clientSocket.setSoLinger(true, 3); + clientSocket.setSoTimeout(1000); + + + System.err.println("Sending data to server ..."); + + BufferedWriter os = new BufferedWriter( + new OutputStreamWriter(clientSocket.getOutputStream())); + os.write(clientData, 0, clientData.length()); + os.newLine(); + os.flush(); + + System.err.println("Sending more data to server ..."); + os.write(clientData, 0, clientData.length()); + os.newLine(); + os.flush(); + } catch (Exception e) { + clientException = e; + } finally { + if (clientSocket != null) { + try{ + clientSocket.close(); + System.err.println("client socket closed"); + } catch (IOException ioe) { + clientException = ioe; + } + } + } + } + } +} + diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketClose.java b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketClose.java new file mode 100644 index 00000000000..47a06093e3f --- /dev/null +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketClose.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// Please run in othervm mode. SunJSSE does not support dynamic system +// properties, no way to re-use system properties in samevm/agentvm mode. +// + +/* + * @test + * @bug 8209333 + * @summary Socket reset issue for TLS 1.3 socket close + * @library /javax/net/ssl/templates + * @run main/othervm SSLSocketClose + */ + +import javax.net.ssl.*; +import java.io.*; +import java.net.InetAddress; + +public class SSLSocketClose implements SSLContextTemplate { + + public static void main(String[] args) throws Exception { + for (int i = 0; i<= 10; i++) { + System.err.println("==================================="); + System.err.println("loop " + i); + System.err.println("==================================="); + new SSLSocketClose().test(); + } + } + + private void test() throws Exception { + SSLServerSocket listenSocket = null; + SSLSocket serverSocket = null; + ClientSocket clientSocket = null; + try { + SSLServerSocketFactory serversocketfactory = + createServerSSLContext().getServerSocketFactory(); + listenSocket = + (SSLServerSocket)serversocketfactory.createServerSocket(0); + listenSocket.setNeedClientAuth(false); + listenSocket.setEnableSessionCreation(true); + listenSocket.setUseClientMode(false); + + + System.err.println("Starting client"); + clientSocket = new ClientSocket(listenSocket.getLocalPort()); + clientSocket.start(); + + System.err.println("Accepting client requests"); + serverSocket = (SSLSocket) listenSocket.accept(); + + System.err.println("Reading data from client"); + BufferedReader serverReader = new BufferedReader( + new InputStreamReader(serverSocket.getInputStream())); + String data = serverReader.readLine(); + System.err.println("Received data from client: " + data); + + System.err.println("Sending data to client ..."); + String serverData = "Hi, I am server"; + BufferedWriter os = new BufferedWriter( + new OutputStreamWriter(serverSocket.getOutputStream())); + os.write(serverData, 0, serverData.length()); + os.newLine(); + os.flush(); + + System.err.println("Reading more data from client"); + data = serverReader.readLine(); + System.err.println("Received data from client: " + data); + } finally { + if (listenSocket != null) { + listenSocket.close(); + } + + if (serverSocket != null) { + serverSocket.close(); + } + } + + if (clientSocket != null && clientSocket.clientException != null) { + throw clientSocket.clientException; + } + } + + private class ClientSocket extends Thread{ + int serverPort = 0; + Exception clientException; + + public ClientSocket(int serverPort) { + this.serverPort = serverPort; + } + + @Override + public void run() { + SSLSocket clientSocket = null; + String clientData = "Hi, I am client"; + try { + System.err.println( + "Connecting to server at port " + serverPort); + SSLSocketFactory sslSocketFactory = + createClientSSLContext().getSocketFactory(); + clientSocket = (SSLSocket)sslSocketFactory.createSocket( + InetAddress.getLocalHost(), serverPort); + clientSocket.setSoLinger(true, 3); + + System.err.println("Sending data to server ..."); + + BufferedWriter os = new BufferedWriter( + new OutputStreamWriter(clientSocket.getOutputStream())); + os.write(clientData, 0, clientData.length()); + os.newLine(); + os.flush(); + + System.err.println("Reading data from server"); + BufferedReader is = new BufferedReader( + new InputStreamReader(clientSocket.getInputStream())); + String data = is.readLine(); + System.err.println("Received Data from server: " + data); + + System.err.println("Sending more data to server ..."); + os.write(clientData, 0, clientData.length()); + os.newLine(); + os.flush(); + } catch (Exception e) { + clientException = e; + } finally { + if (clientSocket != null) { + try{ + clientSocket.close(); + System.err.println("client socket closed"); + } catch (IOException ioe) { + clientException = ioe; + } + } + } + } + } +} + From 57dc039131937dded0e25fcdb61efce6127d5743 Mon Sep 17 00:00:00 2001 From: Dean Long Date: Tue, 18 Dec 2018 16:36:26 -0800 Subject: [PATCH 100/174] 8214583: AccessController.getContext may return wrong value after JDK-8212605 Reviewed-by: mchung, redestad --- src/hotspot/share/include/jvm.h | 9 +++ src/hotspot/share/prims/jvm.cpp | 9 ++- .../java/security/AccessController.java | 19 +++++- .../share/native/libjava/AccessController.c | 9 +++ .../security/AccessController/DoPriv.java | 68 +++++++++++++++++++ .../jdk/javax/security/auth/Subject/DoAs.java | 57 ++++++++++++++++ 6 files changed, 167 insertions(+), 4 deletions(-) create mode 100644 test/jdk/java/security/AccessController/DoPriv.java create mode 100644 test/jdk/javax/security/auth/Subject/DoAs.java diff --git a/src/hotspot/share/include/jvm.h b/src/hotspot/share/include/jvm.h index 5fa112eb3d9..d0ba86e0a33 100644 --- a/src/hotspot/share/include/jvm.h +++ b/src/hotspot/share/include/jvm.h @@ -625,6 +625,15 @@ JVM_GetMethodParameters(JNIEnv *env, jobject method); JNIEXPORT jobject JNICALL JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls); +/* + * Ensure that code doing a stackwalk and using javaVFrame::locals() to + * get the value will see a materialized value and not a scalar-replaced + * null value. + */ +#define JVM_EnsureMaterializedForStackWalk(env, value) \ + do {} while(0) // Nothing to do. The fact that the value escaped + // through a native method is enough. + JNIEXPORT jobject JNICALL JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls); diff --git a/src/hotspot/share/prims/jvm.cpp b/src/hotspot/share/prims/jvm.cpp index 26772e6294a..e1e0fd394e1 100644 --- a/src/hotspot/share/prims/jvm.cpp +++ b/src/hotspot/share/prims/jvm.cpp @@ -61,6 +61,7 @@ #include "runtime/handles.inline.hpp" #include "runtime/init.hpp" #include "runtime/interfaceSupport.inline.hpp" +#include "runtime/deoptimization.hpp" #include "runtime/java.hpp" #include "runtime/javaCalls.hpp" #include "runtime/jfieldIDWorkaround.hpp" @@ -1245,8 +1246,12 @@ JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls)) javaVFrame *priv = vfst.asJavaVFrame(); // executePrivileged StackValueCollection* locals = priv->locals(); - privileged_context = locals->obj_at(1); - Handle caller = locals->obj_at(2); + StackValue* ctx_sv = locals->at(1); // AccessControlContext context + StackValue* clr_sv = locals->at(2); // Class caller + assert(!ctx_sv->obj_is_scalar_replaced(), "found scalar-replaced object"); + assert(!clr_sv->obj_is_scalar_replaced(), "found scalar-replaced object"); + privileged_context = ctx_sv->get_obj(); + Handle caller = clr_sv->get_obj(); Klass *caller_klass = java_lang_Class::as_Klass(caller()); protection_domain = caller_klass->protection_domain(); diff --git a/src/java.base/share/classes/java/security/AccessController.java b/src/java.base/share/classes/java/security/AccessController.java index 5cb1fef74e2..f8548639765 100644 --- a/src/java.base/share/classes/java/security/AccessController.java +++ b/src/java.base/share/classes/java/security/AccessController.java @@ -709,6 +709,13 @@ public final class AccessController { return context; } + /** + * The value needs to be physically located in the frame, so that it + * can be found by a stack walk. + */ + @Hidden + private static native void ensureMaterializedForStackWalk(Object o); + /** * Sanity check that the caller context is indeed privileged. * @@ -734,6 +741,11 @@ public final class AccessController { AccessControlContext context, Class caller) { + // Ensure context has a physical value in the frame + if (context != null) { + ensureMaterializedForStackWalk(context); + } + assert isPrivileged(); // sanity check invariant T result = action.run(); assert isPrivileged(); // sanity check invariant @@ -742,7 +754,6 @@ public final class AccessController { // retrieved by getStackAccessControlContext(). Reference.reachabilityFence(context); Reference.reachabilityFence(caller); - Reference.reachabilityFence(action); return result; } @@ -761,6 +772,11 @@ public final class AccessController { Class caller) throws Exception { + // Ensure context has a physical value in the frame + if (context != null) { + ensureMaterializedForStackWalk(context); + } + assert isPrivileged(); // sanity check invariant T result = action.run(); assert isPrivileged(); // sanity check invariant @@ -769,7 +785,6 @@ public final class AccessController { // retrieved by getStackAccessControlContext(). Reference.reachabilityFence(context); Reference.reachabilityFence(caller); - Reference.reachabilityFence(action); return result; } diff --git a/src/java.base/share/native/libjava/AccessController.c b/src/java.base/share/native/libjava/AccessController.c index 9d6a812505d..3fb85be9ccb 100644 --- a/src/java.base/share/native/libjava/AccessController.c +++ b/src/java.base/share/native/libjava/AccessController.c @@ -59,3 +59,12 @@ Java_java_security_AccessController_getInheritedAccessControlContext( { return JVM_GetInheritedAccessControlContext(env, this); } + +JNIEXPORT void JNICALL +Java_java_security_AccessController_ensureMaterializedForStackWalk( + JNIEnv *env, + jclass cls, + jobject value) +{ + JVM_EnsureMaterializedForStackWalk(env, value); +} diff --git a/test/jdk/java/security/AccessController/DoPriv.java b/test/jdk/java/security/AccessController/DoPriv.java new file mode 100644 index 00000000000..e99b8f62468 --- /dev/null +++ b/test/jdk/java/security/AccessController/DoPriv.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8214583 + * @summary Check that getContext works after JIT compiler escape analysis. + */ +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.DomainCombiner; +import java.security.ProtectionDomain; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.net.URL; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public class DoPriv { + + static void go(final DomainCombiner dc0, final AccessControlContext co, final int index) throws Exception { + final AccessControlContext ci = new AccessControlContext(co, dc0); + AccessController.doPrivileged((PrivilegedExceptionAction)() -> { + AccessControlContext c1 = AccessController.getContext(); + DomainCombiner dc = c1.getDomainCombiner(); + if (dc != dc0 || dc == null) { + throw new AssertionError("iteration " + index + " " + dc + " != " + dc0); + } + return 0; + }, ci); + } + + public static void main(String[] args) throws Exception { + final DomainCombiner dc0 = new DomainCombiner() { + public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, + ProtectionDomain[] assignedDomains) { + return null; + } + }; + + final AccessControlContext co = AccessController.getContext(); + + for (int i = 0; i < 500_000; ++i) { + go(dc0, co, i); + } + } +} diff --git a/test/jdk/javax/security/auth/Subject/DoAs.java b/test/jdk/javax/security/auth/Subject/DoAs.java new file mode 100644 index 00000000000..7f378be80a0 --- /dev/null +++ b/test/jdk/javax/security/auth/Subject/DoAs.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8214583 + * @summary Check that getSubject works after JIT compiler escape analysis. + */ +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedExceptionAction; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import javax.security.auth.Subject; + +public class DoAs { + + public static void main(String[] args) throws Exception { + final Set outer = new HashSet<>(Arrays.asList("Outer")); + final Subject subject = new Subject(true, Collections.EMPTY_SET, outer, Collections.EMPTY_SET); + + for (int i = 0; i < 100_000; ++i) { + final int index = i; + Subject.doAs(subject, (PrivilegedExceptionAction)() -> { + AccessControlContext c1 = AccessController.getContext(); + Subject s = Subject.getSubject(c1); + if (s != subject) { + throw new AssertionError("outer Oops! " + "iteration " + index + " " + s + " != " + subject); + } + return 0; + }); + } + } +} From cfcd43da04c68f0d74f298a6841bc0a83bf14f08 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Wed, 19 Dec 2018 02:27:44 +0000 Subject: [PATCH 101/174] 8214096: sun.security.util.SignatureUtil passes null parameter, so JCE validation fails Changed SignatureUtil.specialSetParameter to ignore null signature parameters Reviewed-by: mullan, weijun --- .../sun/security/util/SignatureUtil.java | 18 +---- .../security/util/misc/SetNullSigParams.java | 78 +++++++++++++++++++ 2 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 test/jdk/sun/security/util/misc/SetNullSigParams.java diff --git a/src/java.base/share/classes/sun/security/util/SignatureUtil.java b/src/java.base/share/classes/sun/security/util/SignatureUtil.java index 2d85566e48d..9fd8d18598b 100644 --- a/src/java.base/share/classes/sun/security/util/SignatureUtil.java +++ b/src/java.base/share/classes/sun/security/util/SignatureUtil.java @@ -28,8 +28,6 @@ package sun.security.util; import java.io.IOException; import java.security.*; import java.security.spec.*; -import sun.security.util.ObjectIdentifier; -import sun.security.x509.AlgorithmId; import sun.security.rsa.RSAUtil; /** @@ -86,13 +84,12 @@ public class SignatureUtil { // specified Signature object as signature parameters. public static void specialSetParameter(Signature sig, byte[] paramBytes) throws InvalidAlgorithmParameterException, ProviderException { - - AlgorithmParameters params = null; if (paramBytes != null) { String sigName = sig.getAlgorithm(); - params = createAlgorithmParameters(sigName, paramBytes); + AlgorithmParameters params = + createAlgorithmParameters(sigName, paramBytes); + specialSetParameter(sig, params); } - specialSetParameter(sig, params); } // Special method for setting the specified AlgorithmParameter object @@ -100,16 +97,9 @@ public class SignatureUtil { public static void specialSetParameter(Signature sig, AlgorithmParameters params) throws InvalidAlgorithmParameterException, ProviderException { - - String sigName = sig.getAlgorithm(); if (params != null) { + String sigName = sig.getAlgorithm(); sig.setParameter(getParamSpec(sigName, params)); - } else { - try { - sig.setParameter(null); - } catch (UnsupportedOperationException e) { - // ignore for maintaining backward compatibility - } } } } diff --git a/test/jdk/sun/security/util/misc/SetNullSigParams.java b/test/jdk/sun/security/util/misc/SetNullSigParams.java new file mode 100644 index 00000000000..f8e9ce0b0ee --- /dev/null +++ b/test/jdk/sun/security/util/misc/SetNullSigParams.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8214096 + * @summary Make sure SignatureUtil can accept null algorithm parameters + * @modules java.base/sun.security.util + */ +import java.security.*; +import java.security.spec.AlgorithmParameterSpec; +import sun.security.util.SignatureUtil; + +public class SetNullSigParams { + + public static void main(String[] args) throws Exception { + Signature sig = new SpecialSigImpl(); + SignatureUtil.specialSetParameter(sig, (byte[]) null); + SignatureUtil.specialSetParameter(sig, (AlgorithmParameters) null); + } + + // Sample Signature impl class which simulates 3rd party provider behavior + // and throws NPE when given null algorithm parameters + // For max backward-compatibility, sun.security.util.SignatureUtil class + // now calls setParameter() only when algorithm parameters is non-null + private static class SpecialSigImpl extends Signature { + SpecialSigImpl() { + super("ANY"); + } + @Override + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException {} + @Override + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException {} + @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 null; } + @Override + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException { return false; } + @Override + protected void engineSetParameter(String param, Object value) + throws InvalidParameterException {} + @Override + protected void engineSetParameter(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + if (params == null) throw new NullPointerException("Test Failed"); + } + @Override + protected Object engineGetParameter(String param) + throws InvalidParameterException { return null; } + } +} From fd6cbffc4bffe9b025f75054af80d8c9a0f6f02f Mon Sep 17 00:00:00 2001 From: Priya Lakshmi Muthuswamy Date: Wed, 19 Dec 2018 11:08:08 +0530 Subject: [PATCH 102/174] 8214570: Use {@systemProperty} for definitions of system properties Reviewed-by: alanb, mullan --- .../share/classes/javax/smartcardio/TerminalFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java b/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java index e37fe33a74f..21b8459c947 100644 --- a/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java +++ b/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -182,7 +182,7 @@ public final class TerminalFactory { *

    It is determined as follows: * * when this class is initialized, the system property - * javax.smartcardio.TerminalFactory.DefaultType + * {@systemProperty javax.smartcardio.TerminalFactory.DefaultType} * is examined. If it is set, a TerminalFactory of this type is * instantiated by calling the {@linkplain #getInstance * getInstance(String,Object)} method passing From b756562a67171906039b5a8b00bd0d3283131251 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Tue, 18 Dec 2018 13:37:06 -0800 Subject: [PATCH 103/174] 8215322: add @file support to jaotc Reviewed-by: kvn --- .../src/jdk/tools/jaotc/Main.java | 32 +++++++++- .../compiler/aot/cli/jaotc/AtFileTest.java | 60 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 test/hotspot/jtreg/compiler/aot/cli/jaotc/AtFileTest.java diff --git a/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java b/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java index ed384d5689f..31dc6bf441a 100644 --- a/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java +++ b/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java @@ -29,11 +29,18 @@ import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC; import static org.graalvm.compiler.core.common.GraalOptions.ImmutableCode; import static org.graalvm.compiler.hotspot.meta.HotSpotAOTProfilingPlugin.Options.TieredAOT; +import java.io.IOException; import java.io.PrintWriter; import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Set; +import java.util.StringTokenizer; +import java.util.stream.Stream; +import java.nio.file.Files; +import java.nio.file.Paths; import org.graalvm.compiler.api.replacements.SnippetReflectionProvider; import org.graalvm.compiler.api.runtime.GraalJVMCICompiler; @@ -78,10 +85,33 @@ public final class Main { public static void main(String[] args) throws Exception { Main t = new Main(); - final int exitCode = t.run(args); + final int exitCode = t.run(parse(args)); System.exit(exitCode); } + /** + * Expands '@file' in command line arguments by replacing '@file' with the content of 'file' + * parsed by StringTokenizer. '@' character can be quoted as '@@'. + */ + private static String[] parse(String[] args) throws IOException { + List result = new ArrayList<>(); + for (String arg : args) { + if (arg.length() > 1 && arg.charAt(0) == '@') { + String v = arg.substring(1); + if (v.charAt(0) == '@') { + result.add(v); + } else { + try (Stream file = Files.lines(Paths.get(v))) { + file.map(StringTokenizer::new).map(Collections::list).flatMap(l -> l.stream().map(o -> (String) o)).forEachOrdered(result::add); + } + } + } else { + result.add(arg); + } + } + return result.toArray(String[]::new); + } + private int run(String[] args) { log = new PrintWriter(System.out); printer = new LogPrinter(this, log); diff --git a/test/hotspot/jtreg/compiler/aot/cli/jaotc/AtFileTest.java b/test/hotspot/jtreg/compiler/aot/cli/jaotc/AtFileTest.java new file mode 100644 index 00000000000..af97bc67c85 --- /dev/null +++ b/test/hotspot/jtreg/compiler/aot/cli/jaotc/AtFileTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary check at-file jaotc support + * @comment based on CompileClassTest with arguments wrote in 'jaotc.cmd' file + * @requires vm.aot + * @bug 8215322 + * @library / /test/lib /testlibrary + * @modules java.base/jdk.internal.misc + * @build compiler.aot.cli.jaotc.AtFileTest + * @run driver ClassFileInstaller compiler.aot.cli.jaotc.data.HelloWorldOne + * @run driver compiler.aot.cli.jaotc.AtFileTest + */ + +package compiler.aot.cli.jaotc; + +import compiler.aot.cli.jaotc.data.HelloWorldOne; +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.Files; +import java.util.List; +import jdk.test.lib.Asserts; +import jdk.test.lib.process.OutputAnalyzer; + +public class AtFileTest { + public static void main(String[] args) throws Exception { + Path file = Paths.get("jatoc.cmd"); + Files.write(file, List.of("--class-name", + JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class))); + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("@" + file.toString()); + oa.shouldHaveExitValue(0); + File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); + Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); + Asserts.assertGT(compiledLibrary.length(), 0L, "Unexpected compiled library size"); + JaotcTestHelper.checkLibraryUsage(HelloWorldOne.class.getName()); + } +} From c9d7dd082744a120a41daea7a03bd7df3b1e74d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Per=20Lid=C3=A9n?= Date: Wed, 19 Dec 2018 08:32:48 +0100 Subject: [PATCH 104/174] 8215487: ZGC: ZRuntimeWorkers incorrectly identify themselves as ZWorkers Reviewed-by: eosterlund --- src/hotspot/share/gc/z/zObjectAllocator.cpp | 6 ++- src/hotspot/share/gc/z/zRuntimeWorkers.cpp | 45 +++++++++++++++++++++ src/hotspot/share/gc/z/zThread.cpp | 14 ++++++- src/hotspot/share/gc/z/zThread.hpp | 11 +++++ src/hotspot/share/gc/z/zWorkers.cpp | 23 +++++++---- 5 files changed, 88 insertions(+), 11 deletions(-) diff --git a/src/hotspot/share/gc/z/zObjectAllocator.cpp b/src/hotspot/share/gc/z/zObjectAllocator.cpp index 15eca0f9f5c..ad0d3098d53 100644 --- a/src/hotspot/share/gc/z/zObjectAllocator.cpp +++ b/src/hotspot/share/gc/z/zObjectAllocator.cpp @@ -128,7 +128,8 @@ uintptr_t ZObjectAllocator::alloc_medium_object(size_t size, ZAllocationFlags fl } uintptr_t ZObjectAllocator::alloc_small_object_from_nonworker(size_t size, ZAllocationFlags flags) { - assert(ZThread::is_java() || ZThread::is_vm(), "Should be a Java or VM thread"); + assert(ZThread::is_java() || ZThread::is_vm() || ZThread::is_runtime_worker(), + "Should be a Java, VM or Runtime worker thread"); // Non-worker small page allocation can never use the reserve flags.set_no_reserve(); @@ -193,7 +194,8 @@ uintptr_t ZObjectAllocator::alloc_object(size_t size) { } uintptr_t ZObjectAllocator::alloc_object_for_relocation(size_t size) { - assert(ZThread::is_java() || ZThread::is_worker() || ZThread::is_vm(), "Unknown thread"); + assert(ZThread::is_java() || ZThread::is_vm() || ZThread::is_worker() || ZThread::is_runtime_worker(), + "Unknown thread"); ZAllocationFlags flags; flags.set_relocation(); diff --git a/src/hotspot/share/gc/z/zRuntimeWorkers.cpp b/src/hotspot/share/gc/z/zRuntimeWorkers.cpp index 00a3e98d9d4..558224daf86 100644 --- a/src/hotspot/share/gc/z/zRuntimeWorkers.cpp +++ b/src/hotspot/share/gc/z/zRuntimeWorkers.cpp @@ -22,7 +22,43 @@ */ #include "precompiled.hpp" +#include "gc/shared/workgroup.hpp" #include "gc/z/zRuntimeWorkers.hpp" +#include "gc/z/zThread.hpp" +#include "runtime/mutexLocker.hpp" + +class ZRuntimeWorkersInitializeTask : public AbstractGangTask { +private: + const uint _nworkers; + uint _started; + Monitor _monitor; + +public: + ZRuntimeWorkersInitializeTask(uint nworkers) : + AbstractGangTask("ZRuntimeWorkersInitializeTask"), + _nworkers(nworkers), + _started(0), + _monitor(Monitor::leaf, + "ZRuntimeWorkersInitialize", + false /* allow_vm_block */, + Monitor::_safepoint_check_never) {} + + virtual void work(uint worker_id) { + // Register as runtime worker + ZThread::set_runtime_worker(); + + // Wait for all threads to start + MonitorLockerEx ml(&_monitor, Monitor::_no_safepoint_check_flag); + if (++_started == _nworkers) { + // All threads started + ml.notify_all(); + } else { + while (_started != _nworkers) { + ml.wait(Monitor::_no_safepoint_check_flag); + } + } + } +}; ZRuntimeWorkers::ZRuntimeWorkers() : _workers("RuntimeWorker", @@ -35,6 +71,15 @@ ZRuntimeWorkers::ZRuntimeWorkers() : // Initialize worker threads _workers.initialize_workers(); _workers.update_active_workers(nworkers()); + if (_workers.active_workers() != nworkers()) { + vm_exit_during_initialization("Failed to create ZRuntimeWorkers"); + } + + // Execute task to register threads as runtime workers. This also + // helps reduce latency in early safepoints, which otherwise would + // have to take on any warmup costs. + ZRuntimeWorkersInitializeTask task(nworkers()); + _workers.run_task(&task); } uint ZRuntimeWorkers::nworkers() const { diff --git a/src/hotspot/share/gc/z/zThread.cpp b/src/hotspot/share/gc/z/zThread.cpp index 5bde1d113e3..a1598671056 100644 --- a/src/hotspot/share/gc/z/zThread.cpp +++ b/src/hotspot/share/gc/z/zThread.cpp @@ -31,6 +31,7 @@ __thread uintptr_t ZThread::_id; __thread bool ZThread::_is_vm; __thread bool ZThread::_is_java; __thread bool ZThread::_is_worker; +__thread bool ZThread::_is_runtime_worker; __thread uint ZThread::_worker_id; void ZThread::initialize() { @@ -40,7 +41,8 @@ void ZThread::initialize() { _id = (uintptr_t)thread; _is_vm = thread->is_VM_thread(); _is_java = thread->is_Java_thread(); - _is_worker = thread->is_Worker_thread(); + _is_worker = false; + _is_runtime_worker = false; _worker_id = (uint)-1; } @@ -56,6 +58,16 @@ const char* ZThread::name() { return "Unknown"; } +void ZThread::set_worker() { + ensure_initialized(); + _is_worker = true; +} + +void ZThread::set_runtime_worker() { + ensure_initialized(); + _is_runtime_worker = true; +} + bool ZThread::has_worker_id() { return _initialized && _is_worker && diff --git a/src/hotspot/share/gc/z/zThread.hpp b/src/hotspot/share/gc/z/zThread.hpp index 365a216caf5..c87ee666d92 100644 --- a/src/hotspot/share/gc/z/zThread.hpp +++ b/src/hotspot/share/gc/z/zThread.hpp @@ -29,6 +29,8 @@ class ZThread : public AllStatic { friend class ZTask; + friend class ZWorkersInitializeTask; + friend class ZRuntimeWorkersInitializeTask; private: static __thread bool _initialized; @@ -36,6 +38,7 @@ private: static __thread bool _is_vm; static __thread bool _is_java; static __thread bool _is_worker; + static __thread bool _is_runtime_worker; static __thread uint _worker_id; static void initialize(); @@ -46,6 +49,9 @@ private: } } + static void set_worker(); + static void set_runtime_worker(); + static bool has_worker_id(); static void set_worker_id(uint worker_id); static void clear_worker_id(); @@ -73,6 +79,11 @@ public: return _is_worker; } + static bool is_runtime_worker() { + ensure_initialized(); + return _is_runtime_worker; + } + static uint worker_id() { assert(has_worker_id(), "Worker id not initialized"); return _worker_id; diff --git a/src/hotspot/share/gc/z/zWorkers.cpp b/src/hotspot/share/gc/z/zWorkers.cpp index 6a0c2561dec..c60c043ad45 100644 --- a/src/hotspot/share/gc/z/zWorkers.cpp +++ b/src/hotspot/share/gc/z/zWorkers.cpp @@ -24,6 +24,7 @@ #include "precompiled.hpp" #include "gc/z/zGlobals.hpp" #include "gc/z/zTask.hpp" +#include "gc/z/zThread.hpp" #include "gc/z/zWorkers.inline.hpp" #include "runtime/os.hpp" #include "runtime/mutexLocker.hpp" @@ -64,20 +65,26 @@ uint ZWorkers::calculate_nconcurrent() { return calculate_nworkers(12.5); } -class ZWorkersWarmupTask : public ZTask { +class ZWorkersInitializeTask : public ZTask { private: const uint _nworkers; uint _started; Monitor _monitor; public: - ZWorkersWarmupTask(uint nworkers) : - ZTask("ZWorkersWarmupTask"), + ZWorkersInitializeTask(uint nworkers) : + ZTask("ZWorkersInitializeTask"), _nworkers(nworkers), _started(0), - _monitor(Monitor::leaf, "ZWorkersWarmup", false, Monitor::_safepoint_check_never) {} + _monitor(Monitor::leaf, + "ZWorkersInitialize", + false /* allow_vm_block */, + Monitor::_safepoint_check_never) {} virtual void work() { + // Register as worker + ZThread::set_worker(); + // Wait for all threads to start MonitorLockerEx ml(&_monitor, Monitor::_no_safepoint_check_flag); if (++_started == _nworkers) { @@ -107,10 +114,10 @@ ZWorkers::ZWorkers() : vm_exit_during_initialization("Failed to create ZWorkers"); } - // Warm up worker threads by having them execute a dummy task. - // This helps reduce latency in early GC pauses, which otherwise - // would have to take on any warmup costs. - ZWorkersWarmupTask task(nworkers()); + // Execute task to register threads as workers. This also helps + // reduce latency in early GC pauses, which otherwise would have + // to take on any warmup costs. + ZWorkersInitializeTask task(nworkers()); run(&task, nworkers()); } From 36d0987f4d52a37b77831768cc0ee31b138bdeeb Mon Sep 17 00:00:00 2001 From: Sean Coffey Date: Wed, 19 Dec 2018 18:21:38 +0000 Subject: [PATCH 105/174] 8214532: Update RFC 2459 references in javadoc to RFC 5280 Reviewed-by: mullan --- .../certpath/DistributionPointFetcher.java | 4 +- .../provider/certpath/ForwardBuilder.java | 4 +- .../share/classes/sun/security/x509/AVA.java | 2 +- .../sun/security/x509/AlgorithmId.java | 8 +-- .../x509/CertificatePoliciesExtension.java | 4 +- .../classes/sun/security/x509/DNSName.java | 2 +- .../sun/security/x509/IPAddressName.java | 55 ++++++++++--------- .../sun/security/x509/KeyIdentifier.java | 4 +- .../x509/NameConstraintsExtension.java | 4 +- .../classes/sun/security/x509/OIDName.java | 4 +- .../classes/sun/security/x509/RFC822Name.java | 25 +++++---- .../classes/sun/security/x509/URIName.java | 4 +- .../sun/security/x509/X400Address.java | 4 +- .../sun/security/x509/X509CertImpl.java | 12 +--- 14 files changed, 66 insertions(+), 70 deletions(-) diff --git a/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java b/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java index 0f16c646a9c..5715842beef 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -770,7 +770,7 @@ public class DistributionPointFetcher { * * In practice, conforming CAs MUST use the key identifier method, * and MUST include authority key identifier extension in all CRLs - * issued. [section 5.2.1, RFC 2459] + * issued. [section 5.2.1, RFC 5280] */ AuthorityKeyIdentifierExtension crlAKID = crl.getAuthKeyIdExtension(); issuerSelector.setSkiAndSerialNumber(crlAKID); diff --git a/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java b/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java index 56ecabfc4f3..6122fdaa970 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -668,7 +668,7 @@ class ForwardBuilder extends Builder { * Verifies a matching certificate. * * This method executes the validation steps in the PKIX path - * validation algorithm which were + * validation algorithm, RFC 5280, which were * not satisfied by the selection criteria used by getCertificates() * to find the certs and only the steps that can be executed in a * forward direction (target to trust anchor). Those steps that can diff --git a/src/java.base/share/classes/sun/security/x509/AVA.java b/src/java.base/share/classes/sun/security/x509/AVA.java index 107189bc47c..654729528f3 100644 --- a/src/java.base/share/classes/sun/security/x509/AVA.java +++ b/src/java.base/share/classes/sun/security/x509/AVA.java @@ -1045,7 +1045,7 @@ public class AVA implements DerEncoder { if (valStr == null) { - // rfc1779 specifies that attribute values associated + // RFC 1779 specifies that attribute values associated // with non-standard keyword attributes may be represented // using the hex format below. This will be used only // when the value is not a string type diff --git a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index 825e4ffb81e..5ecb716adf1 100644 --- a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -166,15 +166,15 @@ public class AlgorithmId implements Serializable, DerEncoder { // Several AlgorithmId should omit the whole parameter part when // it's NULL. They are --- - // rfc3370 2.1: Implementations SHOULD generate SHA-1 + // RFC 3370 2.1: Implementations SHOULD generate SHA-1 // AlgorithmIdentifiers with absent parameters. - // rfc3447 C1: When id-sha1, id-sha224, id-sha256, id-sha384 and + // RFC 3447 C1: When id-sha1, id-sha224, id-sha256, id-sha384 and // id-sha512 are used in an AlgorithmIdentifier the parameters // (which are optional) SHOULD be omitted. - // rfc3279 2.3.2: The id-dsa algorithm syntax includes optional + // RFC 3279 2.3.2: The id-dsa algorithm syntax includes optional // domain parameters... When omitted, the parameters component // MUST be omitted entirely - // rfc3370 3.1: When the id-dsa-with-sha1 algorithm identifier + // RFC 3370 3.1: When the id-dsa-with-sha1 algorithm identifier // is used, the AlgorithmIdentifier parameters field MUST be absent. /*if ( algid.equals((Object)SHA_oid) || diff --git a/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java b/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java index 925936658f7..c2f71b3abc8 100644 --- a/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java +++ b/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -45,7 +45,7 @@ import sun.security.util.DerOutputStream; * certificate. *

    * Optional qualifiers are not supported in this implementation, as they are - * not recommended by RFC2459. + * not recommended by RFC 5280. * * The ASN.1 syntax for this is (IMPLICIT tagging is defined in the * module definition): diff --git a/src/java.base/share/classes/sun/security/x509/DNSName.java b/src/java.base/share/classes/sun/security/x509/DNSName.java index 5ddce75833b..b2c2da637ec 100644 --- a/src/java.base/share/classes/sun/security/x509/DNSName.java +++ b/src/java.base/share/classes/sun/security/x509/DNSName.java @@ -181,7 +181,7 @@ public class DNSName implements GeneralNameInterface { * For example, www.host.example.com would satisfy the constraint but * host1.example.com would not. *

    - * draft-ietf-pkix-new-part1-00.txt: DNSName restrictions are expressed as foo.bar.com. + * RFC 5280: DNSName restrictions are expressed as foo.bar.com. * Any DNSName that * can be constructed by simply adding to the left hand side of the name * satisfies the name constraint. For example, www.foo.bar.com would diff --git a/src/java.base/share/classes/sun/security/x509/IPAddressName.java b/src/java.base/share/classes/sun/security/x509/IPAddressName.java index f9451744059..7c12cae9128 100644 --- a/src/java.base/share/classes/sun/security/x509/IPAddressName.java +++ b/src/java.base/share/classes/sun/security/x509/IPAddressName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -37,27 +37,27 @@ import sun.security.util.DerValue; /** * This class implements the IPAddressName as required by the GeneralNames * ASN.1 object. Both IPv4 and IPv6 addresses are supported using the - * formats specified in IETF PKIX RFC2459. + * formats specified in IETF PKIX RFC 5280. *

    - * [RFC2459 4.2.1.7 Subject Alternative Name] - * When the subjectAltName extension contains a iPAddress, the address - * MUST be stored in the octet string in "network byte order," as - * specified in RFC 791. The least significant bit (LSB) of - * each octet is the LSB of the corresponding byte in the network - * address. For IP Version 4, as specified in RFC 791, the octet string - * MUST contain exactly four octets. For IP Version 6, as specified in - * RFC 1883, the octet string MUST contain exactly sixteen octets. + * [RFC 5280 4.2.1.6 Subject Alternative Name] + * When the subjectAltName extension contains an iPAddress, the address + * MUST be stored in the octet string in "network byte order", as + * specified in [RFC791]. The least significant bit (LSB) of each octet + * is the LSB of the corresponding byte in the network address. For IP + * version 4, as specified in [RFC791], the octet string MUST contain + * exactly four octets. For IP version 6, as specified in + * [RFC 2460], the octet string MUST contain exactly sixteen octets. *

    - * [RFC2459 4.2.1.11 Name Constraints] - * The syntax of iPAddress MUST be as described in section 4.2.1.7 with - * the following additions specifically for Name Constraints. For IPv4 - * addresses, the ipAddress field of generalName MUST contain eight (8) - * octets, encoded in the style of RFC 1519 (CIDR) to represent an - * address range.[RFC 1519] For IPv6 addresses, the ipAddress field + * [RFC 5280 4.2.1.10 Name Constraints] + * The syntax of iPAddress MUST be as described in Section 4.2.1.6 with + * the following additions specifically for name constraints. For IPv4 + * addresses, the iPAddress field of GeneralName MUST contain eight (8) + * octets, encoded in the style of RFC 4632 (CIDR) to represent an + * address range [RFC 4632]. For IPv6 addresses, the iPAddress field * MUST contain 32 octets similarly encoded. For example, a name - * constraint for "class C" subnet 10.9.8.0 shall be represented as the - * octets 0A 09 08 00 FF FF FF 00, representing the CIDR notation - * 10.9.8.0/255.255.255.0. + * constraint for "class C" subnet 192.0.2.0 is represented as the + * octets C0 00 02 00 FF FF FF 00, representing the CIDR notation + * 192.0.2.0/24 (mask 255.255.255.0). *

    * @see GeneralName * @see GeneralNameInterface @@ -376,15 +376,16 @@ public class IPAddressName implements GeneralNameInterface { * . These results are used in checking NameConstraints during * certification path verification. *

    - * [RFC2459] The syntax of iPAddress MUST be as described in section - * 4.2.1.7 with the following additions specifically for Name Constraints. - * For IPv4 addresses, the ipAddress field of generalName MUST contain - * eight (8) octets, encoded in the style of RFC 1519 (CIDR) to represent an - * address range.[RFC 1519] For IPv6 addresses, the ipAddress field + * [RFC 5280 4.2.1.10 Name Constraints] + * The syntax of iPAddress MUST be as described in Section 4.2.1.6 with + * the following additions specifically for name constraints. For IPv4 + * addresses, the iPAddress field of GeneralName MUST contain eight (8) + * octets, encoded in the style of RFC 4632 (CIDR) to represent an + * address range [RFC 4632]. For IPv6 addresses, the iPAddress field * MUST contain 32 octets similarly encoded. For example, a name - * constraint for "class C" subnet 10.9.8.0 shall be represented as the - * octets 0A 09 08 00 FF FF FF 00, representing the CIDR notation - * 10.9.8.0/255.255.255.0. + * constraint for "class C" subnet 192.0.2.0 is represented as the + * octets C0 00 02 00 FF FF FF 00, representing the CIDR notation + * 192.0.2.0/24 (mask 255.255.255.0). * * @param inputName to be checked for being constrained * @return constraint type above diff --git a/src/java.base/share/classes/sun/security/x509/KeyIdentifier.java b/src/java.base/share/classes/sun/security/x509/KeyIdentifier.java index 97036e2ea88..d74bc051b96 100644 --- a/src/java.base/share/classes/sun/security/x509/KeyIdentifier.java +++ b/src/java.base/share/classes/sun/security/x509/KeyIdentifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -63,7 +63,7 @@ public class KeyIdentifier { /** * Creates a KeyIdentifier from a public-key value. * - *

    From RFC2459: Two common methods for generating key identifiers from + *

    From RFC 5280: Two common methods for generating key identifiers from * the public key are: *

      *
    1. The keyIdentifier is composed of the 160-bit SHA-1 hash of the diff --git a/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java b/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java index 88f787e0704..e595fbd6811 100644 --- a/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java +++ b/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -326,7 +326,7 @@ implements CertAttrSet, Cloneable { * expanded by a merge, just remain constant or become more * limiting. *

      - * IETF RFC2459 specifies the processing of Name Constraints as + * IETF RFC 5280 specifies the processing of Name Constraints as * follows: *

      * (j) If permittedSubtrees is present in the certificate, set the diff --git a/src/java.base/share/classes/sun/security/x509/OIDName.java b/src/java.base/share/classes/sun/security/x509/OIDName.java index 6db9d11e2d3..eda3426a985 100644 --- a/src/java.base/share/classes/sun/security/x509/OIDName.java +++ b/src/java.base/share/classes/sun/security/x509/OIDName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -156,7 +156,7 @@ public class OIDName implements GeneralNameInterface { else if (this.equals((OIDName)inputName)) constraintType = NAME_MATCH; else - //widens and narrows not defined in RFC2459 for OIDName (aka registeredID) + //widens and narrows not defined in RFC 5280 for OIDName (aka registeredID) throw new UnsupportedOperationException("Narrowing and widening are not supported for OIDNames"); return constraintType; } diff --git a/src/java.base/share/classes/sun/security/x509/RFC822Name.java b/src/java.base/share/classes/sun/security/x509/RFC822Name.java index 916b1beeecb..312e7a7cf21 100644 --- a/src/java.base/share/classes/sun/security/x509/RFC822Name.java +++ b/src/java.base/share/classes/sun/security/x509/RFC822Name.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,7 @@ public class RFC822Name implements GeneralNameInterface /** * Parse an RFC822Name string to see if it is a valid - * addr-spec according to IETF RFC822 and RFC2459: + * addr-spec according to IETF RFC 822 and RFC 5280: * [local-part@]domain *

      * local-part@ could be empty for an RFC822Name NameConstraint, @@ -131,7 +131,7 @@ public class RFC822Name implements GeneralNameInterface * Compares this name with another, for equality. * * @return true iff the names are equivalent - * according to RFC2459. + * according to RFC 5280. */ public boolean equals(Object obj) { if (this == obj) @@ -142,7 +142,7 @@ public class RFC822Name implements GeneralNameInterface RFC822Name other = (RFC822Name)obj; - // RFC2459 mandates that these names are + // RFC 5280 mandates that these names are // not case-sensitive return name.equalsIgnoreCase(other.name); } @@ -166,14 +166,15 @@ public class RFC822Name implements GeneralNameInterface * . These results are used in checking NameConstraints during * certification path verification. *

      - * [RFC2459] When the subjectAltName extension contains an Internet mail address, - * the address MUST be included as an rfc822Name. The format of an - * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822]. An - * addr-spec has the form "local-part@domain". Note that an addr-spec - * has no phrase (such as a common name) before it, has no comment (text + * + * [RFC 5280]: + * When the subjectAltName extension contains an Internet mail address, + * the address MUST be stored in the rfc822Name. The format of an + * rfc822Name is a "Mailbox" as defined in Section 4.1.2 of [RFC2821]. + * A Mailbox has the form "Local-part@Domain". Note that a Mailbox has + * no phrase (such as a common name) before it, has no comment (text * surrounded in parentheses) after it, and is not surrounded by "<" and - * ">". Note that while upper and lower case letters are allowed in an - * RFC 822 addr-spec, no significance is attached to the case. + * ">". * * @param inputName to be checked for being constrained * @return constraint type above @@ -187,7 +188,7 @@ public class RFC822Name implements GeneralNameInterface else if (inputName.getType() != (GeneralNameInterface.NAME_RFC822)) { constraintType = NAME_DIFF_TYPE; } else { - //RFC2459 specifies that case is not significant in RFC822Names + //RFC 5280 specifies that case is not significant in RFC822Names String inName = (((RFC822Name)inputName).getName()).toLowerCase(Locale.ENGLISH); String thisName = name.toLowerCase(Locale.ENGLISH); diff --git a/src/java.base/share/classes/sun/security/x509/URIName.java b/src/java.base/share/classes/sun/security/x509/URIName.java index 4820de87e11..490a35f86b2 100644 --- a/src/java.base/share/classes/sun/security/x509/URIName.java +++ b/src/java.base/share/classes/sun/security/x509/URIName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -213,7 +213,7 @@ public class URIName implements GeneralNameInterface { /** * Compares this name with another, for equality. * - * @return true iff the names are equivalent according to RFC2459. + * @return true iff the names are equivalent according to RFC 5280. */ public boolean equals(Object obj) { if (this == obj) { diff --git a/src/java.base/share/classes/sun/security/x509/X400Address.java b/src/java.base/share/classes/sun/security/x509/X400Address.java index 35839e87825..f0624d93cc3 100644 --- a/src/java.base/share/classes/sun/security/x509/X400Address.java +++ b/src/java.base/share/classes/sun/security/x509/X400Address.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -403,7 +403,7 @@ public class X400Address implements GeneralNameInterface { else if (inputName.getType() != NAME_X400) constraintType = NAME_DIFF_TYPE; else - //Narrowing, widening, and match constraints not defined in rfc2459 for X400Address + //Narrowing, widening, and match constraints not defined in RFC 5280 for X400Address throw new UnsupportedOperationException("Narrowing, widening, and match are not supported for X400Address."); return constraintType; } diff --git a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java index 52cbe71e88f..5fff18309d2 100644 --- a/src/java.base/share/classes/sun/security/x509/X509CertImpl.java +++ b/src/java.base/share/classes/sun/security/x509/X509CertImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -63,14 +63,8 @@ import sun.security.provider.X509Factory; * direct knowledge of each other. CA certificates are either signed by * themselves, or by some other CA such as a "root" CA. * - *

      RFC 1422 is very informative, though it does not describe much - * of the recent work being done with X.509 certificates. That includes - * a 1996 version (X.509v3) and a variety of enhancements being made to - * facilitate an explosion of personal certificates used as "Internet - * Drivers' Licences", or with SET for credit card transactions. - * - *

      More recent work includes the IETF PKIX Working Group efforts, - * especially RFC2459. + *

      Standards relating to X.509 Public Key Infrastructure for the Internet + * can be referenced in RFC 5280. * * @author Dave Brownell * @author Amit Kapoor From 205598c97fe0d5a10d5fb7f0c36821f4abf7fc41 Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Thu, 20 Dec 2018 02:54:16 +0100 Subject: [PATCH 106/174] Added tag jdk-12+25 for changeset 7496df94b3b7 --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index f2d1a58c394..35959b6d547 100644 --- a/.hgtags +++ b/.hgtags @@ -527,3 +527,4 @@ f8fb0c86f2b3d24294d39c5685a628e1beb14ba7 jdk-12+21 732bec44c89e8b93a38296bf690f97b7230c5b6d jdk-12+22 eef755718cb24813031a842bbfc716a6cea18e9a jdk-12+23 7d4397b43fa305806160785a4c7210600d59581a jdk-12+24 +7496df94b3b79f3da53925d2d137317715f11d97 jdk-12+25 From 1cc5cf4c0200e038fd9cd9b3128c1aba4a369ab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20=C3=96sterlund?= Date: Thu, 20 Dec 2018 10:41:45 +0100 Subject: [PATCH 107/174] 8215500: ICRefillVerifierMark does not set the provided verfier as current Reviewed-by: pliden, thartmann --- src/hotspot/share/code/icBuffer.cpp | 14 +++++++------- src/hotspot/share/runtime/thread.cpp | 2 +- src/hotspot/share/runtime/thread.hpp | 11 ++++++----- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/hotspot/share/code/icBuffer.cpp b/src/hotspot/share/code/icBuffer.cpp index b03554c2bac..39b7ab11e31 100644 --- a/src/hotspot/share/code/icBuffer.cpp +++ b/src/hotspot/share/code/icBuffer.cpp @@ -53,29 +53,29 @@ ICRefillVerifier::ICRefillVerifier() _refill_remembered(false) { Thread* thread = Thread::current(); - assert(thread->missed_ic_stub_refill_mark() == NULL, "nesting not supported"); - thread->set_missed_ic_stub_refill_mark(this); + assert(thread->missed_ic_stub_refill_verifier() == NULL, "nesting not supported"); + thread->set_missed_ic_stub_refill_verifier(this); } ICRefillVerifier::~ICRefillVerifier() { assert(!_refill_requested || _refill_remembered, "Forgot to refill IC stubs after failed IC transition"); - Thread::current()->set_missed_ic_stub_refill_mark(NULL); + Thread::current()->set_missed_ic_stub_refill_verifier(NULL); } ICRefillVerifierMark::ICRefillVerifierMark(ICRefillVerifier* verifier) { Thread* thread = Thread::current(); - assert(thread->missed_ic_stub_refill_mark() == NULL, "nesting not supported"); - thread->set_missed_ic_stub_refill_mark(this); + assert(thread->missed_ic_stub_refill_verifier() == NULL, "nesting not supported"); + thread->set_missed_ic_stub_refill_verifier(verifier); } ICRefillVerifierMark::~ICRefillVerifierMark() { - Thread::current()->set_missed_ic_stub_refill_mark(NULL); + Thread::current()->set_missed_ic_stub_refill_verifier(NULL); } static ICRefillVerifier* current_ic_refill_verifier() { Thread* current = Thread::current(); - ICRefillVerifier* verifier = reinterpret_cast(current->missed_ic_stub_refill_mark()); + ICRefillVerifier* verifier = current->missed_ic_stub_refill_verifier(); assert(verifier != NULL, "need a verifier for safety"); return verifier; } diff --git a/src/hotspot/share/runtime/thread.cpp b/src/hotspot/share/runtime/thread.cpp index e2e43893de2..539810c0fb7 100644 --- a/src/hotspot/share/runtime/thread.cpp +++ b/src/hotspot/share/runtime/thread.cpp @@ -231,7 +231,7 @@ Thread::Thread() { set_active_handles(NULL); set_free_handle_block(NULL); set_last_handle_mark(NULL); - DEBUG_ONLY(_missed_ic_stub_refill_mark = NULL); + DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL); // This initial value ==> never claimed. _oops_do_parity = 0; diff --git a/src/hotspot/share/runtime/thread.hpp b/src/hotspot/share/runtime/thread.hpp index 8509c918f68..b00f662c495 100644 --- a/src/hotspot/share/runtime/thread.hpp +++ b/src/hotspot/share/runtime/thread.hpp @@ -81,6 +81,7 @@ class jvmtiDeferredLocalVariableSet; class GCTaskQueue; class ThreadClosure; +class ICRefillVerifier; class IdealGraphPrinter; class Metadata; @@ -329,15 +330,15 @@ class Thread: public ThreadShadow { private: #ifdef ASSERT - void* _missed_ic_stub_refill_mark; + ICRefillVerifier* _missed_ic_stub_refill_verifier; public: - void* missed_ic_stub_refill_mark() { - return _missed_ic_stub_refill_mark; + ICRefillVerifier* missed_ic_stub_refill_verifier() { + return _missed_ic_stub_refill_verifier; } - void set_missed_ic_stub_refill_mark(void* mark) { - _missed_ic_stub_refill_mark = mark; + void set_missed_ic_stub_refill_verifier(ICRefillVerifier* verifier) { + _missed_ic_stub_refill_verifier = verifier; } #endif From 83adde986667a2fbfb620bf90f6e27607f660e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20=C3=96sterlund?= Date: Thu, 20 Dec 2018 10:41:45 +0100 Subject: [PATCH 108/174] 8215491: ICStubInterface::finalize finds zombie nmethod with ZGC concurrent class unloading Reviewed-by: dlong, coleenp --- src/hotspot/share/code/nmethod.cpp | 7 +++++++ src/hotspot/share/runtime/sweeper.cpp | 6 ------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/hotspot/share/code/nmethod.cpp b/src/hotspot/share/code/nmethod.cpp index bbd416bf828..02c9247bf2a 100644 --- a/src/hotspot/share/code/nmethod.cpp +++ b/src/hotspot/share/code/nmethod.cpp @@ -1283,6 +1283,13 @@ bool nmethod::make_not_entrant_or_zombie(int state) { flush_dependencies(/*delete_immediately*/true); } + // Clear ICStubs to prevent back patching stubs of zombie or flushed + // nmethods during the next safepoint (see ICStub::finalize). + { + CompiledICLocker ml(this); + clear_ic_stubs(); + } + // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload // event and it hasn't already been reported for this nmethod then // report it now. The event may have been reported earlier if the GC diff --git a/src/hotspot/share/runtime/sweeper.cpp b/src/hotspot/share/runtime/sweeper.cpp index 88a94f32dfb..c5e5a7fdfc1 100644 --- a/src/hotspot/share/runtime/sweeper.cpp +++ b/src/hotspot/share/runtime/sweeper.cpp @@ -717,12 +717,6 @@ NMethodSweeper::MethodStateChange NMethodSweeper::process_compiled_method(Compil // stack we can safely convert it to a zombie method OrderAccess::loadload(); // _stack_traversal_mark and _state if (cm->can_convert_to_zombie()) { - // Clear ICStubs to prevent back patching stubs of zombie or flushed - // nmethods during the next safepoint (see ICStub::finalize). - { - CompiledICLocker ml(cm); - cm->clear_ic_stubs(); - } // Code cache state change is tracked in make_zombie() cm->make_zombie(); SWEEP(cm); From 2778c8648819d7a068b0b5e505dc95eb8a6f34c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Per=20Lid=C3=A9n?= Date: Thu, 20 Dec 2018 11:43:04 +0100 Subject: [PATCH 109/174] 8215547: ZGC: Fix incorrect match rule for loadBarrierWeakSlowRegNoVec Reviewed-by: eosterlund, neliasso --- src/hotspot/cpu/x86/x86_64.ad | 258 +++++++++--------- .../linux_x86/gc/z/zArguments_linux_x86.cpp | 40 +++ src/hotspot/share/gc/z/zArguments.cpp | 4 +- src/hotspot/share/gc/z/zArguments.hpp | 3 + 4 files changed, 180 insertions(+), 125 deletions(-) create mode 100644 src/hotspot/os_cpu/linux_x86/gc/z/zArguments_linux_x86.cpp diff --git a/src/hotspot/cpu/x86/x86_64.ad b/src/hotspot/cpu/x86/x86_64.ad index a8ae966fa62..ebaf2fe8355 100644 --- a/src/hotspot/cpu/x86/x86_64.ad +++ b/src/hotspot/cpu/x86/x86_64.ad @@ -4265,132 +4265,196 @@ operand cmpOpUCF2() %{ // Operands for bound floating pointer register arguments operand rxmm0() %{ - constraint(ALLOC_IN_RC(xmm0_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX<= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm0_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm1() %{ - constraint(ALLOC_IN_RC(xmm1_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm1_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm2() %{ - constraint(ALLOC_IN_RC(xmm2_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm2_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm3() %{ - constraint(ALLOC_IN_RC(xmm3_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm3_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm4() %{ - constraint(ALLOC_IN_RC(xmm4_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm4_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm5() %{ - constraint(ALLOC_IN_RC(xmm5_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm5_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm6() %{ - constraint(ALLOC_IN_RC(xmm6_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm6_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm7() %{ - constraint(ALLOC_IN_RC(xmm7_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm7_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm8() %{ - constraint(ALLOC_IN_RC(xmm8_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm8_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm9() %{ - constraint(ALLOC_IN_RC(xmm9_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm9_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm10() %{ - constraint(ALLOC_IN_RC(xmm10_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm10_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm11() %{ - constraint(ALLOC_IN_RC(xmm11_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm11_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm12() %{ - constraint(ALLOC_IN_RC(xmm12_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm12_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm13() %{ - constraint(ALLOC_IN_RC(xmm13_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm13_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm14() %{ - constraint(ALLOC_IN_RC(xmm14_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm14_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm15() %{ - constraint(ALLOC_IN_RC(xmm15_reg)); match(VecX); - predicate((UseSSE > 0) && (UseAVX <= 2)); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm15_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm16() %{ - constraint(ALLOC_IN_RC(xmm16_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm16_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm17() %{ - constraint(ALLOC_IN_RC(xmm17_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm17_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm18() %{ - constraint(ALLOC_IN_RC(xmm18_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm18_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm19() %{ - constraint(ALLOC_IN_RC(xmm19_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm19_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm20() %{ - constraint(ALLOC_IN_RC(xmm20_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm20_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm21() %{ - constraint(ALLOC_IN_RC(xmm21_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm21_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm22() %{ - constraint(ALLOC_IN_RC(xmm22_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm22_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm23() %{ - constraint(ALLOC_IN_RC(xmm23_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm23_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm24() %{ - constraint(ALLOC_IN_RC(xmm24_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm24_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm25() %{ - constraint(ALLOC_IN_RC(xmm25_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm25_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm26() %{ - constraint(ALLOC_IN_RC(xmm26_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm26_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm27() %{ - constraint(ALLOC_IN_RC(xmm27_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm27_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm28() %{ - constraint(ALLOC_IN_RC(xmm28_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm28_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm29() %{ - constraint(ALLOC_IN_RC(xmm29_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm29_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm30() %{ - constraint(ALLOC_IN_RC(xmm30_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm30_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} operand rxmm31() %{ - constraint(ALLOC_IN_RC(xmm31_reg)); match(VecX); - predicate(UseAVX == 3); format%{%} interface(REG_INTER); + constraint(ALLOC_IN_RC(xmm31_reg)); + match(VecX); + format%{%} + interface(REG_INTER); %} //----------OPERAND CLASSES---------------------------------------------------- @@ -12651,33 +12715,6 @@ instruct RethrowException() // Execute ZGC load barrier (strong) slow path // -// When running without XMM regs -instruct loadBarrierSlowRegNoVec(rRegP dst, memory mem, rFlagsReg cr) %{ - - match(Set dst (LoadBarrierSlowReg mem)); - predicate(MaxVectorSize < 16); - - effect(DEF dst, KILL cr); - - format %{"LoadBarrierSlowRegNoVec $dst, $mem" %} - ins_encode %{ -#if INCLUDE_ZGC - Register d = $dst$$Register; - ZBarrierSetAssembler* bs = (ZBarrierSetAssembler*)BarrierSet::barrier_set()->barrier_set_assembler(); - - assert(d != r12, "Can't be R12!"); - assert(d != r15, "Can't be R15!"); - assert(d != rsp, "Can't be RSP!"); - - __ lea(d, $mem$$Address); - __ call(RuntimeAddress(bs->load_barrier_slow_stub(d))); -#else - ShouldNotReachHere(); -#endif - %} - ins_pipe(pipe_slow); -%} - // For XMM and YMM enabled processors instruct loadBarrierSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, rxmm0 x0, rxmm1 x1, rxmm2 x2,rxmm3 x3, @@ -12686,7 +12723,7 @@ instruct loadBarrierSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, rxmm12 x12, rxmm13 x13, rxmm14 x14, rxmm15 x15) %{ match(Set dst (LoadBarrierSlowReg mem)); - predicate((UseSSE > 0) && (UseAVX <= 2) && (MaxVectorSize >= 16)); + predicate(UseAVX <= 2); effect(DEF dst, KILL cr, KILL x0, KILL x1, KILL x2, KILL x3, @@ -12694,7 +12731,7 @@ instruct loadBarrierSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, KILL x8, KILL x9, KILL x10, KILL x11, KILL x12, KILL x13, KILL x14, KILL x15); - format %{"LoadBarrierSlowRegXmm $dst, $mem" %} + format %{"LoadBarrierSlowRegXmmAndYmm $dst, $mem" %} ins_encode %{ #if INCLUDE_ZGC Register d = $dst$$Register; @@ -12725,7 +12762,7 @@ instruct loadBarrierSlowRegZmm(rRegP dst, memory mem, rFlagsReg cr, rxmm28 x28, rxmm29 x29, rxmm30 x30, rxmm31 x31) %{ match(Set dst (LoadBarrierSlowReg mem)); - predicate((UseAVX == 3) && (MaxVectorSize >= 16)); + predicate(UseAVX == 3); effect(DEF dst, KILL cr, KILL x0, KILL x1, KILL x2, KILL x3, @@ -12760,33 +12797,6 @@ instruct loadBarrierSlowRegZmm(rRegP dst, memory mem, rFlagsReg cr, // Execute ZGC load barrier (weak) slow path // -// When running without XMM regs -instruct loadBarrierWeakSlowRegNoVec(rRegP dst, memory mem, rFlagsReg cr) %{ - - match(Set dst (LoadBarrierSlowReg mem)); - predicate(MaxVectorSize < 16); - - effect(DEF dst, KILL cr); - - format %{"LoadBarrierSlowRegNoVec $dst, $mem" %} - ins_encode %{ -#if INCLUDE_ZGC - Register d = $dst$$Register; - ZBarrierSetAssembler* bs = (ZBarrierSetAssembler*)BarrierSet::barrier_set()->barrier_set_assembler(); - - assert(d != r12, "Can't be R12!"); - assert(d != r15, "Can't be R15!"); - assert(d != rsp, "Can't be RSP!"); - - __ lea(d, $mem$$Address); - __ call(RuntimeAddress(bs->load_barrier_weak_slow_stub(d))); -#else - ShouldNotReachHere(); -#endif - %} - ins_pipe(pipe_slow); -%} - // For XMM and YMM enabled processors instruct loadBarrierWeakSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, rxmm0 x0, rxmm1 x1, rxmm2 x2,rxmm3 x3, @@ -12795,7 +12805,7 @@ instruct loadBarrierWeakSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, rxmm12 x12, rxmm13 x13, rxmm14 x14, rxmm15 x15) %{ match(Set dst (LoadBarrierWeakSlowReg mem)); - predicate((UseSSE > 0) && (UseAVX <= 2) && (MaxVectorSize >= 16)); + predicate(UseAVX <= 2); effect(DEF dst, KILL cr, KILL x0, KILL x1, KILL x2, KILL x3, @@ -12803,7 +12813,7 @@ instruct loadBarrierWeakSlowRegXmmAndYmm(rRegP dst, memory mem, rFlagsReg cr, KILL x8, KILL x9, KILL x10, KILL x11, KILL x12, KILL x13, KILL x14, KILL x15); - format %{"LoadBarrierWeakSlowRegXmm $dst, $mem" %} + format %{"LoadBarrierWeakSlowRegXmmAndYmm $dst, $mem" %} ins_encode %{ #if INCLUDE_ZGC Register d = $dst$$Register; @@ -12834,7 +12844,7 @@ instruct loadBarrierWeakSlowRegZmm(rRegP dst, memory mem, rFlagsReg cr, rxmm28 x28, rxmm29 x29, rxmm30 x30, rxmm31 x31) %{ match(Set dst (LoadBarrierWeakSlowReg mem)); - predicate((UseAVX == 3) && (MaxVectorSize >= 16)); + predicate(UseAVX == 3); effect(DEF dst, KILL cr, KILL x0, KILL x1, KILL x2, KILL x3, diff --git a/src/hotspot/os_cpu/linux_x86/gc/z/zArguments_linux_x86.cpp b/src/hotspot/os_cpu/linux_x86/gc/z/zArguments_linux_x86.cpp new file mode 100644 index 00000000000..bd0415e63eb --- /dev/null +++ b/src/hotspot/os_cpu/linux_x86/gc/z/zArguments_linux_x86.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "precompiled.hpp" +#include "gc/z/zArguments.hpp" +#include "runtime/globals.hpp" +#include "runtime/globals_extension.hpp" +#include "utilities/debug.hpp" + +void ZArguments::initialize_platform() { + // The C2 barrier slow path expects vector registers to be least + // 16 bytes wide, which is the minimum width available on all + // x86-64 systems. However, the user could have speficied a lower + // number on the command-line, in which case we print a warning + // and raise it to 16. + if (MaxVectorSize < 16) { + warning("ZGC requires MaxVectorSize to be at least 16"); + FLAG_SET_DEFAULT(MaxVectorSize, 16); + } +} diff --git a/src/hotspot/share/gc/z/zArguments.cpp b/src/hotspot/share/gc/z/zArguments.cpp index 6df13def6b8..6906ba026ea 100644 --- a/src/hotspot/share/gc/z/zArguments.cpp +++ b/src/hotspot/share/gc/z/zArguments.cpp @@ -19,7 +19,6 @@ * Please 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 "precompiled.hpp" @@ -91,6 +90,9 @@ void ZArguments::initialize() { // Verification of stacks not (yet) supported, for the same reason // we need fixup_partial_loads DEBUG_ONLY(FLAG_SET_DEFAULT(VerifyStack, false)); + + // Initialize platform specific arguments + initialize_platform(); } CollectedHeap* ZArguments::create_heap() { diff --git a/src/hotspot/share/gc/z/zArguments.hpp b/src/hotspot/share/gc/z/zArguments.hpp index f85b1471a2b..5edb369c9dc 100644 --- a/src/hotspot/share/gc/z/zArguments.hpp +++ b/src/hotspot/share/gc/z/zArguments.hpp @@ -29,6 +29,9 @@ class CollectedHeap; class ZArguments : public GCArguments { +private: + void initialize_platform(); + public: virtual void initialize(); virtual size_t conservative_max_heap_alignment(); From 9f1d035d8d862fc0e827c1df7e34f4b4c062c6a1 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Thu, 20 Dec 2018 05:27:42 -0800 Subject: [PATCH 110/174] 8215635: Pandoc check in Docs.gmk does not work on Windows Reviewed-by: tbell, ihse --- make/Docs.gmk | 2 +- make/autoconf/basics.m4 | 7 +++++++ make/autoconf/spec.gmk.in | 1 + make/launcher/LauncherCommon.gmk | 2 +- 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/make/Docs.gmk b/make/Docs.gmk index 4ef887fda75..a9fb7e2f2bf 100644 --- a/make/Docs.gmk +++ b/make/Docs.gmk @@ -517,7 +517,7 @@ $(foreach m, $(ALL_MODULES), \ ) \ ) -ifneq ($(PANDOC), ) +ifeq ($(ENABLE_PANDOC), true) # For all markdown files in $module/share/specs directories, convert them to # html, if we have pandoc (otherwise we'll just skip this). diff --git a/make/autoconf/basics.m4 b/make/autoconf/basics.m4 index 02925e9139c..e4fa23acadd 100644 --- a/make/autoconf/basics.m4 +++ b/make/autoconf/basics.m4 @@ -610,7 +610,14 @@ AC_DEFUN_ONCE([BASIC_SETUP_FUNDAMENTAL_TOOLS], BASIC_PATH_PROGS(DF, df) BASIC_PATH_PROGS(CPIO, [cpio bsdcpio]) BASIC_PATH_PROGS(NICE, nice) + BASIC_PATH_PROGS(PANDOC, pandoc) + if test -n "$PANDOC"; then + ENABLE_PANDOC="true" + else + ENABLE_PANDOC="false" + fi + AC_SUBST(ENABLE_PANDOC) ]) ############################################################################### diff --git a/make/autoconf/spec.gmk.in b/make/autoconf/spec.gmk.in index f2b2e56bc71..445c7a49c35 100644 --- a/make/autoconf/spec.gmk.in +++ b/make/autoconf/spec.gmk.in @@ -761,6 +761,7 @@ MSVCR_DLL:=@MSVCR_DLL@ MSVCP_DLL:=@MSVCP_DLL@ UCRT_DLL_DIR:=@UCRT_DLL_DIR@ STLPORT_LIB:=@STLPORT_LIB@ +ENABLE_PANDOC:=@ENABLE_PANDOC@ #################################################### # diff --git a/make/launcher/LauncherCommon.gmk b/make/launcher/LauncherCommon.gmk index 0c77eda7b78..520f6feaa0e 100644 --- a/make/launcher/LauncherCommon.gmk +++ b/make/launcher/LauncherCommon.gmk @@ -203,7 +203,7 @@ ifeq ($(OPENJDK_TARGET_OS_TYPE), unix) ifneq ($(MAN_FILES_MD), ) # If we got markdown files, ignore the troff files - ifeq ($(PANDOC), ) + ifeq ($(ENABLE_PANDOC), false) $(info Warning: pandoc not found. Not generating man pages) else # Create dynamic man pages from markdown using pandoc. We need From 5cdb1c70780c2e7134ef8364909f2d27349d796c Mon Sep 17 00:00:00 2001 From: Lutz Schmidt Date: Thu, 20 Dec 2018 17:29:59 +0100 Subject: [PATCH 111/174] 8215551: Missing case label in nmethod::reloc_string_for() Reviewed-by: kvn, mbaesken --- src/hotspot/share/code/nmethod.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/hotspot/share/code/nmethod.cpp b/src/hotspot/share/code/nmethod.cpp index 02c9247bf2a..3c422fcc08b 100644 --- a/src/hotspot/share/code/nmethod.cpp +++ b/src/hotspot/share/code/nmethod.cpp @@ -2540,6 +2540,7 @@ const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { case relocInfo::section_word_type: return "section_word"; case relocInfo::poll_type: return "poll"; case relocInfo::poll_return_type: return "poll_return"; + case relocInfo::trampoline_stub_type: return "trampoline_stub"; case relocInfo::type_mask: return "type_bit_mask"; default: From d62b658ffcca3fe3ae1baf45552e90807aba853b Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Thu, 20 Dec 2018 17:07:07 +0000 Subject: [PATCH 112/174] 8215100: AArch64: fix compareTo intrinsic with four-character Latin/Unicode Reviewed-by: aph, dpochepk --- src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp | 8 +++----- .../compiler/intrinsics/string/TestStringIntrinsics2.java | 8 +++++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 96106a9f997..43a9ca82560 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -4896,7 +4896,7 @@ void MacroAssembler::string_compare(Register str1, Register str2, // A very short string cmpw(cnt2, minCharsInWord); - br(Assembler::LT, SHORT_STRING); + br(Assembler::LE, SHORT_STRING); // Compare longwords // load first parts of strings and finish initialization while loading @@ -4920,8 +4920,7 @@ void MacroAssembler::string_compare(Register str1, Register str2, ldr(tmp2, Address(str2)); cmp(cnt2, STUB_THRESHOLD); br(GE, STUB); - subsw(cnt2, cnt2, 4); - br(EQ, TAIL_CHECK); + subw(cnt2, cnt2, 4); eor(vtmpZ, T16B, vtmpZ, vtmpZ); lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift))); lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift))); @@ -4937,8 +4936,7 @@ void MacroAssembler::string_compare(Register str1, Register str2, ldrs(vtmp, Address(str2)); cmp(cnt2, STUB_THRESHOLD); br(GE, STUB); - subsw(cnt2, cnt2, 4); - br(EQ, TAIL_CHECK); + subw(cnt2, cnt2, 4); lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift))); eor(vtmpZ, T16B, vtmpZ, vtmpZ); lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift))); diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestStringIntrinsics2.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestStringIntrinsics2.java index 5c4f334afb4..523653b8d0e 100644 --- a/test/hotspot/jtreg/compiler/intrinsics/string/TestStringIntrinsics2.java +++ b/test/hotspot/jtreg/compiler/intrinsics/string/TestStringIntrinsics2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2016 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -642,6 +642,12 @@ public class TestStringIntrinsics2 { assertEquals(-3, asmStringCompareTo(a2, b2), "TestOther.asmStringCompareTo(very_very_long_strings_2)"); } + + // See bug 8215100 + { + assertEquals(-20, asmStringCompareTo("e.\u0259.", "y.e.")); + assertEquals(20, asmStringCompareTo("y.e.", "e.\u0259.")); + } } From 1a1369d270345a737882ff7071a785a0e4b429c4 Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Thu, 20 Dec 2018 19:44:33 +0100 Subject: [PATCH 113/174] 8215548: G1PeriodicGCSystemLoadThreshold needs to be a double Change G1PeriodicGCSystemLoadThreshold to be a double to allow better granularity in determining idleness Reviewed-by: sjohanss, sangheki --- .../share/gc/g1/g1YoungRemSetSamplingThread.cpp | 4 ++-- src/hotspot/share/gc/g1/g1_globals.hpp | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp b/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp index f993ca3ac43..7283dbdc096 100644 --- a/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp +++ b/src/hotspot/share/gc/g1/g1YoungRemSetSamplingThread.cpp @@ -71,9 +71,9 @@ bool G1YoungRemSetSamplingThread::should_start_periodic_gc() { // Check if load is lower than max. double recent_load; - if ((G1PeriodicGCSystemLoadThreshold > 0) && + if ((G1PeriodicGCSystemLoadThreshold > 0.0f) && (os::loadavg(&recent_load, 1) == -1 || recent_load > G1PeriodicGCSystemLoadThreshold)) { - log_debug(gc, periodic)("Load %1.2f is higher than threshold " UINTX_FORMAT ". Skipping.", + log_debug(gc, periodic)("Load %1.2f is higher than threshold %1.2f. Skipping.", recent_load, G1PeriodicGCSystemLoadThreshold); return false; } diff --git a/src/hotspot/share/gc/g1/g1_globals.hpp b/src/hotspot/share/gc/g1/g1_globals.hpp index 83f259da7cc..a4ec8770849 100644 --- a/src/hotspot/share/gc/g1/g1_globals.hpp +++ b/src/hotspot/share/gc/g1/g1_globals.hpp @@ -311,10 +311,11 @@ "perform a concurrent GC as periodic GC, otherwise use a STW " \ "Full GC.") \ \ - manageable(uintx, G1PeriodicGCSystemLoadThreshold, 0, \ - "Maximum recent system wide system load as returned by the 1m " \ - "value of getloadavg() at which G1 triggers a periodic GC. A " \ - "load above this value cancels a given periodic GC. A value of " \ - "zero disables this check.") \ + manageable(double, G1PeriodicGCSystemLoadThreshold, 0.0, \ + "Maximum recent system wide load as returned by the 1m value " \ + "of getloadavg() at which G1 triggers a periodic GC. A load " \ + "above this value cancels a given periodic GC. A value of zero " \ + "disables this check.") \ + range(0.0, (double)max_uintx) \ #endif // SHARE_VM_GC_G1_G1_GLOBALS_HPP From cad5fa8f16a0df2494d36ffe3006d200a20834e1 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Thu, 20 Dec 2018 19:44:08 +0100 Subject: [PATCH 114/174] 8215555: TieredCompilation C2 threads can excessively block handshakes Reviewed-by: kvn, neliasso, rehn --- src/hotspot/share/runtime/sweeper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hotspot/share/runtime/sweeper.cpp b/src/hotspot/share/runtime/sweeper.cpp index c5e5a7fdfc1..59edaad8d97 100644 --- a/src/hotspot/share/runtime/sweeper.cpp +++ b/src/hotspot/share/runtime/sweeper.cpp @@ -149,7 +149,7 @@ long NMethodSweeper::_time_counter = 0; // Virtual time u long NMethodSweeper::_last_sweep = 0; // Value of _time_counter when the last sweep happened int NMethodSweeper::_seen = 0; // Nof. nmethod we have currently processed in current pass of CodeCache -volatile bool NMethodSweeper::_should_sweep = true; // Indicates if we should invoke the sweeper +volatile bool NMethodSweeper::_should_sweep = false;// Indicates if we should invoke the sweeper volatile bool NMethodSweeper::_force_sweep = false;// Indicates if we should force a sweep volatile int NMethodSweeper::_bytes_changed = 0; // Counts the total nmethod size if the nmethod changed from: // 1) alive -> not_entrant From f7e8dcc0bbb95dda10ce69cbe68f156319f71174 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 20 Dec 2018 14:03:56 -0800 Subject: [PATCH 115/174] 8215687: [Graal] unit test CheckGraalIntrinsics failed after 8212043 Add check for new intrinsics Reviewed-by: iveresov, iignatyev --- .../compiler/hotspot/test/CheckGraalIntrinsics.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java index 52feb6be87f..fc67b021c03 100644 --- a/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java +++ b/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.test/src/org/graalvm/compiler/hotspot/test/CheckGraalIntrinsics.java @@ -382,6 +382,14 @@ public class CheckGraalIntrinsics extends GraalTest { "java/lang/CharacterDataLatin1.isWhitespace(I)Z"); } + if (isJDK13OrHigher()) { + add(toBeInvestigated, + "java/lang/Math.max(DD)D", + "java/lang/Math.max(FF)F", + "java/lang/Math.min(DD)D", + "java/lang/Math.min(FF)F"); + } + if (!config.inlineNotify()) { add(ignore, "java/lang/Object.notify()V"); } @@ -542,6 +550,10 @@ public class CheckGraalIntrinsics extends GraalTest { return GraalServices.JAVA_SPECIFICATION_VERSION >= 12; } + private static boolean isJDK13OrHigher() { + return GraalServices.JAVA_SPECIFICATION_VERSION >= 13; + } + public interface Refiner { void refine(CheckGraalIntrinsics checker); } From ae369f40a4737496b9f5a9afb2eddcf3cd924a25 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Thu, 20 Dec 2018 17:51:16 -0800 Subject: [PATCH 116/174] 8215716: PopFrame() was unexpectedly done Reviewed-by: dholmes, sspitsyn --- .../jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java index f45b7a3d5b4..5f487b8605b 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/PopFrame/popframe004.java @@ -147,8 +147,8 @@ public class popframe004 { boolean compl = true; try { - pipeOut.write(123); // notify the main thread out.println("popFrameCls (" + this + "): inside activeMethod()"); + pipeOut.write(123); // notify the main thread // pause here until the main thread suspends us synchronized (popframe004.barrier) { while (true) { From e049d143b0e8ea5ddc9a0233dee15a2c536c85cb Mon Sep 17 00:00:00 2001 From: Pankaj Bansal Date: Fri, 21 Dec 2018 11:43:04 +0530 Subject: [PATCH 117/174] 8215364: JavaFX crashes on Ubuntu 18.04 with Wayland while using Swing-FX interop Reviewed-by: prr, kcr --- src/java.desktop/unix/native/libawt_xawt/xawt/XToolkit.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/java.desktop/unix/native/libawt_xawt/xawt/XToolkit.c b/src/java.desktop/unix/native/libawt_xawt/xawt/XToolkit.c index 5814bb6c8a4..d5f1d012355 100644 --- a/src/java.desktop/unix/native/libawt_xawt/xawt/XToolkit.c +++ b/src/java.desktop/unix/native/libawt_xawt/xawt/XToolkit.c @@ -150,6 +150,10 @@ JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved) { jvm = vm; + + //Set the gtk backend to x11 on all the systems + putenv("GDK_BACKEND=x11"); + return JNI_VERSION_1_2; } From cb553175b7c8248ab89738a7694ea72026027198 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= Date: Fri, 21 Dec 2018 11:02:36 +0100 Subject: [PATCH 118/174] 8215291: Broken links when generating from project without modules Reviewed-by: jjg --- .../javadoc/internal/doclets/formats/html/resources/search.js | 2 +- test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js index 3c535783794..620ba97d003 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js @@ -55,7 +55,7 @@ function getURLPrefix(ui) { return ui.item.m + slash; } else if ((ui.item.category === catTypes && ui.item.p) || ui.item.category === catMembers) { $.each(packageSearchIndex, function(index, item) { - if (ui.item.p == item.l) { + if (item.m && ui.item.p == item.l) { urlPrefix = item.m + slash; } }); diff --git a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java index 1b6b12d0e99..0df1fc27e80 100644 --- a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java +++ b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java @@ -686,7 +686,7 @@ public class TestSearch extends JavadocTester { + " return ui.item.m + slash;\n" + " } else if ((ui.item.category === catTypes && ui.item.p) || ui.item.category === catMembers) {\n" + " $.each(packageSearchIndex, function(index, item) {\n" - + " if (ui.item.p == item.l) {\n" + + " if (item.m && ui.item.p == item.l) {\n" + " urlPrefix = item.m + slash;\n" + " }\n" + " });\n" From 203f6ad99ab580297c039d5d8c903a25a0991948 Mon Sep 17 00:00:00 2001 From: Gary Adams Date: Fri, 21 Dec 2018 07:42:12 -0500 Subject: [PATCH 119/174] 8215571: jdb does not include jdk.* in the default class filter Reviewed-by: alanb, cjplummer --- .../share/classes/com/sun/tools/example/debug/tty/Env.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jdk.jdi/share/classes/com/sun/tools/example/debug/tty/Env.java b/src/jdk.jdi/share/classes/com/sun/tools/example/debug/tty/Env.java index b67295e840e..1af357322a9 100644 --- a/src/jdk.jdi/share/classes/com/sun/tools/example/debug/tty/Env.java +++ b/src/jdk.jdi/share/classes/com/sun/tools/example/debug/tty/Env.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -108,7 +108,7 @@ class Env { static private List excludes() { if (excludes == null) { - setExcludes("java.*, javax.*, sun.*, com.sun.*"); + setExcludes("java.*, javax.*, sun.*, com.sun.*, jdk.*"); } return excludes; } From 1dae61a3743b68a4fef2325a5068469cd9099caa Mon Sep 17 00:00:00 2001 From: Philipp Kunz Date: Fri, 21 Dec 2018 09:54:32 -0500 Subject: [PATCH 120/174] 8066619: Fix deprecation warnings in java.util.jar Reviewed-by: rriggs, lancea --- .../classes/java/util/jar/Attributes.java | 71 +++--- .../share/classes/java/util/jar/Manifest.java | 60 +++-- .../Attributes/NullAndEmptyKeysAndValues.java | 201 +++++++++++++++++ .../util/jar/Manifest/ValueUtf8Coding.java | 212 ++++++++++++++++++ .../jar/Manifest/WriteBinaryStructure.java | 73 ++++++ 5 files changed, 560 insertions(+), 57 deletions(-) create mode 100644 test/jdk/java/util/jar/Attributes/NullAndEmptyKeysAndValues.java create mode 100644 test/jdk/java/util/jar/Manifest/ValueUtf8Coding.java create mode 100644 test/jdk/java/util/jar/Manifest/WriteBinaryStructure.java diff --git a/src/java.base/share/classes/java/util/jar/Attributes.java b/src/java.base/share/classes/java/util/jar/Attributes.java index 61b7c1613e9..345046d6961 100644 --- a/src/java.base/share/classes/java/util/jar/Attributes.java +++ b/src/java.base/share/classes/java/util/jar/Attributes.java @@ -36,6 +36,8 @@ import java.util.Set; import sun.util.logging.PlatformLogger; +import static java.nio.charset.StandardCharsets.UTF_8; + /** * The Attributes class maps Manifest attribute names to associated string * values. Valid attribute names are case-insensitive, are restricted to @@ -298,25 +300,16 @@ public class Attributes implements Map, Cloneable { * Writes the current attributes to the specified data output stream. * XXX Need to handle UTF8 values and break up lines longer than 72 bytes */ - @SuppressWarnings("deprecation") - void write(DataOutputStream os) throws IOException { - for (Entry e : entrySet()) { - StringBuffer buffer = new StringBuffer( - ((Name) e.getKey()).toString()); - buffer.append(": "); - - String value = (String) e.getValue(); - if (value != null) { - byte[] vb = value.getBytes("UTF8"); - value = new String(vb, 0, 0, vb.length); - } - buffer.append(value); - - Manifest.make72Safe(buffer); - buffer.append("\r\n"); - os.writeBytes(buffer.toString()); - } - os.writeBytes("\r\n"); + void write(DataOutputStream out) throws IOException { + StringBuilder buffer = new StringBuilder(72); + for (Entry e : entrySet()) { + buffer.setLength(0); + buffer.append(e.getKey().toString()); + buffer.append(": "); + buffer.append(e.getValue()); + Manifest.println72(out, buffer.toString()); + } + Manifest.println(out); // empty line after individual section } /* @@ -326,9 +319,9 @@ public class Attributes implements Map, Cloneable { * * XXX Need to handle UTF8 values and break up lines longer than 72 bytes */ - @SuppressWarnings("deprecation") - void writeMain(DataOutputStream out) throws IOException - { + void writeMain(DataOutputStream out) throws IOException { + StringBuilder buffer = new StringBuilder(72); + // write out the *-Version header first, if it exists String vername = Name.MANIFEST_VERSION.toString(); String version = getValue(vername); @@ -338,7 +331,11 @@ public class Attributes implements Map, Cloneable { } if (version != null) { - out.writeBytes(vername+": "+version+"\r\n"); + buffer.append(vername); + buffer.append(": "); + buffer.append(version); + out.write(buffer.toString().getBytes(UTF_8)); + Manifest.println(out); } // write out all attributes except for the version @@ -346,34 +343,24 @@ public class Attributes implements Map, Cloneable { for (Entry e : entrySet()) { String name = ((Name) e.getKey()).toString(); if ((version != null) && !(name.equalsIgnoreCase(vername))) { - - StringBuffer buffer = new StringBuffer(name); + buffer.setLength(0); + buffer.append(name); buffer.append(": "); - - String value = (String) e.getValue(); - if (value != null) { - byte[] vb = value.getBytes("UTF8"); - value = new String(vb, 0, 0, vb.length); - } - buffer.append(value); - - Manifest.make72Safe(buffer); - buffer.append("\r\n"); - out.writeBytes(buffer.toString()); + buffer.append(e.getValue()); + Manifest.println72(out, buffer.toString()); } } - out.writeBytes("\r\n"); + + Manifest.println(out); // empty line after main attributes section } /* * Reads attributes from the specified input stream. - * XXX Need to handle UTF8 values. */ void read(Manifest.FastInputStream is, byte[] lbuf) throws IOException { read(is, lbuf, null, 0); } - @SuppressWarnings("deprecation") int read(Manifest.FastInputStream is, byte[] lbuf, String filename, int lineNumber) throws IOException { String name = null, value; byte[] lastline = null; @@ -409,7 +396,7 @@ public class Attributes implements Map, Cloneable { lastline = buf; continue; } - value = new String(buf, 0, buf.length, "UTF8"); + value = new String(buf, 0, buf.length, UTF_8); lastline = null; } else { while (lbuf[i++] != ':') { @@ -422,13 +409,13 @@ public class Attributes implements Map, Cloneable { throw new IOException("invalid header field (" + Manifest.getErrorPosition(filename, lineNumber) + ")"); } - name = new String(lbuf, 0, 0, i - 2); + name = new String(lbuf, 0, i - 2, UTF_8); if (is.peek() == ' ') { lastline = new byte[len - i]; System.arraycopy(lbuf, i, lastline, 0, len - i); continue; } - value = new String(lbuf, i, len - i, "UTF8"); + value = new String(lbuf, i, len - i, UTF_8); } try { if ((putValue(name, value) != null) && (!lineContinued)) { diff --git a/src/java.base/share/classes/java/util/jar/Manifest.java b/src/java.base/share/classes/java/util/jar/Manifest.java index 0362ad13165..251b5100885 100644 --- a/src/java.base/share/classes/java/util/jar/Manifest.java +++ b/src/java.base/share/classes/java/util/jar/Manifest.java @@ -35,6 +35,8 @@ import java.util.Map; import sun.security.util.SecurityProperties; +import static java.nio.charset.StandardCharsets.UTF_8; + /** * The Manifest class is used to maintain Manifest entry names and their * associated Attributes. There are main Manifest Attributes as well as @@ -197,31 +199,28 @@ public class Manifest implements Cloneable { * @exception IOException if an I/O error has occurred * @see #getMainAttributes */ - @SuppressWarnings("deprecation") public void write(OutputStream out) throws IOException { DataOutputStream dos = new DataOutputStream(out); // Write out the main attributes for the manifest attr.writeMain(dos); // Now write out the per-entry attributes + StringBuilder buffer = entries.isEmpty() ? null : new StringBuilder(72); for (Map.Entry e : entries.entrySet()) { - StringBuffer buffer = new StringBuffer("Name: "); - String value = e.getKey(); - if (value != null) { - byte[] vb = value.getBytes("UTF8"); - value = new String(vb, 0, 0, vb.length); - } - buffer.append(value); - make72Safe(buffer); - buffer.append("\r\n"); - dos.writeBytes(buffer.toString()); + buffer.setLength(0); + buffer.append("Name: "); + buffer.append(e.getKey()); + println72(dos, buffer.toString()); e.getValue().write(dos); } dos.flush(); } /** - * Adds line breaks to enforce a maximum 72 bytes per line. + * Adds line breaks to enforce a maximum of 72 bytes per line. + * + * @deprecation Replaced with {@link #println72}. */ + @Deprecated(since = "13") static void make72Safe(StringBuffer line) { int length = line.length(); int index = 72; @@ -230,7 +229,38 @@ public class Manifest implements Cloneable { index += 74; // + line width + line break ("\r\n") length += 3; // + line break ("\r\n") and space } - return; + } + + /** + * Writes {@code line} to {@code out} with line breaks and continuation + * spaces within the limits of 72 bytes of contents per line followed + * by a line break. + */ + static void println72(OutputStream out, String line) throws IOException { + if (!line.isEmpty()) { + byte[] lineBytes = line.getBytes(UTF_8); + int length = lineBytes.length; + // first line can hold one byte more than subsequent lines which + // start with a continuation line break space + out.write(lineBytes[0]); + int pos = 1; + while (length - pos > 71) { + out.write(lineBytes, pos, 71); + pos += 71; + println(out); + out.write(' '); + } + out.write(lineBytes, pos, length - pos); + } + println(out); + } + + /** + * Writes a line break to {@code out}. + */ + static void println(OutputStream out) throws IOException { + out.write('\r'); + out.write('\n'); } static String getErrorPosition(String filename, final int lineNumber) { @@ -304,7 +334,7 @@ public class Manifest implements Cloneable { lastline = buf; continue; } - name = new String(buf, 0, buf.length, "UTF8"); + name = new String(buf, 0, buf.length, UTF_8); lastline = null; } Attributes attr = getAttributes(name); @@ -330,7 +360,7 @@ public class Manifest implements Cloneable { toLower(lbuf[2]) == 'm' && toLower(lbuf[3]) == 'e' && lbuf[4] == ':' && lbuf[5] == ' ') { try { - return new String(lbuf, 6, len - 6, "UTF8"); + return new String(lbuf, 6, len - 6, UTF_8); } catch (Exception e) { } diff --git a/test/jdk/java/util/jar/Attributes/NullAndEmptyKeysAndValues.java b/test/jdk/java/util/jar/Attributes/NullAndEmptyKeysAndValues.java new file mode 100644 index 00000000000..396c0a27b6d --- /dev/null +++ b/test/jdk/java/util/jar/Attributes/NullAndEmptyKeysAndValues.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.jar.Attributes.Name; +import java.lang.reflect.Field; + +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +/** + * @test + * @bug 8066619 + * @modules java.base/java.util.jar:+open + * @run testng/othervm NullAndEmptyKeysAndValues + * @summary Tests manifests with {@code null} and empty string {@code ""} + * values as section name, header name, or value in both main and named + * attributes sections. + */ +/* + * Note to future maintainer: + * In order to actually being able to test all the cases where key and values + * are null normal manifest and attributes manipulation through their public + * api is not sufficient but then there were these null checks there before + * which may or may not have had their reason and this way it's ensured that + * the behavior does not change with that respect. + * Once module isolation is enforced some test cases will not any longer be + * possible and those now tested situations will be guaranteed not to occur + * any longer at all at which point the corresponding tests can be removed + * safely without replacement unless of course another way is found inject the + * tested null values. + * Another trick to access package private class members could be to use + * deserialization or adding a new class to the same package on the classpath. + * Here is not important how the values are set to null because it shows that + * the behavior remains unchanged. + */ +public class NullAndEmptyKeysAndValues { + + static final String SOME_KEY = "some-key"; + static final String SOME_VALUE = "some value"; + static final String NULL_TEXT = "null"; + static final String EMPTY_STR = ""; + static final Name EMPTY_NAME = new Name("tmp") {{ + try { + Field name = Name.class.getDeclaredField("name"); + name.setAccessible(true); + name.set(this, EMPTY_STR); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + }}; + + @Test + public void testMainAttributesHeaderNameNull() throws Exception { + Manifest mf = new Manifest(); + Field attr = mf.getClass().getDeclaredField("attr"); + attr.setAccessible(true); + Attributes mainAtts = new Attributes() {{ + super.put(null, SOME_VALUE); + }}; + attr.set(mf, mainAtts); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + assertThrows(NullPointerException.class, () -> writeAndRead(mf)); + } + + @Test + public void testMainAttributesHeaderNameEmpty() throws Exception { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getMainAttributes().put(EMPTY_NAME, SOME_VALUE); + assertThrows(IOException.class, () -> writeAndRead(mf)); + } + + @Test + public void testMainAttributesHeaderValueNull() throws Exception { + Manifest mf = new Manifest(); + Field attr = mf.getClass().getDeclaredField("attr"); + attr.setAccessible(true); + Attributes mainAtts = new Attributes() {{ + map.put(new Name(SOME_KEY), null); + }}; + attr.set(mf, mainAtts); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf = writeAndRead(mf); + assertEquals(mf.getMainAttributes().getValue(SOME_KEY), NULL_TEXT); + } + + @Test + public void testMainAttributesHeaderValueEmpty() throws Exception { + Manifest mf = new Manifest(); + Field attr = mf.getClass().getDeclaredField("attr"); + attr.setAccessible(true); + Attributes mainAtts = new Attributes() {{ + map.put(new Name(SOME_KEY), EMPTY_STR); + }}; + attr.set(mf, mainAtts); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf = writeAndRead(mf); + assertEquals(mf.getMainAttributes().getValue(SOME_KEY), EMPTY_STR); + } + + @Test + public void testSectionNameNull() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(null, new Attributes()); + mf = writeAndRead(mf); + assertNotNull(mf.getEntries().get(NULL_TEXT)); + } + + @Test + public void testSectionNameEmpty() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(EMPTY_STR, new Attributes()); + mf = writeAndRead(mf); + assertNotNull(mf.getEntries().get(EMPTY_STR)); + } + + @Test + public void testNamedSectionHeaderNameNull() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(SOME_KEY, new Attributes() {{ + map.put(null, SOME_VALUE); + }}); + assertThrows(NullPointerException.class, () -> writeAndRead(mf)); + } + + @Test + public void testNamedSectionHeaderNameEmpty() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(SOME_KEY, new Attributes() {{ + map.put(EMPTY_NAME, SOME_VALUE); + }}); + assertThrows(IOException.class, () -> writeAndRead(mf)); + } + + @Test + public void testNamedSectionHeaderValueNull() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(SOME_KEY, new Attributes() {{ + map.put(new Name(SOME_KEY), null); + }}); + mf = writeAndRead(mf); + assertEquals(mf.getEntries().get(SOME_KEY).getValue(SOME_KEY), + NULL_TEXT); + } + + @Test + public void testNamedSectionHeaderValueEmpty() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getEntries().put(SOME_KEY, new Attributes() {{ + map.put(new Name(SOME_KEY), EMPTY_STR); + }}); + mf = writeAndRead(mf); + assertEquals(mf.getEntries().get(SOME_KEY).getValue(SOME_KEY), + EMPTY_STR); + } + + static Manifest writeAndRead(Manifest mf) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + mf.write(out); + byte[] mfBytes = out.toByteArray(); + System.out.println("-".repeat(72)); + System.out.print(new String(mfBytes, UTF_8)); + System.out.println("-".repeat(72)); + ByteArrayInputStream in = new ByteArrayInputStream(mfBytes); + return new Manifest(in); + } + +} diff --git a/test/jdk/java/util/jar/Manifest/ValueUtf8Coding.java b/test/jdk/java/util/jar/Manifest/ValueUtf8Coding.java new file mode 100644 index 00000000000..533007dcf7a --- /dev/null +++ b/test/jdk/java/util/jar/Manifest/ValueUtf8Coding.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.Attributes.Name; +import java.util.jar.Manifest; +import java.util.List; +import java.util.ArrayList; + +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +/** + * @test + * @bug 8066619 + * @run testng ValueUtf8Coding + * @summary Tests encoding and decoding manifest header values to and from + * UTF-8 with the complete Unicode character set. + */ /* + * see also "../tools/launcher/UnicodeTest.java" for manifest attributes + * parsed during launch + */ +public class ValueUtf8Coding { + + /** + * Maximum number of bytes of UTF-8 encoded characters in one header value. + *

      + * There are too many different Unicode code points (more than one million) + * to fit all into one manifest value. The specifications state: + * Implementations should support 65535-byte (not character) header + * values, and 65535 headers per file. They might run out of memory, + * but there should not be hard-coded limits below these values. + * + * @see + * Notes on Manifest and Signature Files + */ + static final int SUPPORTED_VALUE_LENGTH = 65535; + + /** + * Returns {@code true} if {@code codePoint} is known not to be a supported + * character in manifest header values. Explicitly forbidden in manifest + * header values are according to a statement from the specifications: + * otherchar: any UTF-8 character except NUL, CR and LF. + * {@code NUL} ({@code 0x0}), however, works just fine and might have been + * used and might still be. + * + * @see + * Jar File Specification + */ + static boolean isUnsupportedManifestValueCharacter(int codePoint) { + return codePoint == '\r' /* CR */ || codePoint == '\n' /* LF */; + }; + + /** + * Produces a list of strings with all Unicode characters except those + * explicitly invalid in manifest header values. + * Each string is filled with as many characters as fit into + * {@link #SUPPORTED_VALUE_LENGTH} bytes with UTF-8 encoding except the + * last string which contains the remaining characters. Each of those + * strings becomes a header value the number of which 65535 should be + * supported per file. + * + * @see + * Notes on Manifest and Signature Files + */ + static List produceValuesWithAllUnicodeCharacters() { + ArrayList values = new ArrayList<>(); + byte[] valueBuf = new byte[SUPPORTED_VALUE_LENGTH]; + int pos = 0; + for (int codePoint = Character.MIN_CODE_POINT; + codePoint <= Character.MAX_CODE_POINT; codePoint++) { + if (isUnsupportedManifestValueCharacter(codePoint)) { + continue; + } + + byte[] charBuf = Character.toString(codePoint).getBytes(UTF_8); + if (pos + charBuf.length > valueBuf.length) { + values.add(new String(valueBuf, 0, pos, UTF_8)); + pos = 0; + } + System.arraycopy(charBuf, 0, valueBuf, pos, charBuf.length); + pos += charBuf.length; + } + if (pos > 0) { + values.add(new String(valueBuf, 0, pos, UTF_8)); + } + // minimum number of headers supported is the same as the minimum size + // of each header value in bytes + assertTrue(values.size() <= SUPPORTED_VALUE_LENGTH); + return values; + } + + /** + * Returns simple, valid, short, and distinct manifest header names. + * The returned name cannot collide with "{@code Manifest-Version}" because + * the returned string does not contain "{@code -}". + */ + static Name azName(int seed) { + StringBuffer name = new StringBuffer(); + do { + name.insert(0, (char) (seed % 26 + (seed < 26 ? 'A' : 'a'))); + seed = seed / 26 - 1; + } while (seed >= 0); + return new Name(name.toString()); + } + + /** + * Writes and reads a manifest with the complete Unicode character set. + * The characters are grouped into manifest header values with about as + * many bytes as allowed each, utilizing a single big manifest. + *

      + * This test assumes that a manifest is encoded and decoded correctly if + * writing and then reading it again results in a manifest with identical + * values as the original. The test is not about other aspects of writing + * and reading manifests than only that, given the fact and the way it + * works for some characters such as the most widely and often used ones, + * it also works for the complete Unicode character set just the same. + *

      + * Only header values are tested. The set of allowed characters for header + * names are much more limited and are a different topic entirely and most + * simple ones are used here as necessary just to get valid and different + * ones (see {@link #azName}). + *

      + * Because the current implementation under test uses different portions + * of code depending on where the value occurs to read or write, each + * character is tested in each of the three positions:

        + *
      • main attribute header,
      • + *
      • named section name, and
      • + *
      • named sections header values
      • + *
      + * Implementation of writing the main section headers in + * {@link Attributes#writeMain(java.io.DataOutputStream)} differs from the + * one writing named section headers in + * {@link Attributes#write(java.io.DataOutputStream)} regarding the special + * order of {@link Name#MANIFEST_VERSION} and + * {@link Name#SIGNATURE_VERSION} and also + * {@link Manifest#read(java.io.InputStream)} at least potentially reads + * main sections differently than reading named sections names headers in + * {@link Attributes#read(Manifest.FastInputStream, byte[])}. + */ + @Test + public void testCompleteUnicodeCharacterSet() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + + List values = produceValuesWithAllUnicodeCharacters(); + for (int i = 0; i < values.size(); i++) { + Name name = azName(i); + String value = values.get(i); + + mf.getMainAttributes().put(name, value); + Attributes attributes = new Attributes(); + mf.getEntries().put(value, attributes); + attributes.put(name, value); + } + + mf = writeAndRead(mf); + + for (int i = 0; i < values.size(); i++) { + String value = values.get(i); + Name name = azName(i); + + assertEquals(mf.getMainAttributes().getValue(name), value, + "main attributes header value"); + Attributes attributes = mf.getAttributes(value); + assertNotNull(attributes, "named section"); + assertEquals(attributes.getValue(name), value, + "named section attributes value"); + } + } + + static Manifest writeAndRead(Manifest mf) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + mf.write(out); + byte[] mfBytes = out.toByteArray(); + + System.out.println("-".repeat(72)); + System.out.print(new String(mfBytes, UTF_8)); + System.out.println("-".repeat(72)); + + ByteArrayInputStream in = new ByteArrayInputStream(mfBytes); + return new Manifest(in); + } + +} diff --git a/test/jdk/java/util/jar/Manifest/WriteBinaryStructure.java b/test/jdk/java/util/jar/Manifest/WriteBinaryStructure.java new file mode 100644 index 00000000000..379de6b1adb --- /dev/null +++ b/test/jdk/java/util/jar/Manifest/WriteBinaryStructure.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.Attributes.Name; +import java.util.jar.Manifest; + +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +/** + * @test + * @bug 8066619 + * @run testng WriteBinaryStructure + * @summary Tests that jar manifests are written in a particular structure + */ +public class WriteBinaryStructure { + + @Test + public void testMainAttributes() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + mf.getMainAttributes().put(new Name("Key"), "Value"); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + mf.write(buf); + assertEquals(buf.toByteArray(), ( + "Manifest-Version: 1.0\r\n" + + "Key: Value\r\n" + + "\r\n").getBytes(UTF_8)); + } + + @Test + public void testIndividualSection() throws IOException { + Manifest mf = new Manifest(); + mf.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + Attributes attributes = new Attributes(); + mf.getEntries().put("Individual-Section-Name", attributes); + attributes.put(new Name("Key"), "Value"); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + mf.write(buf); + assertEquals(buf.toByteArray(), ( + "Manifest-Version: 1.0\r\n" + + "\r\n" + + "Name: Individual-Section-Name\r\n" + + "Key: Value\r\n" + + "\r\n").getBytes(UTF_8)); + } + +} From 9cbca323f77e3adba96490f2e1effc5b57f0492f Mon Sep 17 00:00:00 2001 From: Milan Mimica Date: Fri, 21 Dec 2018 16:56:40 +0100 Subject: [PATCH 121/174] 8215727: Restore JFR thread sampler loop to old / previous behavior Reviewed-by: egahlin, mgronlun --- .../jfr/periodic/sampling/jfrThreadSampler.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/jfr/periodic/sampling/jfrThreadSampler.cpp b/src/hotspot/share/jfr/periodic/sampling/jfrThreadSampler.cpp index 581e896bf13..ef05554be1b 100644 --- a/src/hotspot/share/jfr/periodic/sampling/jfrThreadSampler.cpp +++ b/src/hotspot/share/jfr/periodic/sampling/jfrThreadSampler.cpp @@ -287,13 +287,13 @@ static const uint MAX_NR_OF_NATIVE_SAMPLES = 1; void JfrThreadSampleClosure::commit_events(JfrSampleType type) { if (JAVA_SAMPLE == type) { - assert(_added_java <= MAX_NR_OF_JAVA_SAMPLES, "invariant"); + assert(_added_java > 0 && _added_java <= MAX_NR_OF_JAVA_SAMPLES, "invariant"); for (uint i = 0; i < _added_java; ++i) { _events[i].commit(); } } else { assert(NATIVE_SAMPLE == type, "invariant"); - assert(_added_native <= MAX_NR_OF_NATIVE_SAMPLES, "invariant"); + assert(_added_native > 0 && _added_native <= MAX_NR_OF_NATIVE_SAMPLES, "invariant"); for (uint i = 0; i < _added_native; ++i) { _events_native[i].commit(); } @@ -495,7 +495,7 @@ void JfrThreadSampler::task_stacktrace(JfrSampleType type, JavaThread** last_thr JfrThreadSampleClosure sample_task(samples, samples_native); const uint sample_limit = JAVA_SAMPLE == type ? MAX_NR_OF_JAVA_SAMPLES : MAX_NR_OF_NATIVE_SAMPLES; - uint num_sample_attempts = 0; + uint num_samples = 0; JavaThread* start = NULL; { @@ -509,7 +509,7 @@ void JfrThreadSampler::task_stacktrace(JfrSampleType type, JavaThread** last_thr _cur_index = tlh.list()->find_index_of_JavaThread(*last_thread); JavaThread* current = _cur_index != -1 ? *last_thread : NULL; - while (num_sample_attempts < sample_limit) { + while (num_samples < sample_limit) { current = next_thread(tlh.list(), start, current); if (current == NULL) { break; @@ -520,8 +520,9 @@ void JfrThreadSampler::task_stacktrace(JfrSampleType type, JavaThread** last_thr if (current->is_Compiler_thread()) { continue; } - sample_task.do_sample_thread(current, _frames, _max_frames, type); - num_sample_attempts++; + if (sample_task.do_sample_thread(current, _frames, _max_frames, type)) { + num_samples++; + } } *last_thread = current; // remember the thread we last attempted to sample } @@ -529,7 +530,7 @@ void JfrThreadSampler::task_stacktrace(JfrSampleType type, JavaThread** last_thr log_trace(jfr)("JFR thread sampling done in %3.7f secs with %d java %d native samples", sample_time.seconds(), sample_task.java_entries(), sample_task.native_entries()); } - if (num_sample_attempts > 0) { + if (num_samples > 0) { sample_task.commit_events(type); } } From 2162a500c1454533aa408421ad9e62d7e09d5d5e Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Fri, 21 Dec 2018 10:38:33 -0800 Subject: [PATCH 122/174] 8215516: Move JavadocTester to a named package Reviewed-by: hannesw --- .../jdk/javadoc/doclet/5093723/T5093723.java | 10 +- .../doclet/AccessAsciiArt/AccessAsciiArt.java | 8 +- .../AccessFrameTitle/AccessFrameTitle.java | 8 +- .../jdk/javadoc/doclet/AccessH1/AccessH1.java | 8 +- .../doclet/AccessSkipNav/AccessSkipNav.java | 10 +- .../doclet/AccessSummary/AccessSummary.java | 10 +- .../jdk/javadoc/doclet/AuthorDD/AuthorDD.java | 10 +- .../doclet/DocRootSlash/DocRootSlash.java | 8 +- .../doclet/InheritDocForUserTags/DocTest.java | 10 +- .../JavascriptWinTitle.java | 8 +- .../jdk/javadoc/doclet/MetaTag/MetaTag.java | 14 +- .../doclet/PackagesHeader/PackagesHeader.java | 12 +- .../jdk/javadoc/doclet/T6735320/T6735320.java | 10 +- .../javadoc/doclet/ValidHtml/ValidHtml.java | 10 +- .../doclet/VersionNumber/VersionNumber.java | 10 +- .../doclet/WindowTitles/WindowTitles.java | 10 +- .../javadoc/doclet/_template/Template.java | 4 +- .../doclet/_template/TemplateComplete.java | 4 +- .../TestConstantValuesDriver.java | 10 +- .../dupThrowsTags/TestDupThrowsTags.java | 10 +- .../testAbsLinkPath/TestAbsLinkPath.java | 10 +- .../TestAbstractMethod.java | 8 +- .../testAnchorNames/TestAnchorNames.java | 13 +- .../TestAnnotationOptional.java | 10 +- .../TestAnnotationTypes.java | 12 +- .../javadoc/doclet/testAuthor/TestAuthor.java | 9 +- .../TestBackSlashInLink.java | 10 +- .../doclet/testBadHtml/TestBadHtml.java | 10 +- .../TestBadPackageFileInJar.java | 10 +- .../testBadSourceFile/TestBadSourceFile.java | 10 +- .../doclet/testBaseClass/TestBaseClass.java | 10 +- .../testBreakIterator/TestBreakIterator.java | 10 +- .../TestCRLineSeparator.java | 10 +- .../doclet/testCharset/TestCharset.java | 12 +- .../TestCharsetDocencodingOptions.java | 20 +- .../TestClassCrossReferences.java | 12 +- .../TestClassDocCatalog.java | 8 +- .../doclet/testClassLinks/TestClassLinks.java | 10 +- .../doclet/testClassTree/TestClassTree.java | 8 +- .../testCmndLineClass/TestCmndLineClass.java | 10 +- .../TestCompletionFailure.java | 10 +- .../TestConstantValuesPage.java | 10 +- .../TestConstructorIndent.java | 10 +- .../testConstructors/TestConstructors.java | 10 +- .../doclet/testCopyFiles/TestCopyFiles.java | 30 +-- .../TestDeprecatedDocs.java | 10 +- .../testDocEncoding/TestDocEncoding.java | 10 +- .../TestDocErrorReporter.java | 10 +- .../doclet/testDocFileDir/TestDocFileDir.java | 14 +- .../doclet/testDocFiles/TestDocFiles.java | 10 +- .../TestDocRootInlineTag.java | 10 +- .../testDocRootLink/TestDocRootLink.java | 12 +- .../testDupParamWarn/TestDupParamWarn.java | 10 +- .../doclet/testEmptyClass/TestEmptyClass.java | 10 +- .../TestEnclosingClass.java | 10 +- .../doclet/testEncoding/TestEncoding.java | 10 +- .../TestEnumConstructor.java | 10 +- .../TestExternalOverridenMethod.java | 10 +- .../TestFramesNoFrames.java | 16 +- .../testGeneratedBy/TestGeneratedBy.java | 10 +- .../TestGenericMethodLinkTaglet.java | 8 +- .../TestGrandParentTypes.java | 10 +- .../doclet/testGroupName/TestGroupName.java | 7 +- .../testGroupOption/TestGroupOption.java | 14 +- .../doclet/testHeadTag/TestHeadTag.java | 10 +- .../doclet/testHeadings/TestHeadings.java | 8 +- .../doclet/testHelpFile/TestHelpFile.java | 10 +- .../doclet/testHelpOption/TestHelpOption.java | 20 +- .../testHiddenMembers/TestHiddenMembers.java | 10 +- .../doclet/testHiddenTag/TestHiddenTag.java | 6 +- .../jdk/javadoc/doclet/testHref/TestHref.java | 10 +- .../TestHrefInDocComment.java | 10 +- .../testHtmlComments/TestHtmlComments.java | 10 +- .../TestHtmlDefinitionListTag.java | 22 ++- .../testHtmlDocument/TestHtmlDocument.java | 10 +- .../TestHtmlLankmarkRegions.java | 14 +- .../testHtmlStrongTag/TestHtmlStrongTag.java | 12 +- .../TestHtmlTableStyles.java | 10 +- .../testHtmlTableTags/TestHtmlTableTags.java | 10 +- .../doclet/testHtmlTag/TestHtmlTag.java | 16 +- .../testHtmlVersion/TestHtmlVersion.java | 14 +- .../testHtmlWarning/TestHtmlWarning.java | 12 +- .../testIOException/TestIOException.java | 16 +- .../doclet/testIncluded/TestIncluded.java | 10 +- .../testIndentation/TestIndentation.java | 10 +- .../javadoc/doclet/testIndex/TestIndex.java | 8 +- .../doclet/testIndexFiles/TestIndexFiles.java | 8 +- .../TestIndexInPackageFiles.java | 6 +- .../testIndexTaglet/TestIndexTaglet.java | 10 +- .../TestIndexWithModules.java | 18 +- .../TestInlineLinkLabel.java | 8 +- .../doclet/testInterface/TestInterface.java | 16 +- .../doclet/testJavaFX/TestFxProperties.java | 8 +- .../javadoc/doclet/testJavaFX/TestJavaFX.java | 20 +- .../doclet/testJavaFX/TestJavaFxMode.java | 8 +- .../doclet/testJavascript/TestJavascript.java | 8 +- .../testLambdaFeature/TestLambdaFeature.java | 12 +- .../testLeadingSpaces/LeadingSpaces.java | 10 +- .../testLegacyTaglet/TestLegacyTaglet.java | 10 +- .../testLinkOption/TestBadLinkOption.java | 10 +- .../doclet/testLinkOption/TestLinkOption.java | 8 +- .../TestLinkOptionWithModule.java | 14 +- .../testLinkOption/TestNewLineInLink.java | 10 +- .../testLinkOption/TestRedirectLinks.java | 7 +- .../doclet/testLinkTaglet/TestLinkTaglet.java | 10 +- .../TestLinkToSerialForm.java | 10 +- .../TestLinksWithNoDeprecatedOption.java | 8 +- .../TestLiteralCodeInPre.java | 10 +- .../TestMemberInheritance.java | 10 +- .../testMemberSummary/TestMemberSummary.java | 10 +- .../testMethodTypes/TestMethodTypes.java | 8 +- .../testMissingType/TestMissingType.java | 10 +- .../doclet/testModifierEx/TestModifierEx.java | 10 +- .../doclet/testModuleDirs/TestModuleDirs.java | 5 +- .../doclet/testModules/TestEmptyModule.java | 11 +- .../testModules/TestIndirectExportsOpens.java | 8 +- .../testModules/TestModulePackages.java | 5 +- .../testModules/TestModuleServices.java | 8 +- .../testModules/TestModuleServicesLink.java | 8 +- .../doclet/testModules/TestModules.java | 74 +++---- .../testNavigation/TestModuleNavigation.java | 8 +- .../doclet/testNavigation/TestNavigation.java | 19 +- .../TestNestedGenerics.java | 10 +- .../TestNewLanguageFeatures.java | 10 +- .../TestNoPackagesFile.java | 10 +- .../TestNonInlineHtmlTagRemoval.java | 14 +- .../testNotifications/TestNotifications.java | 12 +- .../doclet/testOptions/TestOptions.java | 32 +-- .../doclet/testOrdering/TestOrdering.java | 184 ++++++++---------- .../TestBadOverride.java | 10 +- .../TestMultiInheritance.java | 8 +- .../TestOverriddenDeprecatedMethods.java | 8 +- .../TestOverriddenMethodDocCopy.java | 10 +- .../TestOverriddenPrivateMethods.java | 8 +- ...erriddenPrivateMethodsWithPackageFlag.java | 10 +- ...erriddenPrivateMethodsWithPrivateFlag.java | 8 +- .../TestOverrideMethods.java | 14 +- .../doclet/testOverview/TestOverview.java | 14 +- .../TestPackageDeprecation.java | 10 +- .../TestPackageDescription.java | 10 +- .../testPackageHtml/TestPackageHtml.java | 12 +- .../testPackagePage/TestPackagePage.java | 10 +- .../TestPackageSummary.java | 8 +- .../testParamTaglet/TestParamTaglet.java | 10 +- .../TestPrivateClasses.java | 14 +- .../doclet/testProperty/TestProperty.java | 10 +- .../TestRecurseSubPackages.java | 8 +- .../testRelativeLinks/TestRelativeLinks.java | 10 +- .../TestRepeatedAnnotations.java | 10 +- .../doclet/testReturnTag/TestReturnTag.java | 10 +- .../javadoc/doclet/testSearch/TestSearch.java | 40 ++-- .../javadoc/doclet/testSeeTag/TestSeeTag.java | 12 +- .../doclet/testSerialTag/TestSerialTag.java | 6 +- .../TestSerialVersionUID.java | 10 +- .../TestSerializedForm.java | 14 +- .../TestSerializedFormDeprecationInfo.java | 14 +- .../TestSerializedFormWithClassFile.java | 8 +- .../TestSerializedFormWithSee.java | 6 +- .../doclet/testSimpleTag/TestSimpleTag.java | 10 +- .../TestSimpleTagExclude.java | 10 +- .../TestSimpleTagInherit.java | 10 +- .../doclet/testSinceTag/TestSinceTag.java | 12 +- .../TestSingleQuotedLink.java | 10 +- .../doclet/testSourceTab/TestSourceTab.java | 10 +- .../doclet/testStylesheet/TestStylesheet.java | 10 +- .../TestStylesheetOverwrite.java | 8 +- .../doclet/testSubTitle/TestSubTitle.java | 8 +- .../TestSummaryHeading.java | 10 +- .../doclet/testSummaryTag/TestSummaryTag.java | 14 +- .../TestSuperClassInSerialForm.java | 10 +- .../testSupplementary/TestSupplementary.java | 10 +- .../TestSystemPropertyTaglet.java | 10 +- .../TestTagInheritence.java | 10 +- .../doclet/testTagMisuse/TestTagMisuse.java | 10 +- .../doclet/testTagOutput/TestTagOutput.java | 10 +- .../doclet/testTaglets/TestTaglets.java | 7 +- .../doclet/testThrowsHead/TestThrowsHead.java | 10 +- .../TestThrowsTagInheritence.java | 12 +- .../doclet/testThrowsTag/TestThrowsTag.java | 8 +- .../testTitleInHref/TestTitleInHref.java | 8 +- .../doclet/testTopOption/TestTopOption.java | 10 +- .../TestTypeAnnotations.java | 10 +- .../testTypeParams/TestTypeParameters.java | 12 +- .../TestTypeVariableLinks.java | 10 +- .../doclet/testUnicode/TestUnicode.java | 7 +- .../TestUnnamedPackage.java | 8 +- .../doclet/testUseOption/TestUseOption.java | 18 +- .../doclet/testUserTaglet/TestUserTaglet.java | 8 +- .../doclet/testValueTag/TestValueTag.java | 14 +- .../testValueTag/TestValueTagInModule.java | 8 +- .../testVersionOption/TestVersionOption.java | 12 +- .../doclet/testVersionTag/TestVersionTag.java | 9 +- .../TestVisibleMembers.java | 26 +-- .../TestWarnBadParamNames.java | 10 +- .../doclet/testWarnings/TestWarnings.java | 12 +- .../testWindowTitle/TestWindowTitle.java | 22 ++- .../doclet/testXOption/TestXOption.java | 16 +- .../typeAnnotations/smoke/TestSmoke.java | 10 +- .../javadoc/tester}/JavadocTester.java | 4 +- 199 files changed, 1373 insertions(+), 1012 deletions(-) rename test/langtools/jdk/javadoc/{doclet/lib => lib/javadoc/tester}/JavadocTester.java (99%) diff --git a/test/langtools/jdk/javadoc/doclet/5093723/T5093723.java b/test/langtools/jdk/javadoc/doclet/5093723/T5093723.java index 46bcf0a565b..cf5bb4a7cc6 100644 --- a/test/langtools/jdk/javadoc/doclet/5093723/T5093723.java +++ b/test/langtools/jdk/javadoc/doclet/5093723/T5093723.java @@ -25,12 +25,14 @@ * @test * @bug 5093723 * @summary REGRESSION: ClassCastException in SingleIndexWriter - * @library ../lib - * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @library ../../lib + * @modules jdk.javadoc/jdk.javadoc.internal.tool + * @build javadoc.tester.* * @run main T5093723 */ +import javadoc.tester.JavadocTester; + public class T5093723 extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class T5093723 extends JavadocTester { } @Test - void test() { + public void test() { setAutomaticCheckLinks(false); // @ignore JDK-8202617 javadoc("-d", "out", "-Xdoclint:none", diff --git a/test/langtools/jdk/javadoc/doclet/AccessAsciiArt/AccessAsciiArt.java b/test/langtools/jdk/javadoc/doclet/AccessAsciiArt/AccessAsciiArt.java index dfd8d78d65b..40907cc8bd8 100644 --- a/test/langtools/jdk/javadoc/doclet/AccessAsciiArt/AccessAsciiArt.java +++ b/test/langtools/jdk/javadoc/doclet/AccessAsciiArt/AccessAsciiArt.java @@ -26,12 +26,14 @@ * @bug 4706779 4956908 * @summary Add text equivalent of class tree ASCII art for accessibility * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AccessAsciiArt */ +import javadoc.tester.JavadocTester; + public class AccessAsciiArt extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class AccessAsciiArt extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "p1", "p1.subpkg"); diff --git a/test/langtools/jdk/javadoc/doclet/AccessFrameTitle/AccessFrameTitle.java b/test/langtools/jdk/javadoc/doclet/AccessFrameTitle/AccessFrameTitle.java index 64e4ee6495e..e43d8002c5f 100644 --- a/test/langtools/jdk/javadoc/doclet/AccessFrameTitle/AccessFrameTitle.java +++ b/test/langtools/jdk/javadoc/doclet/AccessFrameTitle/AccessFrameTitle.java @@ -26,12 +26,14 @@ * @bug 4636655 8196202 * @summary Add title attribute to tags for accessibility * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AccessFrameTitle */ +import javadoc.tester.JavadocTester; + public class AccessFrameTitle extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class AccessFrameTitle extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "--frames", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/AccessH1/AccessH1.java b/test/langtools/jdk/javadoc/doclet/AccessH1/AccessH1.java index 1d86c4d026c..34f3a26946d 100644 --- a/test/langtools/jdk/javadoc/doclet/AccessH1/AccessH1.java +++ b/test/langtools/jdk/javadoc/doclet/AccessH1/AccessH1.java @@ -26,13 +26,15 @@ * @bug 4636667 7052425 8016549 8196202 * @summary Use , and

      in proper sequence for accessibility * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AccessH1 */ +import javadoc.tester.JavadocTester; + public class AccessH1 extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class AccessH1 extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-doctitle", "Document Title", "--frames", diff --git a/test/langtools/jdk/javadoc/doclet/AccessSkipNav/AccessSkipNav.java b/test/langtools/jdk/javadoc/doclet/AccessSkipNav/AccessSkipNav.java index c362644da5d..f4f53bbad3a 100644 --- a/test/langtools/jdk/javadoc/doclet/AccessSkipNav/AccessSkipNav.java +++ b/test/langtools/jdk/javadoc/doclet/AccessSkipNav/AccessSkipNav.java @@ -26,12 +26,14 @@ * @bug 4638136 7198273 8025633 8081854 8182765 * @summary Add ability to skip over nav bar for accessibility * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AccessSkipNav */ +import javadoc.tester.JavadocTester; + public class AccessSkipNav extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class AccessSkipNav extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "p1", "p2"); @@ -63,7 +65,7 @@ public class AccessSkipNav extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/AccessSummary/AccessSummary.java b/test/langtools/jdk/javadoc/doclet/AccessSummary/AccessSummary.java index 6926b9ddf06..472c5f0fbf0 100644 --- a/test/langtools/jdk/javadoc/doclet/AccessSummary/AccessSummary.java +++ b/test/langtools/jdk/javadoc/doclet/AccessSummary/AccessSummary.java @@ -26,12 +26,14 @@ * @bug 4637604 4775148 8183037 8182765 8196202 * @summary Test the tables for summary attribute * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AccessSummary */ +import javadoc.tester.JavadocTester; + public class AccessSummary extends JavadocTester { /** * The entry point of the test. @@ -44,7 +46,7 @@ public class AccessSummary extends JavadocTester { } @Test - void testAccessSummary() { + public void testAccessSummary() { javadoc("-d", "out", "--frames", "-sourcepath", testSrc, @@ -54,7 +56,7 @@ public class AccessSummary extends JavadocTester { } @Test - void testAccessSummary_html4() { + public void testAccessSummary_html4() { javadoc("-d", "out-html4", "-html4", "--frames", diff --git a/test/langtools/jdk/javadoc/doclet/AuthorDD/AuthorDD.java b/test/langtools/jdk/javadoc/doclet/AuthorDD/AuthorDD.java index bc7a8b237eb..52afdbabc9b 100644 --- a/test/langtools/jdk/javadoc/doclet/AuthorDD/AuthorDD.java +++ b/test/langtools/jdk/javadoc/doclet/AuthorDD/AuthorDD.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,15 +26,17 @@ * @bug 4651598 8026567 * @summary Javadoc wrongly inserts tags when using multiple @author tags * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main AuthorDD */ /** * Runs javadoc and runs regression tests on the resulting HTML. */ +import javadoc.tester.JavadocTester; + public class AuthorDD extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class AuthorDD extends JavadocTester { } @Test - void test() { + public void test() { // Test for all cases except the split index page javadoc("-d", "out", "-author", diff --git a/test/langtools/jdk/javadoc/doclet/DocRootSlash/DocRootSlash.java b/test/langtools/jdk/javadoc/doclet/DocRootSlash/DocRootSlash.java index b887385df5f..222c02e4b85 100644 --- a/test/langtools/jdk/javadoc/doclet/DocRootSlash/DocRootSlash.java +++ b/test/langtools/jdk/javadoc/doclet/DocRootSlash/DocRootSlash.java @@ -26,9 +26,9 @@ * @bug 4524350 4662945 4633447 8196202 * @summary stddoclet: {@docRoot} inserts an extra trailing "/" * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main DocRootSlash */ @@ -39,6 +39,8 @@ import java.util.regex.*; * It reads each file, complete with newlines, into a string to easily * find strings that contain newlines. */ +import javadoc.tester.JavadocTester; + public class DocRootSlash extends JavadocTester { public static void main(String... args) throws Exception { @@ -47,7 +49,7 @@ public class DocRootSlash extends JavadocTester { } @Test - void test() { + public void test() { // Directory that contains source files that javadoc runs on String srcdir = System.getProperty("test.src", "."); diff --git a/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java b/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java index a6b7e479a65..31bb1d75631 100644 --- a/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java +++ b/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,9 @@ * @bug 8008768 * @summary Using {@inheritDoc} in simple tag defined via -tag fails * @author Mike Duigou - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main DocTest */ @@ -39,6 +39,8 @@ * @implSpec DocTest implementation spec. * @implNote DocTest implementation note. */ +import javadoc.tester.JavadocTester; + public class DocTest extends JavadocTester { public static void main(String... args) throws Exception { DocTest tester = new DocTest(); @@ -46,7 +48,7 @@ public class DocTest extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-verbose", "-d", "DocTest", "-tag", "apiNote:optcm:API Note", diff --git a/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java b/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java index 6d9a5ee4058..c08b6489f59 100644 --- a/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java +++ b/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java @@ -27,12 +27,14 @@ * @summary Javascript IE load error when linked by -linkoffline * Window title shouldn't change when loading left frames (javascript) * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main JavascriptWinTitle */ +import javadoc.tester.JavadocTester; + public class JavascriptWinTitle extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class JavascriptWinTitle extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-source", "8", "--frames", diff --git a/test/langtools/jdk/javadoc/doclet/MetaTag/MetaTag.java b/test/langtools/jdk/javadoc/doclet/MetaTag/MetaTag.java index 5ebb11da952..b16172aa7ef 100644 --- a/test/langtools/jdk/javadoc/doclet/MetaTag/MetaTag.java +++ b/test/langtools/jdk/javadoc/doclet/MetaTag/MetaTag.java @@ -27,15 +27,17 @@ * @summary Add support for HTML keywords via META tag for * class and member names to improve API search * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main MetaTag */ import java.text.SimpleDateFormat; import java.util.Date; +import javadoc.tester.JavadocTester; + public class MetaTag extends JavadocTester { /** @@ -49,7 +51,7 @@ public class MetaTag extends JavadocTester { } @Test - void testStandard() { + public void testStandard() { javadoc("-d", "out-1", "-sourcepath", testSrc, "-keywords", @@ -63,7 +65,7 @@ public class MetaTag extends JavadocTester { } @Test - void testNoTimestamp() { + public void testNoTimestamp() { javadoc("-d", "out-2", "-sourcepath", testSrc, "-notimestamp", @@ -77,7 +79,7 @@ public class MetaTag extends JavadocTester { } @Test - void testStandard_html4() { + public void testStandard_html4() { javadoc("-d", "out-1-html4", "-html4", "-sourcepath", testSrc, @@ -92,7 +94,7 @@ public class MetaTag extends JavadocTester { } @Test - void testNoTimestamp_html4() { + public void testNoTimestamp_html4() { javadoc("-d", "out-2-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/PackagesHeader/PackagesHeader.java b/test/langtools/jdk/javadoc/doclet/PackagesHeader/PackagesHeader.java index 557354049d2..ff04824df00 100644 --- a/test/langtools/jdk/javadoc/doclet/PackagesHeader/PackagesHeader.java +++ b/test/langtools/jdk/javadoc/doclet/PackagesHeader/PackagesHeader.java @@ -28,12 +28,14 @@ * is present for three sets of options: (1) -header, * (2) -packagesheader, and (3) -header -packagesheader * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main PackagesHeader */ +import javadoc.tester.JavadocTester; + public class PackagesHeader extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class PackagesHeader extends JavadocTester { } @Test - void testHeader() { + public void testHeader() { // First test with -header only javadoc("-d", "out-header", "-header", "Main Frame Header", @@ -57,7 +59,7 @@ public class PackagesHeader extends JavadocTester { } @Test - void testPackagesHeader() { + public void testPackagesHeader() { // Second test with -packagesheader only javadoc("-d", "out-packages-header", "-packagesheader", "Packages Frame Header", @@ -73,7 +75,7 @@ public class PackagesHeader extends JavadocTester { } @Test - void testBothHeaders() { + public void testBothHeaders() { // Third test with both -packagesheader and -header javadoc("-d", "out-both", "-packagesheader", "Packages Frame Header", diff --git a/test/langtools/jdk/javadoc/doclet/T6735320/T6735320.java b/test/langtools/jdk/javadoc/doclet/T6735320/T6735320.java index 6f36bee159b..7d945627596 100644 --- a/test/langtools/jdk/javadoc/doclet/T6735320/T6735320.java +++ b/test/langtools/jdk/javadoc/doclet/T6735320/T6735320.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @bug 6735320 * @summary javadoc throws exception if serialField value is missing - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main T6735320 */ +import javadoc.tester.JavadocTester; + public class T6735320 extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class T6735320 extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", testSrc("SerialFieldTest.java")); checkExit(Exit.ERROR); diff --git a/test/langtools/jdk/javadoc/doclet/ValidHtml/ValidHtml.java b/test/langtools/jdk/javadoc/doclet/ValidHtml/ValidHtml.java index 5d444ff96dc..81e5880e9bc 100644 --- a/test/langtools/jdk/javadoc/doclet/ValidHtml/ValidHtml.java +++ b/test/langtools/jdk/javadoc/doclet/ValidHtml/ValidHtml.java @@ -29,12 +29,14 @@ * Missing whitespace in DOCTYPE declaration * HTML table tags inserted in wrong place in pakcage use page * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main ValidHtml */ +import javadoc.tester.JavadocTester; + public class ValidHtml extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class ValidHtml extends JavadocTester { } @Test - void test() { + public void test() { // Test for all cases except the split index page javadoc("-d", "out", "-doctitle", "Document Title", @@ -66,7 +68,7 @@ public class ValidHtml extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { // Test for all cases except the split index page javadoc("-d", "out-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/VersionNumber/VersionNumber.java b/test/langtools/jdk/javadoc/doclet/VersionNumber/VersionNumber.java index 8c88fa5dd52..cb8fdee191c 100644 --- a/test/langtools/jdk/javadoc/doclet/VersionNumber/VersionNumber.java +++ b/test/langtools/jdk/javadoc/doclet/VersionNumber/VersionNumber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,9 @@ * @bug 4720849 * @summary Standard doclet contains hard-coded version number * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main VersionNumber */ @@ -36,6 +36,8 @@ /** * Runs javadoc and runs regression tests on the resulting HTML. */ +import javadoc.tester.JavadocTester; + public class VersionNumber extends JavadocTester { public static void main(String... args) throws Exception { @@ -44,7 +46,7 @@ public class VersionNumber extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "p1"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/WindowTitles/WindowTitles.java b/test/langtools/jdk/javadoc/doclet/WindowTitles/WindowTitles.java index 79b3c9c68d5..1718e526785 100644 --- a/test/langtools/jdk/javadoc/doclet/WindowTitles/WindowTitles.java +++ b/test/langtools/jdk/javadoc/doclet/WindowTitles/WindowTitles.java @@ -26,15 +26,17 @@ * @bug 4530730 8196202 * @summary stddoclet: With frames off, window titles have "()" appended * @author dkramer - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main WindowTitles */ /** * Runs javadoc and runs regression tests on the resulting HTML. */ +import javadoc.tester.JavadocTester; + public class WindowTitles extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class WindowTitles extends JavadocTester { } @Test - void test() { + public void test() { // Test for all cases except the split index page javadoc("-d", "out-1", "-use", @@ -71,7 +73,7 @@ public class WindowTitles extends JavadocTester { } @Test - void test2() { + public void test2() { // Test only for the split-index case (and run on only one package) javadoc("-d", "out-2", "-splitindex", diff --git a/test/langtools/jdk/javadoc/doclet/_template/Template.java b/test/langtools/jdk/javadoc/doclet/_template/Template.java index 92a36f867df..2d39d2e88e1 100644 --- a/test/langtools/jdk/javadoc/doclet/_template/Template.java +++ b/test/langtools/jdk/javadoc/doclet/_template/Template.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -31,6 +31,8 @@ * @ run main */ +import javadoc.tester.JavadocTester; + public class Template extends JavadocTester { //Javadoc arguments. diff --git a/test/langtools/jdk/javadoc/doclet/_template/TemplateComplete.java b/test/langtools/jdk/javadoc/doclet/_template/TemplateComplete.java index cb15e989a35..e134c2a8724 100644 --- a/test/langtools/jdk/javadoc/doclet/_template/TemplateComplete.java +++ b/test/langtools/jdk/javadoc/doclet/_template/TemplateComplete.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -31,6 +31,8 @@ * @ run main */ +import javadoc.tester.JavadocTester; + public class TemplateComplete extends JavadocTester { //Javadoc arguments. diff --git a/test/langtools/jdk/javadoc/doclet/constantValues/TestConstantValuesDriver.java b/test/langtools/jdk/javadoc/doclet/constantValues/TestConstantValuesDriver.java index f94cbc47194..112f06a27b8 100644 --- a/test/langtools/jdk/javadoc/doclet/constantValues/TestConstantValuesDriver.java +++ b/test/langtools/jdk/javadoc/doclet/constantValues/TestConstantValuesDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,13 @@ * @bug 4504730 4526070 5077317 8162363 * @summary Test the generation of constant-values.html. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestConstantValuesDriver */ +import javadoc.tester.JavadocTester; + public class TestConstantValuesDriver extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestConstantValuesDriver extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", testSrc("TestConstantValues.java"), testSrc("TestConstantValues2.java"), diff --git a/test/langtools/jdk/javadoc/doclet/dupThrowsTags/TestDupThrowsTags.java b/test/langtools/jdk/javadoc/doclet/dupThrowsTags/TestDupThrowsTags.java index cf5261f8826..c4ed4e95004 100644 --- a/test/langtools/jdk/javadoc/doclet/dupThrowsTags/TestDupThrowsTags.java +++ b/test/langtools/jdk/javadoc/doclet/dupThrowsTags/TestDupThrowsTags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,13 @@ * @bug 4525364 * @summary Determine if duplicate throws tags can be used. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDupThrowsTags */ +import javadoc.tester.JavadocTester; + public class TestDupThrowsTags extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestDupThrowsTags extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", testSrc("TestDupThrowsTags.java")); checkExit(Exit.ERROR); diff --git a/test/langtools/jdk/javadoc/doclet/testAbsLinkPath/TestAbsLinkPath.java b/test/langtools/jdk/javadoc/doclet/testAbsLinkPath/TestAbsLinkPath.java index 3e715a820f4..81188b92ef1 100644 --- a/test/langtools/jdk/javadoc/doclet/testAbsLinkPath/TestAbsLinkPath.java +++ b/test/langtools/jdk/javadoc/doclet/testAbsLinkPath/TestAbsLinkPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 4640745 * @summary This test verifys that the -link option handles absolute paths. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestAbsLinkPath */ +import javadoc.tester.JavadocTester; + public class TestAbsLinkPath extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestAbsLinkPath extends JavadocTester { } @Test - void test1() { + public void test1() { String out1 = "out1"; javadoc("-d", out1, "-sourcepath", testSrc, "pkg2"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testAbstractMethod/TestAbstractMethod.java b/test/langtools/jdk/javadoc/doclet/testAbstractMethod/TestAbstractMethod.java index fdadf8a3fcf..01deec16834 100644 --- a/test/langtools/jdk/javadoc/doclet/testAbstractMethod/TestAbstractMethod.java +++ b/test/langtools/jdk/javadoc/doclet/testAbstractMethod/TestAbstractMethod.java @@ -27,12 +27,14 @@ * @summary Make sure that the abstract method is identified correctly * if the abstract modifier is present explicitly or implicitly. * @author bpatel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestAbstractMethod */ +import javadoc.tester.JavadocTester; + public class TestAbstractMethod extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestAbstractMethod extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testAnchorNames/TestAnchorNames.java b/test/langtools/jdk/javadoc/doclet/testAnchorNames/TestAnchorNames.java index c12f26fc79c..b2c4bcfdc38 100644 --- a/test/langtools/jdk/javadoc/doclet/testAnchorNames/TestAnchorNames.java +++ b/test/langtools/jdk/javadoc/doclet/testAnchorNames/TestAnchorNames.java @@ -26,9 +26,9 @@ * @bug 8025633 8025524 8081854 8187521 8182765 * @summary Test for valid name attribute in HTML anchors. * @author Bhavesh Patel - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestAnchorNames */ @@ -36,7 +36,8 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ToolBox; public class TestAnchorNames extends JavadocTester { @@ -51,7 +52,7 @@ public class TestAnchorNames extends JavadocTester { } @Test - void testHtml4(Path ignore) { + public void testHtml4(Path ignore) { setAutomaticCheckLinks(false); // @ignore JDK-8202622 javadoc("-d", "out-html4", "-html4", @@ -172,7 +173,7 @@ public class TestAnchorNames extends JavadocTester { } @Test - void testHtml5(Path ignore) { + public void testHtml5(Path ignore) { javadoc("-d", "out-html5", "-sourcepath", testSrc, "-source", "8", //so that '_' can be used as an identifier @@ -289,7 +290,7 @@ public class TestAnchorNames extends JavadocTester { * @throws IOException if there is a problem generating the source files */ @Test - void testNonAscii(Path base) throws IOException { + public void testNonAscii(Path base) throws IOException { Path src = base.resolve("src"); tb.writeJavaFiles(src, "package p; public class Def {\n" diff --git a/test/langtools/jdk/javadoc/doclet/testAnnotationOptional/TestAnnotationOptional.java b/test/langtools/jdk/javadoc/doclet/testAnnotationOptional/TestAnnotationOptional.java index 4b21226eebb..987fc6c3607 100644 --- a/test/langtools/jdk/javadoc/doclet/testAnnotationOptional/TestAnnotationOptional.java +++ b/test/langtools/jdk/javadoc/doclet/testAnnotationOptional/TestAnnotationOptional.java @@ -27,12 +27,14 @@ * @summary Make sure that annotations types with optional elements have * element headers * @author Mahmood Ali - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestAnnotationOptional */ +import javadoc.tester.JavadocTester; + public class TestAnnotationOptional extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestAnnotationOptional extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -52,7 +54,7 @@ public class TestAnnotationOptional extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testAnnotationTypes/TestAnnotationTypes.java b/test/langtools/jdk/javadoc/doclet/testAnnotationTypes/TestAnnotationTypes.java index 29405f290b1..0be1fd0304b 100644 --- a/test/langtools/jdk/javadoc/doclet/testAnnotationTypes/TestAnnotationTypes.java +++ b/test/langtools/jdk/javadoc/doclet/testAnnotationTypes/TestAnnotationTypes.java @@ -27,12 +27,14 @@ * @summary Make sure that annotation types with 0 members does not have * extra HR tags. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestAnnotationTypes */ +import javadoc.tester.JavadocTester; + public class TestAnnotationTypes extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestAnnotationTypes extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out-1", "-sourcepath", testSrc, "pkg"); @@ -92,7 +94,7 @@ public class TestAnnotationTypes extends JavadocTester { } @Test - void testLinkSource() { + public void testLinkSource() { javadoc("-d", "out-2", "-linksource", "-sourcepath", testSrc, @@ -117,7 +119,7 @@ public class TestAnnotationTypes extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java b/test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java index 923eae991a2..ec9b723c8ab 100644 --- a/test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java +++ b/test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java @@ -25,9 +25,9 @@ * @test * @bug 8202947 * @summary test the at-author tag, and corresponding option - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestAuthor */ @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; import toolbox.ToolBox; public class TestAuthor extends JavadocTester { @@ -58,7 +59,7 @@ public class TestAuthor extends JavadocTester { } @Test - void testAuthor() { + public void testAuthor() { javadoc("-d", "out-author", "-sourcepath", src.toString(), "-author", @@ -69,7 +70,7 @@ public class TestAuthor extends JavadocTester { } @Test - void testNoAuthor() { + public void testNoAuthor() { javadoc("-d", "out-noauthor", "-sourcepath", src.toString(), "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testBackSlashInLink/TestBackSlashInLink.java b/test/langtools/jdk/javadoc/doclet/testBackSlashInLink/TestBackSlashInLink.java index e5673158f36..3f16dc8901e 100644 --- a/test/langtools/jdk/javadoc/doclet/testBackSlashInLink/TestBackSlashInLink.java +++ b/test/langtools/jdk/javadoc/doclet/testBackSlashInLink/TestBackSlashInLink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure that the link to source documentation * has a forward slash. It would be wrong to use a back slash. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBackSlashInLink */ +import javadoc.tester.JavadocTester; + public class TestBackSlashInLink extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestBackSlashInLink extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-linksource", diff --git a/test/langtools/jdk/javadoc/doclet/testBadHtml/TestBadHtml.java b/test/langtools/jdk/javadoc/doclet/testBadHtml/TestBadHtml.java index 1b2b0535d34..88aa55dffcf 100644 --- a/test/langtools/jdk/javadoc/doclet/testBadHtml/TestBadHtml.java +++ b/test/langtools/jdk/javadoc/doclet/testBadHtml/TestBadHtml.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,12 +25,14 @@ * @test * @bug 8176901 * @summary The doclet should cope with bad HTML form - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBadHtml */ +import javadoc.tester.JavadocTester; + public class TestBadHtml extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestBadHtml extends JavadocTester { } @Test - void testNegative() { + public void testNegative() { javadoc("-d", "out1", "-sourcepath", testSrc, "pkg1"); diff --git a/test/langtools/jdk/javadoc/doclet/testBadPackageFileInJar/TestBadPackageFileInJar.java b/test/langtools/jdk/javadoc/doclet/testBadPackageFileInJar/TestBadPackageFileInJar.java index ac9ad3b995e..3227f6f456d 100644 --- a/test/langtools/jdk/javadoc/doclet/testBadPackageFileInJar/TestBadPackageFileInJar.java +++ b/test/langtools/jdk/javadoc/doclet/testBadPackageFileInJar/TestBadPackageFileInJar.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,9 +27,9 @@ * @summary Make sure that Javadoc emits a useful warning * when a bad package.html exists in a JAR archive. * @author jamieh - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox toolbox.JarTask + * @build javadoc.tester.* toolbox.ToolBox toolbox.JarTask * @run main TestBadPackageFileInJar */ @@ -41,6 +41,8 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; + public class TestBadPackageFileInJar extends JavadocTester { final ToolBox tb = new ToolBox(); @@ -51,7 +53,7 @@ public class TestBadPackageFileInJar extends JavadocTester { } @Test - void test() throws IOException { + public void test() throws IOException { // create the file Path pkgDir = Paths.get("pkg"); tb.createDirectories(pkgDir); diff --git a/test/langtools/jdk/javadoc/doclet/testBadSourceFile/TestBadSourceFile.java b/test/langtools/jdk/javadoc/doclet/testBadSourceFile/TestBadSourceFile.java index 69aa7ab5be1..6526d05781f 100644 --- a/test/langtools/jdk/javadoc/doclet/testBadSourceFile/TestBadSourceFile.java +++ b/test/langtools/jdk/javadoc/doclet/testBadSourceFile/TestBadSourceFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary Make sure exception is not thrown if there is a bad source * file in the same directory as the file being documented. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBadSourceFile */ +import javadoc.tester.JavadocTester; + public class TestBadSourceFile extends JavadocTester { /** @@ -46,7 +48,7 @@ public class TestBadSourceFile extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", testSrc("C2.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testBaseClass/TestBaseClass.java b/test/langtools/jdk/javadoc/doclet/testBaseClass/TestBaseClass.java index ffa9ce5292b..086f1af1ca0 100644 --- a/test/langtools/jdk/javadoc/doclet/testBaseClass/TestBaseClass.java +++ b/test/langtools/jdk/javadoc/doclet/testBaseClass/TestBaseClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,13 +26,15 @@ * @bug 4197513 * @summary Javadoc does not process base class. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool * @build BaseClass - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBaseClass */ +import javadoc.tester.JavadocTester; + public class TestBaseClass extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestBaseClass extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-sourcepath", testSrc, "-docletpath", System.getProperty("test.classes", "."), "-doclet", "BaseClass", diff --git a/test/langtools/jdk/javadoc/doclet/testBreakIterator/TestBreakIterator.java b/test/langtools/jdk/javadoc/doclet/testBreakIterator/TestBreakIterator.java index b626ccbf334..0de8b228776 100644 --- a/test/langtools/jdk/javadoc/doclet/testBreakIterator/TestBreakIterator.java +++ b/test/langtools/jdk/javadoc/doclet/testBreakIterator/TestBreakIterator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -29,12 +29,14 @@ * Correct Answer: "This is a class (i.e. it is indeed a class)." * Wrong Answer: "This is a class (i.e." * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBreakIterator */ +import javadoc.tester.JavadocTester; + public class TestBreakIterator extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestBreakIterator extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-breakiterator", diff --git a/test/langtools/jdk/javadoc/doclet/testCRLineSeparator/TestCRLineSeparator.java b/test/langtools/jdk/javadoc/doclet/testCRLineSeparator/TestCRLineSeparator.java index e361b974116..bf50278b6d3 100644 --- a/test/langtools/jdk/javadoc/doclet/testCRLineSeparator/TestCRLineSeparator.java +++ b/test/langtools/jdk/javadoc/doclet/testCRLineSeparator/TestCRLineSeparator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,15 +26,17 @@ * @bug 4979486 * @summary Make sure tool parses CR line separators properly. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCRLineSeparator */ import java.io.*; import java.util.*; +import javadoc.tester.JavadocTester; + public class TestCRLineSeparator extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestCRLineSeparator extends JavadocTester { } @Test - void test() throws IOException { + public void test() throws IOException { initFiles(new File(testSrc), new File("src"), "pkg"); javadoc("-d", "out", "-sourcepath", "src", diff --git a/test/langtools/jdk/javadoc/doclet/testCharset/TestCharset.java b/test/langtools/jdk/javadoc/doclet/testCharset/TestCharset.java index 7eb51f548b4..4420a1ed104 100644 --- a/test/langtools/jdk/javadoc/doclet/testCharset/TestCharset.java +++ b/test/langtools/jdk/javadoc/doclet/testCharset/TestCharset.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary Run a test on -charset to make sure the charset gets generated as a * part of the meta tag. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCharset */ +import javadoc.tester.JavadocTester; + public class TestCharset extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestCharset extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-charset", "ISO-8859-1", "-sourcepath", testSrc, @@ -60,7 +62,7 @@ public class TestCharset extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testCharsetDocencodingOptions/TestCharsetDocencodingOptions.java b/test/langtools/jdk/javadoc/doclet/testCharsetDocencodingOptions/TestCharsetDocencodingOptions.java index 2db56bb476f..2ec37a8cd0b 100644 --- a/test/langtools/jdk/javadoc/doclet/testCharsetDocencodingOptions/TestCharsetDocencodingOptions.java +++ b/test/langtools/jdk/javadoc/doclet/testCharsetDocencodingOptions/TestCharsetDocencodingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,12 +25,14 @@ * @test * @bug 8183582 * @summary Rationalize doclet -docencoding and -charset options. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCharsetDocencodingOptions */ +import javadoc.tester.JavadocTester; + public class TestCharsetDocencodingOptions extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testWithNoOptions() { + public void testWithNoOptions() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -49,7 +51,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testWithDocencoding() { + public void testWithDocencoding() { javadoc("-d", "out-1", "-docencoding", "ISO-8859-1", "-sourcepath", testSrc, @@ -60,7 +62,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testWithCharset() { + public void testWithCharset() { javadoc("-d", "out-2", "-charset", "ISO-8859-1", "-sourcepath", testSrc, @@ -71,7 +73,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testDocencodingWithCharsetSimilar() { + public void testDocencodingWithCharsetSimilar() { javadoc("-d", "out-3", "-docencoding", "ISO-8859-1", "-charset", "ISO-8859-1", @@ -83,7 +85,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testDocencodingWithCharsetDifferent() { + public void testDocencodingWithCharsetDifferent() { javadoc("-d", "out-4", "-charset", "UTF-8", "-docencoding", "ISO-8859-1", @@ -96,7 +98,7 @@ public class TestCharsetDocencodingOptions extends JavadocTester { } @Test - void testWithEncoding() { + public void testWithEncoding() { javadoc("-d", "out-5", "-sourcepath", testSrc, "-encoding", "ISO-8859-1", diff --git a/test/langtools/jdk/javadoc/doclet/testClassCrossReferences/TestClassCrossReferences.java b/test/langtools/jdk/javadoc/doclet/testClassCrossReferences/TestClassCrossReferences.java index 766d55d1d52..f3c210c8281 100644 --- a/test/langtools/jdk/javadoc/doclet/testClassCrossReferences/TestClassCrossReferences.java +++ b/test/langtools/jdk/javadoc/doclet/testClassCrossReferences/TestClassCrossReferences.java @@ -26,13 +26,15 @@ * @bug 4652655 4857717 8025633 8026567 8071982 8164407 8182765 8205593 * @summary This test verifies that class cross references work properly. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @build TestClassCrossReferences * @run main TestClassCrossReferences */ +import javadoc.tester.JavadocTester; + public class TestClassCrossReferences extends JavadocTester { static final String uri = "http://docs.oracle.com/javase/8/docs/api/"; @@ -43,7 +45,7 @@ public class TestClassCrossReferences extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-source", "8", "-Xdoclint:none", @@ -70,7 +72,7 @@ public class TestClassCrossReferences extends JavadocTester { } @Test - void test_error() { + public void test_error() { javadoc("-d", "out-error", "-Xdoclint:none", "-sourcepath", testSrc, @@ -83,7 +85,7 @@ public class TestClassCrossReferences extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-source", "8", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testClassDocCatalog/TestClassDocCatalog.java b/test/langtools/jdk/javadoc/doclet/testClassDocCatalog/TestClassDocCatalog.java index 710f2a3dfbb..99d78cf58e3 100644 --- a/test/langtools/jdk/javadoc/doclet/testClassDocCatalog/TestClassDocCatalog.java +++ b/test/langtools/jdk/javadoc/doclet/testClassDocCatalog/TestClassDocCatalog.java @@ -25,12 +25,14 @@ * @test * @bug 8071982 8196202 * @summary Test for package-frame.html. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestClassDocCatalog */ +import javadoc.tester.JavadocTester; + public class TestClassDocCatalog extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestClassDocCatalog extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "--frames", testSrc("pkg1/EmptyAnnotation.java"), diff --git a/test/langtools/jdk/javadoc/doclet/testClassLinks/TestClassLinks.java b/test/langtools/jdk/javadoc/doclet/testClassLinks/TestClassLinks.java index 4865b696ebe..7e29d143320 100644 --- a/test/langtools/jdk/javadoc/doclet/testClassLinks/TestClassLinks.java +++ b/test/langtools/jdk/javadoc/doclet/testClassLinks/TestClassLinks.java @@ -25,13 +25,15 @@ * @test * @bug 8163800 8175200 8186332 8182765 * @summary The fix for JDK-8072052 shows up other minor incorrect use of styles - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @build TestClassLinks * @run main TestClassLinks */ +import javadoc.tester.JavadocTester; + public class TestClassLinks extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestClassLinks extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-Xdoclint:none", @@ -85,7 +87,7 @@ public class TestClassLinks extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testClassTree/TestClassTree.java b/test/langtools/jdk/javadoc/doclet/testClassTree/TestClassTree.java index 47be8c680ad..1daa7493482 100644 --- a/test/langtools/jdk/javadoc/doclet/testClassTree/TestClassTree.java +++ b/test/langtools/jdk/javadoc/doclet/testClassTree/TestClassTree.java @@ -29,12 +29,14 @@ * Make sure class tree includes heirarchy for enums and annotation * types. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestClassTree */ +import javadoc.tester.JavadocTester; + public class TestClassTree extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestClassTree extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testCmndLineClass/TestCmndLineClass.java b/test/langtools/jdk/javadoc/doclet/testCmndLineClass/TestCmndLineClass.java index 7d1d55466da..0062e61bc67 100644 --- a/test/langtools/jdk/javadoc/doclet/testCmndLineClass/TestCmndLineClass.java +++ b/test/langtools/jdk/javadoc/doclet/testCmndLineClass/TestCmndLineClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -28,12 +28,14 @@ * when specifying packages on the command line and specifying individual * classes. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCmndLineClass */ +import javadoc.tester.JavadocTester; + public class TestCmndLineClass extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestCmndLineClass extends JavadocTester { } @Test - void test() { + public void test() { String outdir1 = "out-1"; String outdir2 = "out-2"; diff --git a/test/langtools/jdk/javadoc/doclet/testCompletionFailure/TestCompletionFailure.java b/test/langtools/jdk/javadoc/doclet/testCompletionFailure/TestCompletionFailure.java index 1cafc76ebac..cc9d9d6b02f 100644 --- a/test/langtools/jdk/javadoc/doclet/testCompletionFailure/TestCompletionFailure.java +++ b/test/langtools/jdk/javadoc/doclet/testCompletionFailure/TestCompletionFailure.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 8027977 * @summary Test to verify javadoc executes without CompletionFailure exception. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCompletionFailure */ +import javadoc.tester.JavadocTester; + public class TestCompletionFailure extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestCompletionFailure extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg1"); diff --git a/test/langtools/jdk/javadoc/doclet/testConstantValuesPage/TestConstantValuesPage.java b/test/langtools/jdk/javadoc/doclet/testConstantValuesPage/TestConstantValuesPage.java index d1371f1c589..5a3bb1c6a51 100644 --- a/test/langtools/jdk/javadoc/doclet/testConstantValuesPage/TestConstantValuesPage.java +++ b/test/langtools/jdk/javadoc/doclet/testConstantValuesPage/TestConstantValuesPage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure that constant values page does not get * generated when doclet has nothing to document. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestConstantValuesPage */ +import javadoc.tester.JavadocTester; + public class TestConstantValuesPage extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestConstantValuesPage extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "foo"); diff --git a/test/langtools/jdk/javadoc/doclet/testConstructorIndent/TestConstructorIndent.java b/test/langtools/jdk/javadoc/doclet/testConstructorIndent/TestConstructorIndent.java index 32d9e8fc627..c9b0009d796 100644 --- a/test/langtools/jdk/javadoc/doclet/testConstructorIndent/TestConstructorIndent.java +++ b/test/langtools/jdk/javadoc/doclet/testConstructorIndent/TestConstructorIndent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary The constructor comments should be surrounded by *
      . Check for this in the output. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestConstructorIndent */ +import javadoc.tester.JavadocTester; + public class TestConstructorIndent extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestConstructorIndent extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testConstructors/TestConstructors.java b/test/langtools/jdk/javadoc/doclet/testConstructors/TestConstructors.java index 9c52accb2af..825de46bc0a 100644 --- a/test/langtools/jdk/javadoc/doclet/testConstructors/TestConstructors.java +++ b/test/langtools/jdk/javadoc/doclet/testConstructors/TestConstructors.java @@ -26,12 +26,14 @@ * @bug 8025524 8031625 8081854 8175200 8186332 8182765 * @summary Test for constructor name which should be a non-qualified name. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestConstructors */ +import javadoc.tester.JavadocTester; + public class TestConstructors extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestConstructors extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg1"); @@ -90,7 +92,7 @@ public class TestConstructors extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java b/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java index a5f9d09f7de..80909a50829 100644 --- a/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java +++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java @@ -25,12 +25,14 @@ * @test * @bug 8157349 8185985 8194953 * @summary test copy of doc-files, and its contents for HTML meta content. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestCopyFiles */ +import javadoc.tester.JavadocTester; + public class TestCopyFiles extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInModulePackages() { + public void testDocFilesInModulePackages() { javadoc("-d", "modules-out", "-top", "phi-TOP-phi", "-bottom", "phi-BOTTOM-phi", @@ -75,7 +77,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInMultiModulePackagesWithRecursiveCopy() { + public void testDocFilesInMultiModulePackagesWithRecursiveCopy() { javadoc("-d", "multi-modules-out-recursive", "-docfilessubdirs", "-top", "phi-TOP-phi", @@ -134,7 +136,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInModulePackagesWithRecursiveCopy() { + public void testDocFilesInModulePackagesWithRecursiveCopy() { javadoc("-d", "modules-out-recursive", "-docfilessubdirs", "--module-source-path", testSrc("modules"), @@ -147,7 +149,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInModulePackagesWithRecursiveCopyWithExclusion() { + public void testDocFilesInModulePackagesWithRecursiveCopyWithExclusion() { javadoc("-d", "modules-out-recursive-with-exclusion", "-docfilessubdirs", "-excludedocfilessubdir", "sub-dir", @@ -161,7 +163,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInPackages() { + public void testDocFilesInPackages() { javadoc("-d", "packages-out", "-sourcepath", testSrc("packages"), "p1"); @@ -172,7 +174,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInPackagesWithRecursiveCopy() { + public void testDocFilesInPackagesWithRecursiveCopy() { javadoc("-d", "packages-out-recursive", "-docfilessubdirs", "-sourcepath", testSrc("packages"), @@ -190,7 +192,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInPackagesWithRecursiveCopyWithExclusion() { + public void testDocFilesInPackagesWithRecursiveCopyWithExclusion() { javadoc("-d", "packages-out-recursive-with-exclusion", "-docfilessubdirs", "-excludedocfilessubdir", "sub-dir", @@ -204,7 +206,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInUnnamedPackages() { + public void testDocFilesInUnnamedPackages() { javadoc("-d", "unnamed-out", "-windowtitle", "phi-WINDOW-TITLE-phi", "-sourcepath", testSrc("unnamed"), @@ -218,7 +220,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInUnnamedPackagesWithRecursiveCopy() { + public void testDocFilesInUnnamedPackagesWithRecursiveCopy() { javadoc("-d", "unnamed-out-recursive", "-docfilessubdirs", "-windowtitle", "phi-WINDOW-TITLE-phi", @@ -237,7 +239,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInPackagesSource7() { + public void testDocFilesInPackagesSource7() { javadoc("-d", "packages-out-src7", "-source", "7", "-sourcepath", testSrc("packages"), @@ -249,7 +251,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testDocFilesInPackagesSource7UsingClassPath() { + public void testDocFilesInPackagesSource7UsingClassPath() { javadoc("-d", "packages-out-src7-cp", "-source", "7", "-classpath", testSrc("packages"), @@ -261,7 +263,7 @@ public class TestCopyFiles extends JavadocTester { } @Test - void testCopyThrough() { + public void testCopyThrough() { javadoc("-d", "copy", "-sourcepath", testSrc("packages"), "p2"); diff --git a/test/langtools/jdk/javadoc/doclet/testDeprecatedDocs/TestDeprecatedDocs.java b/test/langtools/jdk/javadoc/doclet/testDeprecatedDocs/TestDeprecatedDocs.java index f122b719aed..99800dd77f9 100644 --- a/test/langtools/jdk/javadoc/doclet/testDeprecatedDocs/TestDeprecatedDocs.java +++ b/test/langtools/jdk/javadoc/doclet/testDeprecatedDocs/TestDeprecatedDocs.java @@ -27,12 +27,14 @@ * 8169819 8074407 8191030 8182765 8184205 * @summary test generated docs for deprecated items * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDeprecatedDocs */ +import javadoc.tester.JavadocTester; + public class TestDeprecatedDocs extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestDeprecatedDocs extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -299,7 +301,7 @@ public class TestDeprecatedDocs extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testDocEncoding/TestDocEncoding.java b/test/langtools/jdk/javadoc/doclet/testDocEncoding/TestDocEncoding.java index 111bce9d2d1..2e3fe1f6f9b 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocEncoding/TestDocEncoding.java +++ b/test/langtools/jdk/javadoc/doclet/testDocEncoding/TestDocEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -31,14 +31,16 @@ * @summary Run tests on -docencoding to see if the value is used for stylesheet as well. * @author jayashree viswanathan - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocEncoding */ import java.nio.charset.Charset; +import javadoc.tester.JavadocTester; + public class TestDocEncoding extends JavadocTester { public static void main(String... args) throws Exception { @@ -47,7 +49,7 @@ public class TestDocEncoding extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-docencoding", "Cp930", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testDocErrorReporter/TestDocErrorReporter.java b/test/langtools/jdk/javadoc/doclet/testDocErrorReporter/TestDocErrorReporter.java index 27fc752d27d..894d6f45673 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocErrorReporter/TestDocErrorReporter.java +++ b/test/langtools/jdk/javadoc/doclet/testDocErrorReporter/TestDocErrorReporter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary Make sure that option validation errors and sent to the * DocErrorReporter. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocErrorReporter */ +import javadoc.tester.JavadocTester; + public class TestDocErrorReporter extends JavadocTester { /** @@ -46,7 +48,7 @@ public class TestDocErrorReporter extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-encoding", "xyz", diff --git a/test/langtools/jdk/javadoc/doclet/testDocFileDir/TestDocFileDir.java b/test/langtools/jdk/javadoc/doclet/testDocFileDir/TestDocFileDir.java index ce2df24e5c4..43b52273feb 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocFileDir/TestDocFileDir.java +++ b/test/langtools/jdk/javadoc/doclet/testDocFileDir/TestDocFileDir.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -29,12 +29,14 @@ * directory. * Also test that -docfilessubdirs and -excludedocfilessubdir both work. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocFileDir */ +import javadoc.tester.JavadocTester; + public class TestDocFileDir extends JavadocTester { public static void main(String... args) throws Exception { @@ -44,7 +46,7 @@ public class TestDocFileDir extends JavadocTester { // Output dir = "", Input dir = "" @Test - void test1() { + public void test1() { copyDir(testSrc("pkg"), "."); setOutputDirectoryCheck(DirectoryCheck.NO_HTML_FILES); javadoc("pkg/C.java"); @@ -55,7 +57,7 @@ public class TestDocFileDir extends JavadocTester { // Output dir = Input Dir @Test - void test2() { + public void test2() { String outdir = "out2"; copyDir(testSrc("pkg"), outdir); setOutputDirectoryCheck(DirectoryCheck.NO_HTML_FILES); @@ -69,7 +71,7 @@ public class TestDocFileDir extends JavadocTester { // Exercising -docfilessubdirs and -excludedocfilessubdir @Test - void test3() { + public void test3() { String outdir = "out3"; setOutputDirectoryCheck(DirectoryCheck.NONE); javadoc("-d", outdir, diff --git a/test/langtools/jdk/javadoc/doclet/testDocFiles/TestDocFiles.java b/test/langtools/jdk/javadoc/doclet/testDocFiles/TestDocFiles.java index ec0863cf76e..899367b605e 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocFiles/TestDocFiles.java +++ b/test/langtools/jdk/javadoc/doclet/testDocFiles/TestDocFiles.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @bug 8008949 * @summary verify that doc-files get copied - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocFiles */ +import javadoc.tester.JavadocTester; + public class TestDocFiles extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestDocFiles extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testDocRootInlineTag/TestDocRootInlineTag.java b/test/langtools/jdk/javadoc/doclet/testDocRootInlineTag/TestDocRootInlineTag.java index 5045f92e7d3..a6a9122cf42 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocRootInlineTag/TestDocRootInlineTag.java +++ b/test/langtools/jdk/javadoc/doclet/testDocRootInlineTag/TestDocRootInlineTag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -28,12 +28,14 @@ * If docRoot performs as documented, the test passes. * Make sure that the docRoot tag works with the -bottom option. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocRootInlineTag */ +import javadoc.tester.JavadocTester; + public class TestDocRootInlineTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestDocRootInlineTag extends JavadocTester { } @Test - void test() { + public void test() { String uri = "http://www.java.sun.com/j2se/1.4/docs/api"; javadoc("-bottom", "The value of @docRoot is \"{@docRoot}\"", diff --git a/test/langtools/jdk/javadoc/doclet/testDocRootLink/TestDocRootLink.java b/test/langtools/jdk/javadoc/doclet/testDocRootLink/TestDocRootLink.java index 6a9ef4feded..508aee0a814 100644 --- a/test/langtools/jdk/javadoc/doclet/testDocRootLink/TestDocRootLink.java +++ b/test/langtools/jdk/javadoc/doclet/testDocRootLink/TestDocRootLink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,13 @@ * @bug 6553182 8025416 8029504 * @summary This test verifies the -Xdocrootparent option. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDocRootLink */ +import javadoc.tester.JavadocTester; + public class TestDocRootLink extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestDocRootLink extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "pkg1", "pkg2"); @@ -71,7 +73,7 @@ public class TestDocRootLink extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-Xdocrootparent", "http://download.oracle.com/javase/7/docs", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testDupParamWarn/TestDupParamWarn.java b/test/langtools/jdk/javadoc/doclet/testDupParamWarn/TestDupParamWarn.java index 7127cdc4e77..c0110a9a762 100644 --- a/test/langtools/jdk/javadoc/doclet/testDupParamWarn/TestDupParamWarn.java +++ b/test/langtools/jdk/javadoc/doclet/testDupParamWarn/TestDupParamWarn.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to ensure that the doclet does not print out bad * warning messages about duplicate param tags. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestDupParamWarn */ +import javadoc.tester.JavadocTester; + public class TestDupParamWarn extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestDupParamWarn extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testEmptyClass/TestEmptyClass.java b/test/langtools/jdk/javadoc/doclet/testEmptyClass/TestEmptyClass.java index 54d2d85da8d..eea227c8e59 100644 --- a/test/langtools/jdk/javadoc/doclet/testEmptyClass/TestEmptyClass.java +++ b/test/langtools/jdk/javadoc/doclet/testEmptyClass/TestEmptyClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure that Javadoc behaves properly when * run on a completely empty class (no comments or members). * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestEmptyClass */ +import javadoc.tester.JavadocTester; + public class TestEmptyClass extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestEmptyClass extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-classpath", testSrc("src"), "-d", "out", "-sourcepath", testSrc("src"), diff --git a/test/langtools/jdk/javadoc/doclet/testEnclosingClass/TestEnclosingClass.java b/test/langtools/jdk/javadoc/doclet/testEnclosingClass/TestEnclosingClass.java index 0673d3ba0ec..a3deedab189 100644 --- a/test/langtools/jdk/javadoc/doclet/testEnclosingClass/TestEnclosingClass.java +++ b/test/langtools/jdk/javadoc/doclet/testEnclosingClass/TestEnclosingClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 5008230 * @summary Check the outer class when documenting enclosing class/interface. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestEnclosingClass */ +import javadoc.tester.JavadocTester; + public class TestEnclosingClass extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestEnclosingClass extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testEncoding/TestEncoding.java b/test/langtools/jdk/javadoc/doclet/testEncoding/TestEncoding.java index 4f8326b65e9..45684e24f59 100644 --- a/test/langtools/jdk/javadoc/doclet/testEncoding/TestEncoding.java +++ b/test/langtools/jdk/javadoc/doclet/testEncoding/TestEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary This test determines if the value of the -encoding option is * properly passed from Javadoc to the source file parser. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestEncoding */ +import javadoc.tester.JavadocTester; + public class TestEncoding extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestEncoding extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-encoding", "iso-8859-1", diff --git a/test/langtools/jdk/javadoc/doclet/testEnumConstructor/TestEnumConstructor.java b/test/langtools/jdk/javadoc/doclet/testEnumConstructor/TestEnumConstructor.java index f3b7a7151a8..76d7a5c5c45 100644 --- a/test/langtools/jdk/javadoc/doclet/testEnumConstructor/TestEnumConstructor.java +++ b/test/langtools/jdk/javadoc/doclet/testEnumConstructor/TestEnumConstructor.java @@ -25,9 +25,9 @@ * @test * @bug 8202624 * @summary javadoc generates references to enum constructors, which are not documented - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestEnumConstructor */ @@ -37,6 +37,8 @@ import java.nio.file.Paths; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestEnumConstructor extends JavadocTester { final ToolBox tb; @@ -51,7 +53,7 @@ public class TestEnumConstructor extends JavadocTester { } @Test - void test1(Path base) throws Exception { + public void test1(Path base) throws Exception { Path srcDir = base.resolve("src"); createEnum(srcDir); @@ -72,7 +74,7 @@ public class TestEnumConstructor extends JavadocTester { } @Test - void test2(Path base) throws Exception { + public void test2(Path base) throws Exception { Path srcDir = base.resolve("src"); createEnum(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testExternalOverridenMethod/TestExternalOverridenMethod.java b/test/langtools/jdk/javadoc/doclet/testExternalOverridenMethod/TestExternalOverridenMethod.java index 57389873191..4c1266437b3 100644 --- a/test/langtools/jdk/javadoc/doclet/testExternalOverridenMethod/TestExternalOverridenMethod.java +++ b/test/langtools/jdk/javadoc/doclet/testExternalOverridenMethod/TestExternalOverridenMethod.java @@ -28,11 +28,13 @@ * are documented properly. The method should still include "implements" or * "overrides" documentation even though the method is external. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester TestExternalOverridenMethod + * @build javadoc.tester.* TestExternalOverridenMethod * @run main TestExternalOverridenMethod */ +import javadoc.tester.JavadocTester; + public class TestExternalOverridenMethod extends JavadocTester { static final String uri = "http://java.sun.com/j2se/1.4.1/docs/api"; @@ -43,7 +45,7 @@ public class TestExternalOverridenMethod extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-source","8", "-sourcepath", testSrc, @@ -66,7 +68,7 @@ public class TestExternalOverridenMethod extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-source", "8", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testFramesNoFrames/TestFramesNoFrames.java b/test/langtools/jdk/javadoc/doclet/testFramesNoFrames/TestFramesNoFrames.java index 00760e7c454..49f7492ad49 100644 --- a/test/langtools/jdk/javadoc/doclet/testFramesNoFrames/TestFramesNoFrames.java +++ b/test/langtools/jdk/javadoc/doclet/testFramesNoFrames/TestFramesNoFrames.java @@ -25,13 +25,13 @@ * @test * @bug 8162353 8164747 8173707 8196202 8204303 8184205 * @summary javadoc should provide a way to disable use of frames - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.tool * @build toolbox.ModuleBuilder toolbox.ToolBox - * @build JavadocTester + * @build javadoc.tester.* * @run main TestFramesNoFrames */ @@ -46,6 +46,8 @@ import java.util.stream.Collectors; import toolbox.ModuleBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestFramesNoFrames extends JavadocTester { public static void main(String... args) throws Exception { @@ -156,7 +158,7 @@ public class TestFramesNoFrames extends JavadocTester { } @Test - void testClass(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws Exception { + public void testClass(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws Exception { javadoc(base, fKind, oKind, hKind, gensrcPackages.resolve("p1/P1C1.java").toString()); @@ -166,7 +168,7 @@ public class TestFramesNoFrames extends JavadocTester { } @Test - void testClasses(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { + public void testClasses(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { javadoc(base, fKind, oKind, hKind, gensrcPackages.resolve("p1/P1C1.java").toString(), gensrcPackages.resolve("p1/P1C2.java").toString(), @@ -178,7 +180,7 @@ public class TestFramesNoFrames extends JavadocTester { } @Test - void testPackage(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { + public void testPackage(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { javadoc(base, fKind, oKind, hKind, "-sourcepath", gensrcPackages.toString(), "p1"); @@ -189,7 +191,7 @@ public class TestFramesNoFrames extends JavadocTester { } @Test - void testPackages(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { + public void testPackages(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { javadoc(base, fKind, oKind, hKind, "-sourcepath", gensrcPackages.toString(), "p1", "p2", "p3"); @@ -202,7 +204,7 @@ public class TestFramesNoFrames extends JavadocTester { } @Test - void testModules(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { + public void testModules(Path base, FrameKind fKind, OverviewKind oKind, HtmlKind hKind) throws IOException { javadoc(base, fKind, oKind, hKind, "--module-source-path", gensrcModules.toString(), "--module", "m1,m2,m3"); diff --git a/test/langtools/jdk/javadoc/doclet/testGeneratedBy/TestGeneratedBy.java b/test/langtools/jdk/javadoc/doclet/testGeneratedBy/TestGeneratedBy.java index 2697a29baec..facfd2e33b2 100644 --- a/test/langtools/jdk/javadoc/doclet/testGeneratedBy/TestGeneratedBy.java +++ b/test/langtools/jdk/javadoc/doclet/testGeneratedBy/TestGeneratedBy.java @@ -25,12 +25,14 @@ * @test * @bug 8000418 8024288 8196202 * @summary Verify that files use a common Generated By string - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestGeneratedBy */ +import javadoc.tester.JavadocTester; + public class TestGeneratedBy extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestGeneratedBy extends JavadocTester { } @Test - void testTimestamp() { + public void testTimestamp() { javadoc("-d", "out-timestamp", "--frames", "-sourcepath", testSrc, @@ -51,7 +53,7 @@ public class TestGeneratedBy extends JavadocTester { } @Test - void testNoTimestamp() { + public void testNoTimestamp() { javadoc("-d", "out-notimestamp", "-notimestamp", "--frames", diff --git a/test/langtools/jdk/javadoc/doclet/testGenericMethodLinkTaglet/TestGenericMethodLinkTaglet.java b/test/langtools/jdk/javadoc/doclet/testGenericMethodLinkTaglet/TestGenericMethodLinkTaglet.java index fe14aec62f6..00d49cb2e53 100644 --- a/test/langtools/jdk/javadoc/doclet/testGenericMethodLinkTaglet/TestGenericMethodLinkTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testGenericMethodLinkTaglet/TestGenericMethodLinkTaglet.java @@ -25,9 +25,9 @@ * @test * @bug 8188248 * @summary NullPointerException on generic methods - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestGenericMethodLinkTaglet */ @@ -38,6 +38,8 @@ import builder.ClassBuilder; import builder.ClassBuilder.MethodBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestGenericMethodLinkTaglet extends JavadocTester { final ToolBox tb; @@ -52,7 +54,7 @@ public class TestGenericMethodLinkTaglet extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testGrandParentTypes/TestGrandParentTypes.java b/test/langtools/jdk/javadoc/doclet/testGrandParentTypes/TestGrandParentTypes.java index 5a9a3ac51dd..ab74d24b1a8 100644 --- a/test/langtools/jdk/javadoc/doclet/testGrandParentTypes/TestGrandParentTypes.java +++ b/test/langtools/jdk/javadoc/doclet/testGrandParentTypes/TestGrandParentTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -26,12 +26,14 @@ * @bug 8182108 * @summary Verify that grand parent interface types are correct, and * various interface related sections are correctly generated. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestGrandParentTypes */ +import javadoc.tester.JavadocTester; + public class TestGrandParentTypes extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestGrandParentTypes extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-package", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testGroupName/TestGroupName.java b/test/langtools/jdk/javadoc/doclet/testGroupName/TestGroupName.java index 73a3fa507a6..6880b152c4e 100644 --- a/test/langtools/jdk/javadoc/doclet/testGroupName/TestGroupName.java +++ b/test/langtools/jdk/javadoc/doclet/testGroupName/TestGroupName.java @@ -25,9 +25,9 @@ * @test * @bug 8190003 8196201 8196202 8184205 * @summary Special characters in group names should be escaped - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestGroupName */ @@ -35,7 +35,8 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ToolBox; public class TestGroupName extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testGroupOption/TestGroupOption.java b/test/langtools/jdk/javadoc/doclet/testGroupOption/TestGroupOption.java index 5f97716907d..c751ca1ab70 100644 --- a/test/langtools/jdk/javadoc/doclet/testGroupOption/TestGroupOption.java +++ b/test/langtools/jdk/javadoc/doclet/testGroupOption/TestGroupOption.java @@ -27,12 +27,14 @@ * @summary Test to make sure the -group option works correctly * with the given pattern usages. * @author jamieh - * @library ../lib - * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @library ../../lib + * @modules jdk.javadoc/jdk.javadoc.internal.tool + * @build javadoc.tester.* * @run main TestGroupOption */ +import javadoc.tester.JavadocTester; + public class TestGroupOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestGroupOption extends JavadocTester { } @Test - void test1() { + public void test1() { // Make sure the warning is not printed when -group is used correctly. javadoc("-d", "out-1", "-sourcepath", testSrc, @@ -58,7 +60,7 @@ public class TestGroupOption extends JavadocTester { @Test // Make sure the "Other packages" section is printed and the header for empty section is not. // Make sure that the headers of group that is defined using patterns are printed. - void test2() { + public void test2() { javadoc("-d", "out-2", "--frames", "-sourcepath", testSrc, @@ -74,7 +76,7 @@ public class TestGroupOption extends JavadocTester { } @Test - void test3() { + public void test3() { // Make sure the warning is printed when -group is not used correctly. javadoc("-d", "out-3", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testHeadTag/TestHeadTag.java b/test/langtools/jdk/javadoc/doclet/testHeadTag/TestHeadTag.java index 046c3592f5f..5daece39616 100644 --- a/test/langtools/jdk/javadoc/doclet/testHeadTag/TestHeadTag.java +++ b/test/langtools/jdk/javadoc/doclet/testHeadTag/TestHeadTag.java @@ -25,9 +25,9 @@ * @test * @bug 8203792 * @summary Remove "compatibility" features from Head.java - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestHeadTag */ @@ -39,6 +39,8 @@ import java.time.LocalDate; import builder.ClassBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestHeadTag extends JavadocTester { final ToolBox tb; @@ -53,7 +55,7 @@ public class TestHeadTag extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(srcDir); @@ -70,7 +72,7 @@ public class TestHeadTag extends JavadocTester { } @Test - void testWithNoTimestamp(Path base) throws Exception { + public void testWithNoTimestamp(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testHeadings/TestHeadings.java b/test/langtools/jdk/javadoc/doclet/testHeadings/TestHeadings.java index b364378553d..1336f1b6afd 100644 --- a/test/langtools/jdk/javadoc/doclet/testHeadings/TestHeadings.java +++ b/test/langtools/jdk/javadoc/doclet/testHeadings/TestHeadings.java @@ -26,13 +26,15 @@ * @bug 4905786 6259611 8162363 8196202 * @summary Make sure that headings use the TH tag instead of the TD tag. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @build TestHeadings * @run main TestHeadings */ +import javadoc.tester.JavadocTester; + public class TestHeadings extends JavadocTester { private static final String[][] TEST = { @@ -58,7 +60,7 @@ public class TestHeadings extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-use", diff --git a/test/langtools/jdk/javadoc/doclet/testHelpFile/TestHelpFile.java b/test/langtools/jdk/javadoc/doclet/testHelpFile/TestHelpFile.java index 43d743fdc0c..49f99442749 100644 --- a/test/langtools/jdk/javadoc/doclet/testHelpFile/TestHelpFile.java +++ b/test/langtools/jdk/javadoc/doclet/testHelpFile/TestHelpFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 7132631 * @summary Make sure that the help file is generated correctly. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHelpFile */ +import javadoc.tester.JavadocTester; + public class TestHelpFile extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestHelpFile extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("TestHelpFile.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testHelpOption/TestHelpOption.java b/test/langtools/jdk/javadoc/doclet/testHelpOption/TestHelpOption.java index a5b23cdaa08..63cf4bf845f 100644 --- a/test/langtools/jdk/javadoc/doclet/testHelpOption/TestHelpOption.java +++ b/test/langtools/jdk/javadoc/doclet/testHelpOption/TestHelpOption.java @@ -26,15 +26,17 @@ * @bug 4934778 4777599 6553182 8146427 8146475 8175055 8185371 * @summary Make sure that --help, -helpfile and -nohelp options work correctly. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester TestHelpOption + * @build javadoc.tester.* TestHelpOption * @run main TestHelpOption */ import java.util.*; import java.util.stream.*; +import javadoc.tester.JavadocTester; + public class TestHelpOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testLineLengths() { + public void testLineLengths() { javadoc("-d", "out1", "-sourcepath", testSrc, "-X", @@ -63,7 +65,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testWithOption() { + public void testWithOption() { javadoc("-d", "out1", "-sourcepath", testSrc, "--help", @@ -74,7 +76,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testWithoutOption() { + public void testWithoutOption() { javadoc("-d", "out2", "-sourcepath", testSrc, testSrc("Sample.java")); @@ -82,7 +84,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testNohelpOption() { + public void testNohelpOption() { javadoc("-d", "out3", "-sourcepath", testSrc, "-nohelp", @@ -92,7 +94,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testHelpfileOption() { + public void testHelpfileOption() { javadoc("-d", "out4", "-sourcepath", testSrc, "-helpfile", testSrc("test-help.html"), @@ -105,7 +107,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testHelpfileReuseOption() { + public void testHelpfileReuseOption() { javadoc("-d", "out5", "-sourcepath", testSrc, "-helpfile", testSrc("test-help.html"), @@ -115,7 +117,7 @@ public class TestHelpOption extends JavadocTester { } @Test - void testHelpfileNohelpConflict() { + public void testHelpfileNohelpConflict() { javadoc("-d", "out6", "-sourcepath", testSrc, "-helpfile", testSrc("test-help.html"), diff --git a/test/langtools/jdk/javadoc/doclet/testHiddenMembers/TestHiddenMembers.java b/test/langtools/jdk/javadoc/doclet/testHiddenMembers/TestHiddenMembers.java index 69e2d3ed074..2781e3900a3 100644 --- a/test/langtools/jdk/javadoc/doclet/testHiddenMembers/TestHiddenMembers.java +++ b/test/langtools/jdk/javadoc/doclet/testHiddenMembers/TestHiddenMembers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure that hidden overriden members are not * documented as inherited. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHiddenMembers */ +import javadoc.tester.JavadocTester; + public class TestHiddenMembers extends JavadocTester { private static final String[][] NEGATED_TEST = { @@ -49,7 +51,7 @@ public class TestHiddenMembers extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testHiddenTag/TestHiddenTag.java b/test/langtools/jdk/javadoc/doclet/testHiddenTag/TestHiddenTag.java index 999efbd8bec..1a19ffa60f5 100644 --- a/test/langtools/jdk/javadoc/doclet/testHiddenTag/TestHiddenTag.java +++ b/test/langtools/jdk/javadoc/doclet/testHiddenTag/TestHiddenTag.java @@ -25,12 +25,14 @@ * @test * @bug 8073100 8182765 8196202 * @summary ensure the hidden tag works as intended - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHiddenTag */ +import javadoc.tester.JavadocTester; + public class TestHiddenTag extends JavadocTester { public static void main(String... args) throws Exception { diff --git a/test/langtools/jdk/javadoc/doclet/testHref/TestHref.java b/test/langtools/jdk/javadoc/doclet/testHref/TestHref.java index a860663482e..b3b48442da2 100644 --- a/test/langtools/jdk/javadoc/doclet/testHref/TestHref.java +++ b/test/langtools/jdk/javadoc/doclet/testHref/TestHref.java @@ -26,12 +26,14 @@ * @bug 4663254 8016328 8025633 8026567 8081854 8182765 8205593 * @summary Verify that spaces do not appear in hrefs and anchors. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHref */ +import javadoc.tester.JavadocTester; + public class TestHref extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestHref extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", "-source", "8", @@ -83,7 +85,7 @@ public class TestHref extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-Xdoclint:none", "-d", "out-html4", "-source", "8", diff --git a/test/langtools/jdk/javadoc/doclet/testHrefInDocComment/TestHrefInDocComment.java b/test/langtools/jdk/javadoc/doclet/testHrefInDocComment/TestHrefInDocComment.java index 9b6d8287878..fef07634608 100644 --- a/test/langtools/jdk/javadoc/doclet/testHrefInDocComment/TestHrefInDocComment.java +++ b/test/langtools/jdk/javadoc/doclet/testHrefInDocComment/TestHrefInDocComment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Determine if Hrefs are processed properly when they * appear in doc comments. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHrefInDocComment */ +import javadoc.tester.JavadocTester; + public class TestHrefInDocComment extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestHrefInDocComment extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlComments/TestHtmlComments.java b/test/langtools/jdk/javadoc/doclet/testHtmlComments/TestHtmlComments.java index f865a680b4b..0ce5d7c6fee 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlComments/TestHtmlComments.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlComments/TestHtmlComments.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary The field detail comment should not show up in the output if there * are no fields to document. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlComments */ +import javadoc.tester.JavadocTester; + public class TestHtmlComments extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestHtmlComments extends JavadocTester { } @Test - void run() { + public void run() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlDefinitionListTag/TestHtmlDefinitionListTag.java b/test/langtools/jdk/javadoc/doclet/testHtmlDefinitionListTag/TestHtmlDefinitionListTag.java index 0c492d20fc5..cf6d295ad91 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlDefinitionListTag/TestHtmlDefinitionListTag.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlDefinitionListTag/TestHtmlDefinitionListTag.java @@ -26,9 +26,9 @@ * @bug 6786690 6820360 8025633 8026567 8175200 8183511 8186332 8074407 8182765 * @summary This test verifies the nesting of definition list tags. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlDefinitionListTag */ @@ -36,6 +36,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javadoc.tester.JavadocTester; + public class TestHtmlDefinitionListTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -44,7 +46,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_Comment_Deprecated() { + public void test_Comment_Deprecated() { // tester.run(ARGS1, TEST_ALL, NEGATED_TEST_NO_C5); // tester.runTestsOnHTML(NO_TEST, NEGATED_TEST_C5); // tester.runTestsOnHTML(TEST_CMNT_DEPR, NO_TEST); @@ -58,7 +60,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_Comment_Deprecated_html4() { + public void test_Comment_Deprecated_html4() { javadoc("-Xdoclint:none", "-d", "out-1-html4", "-html4", @@ -69,7 +71,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_NoComment_Deprecated() { + public void test_NoComment_Deprecated() { // tester.run(ARGS2, TEST_ALL, NEGATED_TEST_NO_C5); // tester.runTestsOnHTML(NO_TEST, NEGATED_TEST_C5); // tester.runTestsOnHTML(NO_TEST, TEST_CMNT_DEPR); @@ -84,7 +86,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_NoComment_Deprecated_html4() { + public void test_NoComment_Deprecated_html4() { javadoc("-Xdoclint:none", "-d", "out-2-html4", "-html4", @@ -96,7 +98,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_Comment_NoDeprecated() { + public void test_Comment_NoDeprecated() { // tester.run(ARGS3, TEST_ALL, NEGATED_TEST_NO_C5); // tester.runTestsOnHTML(TEST_NODEPR, TEST_NOCMNT_NODEPR); javadoc("-Xdoclint:none", @@ -111,7 +113,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void test_Comment_NoDeprecated_html4() { + public void test_Comment_NoDeprecated_html4() { javadoc("-Xdoclint:none", "-d", "out-3-html4", "-html4", @@ -124,7 +126,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void testNoCommentNoDeprecated() { + public void testNoCommentNoDeprecated() { // tester.run(ARGS4, TEST_ALL, NEGATED_TEST_NO_C5); // tester.runTestsOnHTML(TEST_NOCMNT_NODEPR, TEST_CMNT_DEPR); javadoc("-Xdoclint:none", @@ -140,7 +142,7 @@ public class TestHtmlDefinitionListTag extends JavadocTester { } @Test - void testNoCommentNoDeprecated_html4() { + public void testNoCommentNoDeprecated_html4() { javadoc("-Xdoclint:none", "-d", "out-4-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlDocument/TestHtmlDocument.java b/test/langtools/jdk/javadoc/doclet/testHtmlDocument/TestHtmlDocument.java index 27bdcfa4ce7..aeef437c28f 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlDocument/TestHtmlDocument.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlDocument/TestHtmlDocument.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,11 @@ * @test * @bug 6851834 * @summary This test verifies the HTML document generation for javadoc output. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.doclets.formats.html.markup * jdk.javadoc/jdk.javadoc.internal.doclets.toolkit.util * jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @author Bhavesh Patel * @run main TestHtmlDocument */ @@ -43,6 +43,8 @@ import static jdk.javadoc.internal.doclets.toolkit.util.DocletConstants.NL; * The class reads each file, complete with newlines, into a string to easily * compare the existing markup with the generated markup. */ +import javadoc.tester.JavadocTester; + public class TestHtmlDocument extends JavadocTester { // Entry point @@ -52,7 +54,7 @@ public class TestHtmlDocument extends JavadocTester { } @Test - void test() { + public void test() { checking("markup"); // Check whether the generated markup is same as the existing markup. String expected = readFile(testSrc, "testMarkup.html").replace("\n", NL); diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLankmarkRegions.java b/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLankmarkRegions.java index 111b8626ce2..11ff52fe5fa 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLankmarkRegions.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlLandmarkRegions/TestHtmlLankmarkRegions.java @@ -25,12 +25,12 @@ * @test * @bug 8210047 * @summary some pages contains content outside of landmark region - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlLankmarkRegions */ @@ -42,6 +42,8 @@ import builder.ClassBuilder; import toolbox.ModuleBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestHtmlLankmarkRegions extends JavadocTester { final ToolBox tb; @@ -56,7 +58,7 @@ public class TestHtmlLankmarkRegions extends JavadocTester { } @Test - void testModules(Path base) throws Exception { + public void testModules(Path base) throws Exception { Path srcDir = base.resolve("src"); createModules(srcDir); @@ -100,7 +102,7 @@ public class TestHtmlLankmarkRegions extends JavadocTester { } @Test - void testModulesHtml4(Path base) throws Exception { + public void testModulesHtml4(Path base) throws Exception { Path srcDir = base.resolve("src"); createModules(srcDir); @@ -136,7 +138,7 @@ public class TestHtmlLankmarkRegions extends JavadocTester { } @Test - void testPackages(Path base) throws Exception { + public void testPackages(Path base) throws Exception { Path srcDir = base.resolve("src"); createPackages(srcDir); @@ -170,7 +172,7 @@ public class TestHtmlLankmarkRegions extends JavadocTester { } @Test - void testPackagesHtml4(Path base) throws Exception { + public void testPackagesHtml4(Path base) throws Exception { Path srcDir = base.resolve("src"); createPackages(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlStrongTag/TestHtmlStrongTag.java b/test/langtools/jdk/javadoc/doclet/testHtmlStrongTag/TestHtmlStrongTag.java index ec4ccac1b33..ee8bc9e3f68 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlStrongTag/TestHtmlStrongTag.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlStrongTag/TestHtmlStrongTag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 6786028 8026567 * @summary This test verifies the use of HTML tag instead of by Javadoc std doclet. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlStrongTag */ +import javadoc.tester.JavadocTester; + public class TestHtmlStrongTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestHtmlStrongTag extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "pkg1"); @@ -58,7 +60,7 @@ public class TestHtmlStrongTag extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-sourcepath", testSrc, "pkg2"); diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlTableStyles/TestHtmlTableStyles.java b/test/langtools/jdk/javadoc/doclet/testHtmlTableStyles/TestHtmlTableStyles.java index feeba7b0321..925104dbb0b 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlTableStyles/TestHtmlTableStyles.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlTableStyles/TestHtmlTableStyles.java @@ -26,12 +26,14 @@ * @bug 8008164 8169819 8183037 8182765 8196202 8184205 * @summary Test styles on HTML tables generated by javadoc. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlTableStyles */ +import javadoc.tester.JavadocTester; + public class TestHtmlTableStyles extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestHtmlTableStyles extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-use", @@ -77,7 +79,7 @@ public class TestHtmlTableStyles extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlTableTags/TestHtmlTableTags.java b/test/langtools/jdk/javadoc/doclet/testHtmlTableTags/TestHtmlTableTags.java index ac06a13dfc9..63f3e1c98c5 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlTableTags/TestHtmlTableTags.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlTableTags/TestHtmlTableTags.java @@ -26,12 +26,14 @@ * @bug 6786688 8008164 8162363 8169819 8183037 8182765 8184205 * @summary HTML tables should have table summary, caption and table headers. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlTableTags */ +import javadoc.tester.JavadocTester; + public class TestHtmlTableTags extends JavadocTester { //Javadoc arguments. @@ -46,7 +48,7 @@ public class TestHtmlTableTags extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-use", @@ -60,7 +62,7 @@ public class TestHtmlTableTags extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlTag/TestHtmlTag.java b/test/langtools/jdk/javadoc/doclet/testHtmlTag/TestHtmlTag.java index ce573bbe718..f53975dd21a 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlTag/TestHtmlTag.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlTag/TestHtmlTag.java @@ -26,14 +26,16 @@ * @bug 6786682 4649116 8182765 * @summary This test verifies the use of lang attribute by . * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlTag */ import java.util.Locale; +import javadoc.tester.JavadocTester; + public class TestHtmlTag extends JavadocTester { private static final String defaultLanguage = Locale.getDefault().getLanguage(); public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestHtmlTag extends JavadocTester { tester.runTests(); } @Test - void test_default() { + public void test_default() { javadoc("-locale", defaultLanguage, "-d", "out-default", "-sourcepath", testSrc, @@ -60,7 +62,7 @@ public class TestHtmlTag extends JavadocTester { } @Test - void test_ja() { + public void test_ja() { // TODO: why does this test need/use pkg2; why can't it use pkg1 // like the other two tests, so that we can share the check methods? javadoc("-locale", "ja", @@ -80,7 +82,7 @@ public class TestHtmlTag extends JavadocTester { } @Test - void test_en_US() { + public void test_en_US() { javadoc("-locale", "en_US", "-d", "out-en_US", "-sourcepath", testSrc, @@ -98,7 +100,7 @@ public class TestHtmlTag extends JavadocTester { } @Test - void test_other() { + public void test_other() { javadoc("-locale", "en_US", "-d", "out-other", "-sourcepath", testSrc, @@ -195,7 +197,7 @@ public class TestHtmlTag extends JavadocTester { } @Test - void test_other_html4() { + public void test_other_html4() { javadoc("-locale", "en_US", "-d", "out-other-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java b/test/langtools/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java index 1c0aad0dd41..12f9ea1f60d 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java @@ -27,12 +27,14 @@ * 8202624 8210047 8184205 * @summary Test the version of HTML generated by the javadoc tool. * @author bpatel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlVersion */ +import javadoc.tester.JavadocTester; + public class TestHtmlVersion extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestHtmlVersion extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-private", "-linksource", @@ -56,7 +58,7 @@ public class TestHtmlVersion extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-html4", "-private", @@ -72,7 +74,7 @@ public class TestHtmlVersion extends JavadocTester { } @Test - void test3() { + public void test3() { javadoc("-d", "out-3", "-html4", "-private", @@ -88,7 +90,7 @@ public class TestHtmlVersion extends JavadocTester { } @Test - void test4() { + public void test4() { javadoc("-d", "out-4", "-private", "-linksource", diff --git a/test/langtools/jdk/javadoc/doclet/testHtmlWarning/TestHtmlWarning.java b/test/langtools/jdk/javadoc/doclet/testHtmlWarning/TestHtmlWarning.java index 03184eea797..79fb51bb11c 100644 --- a/test/langtools/jdk/javadoc/doclet/testHtmlWarning/TestHtmlWarning.java +++ b/test/langtools/jdk/javadoc/doclet/testHtmlWarning/TestHtmlWarning.java @@ -25,9 +25,9 @@ * @test * @bug 8194955 8182765 * @summary Warn when default HTML version is used. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestHtmlWarning */ @@ -36,6 +36,8 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import javadoc.tester.JavadocTester; + public class TestHtmlWarning extends JavadocTester { public static void main(String... args) throws Exception { @@ -54,7 +56,7 @@ public class TestHtmlWarning extends JavadocTester { + "in your comments are valid in HTML5, and remove the -html4 option."; @Test - void testHtml4() { + public void testHtml4() { javadoc("-d", "out-4", "-html4", testFile.toString()); @@ -64,7 +66,7 @@ public class TestHtmlWarning extends JavadocTester { } @Test - void testHtml5() { + public void testHtml5() { javadoc("-d", "out-5", "-html5", testFile.toString()); @@ -74,7 +76,7 @@ public class TestHtmlWarning extends JavadocTester { } @Test - void testDefault() { + public void testDefault() { javadoc("-d", "out-default", testFile.toString()); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testIOException/TestIOException.java b/test/langtools/jdk/javadoc/doclet/testIOException/TestIOException.java index 9db41724ae5..73bcb7ec924 100644 --- a/test/langtools/jdk/javadoc/doclet/testIOException/TestIOException.java +++ b/test/langtools/jdk/javadoc/doclet/testIOException/TestIOException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,15 +25,17 @@ * @test * @bug 8164130 * @summary test IOException handling - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIOException */ import java.io.File; import java.io.FileWriter; +import javadoc.tester.JavadocTester; + public class TestIOException extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestIOException extends JavadocTester { } @Test - void testReadOnlyDirectory() { + public void testReadOnlyDirectory() { File outDir = new File("out1"); if (!outDir.mkdir()) { throw new Error("Cannot create directory"); @@ -66,7 +68,7 @@ public class TestIOException extends JavadocTester { } @Test - void testReadOnlyFile() throws Exception { + public void testReadOnlyFile() throws Exception { File outDir = new File("out2"); if (!outDir.mkdir()) { throw new Error("Cannot create directory"); @@ -95,7 +97,7 @@ public class TestIOException extends JavadocTester { } @Test - void testReadOnlySubdirectory() throws Exception { + public void testReadOnlySubdirectory() throws Exception { // init source file File srcDir = new File("src4"); File src_p = new File(srcDir, "p"); @@ -133,7 +135,7 @@ public class TestIOException extends JavadocTester { } @Test - void testReadOnlyDocFilesDir() throws Exception { + public void testReadOnlyDocFilesDir() throws Exception { // init source files File srcDir = new File("src4"); File src_p = new File(srcDir, "p"); diff --git a/test/langtools/jdk/javadoc/doclet/testIncluded/TestIncluded.java b/test/langtools/jdk/javadoc/doclet/testIncluded/TestIncluded.java index 3b16b9085d3..a65ddc737f3 100644 --- a/test/langtools/jdk/javadoc/doclet/testIncluded/TestIncluded.java +++ b/test/langtools/jdk/javadoc/doclet/testIncluded/TestIncluded.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @bug 8149842 * @summary Verify that non included classes are not inspected. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIncluded */ +import javadoc.tester.JavadocTester; + public class TestIncluded extends JavadocTester { public static void main(String... args) throws Exception { @@ -44,7 +46,7 @@ public class TestIncluded extends JavadocTester { * an error, if doc comments are inspected. */ @Test - void test() { + public void test() { javadoc("-d", "out", "-Xdoclint:all", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testIndentation/TestIndentation.java b/test/langtools/jdk/javadoc/doclet/testIndentation/TestIndentation.java index 75eab65c3d6..d15886caef3 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndentation/TestIndentation.java +++ b/test/langtools/jdk/javadoc/doclet/testIndentation/TestIndentation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @bug 8011288 8062647 8175200 * @summary Erratic/inconsistent indentation of signatures - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIndentation */ +import javadoc.tester.JavadocTester; + public class TestIndentation extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestIndentation extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "p"); diff --git a/test/langtools/jdk/javadoc/doclet/testIndex/TestIndex.java b/test/langtools/jdk/javadoc/doclet/testIndex/TestIndex.java index 695d88d4bf5..fa6051aa764 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndex/TestIndex.java +++ b/test/langtools/jdk/javadoc/doclet/testIndex/TestIndex.java @@ -28,12 +28,14 @@ * Also test that index-all.html has the appropriate output. * Test for unnamed package in index. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIndex */ +import javadoc.tester.JavadocTester; + public class TestIndex extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestIndex extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "--frames", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testIndexFiles/TestIndexFiles.java b/test/langtools/jdk/javadoc/doclet/testIndexFiles/TestIndexFiles.java index 54caaae066d..a21f32e47b7 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndexFiles/TestIndexFiles.java +++ b/test/langtools/jdk/javadoc/doclet/testIndexFiles/TestIndexFiles.java @@ -26,12 +26,14 @@ * @bug 8170825 8196027 * @summary Perform tests on index files generated by javadoc. * @author bpatel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIndexFiles */ +import javadoc.tester.JavadocTester; + public class TestIndexFiles extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestIndexFiles extends JavadocTester { } @Test - void testIndexFiles() { + public void testIndexFiles() { javadoc("-d", "out", "-splitindex", "-Xdoclint:none", "-sourcepath", testSrc, "-use", "pkg"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java b/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java index 29e685dee00..4698184557d 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java +++ b/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java @@ -25,14 +25,16 @@ * @test * @bug 8213957 8213958 * @summary Test use of at-index in package-iinfo and doc-files - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestIndexInPackageFiles */ import java.io.IOException; import java.nio.file.Path; + +import javadoc.tester.JavadocTester; import toolbox.ToolBox; public class TestIndexInPackageFiles extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testIndexTaglet/TestIndexTaglet.java b/test/langtools/jdk/javadoc/doclet/testIndexTaglet/TestIndexTaglet.java index 988b0bc5809..fe7eb3b2f1f 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndexTaglet/TestIndexTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testIndexTaglet/TestIndexTaglet.java @@ -25,9 +25,9 @@ * @test * @bug 8202462 * @summary {@index} may cause duplicate labels - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestIndexTaglet */ @@ -39,6 +39,8 @@ import builder.ClassBuilder; import builder.ClassBuilder.MethodBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestIndexTaglet extends JavadocTester { final ToolBox tb; @@ -53,7 +55,7 @@ public class TestIndexTaglet extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); Path outDir = base.resolve("out"); @@ -83,7 +85,7 @@ public class TestIndexTaglet extends JavadocTester { } @Test - void testIndexWithinATag(Path base) throws Exception { + public void testIndexWithinATag(Path base) throws Exception { Path srcDir = base.resolve("src"); Path outDir = base.resolve("out"); diff --git a/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java b/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java index 6c353b91b9e..f4b33d1f63b 100644 --- a/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java +++ b/test/langtools/jdk/javadoc/doclet/testIndexWithModules/TestIndexWithModules.java @@ -25,12 +25,12 @@ * @test * @bug 8190875 * @summary modules not listed in overview/index page - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @build JavadocTester + * @build javadoc.tester.* * @run main TestIndexWithModules */ @@ -42,6 +42,8 @@ import toolbox.ModuleBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestIndexWithModules extends JavadocTester { final ToolBox tb; @@ -59,7 +61,7 @@ public class TestIndexWithModules extends JavadocTester { } @Test - void testIndexWithOverviewPath(Path base) throws Exception { + public void testIndexWithOverviewPath(Path base) throws Exception { Path out = base.resolve("out"); tb.writeFile("overview.html", @@ -80,7 +82,7 @@ public class TestIndexWithModules extends JavadocTester { //multiple modules with frames @Test - void testIndexWithMultipleModules1(Path base) throws Exception { + public void testIndexWithMultipleModules1(Path base) throws Exception { Path out = base.resolve("out"); javadoc("-d", out.toString(), "--module-source-path", src.toString(), @@ -100,7 +102,7 @@ public class TestIndexWithModules extends JavadocTester { //multiple modules with out frames @Test - void testIndexWithMultipleModules2(Path base) throws Exception { + public void testIndexWithMultipleModules2(Path base) throws Exception { Path out = base.resolve("out"); javadoc("-d", out.toString(), "--module-source-path", src.toString(), @@ -116,7 +118,7 @@ public class TestIndexWithModules extends JavadocTester { } @Test - void testIndexWithSingleModule(Path base) throws Exception { + public void testIndexWithSingleModule(Path base) throws Exception { Path out = base.resolve("out"); javadoc("-d", out.toString(), "--module-source-path", src.toString(), @@ -129,7 +131,7 @@ public class TestIndexWithModules extends JavadocTester { //no modules and multiple packages @Test - void testIndexWithNoModules1(Path base) throws Exception{ + public void testIndexWithNoModules1(Path base) throws Exception{ Path out = base.resolve("out"); new ClassBuilder(tb, "P1.A1") .setModifiers("public","class") @@ -154,7 +156,7 @@ public class TestIndexWithModules extends JavadocTester { //no modules and one package @Test - void testIndexWithNoModules2(Path base) throws Exception{ + public void testIndexWithNoModules2(Path base) throws Exception{ Path out = base.resolve("out"); new ClassBuilder(tb, "P1.A1") .setModifiers("public","class") diff --git a/test/langtools/jdk/javadoc/doclet/testInlineLinkLabel/TestInlineLinkLabel.java b/test/langtools/jdk/javadoc/doclet/testInlineLinkLabel/TestInlineLinkLabel.java index 1a921e38f2b..e9f4d8fc6c6 100644 --- a/test/langtools/jdk/javadoc/doclet/testInlineLinkLabel/TestInlineLinkLabel.java +++ b/test/langtools/jdk/javadoc/doclet/testInlineLinkLabel/TestInlineLinkLabel.java @@ -26,12 +26,14 @@ * @bug 4524136 * @summary Test to make sure label is used for inline links. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestInlineLinkLabel */ +import javadoc.tester.JavadocTester; + public class TestInlineLinkLabel extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestInlineLinkLabel extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testInterface/TestInterface.java b/test/langtools/jdk/javadoc/doclet/testInterface/TestInterface.java index e06582ac48e..f02ef6afb71 100644 --- a/test/langtools/jdk/javadoc/doclet/testInterface/TestInterface.java +++ b/test/langtools/jdk/javadoc/doclet/testInterface/TestInterface.java @@ -30,9 +30,9 @@ * If A implements I and B extends A, B should be in the list of * implementing classes in the documentation for I. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestInterface */ @@ -50,6 +50,8 @@ and Child */ +import javadoc.tester.JavadocTester; + public class TestInterface extends JavadocTester { public static void main(String... args) throws Exception { @@ -58,7 +60,7 @@ public class TestInterface extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -156,7 +158,7 @@ public class TestInterface extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, @@ -199,7 +201,7 @@ public class TestInterface extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "pkg1"); @@ -215,7 +217,7 @@ public class TestInterface extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out-1-html4", "-html4", "-sourcepath", testSrc, @@ -232,7 +234,7 @@ public class TestInterface extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-sourcepath", testSrc, "pkg2"); diff --git a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestFxProperties.java b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestFxProperties.java index 02d984cd584..14651bf1c71 100644 --- a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestFxProperties.java +++ b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestFxProperties.java @@ -26,9 +26,9 @@ * @bug 8025091 * @summary Tests the basic selection of FX related property methods, fields, * setters and getters, by executing this test in the strict mode. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester propgen.PropGen + * @build javadoc.tester.* propgen.PropGen * @run main TestFxProperties */ @@ -36,6 +36,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; + public class TestFxProperties extends JavadocTester { public static void main(String... args) throws Exception { @@ -59,7 +61,7 @@ public class TestFxProperties extends JavadocTester { } @Test - void test1() throws Exception { + public void test1() throws Exception { Path srcdir = Paths.get("src-propgen"); Files.createDirectory(srcdir); new propgen.PropGen(srcdir).run(); diff --git a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java index 2df4e835a4e..3ddfb21d848 100644 --- a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java +++ b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java @@ -28,12 +28,14 @@ * 8203791 8184205 * @summary Test of the JavaFX doclet features. * @author jvalenta - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestJavaFX */ +import javadoc.tester.JavadocTester; + public class TestJavaFX extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestJavaFX extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out1", "-sourcepath", testSrc, "-javafx", @@ -175,7 +177,7 @@ public class TestJavaFX extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out1-html4", "-html4", "-sourcepath", testSrc, @@ -203,7 +205,7 @@ public class TestJavaFX extends JavadocTester { * are treated correctly. */ @Test - void test2() { + public void test2() { javadoc("-d", "out2a", "-sourcepath", testSrc, "-javafx", @@ -262,7 +264,7 @@ public class TestJavaFX extends JavadocTester { } @Test - void test2_html4() { + public void test2_html4() { javadoc("-d", "out2a-html4", "-html4", "-sourcepath", testSrc, @@ -313,7 +315,7 @@ public class TestJavaFX extends JavadocTester { * are treated just like any other java method. */ @Test - void test3() { + public void test3() { javadoc("-d", "out2b", "-sourcepath", testSrc, "-package", @@ -355,7 +357,7 @@ public class TestJavaFX extends JavadocTester { } @Test - void test3_html4() { + public void test3_html4() { javadoc("-d", "out2b-html4", "-html4", "-sourcepath", testSrc, @@ -402,7 +404,7 @@ public class TestJavaFX extends JavadocTester { * --javafx flag. */ @Test - void test4() { + public void test4() { javadoc("-d", "out4", "--javafx", "--disable-javafx-strict-checks", diff --git a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFxMode.java b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFxMode.java index 48db42c8253..dbb67dc3bec 100644 --- a/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFxMode.java +++ b/test/langtools/jdk/javadoc/doclet/testJavaFX/TestJavaFxMode.java @@ -25,9 +25,9 @@ * @test * @bug 8208531 * @summary -javafx mode should be on by default when JavaFX is available. - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestJavaFxMode */ @@ -36,6 +36,8 @@ import toolbox.ToolBox; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; + public class TestJavaFxMode extends JavadocTester { final ToolBox tb; @@ -63,7 +65,7 @@ public class TestJavaFxMode extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path src = base.resolve("src"); createTestClass(src); Path outDir = base.resolve("out"); diff --git a/test/langtools/jdk/javadoc/doclet/testJavascript/TestJavascript.java b/test/langtools/jdk/javadoc/doclet/testJavascript/TestJavascript.java index db1e3c94bd3..aeb0fb63040 100644 --- a/test/langtools/jdk/javadoc/doclet/testJavascript/TestJavascript.java +++ b/test/langtools/jdk/javadoc/doclet/testJavascript/TestJavascript.java @@ -26,12 +26,14 @@ * @bug 4665566 4855876 7025314 8012375 8015997 8016328 8024756 8148985 8151921 8151743 8196202 * @summary Verify that the output has the right javascript. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestJavascript */ +import javadoc.tester.JavadocTester; + public class TestJavascript extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestJavascript extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "--frames", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testLambdaFeature/TestLambdaFeature.java b/test/langtools/jdk/javadoc/doclet/testLambdaFeature/TestLambdaFeature.java index f4699f83736..dbba43c3922 100644 --- a/test/langtools/jdk/javadoc/doclet/testLambdaFeature/TestLambdaFeature.java +++ b/test/langtools/jdk/javadoc/doclet/testLambdaFeature/TestLambdaFeature.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,9 @@ * @summary Make sure that the lambda feature changes work fine in * javadoc. * @author bpatel - * @library ../lib/ + * @library ../../lib/ * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester TestLambdaFeature + * @build javadoc.tester.* TestLambdaFeature * @run main TestLambdaFeature */ @@ -39,6 +39,8 @@ * removed [ 8022738 ] */ +import javadoc.tester.JavadocTester; + public class TestLambdaFeature extends JavadocTester { public static void main(String... args) throws Exception { @@ -47,7 +49,7 @@ public class TestLambdaFeature extends JavadocTester { } @Test - void testDefault() { + public void testDefault() { javadoc("-d", "out-default", "-sourcepath", testSrc, "pkg", "pkg1"); @@ -101,7 +103,7 @@ public class TestLambdaFeature extends JavadocTester { } @Test - void testSource7() { + public void testSource7() { javadoc("-d", "out-7", "-sourcepath", testSrc, "-source", "1.7", diff --git a/test/langtools/jdk/javadoc/doclet/testLeadingSpaces/LeadingSpaces.java b/test/langtools/jdk/javadoc/doclet/testLeadingSpaces/LeadingSpaces.java index 6b32f8aabef..fec2966bed6 100644 --- a/test/langtools/jdk/javadoc/doclet/testLeadingSpaces/LeadingSpaces.java +++ b/test/langtools/jdk/javadoc/doclet/testLeadingSpaces/LeadingSpaces.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -29,12 +29,14 @@ * begin their comment without a leading star without leading * spaces stripped * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main LeadingSpaces */ +import javadoc.tester.JavadocTester; + public class LeadingSpaces extends JavadocTester { /** * The entry point of the test. @@ -47,7 +49,7 @@ public class LeadingSpaces extends JavadocTester { } @Test - void testLeadingSpaces() { + public void testLeadingSpaces() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("LeadingSpaces.java")); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testLegacyTaglet/TestLegacyTaglet.java b/test/langtools/jdk/javadoc/doclet/testLegacyTaglet/TestLegacyTaglet.java index 84d3d3b2aed..28d0c4494ee 100644 --- a/test/langtools/jdk/javadoc/doclet/testLegacyTaglet/TestLegacyTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testLegacyTaglet/TestLegacyTaglet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary Test to ensure that the refactored version of the standard * doclet still works with Taglets that implement the 1.4.0 interface. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester ToDoTaglet UnderlineTaglet Check + * @build javadoc.tester.* ToDoTaglet UnderlineTaglet Check * @run main TestLegacyTaglet */ +import javadoc.tester.JavadocTester; + public class TestLegacyTaglet extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestLegacyTaglet extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-tagletpath", System.getProperty("test.classes", "."), diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestBadLinkOption.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestBadLinkOption.java index 0fca81bd4b5..41bbaf22da0 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestBadLinkOption.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestBadLinkOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 4625883 8180019 * @summary Make sure that bad -link arguments trigger errors. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestBadLinkOption */ +import javadoc.tester.JavadocTester; + public class TestBadLinkOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestBadLinkOption extends JavadocTester { } @Test - void test() { + public void test() { String out = "out"; javadoc("-d", out, "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOption.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOption.java index 42f983cd1a4..b9fe192ed77 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOption.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOption.java @@ -27,14 +27,16 @@ * @summary Test to make sure that -link and -linkoffline link to * right files, and URLs with and without trailing slash are accepted. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLinkOption */ import java.io.File; +import javadoc.tester.JavadocTester; + public class TestLinkOption extends JavadocTester { /** * The entry point of the test. @@ -50,7 +52,7 @@ public class TestLinkOption extends JavadocTester { // it generates. Therefore we run everything serially in a single @Test // method and not in independent @Test methods. @Test - void test() { + public void test() { String mylib = "mylib"; String[] javacArgs = { "-d", mylib, testSrc + "/extra/StringBuilder.java" diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOptionWithModule.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOptionWithModule.java index da96aff35b8..5a9fe3df096 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOptionWithModule.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestLinkOptionWithModule.java @@ -25,12 +25,12 @@ * @test * @bug 8205593 * @summary Javadoc -link makes broken links if module name matches package name - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLinkOptionWithModule */ @@ -43,6 +43,8 @@ import toolbox.ModuleBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestLinkOptionWithModule extends JavadocTester { final ToolBox tb; @@ -60,7 +62,7 @@ public class TestLinkOptionWithModule extends JavadocTester { } @Test - void testModuleLinkedToModule(Path base) throws Exception { + public void testModuleLinkedToModule(Path base) throws Exception { Path out1 = base.resolve("out1a"), out2 = base.resolve("out1b"); javadoc("-d", out1.toString(), @@ -79,7 +81,7 @@ public class TestLinkOptionWithModule extends JavadocTester { } @Test - void testPackageLinkedToPackage(Path base) throws Exception { + public void testPackageLinkedToPackage(Path base) throws Exception { Path out1 = base.resolve("out2a"), out2 = base.resolve("out2b"); javadoc("-d", out1.toString(), @@ -98,7 +100,7 @@ public class TestLinkOptionWithModule extends JavadocTester { } @Test - void testModuleLinkedToPackage(Path base) throws Exception { + public void testModuleLinkedToPackage(Path base) throws Exception { Path out1 = base.resolve("out3a"), out2 = base.resolve("out3b"); javadoc("-d", out1.toString(), @@ -117,7 +119,7 @@ public class TestLinkOptionWithModule extends JavadocTester { } @Test - void testPackageLinkedToModule(Path base) throws Exception { + public void testPackageLinkedToModule(Path base) throws Exception { Path out1 = base.resolve("out4a"), out2 = base.resolve("out4b"); javadoc("-d", out1.toString(), diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestNewLineInLink.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestNewLineInLink.java index 4801f3527ee..94600d74256 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestNewLineInLink.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestNewLineInLink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Make sure that a new line may act as a separator between * link and label. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNewLineInLink */ +import javadoc.tester.JavadocTester; + public class TestNewLineInLink extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestNewLineInLink extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-source", "8", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java index fd7add71aa7..2d563ed1b17 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java @@ -25,12 +25,12 @@ * @test * @bug 8190312 * @summary test redirected URLs for -link - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.api * jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox toolbox.JavacTask JavadocTester + * @build toolbox.ToolBox toolbox.JavacTask javadoc.tester.* * @run main TestRedirectLinks */ @@ -59,10 +59,10 @@ import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import javadoc.tester.JavadocTester; import toolbox.JavacTask; import toolbox.ToolBox; - public class TestRedirectLinks extends JavadocTester { /** * The entry point of the test. @@ -103,6 +103,7 @@ public class TestRedirectLinks extends JavadocTester { out.println("Header: " + httpConn.getHeaderFieldKey(n) + ": " + httpConn.getHeaderField(n)); n++; } + httpConn.disconnect(); } } catch (Exception e) { out.println("Exception occurred: " + e); diff --git a/test/langtools/jdk/javadoc/doclet/testLinkTaglet/TestLinkTaglet.java b/test/langtools/jdk/javadoc/doclet/testLinkTaglet/TestLinkTaglet.java index f7fe5f07725..e6c71a909dc 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkTaglet/TestLinkTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkTaglet/TestLinkTaglet.java @@ -27,12 +27,14 @@ * @summary Make sure that you can link from one member to another using * non-qualified name, furthermore, ensure the right one is linked. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLinkTaglet */ +import javadoc.tester.JavadocTester; + public class TestLinkTaglet extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestLinkTaglet extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", "-sourcepath", testSrc, @@ -75,7 +77,7 @@ public class TestLinkTaglet extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-Xdoclint:none", "-d", "out-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testLinkToSerialForm/TestLinkToSerialForm.java b/test/langtools/jdk/javadoc/doclet/testLinkToSerialForm/TestLinkToSerialForm.java index 33a3854e047..1f6beb8ef02 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkToSerialForm/TestLinkToSerialForm.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkToSerialForm/TestLinkToSerialForm.java @@ -27,12 +27,14 @@ * @summary Test to make sure that there is a link with a proper anchor * from a serializable class to serialized-form.html. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLinkToSerialForm */ +import javadoc.tester.JavadocTester; + public class TestLinkToSerialForm extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestLinkToSerialForm extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -54,7 +56,7 @@ public class TestLinkToSerialForm extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testLinksWithNoDeprecatedOption/TestLinksWithNoDeprecatedOption.java b/test/langtools/jdk/javadoc/doclet/testLinksWithNoDeprecatedOption/TestLinksWithNoDeprecatedOption.java index 011c2c5e831..6b71ea096cd 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinksWithNoDeprecatedOption/TestLinksWithNoDeprecatedOption.java +++ b/test/langtools/jdk/javadoc/doclet/testLinksWithNoDeprecatedOption/TestLinksWithNoDeprecatedOption.java @@ -25,12 +25,12 @@ * @test * @bug 8202627 * @summary javadoc generates broken links to deprecated items when -nodeprecated is used - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLinksWithNoDeprecatedOption */ @@ -43,6 +43,8 @@ import builder.ClassBuilder.FieldBuilder; import builder.ClassBuilder.MethodBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestLinksWithNoDeprecatedOption extends JavadocTester { final ToolBox tb; @@ -57,7 +59,7 @@ public class TestLinksWithNoDeprecatedOption extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(base, srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testLiteralCodeInPre/TestLiteralCodeInPre.java b/test/langtools/jdk/javadoc/doclet/testLiteralCodeInPre/TestLiteralCodeInPre.java index fd243ba721f..a60f9d2150e 100644 --- a/test/langtools/jdk/javadoc/doclet/testLiteralCodeInPre/TestLiteralCodeInPre.java +++ b/test/langtools/jdk/javadoc/doclet/testLiteralCodeInPre/TestLiteralCodeInPre.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @bug 8002387 8014636 8078320 8175200 8186332 * @summary Improve rendered HTML formatting for {@code} - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestLiteralCodeInPre */ +import javadoc.tester.JavadocTester; + public class TestLiteralCodeInPre extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestLiteralCodeInPre extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-Xdoclint:none", diff --git a/test/langtools/jdk/javadoc/doclet/testMemberInheritance/TestMemberInheritance.java b/test/langtools/jdk/javadoc/doclet/testMemberInheritance/TestMemberInheritance.java index e2f71d24060..92d20e2f6eb 100644 --- a/test/langtools/jdk/javadoc/doclet/testMemberInheritance/TestMemberInheritance.java +++ b/test/langtools/jdk/javadoc/doclet/testMemberInheritance/TestMemberInheritance.java @@ -28,12 +28,14 @@ * @summary Test to make sure that members are inherited properly in the Javadoc. * Verify that inheritance labels are correct. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestMemberInheritance */ +import javadoc.tester.JavadocTester; + public class TestMemberInheritance extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestMemberInheritance extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg", "diamond", "inheritDist", "pkg1"); @@ -105,7 +107,7 @@ public class TestMemberInheritance extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testMemberSummary/TestMemberSummary.java b/test/langtools/jdk/javadoc/doclet/testMemberSummary/TestMemberSummary.java index 8c3ff1f7580..dbb20ac8b6f 100644 --- a/test/langtools/jdk/javadoc/doclet/testMemberSummary/TestMemberSummary.java +++ b/test/langtools/jdk/javadoc/doclet/testMemberSummary/TestMemberSummary.java @@ -28,12 +28,14 @@ * type than the method in the child class. Make sure the * documentation is inherited but the return type isn't. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestMemberSummary */ +import javadoc.tester.JavadocTester; + public class TestMemberSummary extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestMemberSummary extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-private", "-sourcepath", testSrc, @@ -76,7 +78,7 @@ public class TestMemberSummary extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-private", diff --git a/test/langtools/jdk/javadoc/doclet/testMethodTypes/TestMethodTypes.java b/test/langtools/jdk/javadoc/doclet/testMethodTypes/TestMethodTypes.java index d4c2cd5af2f..67117a98467 100644 --- a/test/langtools/jdk/javadoc/doclet/testMethodTypes/TestMethodTypes.java +++ b/test/langtools/jdk/javadoc/doclet/testMethodTypes/TestMethodTypes.java @@ -26,12 +26,14 @@ * @bug 8002304 8024096 8193671 8196201 8203791 8184205 * @summary Test for various method type tabs in the method summary table * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestMethodTypes */ +import javadoc.tester.JavadocTester; + public class TestMethodTypes extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestMethodTypes extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg1"); diff --git a/test/langtools/jdk/javadoc/doclet/testMissingType/TestMissingType.java b/test/langtools/jdk/javadoc/doclet/testMissingType/TestMissingType.java index b544f7cb038..4b998f616d8 100644 --- a/test/langtools/jdk/javadoc/doclet/testMissingType/TestMissingType.java +++ b/test/langtools/jdk/javadoc/doclet/testMissingType/TestMissingType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,12 +25,14 @@ * @test * @bug 8173804 * @summary make sure doclet can handle missing types - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestMissingType */ +import javadoc.tester.JavadocTester; + public class TestMissingType extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestMissingType extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-use", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testModifierEx/TestModifierEx.java b/test/langtools/jdk/javadoc/doclet/testModifierEx/TestModifierEx.java index 0d4224cf416..86bc24c4340 100644 --- a/test/langtools/jdk/javadoc/doclet/testModifierEx/TestModifierEx.java +++ b/test/langtools/jdk/javadoc/doclet/testModifierEx/TestModifierEx.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,12 +24,14 @@ /* * @test * @summary Ensure the modifiers are correct - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestModifierEx */ +import javadoc.tester.JavadocTester; + public class TestModifierEx extends JavadocTester { public static void main(String... args) throws Exception { @@ -38,7 +40,7 @@ public class TestModifierEx extends JavadocTester { } @Test - void test1(){ + public void test1(){ javadoc("-d", "out-1", "-sourcepath", testSrc, "-package", "pkg1"); diff --git a/test/langtools/jdk/javadoc/doclet/testModuleDirs/TestModuleDirs.java b/test/langtools/jdk/javadoc/doclet/testModuleDirs/TestModuleDirs.java index a1778b5a4e2..f69762cf4f0 100644 --- a/test/langtools/jdk/javadoc/doclet/testModuleDirs/TestModuleDirs.java +++ b/test/langtools/jdk/javadoc/doclet/testModuleDirs/TestModuleDirs.java @@ -30,8 +30,8 @@ * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestModuleDirs */ @@ -39,6 +39,7 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; import toolbox.ModuleBuilder; import toolbox.ToolBox; diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestEmptyModule.java b/test/langtools/jdk/javadoc/doclet/testModules/TestEmptyModule.java index 571943318c6..3320963613e 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestEmptyModule.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestEmptyModule.java @@ -29,17 +29,18 @@ * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestEmptyModule */ -import toolbox.ModuleBuilder; -import toolbox.ToolBox; - import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; +import toolbox.ModuleBuilder; +import toolbox.ToolBox; + public class TestEmptyModule extends JavadocTester { public final ToolBox tb; diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java b/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java index 531d032430d..ef8770c94ac 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java @@ -29,15 +29,17 @@ * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestIndirectExportsOpens */ import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ModuleBuilder; +import toolbox.ToolBox; public class TestIndirectExportsOpens extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModulePackages.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModulePackages.java index ad6432c467f..55d29304d3b 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModulePackages.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModulePackages.java @@ -25,11 +25,11 @@ * @test * @bug 8178070 8196201 8184205 * @summary Test packages table in module summary pages - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ModuleBuilder toolbox.ToolBox JavadocTester + * @build toolbox.ModuleBuilder toolbox.ToolBox javadoc.tester.* * @run main TestModulePackages */ @@ -38,6 +38,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; +import javadoc.tester.JavadocTester; import toolbox.ModuleBuilder; import toolbox.ToolBox; diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java index d5935976cef..2b24183ea0b 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java @@ -29,8 +29,8 @@ * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestModuleServices */ @@ -38,7 +38,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ModuleBuilder; +import toolbox.ToolBox; public class TestModuleServices extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServicesLink.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServicesLink.java index a8977f3a41b..7cc33e9d32b 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServicesLink.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServicesLink.java @@ -29,15 +29,17 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.api * jdk.javadoc/jdk.javadoc.internal.tool - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestModuleServicesLink */ import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ModuleBuilder; +import toolbox.ToolBox; public class TestModuleServicesLink extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java index d1f90a00d2b..8055dfab4ff 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java @@ -30,11 +30,13 @@ 8184205 * @summary Test modules support in javadoc. * @author bpatel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestModules */ +import javadoc.tester.JavadocTester; + public class TestModules extends JavadocTester { public static void main(String... args) throws Exception { @@ -46,7 +48,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for HTML 4. */ @Test - void testHtml4() { + public void testHtml4() { javadoc("-d", "out", "-html4", "-use", @@ -73,7 +75,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for HTML 5. */ @Test - void testHtml5() { + public void testHtml5() { javadoc("-d", "out-html5", "-use", "-Xdoclint:none", @@ -99,7 +101,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for HTML 4 with -nocomment option. */ @Test - void testHtml4NoComment() { + public void testHtml4NoComment() { javadoc("-d", "out-nocomment", "-html4", "-nocomment", @@ -122,7 +124,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for HTML 5 with -nocomment option. */ @Test - void testHtml5NoComment() { + public void testHtml5NoComment() { javadoc("-d", "out-html5-nocomment", "-nocomment", "-use", @@ -144,7 +146,7 @@ public class TestModules extends JavadocTester { * Test generated pages, in an unnamed module, for HTML 4. */ @Test - void testHtml4UnnamedModule() { + public void testHtml4UnnamedModule() { javadoc("-d", "out-nomodule", "-html4", "-use", @@ -164,7 +166,7 @@ public class TestModules extends JavadocTester { * Test generated pages, in an unnamed module, for HTML 5. */ @Test - void testHtml5UnnamedModule() { + public void testHtml5UnnamedModule() { javadoc("-d", "out-html5-nomodule", "-use", "--frames", @@ -182,7 +184,7 @@ public class TestModules extends JavadocTester { * Test generated module pages with javadoc tags. */ @Test - void testJDTagsInModules() { + public void testJDTagsInModules() { javadoc("-d", "out-mdltags", "-author", "-version", @@ -200,7 +202,7 @@ public class TestModules extends JavadocTester { * Test generated module pages with javadoc tags. */ @Test - void testJDTagsInModules_html4() { + public void testJDTagsInModules_html4() { javadoc("-d", "out-mdltags-html4", "-html4", "-author", @@ -219,7 +221,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page. */ @Test - void testModuleSummary() { + public void testModuleSummary() { javadoc("-d", "out-moduleSummary", "-use", "-Xdoclint:none", @@ -235,7 +237,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page. */ @Test - void testModuleSummary_html4() { + public void testModuleSummary_html4() { javadoc("-d", "out-moduleSummary-html4", "-html4", "-use", @@ -252,7 +254,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page of an aggregating module. */ @Test - void testAggregatorModuleSummary() { + public void testAggregatorModuleSummary() { javadoc("-d", "out-aggregatorModuleSummary", "-use", "--module-source-path", testSrc, @@ -266,7 +268,7 @@ public class TestModules extends JavadocTester { * Test generated module pages and pages with link to modules. */ @Test - void testModuleFilesAndLinks() { + public void testModuleFilesAndLinks() { javadoc("-d", "out-modulelinks", "-Xdoclint:none", "--frames", @@ -282,7 +284,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for a deprecated module. */ @Test - void testModuleDeprecation() { + public void testModuleDeprecation() { javadoc("-d", "out-moduledepr", "-Xdoclint:none", "-tag", "regular:a:Regular Tag:", @@ -298,7 +300,7 @@ public class TestModules extends JavadocTester { * Test annotations on modules. */ @Test - void testModuleAnnotation() { + public void testModuleAnnotation() { javadoc("-d", "out-moduleanno", "-Xdoclint:none", "--module-source-path", testSrc, @@ -312,7 +314,7 @@ public class TestModules extends JavadocTester { * Test annotations on modules. */ @Test - void testModuleAnnotation_html4() { + public void testModuleAnnotation_html4() { javadoc("-d", "out-moduleanno-html4", "-html4", "-Xdoclint:none", @@ -327,7 +329,7 @@ public class TestModules extends JavadocTester { * Test module summary pages in "api" mode. */ @Test - void testApiMode() { + public void testApiMode() { javadoc("-d", "out-api", "-use", "--show-module-contents=api", @@ -352,7 +354,7 @@ public class TestModules extends JavadocTester { * Test module summary pages in "all" mode. */ @Test - void testAllMode() { + public void testAllMode() { javadoc("-d", "out-all", "-use", "--show-module-contents=all", @@ -377,7 +379,7 @@ public class TestModules extends JavadocTester { * Test module summary pages in "all" mode. */ @Test - void testAllModeHtml4() { + public void testAllModeHtml4() { javadoc("-d", "out-all-html4", "-html4", "-use", @@ -400,7 +402,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page of a module with no exported package. */ @Test - void testModuleSummaryNoExportedPkgAll() { + public void testModuleSummaryNoExportedPkgAll() { javadoc("-d", "out-ModuleSummaryNoExportedPkgAll", "-use", "--show-module-contents=all", @@ -415,7 +417,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page of a module with no exported package. */ @Test - void testModuleSummaryNoExportedPkgAll_html4() { + public void testModuleSummaryNoExportedPkgAll_html4() { javadoc("-d", "out-ModuleSummaryNoExportedPkgAll-html4", "-html4", "-use", @@ -431,7 +433,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page of a module with no exported package. */ @Test - void testModuleSummaryNoExportedPkgApi() { + public void testModuleSummaryNoExportedPkgApi() { javadoc("-d", "out-ModuleSummaryNoExportedPkgApi", "-use", "-sourcepath", testSrc + "/moduleNoExport", @@ -445,7 +447,7 @@ public class TestModules extends JavadocTester { * Test generated module summary page of a module with no exported package. */ @Test - void testModuleSummaryNoExportedPkgApi_html4() { + public void testModuleSummaryNoExportedPkgApi_html4() { javadoc("-d", "out-ModuleSummaryNoExportedPkgApi-html4", "-html4", "-use", @@ -460,7 +462,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for javadoc run for a single module having a single package. */ @Test - void testSingleModuleSinglePkg() { + public void testSingleModuleSinglePkg() { javadoc("-d", "out-singlemod", "--frames", "--module-source-path", testSrc, @@ -474,7 +476,7 @@ public class TestModules extends JavadocTester { * Test generated module pages for javadoc run for a single module having multiple packages. */ @Test - void testSingleModuleMultiplePkg() { + public void testSingleModuleMultiplePkg() { javadoc("-d", "out-singlemodmultiplepkg", "--show-module-contents=all", "-Xdoclint:none", @@ -490,7 +492,7 @@ public class TestModules extends JavadocTester { * Test -group option for modules. The overview-summary.html page should group the modules accordingly. */ @Test - void testGroupOption() { + public void testGroupOption() { javadoc("-d", "out-group", "--show-module-contents=all", "-Xdoclint:none", @@ -512,7 +514,7 @@ public class TestModules extends JavadocTester { * Test -group option for modules. The overview-summary.html page should group the modules accordingly. */ @Test - void testGroupOption_html4() { + public void testGroupOption_html4() { javadoc("-d", "out-group-html4", "-html4", "--show-module-contents=all", @@ -537,7 +539,7 @@ public class TestModules extends JavadocTester { * the order it was provided on the command-line. */ @Test - void testGroupOptionOrdering() { + public void testGroupOptionOrdering() { javadoc("-d", "out-groupOrder", "--show-module-contents=all", "-Xdoclint:none", @@ -560,7 +562,7 @@ public class TestModules extends JavadocTester { * Test -group option for unnamed modules. The overview-summary.html page should group the packages accordingly. */ @Test - void testUnnamedModuleGroupOption() { + public void testUnnamedModuleGroupOption() { javadoc("-d", "out-groupnomodule", "-use", "-Xdoclint:none", @@ -578,7 +580,7 @@ public class TestModules extends JavadocTester { * Test -group option for unnamed modules. The overview-summary.html page should group the packages accordingly. */ @Test - void testUnnamedModuleGroupOption_html4() { + public void testUnnamedModuleGroupOption_html4() { javadoc("-d", "out-groupnomodule-html4", "-html4", "-use", @@ -599,7 +601,7 @@ public class TestModules extends JavadocTester { * the order it was provided on the command-line. */ @Test - void testGroupOptionPackageOrdering() { + public void testGroupOptionPackageOrdering() { javadoc("-d", "out-groupPkgOrder", "-use", "-Xdoclint:none", @@ -617,7 +619,7 @@ public class TestModules extends JavadocTester { * Test -group option for a single module. */ @Test - void testGroupOptionSingleModule() { + public void testGroupOptionSingleModule() { javadoc("-d", "out-groupsinglemodule", "-use", "-Xdoclint:none", @@ -634,7 +636,7 @@ public class TestModules extends JavadocTester { * Test -group option for a single module. */ @Test - void testGroupOptionSingleModule_html4() { + public void testGroupOptionSingleModule_html4() { javadoc("-d", "out-groupsinglemodule-html4", "-html4", "-use", @@ -652,7 +654,7 @@ public class TestModules extends JavadocTester { * Test -group option for a single module. */ @Test - void testModuleName() { + public void testModuleName() { javadoc("-d", "out-modulename", "-use", "-Xdoclint:none", @@ -668,7 +670,7 @@ public class TestModules extends JavadocTester { * Test -linkoffline option. */ @Test - void testLinkOffline() { + public void testLinkOffline() { String url = "https://docs.oracle.com/javase/9/docs/api/"; javadoc("-d", "out-linkoffline", "-use", diff --git a/test/langtools/jdk/javadoc/doclet/testNavigation/TestModuleNavigation.java b/test/langtools/jdk/javadoc/doclet/testNavigation/TestModuleNavigation.java index a763bc15cce..0d54f8cb607 100644 --- a/test/langtools/jdk/javadoc/doclet/testNavigation/TestModuleNavigation.java +++ b/test/langtools/jdk/javadoc/doclet/testNavigation/TestModuleNavigation.java @@ -29,8 +29,8 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.api * jdk.javadoc/jdk.javadoc.internal.tool - * @library ../lib /tools/lib - * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester + * @library ../../lib /tools/lib + * @build toolbox.ToolBox toolbox.ModuleBuilder javadoc.tester.* * @run main TestModuleNavigation */ @@ -38,7 +38,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ModuleBuilder; +import toolbox.ToolBox; public class TestModuleNavigation extends JavadocTester { diff --git a/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java b/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java index cc5ff4992ff..dbfd7af9d71 100644 --- a/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java +++ b/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java @@ -28,9 +28,9 @@ * @summary Make sure the Next/Prev Class links iterate through all types. * Make sure the navagation is 2 columns, not 3. * @author jamieh - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestNavigation */ @@ -38,7 +38,8 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import toolbox.*; +import javadoc.tester.JavadocTester; +import toolbox.ToolBox; public class TestNavigation extends JavadocTester { @@ -53,7 +54,7 @@ public class TestNavigation extends JavadocTester { } @Test - void test(Path ignore) { + public void test(Path ignore) { javadoc("-d", "out", "-overview", testSrc("overview.html"), "--frames", @@ -110,7 +111,7 @@ public class TestNavigation extends JavadocTester { } @Test - void test_html4(Path ignore) { + public void test_html4(Path ignore) { javadoc("-d", "out-html4", "-html4", "-overview", testSrc("overview.html"), @@ -151,7 +152,7 @@ public class TestNavigation extends JavadocTester { // Test for checking additional padding to offset the fixed navigation bar in HTML5. @Test - void test1(Path ignore) { + public void test1(Path ignore) { javadoc("-d", "out-1", "-html5", "--frames", @@ -185,7 +186,7 @@ public class TestNavigation extends JavadocTester { // Test to make sure that no extra padding for nav bar gets generated if -nonavbar is specified for HTML4. @Test - void test2(Path ignore) { + public void test2(Path ignore) { javadoc("-d", "out-2", "-nonavbar", "--frames", @@ -217,7 +218,7 @@ public class TestNavigation extends JavadocTester { // Test to make sure that no extra padding for nav bar gets generated if -nonavbar is specified for HTML5. @Test - void test3(Path ignore) { + public void test3(Path ignore) { javadoc("-d", "out-3", "-html5", "-nonavbar", @@ -251,7 +252,7 @@ public class TestNavigation extends JavadocTester { } @Test - void test4(Path base) throws IOException { + public void test4(Path base) throws IOException { Path src = base.resolve("src"); tb.writeJavaFiles(src, "package pkg1; public class A {\n" diff --git a/test/langtools/jdk/javadoc/doclet/testNestedGenerics/TestNestedGenerics.java b/test/langtools/jdk/javadoc/doclet/testNestedGenerics/TestNestedGenerics.java index 00bfb366d7e..625f70e76d8 100644 --- a/test/langtools/jdk/javadoc/doclet/testNestedGenerics/TestNestedGenerics.java +++ b/test/langtools/jdk/javadoc/doclet/testNestedGenerics/TestNestedGenerics.java @@ -26,12 +26,14 @@ * @bug 6758050 8025633 8182765 * @summary Test HTML output for nested generic types. * @author bpatel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNestedGenerics */ +import javadoc.tester.JavadocTester; + public class TestNestedGenerics extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestNestedGenerics extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -53,7 +55,7 @@ public class TestNestedGenerics extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java b/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java index d066eacbbe1..7ce44f34cbe 100644 --- a/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java +++ b/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java @@ -29,12 +29,14 @@ * language features. Check the output to ensure that the new * language features are properly documented. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNewLanguageFeatures */ +import javadoc.tester.JavadocTester; + public class TestNewLanguageFeatures extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestNewLanguageFeatures extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", "-use", @@ -59,7 +61,7 @@ public class TestNewLanguageFeatures extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-Xdoclint:none", "-d", "out-html4", "-html4", diff --git a/test/langtools/jdk/javadoc/doclet/testNoPackagesFile/TestNoPackagesFile.java b/test/langtools/jdk/javadoc/doclet/testNoPackagesFile/TestNoPackagesFile.java index a1f342a9007..1fd0be11e31 100644 --- a/test/langtools/jdk/javadoc/doclet/testNoPackagesFile/TestNoPackagesFile.java +++ b/test/langtools/jdk/javadoc/doclet/testNoPackagesFile/TestNoPackagesFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,14 @@ * @summary Verify that packages.html is no longer generated since it is no * longer used. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNoPackagesFile */ +import javadoc.tester.JavadocTester; + public class TestNoPackagesFile extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestNoPackagesFile extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java b/test/langtools/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java index f9103f980bc..1ab6d022993 100644 --- a/test/langtools/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java +++ b/test/langtools/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,12 +25,14 @@ * @test * @bug 8048628 8174715 8182765 * @summary Verify html inline tags are removed correctly in the first sentence. - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNonInlineHtmlTagRemoval */ +import javadoc.tester.JavadocTester; + public class TestNonInlineHtmlTagRemoval extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestNonInlineHtmlTagRemoval extends JavadocTester { } @Test - void testPositive() { + public void testPositive() { javadoc("-d", "out1", "-sourcepath", testSrc, testSrc("C.java")); @@ -64,7 +66,7 @@ public class TestNonInlineHtmlTagRemoval extends JavadocTester { } @Test - void testPositive_html4() { + public void testPositive_html4() { javadoc("-d", "out1-html4", "-html4", "-sourcepath", testSrc, @@ -73,7 +75,7 @@ public class TestNonInlineHtmlTagRemoval extends JavadocTester { } @Test - void testNegative() { + public void testNegative() { javadoc("-d", "out2", "-sourcepath", testSrc, testSrc("Negative.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testNotifications/TestNotifications.java b/test/langtools/jdk/javadoc/doclet/testNotifications/TestNotifications.java index bd4e4d03392..b00cf4ef853 100644 --- a/test/langtools/jdk/javadoc/doclet/testNotifications/TestNotifications.java +++ b/test/langtools/jdk/javadoc/doclet/testNotifications/TestNotifications.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,12 +28,14 @@ * be created. * Make sure classname is not include in javadoc usage message. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestNotifications */ +import javadoc.tester.JavadocTester; + public class TestNotifications extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestNotifications extends JavadocTester { } @Test - void test1() { + public void test1() { String outDir = "out"; // Notify that the destination directory must be created. @@ -61,7 +63,7 @@ public class TestNotifications extends JavadocTester { } @Test - void test() { + public void test() { //Make sure classname is not include in javadoc usage message. setOutputDirectoryCheck(DirectoryCheck.NO_HTML_FILES); javadoc("-help"); diff --git a/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java b/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java index 435a76c8651..b9263e63eaf 100644 --- a/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java +++ b/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java @@ -27,14 +27,16 @@ * @summary Test the output for -header, -footer, -nooverview, -nodeprecatedlist, -nonavbar, -notree, * -stylesheetfile, --main-stylesheet, --add-stylesheet options. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestOptions */ import java.io.File; +import javadoc.tester.JavadocTester; + public class TestOptions extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestOptions extends JavadocTester { } @Test - void testHeaderFooter() { + public void testHeaderFooter() { javadoc("-d", "out-1", "-header", "Test header", "-footer", "Test footer", @@ -57,7 +59,7 @@ public class TestOptions extends JavadocTester { } @Test - void testNoOverview() { + public void testNoOverview() { javadoc("-d", "out-4", "-nooverview", "-sourcepath", testSrc, @@ -69,7 +71,7 @@ public class TestOptions extends JavadocTester { } @Test - void testNoDeprecatedList() { + public void testNoDeprecatedList() { javadoc("-d", "out-5", "-nodeprecatedlist", "-sourcepath", testSrc, @@ -80,7 +82,7 @@ public class TestOptions extends JavadocTester { } @Test - void testNoNavbar() { + public void testNoNavbar() { javadoc("-d", "out-6", "-nonavbar", "-bottom", "Bottom text", @@ -93,7 +95,7 @@ public class TestOptions extends JavadocTester { } @Test - void testNoTree() { + public void testNoTree() { javadoc("-d", "out-7", "-notree", "-sourcepath", testSrc, @@ -106,7 +108,7 @@ public class TestOptions extends JavadocTester { } @Test - void testStylesheetFile() { + public void testStylesheetFile() { javadoc("-d", "out-8", "-stylesheetfile", new File(testSrc, "custom-stylesheet.css").getAbsolutePath(), "-sourcepath", testSrc, @@ -119,7 +121,7 @@ public class TestOptions extends JavadocTester { } @Test - void testStylesheetFileAltOption() { + public void testStylesheetFileAltOption() { javadoc("-d", "out-stylesheet-file", "--main-stylesheet", new File(testSrc, "custom-stylesheet.css").getAbsolutePath(), "-sourcepath", testSrc, @@ -132,7 +134,7 @@ public class TestOptions extends JavadocTester { } @Test - void testAdditionalStylesheetFile() { + public void testAdditionalStylesheetFile() { javadoc("-d", "out-additional-css", "--add-stylesheet", new File(testSrc, "additional-stylesheet-1.css").getAbsolutePath(), "--add-stylesheet", new File(testSrc, "additional-stylesheet-2.css").getAbsolutePath(), @@ -151,7 +153,7 @@ public class TestOptions extends JavadocTester { } @Test - void testInvalidStylesheetFile() { + public void testInvalidStylesheetFile() { javadoc("-d", "out-invalid-css", "--main-stylesheet", new File(testSrc, "custom-stylesheet-1.css").getAbsolutePath(), "-sourcepath", testSrc, @@ -164,7 +166,7 @@ public class TestOptions extends JavadocTester { } @Test - void testInvalidAdditionalStylesheetFiles() { + public void testInvalidAdditionalStylesheetFiles() { javadoc("-d", "out-invalid-additional-css", "--add-stylesheet", new File(testSrc, "additional-stylesheet-4.css").getAbsolutePath(), "-sourcepath", testSrc, @@ -177,7 +179,7 @@ public class TestOptions extends JavadocTester { } @Test - void testLinkSource() { + public void testLinkSource() { javadoc("-d", "out-9", "-linksource", "-javafx", @@ -250,7 +252,7 @@ public class TestOptions extends JavadocTester { } @Test - void testLinkSource_html4() { + public void testLinkSource_html4() { javadoc("-d", "out-9-html4", "-html4", "-linksource", @@ -285,7 +287,7 @@ public class TestOptions extends JavadocTester { } @Test - void testNoQualifier() { + public void testNoQualifier() { javadoc("-d", "out-10", "-noqualifier", "pkg", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java b/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java index 588d7703ce4..5a83f864ee0 100644 --- a/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java +++ b/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java @@ -25,9 +25,9 @@ * @test * @bug 8039410 8042601 8042829 8049393 8050031 8155061 8155995 8167967 8169813 8182765 8196202 * @summary test to determine if members are ordered correctly - * @library ../lib/ + * @library ../../lib/ * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestOrdering */ @@ -41,6 +41,8 @@ import java.util.List; import static java.nio.file.StandardOpenOption.*; +import javadoc.tester.JavadocTester; + public class TestOrdering extends JavadocTester { public static void main(String[] args) throws Exception { @@ -49,94 +51,84 @@ public class TestOrdering extends JavadocTester { } @Test - void testUnnamedPackagesForClassUse() { - new UnnamedPackageForClassUseTest(this).run(); + public void testUnnamedPackagesForClassUse() { + new UnnamedPackageForClassUseTest().run(); } @Test - void testNamedPackagesForClassUse() { - new NamedPackagesForClassUseTest(this).run(); + public void testNamedPackagesForClassUse() { + new NamedPackagesForClassUseTest().run(); } @Test - void testIndexOrdering() throws IOException { - new IndexOrderingTest(this).run(); + public void testIndexOrdering() throws IOException { + new IndexOrderingTest().run(); } @Test - void testIndexTypeClustering() { - new IndexTypeClusteringTest(this).run(); + public void testIndexTypeClustering() { + new IndexTypeClusteringTest().run(); } @Test - void testTypeElementMemberOrdering() { - new TypeElementMemberOrderingTest(this).run(); + public void testTypeElementMemberOrdering() { + new TypeElementMemberOrderingTest().run(); } - static class UnnamedPackageForClassUseTest { - final JavadocTester tester; - - UnnamedPackageForClassUseTest(JavadocTester tester) { - this.tester = tester; - } + class UnnamedPackageForClassUseTest { void run() { - tester.javadoc("-d", "out", + javadoc("-d", "out", "-sourcepath", testSrc, "-use", - tester.testSrc("C.java"), tester.testSrc("UsedInC.java")); - tester.checkExit(Exit.OK); + testSrc("C.java"), testSrc("UsedInC.java")); + checkExit(Exit.OK); checkExecutableMemberOrdering("class-use/UsedInC.html"); } void checkExecutableMemberOrdering(String usePage) { - String contents = tester.readFile(usePage); + String contents = readFile(usePage); // check constructors - tester.checking("constructors"); + checking("constructors"); int idx1 = contents.indexOf("C.html#%3Cinit%3E(UsedInC"); int idx2 = contents.indexOf("C.html#%3Cinit%3E(UsedInC,int"); int idx3 = contents.indexOf("C.html#%3Cinit%3E(UsedInC,java.lang.String"); if (idx1 == -1 || idx2 == -1 || idx3 == -1) { - tester.failed("ctor strings not found"); + failed("ctor strings not found"); } else if (idx1 > idx2 || idx2 > idx3 || idx1 > idx3) { - tester.failed("ctor strings are out of order"); + failed("ctor strings are out of order"); } else { - tester.passed("ctor strings are in order"); + passed("ctor strings are in order"); } // check methods - tester.checking("methods"); + checking("methods"); idx1 = contents.indexOf("C.html#ymethod(int"); idx2 = contents.indexOf("C.html#ymethod(java.lang.String"); if (idx1 == -1 || idx2 == -1) { - tester.failed("#ymethod strings not found"); + failed("#ymethod strings not found"); } else if (idx1 > idx2) { - tester.failed("#ymethod strings are out of order"); + failed("#ymethod strings are out of order"); } else { - tester.passed("Executable Member Ordering: OK"); + passed("Executable Member Ordering: OK"); } } } - static class NamedPackagesForClassUseTest { - final JavadocTester tester; - - NamedPackagesForClassUseTest(JavadocTester tester) { - this.tester = tester; - } + class NamedPackagesForClassUseTest { public void run() { - tester.javadoc("-d", "out-1", - "-sourcepath", tester.testSrc, + javadoc("-d", "out-1", + "-sourcepath", testSrc, "-use", "--frames", "pkg1"); - tester.checkExit(Exit.OK); - tester.checkFiles(false, "allclasses-noframe.html"); + checkExit(Exit.OK); + checkFiles(false, "allclasses-noframe.html"); checkClassUseOrdering("pkg1/class-use/UsedClass.html"); - tester.checkOrder("pkg1/class-use/UsedClass.html", + checkOrder("pkg1/class-use/UsedClass.html", "../MethodOrder.html#m()", "../MethodOrder.html#m(byte%5B%5D)", "../MethodOrder.html#m(double)", @@ -160,13 +152,13 @@ public class TestOrdering extends JavadocTester { "../MethodOrder.html#m(java.util.Collection)", "../MethodOrder.html#m(java.util.List)"); - tester.checkOrder("pkg1/class-use/UsedClass.html", + checkOrder("pkg1/class-use/UsedClass.html", "../MethodOrder.html#tpm(pkg1.UsedClass)", "../MethodOrder.html#tpm(pkg1.UsedClass,pkg1.UsedClass)", "../MethodOrder.html#tpm(pkg1.UsedClass,pkg1.UsedClass%5B%5D)", "../MethodOrder.html#tpm(pkg1.UsedClass,java.lang.String)"); - tester.checkOrder("pkg1/class-use/UsedClass.html", + checkOrder("pkg1/class-use/UsedClass.html", "../A.html#%3Cinit%3E(pkg1.UsedClass)", "../B.A.html#%3Cinit%3E(pkg1.UsedClass)", "../B.html#%3Cinit%3E(pkg1.UsedClass)", @@ -174,16 +166,16 @@ public class TestOrdering extends JavadocTester { "../A.C.html#%3Cinit%3E(pkg1.UsedClass,java.util.Collection)", "../A.C.html#%3Cinit%3E(pkg1.UsedClass,java.util.List)"); - tester.checkOrder("pkg1/ImplementsOrdering.html", + checkOrder("pkg1/ImplementsOrdering.html", "
      close in interface java.lang.AutoCloseable
      ", "
      close in interface java.nio.channels.Channel
      ", "
      close in interface java.io.Closeable
      "); - tester.checkOrder("pkg1/OverrideOrdering.html", + checkOrder("pkg1/OverrideOrdering.html", "
      iterator in interface java.util.Collection<", "
      iterator in interface java.lang.Iterable<"); - tester.checkOrder("allclasses-frame.html", + checkOrder("allclasses-frame.html", "pkg1/A.html\" title=\"class in pkg1", "pkg1/A.C.html\" title=\"class in pkg1", "pkg1/B.html\" title=\"class in pkg1", @@ -206,40 +198,36 @@ public class TestOrdering extends JavadocTester { } void checkClassUseOrdering(String usePage, String searchString) { - String contents = tester.readFile(usePage); + String contents = readFile(usePage); int lastidx = 0; System.out.println("testing for " + searchString); for (int i = 1; i < 5; i++) { String s = searchString.replaceAll("#ITERATION#", Integer.toString(i)); - tester.checking(s); + checking(s); int idx = contents.indexOf(s); if (idx < lastidx) { - tester.failed(s + ", member ordering error, last:" + lastidx + ", got:" + idx); + failed(s + ", member ordering error, last:" + lastidx + ", got:" + idx); } else { - tester.passed("\tlast: " + lastidx + " got:" + idx); + passed("\tlast: " + lastidx + " got:" + idx); } lastidx = idx; } } } - static class IndexOrderingTest { - private final JavadocTester tester; + enum ListOrder { + NONE, REVERSE, SHUFFLE + }; - IndexOrderingTest(JavadocTester tester) { - this.tester = tester; - } + class IndexOrderingTest { - enum ListOrder { - NONE, REVERSE, SHUFFLE - }; /* * By default we do not shuffle the input list, in order to keep the list deterministic, * and the test predictable. However, we can turn on the stress mode, by setting the following * property if required. */ - static final ListOrder STRESS_MODE = Boolean.getBoolean("TestOrder.STRESS") + final ListOrder STRESS_MODE = Boolean.getBoolean("TestOrder.STRESS") ? ListOrder.SHUFFLE : ListOrder.REVERSE; @@ -255,7 +243,7 @@ public class TestOrdering extends JavadocTester { */ static final int MAX_PACKAGES = 4; - static String[] contents = { + String[] contents = { "public add ADDADD;", "public add AddAdd;", "public add addadd;", @@ -274,12 +262,12 @@ public class TestOrdering extends JavadocTester { "public int add(Integer i) {return 0;}" }; - static String expectedEnumOrdering[] = { + String expectedEnumOrdering[] = { "Add.add.html\" title=\"enum in REPLACE_ME\"", "Add.ADD.html\" title=\"enum in REPLACE_ME\"" }; - static String expectedFieldOrdering[] = { + String expectedFieldOrdering[] = { "Add.html#addadd\"", "add0/add/add/add/Add.html#addadd\"", "add0/add/add/Add.html#addadd\"", @@ -333,7 +321,7 @@ public class TestOrdering extends JavadocTester { "add3/Add.html#ADDADD\"" }; - static String expectedMethodOrdering[] = { + String expectedMethodOrdering[] = { "Add.html#add()", "Add.html#add(double)", "Add.html#add(double,byte)", @@ -347,7 +335,7 @@ public class TestOrdering extends JavadocTester { "Add.html#add(java.lang.Integer)" }; - static String expectedPackageOrdering[] = { + String expectedPackageOrdering[] = { "\"add0/package-summary.html\">add0 - package add0", "\"add0/add/package-summary.html\">add0.add - package add0.add", "\"add0/add/add/package-summary.html\">add0.add.add - package add0.add.add", @@ -390,13 +378,13 @@ public class TestOrdering extends JavadocTester { } File srcDir = new File(new File("."), "src"); cmdArgs.add(new File(srcDir, clsname + ".java").getPath()); - tester.javadoc(cmdArgs.toArray(new String[cmdArgs.size()])); - tester.checkExit(Exit.OK); - tester.checkOrder("index-all.html", composeTestVectors()); - tester.checkOrder("add0/add/package-tree.html", + javadoc(cmdArgs.toArray(new String[cmdArgs.size()])); + checkExit(Exit.OK); + checkOrder("index-all.html", composeTestVectors()); + checkOrder("add0/add/package-tree.html", "", ""); - tester.checkOrder("overview-tree.html", + checkOrder("overview-tree.html", "", "", "", @@ -432,7 +420,7 @@ public class TestOrdering extends JavadocTester { "", ""); - tester.checkOrder("overview-frame.html", + checkOrder("overview-frame.html", "<unnamed package>", "add0", "add0.add", @@ -523,26 +511,20 @@ public class TestOrdering extends JavadocTester { } } - static class IndexTypeClusteringTest { - - private final JavadocTester tester; - - IndexTypeClusteringTest(JavadocTester tester) { - this.tester = tester; - } + class IndexTypeClusteringTest { void run() { - tester.javadoc("-d", "out-3", - "-sourcepath", tester.testSrc("src-2"), + javadoc("-d", "out-3", + "-sourcepath", testSrc("src-2"), "-use", "a", "b", "e", "something"); - tester.checkExit(Exit.OK); + checkExit(Exit.OK); - tester.checkOrder("index-all.html", + checkOrder("index-all.html", "something - package something", "something - Class in", "something - Enum in", @@ -556,32 +538,26 @@ public class TestOrdering extends JavadocTester { } } - static class TypeElementMemberOrderingTest { - - final JavadocTester tester; - - TypeElementMemberOrderingTest(JavadocTester tester) { - this.tester = tester; - } + class TypeElementMemberOrderingTest { void run() { - tester.javadoc("-d", "out-5", + javadoc("-d", "out-5", "-javafx", "--disable-javafx-strict-checks", - "-sourcepath", tester.testSrc(new File(".").getPath()), + "-sourcepath", testSrc(new File(".").getPath()), "pkg5" ); - tester.checkExit(Exit.OK); + checkExit(Exit.OK); - tester.checkOrder("pkg5/AnnoFieldTest.html", + checkOrder("pkg5/AnnoFieldTest.html", "

      Field Detail

      ", "
      static final int one
      ", "
      static final int two
      ", "
      static final int three
      ", "
      static final int four
      "); - tester.checkOrder("pkg5/AnnoOptionalTest.html", + checkOrder("pkg5/AnnoOptionalTest.html", "

      Optional Element Summary

      ", "four", "one", @@ -593,7 +569,7 @@ public class TestOrdering extends JavadocTester { "

      three

      ", "

      four

      "); - tester.checkOrder("pkg5/AnnoRequiredTest.html", + checkOrder("pkg5/AnnoRequiredTest.html", "

      Required Element Summary

      ", "four", "one", @@ -605,7 +581,7 @@ public class TestOrdering extends JavadocTester { "

      three

      ", "

      four

      "); - tester.checkOrder("pkg5/CtorTest.html", + checkOrder("pkg5/CtorTest.html", "

      Constructor Summary

      ", "", ""); - tester.checkOrder("pkg5/EnumTest.html", + checkOrder("pkg5/EnumTest.html", "

      Enum Constant Summary

      ", "
      FOUR", "ONE", @@ -629,7 +605,7 @@ public class TestOrdering extends JavadocTester { "

      THREE

      ", "

      FOUR

      "); - tester.checkOrder("pkg5/FieldTest.html", + checkOrder("pkg5/FieldTest.html", "

      Field Summary

      ", "four", "one", @@ -641,7 +617,7 @@ public class TestOrdering extends JavadocTester { "

      three

      ", "

      four

      "); - tester.checkOrder("pkg5/IntfTest.html", + checkOrder("pkg5/IntfTest.html", "

      Method Summary

      ", "four", "one", @@ -653,7 +629,7 @@ public class TestOrdering extends JavadocTester { "

      three

      ", "

      four

      "); - tester.checkOrder("pkg5/MethodTest.html", + checkOrder("pkg5/MethodTest.html", "

      Method Summary

      ", "four", "one", @@ -665,7 +641,7 @@ public class TestOrdering extends JavadocTester { "

      three

      ", "

      four

      "); - tester.checkOrder("pkg5/PropertyTest.html", + checkOrder("pkg5/PropertyTest.html", "

      Property Summary

      ", "four", "one", @@ -677,16 +653,16 @@ public class TestOrdering extends JavadocTester { "

      threeProperty

      ", "

      fourProperty

      "); - tester.javadoc("-d", "out-5-html4", + javadoc("-d", "out-5-html4", "-html4", "-javafx", - "-sourcepath", tester.testSrc(new File(".").getPath()), + "-sourcepath", testSrc(new File(".").getPath()), "pkg5" ); - tester.checkExit(Exit.OK); + checkExit(Exit.OK); - tester.checkOrder("pkg5/CtorTest.html", + checkOrder("pkg5/CtorTest.html", "Custom:", diff --git a/test/langtools/jdk/javadoc/doclet/testSinceTag/TestSinceTag.java b/test/langtools/jdk/javadoc/doclet/testSinceTag/TestSinceTag.java index ecb5d5df5e0..17fa2580b71 100644 --- a/test/langtools/jdk/javadoc/doclet/testSinceTag/TestSinceTag.java +++ b/test/langtools/jdk/javadoc/doclet/testSinceTag/TestSinceTag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 7180906 8026567 * @summary Test to make sure that the since tag works correctly * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSinceTag */ +import javadoc.tester.JavadocTester; + public class TestSinceTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestSinceTag extends JavadocTester { } @Test - void testSince() { + public void testSince() { javadoc("-d", "out-since", "-sourcepath", testSrc, "pkg1"); @@ -51,7 +53,7 @@ public class TestSinceTag extends JavadocTester { } @Test - void testNoSince() { + public void testNoSince() { javadoc("-d", "out-nosince", "-sourcepath", testSrc, "-nosince", diff --git a/test/langtools/jdk/javadoc/doclet/testSingleQuotedLink/TestSingleQuotedLink.java b/test/langtools/jdk/javadoc/doclet/testSingleQuotedLink/TestSingleQuotedLink.java index a9118ef33b7..2a668502a4d 100644 --- a/test/langtools/jdk/javadoc/doclet/testSingleQuotedLink/TestSingleQuotedLink.java +++ b/test/langtools/jdk/javadoc/doclet/testSingleQuotedLink/TestSingleQuotedLink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,13 @@ * @bug 6457406 * @summary Verify that a link in single quotes copied to the class-use page as is. * @author Yuri Nesterenko - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSingleQuotedLink */ +import javadoc.tester.JavadocTester; + public class TestSingleQuotedLink extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestSingleQuotedLink extends JavadocTester { } @Test - void run() { + public void run() { javadoc("-d", "out", "-sourcepath", testSrc, "-use", diff --git a/test/langtools/jdk/javadoc/doclet/testSourceTab/TestSourceTab.java b/test/langtools/jdk/javadoc/doclet/testSourceTab/TestSourceTab.java index 4f4d9b41783..647aef96a63 100644 --- a/test/langtools/jdk/javadoc/doclet/testSourceTab/TestSourceTab.java +++ b/test/langtools/jdk/javadoc/doclet/testSourceTab/TestSourceTab.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,14 +27,16 @@ * @summary Test to make sure that the source documentation is indented properly * when -linksourcetab is used. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSourceTab */ import java.io.*; +import javadoc.tester.JavadocTester; + public class TestSourceTab extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestSourceTab extends JavadocTester { } @Test - void test() throws Exception { + public void test() throws Exception { String tmpSrcDir = "tmpSrc"; String outdir1 = "out-tabLengthEight"; String outdir2 = "out-tabLengthFour"; diff --git a/test/langtools/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java b/test/langtools/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java index a08b5a5c7dd..58563734776 100644 --- a/test/langtools/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java +++ b/test/langtools/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java @@ -27,12 +27,14 @@ * 8175218 8176452 8181215 8182263 8183511 8169819 8183037 8185369 8182765 8196201 8184205 * @summary Run tests on doclet stylesheet. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestStylesheet */ +import javadoc.tester.JavadocTester; + public class TestStylesheet extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestStylesheet extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); @@ -242,7 +244,7 @@ public class TestStylesheet extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testStylesheetOverwrite/TestStylesheetOverwrite.java b/test/langtools/jdk/javadoc/doclet/testStylesheetOverwrite/TestStylesheetOverwrite.java index 373256f3b08..0571a8266de 100644 --- a/test/langtools/jdk/javadoc/doclet/testStylesheetOverwrite/TestStylesheetOverwrite.java +++ b/test/langtools/jdk/javadoc/doclet/testStylesheetOverwrite/TestStylesheetOverwrite.java @@ -24,9 +24,9 @@ * @test * @bug 8196913 * @summary javadoc does not (over)write stylesheet.css - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestStylesheetOverwrite */ @@ -38,6 +38,8 @@ import java.util.List; import builder.ClassBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestStylesheetOverwrite extends JavadocTester { final ToolBox tb; @@ -51,7 +53,7 @@ public class TestStylesheetOverwrite extends JavadocTester { } @Test - void testStylesheetFile(Path base) throws Exception { + public void testStylesheetFile(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testSubTitle/TestSubTitle.java b/test/langtools/jdk/javadoc/doclet/testSubTitle/TestSubTitle.java index 2cb887f4ee8..ec87f44a29a 100644 --- a/test/langtools/jdk/javadoc/doclet/testSubTitle/TestSubTitle.java +++ b/test/langtools/jdk/javadoc/doclet/testSubTitle/TestSubTitle.java @@ -26,12 +26,14 @@ * @bug 7010342 8150000 8174974 * @summary Test for correct sub title generation. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSubTitle */ +import javadoc.tester.JavadocTester; + public class TestSubTitle extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestSubTitle extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java b/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java index 4d4f81fcbab..828bff1ad51 100644 --- a/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java +++ b/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,12 +28,14 @@ * "Method Summary" heading should still show up since the class * inherits methods. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSummaryHeading */ +import javadoc.tester.JavadocTester; + public class TestSummaryHeading extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestSummaryHeading extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java b/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java index 9d37a85ad8f..80a1de437cd 100644 --- a/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java +++ b/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java @@ -25,12 +25,14 @@ * @test * @bug 8173425 8186332 8182765 8196202 * @summary tests for the summary tag behavior - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSummaryTag */ +import javadoc.tester.JavadocTester; + public class TestSummaryTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestSummaryTag extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out1", "-sourcepath", testSrc, "p1"); @@ -95,7 +97,7 @@ public class TestSummaryTag extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out1-html4", "-html4", "-sourcepath", testSrc, @@ -139,7 +141,7 @@ public class TestSummaryTag extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out2", "-sourcepath", testSrc, "p2"); @@ -153,7 +155,7 @@ public class TestSummaryTag extends JavadocTester { } @Test - void test3() { + public void test3() { javadoc("-d", "out3", "--frames", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testSuperclassInSerialForm/TestSuperClassInSerialForm.java b/test/langtools/jdk/javadoc/doclet/testSuperclassInSerialForm/TestSuperClassInSerialForm.java index b4dfd387ab2..7c3e7ade2cb 100644 --- a/test/langtools/jdk/javadoc/doclet/testSuperclassInSerialForm/TestSuperClassInSerialForm.java +++ b/test/langtools/jdk/javadoc/doclet/testSuperclassInSerialForm/TestSuperClassInSerialForm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure link to superclass is generated for * each class in serialized form page. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSuperClassInSerialForm */ +import javadoc.tester.JavadocTester; + public class TestSuperClassInSerialForm extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestSuperClassInSerialForm extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testSupplementary/TestSupplementary.java b/test/langtools/jdk/javadoc/doclet/testSupplementary/TestSupplementary.java index 0ec198774c8..255f6cd62a8 100644 --- a/test/langtools/jdk/javadoc/doclet/testSupplementary/TestSupplementary.java +++ b/test/langtools/jdk/javadoc/doclet/testSupplementary/TestSupplementary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,14 +27,16 @@ * @summary Test to make sure that "see" tag and "serialField" tag handle supplementary * characters correctly. This test case needs to be run in en_US locale. * @author Naoto Sato - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestSupplementary */ import java.util.Locale; +import javadoc.tester.JavadocTester; + public class TestSupplementary extends JavadocTester { public static void main(String... args) throws Exception { @@ -48,7 +50,7 @@ public class TestSupplementary extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-locale", "en_US", "-d", "out", testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java b/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java index 0ee6a3604db..551ea5c61f6 100644 --- a/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java @@ -25,9 +25,9 @@ * @test * @bug 5076751 * @summary System properties documentation needed in javadocs - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestSystemPropertyTaglet */ @@ -39,6 +39,8 @@ import builder.ClassBuilder; import builder.ClassBuilder.MethodBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestSystemPropertyTaglet extends JavadocTester { final ToolBox tb; @@ -53,7 +55,7 @@ public class TestSystemPropertyTaglet extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); Path outDir = base.resolve("out"); @@ -97,7 +99,7 @@ public class TestSystemPropertyTaglet extends JavadocTester { } @Test - void testSystemProperytWithinATag(Path base) throws Exception { + public void testSystemProperytWithinATag(Path base) throws Exception { Path srcDir = base.resolve("src"); Path outDir = base.resolve("out"); diff --git a/test/langtools/jdk/javadoc/doclet/testTagInheritence/TestTagInheritence.java b/test/langtools/jdk/javadoc/doclet/testTagInheritence/TestTagInheritence.java index 7a7b498e95a..ad5db2008ea 100644 --- a/test/langtools/jdk/javadoc/doclet/testTagInheritence/TestTagInheritence.java +++ b/test/langtools/jdk/javadoc/doclet/testTagInheritence/TestTagInheritence.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,13 +26,15 @@ * @bug 4496223 4496270 4618686 4720974 4812240 6253614 6253604 * @summary * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTagInheritence */ // TODO: Inheritence should be Inheritance! fix separately as noreg-trivial +import javadoc.tester.JavadocTester; + public class TestTagInheritence extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestTagInheritence extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testTagMisuse/TestTagMisuse.java b/test/langtools/jdk/javadoc/doclet/testTagMisuse/TestTagMisuse.java index 473231e7de2..34e9611e116 100644 --- a/test/langtools/jdk/javadoc/doclet/testTagMisuse/TestTagMisuse.java +++ b/test/langtools/jdk/javadoc/doclet/testTagMisuse/TestTagMisuse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,12 +25,14 @@ * @test * @summary Determine if proper warning messages are printed. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @build TestTagMisuse * @run main TestTagMisuse */ +import javadoc.tester.JavadocTester; + public class TestTagMisuse extends JavadocTester { /** @@ -44,7 +46,7 @@ public class TestTagMisuse extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", testSrc("TestTagMisuse.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testTagOutput/TestTagOutput.java b/test/langtools/jdk/javadoc/doclet/testTagOutput/TestTagOutput.java index f98a5efa64f..634caa9caee 100644 --- a/test/langtools/jdk/javadoc/doclet/testTagOutput/TestTagOutput.java +++ b/test/langtools/jdk/javadoc/doclet/testTagOutput/TestTagOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ * @bug 8026370 8026567 8183511 8074407 * @summary This test checks the generated tag output. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTagOutput */ +import javadoc.tester.JavadocTester; + public class TestTagOutput extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestTagOutput extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg1"); diff --git a/test/langtools/jdk/javadoc/doclet/testTaglets/TestTaglets.java b/test/langtools/jdk/javadoc/doclet/testTaglets/TestTaglets.java index dc9ebf02887..52a5ef887e2 100644 --- a/test/langtools/jdk/javadoc/doclet/testTaglets/TestTaglets.java +++ b/test/langtools/jdk/javadoc/doclet/testTaglets/TestTaglets.java @@ -25,9 +25,9 @@ * @test * @bug 8202947 * @summary Test TagletManager initialization - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestTaglets */ @@ -37,6 +37,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import javadoc.tester.JavadocTester; import toolbox.ToolBox; /* @@ -62,7 +63,7 @@ public class TestTaglets extends JavadocTester { } @Test - void test() throws Exception { + public void test() throws Exception { javadoc("-d", "out", "-javafx", "--show-taglets", diff --git a/test/langtools/jdk/javadoc/doclet/testThrowsHead/TestThrowsHead.java b/test/langtools/jdk/javadoc/doclet/testThrowsHead/TestThrowsHead.java index e73e6bdaa37..de7b1741a60 100644 --- a/test/langtools/jdk/javadoc/doclet/testThrowsHead/TestThrowsHead.java +++ b/test/langtools/jdk/javadoc/doclet/testThrowsHead/TestThrowsHead.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -28,12 +28,14 @@ * not documented with a throws tag, we generate a link to it in the * throws section. Make sure that the link is below a Throws heading. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestThrowsHead */ +import javadoc.tester.JavadocTester; + public class TestThrowsHead extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestThrowsHead extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", testSrc("C.java")); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testThrowsInheritence/TestThrowsTagInheritence.java b/test/langtools/jdk/javadoc/doclet/testThrowsInheritence/TestThrowsTagInheritence.java index de28b8232d4..8629c4484f0 100644 --- a/test/langtools/jdk/javadoc/doclet/testThrowsInheritence/TestThrowsTagInheritence.java +++ b/test/langtools/jdk/javadoc/doclet/testThrowsInheritence/TestThrowsTagInheritence.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -28,13 +28,15 @@ * override the throws tags in interface. This test also verifies that throws tags are inherited properly * the case where the name of one exception is not fully qualified. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestThrowsTagInheritence */ // TODO: should be TestThrowsInheritance! +import javadoc.tester.JavadocTester; + public class TestThrowsTagInheritence extends JavadocTester { public static void main(String... args) throws Exception { @@ -43,7 +45,7 @@ public class TestThrowsTagInheritence extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java"), @@ -62,7 +64,7 @@ public class TestThrowsTagInheritence extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "-package", "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testThrowsTag/TestThrowsTag.java b/test/langtools/jdk/javadoc/doclet/testThrowsTag/TestThrowsTag.java index c40e8a66efd..f07daf7cdbc 100644 --- a/test/langtools/jdk/javadoc/doclet/testThrowsTag/TestThrowsTag.java +++ b/test/langtools/jdk/javadoc/doclet/testThrowsTag/TestThrowsTag.java @@ -27,12 +27,14 @@ * @summary Test to make sure that exceptions always show up in the * correct order. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestThrowsTag */ +import javadoc.tester.JavadocTester; + public class TestThrowsTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestThrowsTag extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testTitleInHref/TestTitleInHref.java b/test/langtools/jdk/javadoc/doclet/testTitleInHref/TestTitleInHref.java index c9a721176f2..1ebaba40af4 100644 --- a/test/langtools/jdk/javadoc/doclet/testTitleInHref/TestTitleInHref.java +++ b/test/langtools/jdk/javadoc/doclet/testTitleInHref/TestTitleInHref.java @@ -26,12 +26,14 @@ * @bug 4714257 8164407 8205593 * @summary Test to make sure that the title attribute shows up in links. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTitleInHref */ +import javadoc.tester.JavadocTester; + public class TestTitleInHref extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestTitleInHref extends JavadocTester { } @Test - void test() { + public void test() { String uri = "http://java.sun.com/j2se/1.4/docs/api"; javadoc("-d", "out", "-source", "8", diff --git a/test/langtools/jdk/javadoc/doclet/testTopOption/TestTopOption.java b/test/langtools/jdk/javadoc/doclet/testTopOption/TestTopOption.java index fb8c7eb36df..ac30827c6ad 100644 --- a/test/langtools/jdk/javadoc/doclet/testTopOption/TestTopOption.java +++ b/test/langtools/jdk/javadoc/doclet/testTopOption/TestTopOption.java @@ -26,12 +26,14 @@ * @bug 6227616 8043186 8196202 * @summary Test the new -top option. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTopOption */ +import javadoc.tester.JavadocTester; + public class TestTopOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestTopOption extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-overview", testSrc("overview.html"), "-use", "-top", "TOP TEXT", @@ -64,7 +66,7 @@ public class TestTopOption extends JavadocTester { } @Test - void testDocRootRewrite() { + public void testDocRootRewrite() { javadoc("-overview", testSrc("overview.html"), "-use", "-top", "\u0130{@docroot}TOP TEXT", diff --git a/test/langtools/jdk/javadoc/doclet/testTypeAnnotations/TestTypeAnnotations.java b/test/langtools/jdk/javadoc/doclet/testTypeAnnotations/TestTypeAnnotations.java index b38c2ab173e..494f856e51e 100644 --- a/test/langtools/jdk/javadoc/doclet/testTypeAnnotations/TestTypeAnnotations.java +++ b/test/langtools/jdk/javadoc/doclet/testTypeAnnotations/TestTypeAnnotations.java @@ -27,12 +27,14 @@ * 8187288 * @summary Make sure that type annotations are displayed correctly * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTypeAnnotations */ +import javadoc.tester.JavadocTester; + public class TestTypeAnnotations extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestTypeAnnotations extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-private", @@ -720,7 +722,7 @@ public class TestTypeAnnotations extends JavadocTester { } @Test - void test_html4() { + public void test_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testTypeParams/TestTypeParameters.java b/test/langtools/jdk/javadoc/doclet/testTypeParams/TestTypeParameters.java index b7f33a6be2d..7b007ed3480 100644 --- a/test/langtools/jdk/javadoc/doclet/testTypeParams/TestTypeParameters.java +++ b/test/langtools/jdk/javadoc/doclet/testTypeParams/TestTypeParameters.java @@ -30,12 +30,14 @@ * class-use pages. The class/annotation pages should check for type * parameter links in the class/annotation signature section when -linksource is set. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTypeParameters */ +import javadoc.tester.JavadocTester; + public class TestTypeParameters extends JavadocTester { public static void main(String... args) throws Exception { @@ -44,7 +46,7 @@ public class TestTypeParameters extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-use", "-sourcepath", testSrc, @@ -74,7 +76,7 @@ public class TestTypeParameters extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out-1-html4", "-html4", "-use", @@ -90,7 +92,7 @@ public class TestTypeParameters extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-linksource", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testTypeVariableLinks/TestTypeVariableLinks.java b/test/langtools/jdk/javadoc/doclet/testTypeVariableLinks/TestTypeVariableLinks.java index b86f0a27817..3de2def3bb8 100644 --- a/test/langtools/jdk/javadoc/doclet/testTypeVariableLinks/TestTypeVariableLinks.java +++ b/test/langtools/jdk/javadoc/doclet/testTypeVariableLinks/TestTypeVariableLinks.java @@ -25,12 +25,14 @@ * @test * @bug 8174805 8182765 * @summary JavacTrees should use Types.skipTypeVars() to get the upper bound of type variables - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestTypeVariableLinks */ +import javadoc.tester.JavadocTester; + public class TestTypeVariableLinks extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestTypeVariableLinks extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out", "-sourcepath", testSrc, "-package", @@ -57,7 +59,7 @@ public class TestTypeVariableLinks extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testUnicode/TestUnicode.java b/test/langtools/jdk/javadoc/doclet/testUnicode/TestUnicode.java index 8ff903815c7..db19ef0ffb7 100644 --- a/test/langtools/jdk/javadoc/doclet/testUnicode/TestUnicode.java +++ b/test/langtools/jdk/javadoc/doclet/testUnicode/TestUnicode.java @@ -25,9 +25,9 @@ * @test * @bug 8203176 * @summary javadoc handles non-ASCII characters incorrectly - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestUnicode */ @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; import toolbox.ToolBox; public class TestUnicode extends JavadocTester { @@ -47,7 +48,7 @@ public class TestUnicode extends JavadocTester { ToolBox tb = new ToolBox(); @Test - void test() throws Exception { + public void test() throws Exception { char ellipsis = '\u2026'; Path src = Files.createDirectories(Paths.get("src")); tb.writeJavaFiles(src, diff --git a/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java b/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java index 942efa24926..f0599ff5b23 100644 --- a/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java +++ b/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java @@ -27,12 +27,14 @@ * @summary Reference unnamed package as "Unnamed", not empty string. * Generate a package summary for the unnamed package. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestUnnamedPackage */ +import javadoc.tester.JavadocTester; + public class TestUnnamedPackage extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestUnnamedPackage extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testUseOption/TestUseOption.java b/test/langtools/jdk/javadoc/doclet/testUseOption/TestUseOption.java index 841276d0616..a2e9074ee2f 100644 --- a/test/langtools/jdk/javadoc/doclet/testUseOption/TestUseOption.java +++ b/test/langtools/jdk/javadoc/doclet/testUseOption/TestUseOption.java @@ -27,12 +27,14 @@ * 8182765 8196202 * @summary A simple test to ensure class-use files are correct. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestUseOption */ +import javadoc.tester.JavadocTester; + public class TestUseOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -42,7 +44,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out-1", "-sourcepath", testSrc, "-use", @@ -142,7 +144,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test1_html4() { + public void test1_html4() { javadoc("-d", "out-1-html4", "-html4", "-sourcepath", testSrc, @@ -181,7 +183,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-d", "out-2", "-sourcepath", testSrc, "-use", @@ -205,7 +207,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test2_html4() { + public void test2_html4() { javadoc("-d", "out-2-html4", "-html4", "-sourcepath", testSrc, @@ -223,7 +225,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test3() { + public void test3() { javadoc("-d", "out-3", "-sourcepath", testSrc, "-use", @@ -237,7 +239,7 @@ public class TestUseOption extends JavadocTester { } @Test - void test3_html4() { + public void test3_html4() { javadoc("-d", "out-3-html4", "-html4", "-sourcepath", testSrc, diff --git a/test/langtools/jdk/javadoc/doclet/testUserTaglet/TestUserTaglet.java b/test/langtools/jdk/javadoc/doclet/testUserTaglet/TestUserTaglet.java index 1d6c2e3be23..1cdee23ad4b 100644 --- a/test/langtools/jdk/javadoc/doclet/testUserTaglet/TestUserTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testUserTaglet/TestUserTaglet.java @@ -25,12 +25,14 @@ * @test * @bug 8176836 8201817 * @summary Provide Taglet with context - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester InfoTaglet + * @build javadoc.tester.* InfoTaglet * @run main TestUserTaglet */ +import javadoc.tester.JavadocTester; + public class TestUserTaglet extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestUserTaglet extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-d", "out", "-sourcepath", testSrc, "-tagletpath", System.getProperty("test.class.path"), diff --git a/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java b/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java index 62afd55b014..b834b9102d2 100644 --- a/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java +++ b/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTag.java @@ -27,9 +27,9 @@ * @summary This test ensures that the value tag works in all * use cases, the tests are explained below. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestValueTag */ @@ -39,6 +39,8 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import javadoc.tester.JavadocTester; + public class TestValueTag extends JavadocTester { public static void main(String... args) throws Exception { @@ -47,7 +49,7 @@ public class TestValueTag extends JavadocTester { } @Test - void test1() { + public void test1() { javadoc("-d", "out1", "-sourcepath", testSrc, "-tag", "todo", @@ -117,7 +119,7 @@ public class TestValueTag extends JavadocTester { } @Test - void test2() { + public void test2() { javadoc("-Xdoclint:none", "-d", "out2", "-sourcepath", testSrc, @@ -140,7 +142,7 @@ public class TestValueTag extends JavadocTester { } @Test - void test3() { + public void test3() { javadoc("-d", "out3", "-sourcepath", testSrc, "pkg2", "pkg3"); @@ -156,7 +158,7 @@ public class TestValueTag extends JavadocTester { } @Test - void test4() throws IOException { + public void test4() throws IOException { Path base = Paths.get("test4"); Path src = base.resolve("src"); Files.createDirectories(src.resolve("p")); diff --git a/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTagInModule.java b/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTagInModule.java index a1728f26f76..97180bcf26b 100644 --- a/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTagInModule.java +++ b/test/langtools/jdk/javadoc/doclet/testValueTag/TestValueTagInModule.java @@ -25,11 +25,11 @@ * @test * @bug 8210244 * @summary {@value} should be permitted in module documentation - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * @build JavadocTester + * @build javadoc.tester.* * @run main TestValueTagInModule */ @@ -40,6 +40,8 @@ import java.nio.file.Paths; import toolbox.ModuleBuilder; import toolbox.ToolBox; +import javadoc.tester.JavadocTester; + public class TestValueTagInModule extends JavadocTester { final ToolBox tb; @@ -54,7 +56,7 @@ public class TestValueTagInModule extends JavadocTester { } @Test - void test(Path base) throws Exception { + public void test(Path base) throws Exception { Path srcDir = base.resolve("src"); createTestClass(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testVersionOption/TestVersionOption.java b/test/langtools/jdk/javadoc/doclet/testVersionOption/TestVersionOption.java index eb3a5d88cd3..bd337276582 100644 --- a/test/langtools/jdk/javadoc/doclet/testVersionOption/TestVersionOption.java +++ b/test/langtools/jdk/javadoc/doclet/testVersionOption/TestVersionOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,12 +25,14 @@ * @test * @bug 8177048 * @summary javadoc should support --version and --full-version flags - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester TestVersionOption + * @build javadoc.tester.* TestVersionOption * @run main TestVersionOption */ +import javadoc.tester.JavadocTester; + public class TestVersionOption extends JavadocTester { public static void main(String... args) throws Exception { @@ -39,7 +41,7 @@ public class TestVersionOption extends JavadocTester { } @Test - void testFullVersionOption() { + public void testFullVersionOption() { javadoc("--full-version"); checkExit(Exit.OK); @@ -48,7 +50,7 @@ public class TestVersionOption extends JavadocTester { @Test - void testVersionOption() { + public void testVersionOption() { javadoc("--version"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testVersionTag/TestVersionTag.java b/test/langtools/jdk/javadoc/doclet/testVersionTag/TestVersionTag.java index 010b6186ffb..1427f69b339 100644 --- a/test/langtools/jdk/javadoc/doclet/testVersionTag/TestVersionTag.java +++ b/test/langtools/jdk/javadoc/doclet/testVersionTag/TestVersionTag.java @@ -25,9 +25,9 @@ * @test * @bug 8202947 * @summary test the at-version tag, and corresponding option - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build toolbox.ToolBox JavadocTester + * @build toolbox.ToolBox javadoc.tester.* * @run main TestVersionTag */ @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import javadoc.tester.JavadocTester; import toolbox.ToolBox; public class TestVersionTag extends JavadocTester { @@ -58,7 +59,7 @@ public class TestVersionTag extends JavadocTester { } @Test - void testVersion() { + public void testVersion() { javadoc("-d", "out-version", "-sourcepath", src.toString(), "-version", @@ -69,7 +70,7 @@ public class TestVersionTag extends JavadocTester { } @Test - void testNoVersion() { + public void testNoVersion() { javadoc("-d", "out-noversion", "-sourcepath", src.toString(), "pkg"); diff --git a/test/langtools/jdk/javadoc/doclet/testVisibleMembers/TestVisibleMembers.java b/test/langtools/jdk/javadoc/doclet/testVisibleMembers/TestVisibleMembers.java index 44f781c9089..3d2ce8c9346 100644 --- a/test/langtools/jdk/javadoc/doclet/testVisibleMembers/TestVisibleMembers.java +++ b/test/langtools/jdk/javadoc/doclet/testVisibleMembers/TestVisibleMembers.java @@ -26,9 +26,9 @@ * @bug 8025091 8198890 * @summary Verify the presence visible members in the case of * member hiding and overridding. - * @library /tools/lib ../lib + * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester toolbox.ToolBox builder.ClassBuilder + * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder * @run main TestVisibleMembers */ @@ -43,6 +43,8 @@ import builder.ClassBuilder.*; import toolbox.ToolBox; import builder.ClassBuilder; +import javadoc.tester.JavadocTester; + public class TestVisibleMembers extends JavadocTester { final ToolBox tb; @@ -56,7 +58,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testChronoDiamondLeafDetail(Path base) throws Exception { + public void testChronoDiamondLeafDetail(Path base) throws Exception { Path srcDir = base.resolve("src"); emitChronoDiamondLeaf(srcDir); @@ -84,7 +86,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testChronoDiamondLeafSummary(Path base) throws Exception { + public void testChronoDiamondLeafSummary(Path base) throws Exception { Path srcDir = base.resolve("src"); emitChronoDiamondLeaf(srcDir); @@ -182,7 +184,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testNestedInterfaceDetail(Path base) throws Exception { + public void testNestedInterfaceDetail(Path base) throws Exception { Path srcDir = base.resolve("src"); emitNestedInterface(srcDir); @@ -202,7 +204,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testNestedInterfaceSummary(Path base) throws Exception { + public void testNestedInterfaceSummary(Path base) throws Exception { Path srcDir = base.resolve("src"); emitNestedInterface(srcDir); @@ -256,7 +258,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testStreamsMissingLinksDetail(Path base) throws Exception { + public void testStreamsMissingLinksDetail(Path base) throws Exception { Path srcDir = base.resolve("src"); emitStreamsMissingLinks(srcDir); @@ -291,7 +293,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testStreamsMissingLinksSummary(Path base) throws Exception { + public void testStreamsMissingLinksSummary(Path base) throws Exception { Path srcDir = base.resolve("src"); emitStreamsMissingLinks(srcDir); @@ -395,7 +397,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testVisibleMemberTableDetail(Path base) throws Exception { + public void testVisibleMemberTableDetail(Path base) throws Exception { Path srcDir = base.resolve("src"); emitVisibleMemberTable(srcDir); @@ -447,7 +449,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testVisibleMemberTableSummary(Path base) throws Exception { + public void testVisibleMemberTableSummary(Path base) throws Exception { Path srcDir = base.resolve("src"); emitVisibleMemberTable(srcDir); @@ -569,7 +571,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testHiddenMembersDetail(Path base) throws Exception { + public void testHiddenMembersDetail(Path base) throws Exception { Path srcDir = base.resolve("src"); emitHiddenMembers(srcDir); @@ -604,7 +606,7 @@ public class TestVisibleMembers extends JavadocTester { } @Test - void testHiddenMembersSummary(Path base) throws Exception { + public void testHiddenMembersSummary(Path base) throws Exception { Path srcDir = base.resolve("src"); emitHiddenMembers(srcDir); diff --git a/test/langtools/jdk/javadoc/doclet/testWarnBadParamNames/TestWarnBadParamNames.java b/test/langtools/jdk/javadoc/doclet/testWarnBadParamNames/TestWarnBadParamNames.java index 5e3d6ca85da..74032734ce9 100644 --- a/test/langtools/jdk/javadoc/doclet/testWarnBadParamNames/TestWarnBadParamNames.java +++ b/test/langtools/jdk/javadoc/doclet/testWarnBadParamNames/TestWarnBadParamNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,12 +27,14 @@ * @summary Test to make sure that warning is printed when bad parameter * name is used with param. * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestWarnBadParamNames */ +import javadoc.tester.JavadocTester; + public class TestWarnBadParamNames extends JavadocTester { public static void main(String... args) throws Exception { @@ -41,7 +43,7 @@ public class TestWarnBadParamNames extends JavadocTester { } @Test - void test() { + public void test() { javadoc("-Xdoclint:none", "-d", "out", testSrc("C.java")); diff --git a/test/langtools/jdk/javadoc/doclet/testWarnings/TestWarnings.java b/test/langtools/jdk/javadoc/doclet/testWarnings/TestWarnings.java index 9287d379ba5..6b3fc5f1355 100644 --- a/test/langtools/jdk/javadoc/doclet/testWarnings/TestWarnings.java +++ b/test/langtools/jdk/javadoc/doclet/testWarnings/TestWarnings.java @@ -30,12 +30,14 @@ * a "link unresolved" warning. * Make sure error message starts with "error -". * @author jamieh - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestWarnings */ +import javadoc.tester.JavadocTester; + public class TestWarnings extends JavadocTester { public static void main(String... args) throws Exception { TestWarnings tester = new TestWarnings(); @@ -43,7 +45,7 @@ public class TestWarnings extends JavadocTester { } @Test - void testDefault() { + public void testDefault() { javadoc("-d", "out-default", "-sourcepath", testSrc, "pkg"); @@ -70,7 +72,7 @@ public class TestWarnings extends JavadocTester { } @Test - void testPrivate() { + public void testPrivate() { javadoc("-d", "out-private", "-private", "-sourcepath", testSrc, @@ -84,7 +86,7 @@ public class TestWarnings extends JavadocTester { } @Test - void testPrivate_html4() { + public void testPrivate_html4() { javadoc("-d", "out-private-html4", "-html4", "-private", diff --git a/test/langtools/jdk/javadoc/doclet/testWindowTitle/TestWindowTitle.java b/test/langtools/jdk/javadoc/doclet/testWindowTitle/TestWindowTitle.java index e147c3bf8c4..44f18639da3 100644 --- a/test/langtools/jdk/javadoc/doclet/testWindowTitle/TestWindowTitle.java +++ b/test/langtools/jdk/javadoc/doclet/testWindowTitle/TestWindowTitle.java @@ -26,11 +26,13 @@ * @bug 8016675 8026736 8196202 * @summary Test for window title. * @author Bhavesh Patel - * @library ../lib + * @library ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool - * @build JavadocTester + * @build javadoc.tester.* * @run main TestWindowTitle */ +import javadoc.tester.JavadocTester; + public class TestWindowTitle extends JavadocTester { public static void main(String... args) throws Exception { @@ -40,7 +42,7 @@ public class TestWindowTitle extends JavadocTester { } @Test - void testJavaScriptChars() { + public void testJavaScriptChars() { // Window title with JavaScript special characters. String title = "Testing \"Window 'Title'\" with a \\ backslash and a / " + "forward slash and a \u00e8 unicode char also a tab and also a " @@ -67,7 +69,7 @@ public class TestWindowTitle extends JavadocTester { } @Test - void testScriptTag() { + public void testScriptTag() { // Window title with a script tag. String title = "Testing script tag in title ."; @@ -100,7 +102,7 @@ public class TestWindowTitle extends JavadocTester { } @Test - void testHtmlTags() { + public void testHtmlTags() { // Window title with other HTML tags. String title = "Testing another

      HTML

      tag. Another

      tag

      . A " + "tag with attributes.

  • Event setting names and their purpose.
    ", CODE)); @@ -560,8 +577,7 @@ public class ModuleSummary { .forEach(s -> sb.append("uses ").append(s).append("
    ").append("\n")); ms.descriptor().provides().stream() .sorted(Comparator.comparing(Provides::service)) - .map(p -> String.format("provides %s
        with %s", - p.service(), p.providers())) + .map(this::providesEntry) .forEach(p -> sb.append(p).append("
    ").append("\n")); sb.append("