From b98290444a4594d0164d6f313c506287282d1929 Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Thu, 16 Sep 2021 23:26:55 +0000 Subject: [PATCH 001/544] 8271073: Improve testing with VM option VerifyArchivedFields Reviewed-by: ccheung, minqi --- src/hotspot/share/cds/heapShared.cpp | 29 ++++++---- src/hotspot/share/gc/shared/gc_globals.hpp | 8 ++- .../jtreg/runtime/cds/appcds/TestCommon.java | 2 + .../cacheObject/VerifyArchivedFields.java | 53 +++++++++++++++++++ test/lib/jdk/test/lib/cds/CDSTestUtils.java | 7 +++ 5 files changed, 86 insertions(+), 13 deletions(-) create mode 100644 test/hotspot/jtreg/runtime/cds/appcds/cacheObject/VerifyArchivedFields.java diff --git a/src/hotspot/share/cds/heapShared.cpp b/src/hotspot/share/cds/heapShared.cpp index 53762408320..821e6594faa 100644 --- a/src/hotspot/share/cds/heapShared.cpp +++ b/src/hotspot/share/cds/heapShared.cpp @@ -674,7 +674,7 @@ void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) { } static void verify_the_heap(Klass* k, const char* which) { - if (VerifyArchivedFields) { + if (VerifyArchivedFields > 0) { ResourceMark rm; log_info(cds, heap)("Verify heap %s initializing static field(s) in %s", which, k->external_name()); @@ -682,15 +682,20 @@ static void verify_the_heap(Klass* k, const char* which) { VM_Verify verify_op; VMThread::execute(&verify_op); - if (!FLAG_IS_DEFAULT(VerifyArchivedFields)) { - // If VerifyArchivedFields has a non-default value (e.g., specified on the command-line), do - // more expensive checks. - if (is_init_completed()) { - FlagSetting fs1(VerifyBeforeGC, true); - FlagSetting fs2(VerifyDuringGC, true); - FlagSetting fs3(VerifyAfterGC, true); - Universe::heap()->collect(GCCause::_java_lang_system_gc); - } + if (VerifyArchivedFields > 1 && is_init_completed()) { + // At this time, the oop->klass() of some archived objects in the heap may not + // have been loaded into the system dictionary yet. Nevertheless, oop->klass() should + // have enough information (object size, oop maps, etc) so that a GC can be safely + // performed. + // + // -XX:VerifyArchivedFields=2 force a GC to happen in such an early stage + // to check for GC safety. + log_info(cds, heap)("Trigger GC %s initializing static field(s) in %s", + which, k->external_name()); + FlagSetting fs1(VerifyBeforeGC, true); + FlagSetting fs2(VerifyDuringGC, true); + FlagSetting fs3(VerifyAfterGC, true); + Universe::heap()->collect(GCCause::_java_lang_system_gc); } } } @@ -1707,10 +1712,12 @@ class VerifyLoadedHeapEmbeddedPointers: public BasicOopIterateClosure { }; void HeapShared::verify_loaded_heap() { - if (!VerifyArchivedFields || !is_loaded()) { + if (VerifyArchivedFields <= 0 || !is_loaded()) { return; } + log_info(cds, heap)("Verify all oops and pointers in loaded heap"); + ResourceMark rm; ResourceHashtable table; VerifyLoadedHeapEmbeddedPointers verifier(&table); diff --git a/src/hotspot/share/gc/shared/gc_globals.hpp b/src/hotspot/share/gc/shared/gc_globals.hpp index eb5ab3b669e..730e5f616bb 100644 --- a/src/hotspot/share/gc/shared/gc_globals.hpp +++ b/src/hotspot/share/gc/shared/gc_globals.hpp @@ -523,8 +523,12 @@ product(bool, VerifyDuringGC, false, DIAGNOSTIC, \ "Verify memory system during GC (between phases)") \ \ - product(bool, VerifyArchivedFields, trueInDebug, DIAGNOSTIC, \ - "Verify memory when archived oop fields are loaded from CDS)") \ + product(int, VerifyArchivedFields, 0, DIAGNOSTIC, \ + "Verify memory when archived oop fields are loaded from CDS; " \ + "0: No check; " \ + "1: Basic verification with VM_Verify (no side effects); " \ + "2: Detailed verification by forcing a GC (with side effects)") \ + range(0, 2) \ \ product(ccstrlist, VerifyGCType, "", DIAGNOSTIC, \ "GC type(s) to verify when Verify*GC is enabled." \ diff --git a/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java b/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java index fc10384b4d1..a90512f73fb 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java @@ -409,6 +409,8 @@ public class TestCommon extends CDSTestUtils { cmd.add(opts.appJar); } + CDSTestUtils.addVerifyArchivedFields(cmd); + for (String s : opts.suffix) cmd.add(s); if (RUN_WITH_JFR) { diff --git a/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/VerifyArchivedFields.java b/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/VerifyArchivedFields.java new file mode 100644 index 00000000000..80eebf60811 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/VerifyArchivedFields.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 run with -XX:VerifyArchivedFields=2 for more expensive verification + * of the archived heap objects. + * @requires vm.cds.write.archived.java.heap + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds /test/hotspot/jtreg/runtime/cds/appcds/test-classes + * @build Hello + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar Hello.jar Hello + * @run driver VerifyArchivedFields + */ + +import jdk.test.lib.helpers.ClassFileInstaller; + +public class VerifyArchivedFields { + // Note: -XX:VerifyArchivedFields=2 will force a GC every time when + // HeapShared::initialize_from_archived_subgraph(Klass* k, ...) is called. This ensures + // that it's safe to do a GC even when the oop->klass() of some archived heap objects + // are not yet loaded into the system dictionary. + public static void main(String[] args) throws Exception { + TestCommon.test(ClassFileInstaller.getJarPath("Hello.jar"), + TestCommon.list("Hello"), + "-XX:+UnlockDiagnosticVMOptions", + "-XX:VerifyArchivedFields=2", + "-Xlog:cds=debug", + "-Xlog:cds+heap=debug", + "-Xlog:gc*=debug", + "Hello"); + } +} diff --git a/test/lib/jdk/test/lib/cds/CDSTestUtils.java b/test/lib/jdk/test/lib/cds/CDSTestUtils.java index 4bc91321a1f..c3ce3a95504 100644 --- a/test/lib/jdk/test/lib/cds/CDSTestUtils.java +++ b/test/lib/jdk/test/lib/cds/CDSTestUtils.java @@ -399,6 +399,12 @@ public class CDSTestUtils { .addPrefix(cliPrefix) ); } + // Enable basic verification (VerifyArchivedFields=1, no side effects) for all CDS + // tests to make sure the archived heap objects are mapped/loaded properly. + public static void addVerifyArchivedFields(ArrayList cmd) { + cmd.add("-XX:+UnlockDiagnosticVMOptions"); + cmd.add("-XX:VerifyArchivedFields=1"); + } // Execute JVM with CDS archive, specify CDSOptions public static OutputAnalyzer runWithArchive(CDSOptions opts) @@ -413,6 +419,7 @@ public class CDSTestUtils { opts.archiveName = getDefaultArchiveName(); cmd.add("-XX:SharedArchiveFile=" + opts.archiveName); } + addVerifyArchivedFields(cmd); if (opts.useVersion) cmd.add("-version"); -- GitLab From 8c022e2c174cca2b03e8fdf4fadad42bc11c65f1 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Thu, 16 Sep 2021 23:45:08 +0000 Subject: [PATCH 002/544] 8270434: JDI+UT: Unexpected event in JDI tests Reviewed-by: sspitsyn, kevinw --- .../EventIterator/nextEvent/nextevent001.java | 8 ++++--- .../methodEntryRequests/methentreq002.java | 4 ++-- .../vmTestbase/nsk/share/jdi/JDIBase.java | 21 +++++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java index 64f98ba53bf..444382bbdb1 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -320,6 +320,8 @@ public class nextevent001 extends JDIBase { log1(" TESTING BEGINS"); { + final String testThreadName = "thread2"; + log2("......setting up ThreadStartRequest"); ThreadStartRequest tsr = eventRManager.createThreadStartRequest(); tsr.addCountFilter(1); @@ -342,7 +344,7 @@ public class nextevent001 extends JDIBase { vm.resume(); log2("......waiting for ThreadStartEvent"); - getEventSet(); + getEventSetForThreadStartDeath(testThreadName); eventSets[10] = eventSet; Event receivedEvent = eventIterator.nextEvent(); @@ -357,7 +359,7 @@ public class nextevent001 extends JDIBase { vm.resume(); log2("......waiting for ThreadDeathEvent"); - getEventSet(); + getEventSetForThreadStartDeath(testThreadName); eventSets[9] = eventSet; receivedEvent = eventIterator.nextEvent(); if ( !(receivedEvent instanceof ThreadDeathEvent) ) { diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventRequestManager/methodEntryRequests/methentreq002.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventRequestManager/methodEntryRequests/methentreq002.java index 691ce87e0d3..6b6fd054412 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventRequestManager/methodEntryRequests/methentreq002.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventRequestManager/methodEntryRequests/methentreq002.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -266,7 +266,7 @@ public class methentreq002 extends JDIBase { for (int i = 0; ; i++) { vm.resume(); - breakpointForCommunication(); + breakpointForCommunication(debuggeeName); int instruction = ((IntegerValue) (debuggeeClass.getValue(debuggeeClass.fieldByName("instruction")))).value(); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java index 4b2f1381828..da8c49119b7 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java @@ -197,4 +197,25 @@ public class JDIBase { throw new JDITestRuntimeException("** event '" + event + "' IS NOT a breakpoint **"); } + // Similar to breakpointForCommunication, but skips Locatable events from unexpected locations. + // It's useful for cases when enabled event requests can cause notifications from system threads + // (like MethodEntryRequest, MethodExitRequest). + protected void breakpointForCommunication(String debuggeeName) throws JDITestRuntimeException { + log2("breakpointForCommunication"); + while (true) { + getEventSet(); + + Event event = eventIterator.nextEvent(); + if (event instanceof BreakpointEvent) { + return; + } + if (EventFilters.filtered(event, debuggeeName)) { + log2(" got unexpected event: " + event + ", skipping"); + eventSet.resume(); + } else { + throw new JDITestRuntimeException("** event '" + event + "' IS NOT a breakpoint **"); + } + } + } + } -- GitLab From e07ab82ee555f27921287a871ba582e0906ad45c Mon Sep 17 00:00:00 2001 From: Guoxiong Li Date: Fri, 17 Sep 2021 05:34:25 +0000 Subject: [PATCH 003/544] 8273408: java.lang.AssertionError: typeSig ERROR on generated class property of record Reviewed-by: vromero --- .../com/sun/tools/javac/code/Symbol.java | 18 +- .../GenerateTypeProcessor.java | 59 ++++++ .../RecordComponentTypeTest.java | 168 ++++++++++++++++++ 3 files changed, 243 insertions(+), 2 deletions(-) create mode 100644 test/langtools/tools/javac/records/recordComponent/GenerateTypeProcessor.java create mode 100644 test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java index a9cd16970fb..17dc60c1a88 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java @@ -1504,16 +1504,30 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem } public RecordComponent getRecordComponent(JCVariableDecl var, boolean addIfMissing, List annotations) { + RecordComponent toRemove = null; for (RecordComponent rc : recordComponents) { /* it could be that a record erroneously declares two record components with the same name, in that * case we need to use the position to disambiguate */ if (rc.name == var.name && var.pos == rc.pos) { - return rc; + if (rc.type.hasTag(TypeTag.ERROR) && !var.sym.type.hasTag(TypeTag.ERROR)) { + // Found a record component with an erroneous type: save it so that it can be removed later. + // If the class type of the record component is generated by annotation processor, it should + // use the new actual class type and symbol instead of the old dummy ErrorType. + toRemove = rc; + } else { + // Found a good record component: just return. + return rc; + } } } RecordComponent rc = null; - if (addIfMissing) { + if (toRemove != null) { + // Found a record component with an erroneous type: remove it and create a new one + recordComponents = List.filter(recordComponents, toRemove); + recordComponents = recordComponents.append(rc = new RecordComponent(var.sym, annotations)); + } else if (addIfMissing) { + // Didn't find the record component: create one. recordComponents = recordComponents.append(rc = new RecordComponent(var.sym, annotations)); } return rc; diff --git a/test/langtools/tools/javac/records/recordComponent/GenerateTypeProcessor.java b/test/langtools/tools/javac/records/recordComponent/GenerateTypeProcessor.java new file mode 100644 index 00000000000..230f3708f8b --- /dev/null +++ b/test/langtools/tools/javac/records/recordComponent/GenerateTypeProcessor.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Set; + +@SupportedAnnotationTypes("*") +public class GenerateTypeProcessor extends AbstractProcessor { + + private String code = "public class GeneratedType { }"; + + private boolean firstTime = true; + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + // Create a new class: GeneratedType + if (firstTime) { + try (OutputStream out = + processingEnv.getFiler().createSourceFile("GeneratedType").openOutputStream()) { + out.write(code.getBytes()); + } catch (IOException ex) { + ex.printStackTrace(); + } + firstTime = false; + } + return false; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latest(); + } +} diff --git a/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java b/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java new file mode 100644 index 00000000000..46418a66d83 --- /dev/null +++ b/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8273408 + * @summary The compiler shouldn't crash when record component uses the class generated by the annotation processor. + * @library /tools/lib + * @modules jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.jdeps/com.sun.tools.classfile + * @compile GenerateTypeProcessor.java + * @run main RecordComponentTypeTest + */ + +import com.sun.tools.classfile.*; + +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +import toolbox.JavacTask; +import toolbox.TestRunner; +import toolbox.ToolBox; +import toolbox.Task; + +public class RecordComponentTypeTest extends TestRunner { + + ToolBox tb; + ClassFile cf; + + public RecordComponentTypeTest() { + super(System.err); + tb = new ToolBox(); + } + + public static void main(String[] args) throws Exception { + RecordComponentTypeTest t = new RecordComponentTypeTest(); + t.runTests(); + } + + @Test + public void testRecordComponentUsingGeneratedType() throws Exception { + String code = "public record RecordComponentUsingGeneratedType(GeneratedType generatedType) { }"; + Path curPath = Path.of("."); + + // Have no annotation processor. + List output = new JavacTask(tb) + .sources(code) + .outdir(curPath) + .options("-XDrawDiagnostics") + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + List expected = Arrays.asList( + "RecordComponentUsingGeneratedType.java:1:49: compiler.err.cant.resolve.location: kindname.class, " + + "GeneratedType, , , (compiler.misc.location: kindname.class, RecordComponentUsingGeneratedType, null)", + "1 error"); + tb.checkEqual(expected, output); + + // Have annotation processor, and processor generates expected type. + new JavacTask(tb) + .sources(code) + .options("-processor", "GenerateTypeProcessor") + .outdir(curPath) + .run(); + } + + @Test + public void testRecordComponentUsingUnknownType() throws Exception { + String code = "public record RecordComponentUsingUnknownType(UnknownType unknownType) { }"; + Path curPath = Path.of("."); + + // Have no annotation processor. + List output = new JavacTask(tb) + .sources(code) + .outdir(curPath) + .options("-XDrawDiagnostics") + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + List expected = Arrays.asList( + "RecordComponentUsingUnknownType.java:1:47: compiler.err.cant.resolve.location: kindname.class, " + + "UnknownType, , , (compiler.misc.location: kindname.class, RecordComponentUsingUnknownType, null)", + "1 error"); + tb.checkEqual(expected, output); + + // Have annotation processor, but processor doesn't generate the expected type. + List output2 = new JavacTask(tb) + .sources(code) + .outdir(curPath) + .options("-XDrawDiagnostics", "-processor", "GenerateTypeProcessor") + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + List expected2 = Arrays.asList( + "RecordComponentUsingUnknownType.java:1:47: compiler.err.cant.resolve.location: kindname.class, " + + "UnknownType, , , (compiler.misc.location: kindname.class, RecordComponentUsingUnknownType, null)", + "1 error"); + tb.checkEqual(expected2, output2); + } + + + @Test + public void testRecordComponentUsingGeneratedTypeWithAnnotation() throws Exception { + String code = """ + import java.lang.annotation.Retention; + import java.lang.annotation.RetentionPolicy; + public record RecordComponentUsingGeneratedTypeWithAnnotation(@TestAnnotation GeneratedType generatedType) { } + + @Retention(RetentionPolicy.RUNTIME) + @interface TestAnnotation { } + """; + Path curPath = Path.of("."); + new JavacTask(tb) + .sources(code) + .options("-processor", "GenerateTypeProcessor") + .outdir(curPath) + .run(); + cf = ClassFile.read(curPath.resolve("RecordComponentUsingGeneratedTypeWithAnnotation.class")); + + for (Field field : cf.fields) { + if ("generatedType".equals(field.getName(cf.constant_pool))) { + checkRuntimeVisibleAnnotation(field.attributes); + } + } + + for (Method method : cf.methods) { + if ("generatedType".equals(method.getName(cf.constant_pool))) { + checkRuntimeVisibleAnnotation(method.attributes); + } + } + } + + private void checkRuntimeVisibleAnnotation(Attributes attributes) throws Exception { + RuntimeVisibleAnnotations_attribute annotations = + (RuntimeVisibleAnnotations_attribute) attributes.get(Attribute.RuntimeVisibleAnnotations); + boolean hasAnnotation = false; + for (Annotation annotation : annotations.annotations) { + if ("LTestAnnotation;".equals(cf.constant_pool.getUTF8Value(annotation.type_index))) { + hasAnnotation = true; + } + } + if (!hasAnnotation) { + throw new AssertionError("Expected RuntimeVisibleAnnotation doesn't appear"); + } + } +} -- GitLab From 54b456764bedb53adb7ae3c25f64d44dd8322ada Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Fri, 17 Sep 2021 06:44:18 +0000 Subject: [PATCH 004/544] 8273880: Zero: Print warnings when unsupported intrinsics are enabled Reviewed-by: dholmes --- src/hotspot/cpu/zero/vm_version_zero.cpp | 65 ++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/hotspot/cpu/zero/vm_version_zero.cpp b/src/hotspot/cpu/zero/vm_version_zero.cpp index 1efd9896863..8b49a084be2 100644 --- a/src/hotspot/cpu/zero/vm_version_zero.cpp +++ b/src/hotspot/cpu/zero/vm_version_zero.cpp @@ -50,6 +50,71 @@ void VM_Version::initialize() { FLAG_SET_DEFAULT(UseHeavyMonitors, true); } + if (UseAESIntrinsics) { + warning("AES intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseAESIntrinsics, false); + } + + if (UseAES) { + warning("AES instructions are not available on this CPU"); + FLAG_SET_DEFAULT(UseAES, false); + } + + if (UseAESCTRIntrinsics) { + warning("AES/CTR intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseAESCTRIntrinsics, false); + } + + if (UseFMA) { + warning("FMA instructions are not available on this CPU"); + FLAG_SET_DEFAULT(UseFMA, false); + } + + if (UseMD5Intrinsics) { + warning("MD5 intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseMD5Intrinsics, false); + } + + if (UseSHA) { + warning("SHA instructions are not available on this CPU"); + FLAG_SET_DEFAULT(UseSHA, false); + } + + if (UseSHA1Intrinsics) { + warning("Intrinsics for SHA-1 crypto hash functions not available on this CPU."); + FLAG_SET_DEFAULT(UseSHA1Intrinsics, false); + } + + if (UseSHA256Intrinsics) { + warning("Intrinsics for SHA-224 and SHA-256 crypto hash functions not available on this CPU."); + FLAG_SET_DEFAULT(UseSHA256Intrinsics, false); + } + + if (UseSHA512Intrinsics) { + warning("Intrinsics for SHA-384 and SHA-512 crypto hash functions not available on this CPU."); + FLAG_SET_DEFAULT(UseSHA512Intrinsics, false); + } + + if (UseSHA3Intrinsics) { + warning("Intrinsics for SHA3-224, SHA3-256, SHA3-384 and SHA3-512 crypto hash functions not available on this CPU."); + FLAG_SET_DEFAULT(UseSHA3Intrinsics, false); + } + + if (UseCRC32Intrinsics) { + warning("CRC32 intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseCRC32Intrinsics, false); + } + + if (UseAdler32Intrinsics) { + warning("Adler32 intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseAdler32Intrinsics, false); + } + + if (UseVectorizedMismatchIntrinsic) { + warning("vectorizedMismatch intrinsic is not available on this CPU."); + FLAG_SET_DEFAULT(UseVectorizedMismatchIntrinsic, false); + } + // Not implemented UNSUPPORTED_OPTION(CriticalJNINatives); } -- GitLab From 1890d85c0e647d3f890e3c7152f8cd2e60dfd826 Mon Sep 17 00:00:00 2001 From: Per Liden Date: Fri, 17 Sep 2021 07:51:45 +0000 Subject: [PATCH 005/544] 8273872: ZGC: Explicitly use 2M large pages Reviewed-by: eosterlund, tschatzl, stefank --- .../gc/z/zPhysicalMemoryBacking_linux.cpp | 18 +++++++++--------- src/hotspot/share/gc/z/zArguments.cpp | 7 +++++++ 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp b/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp index 7a113055423..951b98d6cce 100644 --- a/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp +++ b/src/hotspot/os/linux/gc/z/zPhysicalMemoryBacking_linux.cpp @@ -58,6 +58,9 @@ #ifndef MFD_HUGETLB #define MFD_HUGETLB 0x0004U #endif +#ifndef MFD_HUGE_2MB +#define MFD_HUGE_2MB 0x54000000U +#endif // open(2) flags #ifndef O_CLOEXEC @@ -175,12 +178,6 @@ ZPhysicalMemoryBacking::ZPhysicalMemoryBacking(size_t max_capacity) : return; } - if (ZLargePages::is_explicit() && os::large_page_size() != ZGranuleSize) { - log_error_p(gc)("Incompatible large page size configured " SIZE_FORMAT " (expected " SIZE_FORMAT ")", - os::large_page_size(), ZGranuleSize); - return; - } - // Make sure the filesystem block size is compatible if (ZGranuleSize % _block_size != 0) { log_error_p(gc)("Filesystem backing the heap has incompatible block size (" SIZE_FORMAT ")", @@ -199,17 +196,20 @@ ZPhysicalMemoryBacking::ZPhysicalMemoryBacking(size_t max_capacity) : } int ZPhysicalMemoryBacking::create_mem_fd(const char* name) const { + assert(ZGranuleSize == 2 * M, "Granule size must match MFD_HUGE_2MB"); + // Create file name char filename[PATH_MAX]; snprintf(filename, sizeof(filename), "%s%s", name, ZLargePages::is_explicit() ? ".hugetlb" : ""); // Create file - const int extra_flags = ZLargePages::is_explicit() ? MFD_HUGETLB : 0; + const int extra_flags = ZLargePages::is_explicit() ? (MFD_HUGETLB | MFD_HUGE_2MB) : 0; const int fd = ZSyscall::memfd_create(filename, MFD_CLOEXEC | extra_flags); if (fd == -1) { ZErrno err; log_debug_p(gc, init)("Failed to create memfd file (%s)", - ((ZLargePages::is_explicit() && err == EINVAL) ? "Hugepages not supported" : err.to_string())); + (ZLargePages::is_explicit() && (err == EINVAL || err == ENODEV)) ? + "Hugepages (2M) not available" : err.to_string()); return -1; } @@ -445,7 +445,7 @@ ZErrno ZPhysicalMemoryBacking::fallocate_compat_mmap_tmpfs(size_t offset, size_t } // Advise mapping to use transparent huge pages - os::realign_memory((char*)addr, length, os::large_page_size()); + os::realign_memory((char*)addr, length, ZGranuleSize); // Touch the mapping (safely) to make sure it's backed by memory const bool backed = safe_touch_mapping(addr, length, _block_size); diff --git a/src/hotspot/share/gc/z/zArguments.cpp b/src/hotspot/share/gc/z/zArguments.cpp index e22db0c52a8..ad59d2fbcec 100644 --- a/src/hotspot/share/gc/z/zArguments.cpp +++ b/src/hotspot/share/gc/z/zArguments.cpp @@ -72,6 +72,13 @@ void ZArguments::initialize() { vm_exit_during_initialization("The flag -XX:+UseZGC can not be combined with -XX:ConcGCThreads=0"); } + // Large page size must match granule size + if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != ZGranuleSize) { + vm_exit_during_initialization(err_msg("Incompatible -XX:LargePageSizeInBytes, only " + SIZE_FORMAT "M large pages are supported by ZGC", + ZGranuleSize / M)); + } + // The heuristics used when UseDynamicNumberOfGCThreads is // enabled defaults to using a ZAllocationSpikeTolerance of 1. if (UseDynamicNumberOfGCThreads && FLAG_IS_DEFAULT(ZAllocationSpikeTolerance)) { -- GitLab From 35f6f1d69f4238f16595b9b8f1d11db9e49d4cc9 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Fri, 17 Sep 2021 08:20:10 +0000 Subject: [PATCH 006/544] 8273808: Cleanup AddFontsToX11FontPath Reviewed-by: pbansal, lucy --- .../unix/native/common/awt/fontpath.c | 136 +----------------- 1 file changed, 1 insertion(+), 135 deletions(-) diff --git a/src/java.desktop/unix/native/common/awt/fontpath.c b/src/java.desktop/unix/native/common/awt/fontpath.c index fa5fc982327..c4b2fcb73c0 100644 --- a/src/java.desktop/unix/native/common/awt/fontpath.c +++ b/src/java.desktop/unix/native/common/awt/fontpath.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -135,140 +135,6 @@ jboolean isDisplayLocal(JNIEnv *env) { return isLocal; } -static void AddFontsToX11FontPath ( fDirRecord *fDirP ) -{ - char *onePath; - int index, nPaths; - int origNumPaths, length; - int origIndex; - int totalDirCount; - char **origFontPath; - char **tempFontPath; - int doNotAppend; - int *appendDirList; - char **newFontPath; - int err, compareLength; - char fontDirPath[512]; - int dirFile; - - doNotAppend = 0; - - if ( fDirP->num == 0 ) return; - - appendDirList = SAFE_SIZE_ARRAY_ALLOC(malloc, fDirP->num, sizeof ( int )); - if ( appendDirList == NULL ) { - return; /* if it fails we cannot do much */ - } - - origFontPath = XGetFontPath ( awt_display, &nPaths ); - - totalDirCount = nPaths; - origNumPaths = nPaths; - tempFontPath = origFontPath; - - - for (index = 0; index < fDirP->num; index++ ) { - - doNotAppend = 0; - - tempFontPath = origFontPath; - for ( origIndex = 0; origIndex < nPaths; origIndex++ ) { - - onePath = *tempFontPath; - - compareLength = strlen ( onePath ); - if ( onePath[compareLength -1] == '/' ) - compareLength--; - - /* there is a slash at the end of every solaris X11 font path name */ - if ( strncmp ( onePath, fDirP->name[index], compareLength ) == 0 ) { - doNotAppend = 1; - break; - } - tempFontPath++; - } - - appendDirList[index] = 0; - if ( doNotAppend == 0 ) { - snprintf(fontDirPath, sizeof(fontDirPath), "%s/fonts.dir", fDirP->name[index]); - fontDirPath[sizeof(fontDirPath) - 1] = '\0'; - dirFile = open ( fontDirPath, O_RDONLY, 0 ); - if ( dirFile == -1 ) { - doNotAppend = 1; - } else { - close ( dirFile ); - totalDirCount++; - appendDirList[index] = 1; - } - } - - } - - /* if no changes are required do not bother to do a setfontpath */ - if ( totalDirCount == nPaths ) { - free ( ( void *) appendDirList ); - XFreeFontPath ( origFontPath ); - return; - } - - - newFontPath = SAFE_SIZE_ARRAY_ALLOC(malloc, totalDirCount, sizeof(char *)); - /* if it fails free things and get out */ - if ( newFontPath == NULL ) { - free ( ( void *) appendDirList ); - XFreeFontPath ( origFontPath ); - return; - } - - for ( origIndex = 0; origIndex < nPaths; origIndex++ ) { - onePath = origFontPath[origIndex]; - newFontPath[origIndex] = onePath; - } - - /* now add the other font paths */ - - for (index = 0; index < fDirP->num; index++ ) { - - if ( appendDirList[index] == 1 ) { - - /* printf ( "Appending %s\n", fDirP->name[index] ); */ - - onePath = SAFE_SIZE_ARRAY_ALLOC(malloc, strlen (fDirP->name[index]) + 2, sizeof( char ) ); - if (onePath == NULL) { - free ( ( void *) appendDirList ); - - for ( index = origIndex; index < nPaths; index++ ) { - free( newFontPath[index] ); - } - - free( ( void *) newFontPath); - XFreeFontPath ( origFontPath ); - return; - } - strcpy ( onePath, fDirP->name[index] ); - strcat ( onePath, "/" ); - newFontPath[nPaths++] = onePath; - /* printf ( "The path to be appended is %s\n", onePath ); */ - } - } - - /* printf ( "The dir count = %d\n", totalDirCount ); */ - free ( ( void *) appendDirList ); - - XSetFontPath ( awt_display, newFontPath, totalDirCount ); - - for ( index = origNumPaths; index < totalDirCount; index++ ) { - free( newFontPath[index] ); - } - - free ( (void *) newFontPath ); - XFreeFontPath ( origFontPath ); - return; -} -#endif /* !HEADLESS */ - - -#ifndef HEADLESS static char **getX11FontPath () { char **x11Path, **fontdirs; -- GitLab From 27d747ad4f13193d5fc651d893540465248c48a6 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Fri, 17 Sep 2021 12:53:38 +0000 Subject: [PATCH 007/544] 8273877: os::unsetenv unused Reviewed-by: mdoerr, stuefe --- src/hotspot/os/posix/os_posix.cpp | 6 ------ src/hotspot/os/windows/os_windows.cpp | 5 ----- src/hotspot/share/runtime/os.hpp | 2 -- 3 files changed, 13 deletions(-) diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp index 07ee653ecf5..4b0c98bc1de 100644 --- a/src/hotspot/os/posix/os_posix.cpp +++ b/src/hotspot/os/posix/os_posix.cpp @@ -160,12 +160,6 @@ int os::get_native_stack(address* stack, int frames, int toSkip) { return num_of_frames; } - -bool os::unsetenv(const char* name) { - assert(name != NULL, "Null pointer"); - return (::unsetenv(name) == 0); -} - int os::get_last_error() { return errno; } diff --git a/src/hotspot/os/windows/os_windows.cpp b/src/hotspot/os/windows/os_windows.cpp index 3004cfdcbdc..e6881fa8465 100644 --- a/src/hotspot/os/windows/os_windows.cpp +++ b/src/hotspot/os/windows/os_windows.cpp @@ -258,11 +258,6 @@ static BOOL unmapViewOfFile(LPCVOID lpBaseAddress) { return result; } -bool os::unsetenv(const char* name) { - assert(name != NULL, "Null pointer"); - return (SetEnvironmentVariable(name, NULL) == TRUE); -} - char** os::get_environ() { return _environ; } // No setuid programs under Windows. diff --git a/src/hotspot/share/runtime/os.hpp b/src/hotspot/share/runtime/os.hpp index f821ba1b230..cb26598132e 100644 --- a/src/hotspot/share/runtime/os.hpp +++ b/src/hotspot/share/runtime/os.hpp @@ -186,8 +186,6 @@ class os: AllStatic { static jint init_2(void); // Called after command line parsing // and VM ergonomics processing - // unset environment variable - static bool unsetenv(const char* name); // Get environ pointer, platform independently static char** get_environ(); -- GitLab From 17f7a45ce40ecf0666f282e68be1844d38a5d1c7 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Fri, 17 Sep 2021 15:00:52 +0000 Subject: [PATCH 008/544] 8273913: Problem list some headful client jtreg tests that fail on macOS 12 Reviewed-by: pbansal, aivanov --- test/jdk/ProblemList.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 25269278959..82a412c802f 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -144,6 +144,7 @@ java/awt/Frame/ExceptionOnSetExtendedStateTest/ExceptionOnSetExtendedStateTest.j java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java 8144030 macosx-all,linux-all java/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java 7080150 macosx-all java/awt/event/InputEvent/EventWhenTest/EventWhenTest.java 8168646 generic-all +java/awt/KeyboardFocusmanager/TypeAhead/SubMenuShowTest/SubMenuShowTest.java 8273520 macosx-all java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java 8198626 macosx-all java/awt/Mixing/AWT_Mixing/HierarchyBoundsListenerMixingTest.java 8049405 macosx-all java/awt/Mixing/AWT_Mixing/OpaqueOverlappingChoice.java 8048171 generic-all @@ -257,7 +258,8 @@ sun/java2d/SunGraphics2D/SimplePrimQuality.java 6992007 generic-all sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java 8196185 generic-all sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh 8221451 linux-all -java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469 windows-all +java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469,8273618 windows-all,macosx-all +java/awt/FullScreen/UninitializedDisplayModeChangeTest/UninitializedDisplayModeChangeTest.java 8273617 macosx-all java/awt/print/PrinterJob/PSQuestionMark.java 7003378 generic-all java/awt/print/PrinterJob/GlyphPositions.java 7003378 generic-all java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java 7100044 macosx-all,linux-all @@ -745,6 +747,8 @@ javax/swing/JEditorPane/6917744/bug6917744.java 8213124 macosx-all javax/swing/JRootPane/4670486/bug4670486.java 8042381 macosx-all javax/swing/JPopupMenu/4634626/bug4634626.java 8017175 macosx-all javax/swing/JButton/8151303/PressedIconTest.java 8266246 macosx-aarch64 +javax/swing/JMenu/4515762/bug4515762.java 8273578 macosx-all +javax/swing/JMenuItem/ActionListenerCalledTwice/ActionListenerCalledTwiceTest.java 8273573 macosx-all sanity/client/SwingSet/src/ToolTipDemoTest.java 8225012 windows-all,macosx-all sanity/client/SwingSet/src/ScrollPaneDemoTest.java 8225013 linux-all -- GitLab From 2f8c2211c8c7f9661e283c8df914fde5bda197a6 Mon Sep 17 00:00:00 2001 From: Kartik Ohri Date: Fri, 17 Sep 2021 15:12:34 +0000 Subject: [PATCH 009/544] 8273681: Add Vector API vs Arrays.mismatch intrinsic benchmark Reviewed-by: psandoz --- .../vector/ArrayMismatchBenchmark.java | 229 ++++++++++++++++++ 1 file changed, 229 insertions(+) create mode 100644 test/micro/org/openjdk/bench/jdk/incubator/vector/ArrayMismatchBenchmark.java diff --git a/test/micro/org/openjdk/bench/jdk/incubator/vector/ArrayMismatchBenchmark.java b/test/micro/org/openjdk/bench/jdk/incubator/vector/ArrayMismatchBenchmark.java new file mode 100644 index 00000000000..c6c34e890fa --- /dev/null +++ b/test/micro/org/openjdk/bench/jdk/incubator/vector/ArrayMismatchBenchmark.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.jdk.incubator.vector; + + +import jdk.incubator.vector.ByteVector; +import jdk.incubator.vector.DoubleVector; +import jdk.incubator.vector.IntVector; +import jdk.incubator.vector.LongVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorOperators; +import jdk.incubator.vector.VectorSpecies; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.infra.BenchmarkParams; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.random.RandomGenerator; + +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Thread) +@Fork(jvmArgsPrepend = {"--add-modules=jdk.incubator.vector"}) +public class ArrayMismatchBenchmark { + + @Param({"9", "257", "100000"}) + int size; + + @Param({"0.5", "1.0"}) + double prefix; + + byte[] byteData1; + byte[] byteData2; + + int[] intData1; + int[] intData2; + + long[] longData1; + long[] longData2; + + double[] doubleData1; + double[] doubleData2; + + static final VectorSpecies BYTE_SPECIES_PREFERRED = ByteVector.SPECIES_PREFERRED; + static final VectorSpecies INT_SPECIES_PREFERRED = IntVector.SPECIES_PREFERRED; + static final VectorSpecies FLOAT_SPECIES_PREFERRED = DoubleVector.SPECIES_PREFERRED; + static final VectorSpecies LONG_SPECIES_PREFERRED = LongVector.SPECIES_PREFERRED; + + @Setup + public void setup(BenchmarkParams params) { + RandomGenerator random = RandomGenerator.getDefault(); + int common = (int) (prefix * size); + + if (params.getBenchmark().endsWith("Byte")) { + byteData1 = new byte[size]; + byteData2 = new byte[size]; + random.nextBytes(byteData1); + random.nextBytes(byteData2); + + byte[] commonBytes = new byte[common]; + random.nextBytes(commonBytes); + + System.arraycopy(commonBytes, 0, byteData1, 0, common); + System.arraycopy(commonBytes, 0, byteData2, 0, common); + } else if (params.getBenchmark().endsWith("Int")) { + intData1 = random.ints(size).toArray(); + intData2 = random.ints(size).toArray(); + + int[] commonInts = random.ints(common).toArray(); + System.arraycopy(commonInts, 0, intData1, 0, common); + System.arraycopy(commonInts, 0, intData2, 0, common); + } else if (params.getBenchmark().endsWith("Double")) { + doubleData1 = random.doubles(size).toArray(); + doubleData2 = random.doubles(size).toArray(); + + double[] commonDoubles = random.doubles(common).toArray(); + System.arraycopy(commonDoubles, 0, doubleData1, 0, common); + System.arraycopy(commonDoubles, 0, doubleData2, 0, common); + } else if (params.getBenchmark().endsWith("Long")) { + longData1 = random.longs(size).toArray(); + longData2 = random.longs(size).toArray(); + + long[] commonLongs = random.longs(common).toArray(); + System.arraycopy(commonLongs, 0, longData1, 0, common); + System.arraycopy(commonLongs, 0, longData2, 0, common); + } + } + + @Benchmark + public int mismatchIntrinsicByte() { + return Arrays.mismatch(byteData1, byteData2); + } + + @Benchmark + public int mismatchVectorByte() { + int length = Math.min(byteData1.length, byteData2.length); + int index = 0; + for (; index < BYTE_SPECIES_PREFERRED.loopBound(length); index += BYTE_SPECIES_PREFERRED.length()) { + ByteVector vector1 = ByteVector.fromArray(BYTE_SPECIES_PREFERRED, byteData1, index); + ByteVector vector2 = ByteVector.fromArray(BYTE_SPECIES_PREFERRED, byteData2, index); + VectorMask mask = vector1.compare(VectorOperators.NE, vector2); + if (mask.anyTrue()) { + return index + mask.firstTrue(); + } + } + // process the tail + int mismatch = -1; + for (int i = index; i < length; ++i) { + if (byteData1[i] != byteData2[i]) { + mismatch = i; + break; + } + } + return mismatch; + } + + @Benchmark + public int mismatchIntrinsicInt() { + return Arrays.mismatch(intData1, intData2); + } + + @Benchmark + public int mismatchVectorInt() { + int length = Math.min(intData1.length, intData2.length); + int index = 0; + for (; index < INT_SPECIES_PREFERRED.loopBound(length); index += INT_SPECIES_PREFERRED.length()) { + IntVector vector1 = IntVector.fromArray(INT_SPECIES_PREFERRED, intData1, index); + IntVector vector2 = IntVector.fromArray(INT_SPECIES_PREFERRED, intData2, index); + VectorMask mask = vector1.compare(VectorOperators.NE, vector2); + if (mask.anyTrue()) { + return index + mask.firstTrue(); + } + } + // process the tail + int mismatch = -1; + for (int i = index; i < length; ++i) { + if (intData1[i] != intData2[i]) { + mismatch = i; + break; + } + } + return mismatch; + } + + @Benchmark + public int mismatchIntrinsicDouble() { + return Arrays.mismatch(doubleData1, doubleData2); + } + + @Benchmark + public int mismatchVectorDouble() { + int length = Math.min(doubleData1.length, doubleData2.length); + int index = 0; + for (; index < FLOAT_SPECIES_PREFERRED.loopBound(length); index += FLOAT_SPECIES_PREFERRED.length()) { + DoubleVector vector1 = DoubleVector.fromArray(FLOAT_SPECIES_PREFERRED, doubleData1, index); + DoubleVector vector2 = DoubleVector.fromArray(FLOAT_SPECIES_PREFERRED, doubleData2, index); + VectorMask mask = vector1.compare(VectorOperators.NE, vector2); + if (mask.anyTrue()) { + return index + mask.firstTrue(); + } + } + // process the tail + int mismatch = -1; + for (int i = index; i < length; ++i) { + if (doubleData1[i] != doubleData2[i]) { + mismatch = i; + break; + } + } + return mismatch; + } + + @Benchmark + public int mismatchIntrinsicLong() { + return Arrays.mismatch(longData1, longData2); + } + + @Benchmark + public int mismatchVectorLong() { + int length = Math.min(longData1.length, longData2.length); + int index = 0; + for (; index < LONG_SPECIES_PREFERRED.loopBound(length); index += LONG_SPECIES_PREFERRED.length()) { + LongVector vector1 = LongVector.fromArray(LONG_SPECIES_PREFERRED, longData1, index); + LongVector vector2 = LongVector.fromArray(LONG_SPECIES_PREFERRED, longData2, index); + VectorMask mask = vector1.compare(VectorOperators.NE, vector2); + if (mask.anyTrue()) { + return index + mask.firstTrue(); + } + } + // process the tail + int mismatch = -1; + for (int i = index; i < length; ++i) { + if (longData1[i] != longData2[i]) { + mismatch = i; + break; + } + } + return mismatch; + } + +} + -- GitLab From 83020617e70d40a42029720534af561f8af8bce2 Mon Sep 17 00:00:00 2001 From: sunxu Date: Fri, 17 Sep 2021 16:41:51 +0000 Subject: [PATCH 010/544] 8273774: CDSPluginTest should only expect classes_nocoops.jsa exists on supported 64-bit platforms Reviewed-by: ccheung, mchung --- test/jdk/tools/jlink/plugins/CDSPluginTest.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/test/jdk/tools/jlink/plugins/CDSPluginTest.java b/test/jdk/tools/jlink/plugins/CDSPluginTest.java index 5a973320951..f85769645ce 100644 --- a/test/jdk/tools/jlink/plugins/CDSPluginTest.java +++ b/test/jdk/tools/jlink/plugins/CDSPluginTest.java @@ -29,6 +29,8 @@ import jdk.test.lib.process.*; import tests.Helper; +import jtreg.SkippedException; + /* @test * @bug 8264322 * @summary Test the --generate-cds-archive plugin @@ -49,6 +51,9 @@ public class CDSPluginTest { public static void main(String[] args) throws Throwable { + if (!Platform.isDefaultCDSArchiveSupported()) + throw new SkippedException("not a supported platform"); + Helper helper = Helper.newHelper(); if (helper == null) { System.err.println("Test not run"); @@ -69,8 +74,14 @@ public class CDSPluginTest { subDir = "lib" + sep; } subDir += "server" + sep; - helper.checkImage(image, module, null, null, - new String[] { subDir + "classes.jsa", subDir + "classes_nocoops.jsa" }); + + if (Platform.isAArch64() || Platform.isX64()) { + helper.checkImage(image, module, null, null, + new String[] { subDir + "classes.jsa", subDir + "classes_nocoops.jsa" }); + } else { + helper.checkImage(image, module, null, null, + new String[] { subDir + "classes.jsa" }); + } // Simulate different platforms between current runtime and target image. if (Platform.isLinux()) { -- GitLab From 2a2e9190d4e866ac1b712feb0e4bb61d08e112c7 Mon Sep 17 00:00:00 2001 From: "lawrence.andrews" Date: Fri, 17 Sep 2021 18:11:23 +0000 Subject: [PATCH 011/544] 8273685: Remove jtreg tag manual=yesno for java/awt/Graphics/LCDTextAndGraphicsState.java & show test instruction Reviewed-by: aivanov, pbansal --- .../awt/Graphics/LCDTextAndGraphicsState.java | 110 ++++++++++++++---- 1 file changed, 86 insertions(+), 24 deletions(-) diff --git a/test/jdk/java/awt/Graphics/LCDTextAndGraphicsState.java b/test/jdk/java/awt/Graphics/LCDTextAndGraphicsState.java index a50c045865c..3ddae5c3761 100644 --- a/test/jdk/java/awt/Graphics/LCDTextAndGraphicsState.java +++ b/test/jdk/java/awt/Graphics/LCDTextAndGraphicsState.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,28 +21,47 @@ * questions. */ -/** +/* * @test * @bug 6576507 * @summary Both lines of text should be readable - * @run main/manual=yesno LCDTextAndGraphicsState + * @run main/manual LCDTextAndGraphicsState */ -import java.awt.*; -import java.awt.geom.*; + +import java.awt.AlphaComposite; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridLayout; +import java.awt.Panel; +import java.awt.RenderingHints; +import java.awt.Shape; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.geom.RoundRectangle2D; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; public class LCDTextAndGraphicsState extends Component { - String text = "This test passes only if this text appears SIX TIMES"; + private static final Frame testFrame = new Frame("Composite and Text Test"); + private static final String text = "This test passes only if this text appears SIX TIMES else fail"; + private static volatile boolean testResult; + private static volatile CountDownLatch countDownLatch; public void paint(Graphics g) { - Graphics2D g2d = (Graphics2D)g.create(); g2d.setColor(Color.white); g2d.fillRect(0,0,getSize().width, getSize().height); - - test1(g.create(0, 0, 500, 200)); - test2(g.create(0, 200, 500, 200)); - test3(g.create(0, 400, 500, 200)); + test1(g.create(0, 0, 500, 100)); + test2(g.create(0, 100, 500, 100)); + test3(g.create(0, 200, 500, 100)); } public void test1(Graphics g) { @@ -50,10 +69,10 @@ public class LCDTextAndGraphicsState extends Component { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2d.setColor(Color.black); - g2d.drawString(text, 10, 50); + g2d.drawString(text, 10, 20); g2d.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.9f)); - g2d.drawString(text, 10, 80); + g2d.drawString(text, 10, 50); } public void test2(Graphics g) { @@ -61,10 +80,10 @@ public class LCDTextAndGraphicsState extends Component { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2d.setColor(Color.black); - g2d.drawString(text, 10, 50); + g2d.drawString(text, 10, 20); g2d.setPaint(new GradientPaint( 0f, 0f, Color.BLACK, 100f, 100f, Color.GRAY)); - g2d.drawString(text, 10, 80); + g2d.drawString(text, 10, 50); } public void test3(Graphics g) { @@ -72,21 +91,64 @@ public class LCDTextAndGraphicsState extends Component { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2d.setColor(Color.black); - g2d.drawString(text, 10, 50); - Shape s = new RoundRectangle2D.Double(0, 60, 400, 50, 5, 5); + g2d.drawString(text, 10, 20); + Shape s = new RoundRectangle2D.Double(0, 30, 400, 50, 5, 5); g2d.clip(s); - g2d.drawString(text, 10, 80); + g2d.drawString(text, 10, 50); } public Dimension getPreferredSize() { - return new Dimension(500,600); + return new Dimension(500,300); + } + + public static void disposeUI() { + countDownLatch.countDown(); + testFrame.dispose(); } - public static void main(String[] args) throws Exception { + public static void createTestUI() { + testFrame.add(new LCDTextAndGraphicsState(), BorderLayout.NORTH); + Panel resultButtonPanel = new Panel(new GridLayout(1, 2)); + Button passButton = new Button("Pass"); + passButton.addActionListener((ActionEvent e) -> { + testResult = true; + disposeUI(); + }); + Button failButton = new Button("Fail"); + failButton.addActionListener(e -> { + testResult = false; + disposeUI(); + }); + resultButtonPanel.add(passButton); + resultButtonPanel.add(failButton); + + Panel controlUI = new Panel(new BorderLayout()); + TextArea instructions = new TextArea( + "Instructions:\n" + + "If you see the text six times above, press Pass.\n" + + "If not, press Fail.", + 3, + 50, + TextArea.SCROLLBARS_NONE + ); + instructions.setEditable(false); + controlUI.add(instructions, BorderLayout.CENTER); + controlUI.add(resultButtonPanel, BorderLayout.SOUTH); + + testFrame.add(controlUI, BorderLayout.SOUTH); + testFrame.pack(); + testFrame.setLocationRelativeTo(null); + testFrame.setVisible(true); + } - Frame f = new Frame("Composite and Text Test"); - f.add(new LCDTextAndGraphicsState(), BorderLayout.CENTER); - f.pack(); - f.setVisible(true); + public static void main(String[] args) throws InterruptedException { + countDownLatch = new CountDownLatch(1); + createTestUI(); + if (!countDownLatch.await(10, TimeUnit.MINUTES)) { + throw new RuntimeException("Timeout : No action was performed on the test UI."); + } + if (!testResult) { + throw new RuntimeException("Test failed!"); + } } } -- GitLab From bb9d142759ece7665329b124a8ea0b16049b024a Mon Sep 17 00:00:00 2001 From: Thomas Stuefe Date: Sat, 18 Sep 2021 08:29:48 +0000 Subject: [PATCH 012/544] 8273958: gtest/MetaspaceGtests executes unnecessary tests in debug builds Reviewed-by: jiefu --- test/hotspot/jtreg/gtest/MetaspaceGtests.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/hotspot/jtreg/gtest/MetaspaceGtests.java b/test/hotspot/jtreg/gtest/MetaspaceGtests.java index c4d0f9217dc..bf0b3746cc4 100644 --- a/test/hotspot/jtreg/gtest/MetaspaceGtests.java +++ b/test/hotspot/jtreg/gtest/MetaspaceGtests.java @@ -32,10 +32,10 @@ /* @test id=reclaim-none-debug * @bug 8251158 * @summary Run metaspace-related gtests for reclaim policy none (with verifications) - * @requires vm.debug * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.debug * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=none -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 */ @@ -46,6 +46,7 @@ * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.debug == false * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=none */ @@ -56,10 +57,10 @@ /* @test id=reclaim-aggressive-debug * @bug 8251158 * @summary Run metaspace-related gtests for reclaim policy aggressive (with verifications) - * @requires vm.debug * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.debug * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=aggressive -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 */ @@ -70,6 +71,7 @@ * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.debug == false * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=aggressive */ @@ -79,10 +81,10 @@ /* @test id=balanced-with-guards * @summary Run metaspace-related gtests with allocation guards enabled - * @requires vm.debug * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.debug * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 -XX:+MetaspaceGuardAllocations */ @@ -92,10 +94,10 @@ /* @test id=balanced-no-ccs * @summary Run metaspace-related gtests with compressed class pointers off - * @requires vm.bits == 64 * @library /test/lib * @modules java.base/jdk.internal.misc * java.xml + * @requires vm.bits == 64 * @requires vm.flagless * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=balanced -XX:-UseCompressedClassPointers */ -- GitLab From 7c9868c0b3c9bd3d305e71f91596190813cdccce Mon Sep 17 00:00:00 2001 From: Zhengyu Gu Date: Sat, 18 Sep 2021 23:11:06 +0000 Subject: [PATCH 013/544] 8273454: C2: Transform (-a)*(-b) into a*b Reviewed-by: thartmann, eliu, chagedorn --- src/hotspot/share/opto/mulnode.cpp | 17 ++- .../integerArithmetic/TestNegMultiply.java | 104 ++++++++++++++++++ 2 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 test/hotspot/jtreg/compiler/integerArithmetic/TestNegMultiply.java diff --git a/src/hotspot/share/opto/mulnode.cpp b/src/hotspot/share/opto/mulnode.cpp index 5d2b91a704a..be5039268b2 100644 --- a/src/hotspot/share/opto/mulnode.cpp +++ b/src/hotspot/share/opto/mulnode.cpp @@ -63,9 +63,24 @@ Node *MulNode::Ideal(PhaseGVN *phase, bool can_reshape) { const Type *t2 = phase->type( in(2) ); Node *progress = NULL; // Progress flag - // convert "max(a,b) * min(a,b)" into "a*b". + // convert "(-a)*(-b)" into "a*b" Node *in1 = in(1); Node *in2 = in(2); + if (in1->is_Sub() && in2->is_Sub()) { + if (phase->type(in1->in(1))->is_zero_type() && + phase->type(in2->in(1))->is_zero_type()) { + set_req(1, in1->in(2)); + set_req(2, in2->in(2)); + PhaseIterGVN* igvn = phase->is_IterGVN(); + if (igvn) { + igvn->_worklist.push(in1); + igvn->_worklist.push(in2); + } + progress = this; + } + } + + // convert "max(a,b) * min(a,b)" into "a*b". if ((in(1)->Opcode() == max_opcode() && in(2)->Opcode() == min_opcode()) || (in(1)->Opcode() == min_opcode() && in(2)->Opcode() == max_opcode())) { Node *in11 = in(1)->in(1); diff --git a/test/hotspot/jtreg/compiler/integerArithmetic/TestNegMultiply.java b/test/hotspot/jtreg/compiler/integerArithmetic/TestNegMultiply.java new file mode 100644 index 00000000000..a702dd7afa6 --- /dev/null +++ b/test/hotspot/jtreg/compiler/integerArithmetic/TestNegMultiply.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021, 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. + */ + +/** + * @test + * @key randomness + * @bug 8273454 + * @summary Test transformation (-a)*(-b) = a*b + * + * @library /test/lib + * + * @run main/othervm -XX:-TieredCompilation -XX:-BackgroundCompilation -XX:-UseOnStackReplacement -XX:CompileCommand="dontinline,TestNegMultiply::test*" TestNegMultiply + * + */ + +import java.util.Random; +import jdk.test.lib.Utils; +import jdk.test.lib.Asserts; + +public class TestNegMultiply { + private static final Random random = Utils.getRandomInstance(); + // Enough cycles to ensure test methods are JIT-ed + private static final int TEST_COUNT = 20_000; + + private static int testInt(int a, int b) { + return (-a) * (-b); + } + private static long testLong(long a, long b) { + return (-a) * (-b); + } + private static float testFloat(float a, float b) { + return (-a) * (-b); + } + private static double testDouble(double a, double b) { + return (-a) * (-b); + } + + private static void runIntTests() { + for (int index = 0; index < TEST_COUNT; index ++) { + int a = random.nextInt(); + int b = random.nextInt(); + int expected = (-a) * (-b); + int res = testInt(a, b); + Asserts.assertEQ(res, expected); + } + } + + private static void runLongTests() { + for (int index = 0; index < TEST_COUNT; index ++) { + long a = random.nextLong(); + long b = random.nextLong(); + long expected = (-a) * (-b); + long res = testLong(a, b); + Asserts.assertEQ(res, expected); + } + } + + private static void runFloatTests() { + for (int index = 0; index < TEST_COUNT; index ++) { + float a = random.nextFloat(); + float b = random.nextFloat(); + float expected = (-a) * (-b); + float res = testFloat(a, b); + Asserts.assertEQ(res, expected); + } + } + + private static void runDoubleTests() { + for (int index = 0; index < TEST_COUNT; index ++) { + double a = random.nextDouble(); + double b = random.nextDouble(); + double expected = (-a) * (-b); + double res = testDouble(a, b); + Asserts.assertEQ(res, expected); + } + } + + public static void main(String[] args) { + runIntTests(); + runLongTests(); + runFloatTests(); + runDoubleTests(); + } +} -- GitLab From dc7f452acbe3afa5aa6e31d316bd5e669c86d6f6 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Mon, 20 Sep 2021 08:29:12 +0000 Subject: [PATCH 014/544] 8273815: move have_special_privileges to os_posix for POSIX platforms Reviewed-by: mdoerr, stuefe, dholmes --- src/hotspot/os/aix/os_aix.cpp | 12 ------------ src/hotspot/os/bsd/os_bsd.cpp | 14 -------------- src/hotspot/os/linux/os_linux.cpp | 13 ------------- src/hotspot/os/posix/os_posix.cpp | 6 ++++++ 4 files changed, 6 insertions(+), 39 deletions(-) diff --git a/src/hotspot/os/aix/os_aix.cpp b/src/hotspot/os/aix/os_aix.cpp index 79fcdd886a2..6d52b285a42 100644 --- a/src/hotspot/os/aix/os_aix.cpp +++ b/src/hotspot/os/aix/os_aix.cpp @@ -267,18 +267,6 @@ julong os::physical_memory() { return Aix::physical_memory(); } -// Return true if user is running as root. - -bool os::have_special_privileges() { - static bool init = false; - static bool privileges = false; - if (!init) { - privileges = (getuid() != geteuid()) || (getgid() != getegid()); - init = true; - } - return privileges; -} - // Helper function, emulates disclaim64 using multiple 32bit disclaims // because we cannot use disclaim64() on AS/400 and old AIX releases. static bool my_disclaim64(char* addr, size_t size) { diff --git a/src/hotspot/os/bsd/os_bsd.cpp b/src/hotspot/os/bsd/os_bsd.cpp index 2c0ecd0fe6b..40bdd699791 100644 --- a/src/hotspot/os/bsd/os_bsd.cpp +++ b/src/hotspot/os/bsd/os_bsd.cpp @@ -179,20 +179,6 @@ julong os::physical_memory() { return Bsd::physical_memory(); } -// Return true if user is running as root. - -bool os::have_special_privileges() { - static bool init = false; - static bool privileges = false; - if (!init) { - privileges = (getuid() != geteuid()) || (getgid() != getegid()); - init = true; - } - return privileges; -} - - - // Cpu architecture string #if defined(ZERO) static char cpu_arch[] = ZERO_LIBARCH; diff --git a/src/hotspot/os/linux/os_linux.cpp b/src/hotspot/os/linux/os_linux.cpp index cb4ba76a6d4..72abf03ddc6 100644 --- a/src/hotspot/os/linux/os_linux.cpp +++ b/src/hotspot/os/linux/os_linux.cpp @@ -308,19 +308,6 @@ bool os::Linux::get_tick_information(CPUPerfTicks* pticks, int which_logical_cpu return true; } -// Return true if user is running as root. - -bool os::have_special_privileges() { - static bool init = false; - static bool privileges = false; - if (!init) { - privileges = (getuid() != geteuid()) || (getgid() != getegid()); - init = true; - } - return privileges; -} - - #ifndef SYS_gettid // i386: 224, ia64: 1105, amd64: 186, sparc: 143 #ifdef __ia64__ diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp index 4b0c98bc1de..8a361bac12b 100644 --- a/src/hotspot/os/posix/os_posix.cpp +++ b/src/hotspot/os/posix/os_posix.cpp @@ -177,6 +177,12 @@ size_t os::lasterror(char *buf, size_t len) { return n; } +// Return true if user is running as root. +bool os::have_special_privileges() { + static bool privileges = (getuid() != geteuid()) || (getgid() != getegid()); + return privileges; +} + void os::wait_for_keypress_at_exit(void) { // don't do anything on posix platforms return; -- GitLab From d2388b7a0f4bfb55ea0d5648175e3253f30a4302 Mon Sep 17 00:00:00 2001 From: Thomas Stuefe Date: Mon, 20 Sep 2021 08:46:44 +0000 Subject: [PATCH 015/544] 8273959: Some metaspace diagnostic switches should be develop Reviewed-by: dholmes, jiefu --- src/hotspot/share/runtime/globals.hpp | 4 ++-- test/hotspot/jtreg/gtest/MetaspaceGtests.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/hotspot/share/runtime/globals.hpp b/src/hotspot/share/runtime/globals.hpp index a1d30d694d1..d98d0ad5226 100644 --- a/src/hotspot/share/runtime/globals.hpp +++ b/src/hotspot/share/runtime/globals.hpp @@ -1435,10 +1435,10 @@ const intx ObjectAlignmentInBytes = 8; product(bool, PrintMetaspaceStatisticsAtExit, false, DIAGNOSTIC, \ "Print metaspace statistics upon VM exit.") \ \ - product(bool, MetaspaceGuardAllocations, false, DIAGNOSTIC, \ + develop(bool, MetaspaceGuardAllocations, false, \ "Metapace allocations are guarded.") \ \ - product(bool, MetaspaceHandleDeallocations, true, DIAGNOSTIC, \ + develop(bool, MetaspaceHandleDeallocations, true, \ "Switch off Metapace deallocation handling.") \ \ product(uintx, MinHeapFreeRatio, 40, MANAGEABLE, \ diff --git a/test/hotspot/jtreg/gtest/MetaspaceGtests.java b/test/hotspot/jtreg/gtest/MetaspaceGtests.java index bf0b3746cc4..75cb7fe52fc 100644 --- a/test/hotspot/jtreg/gtest/MetaspaceGtests.java +++ b/test/hotspot/jtreg/gtest/MetaspaceGtests.java @@ -37,7 +37,7 @@ * java.xml * @requires vm.debug * @requires vm.flagless - * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=none -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 + * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=none -XX:VerifyMetaspaceInterval=3 */ /* @test id=reclaim-none-ndebug @@ -62,7 +62,7 @@ * java.xml * @requires vm.debug * @requires vm.flagless - * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=aggressive -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 + * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:MetaspaceReclaimPolicy=aggressive -XX:VerifyMetaspaceInterval=3 */ /* @test id=reclaim-aggressive-ndebug @@ -86,7 +86,7 @@ * java.xml * @requires vm.debug * @requires vm.flagless - * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:+UnlockDiagnosticVMOptions -XX:VerifyMetaspaceInterval=3 -XX:+MetaspaceGuardAllocations + * @run main/native GTestWrapper --gtest_filter=metaspace* -XX:VerifyMetaspaceInterval=3 -XX:+MetaspaceGuardAllocations */ -- GitLab From a561eac912740da6a5982c47558e13f34481219f Mon Sep 17 00:00:00 2001 From: Christian Hagedorn Date: Mon, 20 Sep 2021 12:53:56 +0000 Subject: [PATCH 016/544] 8273895: compiler/ciReplay/TestVMNoCompLevel.java fails due to wrong data size with TieredStopAtLevel=2,3 Reviewed-by: kvn, dlong --- test/hotspot/jtreg/compiler/ciReplay/TestVMNoCompLevel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/compiler/ciReplay/TestVMNoCompLevel.java b/test/hotspot/jtreg/compiler/ciReplay/TestVMNoCompLevel.java index 0418ba5ad36..a0c3fc69f8d 100644 --- a/test/hotspot/jtreg/compiler/ciReplay/TestVMNoCompLevel.java +++ b/test/hotspot/jtreg/compiler/ciReplay/TestVMNoCompLevel.java @@ -26,7 +26,8 @@ * @bug 8011675 * @library / /test/lib * @summary testing of ciReplay with using generated by VM replay.txt w/o comp_level - * @requires vm.flightRecorder != true & vm.compMode != "Xint" & vm.debug == true + * @requires vm.flightRecorder != true & vm.compMode != "Xint" & vm.debug == true & + * (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 1 | vm.opt.TieredStopAtLevel == 4) * @modules java.base/jdk.internal.misc * @build sun.hotspot.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox -- GitLab From 6f3e40c16db899f1add67b997dede17eeb83418f Mon Sep 17 00:00:00 2001 From: Christian Hagedorn Date: Mon, 20 Sep 2021 12:56:08 +0000 Subject: [PATCH 017/544] 8273825: TestIRMatching.java fails after JDK-8266550 Reviewed-by: thartmann, roland --- test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java index d99e51462ba..92a6fc10d5e 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java @@ -59,7 +59,7 @@ public class IRNode { public static final String ALLOC_ARRAY_OF = COMPOSITE_PREFIX + "(.*precise \\[.*" + IS_REPLACED + ":.*\\R((.*(?i:mov|xorl|nop|spill).*|\\s*|.*LGHI.*)\\R)*.*(?i:call,static).*wrapper for: _new_array_Java" + END; public static final String CHECKCAST_ARRAY = "(((?i:cmp|CLFI|CLR).*precise \\[.*:|.*(?i:mov|or).*precise \\[.*:.*\\R.*(cmp|CMP|CLR))" + END; - public static final String CHECKCAST_ARRAY_OF = COMPOSITE_PREFIX + "(((?i:cmp|CLFI|CLR).*precise \\[.*" + IS_REPLACED + ":|.*(?i:mov|or).*precise klass \\[.*" + IS_REPLACED + ";:.*\\R.*(cmp|CMP|CLR))" + END; + public static final String CHECKCAST_ARRAY_OF = COMPOSITE_PREFIX + "(((?i:cmp|CLFI|CLR).*precise \\[.*" + IS_REPLACED + ":|.*(?i:mov|or).*precise \\[.*" + IS_REPLACED + ":.*\\R.*(cmp|CMP|CLR))" + END; // Does not work on s390 (a rule containing this regex will be skipped on s390). public static final String CHECKCAST_ARRAYCOPY = "(.*((?i:call_leaf_nofp,runtime)|CALL,\\s?runtime leaf nofp|BCTRL.*.leaf call).*checkcast_arraycopy.*" + END; -- GitLab From f71df142a97f522b40e90c3105e0e5bd8d5af9a2 Mon Sep 17 00:00:00 2001 From: Naoto Sato Date: Mon, 20 Sep 2021 13:38:38 +0000 Subject: [PATCH 018/544] 8273187: jtools tests fail with missing markerName check Reviewed-by: iris, sspitsyn, joehw --- test/jdk/ProblemList.txt | 3 --- test/jdk/sun/tools/jcmd/JcmdOutputEncodingTest.java | 6 +++--- test/jdk/sun/tools/jstack/BasicJStackTest.java | 4 +++- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index 82a412c802f..31782a285e1 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -813,9 +813,6 @@ sun/tools/jstat/jstatLineCounts2.sh 8268211 linux-aa sun/tools/jstat/jstatLineCounts3.sh 8268211 linux-aarch64 sun/tools/jstat/jstatLineCounts4.sh 8268211 linux-aarch64 -sun/tools/jcmd/JcmdOutputEncodingTest.java 8273187 generic-all -sun/tools/jstack/BasicJStackTest.java 8273187 generic-all - ############################################################################ # jdk_other diff --git a/test/jdk/sun/tools/jcmd/JcmdOutputEncodingTest.java b/test/jdk/sun/tools/jcmd/JcmdOutputEncodingTest.java index 45ba91f2f7e..14f5a2be167 100644 --- a/test/jdk/sun/tools/jcmd/JcmdOutputEncodingTest.java +++ b/test/jdk/sun/tools/jcmd/JcmdOutputEncodingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,7 +21,6 @@ * questions. */ -import java.util.Arrays; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -32,7 +31,7 @@ import jdk.test.lib.JDKToolLauncher; /* * @test - * @bug 8222491 + * @bug 8222491 8273187 * @summary Tests if we handle the encoding of jcmd output correctly. * @library /test/lib * @run main JcmdOutputEncodingTest @@ -51,6 +50,7 @@ public class JcmdOutputEncodingTest { JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jcmd"); launcher.addVMArgs(Utils.getTestJavaOpts()); launcher.addVMArg("-Dfile.encoding=" + cs); + launcher.addVMArg("-Dsun.stdout.encoding=" + cs); launcher.addToolArg(Long.toString(ProcessTools.getProcessId())); launcher.addToolArg("Thread.print"); diff --git a/test/jdk/sun/tools/jstack/BasicJStackTest.java b/test/jdk/sun/tools/jstack/BasicJStackTest.java index 23559f85700..e0a9c96d6ad 100644 --- a/test/jdk/sun/tools/jstack/BasicJStackTest.java +++ b/test/jdk/sun/tools/jstack/BasicJStackTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * 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 jdk.test.lib.JDKToolLauncher; /* * @test + * @bug 8273187 * @summary Unit test for jstack utility * @library /test/lib * @run main BasicJStackTest @@ -74,6 +75,7 @@ public class BasicJStackTest { launcher.addVMArgs(Utils.getFilteredTestJavaOpts("-XX:+UsePerfData")); launcher.addVMArg("-XX:+UsePerfData"); launcher.addVMArg("-Dfile.encoding=" + cs); + launcher.addVMArg("-Dsun.stdout.encoding=" + cs); if (toolArgs != null) { for (String toolArg : toolArgs) { launcher.addToolArg(toolArg); -- GitLab From 699865f76cdf76fbd8042c1b5677b71e29faa4bc Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Mon, 20 Sep 2021 13:43:14 +0000 Subject: [PATCH 019/544] 8259039: Passing different version to --release flag than javac version output warning Reviewed-by: jjg --- .../com/sun/tools/javac/code/ClassFinder.java | 25 ++-- .../sun/tools/javac/resources/ct.properties | 2 +- .../com/sun/tools/javac/util/Names.java | 2 + .../javac/platform/CtPropertiesTest.java | 139 ++++++++++++++++++ 4 files changed, 158 insertions(+), 10 deletions(-) create mode 100644 test/langtools/tools/javac/platform/CtPropertiesTest.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java index beef242a534..fa67ff3a7ca 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java @@ -250,22 +250,29 @@ public class ClassFinder { supplementaryFlags = new HashMap<>(); } - Long flags = supplementaryFlags.get(c.packge()); + PackageSymbol packge = c.packge(); + + Long flags = supplementaryFlags.get(packge); if (flags == null) { long newFlags = 0; try { - JRTIndex.CtSym ctSym = jrtIndex.getCtSym(c.packge().flatName()); - Profile minProfile = Profile.DEFAULT; - if (ctSym.proprietary) + ModuleSymbol owningModule = packge.modle; + if (owningModule == syms.noModule) { + JRTIndex.CtSym ctSym = jrtIndex.getCtSym(packge.flatName()); + Profile minProfile = Profile.DEFAULT; + if (ctSym.proprietary) + newFlags |= PROPRIETARY; + if (ctSym.minProfile != null) + minProfile = Profile.lookup(ctSym.minProfile); + if (profile != Profile.DEFAULT && minProfile.value > profile.value) { + newFlags |= NOT_IN_PROFILE; + } + } else if (owningModule.name == names.jdk_unsupported) { newFlags |= PROPRIETARY; - if (ctSym.minProfile != null) - minProfile = Profile.lookup(ctSym.minProfile); - if (profile != Profile.DEFAULT && minProfile.value > profile.value) { - newFlags |= NOT_IN_PROFILE; } } catch (IOException ignore) { } - supplementaryFlags.put(c.packge(), flags = newFlags); + supplementaryFlags.put(packge, flags = newFlags); } return flags; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/ct.properties b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/ct.properties index c5d87e170dd..ba42e8e067c 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/ct.properties +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/ct.properties @@ -163,7 +163,7 @@ com.sun.net.httpserver.*: compact2 com.sun.net.httpserver.spi.*: compact2 com.sun.net.ssl.*: compact1 com.sun.net.ssl.internal.www.protocol.https.*: proprietary compact1 -com.sun.nio.file.*: compact1 +com.sun.nio.file.*: proprietary compact1 com.sun.nio.sctp.*: compact3 com.sun.org.apache.bcel.internal.*: proprietary compact2 com.sun.org.apache.bcel.internal.classfile.*: proprietary compact2 diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java index c6be1ad8e22..90f0dac72e7 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Names.java @@ -122,6 +122,7 @@ public class Names { // module names public final Name java_base; + public final Name jdk_unsupported; // attribute names public final Name Annotation; @@ -301,6 +302,7 @@ public class Names { // module names java_base = fromString("java.base"); + jdk_unsupported = fromString("jdk.unsupported"); // attribute names Annotation = fromString("Annotation"); diff --git a/test/langtools/tools/javac/platform/CtPropertiesTest.java b/test/langtools/tools/javac/platform/CtPropertiesTest.java new file mode 100644 index 00000000000..6ff09ada157 --- /dev/null +++ b/test/langtools/tools/javac/platform/CtPropertiesTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8259039 + * @summary Verify behavior of --release and -source related to com.sun.nio.file + * @library /tools/lib + * @modules jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.compiler/com.sun.tools.javac.platform + * jdk.compiler/com.sun.tools.javac.util:+open + * @build toolbox.ToolBox CtPropertiesTest + * @run main CtPropertiesTest + */ + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import toolbox.JavacTask; +import toolbox.Task; +import toolbox.ToolBox; + +public class CtPropertiesTest { + + public static void main(String... args) throws IOException, URISyntaxException { + CtPropertiesTest t = new CtPropertiesTest(); + + t.runSource(); + t.runRelease(); + } + + void runSource() throws IOException { + Path root = Paths.get("."); + Path classes = root.resolve("classes"); + Files.createDirectories(classes); + ToolBox tb = new ToolBox(); + List log; + List expected; + + expected = List.of( + "Test.java:2:21: compiler.warn.sun.proprietary: com.sun.nio.file.ExtendedOpenOption", + "1 warning" + ); + + List versions = new ArrayList<>(); + + Path javaHome = FileSystems.getDefault().getPath(System.getProperty("java.home")); + Path thisSystemModules = javaHome.resolve("lib").resolve("modules"); + + if (Files.isRegularFile(thisSystemModules)) { + //only use -source 8 when running on full JDK images (not on the exploded JDK), as the + //classfiles are not considered to be part of JRT image when running with -source 8: + versions.add("8"); + } + + versions.addAll(List.of("11", "17", System.getProperty("java.specification.version"))); + + for (String version : versions) { + log = new JavacTask(tb) + .outdir(classes) + .options("-source", version, + "-XDrawDiagnostics", + "-Xlint:-options") + .sources(""" + public class Test { + com.sun.nio.file.ExtendedOpenOption o; + } + """) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + if (!expected.equals(log)) { + throw new AssertionError("Unexpected output: " + log + ", version: " + version); + } + } + } + + void runRelease() throws IOException { + Path root = Paths.get("."); + Path classes = root.resolve("classes"); + Files.createDirectories(classes); + ToolBox tb = new ToolBox(); + List log; + List expected; + + expected = List.of( + "Test.java:2:21: compiler.warn.sun.proprietary: com.sun.nio.file.ExtendedOpenOption", + "1 warning" + ); + + for (String version : new String[] {"11", "17", System.getProperty("java.specification.version")}) { + log = new JavacTask(tb) + .outdir(classes) + .options("--release", version, + "-XDrawDiagnostics") + .sources(""" + public class Test { + com.sun.nio.file.ExtendedOpenOption o; + } + """) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + if (!expected.equals(log)) { + throw new AssertionError("Unexpected output: " + log + ", version: " + version); + } + } + } + +} -- GitLab From 1f8af524ffe2d2d1469d8f07887b1f61c6e4d7b8 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Mon, 20 Sep 2021 14:02:07 +0000 Subject: [PATCH 020/544] 8273314: Add tier4 test groups Reviewed-by: serb, iignatyev --- test/hotspot/jtreg/TEST.groups | 7 +++++++ test/jaxp/TEST.groups | 3 +++ test/jdk/TEST.groups | 7 +++++++ test/langtools/TEST.groups | 3 +++ 4 files changed, 20 insertions(+) diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups index 9e948283c8d..d1e3107adc6 100644 --- a/test/hotspot/jtreg/TEST.groups +++ b/test/hotspot/jtreg/TEST.groups @@ -464,6 +464,13 @@ tier3 = \ :hotspot_tier3_runtime \ :tier3_gc_shenandoah +# Everything that is not in other tiers, but not apps +tier4 = \ + :hotspot_all_no_apps \ + -:tier1 \ + -:tier2 \ + -:tier3 + hotspot_tier2_runtime = \ runtime/ \ -runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java \ diff --git a/test/jaxp/TEST.groups b/test/jaxp/TEST.groups index 91d4e999021..0b67ed428b9 100644 --- a/test/jaxp/TEST.groups +++ b/test/jaxp/TEST.groups @@ -32,5 +32,8 @@ tier2 = \ # No tier 3 tests. tier3 = +# No tier 4 tests. +tier4 = + jaxp_all = \ javax/xml/jaxp diff --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups index dd5b089e9b0..58e7ac3f836 100644 --- a/test/jdk/TEST.groups +++ b/test/jdk/TEST.groups @@ -76,6 +76,13 @@ tier3 = \ :jdk_rmi \ :jdk_jfr_tier3 +# Everything not in other tiers +tier4 = \ + / \ + -:tier1 \ + -:tier2 \ + -:tier3 + ############################################################################### # # Other test definitions; generally smaller granularity than tiers diff --git a/test/langtools/TEST.groups b/test/langtools/TEST.groups index d97a6859535..8df9dcaadf5 100644 --- a/test/langtools/TEST.groups +++ b/test/langtools/TEST.groups @@ -87,3 +87,6 @@ tier2 = \ # No langtools tests are tier 3 either. tier3 = + +# No langtools tests are tier 4 either. +tier4 = -- GitLab From 544193a3bb6431ee4bb0bd43cb29cc60c7709b25 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Mon, 20 Sep 2021 14:05:03 +0000 Subject: [PATCH 021/544] 8247980: Exclusive execution of java/util/stream tests slows down tier1 Reviewed-by: iignatyev --- test/jdk/TEST.ROOT | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jdk/TEST.ROOT b/test/jdk/TEST.ROOT index 6b78ca255f5..9f8bcca9b91 100644 --- a/test/jdk/TEST.ROOT +++ b/test/jdk/TEST.ROOT @@ -27,7 +27,7 @@ exclusiveAccess.dirs=java/math/BigInteger/largeMemory \ java/rmi/Naming java/util/prefs sun/management/jmxremote \ sun/tools/jstatd sun/tools/jcmd \ sun/tools/jinfo sun/tools/jmap sun/tools/jps sun/tools/jstack sun/tools/jstat \ -com/sun/tools/attach sun/security/mscapi java/util/stream java/util/Arrays/largeMemory \ +com/sun/tools/attach sun/security/mscapi java/util/Arrays/largeMemory \ java/util/BitSet/stream javax/rmi java/net/httpclient/websocket # Group definitions -- GitLab From 4da45c430139fe66fab020c2f96686dc9cf26a97 Mon Sep 17 00:00:00 2001 From: "lawrence.andrews" Date: Mon, 20 Sep 2021 14:07:50 +0000 Subject: [PATCH 022/544] 8270609: [TESTBUG] java/awt/print/Dialog/DialogCopies.java does not show instruction Reviewed-by: aivanov --- .../java/awt/print/Dialog/DialogCopies.java | 79 +++++++++++++------ 1 file changed, 56 insertions(+), 23 deletions(-) diff --git a/test/jdk/java/awt/print/Dialog/DialogCopies.java b/test/jdk/java/awt/print/Dialog/DialogCopies.java index 5086f95660f..39d15461de8 100644 --- a/test/jdk/java/awt/print/Dialog/DialogCopies.java +++ b/test/jdk/java/awt/print/Dialog/DialogCopies.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,40 +21,73 @@ * questions. */ -/** +/* * @test * @bug 6357858 * @summary Job must reports the number of copies set in the dialog. * @run main/manual DialogCopies */ -import java.awt.print.*; +import java.awt.Frame; +import java.awt.TextArea; +import java.awt.BorderLayout; +import java.awt.print.PrinterJob; public class DialogCopies { - static String[] instructions = { - "This test assumes and requires that you have a printer installed", - "When the dialog appears, increment the number of copies then press OK.", - "The test will throw an exception if you fail to do this, since", - "it cannot distinguish that from a failure", - "" - }; + private static Frame createInstructionUI() { + final String instruction = """ + This test requires that you have a printer. + + Press Cancel if your system has only virtual printers such as + Microsoft Print to PDF or Microsoft XPS Document Writer since + they don't allow setting copies to anything but 1. + + If a real printer is installed, select it from the drop-down + list in the Print dialog and increase the number of copies, + then press OK button."""; - public static void main(String[] args) { + TextArea instructionTextArea = new TextArea(instruction); + instructionTextArea.setEditable(false); - for (int i=0;i Date: Mon, 20 Sep 2021 14:11:16 +0000 Subject: [PATCH 023/544] 8273934: Remove unused perfcounters Reviewed-by: chagedorn --- src/hotspot/share/compiler/compileBroker.hpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/hotspot/share/compiler/compileBroker.hpp b/src/hotspot/share/compiler/compileBroker.hpp index 2159c3b7662..a33b7ea0a78 100644 --- a/src/hotspot/share/compiler/compileBroker.hpp +++ b/src/hotspot/share/compiler/compileBroker.hpp @@ -181,14 +181,12 @@ class CompileBroker: AllStatic { // performance counters static PerfCounter* _perf_total_compilation; - static PerfCounter* _perf_native_compilation; static PerfCounter* _perf_osr_compilation; static PerfCounter* _perf_standard_compilation; static PerfCounter* _perf_total_bailout_count; static PerfCounter* _perf_total_invalidated_count; static PerfCounter* _perf_total_compile_count; - static PerfCounter* _perf_total_native_compile_count; static PerfCounter* _perf_total_osr_compile_count; static PerfCounter* _perf_total_standard_compile_count; -- GitLab From 4d95a5d6dc7cc3d2b239c554a1302ac647807bd6 Mon Sep 17 00:00:00 2001 From: Nils Eliasson Date: Mon, 20 Sep 2021 14:59:44 +0000 Subject: [PATCH 024/544] 8273933: [TESTBUG] Test must run without preallocated exceptions Reviewed-by: chagedorn, thartmann --- test/hotspot/jtreg/vmTestbase/jit/t/t105/t105.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/hotspot/jtreg/vmTestbase/jit/t/t105/t105.java b/test/hotspot/jtreg/vmTestbase/jit/t/t105/t105.java index d6c1ac7185e..6cdb615852f 100644 --- a/test/hotspot/jtreg/vmTestbase/jit/t/t105/t105.java +++ b/test/hotspot/jtreg/vmTestbase/jit/t/t105/t105.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * 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,10 @@ * * @library /vmTestbase * /test/lib - * @run main/othervm jit.t.t105.t105 + * @run main/othervm -XX:-OmitStackTraceInFastThrow jit.t.t105.t105 + * + * This test must be run with ProfileTraps disabled to avoid preallocated + * exceptions. They don't have the detailed message that this test relies on. */ package jit.t.t105; -- GitLab From 48aff23165db668eb9c06477d16a8e72b6dc6b56 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 15:44:46 +0000 Subject: [PATCH 025/544] 8272515: JFR: Names should only be valid Java identifiers Reviewed-by: mgronlun --- .../classes/jdk/internal/module/Checks.java | 4 +- .../share/classes/jdk/jfr/EventFactory.java | 3 +- src/jdk.jfr/share/classes/jdk/jfr/Name.java | 12 +- .../classes/jdk/jfr/ValueDescriptor.java | 15 +- .../jdk/jfr/internal/EventControl.java | 4 +- .../jfr/internal/EventInstrumentation.java | 12 +- .../jdk/jfr/internal/MetadataLoader.java | 5 +- .../share/classes/jdk/jfr/internal/Type.java | 29 +-- .../classes/jdk/jfr/internal/TypeLibrary.java | 10 +- .../share/classes/jdk/jfr/internal/Utils.java | 25 ++ .../api/metadata/annotations/TestName.java | 215 +++++++++++++++++- 11 files changed, 285 insertions(+), 49 deletions(-) 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 3b7dd137225..7965391f049 100644 --- a/src/java.base/share/classes/jdk/internal/module/Checks.java +++ b/src/java.base/share/classes/jdk/internal/module/Checks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -168,7 +168,7 @@ public final class Checks { * Returns true if the given string is a legal Java identifier, * otherwise false. */ - private static boolean isJavaIdentifier(String str) { + public static boolean isJavaIdentifier(String str) { if (str.isEmpty() || RESERVED.contains(str)) return false; diff --git a/src/jdk.jfr/share/classes/jdk/jfr/EventFactory.java b/src/jdk.jfr/share/classes/jdk/jfr/EventFactory.java index bbda1be7490..71b08e74baa 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/EventFactory.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/EventFactory.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import jdk.internal.module.Checks; import jdk.jfr.internal.EventClassBuilder; import jdk.jfr.internal.JVMSupport; import jdk.jfr.internal.MetadataRepository; @@ -135,7 +136,7 @@ public final class EventFactory { if (!Type.isValidJavaFieldType(v.getTypeName())) { throw new IllegalArgumentException(v.getTypeName() + " is not a valid type for an event field"); } - if (!Type.isValidJavaIdentifier(v.getName())) { + if (!Checks.isJavaIdentifier(v.getName())) { throw new IllegalArgumentException(name + " is not a valid name for an event field"); } if (nameSet.contains(name)) { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/Name.java b/src/jdk.jfr/share/classes/jdk/jfr/Name.java index 7c43911f01c..26d1b84c436 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/Name.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/Name.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * 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,9 +33,13 @@ import java.lang.annotation.Target; /** * Annotation that sets the default name for an element. *

- * The name must be a valid identifier as specified in the Java language (for - * example, {@code "com.example.Transaction"} for an event class or - * {@code "message"} for an event field). + * For event classes, the name must be a legal class name as specified in the Java + * language, (for example, {@code "com.example.Transaction"}. For event fields + * or event settings, the name must be a valid identifier (for example, + * {@code "message"}). See section 3.8 and 3.9 of the Java Language + * Specification for more information. + *

+ * If the specified name is invalid, the annotation is ignored. *

* A stable and easy-to-use event name is of the form: *

diff --git a/src/jdk.jfr/share/classes/jdk/jfr/ValueDescriptor.java b/src/jdk.jfr/share/classes/jdk/jfr/ValueDescriptor.java index 3132d2b050e..26e523ed40c 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/ValueDescriptor.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/ValueDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,12 +83,14 @@ public final class ValueDescriptor { * * *

- * The name must be a valid Java identifier (for example, {@code "maxThroughput"}). See 3.8 - * Java Language Specification for more information. + * The name must be a valid Java identifier (for example, {@code "maxThroughput"}). See + * section 3.8 and 3.9 of the Java Language Specification for more information. * * @param type the type, not {@code null} * @param name the name, not {@code null} * + * @throws IllegalArgumentException if the name is not a valid Java identifier + * * @throws SecurityException if a security manager is present and the caller * doesn't have {@code FlightRecorderPermission("registerEvent")} * @@ -118,14 +120,16 @@ public final class ValueDescriptor { * * *

- * The name must be a valid Java identifier (for example, {@code "maxThroughput"}). See 3.8 - * Java Language Specification for more information. + * The name must be a valid Java identifier (for example, {@code "maxThroughput"}). See + * section 3.8 and 3.9 of the Java Language Specification for more information. * * @param type the type, not {@code null} * @param name the name, not {@code null} * @param annotations the annotations on the value descriptors, not * {@code null} * + * @throws IllegalArgumentException if the name is not a valid Java identifier + * * @throws SecurityException if a security manager is present and the caller * doesn't have {@code FlightRecorderPermission("registerEvent")} */ @@ -143,6 +147,7 @@ public final class ValueDescriptor { } } this.name = Objects.requireNonNull(name, "Name of value descriptor can't be null"); + Utils.ensureJavaIdentifier(name); this.type = Objects.requireNonNull(Utils.getValidType(Objects.requireNonNull(type), Objects.requireNonNull(name))); this.annotationConstruct = new AnnotationConstruct(annotations); this.javaFieldName = name; // Needed for dynamic events diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventControl.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventControl.java index 3ef0948a8b3..6a89ce02d1e 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventControl.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -150,7 +150,7 @@ public final class EventControl { String name = m.getName(); Name n = m.getAnnotation(Name.class); if (n != null) { - name = n.value(); + name = Utils.validJavaIdentifier(n.value(), name); } if (!hasControl(name)) { diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java index e59458a9cc0..9320bb83229 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * 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,6 +213,7 @@ public final class EventInstrumentation { Set methodSet = new HashSet<>(); List settingInfos = new ArrayList<>(); String settingDescriptor = Type.getType(SettingDefinition.class).getDescriptor(); + String nameDescriptor = Type.getType(Name.class).getDescriptor(); for (MethodNode m : classNode.methods) { if (m.visibleAnnotations != null) { for (AnnotationNode an : m.visibleAnnotations) { @@ -220,6 +221,15 @@ public final class EventInstrumentation { // stage. We would need to check that the parameter // is an instance of SettingControl. if (settingDescriptor.equals(an.desc)) { + String name = m.name; + for (AnnotationNode nameCandidate : m.visibleAnnotations) { + if (nameDescriptor.equals(nameCandidate.desc)) { + List values = nameCandidate.values; + if (values.size() == 1 && values.get(0) instanceof String s) { + name = Utils.validJavaIdentifier(s, name); + } + } + } Type returnType = Type.getReturnType(m.desc); if (returnType.equals(Type.getType(Boolean.TYPE))) { Type[] args = Type.getArgumentTypes(m.desc); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataLoader.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataLoader.java index 1c5e5ab7af4..ef9c22556f2 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataLoader.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/MetadataLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -255,6 +255,9 @@ public final class MetadataLoader { if ("to".equals(f.transition)) { aes.add(TRANSITION_TO); } + if (!"package".equals(f.name) && !"java.lang.Class".equals(te.name)) { + Utils.ensureJavaIdentifier(f.name); + } type.add(PrivateAccess.getInstance().newValueDescriptor(f.name, fieldType, aes, f.array ? 1 : 0, f.constantPool, null)); } } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/Type.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/Type.java index ecdb6fa0157..9b6891bcdec 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/Type.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/Type.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import jdk.internal.module.Checks; import jdk.jfr.AnnotationElement; import jdk.jfr.Event; import jdk.jfr.SettingControl; @@ -76,7 +77,7 @@ public class Type implements Comparable { private static Type createKnownType(String name, Class clazz) { long id = JVM.getJVM().getTypeId(name); - Type t = new Type(name, null, id); + Type t = new Type(name, null, id, null); knownTypes.put(t, clazz); return t; } @@ -99,14 +100,14 @@ public class Type implements Comparable { */ public Type(String javaTypeName, String superType, long typeId) { this(javaTypeName, superType, typeId, null); + if (!Checks.isClassName(javaTypeName)) { + // Should not be able to come here with an invalid type name + throw new InternalError(javaTypeName + " is not a valid Java type"); + } } Type(String javaTypeName, String superType, long typeId, Boolean simpleType) { Objects.requireNonNull(javaTypeName); - - if (!isValidJavaIdentifier(javaTypeName)) { - throw new IllegalArgumentException(javaTypeName + " is not a valid Java identifier"); - } this.superType = superType; this.name = javaTypeName; this.id = typeId; @@ -126,24 +127,6 @@ public class Type implements Comparable { return knownTypes.keySet(); } - public static boolean isValidJavaIdentifier(String identifier) { - if (identifier.isEmpty()) { - return false; - } - if (!Character.isJavaIdentifierStart(identifier.charAt(0))) { - return false; - } - for (int i = 1; i < identifier.length(); i++) { - char c = identifier.charAt(i); - if (c != '.') { - if (!Character.isJavaIdentifierPart(c)) { - return false; - } - } - } - return true; - } - public static boolean isValidJavaFieldType(String name) { for (Map.Entry> entry : knownTypes.entrySet()) { Class clazz = entry.getValue(); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/TypeLibrary.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/TypeLibrary.java index b7fd93fcf07..fb16c92f171 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/TypeLibrary.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/TypeLibrary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -191,7 +191,10 @@ public final class TypeLibrary { private static Type defineType(Class clazz, String superType, boolean eventType) { if (!isDefined(clazz)) { Name name = clazz.getAnnotation(Name.class); - String typeName = name != null ? name.value() : clazz.getName(); + String typeName = clazz.getName(); + if (name != null) { + typeName = Utils.validTypeName(name.value(), typeName); + } long id = Type.getTypeId(clazz); Type t; if (eventType) { @@ -317,7 +320,6 @@ public final class TypeLibrary { createAnnotationType(Timespan.class); createAnnotationType(Timestamp.class); createAnnotationType(Label.class); - defineType(long.class, null, false); implicitFieldTypes = true; } addFields(type, requestable, hasDuration, hasThread, hasStackTrace, hasCutoff); @@ -363,7 +365,7 @@ public final class TypeLibrary { Name name = field.getAnnotation(Name.class); String useName = fieldName; if (name != null) { - useName = name.value(); + useName = Utils.validJavaIdentifier(name.value(), useName); } List ans = new ArrayList<>(); for (Annotation a : resolveRepeatedAnnotations(field.getAnnotations())) { 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 db38d3a8d1c..38179ba891b 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/Utils.java @@ -54,6 +54,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import jdk.internal.module.Checks; import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.util.CheckClassAdapter; import jdk.internal.platform.Metrics; @@ -841,4 +842,28 @@ public final class Utils { public static long timeToNanos(Instant timestamp) { return timestamp.getEpochSecond() * 1_000_000_000L + timestamp.getNano(); } + + public static String validTypeName(String typeName, String defaultTypeName) { + if (Checks.isClassName(typeName)) { + return typeName; + } else { + Logger.log(LogTag.JFR, LogLevel.WARN, "@Name ignored, not a valid Java type name."); + return defaultTypeName; + } + } + + public static String validJavaIdentifier(String identifier, String defaultIdentifier) { + if (Checks.isJavaIdentifier(identifier)) { + return identifier; + } else { + Logger.log(LogTag.JFR, LogLevel.WARN, "@Name ignored, not a valid Java identifier."); + return defaultIdentifier; + } + } + + public static void ensureJavaIdentifier(String name) { + if (!Checks.isJavaIdentifier(name)) { + throw new IllegalArgumentException("'" + name + "' is not a valid Java identifier"); + } + } } diff --git a/test/jdk/jdk/jfr/api/metadata/annotations/TestName.java b/test/jdk/jdk/jfr/api/metadata/annotations/TestName.java index 3eb150ade81..ee0d38a58e1 100644 --- a/test/jdk/jdk/jfr/api/metadata/annotations/TestName.java +++ b/test/jdk/jdk/jfr/api/metadata/annotations/TestName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * 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,10 +23,13 @@ package jdk.jfr.api.metadata.annotations; +import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.List; +import java.util.Map; import jdk.jfr.AnnotationElement; import jdk.jfr.Event; @@ -56,6 +59,41 @@ public class TestName { @interface NamedAnnotation { } + @MetadataDefinition + @Name("for") + @Target({ ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @interface ReservedAnnotation { + } + + @MetadataDefinition + @Name("Hello World") + @Target({ ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @interface InvalidAnnotation1 { + } + + @MetadataDefinition + @Name("Bad#Name") + @Target({ ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @interface InvalidAnnotation2 { + } + + @MetadataDefinition + @Name("com.example.9thing") + @Target({ ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @interface InvalidAnnotation3 { + } + + @MetadataDefinition + @Name("") + @Target({ ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @interface EmptyAnnotation { + } + @NamedAnnotation @Name("com.oracle.TestEvent") static class NamedEvent extends Event { @@ -69,6 +107,91 @@ public class TestName { } } + @Name("continue") + static class ReservedEventName extends Event { + } + + static class ReservedFieldName extends Event { + @Name("final") + private int field; + } + + static class ReservedSettingName extends Event { + @SettingDefinition + @Name("true") + public boolean setting(SimpleSetting s) { + return true; + } + } + + @Name("Hello World") + static class InvalidEventName1 extends Event { + } + + @Name("Bad#Name") + static class InvalidEventName2 extends Event { + } + + @Name("com.example.9thing") + static class InvalidEventName3 extends Event { + } + + static class InvalidFieldName1 extends Event { + @Name("foo.bar") + int field; + } + + static class InvalidFieldName2 extends Event { + @Name("Hello World") + int field; + } + + static class InvalidFieldName3 extends Event { + @Name("1up") + int field; + } + + static class InvalidSettingName1 extends Event { + @SettingDefinition + @Name("foo.bar") + public boolean setting(SimpleSetting s) { + return true; + } + } + + static class InvalidSettingName2 extends Event { + @SettingDefinition + @Name("Hello World") + public boolean setting(SimpleSetting s) { + return true; + } + } + + static class InvalidSettingName3 extends Event { + @SettingDefinition + @Name("1up") + public boolean setting(SimpleSetting s) { + return true; + } + } + + @Name("") + static class EmptyEventName extends Event { + } + + static class EmptyFieldName extends Event { + @Name("") + private String field; + } + + static class EmptySettingName extends Event { + @SettingDefinition + @Name("") + public boolean setting(SimpleSetting s) { + return true; + } + } + public static void main(String[] args) throws Exception { EventType t = EventType.getEventType(NamedEvent.class); ValueDescriptor testField = t.getField("testField"); @@ -87,13 +210,93 @@ public class TestName { assertAnnotation(testField.getAnnotation(Name.class), "@Name should be persisted on field"); assertAnnotation(a.getAnnotation(Name.class), "@Name should be persisted on annotations"); assertAnnotation(setting.getAnnotation(Name.class), "@Name should be persisted on setting"); + + // Check invalid event name + assertIllegalEventName(ReservedEventName.class); + assertIllegalEventName(InvalidEventName1.class); + assertIllegalEventName(InvalidEventName2.class); + assertIllegalEventName(InvalidEventName3.class); + assertIllegalEventName(EmptyEventName.class); + + // Check invalid field names + assertIllegalFieldName(ReservedFieldName.class); + assertIllegalFieldName(InvalidFieldName1.class); + assertIllegalFieldName(InvalidFieldName2.class); + assertIllegalFieldName(InvalidFieldName3.class); + assertIllegalFieldName(EmptyFieldName.class); + + // Check invalid setting names + assertIllegalSettingName(ReservedSettingName.class); + assertIllegalSettingName(InvalidSettingName1.class); + assertIllegalSettingName(InvalidSettingName1.class); + assertIllegalSettingName(InvalidSettingName1.class); + assertIllegalSettingName(EmptySettingName.class); + + // Check invalid value descriptor names + testIllegalValueDescriptorName("goto"); + testIllegalValueDescriptorName("Hello World"); + testIllegalValueDescriptorName("1up"); + testIllegalValueDescriptorName("foo.bar"); + testIllegalValueDescriptorName(""); + + // Check invalid annotation names + testIllegalAnnotationName(ReservedAnnotation.class); + testIllegalAnnotationName(InvalidAnnotation1.class); + testIllegalAnnotationName(InvalidAnnotation2.class); + testIllegalAnnotationName(InvalidAnnotation3.class); + testIllegalAnnotationName(EmptyAnnotation.class); + } + + private static void assertIllegalEventName(Class eventClass) throws Exception { + EventType type = EventType.getEventType(eventClass); + if (!type.getName().equals(eventClass.getName())) { + throw new Exception("Expected default name " + eventClass.getName() + ", not illegal name " + type.getName()); + } } - // Can't use assert since the use toString on the object which doesn't work well JFR proxies. - private static void assertAnnotation(Object annotation,String message) throws Exception { - if (annotation == null) { - throw new Exception(message); - } + private static void assertIllegalSettingName(Class eventClass) throws Exception { + EventType type = EventType.getEventType(eventClass); + for (SettingDescriptor s : type.getSettingDescriptors()) { + if (s.getName().equals("setting")) { + return; + } + if (!List.of("threshold", "enabled", "stackTrace").contains(s.getName())) { + throw new Exception("Expected default setting name 'setting' for event " + type.getName() + ", not illegal " + s.getName()); + } + } + } + + private static void assertIllegalFieldName(Class eventClass) throws Exception { + EventType type = EventType.getEventType(eventClass); + if (type.getField("field") == null) { + String illegal = type.getFields().get(type.getFields().size() - 1).getName(); + throw new Exception("Expected default field name 'field' for event " + type.getName() + ", not illegal name " + illegal); + } + } + + private static void testIllegalValueDescriptorName(String illegalName) throws Exception { + try { + new ValueDescriptor(int.class, illegalName); + } catch (IllegalArgumentException iae) { + // OK, as expected + return; + } + throw new Exception("ValueDescriptor should not accept invalid field name '" + illegalName + "'"); + } + + private static void testIllegalAnnotationName(Class annotationClass) throws Exception { + AnnotationElement ae = new AnnotationElement(annotationClass, Map.of()); + if (!ae.getTypeName().equals(annotationClass.getName())) { + throw new Exception("AnnotationElement for class " + annotationClass + " not accept invalid type name '" + ae.getTypeName() + "'"); + } + } + + // Can't use assert since the use toString on the object which doesn't work well + // JFR proxies. + private static void assertAnnotation(Object annotation, String message) throws Exception { + if (annotation == null) { + throw new Exception(message); + } } private static SettingDescriptor getSetting(EventType t, String name) { -- GitLab From dad5d27172dbe24ae13b6386d1cdf15549f6619d Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 15:59:02 +0000 Subject: [PATCH 026/544] 8272867: JFR: ManagementSupport.removeBefore() lost coverage Reviewed-by: mseledtsov, mgronlun --- .../jdk/jfr/internal/management/ManagementSupport.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/management/ManagementSupport.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/management/ManagementSupport.java index 4230ed89e6e..b18a7901b99 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/management/ManagementSupport.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/management/ManagementSupport.java @@ -136,12 +136,6 @@ public final class ManagementSupport { return PrivateAccess.getInstance().newEventSettings(esm); } - // When streaming an ongoing recording, consumed chunks should be removed - public static void removeBefore(Recording recording, Instant timestamp) { - PlatformRecording pr = PrivateAccess.getInstance().getPlatformRecording(recording); - pr.removeBefore(timestamp); - } - // Needed callback to detect when a chunk has been parsed. public static void removePath(Recording recording, Path path) { PlatformRecording pr = PrivateAccess.getInstance().getPlatformRecording(recording); -- GitLab From 4b3a4fff39c1fba0d7eae719525e2a46b0a6d6ed Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Mon, 20 Sep 2021 16:17:52 +0000 Subject: [PATCH 027/544] 8273940: vmTestbase/vm/mlvm/meth/stress/gc/callSequencesDuringGC/Test.java crashes in full gc during VM exit Reviewed-by: lkorinth --- src/hotspot/share/gc/g1/g1ConcurrentMark.cpp | 11 +++-------- src/hotspot/share/gc/g1/g1ConcurrentMark.hpp | 4 ---- src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp | 2 -- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp index 5600826e3bf..3a377b80f1f 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp @@ -2036,8 +2036,9 @@ void G1ConcurrentMark::concurrent_cycle_abort() { for (uint i = 0; i < _max_num_tasks; ++i) { _tasks[i]->clear_region_fields(); } - - abort_marking_threads(); + _first_overflow_barrier_sync.abort(); + _second_overflow_barrier_sync.abort(); + _has_aborted = true; SATBMarkQueueSet& satb_mq_set = G1BarrierSet::satb_mark_queue_set(); satb_mq_set.abandon_partial_marking(); @@ -2048,12 +2049,6 @@ void G1ConcurrentMark::concurrent_cycle_abort() { satb_mq_set.is_active() /* expected_active */); } -void G1ConcurrentMark::abort_marking_threads() { - _has_aborted = true; - _first_overflow_barrier_sync.abort(); - _second_overflow_barrier_sync.abort(); -} - static void print_ms_time_info(const char* prefix, const char* name, NumberSeq& ns) { log_trace(gc, marking)("%s%5d %12s: total time = %8.2f s (avg = %8.2f ms).", diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp index c4da559b497..054fc39e6b9 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp @@ -495,10 +495,6 @@ public: void concurrent_cycle_abort(); void concurrent_cycle_end(); - // Notifies marking threads to abort. This is a best-effort notification. Does not - // guarantee or update any state after the call. - void abort_marking_threads(); - void update_accum_task_vtime(int i, double vtime) { _accum_task_vtime[i] += vtime; } diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp b/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp index 5ecc2e6dcdc..dde620e9398 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp @@ -159,8 +159,6 @@ void G1ConcurrentMarkThread::run_service() { } void G1ConcurrentMarkThread::stop_service() { - _cm->abort_marking_threads(); - MutexLocker ml(CGC_lock, Mutex::_no_safepoint_check_flag); CGC_lock->notify_all(); } -- GitLab From 26e5e9ae8cddbbd8bc498d2951e37970358f79ba Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 16:53:20 +0000 Subject: [PATCH 028/544] 8273654: JFR: Remove unused SecuritySupport.setAccessible(Field) Reviewed-by: mseledtsov, shade --- .../share/classes/jdk/jfr/internal/SecuritySupport.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java index 55828463248..d761eb98c58 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java @@ -431,10 +431,6 @@ public final class SecuritySupport { doPrivileged(() -> method.setAccessible(true), new ReflectPermission("suppressAccessChecks")); } - static void setAccessible(Field field) { - doPrivileged(() -> field.setAccessible(true), new ReflectPermission("suppressAccessChecks")); - } - static void setAccessible(Constructor constructor) { doPrivileged(() -> constructor.setAccessible(true), new ReflectPermission("suppressAccessChecks")); } -- GitLab From a67f0f9dc04200c22db05e277346f24d31306b53 Mon Sep 17 00:00:00 2001 From: Calvin Cheung Date: Mon, 20 Sep 2021 16:56:32 +0000 Subject: [PATCH 029/544] 8273505: runtime/cds/appcds/loaderConstraints/DynamicLoaderConstraintsTest.java#default-cl crashed with SIGSEGV in MetaspaceShared::link_shared_classes Reviewed-by: iklam, minqi --- src/hotspot/share/cds/metaspaceShared.cpp | 14 +++++++------- src/hotspot/share/classfile/classLoaderData.cpp | 4 +--- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/hotspot/share/cds/metaspaceShared.cpp b/src/hotspot/share/cds/metaspaceShared.cpp index a67450cb122..a884cbd0c00 100644 --- a/src/hotspot/share/cds/metaspaceShared.cpp +++ b/src/hotspot/share/cds/metaspaceShared.cpp @@ -584,18 +584,19 @@ void VM_PopulateDumpSharedSpace::doit() { class CollectCLDClosure : public CLDClosure { GrowableArray _loaded_cld; + GrowableArray _loaded_cld_handles; // keep the CLDs alive + Thread* _current_thread; public: - CollectCLDClosure() {} + CollectCLDClosure(Thread* thread) : _current_thread(thread) {} ~CollectCLDClosure() { for (int i = 0; i < _loaded_cld.length(); i++) { ClassLoaderData* cld = _loaded_cld.at(i); - cld->dec_keep_alive(); } } void do_cld(ClassLoaderData* cld) { if (!cld->is_unloading()) { - cld->inc_keep_alive(); _loaded_cld.append(cld); + _loaded_cld_handles.append(Handle(_current_thread, cld->holder_phantom())); } } @@ -641,11 +642,10 @@ bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) { } void MetaspaceShared::link_shared_classes(TRAPS) { - // Collect all loaded ClassLoaderData. - ResourceMark rm; - LambdaFormInvokers::regenerate_holder_classes(CHECK); - CollectCLDClosure collect_cld; + + // Collect all loaded ClassLoaderData. + CollectCLDClosure collect_cld(THREAD); { // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock. // We cannot link the classes while holding this lock (or else we may run into deadlock). diff --git a/src/hotspot/share/classfile/classLoaderData.cpp b/src/hotspot/share/classfile/classLoaderData.cpp index 3c9d842d969..87a6f27544a 100644 --- a/src/hotspot/share/classfile/classLoaderData.cpp +++ b/src/hotspot/share/classfile/classLoaderData.cpp @@ -302,9 +302,7 @@ bool ClassLoaderData::try_claim(int claim) { // it is being defined, therefore _keep_alive is not volatile or atomic. void ClassLoaderData::inc_keep_alive() { if (has_class_mirror_holder()) { - if (!Arguments::is_dumping_archive()) { - assert(_keep_alive > 0, "Invalid keep alive increment count"); - } + assert(_keep_alive > 0, "Invalid keep alive increment count"); _keep_alive++; } } -- GitLab From b3b4b1cc218d4c02809eb7fd4d83d541acfbd9bd Mon Sep 17 00:00:00 2001 From: Andrey Turbanov Date: Mon, 20 Sep 2021 17:23:02 +0000 Subject: [PATCH 030/544] 8273907: Cleanup redundant Math.max/min calls in DefaultHighlighter Reviewed-by: pbansal, aivanov, azvegint --- .../share/classes/javax/swing/text/DefaultHighlighter.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java b/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java index 6ce84a0a849..790fc977793 100644 --- a/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * 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 javax.swing.*; public class DefaultHighlighter extends LayeredHighlighter { /** - * Creates a new DefaultHighlighther object. + * Creates a new DefaultHighlighter object. */ public DefaultHighlighter() { drawsLayeredHighlights = true; @@ -244,7 +244,7 @@ public class DefaultHighlighter extends LayeredHighlighter { lhi.width = lhi.height = 0; lhi.p0 = doc.createPosition(p0); lhi.p1 = doc.createPosition(p1); - safeDamageRange(Math.min(p0, p1), Math.max(p0, p1)); + safeDamageRange(p0, p1); } else { HighlightInfo info = (HighlightInfo) tag; -- GitLab From 5c21c0044104b52fcaf3f3a830ea6e219d504ada Mon Sep 17 00:00:00 2001 From: Mikhailo Seledtsov Date: Mon, 20 Sep 2021 19:03:34 +0000 Subject: [PATCH 031/544] 8267163: Rename anonymous loader tests to hidden loader tests Reviewed-by: dholmes, hseigel --- test/hotspot/jtreg/ProblemList-Xcomp.txt | 2 +- .../func/findByName/Test.java | 10 +++---- .../share/HiddenkTestee01.java} | 4 +-- .../share/HiddenkTestee02.java} | 6 ++--- .../share/StressClassLoadingTest.java | 8 +++--- .../stress/byteMutation/TEST.properties | 0 .../stress/byteMutation/Test.java | 26 +++++++++---------- .../stress/oome/heap/TEST.properties | 0 .../stress/oome/heap/Test.java | 12 ++++----- .../stress/oome/metaspace/TEST.properties | 0 .../stress/oome/metaspace/Test.java | 12 ++++----- .../stress/parallelLoad/TEST.properties | 0 .../stress/parallelLoad/Test.java | 14 +++++----- .../stress/randomBytecodes/TEST.properties | 0 .../stress/randomBytecodes/Test.java | 12 ++++----- 15 files changed, 53 insertions(+), 53 deletions(-) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/func/findByName/Test.java (89%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader/share/AnonkTestee01.java => hiddenloader/share/HiddenkTestee01.java} (97%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader/share/AnonkTestee02.java => hiddenloader/share/HiddenkTestee02.java} (89%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/share/StressClassLoadingTest.java (97%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/byteMutation/TEST.properties (100%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/byteMutation/Test.java (77%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/oome/heap/TEST.properties (100%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/oome/heap/Test.java (88%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/oome/metaspace/TEST.properties (100%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/oome/metaspace/Test.java (88%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/parallelLoad/TEST.properties (100%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/parallelLoad/Test.java (88%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/randomBytecodes/TEST.properties (100%) rename test/hotspot/jtreg/vmTestbase/vm/mlvm/{anonloader => hiddenloader}/stress/randomBytecodes/Test.java (89%) diff --git a/test/hotspot/jtreg/ProblemList-Xcomp.txt b/test/hotspot/jtreg/ProblemList-Xcomp.txt index 9a98552f228..ce331d62c28 100644 --- a/test/hotspot/jtreg/ProblemList-Xcomp.txt +++ b/test/hotspot/jtreg/ProblemList-Xcomp.txt @@ -35,4 +35,4 @@ vmTestbase/vm/mlvm/mixed/stress/regression/b6969574/INDIFY_Test.java 8265295 lin vmTestbase/nsk/jvmti/scenarios/sampling/SP07/sp07t002/TestDescription.java 8245680 windows-x64 -vmTestbase/vm/mlvm/anonloader/stress/oome/heap/Test.java 8273095 generic-all +vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/Test.java 8273095 generic-all diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/func/findByName/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/func/findByName/Test.java similarity index 89% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/func/findByName/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/func/findByName/Test.java index c327000dcdb..f891b980f82 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/func/findByName/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/func/findByName/Test.java @@ -37,23 +37,23 @@ * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.func.findByName.Test + * @build vm.mlvm.hiddenloader.func.findByName.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * - * @run main/othervm vm.mlvm.anonloader.func.findByName.Test + * @run main/othervm vm.mlvm.hiddenloader.func.findByName.Test */ -package vm.mlvm.anonloader.func.findByName; +package vm.mlvm.hiddenloader.func.findByName; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; -import vm.mlvm.anonloader.share.AnonkTestee01; +import vm.mlvm.hiddenloader.share.HiddenkTestee01; import vm.mlvm.share.MlvmTest; import vm.share.FileUtils; public class Test extends MlvmTest { - private static final Class PARENT = AnonkTestee01.class; + private static final Class PARENT = HiddenkTestee01.class; public boolean run() throws Exception { try { diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee01.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee01.java similarity index 97% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee01.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee01.java index 0594e8c523c..15b81f3c5a5 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee01.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee01.java @@ -21,11 +21,11 @@ * questions. */ -package vm.mlvm.anonloader.share; +package vm.mlvm.hiddenloader.share; import vm.mlvm.share.Env; -public class AnonkTestee01 { +public class HiddenkTestee01 { public final static String muzzy = "BIG \uFFFF\u0000\uFFFE\uFEFF MUZZY"; public final static String theDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrumIsTheDrum diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee02.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee02.java similarity index 89% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee02.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee02.java index 89f526e02e6..95d5372c762 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/AnonkTestee02.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/HiddenkTestee02.java @@ -21,8 +21,8 @@ * questions. */ -package vm.mlvm.anonloader.share; +package vm.mlvm.hiddenloader.share; -public class AnonkTestee02 extends AnonkTestee01 { - public AnonkTestee02() {} +public class HiddenkTestee02 extends HiddenkTestee01 { + public HiddenkTestee02() {} } diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/StressClassLoadingTest.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/StressClassLoadingTest.java similarity index 97% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/StressClassLoadingTest.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/StressClassLoadingTest.java index 2c9d96aac76..edb91743c44 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/share/StressClassLoadingTest.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/share/StressClassLoadingTest.java @@ -21,7 +21,7 @@ * questions. */ -package vm.mlvm.anonloader.share; +package vm.mlvm.hiddenloader.share; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; @@ -65,14 +65,14 @@ import vm.share.UnsafeAccess; *

The test fails, if there were hangups. * *

By default, before loading class, the bytes are - * saved to {@code _AnonkTestee01.class} file in the current directory. + * saved to {@code _HiddenkTestee01.class} file in the current directory. * If JVM crashes, the bytecodes can be analysed. * Class saving is controlled by -saveClassFile option. * A prefix can be added to the file name using {@link #setFileNamePrefix} * function. */ public abstract class StressClassLoadingTest extends MlvmTest { - private static final String RESCUE_FILE_NAME = "_AnonkTestee01.class"; + private static final String RESCUE_FILE_NAME = "_HiddenkTestee01.class"; private static final String HUNG_CLASS_FILE_NAME = "hang.class"; @Option(name = "iterations", default_value = "100000", @@ -100,7 +100,7 @@ public abstract class StressClassLoadingTest extends MlvmTest { /** * Sets prefix for names of the files, created by test: - * _AnonkTestee01.class and hangXX.class. + * _HiddenkTestee01.class and hangXX.class. * * @param p a prefix to add before file name. * @throws java.lang.NullPointerException if p is null diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/byteMutation/TEST.properties b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/byteMutation/TEST.properties similarity index 100% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/byteMutation/TEST.properties rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/byteMutation/TEST.properties diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/byteMutation/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/byteMutation/Test.java similarity index 77% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/byteMutation/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/byteMutation/Test.java index 305eb6cc408..e6a3e8a890d 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/byteMutation/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/byteMutation/Test.java @@ -27,23 +27,23 @@ * @key randomness * @modules java.base/jdk.internal.misc * - * @summary converted from VM Testbase vm/mlvm/anonloader/stress/byteMutation. + * @summary converted from VM Testbase vm/mlvm/hiddenloader/stress/byteMutation. * VM Testbase keywords: [feature_mlvm, nonconcurrent] * * @library /vmTestbase * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.stress.byteMutation.Test + * @build vm.mlvm.hiddenloader.stress.byteMutation.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * - * @run main/othervm vm.mlvm.anonloader.stress.byteMutation.Test -stressIterationsFactor 100000 + * @run main/othervm vm.mlvm.hiddenloader.stress.byteMutation.Test -stressIterationsFactor 100000 */ -package vm.mlvm.anonloader.stress.byteMutation; +package vm.mlvm.hiddenloader.stress.byteMutation; -import vm.mlvm.anonloader.share.AnonkTestee01; -import vm.mlvm.anonloader.share.StressClassLoadingTest; +import vm.mlvm.hiddenloader.share.HiddenkTestee01; +import vm.mlvm.hiddenloader.share.StressClassLoadingTest; import vm.share.FileUtils; import vm.share.options.Option; @@ -67,7 +67,7 @@ import vm.share.options.Option; * */ public class Test extends StressClassLoadingTest { - private final static Class HOST_CLASS = AnonkTestee01.class; + private final static Class HOST_CLASS = HiddenkTestee01.class; private final byte[] testeeBytes; @Option(name = "mutationCount", default_value = "3", description = "How many bytes to mutate in a class") @@ -76,16 +76,16 @@ public class Test extends StressClassLoadingTest { /** * Constructs the test. * @throws Exception if there are any errors when - * reading {@link vm.mlvm.anonloader.share.AnonkTestee01} class bytecodes. + * reading {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class bytecodes. */ public Test() throws Exception { - this.testeeBytes = FileUtils.readClass(AnonkTestee01.class.getName()); + this.testeeBytes = FileUtils.readClass(HiddenkTestee01.class.getName()); } /** - * Returns {@link vm.mlvm.anonloader.share.AnonkTestee01} class to the + * Returns {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class to the * parent. - * @return {@link vm.mlvm.anonloader.share.AnonkTestee01} class. + * @return {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class. */ @Override protected Class getHostClass() { @@ -93,9 +93,9 @@ public class Test extends StressClassLoadingTest { } /** - * Takes {@link vm.mlvm.anonloader.share.AnonkTestee01} class bytecodes + * Takes {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class bytecodes * and modifies mutationCount bytes setting them to random values. - * @return {@link vm.mlvm.anonloader.share.AnonkTestee01} class bytecodes with modified bytes. + * @return {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class bytecodes with modified bytes. */ @Override protected byte[] generateClassBytes() { diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/heap/TEST.properties b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/TEST.properties similarity index 100% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/heap/TEST.properties rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/TEST.properties diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/heap/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/Test.java similarity index 88% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/heap/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/Test.java index 723c63d02fb..9d0a25b00e4 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/heap/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/heap/Test.java @@ -34,20 +34,20 @@ * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.stress.oome.heap.Test + * @build vm.mlvm.hiddenloader.stress.oome.heap.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * - * @run main/othervm -XX:-UseGCOverheadLimit -Xmx128m vm.mlvm.anonloader.stress.oome.heap.Test + * @run main/othervm -XX:-UseGCOverheadLimit -Xmx128m vm.mlvm.hiddenloader.stress.oome.heap.Test */ -package vm.mlvm.anonloader.stress.oome.heap; +package vm.mlvm.hiddenloader.stress.oome.heap; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.util.List; import java.io.IOException; -import vm.mlvm.anonloader.share.AnonkTestee01; +import vm.mlvm.hiddenloader.share.HiddenkTestee01; import vm.mlvm.share.MlvmOOMTest; import vm.mlvm.share.MlvmTestExecutor; import vm.mlvm.share.Env; @@ -71,14 +71,14 @@ public class Test extends MlvmOOMTest { protected void eatMemory(List list) { byte[] classBytes = null; try { - classBytes = FileUtils.readClass(AnonkTestee01.class.getName()); + classBytes = FileUtils.readClass(HiddenkTestee01.class.getName()); } catch (IOException e) { Env.throwAsUncheckedException(e); } try { while (true) { Lookup lookup = MethodHandles.lookup(); - Lookup ank_lookup = MethodHandles.privateLookupIn(AnonkTestee01.class, lookup); + Lookup ank_lookup = MethodHandles.privateLookupIn(HiddenkTestee01.class, lookup); Class c = ank_lookup.defineHiddenClass(classBytes, true).lookupClass(); list.add(c.newInstance()); } diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/metaspace/TEST.properties b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/metaspace/TEST.properties similarity index 100% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/metaspace/TEST.properties rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/metaspace/TEST.properties diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/metaspace/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/metaspace/Test.java similarity index 88% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/metaspace/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/metaspace/Test.java index 1984555708e..85bb7c6167f 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/oome/metaspace/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/oome/metaspace/Test.java @@ -33,21 +33,21 @@ * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.stress.oome.metaspace.Test + * @build vm.mlvm.hiddenloader.stress.oome.metaspace.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * * @run main/othervm -XX:MaxRAMPercentage=25 -XX:-UseGCOverheadLimit -XX:MetaspaceSize=10m - * -XX:MaxMetaspaceSize=20m vm.mlvm.anonloader.stress.oome.metaspace.Test + * -XX:MaxMetaspaceSize=20m vm.mlvm.hiddenloader.stress.oome.metaspace.Test */ -package vm.mlvm.anonloader.stress.oome.metaspace; +package vm.mlvm.hiddenloader.stress.oome.metaspace; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.util.List; import java.io.IOException; -import vm.mlvm.anonloader.share.AnonkTestee01; +import vm.mlvm.hiddenloader.share.HiddenkTestee01; import vm.mlvm.share.MlvmOOMTest; import vm.mlvm.share.MlvmTestExecutor; import vm.mlvm.share.Env; @@ -71,14 +71,14 @@ public class Test extends MlvmOOMTest { protected void eatMemory(List list) { byte[] classBytes = null; try { - classBytes = FileUtils.readClass(AnonkTestee01.class.getName()); + classBytes = FileUtils.readClass(HiddenkTestee01.class.getName()); } catch (IOException e) { Env.throwAsUncheckedException(e); } try { while (true) { Lookup lookup = MethodHandles.lookup(); - Lookup ank_lookup = MethodHandles.privateLookupIn(AnonkTestee01.class, lookup); + Lookup ank_lookup = MethodHandles.privateLookupIn(HiddenkTestee01.class, lookup); Class c = ank_lookup.defineHiddenClass(classBytes, true).lookupClass(); list.add(c.newInstance()); } diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/parallelLoad/TEST.properties b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/parallelLoad/TEST.properties similarity index 100% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/parallelLoad/TEST.properties rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/parallelLoad/TEST.properties diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/parallelLoad/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/parallelLoad/Test.java similarity index 88% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/parallelLoad/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/parallelLoad/Test.java index 4ba9a037ead..fa4dbf3f4eb 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/parallelLoad/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/parallelLoad/Test.java @@ -33,22 +33,22 @@ * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.stress.parallelLoad.Test + * @build vm.mlvm.hiddenloader.stress.parallelLoad.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * * @run main/othervm * -Xverify:all - * vm.mlvm.anonloader.stress.parallelLoad.Test + * vm.mlvm.hiddenloader.stress.parallelLoad.Test * -threadsPerCpu 4 * -threadsExtra 20 * -parseTimeout 0 * -hiddenLoad true */ -package vm.mlvm.anonloader.stress.parallelLoad; +package vm.mlvm.hiddenloader.stress.parallelLoad; -import vm.mlvm.anonloader.share.StressClassLoadingTest; -import vm.mlvm.anonloader.share.AnonkTestee01; +import vm.mlvm.hiddenloader.share.StressClassLoadingTest; +import vm.mlvm.hiddenloader.share.HiddenkTestee01; import vm.mlvm.share.MlvmTestExecutor; import vm.mlvm.share.MultiThreadedTest; import vm.share.FileUtils; @@ -60,7 +60,7 @@ import vm.share.FileUtils; * */ public class Test extends MultiThreadedTest { - private static final Class HOST_CLASS = AnonkTestee01.class; + private static final Class HOST_CLASS = HiddenkTestee01.class; private static final String NAME_PREFIX = "thread%03d"; private final byte[] classBytes; @@ -89,7 +89,7 @@ public class Test extends MultiThreadedTest { /** * Constructs a sub-test class and runs it. The sub-test class loads - * {@link vm.mlvm.anonloader.share.AnonkTestee01} class bytecodes + * {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class bytecodes * using {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass} * @param numThread Number of the thread * @throws Exception if there any exceptions thrown in the sub-test diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/randomBytecodes/TEST.properties b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/randomBytecodes/TEST.properties similarity index 100% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/randomBytecodes/TEST.properties rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/randomBytecodes/TEST.properties diff --git a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/randomBytecodes/Test.java b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/randomBytecodes/Test.java similarity index 89% rename from test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/randomBytecodes/Test.java rename to test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/randomBytecodes/Test.java index d28525041f6..b6146e59eed 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/mlvm/anonloader/stress/randomBytecodes/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/mlvm/hiddenloader/stress/randomBytecodes/Test.java @@ -34,16 +34,16 @@ * /test/lib * * @comment build test class and indify classes - * @build vm.mlvm.anonloader.stress.randomBytecodes.Test + * @build vm.mlvm.hiddenloader.stress.randomBytecodes.Test * @run driver vm.mlvm.share.IndifiedClassesBuilder * - * @run main/othervm vm.mlvm.anonloader.stress.randomBytecodes.Test -stressIterationsFactor 100000 + * @run main/othervm vm.mlvm.hiddenloader.stress.randomBytecodes.Test -stressIterationsFactor 100000 */ -package vm.mlvm.anonloader.stress.randomBytecodes; +package vm.mlvm.hiddenloader.stress.randomBytecodes; import java.util.Arrays; -import vm.mlvm.anonloader.share.StressClassLoadingTest; +import vm.mlvm.hiddenloader.share.StressClassLoadingTest; /** * The test does the following in a cycle: @@ -72,9 +72,9 @@ public class Test extends StressClassLoadingTest { }; /** - * Returns {@link vm.mlvm.anonloader.share.AnonkTestee01} class to the + * Returns {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class to the * parent. - * @return {@link vm.mlvm.anonloader.share.AnonkTestee01} class. + * @return {@link vm.mlvm.hiddenloader.share.HiddenkTestee01} class. */ @Override protected Class getHostClass() { -- GitLab From 04891c95e0a29409959aa3e649964788e589a6da Mon Sep 17 00:00:00 2001 From: Chris Plummer Date: Mon, 20 Sep 2021 20:10:10 +0000 Subject: [PATCH 032/544] 8273912: Add threadControl_dumpThread(jthread) function Reviewed-by: kevinw, sspitsyn --- .../share/native/libjdwp/threadControl.c | 11 +++++++++++ .../share/native/libjdwp/threadControl.h | 1 + 2 files changed, 12 insertions(+) diff --git a/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.c b/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.c index 59abd4a4942..a35458c2f18 100644 --- a/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.c +++ b/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.c @@ -2586,6 +2586,17 @@ threadControl_dumpAllThreads() dumpThreadList(&otherThreads); } +void +threadControl_dumpThread(jthread thread) +{ + ThreadNode* node = findThread(NULL, thread); + if (node == NULL) { + tty_message("Thread not found"); + } else { + dumpThread(node); + } +} + static void dumpThreadList(ThreadList *list) { diff --git a/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.h b/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.h index c8210cfb99d..c58c066feb8 100644 --- a/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.h +++ b/src/jdk.jdwp.agent/share/native/libjdwp/threadControl.h @@ -78,6 +78,7 @@ jlong threadControl_getFrameGeneration(jthread thread); #ifdef DEBUG void threadControl_dumpAllThreads(); +void threadControl_dumpThread(jthread thread); #endif #endif -- GitLab From 5fde4b64e25a3b3a4c01c57064624b9f930a1324 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Mon, 20 Sep 2021 20:17:57 +0000 Subject: [PATCH 033/544] 8273909: vmTestbase/nsk/jdi/Event/request/request001 can still fail with "ERROR: new event is not ThreadStartEvent" Reviewed-by: cjplummer, sspitsyn --- .../nsk/jdi/Event/request/request001.java | 2 -- .../EventIterator/nextEvent/nextevent001.java | 2 -- .../addThreadFilter/addthreadfilter001.java | 3 --- .../vmTestbase/nsk/share/jdi/JDIBase.java | 20 ++++++++++--------- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/request/request001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/request/request001.java index 1e9560e712f..5034a5f5ee0 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/request/request001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/request/request001.java @@ -335,7 +335,6 @@ public class request001 extends JDIBase { log2("......setting up ThreadStartRequest"); ThreadStartRequest tsr = eventRManager.createThreadStartRequest(); - tsr.addCountFilter(1); tsr.setSuspendPolicy(EventRequest.SUSPEND_ALL); tsr.putProperty("number", "ThreadStartRequest"); tsr.enable(); @@ -344,7 +343,6 @@ public class request001 extends JDIBase { log2("......setting up ThreadDeathRequest"); ThreadDeathRequest tdr = eventRManager.createThreadDeathRequest(); - tdr.addCountFilter(1); tdr.setSuspendPolicy(EventRequest.SUSPEND_ALL); tsr.putProperty("number", "ThreadDeathRequest"); tdr.enable(); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java index 444382bbdb1..1c3a03f4fe7 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventIterator/nextEvent/nextevent001.java @@ -324,7 +324,6 @@ public class nextevent001 extends JDIBase { log2("......setting up ThreadStartRequest"); ThreadStartRequest tsr = eventRManager.createThreadStartRequest(); - tsr.addCountFilter(1); tsr.setSuspendPolicy(EventRequest.SUSPEND_ALL); tsr.putProperty("number", "ThreadStartRequest"); tsr.enable(); @@ -333,7 +332,6 @@ public class nextevent001 extends JDIBase { log2("......setting up ThreadDeathRequest"); ThreadDeathRequest tdr = eventRManager.createThreadDeathRequest(); - tdr.addCountFilter(1); tdr.setSuspendPolicy(EventRequest.SUSPEND_ALL); tsr.putProperty("number", "ThreadDeathRequest"); tdr.enable(); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadDeathRequest/addThreadFilter/addthreadfilter001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadDeathRequest/addThreadFilter/addthreadfilter001.java index 573ef44f867..5dc0293b848 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadDeathRequest/addThreadFilter/addthreadfilter001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadDeathRequest/addThreadFilter/addthreadfilter001.java @@ -279,21 +279,18 @@ public class addthreadfilter001 extends JDIBase { log2("......setting up ThreadDeathRequest"); ThreadDeathRequest tdr1 = eventRManager.createThreadDeathRequest(); // tdr1.addThreadFilter(mainThread); - tdr1.addCountFilter(1); tdr1.setSuspendPolicy(EventRequest.SUSPEND_ALL); tdr1.putProperty("number", "ThreadDeathRequest1"); tdr1.enable(); ThreadDeathRequest tdr2 = eventRManager.createThreadDeathRequest(); // tsr2.addThreadFilter(mainThread); - tdr2.addCountFilter(1); tdr2.setSuspendPolicy(EventRequest.SUSPEND_ALL); tdr2.putProperty("number", "ThreadDeathRequest2"); tdr2.enable(); ThreadDeathRequest tdr3 = eventRManager.createThreadDeathRequest(); tdr3.addThreadFilter(testThread); - tdr3.addCountFilter(1); tdr3.setSuspendPolicy(EventRequest.SUSPEND_ALL); tdr3.putProperty("number", "ThreadDeathRequest3"); tdr3.enable(); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java index da8c49119b7..d20a084a632 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jdi/JDIBase.java @@ -157,27 +157,29 @@ public class JDIBase { // we can get the events from system threads unexpected for tests. // The method skips ThreadStartEvent/ThreadDeathEvent events // for all threads except the expected one. + // Note: don't limit ThreadStartRequest/ThreadDeathRequest request by addCountFilter(), + // as it limits the requested event to be reported at most once. protected void getEventSetForThreadStartDeath(String threadName) throws JDITestRuntimeException { - boolean gotDesiredEvent = false; - while (!gotDesiredEvent) { + while (true) { getEventSet(); Event event = eventIterator.nextEvent(); if (event instanceof ThreadStartEvent evt) { if (evt.thread().name().equals(threadName)) { - gotDesiredEvent = true; - } else { - log2("Got ThreadStartEvent for wrong thread: " + event); + break; } + log2("Got ThreadStartEvent for '" + evt.thread().name() + + "' instead of '" + threadName + "', skipping"); } else if (event instanceof ThreadDeathEvent evt) { if (evt.thread().name().equals(threadName)) { - gotDesiredEvent = true; - } else { - log2("Got ThreadDeathEvent for wrong thread: " + event); + break; } + log2("Got ThreadDeathEvent for '" + evt.thread().name() + + "' instead of '" + threadName + "', skipping"); } else { // not ThreadStartEvent nor ThreadDeathEvent - gotDesiredEvent = true; + break; } + eventSet.resume(); } // reset the iterator before return eventIterator = eventSet.eventIterator(); -- GitLab From ee3576a48b700df3d8ad4bd447346d4102b20818 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 20:43:22 +0000 Subject: [PATCH 034/544] 8256735: JFR: 'jfr' tool displays incorrect timestamps Reviewed-by: mseledtsov, mgronlun --- .../share/classes/jdk/jfr/internal/tool/PrettyWriter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 133a35e3979..32178df920c 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 @@ -59,7 +59,7 @@ import jdk.jfr.internal.Utils; */ public final class PrettyWriter extends EventPrintWriter { private static final String TYPE_OLD_OBJECT = Type.TYPES_PREFIX + "OldObject"; - private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss.SSS (YYYY-MM-dd)"); private static final Long ZERO = 0L; private boolean showIds; private RecordedEvent currentEvent; -- GitLab From 1bd11a7f2ca433f4aa9c545a20960e0778ec545e Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Mon, 20 Sep 2021 21:25:40 +0000 Subject: [PATCH 035/544] 8273887: [macos] java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java timed out Reviewed-by: aivanov --- .../awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java b/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java index 7d0b501e72b..d9e10785cff 100644 --- a/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java +++ b/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java @@ -110,7 +110,7 @@ public final class MTTransformReplacedProfile { float[] colorvalue = new float[3]; Thread transform = new Thread(() -> { boolean rgb = true; - while (!stop.get()) { + while (!stop.get() && !isComplete()) { try { if (rgb) { cs.toRGB(colorvalue); -- GitLab From 7ce60c6ff6950bbe07fbc363303e7e6ce5e1b696 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 21:58:57 +0000 Subject: [PATCH 036/544] 8273651: JFR: onMetadata(), setStartTime(), setEndTime() lacks test coverage Reviewed-by: mgronlun, mseledtsov --- .../jdk/jfr/jmx/streaming/TestDelegated.java | 34 ++++++++- .../jfr/jmx/streaming/TestMetadataEvent.java | 76 +++++++++++++++++++ 2 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java b/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java index 8ecd6c8e2da..2232000a559 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestDelegated.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ package jdk.jfr.jmx.streaming; import java.lang.management.ManagementFactory; import java.time.Duration; +import java.time.Instant; import java.util.concurrent.CountDownLatch; import javax.management.MBeanServerConnection; @@ -63,6 +64,8 @@ public class TestDelegated { testSetMaxAge(); testAwaitTermination(); testAwaitTerminationWithDuration(); + testSetStartTime(); + testSetEndTime(); } private static void testSetMaxAge() throws Exception { @@ -166,7 +169,6 @@ public class TestDelegated { e.commit(); latch.await(); } - } private static void testOrdered() throws Exception { @@ -198,4 +200,32 @@ public class TestDelegated { } } } + + private static void testSetEndTime() throws Exception { + Instant t = Instant.now().plus(Duration.ofDays(1)); + try (RemoteRecordingStream stream = new RemoteRecordingStream(CONNECTION)) { + stream.setEndTime(t); + stream.onEvent(e -> { + stream.close(); + }); + stream.startAsync(); + TestDelegatedEvent e = new TestDelegatedEvent(); + e.commit(); + stream.awaitTermination(); + } + } + + private static void testSetStartTime() throws Exception { + Instant t = Instant.now().minus(Duration.ofDays(1)); + try (RemoteRecordingStream stream = new RemoteRecordingStream(CONNECTION)) { + stream.setStartTime(t); + stream.onEvent(e -> { + stream.close(); + }); + stream.startAsync(); + TestDelegatedEvent e = new TestDelegatedEvent(); + e.commit(); + stream.awaitTermination(); + } + } } diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java b/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java new file mode 100644 index 00000000000..935ef292a55 --- /dev/null +++ b/test/jdk/jdk/jfr/jmx/streaming/TestMetadataEvent.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.jmx.streaming; + +import java.lang.management.ManagementFactory; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.function.Function; + +import jdk.jfr.Configuration; +import jdk.jfr.EventType; +import jdk.jfr.FlightRecorder; +import jdk.jfr.consumer.MetadataEvent; +import jdk.management.jfr.RemoteRecordingStream; + +/** + * @test + * @key jfr + * @summary Sanity tests RemoteRecordingStream::onMetadata + * @requires vm.hasJFR + * @library /test/lib /test/jdk + * @run main/othervm jdk.jfr.jmx.streaming.TestMetadataEvent + */ +public class TestMetadataEvent { + + public static void main(String... args) throws Exception { + var conn = ManagementFactory.getPlatformMBeanServer(); + var q = new ArrayBlockingQueue(1); + try (RemoteRecordingStream e = new RemoteRecordingStream(conn)) { + e.onMetadata(q::offer); + e.startAsync(); + MetadataEvent event = q.take(); + assertEventTypes(FlightRecorder.getFlightRecorder().getEventTypes(), event.getEventTypes()); + assertConfigurations(Configuration.getConfigurations(), event.getConfigurations()); + } + } + + private static void assertEventTypes(List expected, List eventTypes) throws Exception { + assertListProperty(expected, eventTypes, EventType::getName); + } + + private static void assertConfigurations(List expected, List configurations) throws Exception { + assertListProperty(expected, configurations, Configuration::getName); + } + + private static void assertListProperty(List expected, List result, Function mapper) throws Exception { + var a1 = new HashSet(); + a1.addAll(expected.stream().map(mapper).toList()); + var a2 = new HashSet(); + a2.addAll(result.stream().map(mapper).toList()); + if (!a1.equals(a2)) { + throw new Exception("Result not as expected!\nexpected = " + a1 + "\nresult= " + a2); + } + } +} -- GitLab From d16bf04c95ad20a003af70679e7b735b0780ac30 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Mon, 20 Sep 2021 23:15:39 +0000 Subject: [PATCH 037/544] 8273613: JFR: RemoteRecordingStream::start() blocks close() Reviewed-by: mgronlun --- .../management/jfr/RemoteRecordingStream.java | 57 +++++----- test/jdk/jdk/jfr/jmx/streaming/TestStart.java | 101 ++++++++++++++++++ 2 files changed, 128 insertions(+), 30 deletions(-) create mode 100644 test/jdk/jdk/jfr/jmx/streaming/TestStart.java diff --git a/src/jdk.management.jfr/share/classes/jdk/management/jfr/RemoteRecordingStream.java b/src/jdk.management.jfr/share/classes/jdk/management/jfr/RemoteRecordingStream.java index 2108cd97c7f..6010b8d8456 100644 --- a/src/jdk.management.jfr/share/classes/jdk/management/jfr/RemoteRecordingStream.java +++ b/src/jdk.management.jfr/share/classes/jdk/management/jfr/RemoteRecordingStream.java @@ -520,47 +520,44 @@ public final class RemoteRecordingStream implements EventStream { @Override public void start() { - synchronized (lock) { // ensure one starter - ensureStartable(); + ensureStartable(); + try { try { - try { - mbean.startRecording(recordingId); - } catch (IllegalStateException ise) { - throw ise; - } - startDownload(); - } catch (Exception e) { - ManagementSupport.logDebug(e.getMessage()); - close(); - return; + mbean.startRecording(recordingId); + } catch (IllegalStateException ise) { + throw ise; } - stream.start(); - started = true; + startDownload(); + } catch (Exception e) { + ManagementSupport.logDebug(e.getMessage()); + close(); + return; } + stream.start(); } @Override public void startAsync() { - synchronized (lock) { // ensure one starter - ensureStartable(); - stream.startAsync(); - try { - mbean.startRecording(recordingId); - startDownload(); - } catch (Exception e) { - ManagementSupport.logDebug(e.getMessage()); - close(); - } - started = true; + ensureStartable(); + stream.startAsync(); + try { + mbean.startRecording(recordingId); + startDownload(); + } catch (Exception e) { + ManagementSupport.logDebug(e.getMessage()); + close(); } } private void ensureStartable() { - if (closed) { - throw new IllegalStateException("Event stream is closed"); - } - if (started) { - throw new IllegalStateException("Event stream can only be started once"); + synchronized (lock) { + if (closed) { + throw new IllegalStateException("Event stream is closed"); + } + if (started) { + throw new IllegalStateException("Event stream can only be started once"); + } + started = true; } } diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestStart.java b/test/jdk/jdk/jfr/jmx/streaming/TestStart.java new file mode 100644 index 00000000000..0755e99cb04 --- /dev/null +++ b/test/jdk/jdk/jfr/jmx/streaming/TestStart.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.jmx.streaming; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.concurrent.CountDownLatch; + +import javax.management.MBeanServerConnection; + +import jdk.management.jfr.RemoteRecordingStream; + +/** + * @test + * @key jfr + * @summary Sanity tests RemoteRecordingStream::start() + * @requires vm.hasJFR + * @library /test/lib /test/jdk + * @run main/othervm jdk.jfr.jmx.streaming.TestStart + */ +public class TestStart { + + private final static MBeanServerConnection CONNECTION = ManagementFactory.getPlatformMBeanServer(); + + public static void main(String... args) throws Exception { + testStart(); + testStartTwice(); + testStartClosed(); + } + + private static void testStart() throws IOException { + try (var r = new RemoteRecordingStream(CONNECTION)) { + r.onFlush(() -> { + System.out.print("Started."); + r.close(); + }); + System.out.println("About to start ..."); + r.start(); + System.out.println("Finished!"); + } + } + + private static void testStartTwice() throws Exception { + var latch = new CountDownLatch(1); + try (var r = new RemoteRecordingStream(CONNECTION)) { + r.onFlush(() -> latch.countDown()); + Runnable starter = () -> { + r.start(); + }; + new Thread(starter).start(); + latch.await(); + try { + r.start(); + } catch (IllegalStateException ise) { + // OK, as expected + return; + } + throw new Exception("Expected IllegalStateException when starting same stream twice"); + } + } + + private static void testStartClosed() throws Exception { + var latch = new CountDownLatch(1); + try (var r = new RemoteRecordingStream(CONNECTION)) { + r.onFlush(() -> latch.countDown()); + Runnable starter = () -> { + r.start(); + }; + new Thread(starter).start(); + latch.await(); + r.close(); + try { + r.start(); + } catch (IllegalStateException ise) { + // OK, as expected + return; + } + throw new Exception("Expected IllegalStateException when starting closed stream"); + } + } +} -- GitLab From 9c91ff57e8b4b48e997e0424ff93b29e695ec527 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 21 Sep 2021 02:23:52 +0000 Subject: [PATCH 038/544] 8274031: Typo in StringBuilder.readObject Reviewed-by: bpb --- src/java.base/share/classes/java/lang/StringBuilder.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/java.base/share/classes/java/lang/StringBuilder.java b/src/java.base/share/classes/java/lang/StringBuilder.java index e52da83fd26..b22ed99dbfc 100644 --- a/src/java.base/share/classes/java/lang/StringBuilder.java +++ b/src/java.base/share/classes/java/lang/StringBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -479,7 +479,7 @@ public final class StringBuilder } /** - * readObject is called to restore the state of the StringBuffer from + * readObject is called to restore the state of the StringBuilder from * a stream. * * @param s the {@code ObjectInputStream} from which data is read -- GitLab From 240fa6efa266bc9c9f269c6215aa9df469b6eaa8 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Tue, 21 Sep 2021 05:57:57 +0000 Subject: [PATCH 039/544] 8273927: Enable hsdis for riscv64 Reviewed-by: ihse --- src/utils/hsdis/hsdis.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/utils/hsdis/hsdis.c b/src/utils/hsdis/hsdis.c index fe7810b1957..8e3f0ca7836 100644 --- a/src/utils/hsdis/hsdis.c +++ b/src/utils/hsdis/hsdis.c @@ -495,6 +495,9 @@ static const char* native_arch_name() { #endif #ifdef LIBARCH_s390x res = "s390:64-bit"; +#endif +#ifdef LIBARCH_riscv64 + res = "riscv:rv64"; #endif if (res == NULL) res = "architecture not set in Makefile!"; -- GitLab From f242cb5ce0af3bacf7af51351121f9137db92931 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Tue, 21 Sep 2021 06:00:06 +0000 Subject: [PATCH 040/544] 8273797: Stop impersonating "server" VM in all VM variants Reviewed-by: dholmes, erikj, ihse --- make/autoconf/flags-ldflags.m4 | 12 +++--------- make/autoconf/hotspot.m4 | 9 --------- make/hotspot/HotspotCommon.gmk | 8 +------- make/modules/java.base/Copy.gmk | 10 ++-------- make/modules/java.base/Lib.gmk | 7 ++----- 5 files changed, 8 insertions(+), 38 deletions(-) diff --git a/make/autoconf/flags-ldflags.m4 b/make/autoconf/flags-ldflags.m4 index c0e6ffec56b..e9d4557f866 100644 --- a/make/autoconf/flags-ldflags.m4 +++ b/make/autoconf/flags-ldflags.m4 @@ -32,16 +32,10 @@ AC_DEFUN([FLAGS_SETUP_LDFLAGS], # Setup the target toolchain + # The target dir matches the name of VM variant + TARGET_JVM_VARIANT_PATH=$JVM_VARIANT_MAIN + # On some platforms (mac) the linker warns about non existing -L dirs. - # For any of the variants server, client, minimal or zero, the dir matches the - # variant name. The "main" variant should be used for linking. For the - # rest, the dir is just server. - if HOTSPOT_CHECK_JVM_VARIANT(server) || HOTSPOT_CHECK_JVM_VARIANT(client) \ - || HOTSPOT_CHECK_JVM_VARIANT(minimal) || HOTSPOT_CHECK_JVM_VARIANT(zero); then - TARGET_JVM_VARIANT_PATH=$JVM_VARIANT_MAIN - else - TARGET_JVM_VARIANT_PATH=server - fi FLAGS_SETUP_LDFLAGS_CPU_DEP([TARGET]) # Setup the build toolchain diff --git a/make/autoconf/hotspot.m4 b/make/autoconf/hotspot.m4 index 6959db761af..1cac6bb00c6 100644 --- a/make/autoconf/hotspot.m4 +++ b/make/autoconf/hotspot.m4 @@ -83,15 +83,6 @@ AC_DEFUN_ONCE([HOTSPOT_SETUP_JVM_VARIANTS], AC_MSG_ERROR([Cannot continue]) fi - # All "special" variants share the same output directory ("server") - VALID_MULTIPLE_JVM_VARIANTS="server client minimal zero" - UTIL_GET_NON_MATCHING_VALUES(INVALID_MULTIPLE_VARIANTS, $JVM_VARIANTS, \ - $VALID_MULTIPLE_JVM_VARIANTS) - if test "x$INVALID_MULTIPLE_VARIANTS" != x && \ - test "x$BUILDING_MULTIPLE_JVM_VARIANTS" = xtrue; then - AC_MSG_ERROR([You can only build multiple variants using these variants: '$VALID_MULTIPLE_JVM_VARIANTS']) - fi - # The "main" variant is the one used by other libs to link against during the # build. if test "x$BUILDING_MULTIPLE_JVM_VARIANTS" = "xtrue"; then diff --git a/make/hotspot/HotspotCommon.gmk b/make/hotspot/HotspotCommon.gmk index 2a371f1aad5..3aacdf30c4c 100644 --- a/make/hotspot/HotspotCommon.gmk +++ b/make/hotspot/HotspotCommon.gmk @@ -34,13 +34,7 @@ JVM_SUPPORT_DIR := $(JVM_VARIANT_OUTPUTDIR)/support DTRACE_SUPPORT_DIR := $(JVM_SUPPORT_DIR)/dtrace LIB_OUTPUTDIR := $(call FindLibDirForModule, java.base) -ifneq ($(filter client minimal zero, $(JVM_VARIANT)), ) - JVM_VARIANT_SUBDIR := $(JVM_VARIANT) -else - # Use 'server' as default target directory name for all other variants. - JVM_VARIANT_SUBDIR := server -endif -JVM_LIB_OUTPUTDIR := $(LIB_OUTPUTDIR)/$(JVM_VARIANT_SUBDIR) +JVM_LIB_OUTPUTDIR := $(LIB_OUTPUTDIR)/$(JVM_VARIANT) ################################################################################ diff --git a/make/modules/java.base/Copy.gmk b/make/modules/java.base/Copy.gmk index c32139a71e9..d61a2743172 100644 --- a/make/modules/java.base/Copy.gmk +++ b/make/modules/java.base/Copy.gmk @@ -95,16 +95,10 @@ ifeq ($(call And, $(call isTargetOs, windows) $(call isTargetCpu, x86)), true) endif DEFAULT_CFG_VARIANT ?= server -# Any variant other than server, client, minimal, or zero is represented as server in -# the cfg file. -VALID_CFG_VARIANTS := server client minimal zero -CFG_VARIANTS := $(filter $(VALID_CFG_VARIANTS), $(JVM_VARIANTS)) \ - $(if $(filter-out $(VALID_CFG_VARIANTS), $(JVM_VARIANTS)), server) - # Change the order to put the default variant first if present. ORDERED_CFG_VARIANTS := \ - $(if $(filter $(DEFAULT_CFG_VARIANT), $(CFG_VARIANTS)), $(DEFAULT_CFG_VARIANT)) \ - $(filter-out $(DEFAULT_CFG_VARIANT), $(CFG_VARIANTS)) + $(if $(filter $(DEFAULT_CFG_VARIANT), $(JVM_VARIANTS)), $(DEFAULT_CFG_VARIANT)) \ + $(filter-out $(DEFAULT_CFG_VARIANT), $(JVM_VARIANTS)) JVMCFG := $(LIB_DST_DIR)/jvm.cfg diff --git a/make/modules/java.base/Lib.gmk b/make/modules/java.base/Lib.gmk index 84a6edfaca6..eee488607f2 100644 --- a/make/modules/java.base/Lib.gmk +++ b/make/modules/java.base/Lib.gmk @@ -156,11 +156,8 @@ ifeq ($(call isTargetOsType, unix), true) TARGETS += $(LIB_OUTPUTDIR)/$1/$(call SHARED_LIBRARY,jsig) endef - # The subdir is the same as the variant for client, minimal or zero, for all - # others it's server. - VARIANT_SUBDIRS := $(filter client minimal zero, $(JVM_VARIANTS)) \ - $(if $(filter-out client minimal zero, $(JVM_VARIANTS)), server) - $(foreach v, $(VARIANT_SUBDIRS), $(eval $(call CreateSymlinks,$v))) + # The subdir is the same as the variant + $(foreach v, $(JVM_VARIANTS), $(eval $(call CreateSymlinks,$v))) endif ############################################################################ -- GitLab From 6642d2eb8b129a2291191647197c5b3333a32989 Mon Sep 17 00:00:00 2001 From: Thomas Stuefe Date: Tue, 21 Sep 2021 06:27:32 +0000 Subject: [PATCH 041/544] 8273783: Simplify Metaspace arena guard handling Reviewed-by: coleenp, lucy --- src/hotspot/share/memory/metaspace.cpp | 3 +- .../memory/metaspace/allocationGuard.hpp | 116 ------------------ .../share/memory/metaspace/metaspaceArena.cpp | 88 ++++++------- .../share/memory/metaspace/metaspaceArena.hpp | 24 ++++ .../memory/metaspace/metaspaceCommon.cpp | 7 -- .../memory/metaspace/metaspaceSettings.cpp | 5 - .../gtest/metaspace/test_allocationGuard.cpp | 7 +- .../gtest/metaspace/test_metaspace_misc.cpp | 3 +- .../metaspace/test_metaspacearena_stress.cpp | 5 +- 9 files changed, 79 insertions(+), 179 deletions(-) delete mode 100644 src/hotspot/share/memory/metaspace/allocationGuard.hpp diff --git a/src/hotspot/share/memory/metaspace.cpp b/src/hotspot/share/memory/metaspace.cpp index 2c42c013560..74b5d1a0b30 100644 --- a/src/hotspot/share/memory/metaspace.cpp +++ b/src/hotspot/share/memory/metaspace.cpp @@ -867,8 +867,7 @@ void Metaspace::post_initialize() { } size_t Metaspace::max_allocation_word_size() { - const size_t max_overhead_words = metaspace::get_raw_word_size_for_requested_word_size(1); - return metaspace::chunklevel::MAX_CHUNK_WORD_SIZE - max_overhead_words; + return metaspace::chunklevel::MAX_CHUNK_WORD_SIZE; } // This version of Metaspace::allocate does not throw OOM but simply returns NULL, and diff --git a/src/hotspot/share/memory/metaspace/allocationGuard.hpp b/src/hotspot/share/memory/metaspace/allocationGuard.hpp deleted file mode 100644 index 0125c23ed61..00000000000 --- a/src/hotspot/share/memory/metaspace/allocationGuard.hpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2020 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. - * - */ - -#ifndef SHARE_MEMORY_METASPACE_ALLOCATIONGUARD_HPP -#define SHARE_MEMORY_METASPACE_ALLOCATIONGUARD_HPP - -#include "memory/allocation.hpp" -#include "memory/metaspace/chunklevel.hpp" -#include "utilities/globalDefinitions.hpp" - -// In Debug builds, Metadata in Metaspace can be optionally guarded - enclosed in canaries - -// to detect memory overwriters. -// -// These canaries are periodically checked, e.g. when the Metaspace is purged in a context -// of a GC. - -// The canaries precede any allocated block... -// -// +---------------+ -// | 'METAMETA' | -// +---------------+ -// | block size | -// +---------------+ -// | block... | -// . . -// . . -// . . -// | | -// +---------------+ -// . . -// +---------------+ -// | 'METAMETA' | -// +---------------+ -// | block size | -// +---------------+ -// | block... | - -// ... and since the blocks are allocated via pointer bump and closely follow each other, -// one block's prefix is its predecessor's suffix, so apart from the last block all -// blocks have an overwriter canary on both ends. -// - -// Note: this feature is only available in debug, and is activated using -// -XX:+MetaspaceGuardAllocations. When active, it disables deallocation handling - since -// freeblock handling in the freeblock lists would get too complex - so one may run leaks -// in deallocation-heavy scenarios (e.g. lots of class redefinitions). -// - -namespace metaspace { - -#ifdef ASSERT - -struct Prefix { - static const uintx EyeCatcher = - NOT_LP64(0x77698465) LP64_ONLY(0x7769846577698465ULL); // "META" resp "METAMETA" - - const uintx _mark; - const size_t _word_size; // raw word size including prefix - // MetaWord payload [0]; // varsized (but unfortunately not all our compilers understand that) - - Prefix(size_t word_size) : - _mark(EyeCatcher), - _word_size(word_size) - {} - - MetaWord* payload() const { - return (MetaWord*)(this + 1); - } - - bool is_valid() const { - return _mark == EyeCatcher && _word_size > 0 && _word_size < chunklevel::MAX_CHUNK_WORD_SIZE; - } - -}; - -// The prefix structure must be aligned to MetaWord size. -STATIC_ASSERT((sizeof(Prefix) & WordAlignmentMask) == 0); - -inline size_t prefix_size() { - return sizeof(Prefix); -} - -// Given a pointer to a memory area, establish the prefix at the start of that area and -// return the starting pointer to the payload. -inline MetaWord* establish_prefix(MetaWord* p_raw, size_t raw_word_size) { - const Prefix* pp = new(p_raw)Prefix(raw_word_size); - return pp->payload(); -} - -#endif - -} // namespace metaspace - -#endif // SHARE_MEMORY_METASPACE_ALLOCATIONGUARD_HPP diff --git a/src/hotspot/share/memory/metaspace/metaspaceArena.cpp b/src/hotspot/share/memory/metaspace/metaspaceArena.cpp index ae058fe2fdf..7d9441956d7 100644 --- a/src/hotspot/share/memory/metaspace/metaspaceArena.cpp +++ b/src/hotspot/share/memory/metaspace/metaspaceArena.cpp @@ -26,7 +26,6 @@ #include "precompiled.hpp" #include "logging/log.hpp" #include "logging/logStream.hpp" -#include "memory/metaspace/allocationGuard.hpp" #include "memory/metaspace/chunkManager.hpp" #include "memory/metaspace/counters.hpp" #include "memory/metaspace/freeBlocks.hpp" @@ -123,6 +122,9 @@ MetaspaceArena::MetaspaceArena(ChunkManager* chunk_manager, const ArenaGrowthPol _fbl(NULL), _total_used_words_counter(total_used_words_counter), _name(name) +#ifdef ASSERT + , _first_fence(NULL) +#endif { UL(debug, ": born."); @@ -229,28 +231,56 @@ MetaWord* MetaspaceArena::allocate(size_t requested_word_size) { MetaWord* p = NULL; const size_t raw_word_size = get_raw_word_size_for_requested_word_size(requested_word_size); - // 1) Attempt to allocate from the free blocks list - // (Note: to reduce complexity, deallocation handling is disabled if allocation guards - // are enabled, see Settings::ergo_initialize()) + // Before bothering the arena proper, attempt to re-use a block from the free blocks list if (Settings::handle_deallocations() && _fbl != NULL && !_fbl->is_empty()) { p = _fbl->remove_block(raw_word_size); if (p != NULL) { DEBUG_ONLY(InternalStats::inc_num_allocs_from_deallocated_blocks();) UL2(trace, "taken from fbl (now: %d, " SIZE_FORMAT ").", _fbl->count(), _fbl->total_size()); - // Note: Space which is kept in the freeblock dictionary still counts as used as far - // as statistics go; therefore we skip the epilogue in this function to avoid double - // accounting. + // Note: free blocks in freeblock dictionary still count as "used" as far as statistics go; + // therefore we have no need to adjust any usage counters (see epilogue of allocate_inner()) + // and can just return here. return p; } } + // Primary allocation + p = allocate_inner(requested_word_size); + +#ifdef ASSERT + // Fence allocation + if (p != NULL && Settings::use_allocation_guard()) { + STATIC_ASSERT(is_aligned(sizeof(Fence), BytesPerWord)); + MetaWord* guard = allocate_inner(sizeof(Fence) / BytesPerWord); + if (guard != NULL) { + // Ignore allocation errors for the fence to keep coding simple. If this + // happens (e.g. because right at this time we hit the Metaspace GC threshold) + // we miss adding this one fence. Not a big deal. Note that his would + // be pretty rare. Chances are much higher the primary allocation above + // would have already failed). + Fence* f = new(guard) Fence(_first_fence); + _first_fence = f; + } + } +#endif // ASSERT + + return p; +} + +// Allocate from the arena proper, once dictionary allocations and fencing are sorted out. +MetaWord* MetaspaceArena::allocate_inner(size_t requested_word_size) { + + assert_lock_strong(lock()); + + const size_t raw_word_size = get_raw_word_size_for_requested_word_size(requested_word_size); + MetaWord* p = NULL; bool current_chunk_too_small = false; bool commit_failure = false; if (current_chunk() != NULL) { - // 2) Attempt to satisfy the allocation from the current chunk. + // Attempt to satisfy the allocation from the current chunk. // If the current chunk is too small to hold the requested size, attempt to enlarge it. // If that fails, retire the chunk. @@ -311,13 +341,6 @@ MetaWord* MetaspaceArena::allocate(size_t requested_word_size) { } } -#ifdef ASSERT - // When using allocation guards, establish a prefix. - if (p != NULL && Settings::use_allocation_guard()) { - p = establish_prefix(p, raw_word_size); - } -#endif - if (p == NULL) { InternalStats::inc_num_allocs_failed_limit(); } else { @@ -425,36 +448,15 @@ void MetaspaceArena::verify_locked() const { } } +void MetaspaceArena::Fence::verify() const { + assert(_eye1 == EyeCatcher && _eye2 == EyeCatcher, + "Metaspace corruption: fence block at " PTR_FORMAT " broken.", p2i(this)); +} + void MetaspaceArena::verify_allocation_guards() const { assert(Settings::use_allocation_guard(), "Don't call with guards disabled."); - - // Verify canaries of all allocations. - // (We can walk all allocations since at the start of a chunk an allocation - // must be present, and the allocation header contains its size, so we can - // find the next one). - for (const Metachunk* c = _chunks.first(); c != NULL; c = c->next()) { - const Prefix* first_broken_block = NULL; - int num_broken_blocks = 0; - const MetaWord* p = c->base(); - while (p < c->top()) { - const Prefix* pp = (const Prefix*)p; - if (!pp->is_valid()) { - UL2(error, "Corrupt block at " PTR_FORMAT " (chunk: " METACHUNK_FORMAT ").", - p2i(pp), METACHUNK_FORMAT_ARGS(c)); - if (first_broken_block == NULL) { - first_broken_block = pp; - } - num_broken_blocks ++; - } - p += pp->_word_size; - } - // After examining all blocks in a chunk, assert if any of those blocks - // was found to be corrupted. - if (first_broken_block != NULL) { - assert(false, "Corrupt block: found at least %d corrupt metaspace block(s) - " - "first corrupted block at " PTR_FORMAT ".", - num_broken_blocks, p2i(first_broken_block)); - } + for (const Fence* f = _first_fence; f != NULL; f = f->next()) { + f->verify(); } } diff --git a/src/hotspot/share/memory/metaspace/metaspaceArena.hpp b/src/hotspot/share/memory/metaspace/metaspaceArena.hpp index 1edbc8997b9..0093e7d15fa 100644 --- a/src/hotspot/share/memory/metaspace/metaspaceArena.hpp +++ b/src/hotspot/share/memory/metaspace/metaspaceArena.hpp @@ -107,6 +107,27 @@ class MetaspaceArena : public CHeapObj { // A name for purely debugging/logging purposes. const char* const _name; +#ifdef ASSERT + // Allocation guards: When active, arena allocations are interleaved with + // fence allocations. An overwritten fence indicates a buffer overrun in either + // the preceding or the following user block. All fences are linked together; + // validating the fences just means walking that linked list. + // Note that for the Arena, fence blocks are just another form of user blocks. + class Fence { + static const uintx EyeCatcher = + NOT_LP64(0x77698465) LP64_ONLY(0x7769846577698465ULL); // "META" resp "METAMETA" + // Two eyecatchers to easily spot a corrupted _next pointer + const uintx _eye1; + const Fence* const _next; + const uintx _eye2; + public: + Fence(const Fence* next) : _eye1(EyeCatcher), _next(next), _eye2(EyeCatcher) {} + const Fence* next() const { return _next; } + void verify() const; + }; + const Fence* _first_fence; +#endif // ASSERT + Mutex* lock() const { return _lock; } ChunkManager* chunk_manager() const { return _chunk_manager; } @@ -138,6 +159,9 @@ class MetaspaceArena : public CHeapObj { // from this arena. DEBUG_ONLY(bool is_valid_area(MetaWord* p, size_t word_size) const;) + // Allocate from the arena proper, once dictionary allocations and fencing are sorted out. + MetaWord* allocate_inner(size_t word_size); + public: MetaspaceArena(ChunkManager* chunk_manager, const ArenaGrowthPolicy* growth_policy, diff --git a/src/hotspot/share/memory/metaspace/metaspaceCommon.cpp b/src/hotspot/share/memory/metaspace/metaspaceCommon.cpp index 61d364b7e33..00c9bb640ff 100644 --- a/src/hotspot/share/memory/metaspace/metaspaceCommon.cpp +++ b/src/hotspot/share/memory/metaspace/metaspaceCommon.cpp @@ -24,7 +24,6 @@ */ #include "precompiled.hpp" -#include "memory/metaspace/allocationGuard.hpp" #include "memory/metaspace/freeBlocks.hpp" #include "memory/metaspace/metaspaceCommon.hpp" #include "memory/metaspace/metaspaceSettings.hpp" @@ -182,12 +181,6 @@ size_t get_raw_word_size_for_requested_word_size(size_t word_size) { // Metaspace allocations are aligned to word size. byte_size = align_up(byte_size, AllocationAlignmentByteSize); - // If we guard allocations, we need additional space for a prefix. -#ifdef ASSERT - if (Settings::use_allocation_guard()) { - byte_size += align_up(prefix_size(), AllocationAlignmentByteSize); - } -#endif size_t raw_word_size = byte_size / BytesPerWord; assert(raw_word_size * BytesPerWord == byte_size, "Sanity"); return raw_word_size; diff --git a/src/hotspot/share/memory/metaspace/metaspaceSettings.cpp b/src/hotspot/share/memory/metaspace/metaspaceSettings.cpp index ffc8630e9be..c8b80b78ac0 100644 --- a/src/hotspot/share/memory/metaspace/metaspaceSettings.cpp +++ b/src/hotspot/share/memory/metaspace/metaspaceSettings.cpp @@ -84,11 +84,6 @@ void Settings::ergo_initialize() { // Deallocations can be manually switched off to aid error analysis, since this removes one layer of complexity // from allocation. _handle_deallocations = MetaspaceHandleDeallocations; - - // We also switch it off automatically if we use allocation guards. This is to keep prefix handling in MetaspaceArena simple. - if (_use_allocation_guard) { - _handle_deallocations = false; - } #endif LogStream ls(Log(metaspace)::info()); Settings::print_on(&ls); diff --git a/test/hotspot/gtest/metaspace/test_allocationGuard.cpp b/test/hotspot/gtest/metaspace/test_allocationGuard.cpp index 76eca074002..9b0eb3d69a5 100644 --- a/test/hotspot/gtest/metaspace/test_allocationGuard.cpp +++ b/test/hotspot/gtest/metaspace/test_allocationGuard.cpp @@ -44,13 +44,13 @@ using metaspace::Settings; // Note: We use TEST_VM_ASSERT_MSG. However, an assert is only triggered if allocation // guards are enabled; if guards are disabled for the gtests, this test would fail. // So for that case, we trigger a fake assert. -TEST_VM_ASSERT_MSG(metaspace, test_overwriter, ".*failed: Corrupt block") { +TEST_VM_ASSERT_MSG(metaspace, test_overwriter, ".*Metaspace corruption.*") { if (Settings::use_allocation_guard()) { MetaspaceGtestContext context; MetaspaceTestArena* arena = context.create_arena(Metaspace::StandardMetaspaceType); // We allocate two blocks. We then write over the end of the first block, which - // should corrupt the eyecatcher at the start of the second block. + // should corrupt the fence between the two blocks. // Note: there is of course no guarantee that blocks allocated sequentially are neighbors; // but in this case (clean standard-sized test arena and very small allocations) it can // be safely assumed). @@ -59,10 +59,9 @@ TEST_VM_ASSERT_MSG(metaspace, test_overwriter, ".*failed: Corrupt block") { p1[8] = (MetaWord)0x9345; // Overwriter // Now we delete the arena (as happens during class unloading); this will check all // block canaries and should trigger an assert (see MetaspaceArena::verify_allocation_guards()). - tty->print_cr("Death test, please ignore the following \"Corrupt block\" printout."); delete arena; } else { - assert(false, "Corrupt block fake message to satisfy tests"); + assert(false, "Metaspace corruption - please ignore this, fake message to satisfy tests"); } } diff --git a/test/hotspot/gtest/metaspace/test_metaspace_misc.cpp b/test/hotspot/gtest/metaspace/test_metaspace_misc.cpp index e749c84c88e..dba19bd60ab 100644 --- a/test/hotspot/gtest/metaspace/test_metaspace_misc.cpp +++ b/test/hotspot/gtest/metaspace/test_metaspace_misc.cpp @@ -55,11 +55,12 @@ TEST_VM(metaspace, misc_sizes) { TEST_VM(metaspace, misc_max_alloc_size) { - // Make sure we can allocate what we promise to allocate + // Make sure we can allocate what we promise to allocate... const size_t sz = Metaspace::max_allocation_word_size(); ClassLoaderData* cld = ClassLoaderData::the_null_class_loader_data(); MetaWord* p = cld->metaspace_non_null()->allocate(sz, Metaspace::NonClassType); ASSERT_NOT_NULL(p); + // And also, successfully deallocate it. cld->metaspace_non_null()->deallocate(p, sz, false); } diff --git a/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp b/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp index 17839b44080..373e9e8d874 100644 --- a/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp +++ b/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp @@ -28,6 +28,7 @@ #include "memory/metaspace/counters.hpp" #include "memory/metaspace/metaspaceArena.hpp" #include "memory/metaspace/metaspaceArenaGrowthPolicy.hpp" +#include "memory/metaspace/metaspaceSettings.hpp" #include "memory/metaspace/metaspaceStatistics.hpp" #include "runtime/mutexLocker.hpp" #include "utilities/debug.hpp" @@ -111,13 +112,15 @@ class MetaspaceArenaTestBed : public CHeapObj { // - alignment/padding of allocations // - inside used counter contains blocks in free list // - free block list splinter threshold + // - if +MetaspaceGuardAllocations, guard costs // Since what we deallocated may have been given back to us in a following allocation, // we only know fore sure we allocated what we did not give back. const size_t at_least_allocated = _alloc_count.total_size() - _dealloc_count.total_size(); // At most we allocated this: - const size_t max_word_overhead_per_alloc = 4; + const size_t max_word_overhead_per_alloc = + 4 + (metaspace::Settings::use_allocation_guard() ? 4 : 0); const size_t at_most_allocated = _alloc_count.total_size() + max_word_overhead_per_alloc * _alloc_count.count(); ASSERT_LE(at_least_allocated, in_use_stats._used_words - stats._free_blocks_word_size); -- GitLab From c60bcd09b73f6ad176bbd73fe3c1a09545609353 Mon Sep 17 00:00:00 2001 From: Stefan Karlsson Date: Tue, 21 Sep 2021 07:42:36 +0000 Subject: [PATCH 042/544] 8273928: Use named run ids when problem listing tests Reviewed-by: pliden, kbarrett, dholmes --- test/hotspot/jtreg/ProblemList-zgc.txt | 12 +++++----- test/hotspot/jtreg/ProblemList.txt | 22 +++++++++---------- .../gcbarriers/UnsafeIntrinsicsTest.java | 4 ++-- .../TestRangeCheckPredicatesControl.java | 2 +- .../vectorapi/VectorRebracket128Test.java | 2 +- ...ferenceClearDuringReferenceProcessing.java | 17 ++++++++++++-- .../TestStringDeduplicationAgeThreshold.java | 10 ++++----- .../TestStringDeduplicationFullGC.java | 10 ++++----- .../TestStringDeduplicationInterned.java | 10 ++++----- .../TestStringDeduplicationPrintOptions.java | 10 ++++----- .../TestStringDeduplicationTableResize.java | 10 ++++----- .../TestStringDeduplicationYoungGC.java | 10 ++++----- .../jtreg/runtime/os/TestTracePageSizes.java | 6 ++--- .../dcmd/gc/HeapDumpCompressedTest.java | 13 +++++------ .../jtreg/serviceability/sa/ClhsdbFindPC.java | 8 +++---- .../jtreg/serviceability/sa/ClhsdbPmap.java | 4 ++-- .../jtreg/serviceability/sa/ClhsdbPstack.java | 4 ++-- 17 files changed, 83 insertions(+), 71 deletions(-) diff --git a/test/hotspot/jtreg/ProblemList-zgc.txt b/test/hotspot/jtreg/ProblemList-zgc.txt index 0a96a797d41..1032c144e59 100644 --- a/test/hotspot/jtreg/ProblemList-zgc.txt +++ b/test/hotspot/jtreg/ProblemList-zgc.txt @@ -34,13 +34,13 @@ serviceability/sa/CDSJMapClstats.java 8220624 generic- serviceability/sa/ClhsdbJhisto.java 8220624 generic-all serviceability/sa/ClhsdbCDSCore.java 8268722 macosx-x64 -serviceability/sa/ClhsdbFindPC.java#id1 8268722 macosx-x64 -serviceability/sa/ClhsdbFindPC.java#id3 8268722 macosx-x64 -serviceability/sa/ClhsdbPmap.java#id1 8268722 macosx-x64 -serviceability/sa/ClhsdbPstack.java#id1 8268722 macosx-x64 +serviceability/sa/ClhsdbFindPC.java#xcomp-core 8268722 macosx-x64 +serviceability/sa/ClhsdbFindPC.java#no-xcomp-core 8268722 macosx-x64 +serviceability/sa/ClhsdbPmap.java#core 8268722 macosx-x64 +serviceability/sa/ClhsdbPstack.java#core 8268722 macosx-x64 serviceability/sa/TestJmapCore.java 8268722,8268283,8270202 macosx-x64,linux-aarch64,linux-x64 serviceability/sa/TestJmapCoreMetaspace.java 8268722,8268636 generic-all serviceability/sa/TestJhsdbJstackMixed.java 8248912 generic-all -serviceability/sa/ClhsdbPstack.java#id0 8248912 generic-all -serviceability/sa/ClhsdbPstack.java#id1 8248912 generic-all +serviceability/sa/ClhsdbPstack.java#process 8248912 generic-all +serviceability/sa/ClhsdbPstack.java#core 8248912 generic-all diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index ad4a6d771d1..088f7a08104 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -85,11 +85,11 @@ gc/stress/gclocker/TestGCLockerWithParallel.java 8180622 generic-all gc/stress/gclocker/TestGCLockerWithG1.java 8180622 generic-all gc/stress/TestJNIBlockFullGC/TestJNIBlockFullGC.java 8192647 generic-all gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java 8241293 macosx-x64 -gc/stringdedup/TestStringDeduplicationAgeThreshold.java#id4 8273695 generic-all -gc/stringdedup/TestStringDeduplicationPrintOptions.java#id4 8273695 generic-all -gc/stringdedup/TestStringDeduplicationInterned.java#id4 8273695 generic-all -gc/stringdedup/TestStringDeduplicationTableResize.java#id4 8273695 generic-all -gc/stringdedup/TestStringDeduplicationYoungGC.java#id4 8273695 generic-all +gc/stringdedup/TestStringDeduplicationAgeThreshold.java#Z 8273695 generic-all +gc/stringdedup/TestStringDeduplicationPrintOptions.java#Z 8273695 generic-all +gc/stringdedup/TestStringDeduplicationInterned.java#Z 8273695 generic-all +gc/stringdedup/TestStringDeduplicationTableResize.java#Z 8273695 generic-all +gc/stringdedup/TestStringDeduplicationYoungGC.java#Z 8273695 generic-all ############################################################################# @@ -104,9 +104,9 @@ runtime/jni/terminatedThread/TestTerminatedThread.java 8219652 aix-ppc64 runtime/os/TestTracePageSizes.java#no-options 8267460 linux-aarch64 runtime/os/TestTracePageSizes.java#explicit-large-page-size 8267460 linux-aarch64 runtime/os/TestTracePageSizes.java#compiler-options 8267460 linux-aarch64 -runtime/os/TestTracePageSizes.java#with-G1 8267460 linux-aarch64 -runtime/os/TestTracePageSizes.java#with-Parallel 8267460 linux-aarch64 -runtime/os/TestTracePageSizes.java#with-Serial 8267460 linux-aarch64 +runtime/os/TestTracePageSizes.java#G1 8267460 linux-aarch64 +runtime/os/TestTracePageSizes.java#Parallel 8267460 linux-aarch64 +runtime/os/TestTracePageSizes.java#Serial 8267460 linux-aarch64 applications/jcstress/copy.java 8229852 linux-x64 @@ -121,9 +121,9 @@ serviceability/jvmti/ModuleAwareAgents/ThreadStart/MAAThreadStart.java 8225354 w serviceability/dcmd/gc/RunFinalizationTest.java 8227120 linux-all,windows-x64 serviceability/sa/ClhsdbCDSCore.java 8269982 macosx-aarch64 -serviceability/sa/ClhsdbFindPC.java#id1 8269982 macosx-aarch64 -serviceability/sa/ClhsdbFindPC.java#id3 8269982 macosx-aarch64 -serviceability/sa/ClhsdbPstack.java#id1 8269982 macosx-aarch64 +serviceability/sa/ClhsdbFindPC.java#xcomp-core 8269982 macosx-aarch64 +serviceability/sa/ClhsdbFindPC.java#no-xcomp-core 8269982 macosx-aarch64 +serviceability/sa/ClhsdbPstack.java#core 8269982 macosx-aarch64 ############################################################################# diff --git a/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java b/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java index f6d57905381..b96e5ce54de 100644 --- a/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java +++ b/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java @@ -22,7 +22,7 @@ */ /* - * @test id=z + * @test id=Z * @key randomness * @bug 8059022 * @modules java.base/jdk.internal.misc:+open @@ -38,7 +38,7 @@ */ /* - * @test id=shenandoah + * @test id=Shenandoah * @key randomness * @bug 8255401 8251944 * @modules java.base/jdk.internal.misc:+open diff --git a/test/hotspot/jtreg/compiler/loopopts/TestRangeCheckPredicatesControl.java b/test/hotspot/jtreg/compiler/loopopts/TestRangeCheckPredicatesControl.java index 3d41d64cf32..1f64ed28d8a 100644 --- a/test/hotspot/jtreg/compiler/loopopts/TestRangeCheckPredicatesControl.java +++ b/test/hotspot/jtreg/compiler/loopopts/TestRangeCheckPredicatesControl.java @@ -22,7 +22,7 @@ */ /* - * @test + * @test id=Z * @key stress randomness * @requires vm.gc.Z * @bug 8237859 diff --git a/test/hotspot/jtreg/compiler/vectorapi/VectorRebracket128Test.java b/test/hotspot/jtreg/compiler/vectorapi/VectorRebracket128Test.java index 6b266db08b6..fc18b08656c 100644 --- a/test/hotspot/jtreg/compiler/vectorapi/VectorRebracket128Test.java +++ b/test/hotspot/jtreg/compiler/vectorapi/VectorRebracket128Test.java @@ -38,7 +38,7 @@ import jdk.incubator.vector.VectorSpecies; import jdk.internal.vm.annotation.ForceInline; /* - * @test + * @test id=Z * @bug 8260473 * @requires vm.gc.Z * @modules jdk.incubator.vector diff --git a/test/hotspot/jtreg/gc/TestReferenceClearDuringReferenceProcessing.java b/test/hotspot/jtreg/gc/TestReferenceClearDuringReferenceProcessing.java index 183a22fc115..771daa19e9c 100644 --- a/test/hotspot/jtreg/gc/TestReferenceClearDuringReferenceProcessing.java +++ b/test/hotspot/jtreg/gc/TestReferenceClearDuringReferenceProcessing.java @@ -23,9 +23,22 @@ package gc; -/* @test +/* @test id=Shenandoah * @bug 8256517 - * @requires vm.gc.Z | vm.gc.Shenandoah + * @requires vm.gc.Shenandoah + * @requires vm.gc != "null" + * @library /test/lib + * @build sun.hotspot.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox + * @run main/othervm + * -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * gc.TestReferenceClearDuringReferenceProcessing + */ + +/* @test id=Z + * @bug 8256517 + * @requires vm.gc.Z * @requires vm.gc != "null" * @library /test/lib * @build sun.hotspot.WhiteBox diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationAgeThreshold.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationAgeThreshold.java index 6034b9b0ecf..090a49aa80b 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationAgeThreshold.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationAgeThreshold.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationAgeThreshold + * @test id=Serial * @summary Test string deduplication age threshold * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationAgeThreshold + * @test id=G1 * @summary Test string deduplication age threshold * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationAgeThreshold + * @test id=Parallel * @summary Test string deduplication age threshold * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationAgeThreshold + * @test id=Shenandoah * @summary Test string deduplication age threshold * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationAgeThreshold + * @test id=Z * @summary Test string deduplication age threshold * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationFullGC.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationFullGC.java index 724e69f8137..7105be7d478 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationFullGC.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationFullGC.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationFullGC + * @test id=Serial * @summary Test string deduplication during full GC * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationFullGC + * @test id=G1 * @summary Test string deduplication during full GC * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationFullGC + * @test id=Parallel * @summary Test string deduplication during full GC * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationFullGC + * @test id=Shenandoah * @summary Test string deduplication during full GC * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationFullGC + * @test id=Z * @summary Test string deduplication during full GC * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationInterned.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationInterned.java index 46749e2a69d..124bf9d5cf9 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationInterned.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationInterned.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationInterned + * @test id=Serial * @summary Test string deduplication of interned strings * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationInterned + * @test id=G1 * @summary Test string deduplication of interned strings * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationInterned + * @test id=Parallel * @summary Test string deduplication of interned strings * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationInterned + * @test id=Shenandoah * @summary Test string deduplication of interned strings * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationInterned + * @test id=Z * @summary Test string deduplication of interned strings * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationPrintOptions.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationPrintOptions.java index 95480700f90..0659bc5aea3 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationPrintOptions.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationPrintOptions.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationPrintOptions + * @test id=Serial * @summary Test string deduplication print options * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationPrintOptions + * @test id=G1 * @summary Test string deduplication print options * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationPrintOptions + * @test id=Parallel * @summary Test string deduplication print options * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationPrintOptions + * @test id=Shenandoah * @summary Test string deduplication print options * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationPrintOptions + * @test id=Z * @summary Test string deduplication print options * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTableResize.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTableResize.java index e3227aec448..d82244ef07a 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTableResize.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTableResize.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationTableResize + * @test id=Serial * @summary Test string deduplication table resize * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationTableResize + * @test id=G1 * @summary Test string deduplication table resize * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationTableResize + * @test id=Parallel * @summary Test string deduplication table resize * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationTableResize + * @test id=Shenandoah * @summary Test string deduplication table resize * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationTableResize + * @test id=Z * @summary Test string deduplication table resize * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationYoungGC.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationYoungGC.java index cb6aaf2cc61..053dc0a2862 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationYoungGC.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationYoungGC.java @@ -24,7 +24,7 @@ package gc.stringdedup; /* - * @test TestStringDeduplicationYoungGC + * @test id=Serial * @summary Test string deduplication during young GC * @bug 8029075 * @requires vm.gc.Serial @@ -37,7 +37,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationYoungGC + * @test id=G1 * @summary Test string deduplication during young GC * @bug 8029075 * @requires vm.gc.G1 @@ -50,7 +50,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationYoungGC + * @test id=Parallel * @summary Test string deduplication during young GC * @bug 8029075 * @requires vm.gc.Parallel @@ -63,7 +63,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationYoungGC + * @test id=Shenandoah * @summary Test string deduplication during young GC * @bug 8029075 * @requires vm.gc.Shenandoah @@ -76,7 +76,7 @@ package gc.stringdedup; */ /* - * @test TestStringDeduplicationYoungGC + * @test id=Z * @summary Test string deduplication during young GC * @bug 8029075 * @requires vm.gc.Z diff --git a/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java b/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java index 3275e4337e1..7bc07d1c9c3 100644 --- a/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java +++ b/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java @@ -58,7 +58,7 @@ */ /* - * @test id=with-G1 + * @test id=G1 * @summary Run tests with G1 * @library /test/lib * @build jdk.test.lib.Platform @@ -70,7 +70,7 @@ */ /* - * @test id=with-Parallel + * @test id=Parallel * @summary Run tests with Parallel * @library /test/lib * @build jdk.test.lib.Platform @@ -82,7 +82,7 @@ */ /* - * @test id=with-Serial + * @test id=Serial * @summary Run tests with Serial * @library /test/lib * @build jdk.test.lib.Platform diff --git a/test/hotspot/jtreg/serviceability/dcmd/gc/HeapDumpCompressedTest.java b/test/hotspot/jtreg/serviceability/dcmd/gc/HeapDumpCompressedTest.java index cb0a19a65b2..95b3fa67d2c 100644 --- a/test/hotspot/jtreg/serviceability/dcmd/gc/HeapDumpCompressedTest.java +++ b/test/hotspot/jtreg/serviceability/dcmd/gc/HeapDumpCompressedTest.java @@ -35,7 +35,7 @@ import jdk.test.lib.dcmd.PidJcmdExecutor; import jdk.test.lib.process.OutputAnalyzer; /* - * @test + * @test id=Serial * @requires vm.gc.Serial * @summary Test of diagnostic command GC.heap_dump with gzipped output (Serial GC) * @library /test/lib @@ -47,7 +47,7 @@ import jdk.test.lib.process.OutputAnalyzer; */ /* - * @test + * @test id=Parallel * @requires vm.gc.Parallel * @summary Test of diagnostic command GC.heap_dump with gzipped output (Parallel GC) * @library /test/lib @@ -59,7 +59,7 @@ import jdk.test.lib.process.OutputAnalyzer; */ /* - * @test + * @test id=G1 * @requires vm.gc.G1 * @summary Test of diagnostic command GC.heap_dump with gzipped output (G1 GC) * @library /test/lib @@ -71,7 +71,7 @@ import jdk.test.lib.process.OutputAnalyzer; */ /* - * @test + * @test id=Z * @requires vm.gc.Z * @summary Test of diagnostic command GC.heap_dump with gzipped output (Z GC) * @library /test/lib @@ -83,7 +83,7 @@ import jdk.test.lib.process.OutputAnalyzer; */ /* - * @test + * @test id=Shenandoah * @requires vm.gc.Shenandoah * @summary Test of diagnostic command GC.heap_dump with gzipped output (Shenandoah GC) * @library /test/lib @@ -95,7 +95,7 @@ import jdk.test.lib.process.OutputAnalyzer; */ /* - * @test + * @test id=Epsilon * @requires vm.gc.Epsilon * @summary Test of diagnostic command GC.heap_dump with gzipped output (Epsilon GC) * @library /test/lib @@ -159,4 +159,3 @@ public class HeapDumpCompressedTest { } } } - diff --git a/test/hotspot/jtreg/serviceability/sa/ClhsdbFindPC.java b/test/hotspot/jtreg/serviceability/sa/ClhsdbFindPC.java index fc4022f5d80..9990cca9a81 100644 --- a/test/hotspot/jtreg/serviceability/sa/ClhsdbFindPC.java +++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbFindPC.java @@ -32,7 +32,7 @@ import jdk.test.lib.util.CoreUtils; import jtreg.SkippedException; /** - * @test + * @test id=xcomp-process * @bug 8193124 * @summary Test the clhsdb 'findpc' command with Xcomp on live process * @requires vm.hasSA @@ -43,7 +43,7 @@ import jtreg.SkippedException; */ /** - * @test + * @test id=xcomp-core * @bug 8193124 * @summary Test the clhsdb 'findpc' command with Xcomp on core file * @requires vm.compMode != "Xcomp" @@ -54,7 +54,7 @@ import jtreg.SkippedException; */ /** - * @test + * @test id=no-xcomp-process * @bug 8193124 * @summary Test the clhsdb 'findpc' command w/o Xcomp on live process * @requires vm.hasSA @@ -65,7 +65,7 @@ import jtreg.SkippedException; */ /** - * @test + * @test id=no-xcomp-core * @bug 8193124 * @summary Test the clhsdb 'findpc' command w/o Xcomp on core file * @requires vm.compMode != "Xcomp" diff --git a/test/hotspot/jtreg/serviceability/sa/ClhsdbPmap.java b/test/hotspot/jtreg/serviceability/sa/ClhsdbPmap.java index 6f0023a21e9..cf1fdc78d95 100644 --- a/test/hotspot/jtreg/serviceability/sa/ClhsdbPmap.java +++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbPmap.java @@ -31,7 +31,7 @@ import jdk.test.lib.Platform; import jtreg.SkippedException; /** - * @test + * @test id=process * @bug 8190198 * @summary Test clhsdb pmap command on a live process * @requires vm.hasSA @@ -40,7 +40,7 @@ import jtreg.SkippedException; */ /** - * @test + * @test id=core * @bug 8190198 * @summary Test clhsdb pmap command on a core file * @requires vm.hasSA diff --git a/test/hotspot/jtreg/serviceability/sa/ClhsdbPstack.java b/test/hotspot/jtreg/serviceability/sa/ClhsdbPstack.java index e4101a8c372..43b2b90e0fa 100644 --- a/test/hotspot/jtreg/serviceability/sa/ClhsdbPstack.java +++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbPstack.java @@ -31,7 +31,7 @@ import jdk.test.lib.Platform; import jtreg.SkippedException; /** - * @test + * @test id=process * @bug 8190198 * @summary Test clhsdb pstack command on a live process * @requires vm.hasSA @@ -40,7 +40,7 @@ import jtreg.SkippedException; */ /** - * @test + * @test id=core * @bug 8190198 * @summary Test clhsdb pstack command on a core file * @requires vm.hasSA -- GitLab From 65ed0a742e65fe7e661e8da2adea6cd41992869e Mon Sep 17 00:00:00 2001 From: Julia Boes Date: Tue, 21 Sep 2021 08:07:25 +0000 Subject: [PATCH 043/544] 8273655: content-types.properties files are missing some common types Reviewed-by: bpb, dfuchs --- .../sun/net/www/content-types.properties | 88 ++++++++++++++++++- .../sun/net/www/content-types.properties | 86 +++++++++++++++++- .../file/Files/probeContentType/Basic.java | 74 ++++++++++------ 3 files changed, 214 insertions(+), 34 deletions(-) diff --git a/src/java.base/unix/classes/sun/net/www/content-types.properties b/src/java.base/unix/classes/sun/net/www/content-types.properties index c02dfa632b0..27e4f4004d9 100644 --- a/src/java.base/unix/classes/sun/net/www/content-types.properties +++ b/src/java.base/unix/classes/sun/net/www/content-types.properties @@ -27,7 +27,7 @@ temp.file.template: /tmp/%s # application/octet-stream: \ description=Generic Binary Stream;\ - file_extensions=.saveme,.dump,.hqx,.arc,.o,.a,.bin,.exe,.z,.gz + file_extensions=.saveme,.dump,.hqx,.arc,.o,.a,.bin,.exe,.z application/oda: \ description=ODA Document;\ @@ -253,14 +253,26 @@ image/bmp: \ description=Bitmap Image;\ file_extensions=.bmp; +image/webp: \ + description=WEBP image;\ + file_extensions=.webp; + +text/css: \ + description=CSS File;\ + file_extensions=.css; + text/html: \ description=HTML Document;\ file_extensions=.htm,.html;\ icon=html +text/javascript: \ + description=JavaScript File;\ + file_extensions=.js; + text/plain: \ description=Plain Text;\ - file_extensions=.text,.c,.cc,.c++,.h,.pl,.txt,.java,.el;\ + file_extensions=.text,.c,.cc,.c++,.h,.pl,.txt,.java,.el,.php,.adoc,.py;\ icon=text;\ action=browser @@ -272,6 +284,14 @@ text/x-setext: \ description=Structure Enhanced Text;\ file_extensions=.etx +text/csv: \ + description=CSV File;\ + file_extensions=.csv; + +text/markdown: \ + description=Markdown File;\ + file_extensions=.md,.markdown + video/mp4: \ description=MPEG-4 Video;\ file_extensions=.m4v,.mp4 @@ -311,3 +331,67 @@ message/rfc822: \ application/xml: \ description=XML document;\ file_extensions=.xml + +application/rtf: \ + description=WordPad Document;\ + file_extensions=.rtf; + +application/gzip: \ + description=GZip File;\ + file_extensions=.gz; + +application/vnd.oasis.opendocument.presentation: \ + description=OpenDocument presentation document;\ + file_extensions=.odp; + +application/vnd.oasis.opendocument.spreadsheet: \ + description=OpenDocument spreadsheet document;\ + file_extensions=.ods; + +application/vnd.oasis.opendocument.text: \ + description=OpenDocument text document;\ + file_extensions=.odt; + +application/vnd.ms-excel: \ + description=Microsoft Excel File;\ + file_extensions=.xls; + +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: \ + description=XLSX File;\ + file_extensions=.xlsx; + +application/vnd.openxmlformats-officedocument.presentationml.presentation: \ + description=PPTX File;\ + file_extensions=.pptx; + +application/vnd.ms-powerpoint: \ + description=Microsoft PowerPoint File;\ + file_extensions=.ppt; + +application/x-7z-compressed: \ + description=7-Zip File;\ + file_extensions=.7z; + +application/msword: \ + description=Microsoft Word File;\ + file_extensions=.doc; + +application/vnd.openxmlformats-officedocument.wordprocessingml.document: \ + description=DOCX File;\ + file_extensions=.docx; + +application/vnd.rar: \ + description=RAR File;\ + file_extensions=.rar; + +application/json: \ + description=JSON File;\ + file_extensions=.json; + +application/bz2: \ + description=BZ2 File;\ + file_extensions=.bz2; + +application/java-archive: \ + description=JAR File;\ + file_extensions=.jar; diff --git a/src/java.base/windows/classes/sun/net/www/content-types.properties b/src/java.base/windows/classes/sun/net/www/content-types.properties index 34e8286a3c5..9e27d3d1af5 100644 --- a/src/java.base/windows/classes/sun/net/www/content-types.properties +++ b/src/java.base/windows/classes/sun/net/www/content-types.properties @@ -27,7 +27,7 @@ temp.file.template: c:\\temp\\%s # application/octet-stream: \ description=Generic Binary Stream;\ - file_extensions=.saveme,.dump,.hqx,.arc,.obj,.lib,.bin,.exe,.zip,.gz + file_extensions=.saveme,.dump,.hqx,.arc,.obj,.lib,.bin,.exe application/oda: \ description=ODA Document;\ @@ -43,11 +43,15 @@ application/postscript: \ icon=ps application/rtf: \ - description=Wordpad Document;\ + description=WordPad Document;\ file_extensions=.rtf;\ action=application;\ application=wordpad.exe %s +application/gzip: \ + description=GZip File;\ + file_extensions=.gz; + application/x-dvi: \ description=TeX DVI File;\ file_extensions=.dvi @@ -250,14 +254,26 @@ image/bmp: \ description=Bitmap Image;\ file_extensions=.bmp; +image/webp: \ + description=WEBP image;\ + file_extensions=.webp; + +text/css: \ + description=CSS File;\ + file_extensions=.css; + text/html: \ description=HTML Document;\ file_extensions=.htm,.html;\ icon=html +text/javascript: \ + description=JavaScript File;\ + file_extensions=.js; + text/plain: \ description=Plain Text;\ - file_extensions=.text,.c,.cc,.c++,.h,.pl,.txt,.java,.el;\ + file_extensions=.text,.c,.cc,.c++,.h,.pl,.txt,.java,.el,.php,.adoc,.py;\ icon=text;\ action=browser @@ -269,6 +285,14 @@ text/x-setext: \ description=Structure Enhanced Text;\ file_extensions=.etx +text/csv: \ + description=CSV File;\ + file_extensions=.csv; + +text/markdown: \ + description=Markdown File;\ + file_extensions=.md,.markdown + video/mp4: \ description=MPEG-4 Video;\ file_extensions=.m4v,.mp4 @@ -308,3 +332,59 @@ message/rfc822: \ application/xml: \ description=XML document;\ file_extensions=.xml + +application/vnd.oasis.opendocument.presentation: \ + description=OpenDocument presentation document;\ + file_extensions=.odp; + +application/vnd.oasis.opendocument.spreadsheet: \ + description=OpenDocument spreadsheet document;\ + file_extensions=.ods; + +application/vnd.oasis.opendocument.text: \ + description=OpenDocument text document;\ + file_extensions=.odt; + +application/vnd.ms-excel: \ + description=Microsoft Excel File;\ + file_extensions=.xls; + +application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: \ + description=XLSX File;\ + file_extensions=.xlsx; + +application/vnd.openxmlformats-officedocument.presentationml.presentation: \ + description=PPTX File;\ + file_extensions=.pptx; + +application/vnd.ms-powerpoint: \ + description=Microsoft PowerPoint File;\ + file_extensions=.ppt; + +application/x-7z-compressed: \ + description=7-Zip File;\ + file_extensions=.7z; + +application/msword: \ + description=Microsoft Word File;\ + file_extensions=.doc; + +application/vnd.openxmlformats-officedocument.wordprocessingml.document: \ + description=DOCX File;\ + file_extensions=.docx; + +application/vnd.rar: \ + description=RAR File;\ + file_extensions=.rar; + +application/json: \ + description=JSON File;\ + file_extensions=.json; + +application/bz2: \ + description=BZ2 File;\ + file_extensions=.bz2; + +application/java-archive: \ + description=JAR File;\ + file_extensions=.jar; diff --git a/test/jdk/java/nio/file/Files/probeContentType/Basic.java b/test/jdk/java/nio/file/Files/probeContentType/Basic.java index 3bb7862948d..c4870369a2d 100644 --- a/test/jdk/java/nio/file/Files/probeContentType/Basic.java +++ b/test/jdk/java/nio/file/Files/probeContentType/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* @test - * @bug 4313887 8129632 8129633 8162624 8146215 8162745 + * @bug 4313887 8129632 8129633 8162624 8146215 8162745 8273655 * @summary Unit test for probeContentType method * @library ../.. * @build Basic SimpleFileTypeDetector @@ -31,6 +31,7 @@ import java.io.*; import java.nio.file.*; +import java.util.List; import java.util.stream.Stream; /** @@ -95,16 +96,12 @@ public class Basic { return 0; } - static int checkContentTypes(String[] extensions, String[] expectedTypes) + static int checkContentTypes(ExType[] exTypes) throws IOException { - if (extensions.length != expectedTypes.length) { - System.err.println("Parameter array lengths differ"); - return 1; - } - int failures = 0; - for (int i = 0; i < extensions.length; i++) { - String extension = extensions[i]; + for (int i = 0; i < exTypes.length; i++) { + String extension = exTypes[i].extension(); + List expectedTypes = exTypes[i].expectedTypes(); Path file = Files.createTempFile("foo", "." + extension); try { String type = Files.probeContentType(file); @@ -112,9 +109,9 @@ public class Basic { System.err.println("Content type of " + extension + " cannot be determined"); failures++; - } else if (!type.equals(expectedTypes[i])) { + } else if (!expectedTypes.contains(type)) { System.err.printf("Content type: %s; expected: %s%n", - type, expectedTypes[i]); + type, expectedTypes); failures++; } } finally { @@ -155,27 +152,46 @@ public class Basic { Files.delete(file); } - // Verify that certain media extensions are mapped to the correct type. - String[] extensions = new String[]{ - "jpg", - "mp3", - "mp4", - "pdf", - "png", - "webm" + // Verify that certain extensions are mapped to the correct type. + var exTypes = new ExType[] { + new ExType("adoc", List.of("text/plain")), + new ExType("bz2", List.of("application/bz2", "application/x-bzip2")), + new ExType("css", List.of("text/css")), + new ExType("csv", List.of("text/csv")), + new ExType("doc", List.of("application/msword")), + new ExType("docx", List.of("application/vnd.openxmlformats-officedocument.wordprocessingml.document")), + new ExType("gz", List.of("application/gzip", "application/x-gzip")), + new ExType("jar", List.of("application/java-archive", "application/x-java-archive")), + new ExType("jpg", List.of("image/jpeg")), + new ExType("js", List.of("text/javascript", "application/javascript")), + new ExType("json", List.of("application/json")), + new ExType("markdown", List.of("text/markdown")), + new ExType("md", List.of("text/markdown")), + new ExType("mp3", List.of("audio/mpeg")), + new ExType("mp4", List.of("video/mp4")), + new ExType("odp", List.of("application/vnd.oasis.opendocument.presentation")), + new ExType("ods", List.of("application/vnd.oasis.opendocument.spreadsheet")), + new ExType("odt", List.of("application/vnd.oasis.opendocument.text")), + new ExType("pdf", List.of("application/pdf")), + new ExType("php", List.of("text/plain", "text/php")), + new ExType("png", List.of("image/png")), + new ExType("ppt", List.of("application/vnd.ms-powerpoint")), + new ExType("pptx",List.of("application/vnd.openxmlformats-officedocument.presentationml.presentation")), + new ExType("py", List.of("text/plain", "text/x-python-script")), + new ExType("rar", List.of("application/vnd.rar")), + new ExType("rtf", List.of("application/rtf", "text/rtf")), + new ExType("webm", List.of("video/webm")), + new ExType("webp", List.of("image/webp")), + new ExType("xls", List.of("application/vnd.ms-excel")), + new ExType("xlsx", List.of("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")), + new ExType("7z", List.of("application/x-7z-compressed")), }; - String[] expectedTypes = new String[] { - "image/jpeg", - "audio/mpeg", - "video/mp4", - "application/pdf", - "image/png", - "video/webm" - }; - failures += checkContentTypes(extensions, expectedTypes); + failures += checkContentTypes(exTypes); if (failures > 0) { throw new RuntimeException("Test failed!"); } } + + record ExType(String extension, List expectedTypes) { } } -- GitLab From a5108a605e6a1e427d90dbeeb8630a3d01d6b405 Mon Sep 17 00:00:00 2001 From: Thejasvi Voniadka Date: Tue, 21 Sep 2021 09:01:09 +0000 Subject: [PATCH 044/544] 8273646: Add openssl from path variable also in to Default System Openssl Path in OpensslArtifactFetcher Reviewed-by: weijun --- test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java b/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java index d70f187301e..55ff8c9ef98 100644 --- a/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java +++ b/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java @@ -82,8 +82,8 @@ public class OpensslArtifactFetcher { } private static String getDefaultSystemOpensslPath(String version) { - if (verifyOpensslVersion("/usr/bin/openssl", version)) { - return "/usr/bin/openssl"; + if (verifyOpensslVersion("openssl", version)) { + return "openssl"; } else if (verifyOpensslVersion("/usr/local/bin/openssl", version)) { return "/usr/local/bin/openssl"; } -- GitLab From afd218d39a3125fcea50968edef6e6cfbacfff50 Mon Sep 17 00:00:00 2001 From: Thomas Schatzl Date: Tue, 21 Sep 2021 09:20:21 +0000 Subject: [PATCH 045/544] 8274053: [BACKOUT] JDK-8270842: G1: Only young regions need to redirty outside references in remset. Reviewed-by: sjohanss --- src/hotspot/share/gc/g1/g1EvacFailure.cpp | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1EvacFailure.cpp b/src/hotspot/share/gc/g1/g1EvacFailure.cpp index bb711c3b17d..b7b564abe49 100644 --- a/src/hotspot/share/gc/g1/g1EvacFailure.cpp +++ b/src/hotspot/share/gc/g1/g1EvacFailure.cpp @@ -81,7 +81,6 @@ class RemoveSelfForwardPtrObjClosure: public ObjectClosure { G1CollectedHeap* _g1h; G1ConcurrentMark* _cm; HeapRegion* _hr; - const bool _is_young; size_t _marked_bytes; UpdateLogBuffersDeferred* _log_buffer_cl; bool _during_concurrent_start; @@ -96,7 +95,6 @@ public: _g1h(G1CollectedHeap::heap()), _cm(_g1h->concurrent_mark()), _hr(hr), - _is_young(hr->is_young()), _marked_bytes(0), _log_buffer_cl(log_buffer_cl), _during_concurrent_start(during_concurrent_start), @@ -143,14 +141,19 @@ public: _marked_bytes += (obj_size * HeapWordSize); PreservedMarks::init_forwarded_mark(obj); - // During evacuation failure we do not record inter-region - // references referencing regions that need a remembered set - // update originating from young regions (including eden) that - // failed evacuation. Make up for that omission now by rescanning - // these failed objects. - if (_is_young) { - obj->oop_iterate(_log_buffer_cl); - } + // While we were processing RSet buffers during the collection, + // we actually didn't scan any cards on the collection set, + // since we didn't want to update remembered sets with entries + // that point into the collection set, given that live objects + // from the collection set are about to move and such entries + // will be stale very soon. + // This change also dealt with a reliability issue which + // involved scanning a card in the collection set and coming + // across an array that was being chunked and looking malformed. + // The problem is that, if evacuation fails, we might have + // remembered set entries missing given that we skipped cards on + // the collection set. So, we'll recreate such entries now. + obj->oop_iterate(_log_buffer_cl); HeapWord* obj_end = obj_addr + obj_size; _last_forwarded_object_end = obj_end; -- GitLab From 7acec3f161234b99da76193781296157b98d689c Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Tue, 21 Sep 2021 11:26:28 +0000 Subject: [PATCH 046/544] 8236505: Mark jdk/editpad/EditPadTest.java as @headful Reviewed-by: jlahoda --- test/jdk/jdk/editpad/EditPadTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/test/jdk/jdk/editpad/EditPadTest.java b/test/jdk/jdk/editpad/EditPadTest.java index 8565a0046ce..d784b98db1c 100644 --- a/test/jdk/jdk/editpad/EditPadTest.java +++ b/test/jdk/jdk/editpad/EditPadTest.java @@ -23,6 +23,7 @@ /* * @test + * @key headful * @bug 8167636 8167639 8168972 * @summary Testing built-in editor. * @modules java.desktop/java.awt -- GitLab From 111d5e1a9324cb5e8d98627f6329d17fcbc9c13d Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Tue, 21 Sep 2021 11:37:49 +0000 Subject: [PATCH 047/544] 8273915: Create 'nosafepoint' rank Reviewed-by: dholmes, iklam --- .../share/classfile/classLoaderData.cpp | 2 +- src/hotspot/share/gc/g1/g1ServiceThread.cpp | 4 +- .../share/gc/parallel/psCompactionManager.cpp | 2 +- .../share/gc/shared/taskTerminator.cpp | 2 +- src/hotspot/share/gc/shared/workgroup.cpp | 2 +- .../share/gc/z/zMessagePort.inline.hpp | 4 +- src/hotspot/share/gc/z/zMetronome.cpp | 2 +- src/hotspot/share/memory/heapInspection.hpp | 2 +- .../share/memory/metaspace/testHelpers.cpp | 2 +- src/hotspot/share/prims/jvmtiTagMap.cpp | 2 +- src/hotspot/share/runtime/handshake.cpp | 2 +- src/hotspot/share/runtime/mutex.cpp | 19 +++--- src/hotspot/share/runtime/mutex.hpp | 11 ++-- src/hotspot/share/runtime/mutexLocker.cpp | 58 +++++++++---------- src/hotspot/share/runtime/vmOperations.cpp | 2 +- src/hotspot/share/runtime/vmThread.cpp | 2 +- .../share/services/heapDumperCompression.cpp | 2 +- src/hotspot/share/services/memoryManager.cpp | 2 +- .../utilities/concurrentHashTable.inline.hpp | 2 +- .../gtest/metaspace/test_is_metaspace_obj.cpp | 2 +- .../gtest/metaspace/test_metaspacearena.cpp | 2 +- .../metaspace/test_metaspacearena_stress.cpp | 2 +- test/hotspot/gtest/runtime/test_mutex.cpp | 30 ++++++---- .../gtest/runtime/test_safepoint_locks.cpp | 4 +- .../gtest/utilities/test_filterQueue.cpp | 2 +- 25 files changed, 90 insertions(+), 76 deletions(-) diff --git a/src/hotspot/share/classfile/classLoaderData.cpp b/src/hotspot/share/classfile/classLoaderData.cpp index 87a6f27544a..67fa8602df0 100644 --- a/src/hotspot/share/classfile/classLoaderData.cpp +++ b/src/hotspot/share/classfile/classLoaderData.cpp @@ -133,7 +133,7 @@ void ClassLoaderData::initialize_name(Handle class_loader) { ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool has_class_mirror_holder) : _metaspace(NULL), - _metaspace_lock(new Mutex(Mutex::leaf-2, "MetaspaceAllocation_lock", + _metaspace_lock(new Mutex(Mutex::nosafepoint-2, "MetaspaceAllocation_lock", Mutex::_safepoint_check_never)), _unloading(false), _has_class_mirror_holder(has_class_mirror_holder), _modified_oops(true), diff --git a/src/hotspot/share/gc/g1/g1ServiceThread.cpp b/src/hotspot/share/gc/g1/g1ServiceThread.cpp index 0a8b7f94cc0..9945c17513c 100644 --- a/src/hotspot/share/gc/g1/g1ServiceThread.cpp +++ b/src/hotspot/share/gc/g1/g1ServiceThread.cpp @@ -40,8 +40,8 @@ void G1SentinelTask::execute() { G1ServiceThread::G1ServiceThread() : ConcurrentGCThread(), - _monitor(Mutex::leaf, - "G1ServiceThread monitor", + _monitor(Mutex::nosafepoint, + "G1ServiceThread_lock", Monitor::_safepoint_check_never), _task_queue() { set_name("G1 Service"); diff --git a/src/hotspot/share/gc/parallel/psCompactionManager.cpp b/src/hotspot/share/gc/parallel/psCompactionManager.cpp index 3ea3c4a9c10..883a0053610 100644 --- a/src/hotspot/share/gc/parallel/psCompactionManager.cpp +++ b/src/hotspot/share/gc/parallel/psCompactionManager.cpp @@ -92,7 +92,7 @@ void ParCompactionManager::initialize(ParMarkBitMap* mbm) { _shadow_region_array = new (ResourceObj::C_HEAP, mtGC) GrowableArray(10, mtGC); - _shadow_region_monitor = new Monitor(Mutex::barrier, "CompactionManager monitor", + _shadow_region_monitor = new Monitor(Mutex::nosafepoint, "CompactionManager_lock", Monitor::_safepoint_check_never); } diff --git a/src/hotspot/share/gc/shared/taskTerminator.cpp b/src/hotspot/share/gc/shared/taskTerminator.cpp index 59dd67c2230..a3f9c8f8f80 100644 --- a/src/hotspot/share/gc/shared/taskTerminator.cpp +++ b/src/hotspot/share/gc/shared/taskTerminator.cpp @@ -72,7 +72,7 @@ TaskTerminator::TaskTerminator(uint n_threads, TaskQueueSetSuper* queue_set) : _n_threads(n_threads), _queue_set(queue_set), _offered_termination(0), - _blocker(Mutex::leaf, "TaskTerminator", Monitor::_safepoint_check_never), + _blocker(Mutex::nosafepoint, "TaskTerminator_lock", Monitor::_safepoint_check_never), _spin_master(NULL) { } TaskTerminator::~TaskTerminator() { diff --git a/src/hotspot/share/gc/shared/workgroup.cpp b/src/hotspot/share/gc/shared/workgroup.cpp index 9e66026e99c..c09108c719d 100644 --- a/src/hotspot/share/gc/shared/workgroup.cpp +++ b/src/hotspot/share/gc/shared/workgroup.cpp @@ -245,7 +245,7 @@ void GangWorker::loop() { // *** WorkGangBarrierSync WorkGangBarrierSync::WorkGangBarrierSync() - : _monitor(Mutex::safepoint, "work gang barrier sync", + : _monitor(Mutex::nosafepoint, "WorkGangBarrierSync_lock", Monitor::_safepoint_check_never), _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) { } diff --git a/src/hotspot/share/gc/z/zMessagePort.inline.hpp b/src/hotspot/share/gc/z/zMessagePort.inline.hpp index 91f161684f4..fd036ebc983 100644 --- a/src/hotspot/share/gc/z/zMessagePort.inline.hpp +++ b/src/hotspot/share/gc/z/zMessagePort.inline.hpp @@ -66,8 +66,8 @@ public: template inline ZMessagePort::ZMessagePort() : - _monitor(Monitor::leaf, - "ZMessagePort", + _monitor(Monitor::nosafepoint, + "ZMessagePort_lock", Monitor::_safepoint_check_never), _has_message(false), _seqnum(0), diff --git a/src/hotspot/share/gc/z/zMetronome.cpp b/src/hotspot/share/gc/z/zMetronome.cpp index ff5f3749913..93753377065 100644 --- a/src/hotspot/share/gc/z/zMetronome.cpp +++ b/src/hotspot/share/gc/z/zMetronome.cpp @@ -28,7 +28,7 @@ #include "utilities/ticks.hpp" ZMetronome::ZMetronome(uint64_t hz) : - _monitor(Monitor::leaf, "ZMetronome", Monitor::_safepoint_check_never), + _monitor(Monitor::nosafepoint, "ZMetronome_lock", Monitor::_safepoint_check_never), _interval_ms(MILLIUNITS / hz), _start_ms(0), _nticks(0), diff --git a/src/hotspot/share/memory/heapInspection.hpp b/src/hotspot/share/memory/heapInspection.hpp index fad84cce59b..b7017f2c4ae 100644 --- a/src/hotspot/share/memory/heapInspection.hpp +++ b/src/hotspot/share/memory/heapInspection.hpp @@ -245,7 +245,7 @@ class ParHeapInspectTask : public AbstractGangTask { _filter(filter), _missed_count(0), _success(true), - _mutex(Mutex::leaf, "ParHeapInspectTask_lock", Mutex::_safepoint_check_never) {} + _mutex(Mutex::nosafepoint, "ParHeapInspectTask_lock", Mutex::_safepoint_check_never) {} uintx missed_count() const { return _missed_count; diff --git a/src/hotspot/share/memory/metaspace/testHelpers.cpp b/src/hotspot/share/memory/metaspace/testHelpers.cpp index 73554807b7d..c1527c18192 100644 --- a/src/hotspot/share/memory/metaspace/testHelpers.cpp +++ b/src/hotspot/share/memory/metaspace/testHelpers.cpp @@ -92,7 +92,7 @@ MetaspaceTestContext::~MetaspaceTestContext() { // Create an arena, feeding off this area. MetaspaceTestArena* MetaspaceTestContext::create_arena(Metaspace::MetaspaceType type) { const ArenaGrowthPolicy* growth_policy = ArenaGrowthPolicy::policy_for_space_type(type, false); - Mutex* lock = new Mutex(Monitor::leaf, "MetaspaceTestArea-lock", Monitor::_safepoint_check_never); + Mutex* lock = new Mutex(Monitor::nosafepoint, "MetaspaceTestArea_lock", Monitor::_safepoint_check_never); MetaspaceArena* arena = NULL; { MutexLocker ml(lock, Mutex::_no_safepoint_check_flag); diff --git a/src/hotspot/share/prims/jvmtiTagMap.cpp b/src/hotspot/share/prims/jvmtiTagMap.cpp index 95a9375e110..5ffefc0d36e 100644 --- a/src/hotspot/share/prims/jvmtiTagMap.cpp +++ b/src/hotspot/share/prims/jvmtiTagMap.cpp @@ -72,7 +72,7 @@ bool JvmtiTagMap::_has_object_free_events = false; // create a JvmtiTagMap JvmtiTagMap::JvmtiTagMap(JvmtiEnv* env) : _env(env), - _lock(Mutex::leaf, "JvmtiTagMap_lock", Mutex::_safepoint_check_never), + _lock(Mutex::nosafepoint, "JvmtiTagMap_lock", Mutex::_safepoint_check_never), _needs_rehashing(false), _needs_cleaning(false) { diff --git a/src/hotspot/share/runtime/handshake.cpp b/src/hotspot/share/runtime/handshake.cpp index e2a951397ef..044ba38ae94 100644 --- a/src/hotspot/share/runtime/handshake.cpp +++ b/src/hotspot/share/runtime/handshake.cpp @@ -408,7 +408,7 @@ void Handshake::execute(AsyncHandshakeClosure* hs_cl, JavaThread* target) { HandshakeState::HandshakeState(JavaThread* target) : _handshakee(target), _queue(), - _lock(Monitor::leaf, "HandshakeState", Monitor::_safepoint_check_never), + _lock(Monitor::nosafepoint, "HandshakeState_lock", Monitor::_safepoint_check_never), _active_handshaker(), _suspended(false), _async_suspend_handshake(false) diff --git a/src/hotspot/share/runtime/mutex.cpp b/src/hotspot/share/runtime/mutex.cpp index e8bedb89f84..98f56a3c18b 100644 --- a/src/hotspot/share/runtime/mutex.cpp +++ b/src/hotspot/share/runtime/mutex.cpp @@ -98,7 +98,7 @@ void Mutex::lock_contended(Thread* self) { // Is it a JavaThread participating in the safepoint protocol. if (is_active_Java_thread) { InFlightMutexRelease ifmr(this); - assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex"); + assert(rank() > Mutex::nosafepoint, "Potential deadlock with nosafepoint or lesser rank mutex"); { ThreadBlockInVMPreprocess tbivmdc(JavaThread::cast(self), ifmr); _lock.lock(); @@ -285,11 +285,11 @@ Mutex::Mutex(int Rank, const char * name, SafepointCheckRequired safepoint_check _safepoint_check_required = safepoint_check_required; _skip_rank_check = false; - assert(_rank < nonleaf || _safepoint_check_required == _safepoint_check_always, - "higher than nonleaf should safepoint %s", name); + assert(_rank > nosafepoint || _safepoint_check_required == _safepoint_check_never, + "Locks below nosafepoint rank should never safepoint: %s", name); - assert(_rank > special || _safepoint_check_required == _safepoint_check_never, - "Special locks or below should never safepoint: %s", name); + assert(_rank <= nosafepoint || _safepoint_check_required == _safepoint_check_always, + "Locks above nosafepoint rank should safepoint: %s", name); // The allow_vm_block also includes allowing other non-Java threads to block or // allowing Java threads to block in native. @@ -384,13 +384,14 @@ void Mutex::check_rank(Thread* thread) { if (owned_by_self()) { // wait() case Mutex* least = get_least_ranked_lock_besides_this(locks_owned); - // We enforce not holding locks of rank special or lower while waiting. + // We enforce not holding locks of rank nosafepoint or lower while waiting. // Also "this" should be the monitor with lowest rank owned by this thread. - if (least != NULL && (least->rank() <= special || least->rank() <= this->rank())) { + if (least != NULL && (least->rank() <= nosafepoint || least->rank() <= this->rank())) { assert(false, "Attempting to wait on monitor %s/%d while holding lock %s/%d -- " "possible deadlock. %s", name(), rank(), least->name(), least->rank(), - least->rank() <= this->rank() ? "Should wait on the least ranked monitor from " - "all owned locks." : "Should not block(wait) while holding a lock of rank special."); + least->rank() <= this->rank() ? + "Should wait on the least ranked monitor from all owned locks." : + "Should not block(wait) while holding a lock of rank nosafepoint or below."); } } else { // lock()/lock_without_safepoint_check()/try_lock() case diff --git a/src/hotspot/share/runtime/mutex.hpp b/src/hotspot/share/runtime/mutex.hpp index fc7f84608fd..f8aafbeb174 100644 --- a/src/hotspot/share/runtime/mutex.hpp +++ b/src/hotspot/share/runtime/mutex.hpp @@ -39,20 +39,23 @@ // The underlying PlatformMutex may support recursive locking but this is not exposed // and we account for that possibility in try_lock. +// A thread is not allowed to safepoint while holding a mutex whose rank +// is nosafepoint or lower. + class Mutex : public CHeapObj { public: // Special low level locks are given names and ranges avoid overlap. - enum lock_types { + enum Rank { event, service = event + 6, stackwatermark = service + 3, tty = stackwatermark + 3, special = tty + 3, oopstorage = special + 3, - leaf = oopstorage + 10, - safepoint = leaf + 10, - barrier = safepoint + 1, + nosafepoint = oopstorage + 6, + leaf = nosafepoint + 6, + barrier = leaf + 10, nonleaf = barrier + 1, max_nonleaf = nonleaf + 900 }; diff --git a/src/hotspot/share/runtime/mutexLocker.cpp b/src/hotspot/share/runtime/mutexLocker.cpp index 8be340cb689..497c514b4a1 100644 --- a/src/hotspot/share/runtime/mutexLocker.cpp +++ b/src/hotspot/share/runtime/mutexLocker.cpp @@ -204,33 +204,33 @@ void assert_locked_or_safepoint_or_handshake(const Mutex* lock, const JavaThread void mutex_init() { def(tty_lock , PaddedMutex , tty, true, _safepoint_check_never); // allow to lock in VM - def(STS_lock , PaddedMonitor, leaf, true, _safepoint_check_never); + def(STS_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); if (UseG1GC) { - def(CGC_lock , PaddedMonitor, leaf, true, _safepoint_check_never); + def(CGC_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); def(G1OldGCCount_lock , PaddedMonitor, leaf, true, _safepoint_check_always); - def(G1DetachedRefinementStats_lock, PaddedMutex, leaf-2, true, _safepoint_check_never); + def(G1DetachedRefinementStats_lock, PaddedMutex, nosafepoint-2, true, _safepoint_check_never); def(FreeList_lock , PaddedMutex , service-1, true, _safepoint_check_never); - def(OldSets_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(OldSets_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(Uncommit_lock , PaddedMutex , service-2, true, _safepoint_check_never); - def(RootRegionScan_lock , PaddedMonitor, leaf-1, true, _safepoint_check_never); + def(RootRegionScan_lock , PaddedMonitor, nosafepoint-1, true, _safepoint_check_never); - def(MarkStackFreeList_lock , PaddedMutex , leaf , true, _safepoint_check_never); - def(MarkStackChunkList_lock , PaddedMutex , leaf , true, _safepoint_check_never); + def(MarkStackFreeList_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); + def(MarkStackChunkList_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(MonitoringSupport_lock , PaddedMutex , service-1, true, _safepoint_check_never); // used for serviceability monitoring support } - def(StringDedup_lock , PaddedMonitor, leaf, true, _safepoint_check_never); - def(StringDedupIntern_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(StringDedup_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); + def(StringDedupIntern_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(ParGCRareEvent_lock , PaddedMutex , leaf, true, _safepoint_check_always); def(CodeCache_lock , PaddedMonitor, special, true, _safepoint_check_never); def(CodeSweeper_lock , PaddedMonitor, special-2, true, _safepoint_check_never); def(RawMonitor_lock , PaddedMutex , special, true, _safepoint_check_never); def(OopMapCacheAlloc_lock , PaddedMutex , leaf, true, _safepoint_check_always); // used for oop_map_cache allocation. - def(Metaspace_lock , PaddedMutex , leaf-3, true, _safepoint_check_never); + def(Metaspace_lock , PaddedMutex , nosafepoint-3, true, _safepoint_check_never); def(ClassLoaderDataGraph_lock , PaddedMutex , nonleaf, false, _safepoint_check_always); def(Patching_lock , PaddedMutex , special, true, _safepoint_check_never); // used for safepointing and code patching. @@ -250,12 +250,12 @@ void mutex_init() { def(SharedDictionary_lock , PaddedMutex , leaf, true, _safepoint_check_always); def(ClassInitError_lock , PaddedMonitor, leaf+1, true, _safepoint_check_always); def(Module_lock , PaddedMutex , leaf+2, false, _safepoint_check_always); - def(InlineCacheBuffer_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(InlineCacheBuffer_lock , PaddedMutex , nosafepoint-1, true, _safepoint_check_never); def(VMStatistic_lock , PaddedMutex , leaf, false, _safepoint_check_always); def(ExpandHeap_lock , PaddedMutex , leaf, true, _safepoint_check_always); // Used during compilation by VM thread - def(JNIHandleBlockFreeList_lock , PaddedMutex , leaf-1, true, _safepoint_check_never); // handles are used by VM thread + def(JNIHandleBlockFreeList_lock , PaddedMutex , nosafepoint-1, true, _safepoint_check_never); // handles are used by VM thread def(SignatureHandlerLibrary_lock , PaddedMutex , leaf, false, _safepoint_check_always); - def(SymbolArena_lock , PaddedMutex , leaf+2, true, _safepoint_check_never); + def(SymbolArena_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(ExceptionCache_lock , PaddedMutex , leaf, false, _safepoint_check_always); #ifndef PRODUCT def(FullGCALot_lock , PaddedMutex , leaf, false, _safepoint_check_always); // a lock to make FullGCALot MT safe @@ -265,14 +265,14 @@ void mutex_init() { def(PerfDataManager_lock , PaddedMutex , leaf, true, _safepoint_check_always); // used for synchronized access to PerfDataManager resources def(Threads_lock , PaddedMonitor, barrier, true, _safepoint_check_always); // Used for safepoint protocol. - def(NonJavaThreadsList_lock , PaddedMutex, leaf-1, true, _safepoint_check_never); - def(NonJavaThreadsListSync_lock , PaddedMutex, leaf, true, _safepoint_check_never); + def(NonJavaThreadsList_lock , PaddedMutex, nosafepoint-1, true, _safepoint_check_never); + def(NonJavaThreadsListSync_lock , PaddedMutex, nosafepoint, true, _safepoint_check_never); def(VMOperation_lock , PaddedMonitor, nonleaf, true, _safepoint_check_always); // VM_thread allowed to block on these def(RetData_lock , PaddedMutex , nonleaf, false, _safepoint_check_always); def(Terminator_lock , PaddedMonitor, nonleaf, true, _safepoint_check_always); - def(InitCompleted_lock , PaddedMonitor, leaf, true, _safepoint_check_never); - def(VtableStubs_lock , PaddedMutex , leaf-2, true, _safepoint_check_never); + def(InitCompleted_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); + def(VtableStubs_lock , PaddedMutex , nosafepoint-2, true, _safepoint_check_never); def(Notify_lock , PaddedMonitor, nonleaf, true, _safepoint_check_always); def(JNICritical_lock , PaddedMonitor, nonleaf, true, _safepoint_check_always); // used for JNI critical regions def(AdapterHandlerLibrary_lock , PaddedMutex , nonleaf, true, _safepoint_check_always); @@ -280,14 +280,14 @@ void mutex_init() { def(Heap_lock , PaddedMonitor, nonleaf+1, false, _safepoint_check_always); // Doesn't safepoint check during termination. def(JfieldIdCreation_lock , PaddedMutex , nonleaf+1, true, _safepoint_check_always); // jfieldID, Used in VM_Operation - def(CompiledIC_lock , PaddedMutex , leaf+2, true, _safepoint_check_never); // locks VtableStubs_lock, InlineCacheBuffer_lock + def(CompiledIC_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); // locks VtableStubs_lock, InlineCacheBuffer_lock def(CompileTaskAlloc_lock , PaddedMutex , nonleaf+2, true, _safepoint_check_always); def(CompileStatistics_lock , PaddedMutex , nonleaf+2, false, _safepoint_check_always); def(DirectivesStack_lock , PaddedMutex , special, true, _safepoint_check_never); def(MultiArray_lock , PaddedMutex , nonleaf+2, false, _safepoint_check_always); def(JvmtiThreadState_lock , PaddedMutex , nonleaf+2, false, _safepoint_check_always); // Used by JvmtiThreadState/JvmtiEventController - def(EscapeBarrier_lock , PaddedMonitor, leaf, true, _safepoint_check_never); // Used to synchronize object reallocation/relocking triggered by JVMTI + def(EscapeBarrier_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); // Used to synchronize object reallocation/relocking triggered by JVMTI def(Management_lock , PaddedMutex , nonleaf+2, false, _safepoint_check_always); // used for JVM management def(ConcurrentGCBreakpoints_lock , PaddedMonitor, nonleaf, true, _safepoint_check_always); @@ -300,17 +300,17 @@ void mutex_init() { def(PeriodicTask_lock , PaddedMonitor, nonleaf+5, true, _safepoint_check_always); def(RedefineClasses_lock , PaddedMonitor, nonleaf+5, true, _safepoint_check_always); def(Verify_lock , PaddedMutex, nonleaf+5, true, _safepoint_check_always); - def(Zip_lock , PaddedMonitor, leaf-2, true, _safepoint_check_never); + def(Zip_lock , PaddedMonitor, nosafepoint-2, true, _safepoint_check_never); if (WhiteBoxAPI) { - def(Compilation_lock , PaddedMonitor, leaf, true, _safepoint_check_never); + def(Compilation_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); } #if INCLUDE_JFR def(JfrMsg_lock , PaddedMonitor, leaf, true, _safepoint_check_always); - def(JfrBuffer_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(JfrBuffer_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(JfrStacktrace_lock , PaddedMutex , stackwatermark-1, true, _safepoint_check_never); - def(JfrThreadSampler_lock , PaddedMonitor, leaf, true, _safepoint_check_never); + def(JfrThreadSampler_lock , PaddedMonitor, nosafepoint, true, _safepoint_check_never); #endif #ifndef SUPPORTS_NATIVE_CX8 @@ -322,7 +322,7 @@ void mutex_init() { def(ThreadsSMRDelete_lock , PaddedMonitor, special, true, _safepoint_check_never); def(ThreadIdTableCreate_lock , PaddedMutex , leaf, false, _safepoint_check_always); def(SharedDecoder_lock , PaddedMutex , tty-1, true, _safepoint_check_never); - def(DCmdFactory_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(DCmdFactory_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); #if INCLUDE_NMT def(NMTQuery_lock , PaddedMutex , max_nonleaf, false, _safepoint_check_always); #endif @@ -330,13 +330,13 @@ void mutex_init() { #if INCLUDE_JVMTI def(CDSClassFileStream_lock , PaddedMutex , max_nonleaf, false, _safepoint_check_always); #endif - def(DumpTimeTable_lock , PaddedMutex , leaf-1, true, _safepoint_check_never); - def(CDSLambda_lock , PaddedMutex , leaf, true, _safepoint_check_never); - def(DumpRegion_lock , PaddedMutex , leaf, true, _safepoint_check_never); - def(ClassListFile_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(DumpTimeTable_lock , PaddedMutex , nosafepoint-1, true, _safepoint_check_never); + def(CDSLambda_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); + def(DumpRegion_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); + def(ClassListFile_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); def(LambdaFormInvokers_lock , PaddedMutex , nonleaf+2, false, _safepoint_check_always); #endif // INCLUDE_CDS - def(Bootclasspath_lock , PaddedMutex , leaf, true, _safepoint_check_never); + def(Bootclasspath_lock , PaddedMutex , nosafepoint, true, _safepoint_check_never); #if INCLUDE_JVMCI def(JVMCI_lock , PaddedMonitor, nonleaf+2, true, _safepoint_check_always); diff --git a/src/hotspot/share/runtime/vmOperations.cpp b/src/hotspot/share/runtime/vmOperations.cpp index a6d42120582..ed728f1a1da 100644 --- a/src/hotspot/share/runtime/vmOperations.cpp +++ b/src/hotspot/share/runtime/vmOperations.cpp @@ -368,7 +368,7 @@ int VM_Exit::wait_for_threads_in_native_to_block() { assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint already"); Thread * thr_cur = Thread::current(); - Monitor timer(Mutex::leaf, "VM_Exit timer", Monitor::_safepoint_check_never); + Monitor timer(Mutex::nosafepoint, "VM_ExitTimer_lock", Monitor::_safepoint_check_never); // Compiler threads need longer wait because they can access VM data directly // while in native. If they are active and some structures being used are diff --git a/src/hotspot/share/runtime/vmThread.cpp b/src/hotspot/share/runtime/vmThread.cpp index 48906c8c90c..63341d8a8ab 100644 --- a/src/hotspot/share/runtime/vmThread.cpp +++ b/src/hotspot/share/runtime/vmThread.cpp @@ -128,7 +128,7 @@ void VMThread::create() { assert(_timeout_task == NULL, "sanity"); } - _terminate_lock = new Monitor(Mutex::safepoint, "VMThread::_terminate_lock", + _terminate_lock = new Monitor(Mutex::nosafepoint, "VMThreadTerminate_lock", Monitor::_safepoint_check_never); if (UsePerfData) { diff --git a/src/hotspot/share/services/heapDumperCompression.cpp b/src/hotspot/share/services/heapDumperCompression.cpp index ec33264b889..b9c456a8ecf 100644 --- a/src/hotspot/share/services/heapDumperCompression.cpp +++ b/src/hotspot/share/services/heapDumperCompression.cpp @@ -200,7 +200,7 @@ CompressionBackend::CompressionBackend(AbstractWriter* writer, _written(0), _writer(writer), _compressor(compressor), - _lock(new (std::nothrow) PaddedMonitor(Mutex::leaf, "HProf Compression Backend", + _lock(new (std::nothrow) PaddedMonitor(Mutex::nosafepoint, "HProfCompressionBackend_lock", Mutex::_safepoint_check_never)) { if (_writer == NULL) { set_error("Could not allocate writer"); diff --git a/src/hotspot/share/services/memoryManager.cpp b/src/hotspot/share/services/memoryManager.cpp index 690393deb78..30a14f77745 100644 --- a/src/hotspot/share/services/memoryManager.cpp +++ b/src/hotspot/share/services/memoryManager.cpp @@ -174,7 +174,7 @@ GCMemoryManager::GCMemoryManager(const char* name, const char* gc_end_message) : MemoryManager(name), _gc_end_message(gc_end_message) { _num_collections = 0; _last_gc_stat = NULL; - _last_gc_lock = new Mutex(Mutex::leaf, "_last_gc_lock", + _last_gc_lock = new Mutex(Mutex::nosafepoint, "GCMemoryManager_lock", Mutex::_safepoint_check_never); _current_gc_stat = NULL; _num_gc_threads = 1; diff --git a/src/hotspot/share/utilities/concurrentHashTable.inline.hpp b/src/hotspot/share/utilities/concurrentHashTable.inline.hpp index 234f8b38099..fcfb350dfe2 100644 --- a/src/hotspot/share/utilities/concurrentHashTable.inline.hpp +++ b/src/hotspot/share/utilities/concurrentHashTable.inline.hpp @@ -1014,7 +1014,7 @@ inline ConcurrentHashTable:: { _stats_rate = TableRateStatistics(); _resize_lock = - new Mutex(Mutex::leaf-2, "ConcurrentHashTableResize_lock", + new Mutex(Mutex::nosafepoint-2, "ConcurrentHashTableResize_lock", Mutex::_safepoint_check_never); _table = new InternalTable(log2size); assert(log2size_limit >= log2size, "bad ergo"); diff --git a/test/hotspot/gtest/metaspace/test_is_metaspace_obj.cpp b/test/hotspot/gtest/metaspace/test_is_metaspace_obj.cpp index 816a4b42dfd..9ddc7665c9a 100644 --- a/test/hotspot/gtest/metaspace/test_is_metaspace_obj.cpp +++ b/test/hotspot/gtest/metaspace/test_is_metaspace_obj.cpp @@ -49,7 +49,7 @@ public: } void do_test(Metaspace::MetadataType mdType) { - _lock = new Mutex(Monitor::leaf, "gtest-IsMetaspaceObjTest-lock", Monitor::_safepoint_check_never); + _lock = new Mutex(Monitor::nosafepoint, "gtest-IsMetaspaceObjTest_lock", Monitor::_safepoint_check_never); { MutexLocker ml(_lock, Mutex::_no_safepoint_check_flag); _ms = new ClassLoaderMetaspace(_lock, Metaspace::StandardMetaspaceType); diff --git a/test/hotspot/gtest/metaspace/test_metaspacearena.cpp b/test/hotspot/gtest/metaspace/test_metaspacearena.cpp index 62d0ddfec53..bc43e21d480 100644 --- a/test/hotspot/gtest/metaspace/test_metaspacearena.cpp +++ b/test/hotspot/gtest/metaspace/test_metaspacearena.cpp @@ -66,7 +66,7 @@ class MetaspaceArenaTestHelper { void initialize(const ArenaGrowthPolicy* growth_policy, const char* name = "gtest-MetaspaceArena") { _growth_policy = growth_policy; - _lock = new Mutex(Monitor::leaf, "gtest-MetaspaceArenaTest-lock", Monitor::_safepoint_check_never); + _lock = new Mutex(Monitor::nosafepoint, "gtest-MetaspaceArenaTest_lock", Monitor::_safepoint_check_never); // Lock during space creation, since this is what happens in the VM too // (see ClassLoaderData::metaspace_non_null(), which we mimick here). { diff --git a/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp b/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp index 373e9e8d874..9a45107f50a 100644 --- a/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp +++ b/test/hotspot/gtest/metaspace/test_metaspacearena_stress.cpp @@ -142,7 +142,7 @@ public: _alloc_count(), _dealloc_count() { - _lock = new Mutex(Monitor::leaf, "gtest-MetaspaceArenaTestBed-lock", Monitor::_safepoint_check_never); + _lock = new Mutex(Monitor::nosafepoint, "gtest-MetaspaceArenaTestBed_lock", Monitor::_safepoint_check_never); // Lock during space creation, since this is what happens in the VM too // (see ClassLoaderData::metaspace_non_null(), which we mimick here). MutexLocker ml(_lock, Mutex::_no_safepoint_check_flag); diff --git a/test/hotspot/gtest/runtime/test_mutex.cpp b/test/hotspot/gtest/runtime/test_mutex.cpp index d3a38cda54e..2908aa74ab5 100644 --- a/test/hotspot/gtest/runtime/test_mutex.cpp +++ b/test/hotspot/gtest/runtime/test_mutex.cpp @@ -35,7 +35,7 @@ static Mutex* m[iterations]; static int i = 0; static void create_mutex(Thread* thr) { - m[i] = new Mutex(Mutex::leaf, FormatBuffer<128>("MyLock lock #%u", i), Mutex::_safepoint_check_never); + m[i] = new Mutex(Mutex::nosafepoint, FormatBuffer<128>("MyLock#%u_lock", i), Mutex::_safepoint_check_never); i++; } @@ -46,7 +46,7 @@ TEST_VM(MutexName, mutex_name) { nomt_test_doer(create_mutex); } for (int i = 0; i < iterations; i++) { - FormatBuffer<128> f("MyLock lock #%u", i); + FormatBuffer<128> f("MyLock#%u_lock", i); ASSERT_STREQ(m[i]->name(), f.buffer()) << "Wrong name!"; } } @@ -128,18 +128,18 @@ TEST_VM_ASSERT_MSG(MutexRank, mutex_trylock_rank_out_of_orderB, mutex_rankA->unlock(); } -TEST_VM_ASSERT_MSG(MutexRank, mutex_lock_event_leaf, - ".* Attempting to acquire lock mutex_rank_leaf/.* out of order with lock mutex_rank_event/0 " +TEST_VM_ASSERT_MSG(MutexRank, mutex_lock_event_nosafepoint, + ".* Attempting to acquire lock mutex_rank_nosafepoint/.* out of order with lock mutex_rank_event/0 " "-- possible deadlock") { JavaThread* THREAD = JavaThread::current(); ThreadInVMfromNative invm(THREAD); Mutex* mutex_rank_event = new Mutex(Mutex::event, "mutex_rank_event", Mutex::_safepoint_check_never); - Mutex* mutex_rank_leaf = new Mutex(Mutex::leaf, "mutex_rank_leaf", Mutex::_safepoint_check_never); + Mutex* mutex_rank_nonleaf = new Mutex(Mutex::nosafepoint, "mutex_rank_nosafepoint", Mutex::_safepoint_check_never); mutex_rank_event->lock_without_safepoint_check(); - mutex_rank_leaf->lock_without_safepoint_check(); - mutex_rank_leaf->unlock(); + mutex_rank_nonleaf->lock_without_safepoint_check(); + mutex_rank_nonleaf->unlock(); mutex_rank_event->unlock(); } @@ -206,7 +206,7 @@ TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_rank_out_of_order_trylock, TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_rank_special, ".* Attempting to wait on monitor monitor_rank_special_minus_one/.* while holding lock monitor_rank_special/.*" - "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank special.") { + "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank nosafepoint or below.") { JavaThread* THREAD = JavaThread::current(); ThreadInVMfromNative invm(THREAD); @@ -222,7 +222,7 @@ TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_rank_special, TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_event_tty, ".* Attempting to wait on monitor monitor_rank_event/0 while holding lock monitor_rank_tty/.*" - "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank special.") { + "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank nosafepoint or below.") { JavaThread* THREAD = JavaThread::current(); ThreadInVMfromNative invm(THREAD); @@ -238,7 +238,7 @@ TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_event_tty, TEST_VM_ASSERT_MSG(MutexRank, monitor_wait_tty_special, ".* Attempting to wait on monitor monitor_rank_tty/.* while holding lock monitor_rank_special/.*" - "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank special.") { + "-- possible deadlock. Should not block\\(wait\\) while holding a lock of rank nosafepoint or below.") { JavaThread* THREAD = JavaThread::current(); ThreadInVMfromNative invm(THREAD); @@ -271,4 +271,14 @@ TEST_VM_ASSERT_MSG(MutexRank, monitor_negative_rank, monitor_rank_broken->lock_without_safepoint_check(); monitor_rank_broken->unlock(); } + +TEST_VM_ASSERT_MSG(MutexRank, monitor_nosafepoint_rank, + ".*failed: Locks above nosafepoint rank should safepoint: monitor_rank_leaf") { + JavaThread* THREAD = JavaThread::current(); + ThreadInVMfromNative invm(THREAD); + + Monitor* monitor_rank_leaf = new Monitor(Mutex::leaf, "monitor_rank_leaf", Mutex::_safepoint_check_never); + monitor_rank_leaf->lock_without_safepoint_check(); + monitor_rank_leaf->unlock(); +} #endif // ASSERT diff --git a/test/hotspot/gtest/runtime/test_safepoint_locks.cpp b/test/hotspot/gtest/runtime/test_safepoint_locks.cpp index a2bc9b74881..a1050b7b874 100644 --- a/test/hotspot/gtest/runtime/test_safepoint_locks.cpp +++ b/test/hotspot/gtest/runtime/test_safepoint_locks.cpp @@ -38,12 +38,12 @@ TEST_VM_ASSERT_MSG(SafepointLockAssertTest, always_check, TEST_VM_ASSERT_MSG(SafepointLockAssertTest, never_check, ".*This lock should never have a safepoint check for Java threads: SFPT_Test_lock") { - MutexLocker ml(new Mutex(Mutex::leaf, "SFPT_Test_lock", Mutex::_safepoint_check_never), + MutexLocker ml(new Mutex(Mutex::nosafepoint, "SFPT_Test_lock", Mutex::_safepoint_check_never), Mutex::_safepoint_check_flag); } TEST_VM_ASSERT_MSG(SafepointLockAssertTest, special_locks, - ".*Special locks or below should never safepoint") { + ".*Locks below nosafepoint rank should never safepoint: SpecialTest_lock") { MutexLocker ml(new Mutex(Mutex::special, "SpecialTest_lock", Mutex::_safepoint_check_always), Mutex::_safepoint_check_flag); } diff --git a/test/hotspot/gtest/utilities/test_filterQueue.cpp b/test/hotspot/gtest/utilities/test_filterQueue.cpp index 236d6251787..a7dc39ef20d 100644 --- a/test/hotspot/gtest/utilities/test_filterQueue.cpp +++ b/test/hotspot/gtest/utilities/test_filterQueue.cpp @@ -196,7 +196,7 @@ public: TEST_VM(FilterQueue, stress) { FilterQueue queue; - Mutex lock(Mutex::leaf, "Test Lock", Mutex::_safepoint_check_never); + Mutex lock(Mutex::nosafepoint, "Test_lock", Mutex::_safepoint_check_never); static const int nthreads = 4; Semaphore post; FilterQueueTestThread* threads[nthreads] = {}; -- GitLab From 57df0dbc45914969df34e6f42b6c815785e11048 Mon Sep 17 00:00:00 2001 From: Erik Gahlin Date: Tue, 21 Sep 2021 12:02:00 +0000 Subject: [PATCH 048/544] 8270873: JFR: Catch DirectoryIteratorException when scanning for .jfr files Reviewed-by: mgronlun --- .../jdk/jfr/internal/consumer/RepositoryFiles.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/consumer/RepositoryFiles.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/consumer/RepositoryFiles.java index 704f2ba92a0..78bd18ddc7a 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/consumer/RepositoryFiles.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/consumer/RepositoryFiles.java @@ -26,6 +26,7 @@ package jdk.jfr.internal.consumer; import java.io.IOException; +import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.nio.file.attribute.FileTime; @@ -100,12 +101,11 @@ public final class RepositoryFiles { if (updatePaths()) { break; } - } catch (IOException e) { - Logger.log(LogTag.JFR_SYSTEM_STREAMING, LogLevel.DEBUG, "IOException during repository file scan " + e.getMessage()); + } catch (IOException | DirectoryIteratorException e) { + Logger.log(LogTag.JFR_SYSTEM_STREAMING, LogLevel.DEBUG, "Exception during repository file scan " + e.getMessage()); // This can happen if a chunk is being removed // between the file was discovered and an instance - // was accessed, or if new file has been written yet - // Just ignore, and retry later. + // was accessed. Just ignore, and retry later. } if (wait) { nap(); @@ -131,7 +131,7 @@ public final class RepositoryFiles { // Update paths try { updatePaths(); - } catch (IOException e) { + } catch (IOException | DirectoryIteratorException e) { // ignore } // try to get the next file @@ -167,7 +167,7 @@ public final class RepositoryFiles { } } - private boolean updatePaths() throws IOException { + private boolean updatePaths() throws IOException, DirectoryIteratorException { boolean foundNew = false; Path repoPath = repository; @@ -254,7 +254,7 @@ public final class RepositoryFiles { } } } - } catch (IOException e) { + } catch (IOException | DirectoryIteratorException e) { // Ignore } return latestPath; -- GitLab From 42d5d2abaad8a88a5e1326ea8b4494aeb8b5748b Mon Sep 17 00:00:00 2001 From: Artem Semenov Date: Tue, 21 Sep 2021 12:38:29 +0000 Subject: [PATCH 049/544] 8274056: JavaAccessibilityUtilities leaks JNI objects Reviewed-by: aivanov, ant --- .../libawt_lwawt/awt/JavaAccessibilityUtilities.m | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m index 9520c3d552b..662c8b0287b 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaAccessibilityUtilities.m @@ -57,11 +57,14 @@ NSSize getAxComponentSize(JNIEnv *env, jobject axComponent, jobject component) DECLARE_STATIC_METHOD_RETURN(jm_getSize, sjc_CAccessibility, "getSize", "(Ljavax/accessibility/AccessibleComponent;Ljava/awt/Component;)Ljava/awt/Dimension;", NSZeroSize); - jobject dimension = (*env)->CallStaticObjectMethod(env, jc_Dimension, jm_getSize, axComponent, component); + jobject dimension = (*env)->CallStaticObjectMethod(env, sjc_CAccessibility, jm_getSize, axComponent, component); CHECK_EXCEPTION(); if (dimension == NULL) return NSZeroSize; - return NSMakeSize((*env)->GetIntField(env, dimension, jf_width), (*env)->GetIntField(env, dimension, jf_height)); + + NSSize size = NSMakeSize((*env)->GetIntField(env, dimension, jf_width), (*env)->GetIntField(env, dimension, jf_height)); + (*env)->DeleteLocalRef(env, dimension); + return size; } NSString *getJavaRole(JNIEnv *env, jobject axComponent, jobject component) @@ -226,7 +229,9 @@ NSPoint getAxComponentLocationOnScreen(JNIEnv *env, jobject axComponent, jobject axComponent, component); CHECK_EXCEPTION(); if (jpoint == NULL) return NSZeroPoint; - return NSMakePoint((*env)->GetIntField(env, jpoint, sjf_X), (*env)->GetIntField(env, jpoint, sjf_Y)); + NSPoint p = NSMakePoint((*env)->GetIntField(env, jpoint, sjf_X), (*env)->GetIntField(env, jpoint, sjf_Y)); + (*env)->DeleteLocalRef(env, jpoint); + return p; } jint getAxTextCharCount(JNIEnv *env, jobject axText, jobject component) -- GitLab From 6d91a3eb7bd1e1403cfb67f7eb8ce06d7e08e7a7 Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Tue, 21 Sep 2021 13:45:47 +0000 Subject: [PATCH 050/544] 8269039: Disable SHA-1 Signed JARs Reviewed-by: weijun --- src/java.base/share/classes/module-info.java | 3 +- .../provider/certpath/AlgorithmChecker.java | 16 +- .../CertPathConstraintsParameters.java | 6 +- .../sun/security/provider/certpath/PKIX.java | 26 ++- .../certpath/PKIXCertPathValidator.java | 6 +- .../provider/certpath/SunCertPathBuilder.java | 4 +- .../util/DisabledAlgorithmConstraints.java | 9 +- .../util/JarConstraintsParameters.java | 32 ++- .../share/conf/security/java.security | 7 +- .../sun/security/tools/jarsigner/Main.java | 213 +++++++++++------- .../java/security/Security/signedfirst/Dyn.sh | 94 -------- .../Security/signedfirst/DynStatic.java | 96 ++++++++ .../security/Security/signedfirst/Static.sh | 96 -------- .../signedfirst/com/sun/exp/provider/EXP.java | 34 +++ .../signedfirst/com/sun/exp/provider/SHA.java | 33 +++ .../security/Security/signedfirst/exp.jar | Bin 5772 -> 0 bytes .../Security/signedfirst/keystore.jks | Bin 1215 -> 0 bytes test/jdk/java/util/jar/JarFile/Signed.jar | Bin 2966 -> 3466 bytes test/jdk/java/util/jar/JarFile/test.jar | Bin 2324 -> 2843 bytes .../java/util/jar/JarInputStream/signed.jar | Bin 2298 -> 2774 bytes .../tools/jarsigner/CheckSignerCertChain.java | 4 +- .../sun/security/tools/jarsigner/DiffEnd.java | 4 +- .../sun/security/tools/jarsigner/OldSig.java | 7 +- .../sun/security/tools/jarsigner/OldSig.props | 2 + .../security/tools/jarsigner/Test4431684.java | 9 +- .../tools/jarsigner/TimestampCheck.java | 92 +++++--- .../jdk/test/lib/security/SecurityUtils.java | 11 +- 27 files changed, 452 insertions(+), 352 deletions(-) delete mode 100644 test/jdk/java/security/Security/signedfirst/Dyn.sh create mode 100644 test/jdk/java/security/Security/signedfirst/DynStatic.java delete mode 100644 test/jdk/java/security/Security/signedfirst/Static.sh create mode 100644 test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/EXP.java create mode 100644 test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/SHA.java delete mode 100644 test/jdk/java/security/Security/signedfirst/exp.jar delete mode 100644 test/jdk/java/security/Security/signedfirst/keystore.jks create mode 100644 test/jdk/sun/security/tools/jarsigner/OldSig.props diff --git a/src/java.base/share/classes/module-info.java b/src/java.base/share/classes/module-info.java index 9d4a794de1a..19e8bcfd255 100644 --- a/src/java.base/share/classes/module-info.java +++ b/src/java.base/share/classes/module-info.java @@ -318,7 +318,8 @@ module java.base { jdk.crypto.ec, jdk.security.auth; exports sun.security.provider.certpath to - java.naming; + java.naming, + jdk.jartool; exports sun.security.rsa to jdk.crypto.cryptoki; exports sun.security.timestamp to diff --git a/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java b/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java index 56f26d69280..3ed82afaab8 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -131,7 +131,7 @@ public final class AlgorithmChecker extends PKIXCertPathChecker { * certificate * @param constraints the algorithm constraints (or null) * @param date the date specified by the PKIXParameters date, or the - * JAR timestamp if jar files are being validated and the + * timestamp if JAR files are being validated and the * JAR is timestamped. May be null if no timestamp or * PKIXParameter date is set. * @param variant the Validator variant of the operation. A null value @@ -160,17 +160,19 @@ public final class AlgorithmChecker extends PKIXCertPathChecker { /** * Create a new {@code AlgorithmChecker} with the given {@code TrustAnchor}, - * {@code PKIXParameter} date, and {@code varient} + * {@code PKIXParameter} date, and {@code variant}. * * @param anchor the trust anchor selected to validate the target * certificate - * @param pkixdate Date the constraints are checked against. The value is - * either the PKIXParameters date or null for the current date. + * @param date the date specified by the PKIXParameters date, or the + * timestamp if JAR files are being validated and the + * JAR is timestamped. May be null if no timestamp or + * PKIXParameter date is set. * @param variant the Validator variant of the operation. A null value * passed will set it to Validator.GENERIC. */ - public AlgorithmChecker(TrustAnchor anchor, Date pkixdate, String variant) { - this(anchor, certPathDefaultConstraints, pkixdate, variant); + public AlgorithmChecker(TrustAnchor anchor, Date date, String variant) { + this(anchor, certPathDefaultConstraints, date, variant); } @Override diff --git a/src/java.base/share/classes/sun/security/provider/certpath/CertPathConstraintsParameters.java b/src/java.base/share/classes/sun/security/provider/certpath/CertPathConstraintsParameters.java index 597c1f7935c..dacbd12737a 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/CertPathConstraintsParameters.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/CertPathConstraintsParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. * 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.validator.Validator; * constraints specified in the jdk.certpath.disabledAlgorithms security * property. */ -class CertPathConstraintsParameters implements ConstraintsParameters { +public class CertPathConstraintsParameters implements ConstraintsParameters { // The public key of the certificate private final Key key; // The certificate's trust anchor which will be checked against the @@ -103,7 +103,7 @@ class CertPathConstraintsParameters implements ConstraintsParameters { @Override public String toString() { StringBuilder sb = new StringBuilder("[\n"); - sb.append("\n Variant: ").append(variant); + sb.append(" Variant: ").append(variant); if (anchor != null) { sb.append("\n Anchor: ").append(anchor); } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java b/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java index 32f2034394f..1362fccc3ba 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java @@ -88,6 +88,7 @@ class PKIX { private Set anchors; private List certs; private Timestamp timestamp; + private Date timestampDate; private String variant = Validator.VAR_GENERIC; ValidatorParams(CertPath cp, PKIXParameters params) @@ -154,10 +155,20 @@ class PKIX { stores = params.getCertStores(); return stores; } + // The date() param is used when enforcing the validity period + // of certificates and when checking the time period of revocation data. + // The main difference between the date() and timestamp() method is + // that the date() method only uses the timestamp (if specified) + // for certificates in a code signer's chain. Date date() { if (!gotDate) { - // use timestamp if checking signed code that is - // timestamped, otherwise use date parameter + // Use timestamp if checking signed code that is + // timestamped, otherwise use date parameter. + // Note that TSA server certificates do not use the + // timestamp, which means that an expired TSA certificate + // is considered a validation failure. This policy means + // that signed and timestamped code is valid until the TSA + // certificate expires (assuming all other checks are valid). if (timestamp != null && variant.equals(Validator.VAR_CODE_SIGNING)) { date = timestamp.getTimestamp(); @@ -209,6 +220,17 @@ class PKIX { String variant() { return variant; } + // The timestamp() param is passed as the date param when creating an + // AlgorithmChecker. An AlgorithmChecker always uses the timestamp + // if specified in order to enforce the denyAfter constraint. + Date timestamp() { + // return timestamp date if set, otherwise use date parameter + if (timestampDate == null) { + timestampDate = (timestamp != null) + ? timestamp.getTimestamp() : date(); + } + return timestampDate; + } } static class BuilderParams extends ValidatorParams { diff --git a/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java b/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java index fdacbf716df..de3923bb3bc 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -176,8 +176,8 @@ public final class PKIXCertPathValidator extends CertPathValidatorSpi { List certPathCheckers = new ArrayList<>(); // add standard checkers that we will be using certPathCheckers.add(untrustedChecker); - certPathCheckers.add(new AlgorithmChecker(anchor, null, params.date(), - params.variant())); + certPathCheckers.add(new AlgorithmChecker(anchor, null, + params.timestamp(), params.variant())); certPathCheckers.add(new KeyChecker(certPathLen, params.targetCertConstraints())); certPathCheckers.add(new ConstraintsChecker(certPathLen)); diff --git a/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java b/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java index 5f825ff44bf..c1c03d86b7e 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -344,7 +344,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { // add the algorithm checker checkers.add(new AlgorithmChecker(builder.trustAnchor, - buildParams.date(), buildParams.variant())); + buildParams.timestamp(), buildParams.variant())); BasicChecker basicChecker = null; if (nextState.keyParamsNeeded()) { 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 46064d0e9cc..c56f9b60b75 100644 --- a/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java +++ b/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java @@ -39,7 +39,6 @@ import java.security.spec.InvalidParameterSpecException; import java.security.spec.MGF1ParameterSpec; import java.security.spec.NamedParameterSpec; import java.security.spec.PSSParameterSpec; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -688,8 +687,6 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { */ private static class DenyAfterConstraint extends Constraint { private Date denyAfterDate; - private static final SimpleDateFormat dateFormat = - new SimpleDateFormat("EEE, MMM d HH:mm:ss z yyyy"); DenyAfterConstraint(String algo, int year, int month, int day) { Calendar c; @@ -723,7 +720,7 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { denyAfterDate = c.getTime(); if (debug != null) { debug.println("DenyAfterConstraint date set to: " + - dateFormat.format(denyAfterDate)); + denyAfterDate); } } @@ -754,8 +751,8 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { throw new CertPathValidatorException( "denyAfter constraint check failed: " + algorithm + " used with Constraint date: " + - dateFormat.format(denyAfterDate) + "; params date: " + - dateFormat.format(currentDate) + cp.extendedExceptionMsg(), + denyAfterDate + "; params date: " + + currentDate + cp.extendedExceptionMsg(), null, null, -1, BasicReason.ALGORITHM_CONSTRAINED); } } diff --git a/src/java.base/share/classes/sun/security/util/JarConstraintsParameters.java b/src/java.base/share/classes/sun/security/util/JarConstraintsParameters.java index 81fe0eaa835..9cf2bf9ffb3 100644 --- a/src/java.base/share/classes/sun/security/util/JarConstraintsParameters.java +++ b/src/java.base/share/classes/sun/security/util/JarConstraintsParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,9 +50,9 @@ public class JarConstraintsParameters implements ConstraintsParameters { private boolean anchorIsJdkCASet; // The timestamp of the signed JAR file, if timestamped private Date timestamp; - // The keys of the signers + // The keys of the signers and TSA private final Set keys; - // The certs in the signers' chains that are issued by the trust anchor + // The certs in the signers and TSA chain that are issued by the trust anchor private final Set certsIssuedByAnchor; // The extended exception message private String message; @@ -73,7 +73,7 @@ public class JarConstraintsParameters implements ConstraintsParameters { // used for checking if the signer's certificate chains back to a // JDK root CA for (CodeSigner signer : signers) { - init(signer.getSignerCertPath()); + addToCertsAndKeys(signer.getSignerCertPath()); Timestamp timestamp = signer.getTimestamp(); if (timestamp == null) { // this means one of the signers doesn't have a timestamp @@ -82,7 +82,7 @@ public class JarConstraintsParameters implements ConstraintsParameters { skipTimestamp = true; } else { // add the key and last cert of TSA too - init(timestamp.getSignerCertPath()); + addToCertsAndKeys(timestamp.getSignerCertPath()); if (!skipTimestamp) { Date timestampDate = timestamp.getTimestamp(); if (latestTimestamp == null) { @@ -98,11 +98,27 @@ public class JarConstraintsParameters implements ConstraintsParameters { this.timestamp = latestTimestamp; } - // extract last certificate and key from chain - private void init(CertPath cp) { + public JarConstraintsParameters(List chain, Timestamp timestamp) { + this.keys = new HashSet<>(); + this.certsIssuedByAnchor = new HashSet<>(); + addToCertsAndKeys(chain); + if (timestamp != null) { + addToCertsAndKeys(timestamp.getSignerCertPath()); + this.timestamp = timestamp.getTimestamp(); + } else { + this.timestamp = null; + } + } + + // extract last certificate and signer's public key from chain + private void addToCertsAndKeys(CertPath cp) { @SuppressWarnings("unchecked") List chain = (List)cp.getCertificates(); + addToCertsAndKeys(chain); + } + + private void addToCertsAndKeys(List chain) { if (!chain.isEmpty()) { this.certsIssuedByAnchor.add(chain.get(chain.size() - 1)); this.keys.add(chain.get(0).getPublicKey()); @@ -168,7 +184,7 @@ public class JarConstraintsParameters implements ConstraintsParameters { @Override public String toString() { StringBuilder sb = new StringBuilder("[\n"); - sb.append("\n Variant: ").append(getVariant()); + sb.append(" Variant: ").append(getVariant()); sb.append("\n Certs Issued by Anchor:"); for (X509Certificate cert : certsIssuedByAnchor) { sb.append("\n Cert Issuer: ") diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index 6d91e3f8e4e..63be286686d 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -558,7 +558,7 @@ sun.security.krb5.maxReferrals=5 # can be included in the disabledAlgorithms properties. These properties are # to help manage common actions easier across multiple disabledAlgorithm # properties. -# There is one defined security property: jdk.disabled.NamedCurves +# There is one defined security property: jdk.disabled.namedCurves # See the property for more specific details. # # @@ -634,7 +634,8 @@ sun.security.krb5.maxReferrals=5 # # jdk.certpath.disabledAlgorithms=MD2, MD5, SHA1 jdkCA & usage TLSServer, \ - RSA keySize < 1024, DSA keySize < 1024, EC keySize < 224 + RSA keySize < 1024, DSA keySize < 1024, EC keySize < 224, \ + SHA1 usage SignedJAR & denyAfter 2019-01-01 # # Legacy algorithms for certification path (CertPath) processing and @@ -698,7 +699,7 @@ jdk.security.legacyAlgorithms=SHA1, \ # See "jdk.certpath.disabledAlgorithms" for syntax descriptions. # jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, \ - DSA keySize < 1024 + DSA keySize < 1024, SHA1 denyAfter 2019-01-01 # # Algorithm restrictions for Secure Socket Layer/Transport Layer Security diff --git a/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java b/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java index fcf3691cffd..139243a61ad 100644 --- a/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java +++ b/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java @@ -56,6 +56,7 @@ import jdk.security.jarsigner.JarSigner; import jdk.security.jarsigner.JarSignerException; import sun.security.pkcs.PKCS7; import sun.security.pkcs.SignerInfo; +import sun.security.provider.certpath.CertPathConstraintsParameters; import sun.security.timestamp.TimestampToken; import sun.security.tools.KeyStoreUtil; import sun.security.validator.Validator; @@ -972,7 +973,8 @@ public class Main { String history; try { SignerInfo si = p7.getSignerInfos()[0]; - X509Certificate signer = si.getCertificate(p7); + ArrayList chain = si.getCertificateChain(p7); + X509Certificate signer = chain.get(0); String digestAlg = digestMap.get(s); String sigAlg = SignerInfo.makeSigAlg( si.getDigestAlgorithmId(), @@ -996,26 +998,31 @@ public class Main { TimeZone.getTimeZone("UTC"), Locale.getDefault(Locale.Category.FORMAT)); c.setTime(tsTokenInfo.getDate()); + JarConstraintsParameters jcp = + new JarConstraintsParameters(chain, si.getTimestamp()); history = String.format( rb.getString("history.with.ts"), signer.getSubjectX500Principal(), - verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false), - verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false), - verifyWithWeak(key), + verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false, jcp), + verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false, jcp), + verifyWithWeak(key, jcp), c, tsSigner.getSubjectX500Principal(), - verifyWithWeak(tsDigestAlg, DIGEST_PRIMITIVE_SET, true), - verifyWithWeak(tsSigAlg, SIG_PRIMITIVE_SET, true), - verifyWithWeak(tsKey)); + verifyWithWeak(tsDigestAlg, DIGEST_PRIMITIVE_SET, true, jcp), + verifyWithWeak(tsSigAlg, SIG_PRIMITIVE_SET, true, jcp), + verifyWithWeak(tsKey, jcp)); } else { + JarConstraintsParameters jcp = + new JarConstraintsParameters(chain, null); history = String.format( rb.getString("history.without.ts"), signer.getSubjectX500Principal(), - verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false), - verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false), - verifyWithWeak(key)); + verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false, jcp), + verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false, jcp), + verifyWithWeak(key, jcp)); } } catch (Exception e) { + e.printStackTrace(); // The only usage of sigNameMap, remember the name // of the block file if it's invalid. history = String.format( @@ -1339,56 +1346,67 @@ public class Main { } } - private String verifyWithWeak(String alg, Set primitiveSet, boolean tsa) { - if (JAR_DISABLED_CHECK.permits(primitiveSet, alg, null)) { - if (LEGACY_CHECK.permits(primitiveSet, alg, null)) { - return alg; + private String verifyWithWeak(String alg, Set primitiveSet, + boolean tsa, JarConstraintsParameters jcp) { + + try { + JAR_DISABLED_CHECK.permits(alg, jcp); + } catch (CertPathValidatorException e) { + disabledAlgFound = true; + return String.format(rb.getString("with.disabled"), alg); + } + try { + LEGACY_CHECK.permits(alg, jcp); + return alg; + } catch (CertPathValidatorException e) { + if (primitiveSet == SIG_PRIMITIVE_SET) { + legacyAlg |= 2; + legacySigAlg = alg; } else { - if (primitiveSet == SIG_PRIMITIVE_SET) { - legacyAlg |= 2; - legacySigAlg = alg; + if (tsa) { + legacyAlg |= 4; + legacyTsaDigestAlg = alg; } else { - if (tsa) { - legacyAlg |= 4; - legacyTsaDigestAlg = alg; - } else { - legacyAlg |= 1; - legacyDigestAlg = alg; - } + legacyAlg |= 1; + legacyDigestAlg = alg; } - return String.format(rb.getString("with.weak"), alg); } - } else { - disabledAlgFound = true; - return String.format(rb.getString("with.disabled"), alg); + return String.format(rb.getString("with.weak"), alg); } } - private String verifyWithWeak(PublicKey key) { + private String verifyWithWeak(PublicKey key, JarConstraintsParameters jcp) { int kLen = KeyUtil.getKeySize(key); - if (JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) { - if (LEGACY_CHECK.permits(SIG_PRIMITIVE_SET, key)) { - if (kLen >= 0) { - return String.format(rb.getString("key.bit"), kLen); - } else { - return rb.getString("unknown.size"); - } + try { + JAR_DISABLED_CHECK.permits(key.getAlgorithm(), jcp); + } catch (CertPathValidatorException e) { + disabledAlgFound = true; + return String.format(rb.getString("key.bit.disabled"), kLen); + } + try { + LEGACY_CHECK.permits(key.getAlgorithm(), jcp); + if (kLen >= 0) { + return String.format(rb.getString("key.bit"), kLen); } else { - weakPublicKey = key; - legacyAlg |= 8; - return String.format(rb.getString("key.bit.weak"), kLen); + return rb.getString("unknown.size"); } - } else { - disabledAlgFound = true; - return String.format(rb.getString("key.bit.disabled"), kLen); + } catch (CertPathValidatorException e) { + weakPublicKey = key; + legacyAlg |= 8; + return String.format(rb.getString("key.bit.weak"), kLen); } } - private void checkWeakSign(String alg, Set primitiveSet, boolean tsa) { - if (JAR_DISABLED_CHECK.permits(primitiveSet, alg, null)) { - if (!LEGACY_CHECK.permits(primitiveSet, alg, null)) { + private void checkWeakSign(String alg, Set primitiveSet, + boolean tsa, JarConstraintsParameters jcp) { + + try { + JAR_DISABLED_CHECK.permits(alg, jcp); + try { + LEGACY_CHECK.permits(alg, jcp); + } catch (CertPathValidatorException e) { if (primitiveSet == SIG_PRIMITIVE_SET) { - legacyAlg |= 2; + legacyAlg |= 2; } else { if (tsa) { legacyAlg |= 4; @@ -1397,7 +1415,7 @@ public class Main { } } } - } else { + } catch (CertPathValidatorException e) { if (primitiveSet == SIG_PRIMITIVE_SET) { disabledAlg |= 2; } else { @@ -1410,43 +1428,50 @@ public class Main { } } - private void checkWeakSign(PrivateKey key) { - if (JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) { - if (!LEGACY_CHECK.permits(SIG_PRIMITIVE_SET, key)) { + private void checkWeakSign(PrivateKey key, JarConstraintsParameters jcp) { + try { + JAR_DISABLED_CHECK.permits(key.getAlgorithm(), jcp); + try { + LEGACY_CHECK.permits(key.getAlgorithm(), jcp); + } catch (CertPathValidatorException e) { legacyAlg |= 8; } - } else { + } catch (CertPathValidatorException e) { disabledAlg |= 8; } } - private static String checkWeakKey(PublicKey key) { + private static String checkWeakKey(PublicKey key, CertPathConstraintsParameters cpcp) { int kLen = KeyUtil.getKeySize(key); - if (CERTPATH_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) { - if (LEGACY_CHECK.permits(SIG_PRIMITIVE_SET, key)) { - if (kLen >= 0) { - return String.format(rb.getString("key.bit"), kLen); - } else { - return rb.getString("unknown.size"); - } + try { + CERTPATH_DISABLED_CHECK.permits(key.getAlgorithm(), cpcp); + } catch (CertPathValidatorException e) { + return String.format(rb.getString("key.bit.disabled"), kLen); + } + try { + LEGACY_CHECK.permits(key.getAlgorithm(), cpcp); + if (kLen >= 0) { + return String.format(rb.getString("key.bit"), kLen); } else { - return String.format(rb.getString("key.bit.weak"), kLen); + return rb.getString("unknown.size"); } - } else { - return String.format(rb.getString("key.bit.disabled"), kLen); + } catch (CertPathValidatorException e) { + return String.format(rb.getString("key.bit.weak"), kLen); } } - private static String checkWeakAlg(String alg) { - if (CERTPATH_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, alg, null)) { - if (LEGACY_CHECK.permits(SIG_PRIMITIVE_SET, alg, null)) { - return alg; - } else { - return String.format(rb.getString("with.weak"), alg); - } - } else { + private static String checkWeakAlg(String alg, CertPathConstraintsParameters cpcp) { + try { + CERTPATH_DISABLED_CHECK.permits(alg, cpcp); + } catch (CertPathValidatorException e) { return String.format(rb.getString("with.disabled"), alg); } + try { + LEGACY_CHECK.permits(alg, cpcp); + return alg; + } catch (CertPathValidatorException e) { + return String.format(rb.getString("with.weak"), alg); + } } private static MessageFormat validityTimeForm = null; @@ -1471,7 +1496,7 @@ public class Main { * @param checkUsage true to check code signer keyUsage */ String printCert(boolean isTsCert, String tab, Certificate c, - Date timestamp, boolean checkUsage) throws Exception { + Date timestamp, boolean checkUsage, CertPathConstraintsParameters cpcp) throws Exception { StringBuilder certStr = new StringBuilder(); String space = rb.getString("SPACE"); @@ -1504,16 +1529,16 @@ public class Main { .append("Signature algorithm: ") .append(sigalg) .append(rb.getString("COMMA")) - .append(checkWeakKey(key)); + .append(checkWeakKey(key, cpcp)); certStr.append("\n").append(tab).append("["); certStr.append(rb.getString("trusted.certificate")); } else { certStr.append("\n").append(tab) .append("Signature algorithm: ") - .append(checkWeakAlg(sigalg)) + .append(checkWeakAlg(sigalg, cpcp)) .append(rb.getString("COMMA")) - .append(checkWeakKey(key)); + .append(checkWeakKey(key, cpcp)); certStr.append("\n").append(tab).append("["); @@ -1694,19 +1719,21 @@ public class Main { if (digestalg == null) { digestalg = JarSigner.Builder.getDefaultDigestAlgorithm(); } - checkWeakSign(digestalg, DIGEST_PRIMITIVE_SET, false); + JarConstraintsParameters jcp = + new JarConstraintsParameters(Arrays.asList(certChain), null); + checkWeakSign(digestalg, DIGEST_PRIMITIVE_SET, false, jcp); if (tSADigestAlg == null) { tSADigestAlg = JarSigner.Builder.getDefaultDigestAlgorithm(); } - checkWeakSign(tSADigestAlg, DIGEST_PRIMITIVE_SET, true); + checkWeakSign(tSADigestAlg, DIGEST_PRIMITIVE_SET, true, jcp); if (sigalg == null) { sigalg = JarSigner.Builder.getDefaultSignatureAlgorithm(privateKey); } - checkWeakSign(sigalg, SIG_PRIMITIVE_SET, false); + checkWeakSign(sigalg, SIG_PRIMITIVE_SET, false, jcp); - checkWeakSign(privateKey); + checkWeakSign(privateKey, jcp); boolean aliasUsed = false; X509Certificate tsaCert = null; @@ -1804,8 +1831,10 @@ public class Main { if (tsaUrl != null) { System.out.println(rb.getString("TSA.location.") + tsaUrl); } else if (tsaCert != null) { + CertPathConstraintsParameters cpcp = + new CertPathConstraintsParameters(tsaCert, Validator.VAR_TSA_SERVER, null, null); System.out.println(rb.getString("TSA.certificate.") + - printCert(true, "", tsaCert, null, false)); + printCert(true, "", tsaCert, null, false, cpcp)); } } builder.tsa(tsaURI); @@ -2015,8 +2044,13 @@ public class Main { boolean first = true; StringBuilder sb = new StringBuilder(); sb.append(tab1).append(rb.getString("...Signer")).append('\n'); + @SuppressWarnings("unchecked") + List chain = (List)certs; + TrustAnchor anchor = findTrustAnchor(chain); for (Certificate c : certs) { - sb.append(printCert(false, tab2, c, timestamp, first)); + CertPathConstraintsParameters cpcp = + new CertPathConstraintsParameters((X509Certificate)c, Validator.VAR_CODE_SIGNING, anchor, timestamp); + sb.append(printCert(false, tab2, c, timestamp, first, cpcp)); sb.append('\n'); first = false; } @@ -2029,9 +2063,15 @@ public class Main { .append(e.getLocalizedMessage()).append("]\n"); } if (ts != null) { + List tscerts = ts.getSignerCertPath().getCertificates(); + @SuppressWarnings("unchecked") + List tschain = (List)tscerts; + anchor = findTrustAnchor(chain); sb.append(tab1).append(rb.getString("...TSA")).append('\n'); - for (Certificate c : ts.getSignerCertPath().getCertificates()) { - sb.append(printCert(true, tab2, c, null, false)); + for (Certificate c : tschain) { + CertPathConstraintsParameters cpcp = + new CertPathConstraintsParameters((X509Certificate)c, Validator.VAR_TSA_SERVER, anchor, timestamp); + sb.append(printCert(true, tab2, c, null, false, cpcp)); sb.append('\n'); } try { @@ -2052,6 +2092,15 @@ public class Main { return sb.toString(); } + private TrustAnchor findTrustAnchor(List chain) { + X509Certificate last = chain.get(chain.size() - 1); + Optional trusted = + trustedCerts.stream() + .filter(c -> c.getSubjectX500Principal().equals(last.getIssuerX500Principal())) + .findFirst(); + return trusted.isPresent() ? new TrustAnchor(trusted.get(), null) : null; + } + void loadKeyStore(String keyStoreName, boolean prompt) { if (!nullStream && keyStoreName == null) { diff --git a/test/jdk/java/security/Security/signedfirst/Dyn.sh b/test/jdk/java/security/Security/signedfirst/Dyn.sh deleted file mode 100644 index ad1211c2fbf..00000000000 --- a/test/jdk/java/security/Security/signedfirst/Dyn.sh +++ /dev/null @@ -1,94 +0,0 @@ -# -# Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please 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 4504355 -# @summary problems if signed crypto provider is the most preferred provider -# -# @run shell Dyn.sh - -# set a few environment variables so that the shell-script can run stand-alone -# in the source directory -if [ "${TESTSRC}" = "" ] ; then - TESTSRC="." -fi - -if [ "${TESTCLASSES}" = "" ] ; then - TESTCLASSES="." -fi - -if [ "${TESTJAVA}" = "" ] ; then - echo "TESTJAVA not set. Test cannot execute." - echo "FAILED!!!" - exit 1 -fi - -if [ "${COMPILEJAVA}" = "" ]; then - COMPILEJAVA="${TESTJAVA}" -fi - -# set platform-dependent variables -OS=`uname -s` -case "$OS" in - Linux ) - PATHSEP=":" - FILESEP="/" - ;; - Darwin ) - PATHSEP=":" - FILESEP="/" - ;; - AIX ) - PATHSEP=":" - FILESEP="/" - ;; - CYGWIN* ) - PATHSEP=";" - FILESEP="/" - ;; - Windows* ) - PATHSEP=";" - FILESEP="\\" - ;; - * ) - echo "Unrecognized system!" - exit 1; - ;; -esac - -# remove old class files -cd ${TESTCLASSES}${FILESEP} -rm DynSignedProvFirst.class - -# compile the test program -${COMPILEJAVA}${FILESEP}bin${FILESEP}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ - -classpath ${TESTSRC}${FILESEP}exp.jar \ - -d ${TESTCLASSES}${FILESEP} \ - ${TESTSRC}${FILESEP}DynSignedProvFirst.java - -# run the test -${TESTJAVA}${FILESEP}bin${FILESEP}java ${TESTVMOPTS} \ - -classpath "${TESTCLASSES}${PATHSEP}${TESTSRC}${FILESEP}exp.jar" \ - DynSignedProvFirst - -exit $? diff --git a/test/jdk/java/security/Security/signedfirst/DynStatic.java b/test/jdk/java/security/Security/signedfirst/DynStatic.java new file mode 100644 index 00000000000..5256564064b --- /dev/null +++ b/test/jdk/java/security/Security/signedfirst/DynStatic.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 4504355 4744260 + * @summary problems if signed crypto provider is the most preferred provider + * @modules java.base/sun.security.tools.keytool + * jdk.jartool/sun.security.tools.jarsigner + * @library /test/lib + * @run main/othervm DynStatic + */ + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.util.JarUtils; + +public class DynStatic { + + private static final String TEST_SRC = + Paths.get(System.getProperty("test.src")).toString(); + private static final Path TEST_CLASSES = + Paths.get(System.getProperty("test.classes")); + + private static final Path EXP_SRC_DIR = Paths.get(TEST_SRC, "com"); + private static final Path EXP_DEST_DIR = Paths.get("build"); + private static final Path DYN_SRC = + Paths.get(TEST_SRC, "DynSignedProvFirst.java"); + private static final Path STATIC_SRC = + Paths.get(TEST_SRC, "StaticSignedProvFirst.java"); + + private static final String STATIC_PROPS = + Paths.get(TEST_SRC, "Static.props").toString(); + + public static void main(String[] args) throws Exception { + + // Compile the provider + CompilerUtils.compile(EXP_SRC_DIR, EXP_DEST_DIR); + + // Create a jar file containing the provider + JarUtils.createJarFile(Path.of("exp.jar"), EXP_DEST_DIR, "com"); + + // Create a keystore + sun.security.tools.keytool.Main.main( + ("-genkeypair -dname CN=Signer -keystore exp.ks -storepass " + + "changeit -keypass changeit -keyalg rsa").split(" ")); + + // Sign jar + sun.security.tools.jarsigner.Main.main( + "-storepass changeit -keystore exp.ks exp.jar mykey" + .split(" ")); + + // Compile the DynSignedProvFirst test program + CompilerUtils.compile(DYN_SRC, TEST_CLASSES, "-classpath", "exp.jar"); + + // Run the DynSignedProvFirst test program + ProcessTools.executeTestJvm("-classpath", + TEST_CLASSES.toString() + File.pathSeparator + "exp.jar", + "DynSignedProvFirst") + .shouldContain("test passed"); + + // Compile the StaticSignedProvFirst test program + CompilerUtils.compile(STATIC_SRC, TEST_CLASSES, "-classpath", "exp.jar"); + + // Run the StaticSignedProvFirst test program + ProcessTools.executeTestJvm("-classpath", + TEST_CLASSES.toString() + File.pathSeparator + "exp.jar", + "-Djava.security.properties=file:" + STATIC_PROPS, + "StaticSignedProvFirst") + .shouldContain("test passed"); + } +} diff --git a/test/jdk/java/security/Security/signedfirst/Static.sh b/test/jdk/java/security/Security/signedfirst/Static.sh deleted file mode 100644 index 940e10a1c5a..00000000000 --- a/test/jdk/java/security/Security/signedfirst/Static.sh +++ /dev/null @@ -1,96 +0,0 @@ -# -# Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please 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 4504355 4744260 -# @summary problems if signed crypto provider is the most preferred provider -# -# @run shell Static.sh - -# set a few environment variables so that the shell-script can run stand-alone -# in the source directory -if [ "${TESTSRC}" = "" ] ; then - TESTSRC="." -fi - -if [ "${TESTCLASSES}" = "" ] ; then - TESTCLASSES="." -fi - -if [ "${TESTJAVA}" = "" ] ; then - echo "TESTJAVA not set. Test cannot execute." - echo "FAILED!!!" - exit 1 -fi - -if [ "${COMPILEJAVA}" = "" ]; then - COMPILEJAVA="${TESTJAVA}" -fi - -# set platform-dependent variables -OS=`uname -s` -case "$OS" in - Linux ) - PATHSEP=":" - FILESEP="/" - ;; - Darwin ) - PATHSEP=":" - FILESEP="/" - ;; - AIX ) - PATHSEP=":" - FILESEP="/" - ;; - CYGWIN* ) - PATHSEP=";" - FILESEP="/" - ;; - Windows* ) - PATHSEP=";" - FILESEP="\\" - ;; - * ) - echo "Unrecognized system!" - exit 1; - ;; -esac - -# remove old class files -cd ${TESTCLASSES}${FILESEP} -rm StaticSignedProvFirst.class - -# compile the test program -${COMPILEJAVA}${FILESEP}bin${FILESEP}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ - -classpath "${TESTCLASSES}${PATHSEP}${TESTSRC}${FILESEP}exp.jar" \ - -d ${TESTCLASSES}${FILESEP} \ - ${TESTSRC}${FILESEP}StaticSignedProvFirst.java - -# run the test -cd ${TESTSRC}${FILESEP} -${TESTJAVA}${FILESEP}bin${FILESEP}java ${TESTVMOPTS} \ - -classpath "${TESTCLASSES}${PATHSEP}${TESTSRC}${FILESEP}exp.jar" \ - -Djava.security.properties=file:${TESTSRC}${FILESEP}Static.props \ - StaticSignedProvFirst - -exit $? diff --git a/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/EXP.java b/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/EXP.java new file mode 100644 index 00000000000..ef916e6e100 --- /dev/null +++ b/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/EXP.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.exp.provider; + +import java.security.Provider; + +public class EXP extends Provider { + + public EXP() { + super("EXP", 0.0d, "Test provider"); + put("MessageDigest.SHA1", "com.sun.exp.provider.SHA"); + } +} diff --git a/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/SHA.java b/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/SHA.java new file mode 100644 index 00000000000..7f6c4128ac0 --- /dev/null +++ b/test/jdk/java/security/Security/signedfirst/com/sun/exp/provider/SHA.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.exp.provider; + +import java.security.MessageDigestSpi; + +public class SHA extends MessageDigestSpi { + protected void engineReset() {} + protected void engineUpdate(byte input) {} + protected void engineUpdate(byte[] input, int offset, int len) {} + protected byte[] engineDigest() { return null; } +} diff --git a/test/jdk/java/security/Security/signedfirst/exp.jar b/test/jdk/java/security/Security/signedfirst/exp.jar deleted file mode 100644 index 7411a0a18a8ea9de8c439939bec290b53233279c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5772 zcmbW5cQ{;I_s1nfpAbZennW4FV05ArQAV$$-5716_ZqG;>JUVU-fM`?5G68t84@L4qRN)$W0(iMCY5L ztGX`)$2ww~Q>S?J?Ib>{23BUhFd=Hl_wv5{2*WM(G4kaFq}Qbz?^t5{bF3=$z_(9A zZ!@xXe-amMlAZM5Bo}b_;2dgZEJHb2B;rD)RQYP-V*P82De-bL#_iw*x;_cKW`Q!JqhiC>Wr%R=hvXiQYMz<^mzkOR`UPhHZ?Nv;y9#I=x0m1gR zf}ZLI?IHSs-h7{2b+cg^$;0anMFzEg?rQ>LBOOLkQD@^h61MWaW@=Q!o_*M>a4zs z(r_A2Ql^~G9QOh@U*f*X;j50yA@#SU*Vh($2$^= z*bEPF%>wPXJ9+1o_Up92wQ?9`)s`)pN$bv2=wH~14$PtH6E1RGOQ2mQERz+&>@R`n z6(5be@6q^pf)Zj3xTA{mT-bT%IUPf6Y18?;g;LN?dz6~01cVaK7dPmzHPnHGj)IT*PB}qsNHpV1dzn?P${FP9MM^ z014oZLB;?8kUZ>E)Hx1!b7U8C= zn8J5V4-v)0`!2qzY3Z`t+S)PsEcNX8UH6T?R+_2DGugd$R08@1nbT8SB@+#f+v5^D zOgyPBreD^|tc;F{smqq1fcXW$d?0!xpizorfih^OVk_8OLnP)Z?ofQd=5U0(tBjRKbmpd3E1WP zAOtRJo~h(Fm=ia}@tyc9WYT@jBD5`>!qYwH!TSYmX{j1*z=M_`m!84xLJURJ zESWth;7Mv4W9L^s@eRe1N26Ch&A>O<+Jj>!Xx1i6xx~D>J`~NlsT+{{;bUu(fRNZ} zO2+ac4o(yHI;&BQdH~lyA3k2V>Vsqk9FG5y?N&*l1? zdj`6U=0ELl@duZN3K2zTG`WpxRR zlSGKy&TzB}qp7BjC~t?A)VHqB#lzP>M7NDT%nw@MojUS#twL*VkfN6pIbP%=hi_2z z(S#}5x%PKok#?#zcq+K>u7Gf|mbGe-ZDvU3QFRqte$Z~!VHEgi;T z2Gof_a)I&F$Rg@EJ?~Y?G~K30YdYi z$sxOi3}O4kP3AJmxK!_S+bPg)gRgg`uV?4hcRMZLI#Rh8%F$zFQf_;5z32Vj^}s09 zb3g6xf8J_PwgHU>2I&>vE!SQp{Qjdv<78PJs<8WS{lDt_*VSkGAFKb@+H1`^j>=GF zIOxm@u_H89fP%EZBpro{8)llfG!vzZ)9iwTjqAo(2*mSCGxWeJiY$6P)Z{m3 zN&g_sQttEM&_FJByE-ySHSuWh$oNdf|Ik4-@6`#81+ z=Wf9H3+KR6mfn1|Qq|+TRuVj+2^Fi6ie{vjy`gngfa6MsfVQEuX0eSYhIzh0>SWb2 zjLsgl-O2oibV)b4{loV?_X)QRyep-XmZNo_JTCT4vE0s8S0Jlz2ghjRIp2>q*F5TR zQSlE^<4u|vFf44;DABP}mwM{QuQ}&RyA`H4tOq=WJqi^?PRPF-Ev` zdb=U$eUWPRyQi$91Oxf-QFh2|oe$NQKO1Cf=UV})kLIiV8tqvMt^?|NBi=AaUCL<4 z3(`{3Okt_uiCt%A0rw+&Bf!8|;4Q+~65yuT;cI*Cy4b#D|Fw*r47Xvig&qIH)uV@5 zVk9|NvOij|B`~pbUQeSTc*!vbk$WZQNbRb5w>|CxFGxTVELYQ?Rh>IbB2r>$_Tad{ zxe=KCRAN8PS#0I#+rqa}XCI$9Pyx$w97&_E%aw#1RE&Iq?^Vo?<+NY>>~b9f$)xsY zl%kp~dakedN&76B^3%I63ez}x!KR|SQ0SN|ywrWZ-u>-eS`7h3f{rc>Nr^k|_XZI+ zLC9y$G#wsy2UbR>NrS`*UvH&P?rhrcysm=@+|xG}el$r*_rM^pJ%^Kl?YaIWg}vYO zSo|P0Se&bYd=6ha4j45e9^8|#PoOyRf@yP70PbM*YNFc`jnBTdWuFQg7~6Y5@QE{^ zi!@+`G$5%%B7HQqt}U6|ab3-tAZ-t!_DG+>{@S1wS)mT}X(WkZt36G}>tqN#bUO1L za>A5$s&d7X_296!`}ND~$0{K&bCTb|LLg~v*XN5@KB*^vN=KT4Mr^jX8PwR^(Y1R1 zCICNU2_&s&A41bA%`|^SsP(O7H)XMvpD~yEtG5Rh+Vo>hD?Y-j*YHW2CuXuCOo>?s zHUeJ@WY9I3bjolF$hSx}bDiOn^!kD}s5*ynFI#;Kyc9i@Bpek_W{T<#A8k0?tInvZ<^|D`2N0d{(x>X?GOMTrK;ZEG7F1Ot|E;ScnM+g|5E+1Z@ zkY`Ly)PK*pE=d4gvENHd>x8F}`8i86$1f&MCLm0p%=f_(+SROs>6d5XN9s-3M;5XM ztlaSKLJrC0LLxJ=)ITa|hdD_l^lijv6w$cS@hBQ*VwOn=E*Ct4^W-b-g+vxmE8E=o z0)es`zig_E|JG8ma>G|RVX{_iXbKEFsxnrY3pbP7Lc}Q;3TDF6Gaz323ud$ogRAa5 zLiveb_EooD?Hws(BZ9U<;4d;BcJWu2sM|G?t#~;6*^w1@!d@F9A8LyZ%*$D7FCpc_ zx4Gst>Gn>Ind~BHv8kOjRMZ;H&axQPLTj+6f{OB?*WYJe>V889ZuxSFA?e#E?nX@9 z>}RKtD?RMb!4okP&3#Z2`X}Z&db>}oeFjL4tb8^}r-$1!1(tEF`M2am?0gN~cp12H zB}bGs1rK!~NJW+1Z6RwYh!CS&FUm{Wn?t9y+M#lgu^rxf z>SN5n>$DGu-HMqTf=BTW=P;GHWKu!bOrn}H0tg|7GPk=d#fnDTt-P1RhnLHWnbgI^jPVOlfMWGc#*!)hBOaB+Y+J{ObTFm`I7^zS z>68SA`K&)`6oP$b5%K@?As37_up*Vzr-_xrIPm62a_ewrIX&PUy~Hu_zQ$7C{3Fz7 z6G3X|5!FVwgW%Idw7CrCZikp_%hw6KIu)YEuB`;umzdRra;Py9@xGP4l3EFNJ)8}t z=$v+uhV_VmJb}0%>aH7e7_mbM;6 zxzFDn?iwmhaHr`YpLEiX*8T9U{@m~kfitrdx?O3PP%50#o1C&mDsqWotC^UAgj7ka zjVu4eHNHt{Oh2iK|w>!L-Uu-63x#Wp^%=Yaa#|+9dN>^j%T4>Mj%HWK2zOd&Qz%~xUG0;Snlkewq%iIlMkfN^$D1DV2C5wrr#l% z)5vigdv{2fbpUd;Lt;fArjne#kjULA7RKsGidYfY$v>u*eZKE6%FFjPuy+B&TeI2| zv1rwXW4@R&Km6I%4`D7Vy_OpYQ2t6`)Dn9;pbNcg=TGbe{t$>J{L0f7+4zAwAe?#e z(Ec02>PZCI2M*UajC)JNR2_a}5r?I8fw`BzCOz#UC|Gn#>{)ISn7I}xeQu7DK<))&LS#5`d*O^ zX~US6>#UJIJU~8+@bYEic}Swh8mIac+UVlq^Vap)dr6&bJ4;5j*Oau>1D(H^^MKW! zo<#i49lsEK=fs?6)syD)vkdN?nX-O!SM)cd@AZ7JonwL;H(Jj@WE-!E8U^SBIwdI$ zC2vxM(>+nxb*B0htaY2}V+nv`V7L_EvV%8+8BnSrni(GG8yNXYgIq1lF>sJFlFAqE zd2*tpuE)UU+yT_1Do@zl5~I_!DKT(VTs2uVYobeaBiL$nl>~1RiTkd^T22g%3?Em0 zzK|>+K>#AoNei|u^r6jxlGbiJ5-*w&F9nqK*ubTjtY2p4A-s{)iBfuAAwB(4D30n9h3mU8^U_Rr{XkSNQ zHbWw9`cTmwH~D3Zp~_xP=PKtt|8Ce}PxI&O ztZ8-DzWY1E-;J*Gt(wzD*O?Jx4~}OM{%U*uDnC!rr~RBWv%sD?f01LmJLmO(v-aO0 zeahNrhJWdt{*=5=rNlVDC+#z-JXZRXyMM1ZCGRt{`b+VX!+)+ zlKGj{|Drs{=|30vZ&E)`aV%$g>}dUWAHn`-|L}yS>LvWs|0coyda%o1NqIW^4fhf7^Jz1t(8*&Jf<Uq z*qR8R^4w!~b2NnX|7UK@E`0q|-6D0bM+lRSdFK&76Tz@Q9R~VI6D;DU-CViG{c79# z$Gpu~hZ0|BTHRCBG$E;iCi47d7607otmaNRS?~?SJ z+sks2zSumD`4HmT8R)uKDYs(sgPNZ&AJt4dEfH9fW_DjPNbuU~q8=~l$n87Z)t|Ro z_$O*L1nil~rCaCV`a32sG<(^Kc{Z<$E@%G#_0?m0nAAm?t?xhHdHTJ_;K5r*`Qtkj zb8kj(4KI9YC2G8K%JeXn)I~G*Z@;i(n@1Vz$z?Aua{PE8{d_u)q5a*~uHHp1*RRj} zFZA`}g7=~3R%!=iQ>+t97soFAJ5Ax#vgOXtc}{n3-e~%IIiKZPc|DbF^L=J(eMo0K z%v{A)9({|&N-rQXvp&k+?RFBc&~bjXu5Lf)nTo$o>YM$T&YtwJDL(t+sh0~5i{3hU zuj;3-iQ|2a)<6IDe>B)OWvNi;xxXrHeMS@clG3#u^>b!S`fS_xUZ}(J+C}R>dzO6L zkrHBVHS7Gj8xwj0wi%cF+`VllSJES0Io;`e?*zNW(?#T?An7?m&(y#Yn4S+9G%@Z0 zV$}uAOpHuSEUq8lIT`S>acZ@Bw0-9VCTdm&13^Q6pb&E?3$rj=aAta5YLS7QIIn@Z zfw6(5k+HF%p-GfDuOWzQ2IXSY(l{U4TwrctZtP_+XzXNaY-E_?y@;<{rtOD$#Nwhg zDciPX?MT|Xbg%pUC(5h}8Z0*)PPTsIRH`-MUb$n=b}^6T7S3-uuh}tLhp03Q-&7Ij zsERIO_BWbvoFnzZ!DV@i*V^0Px$u2<_tT9~r7a2UDw&ucw^08WU&~|`|Af5AvxlGFsPkmc*PeU# zi-&=)kx|vvevP@}*6~tNQ=_uhwyd}2zI91YE7XLkJZYtC;{`eXl^lgjvRQV0mrag; zWwP1(j(e7@o)*iFqn8;y)TX~Jycn?a(^cac1})u>J9eCYBf9cS(glg9H5ZqJS1dQK RpQ6yy_oUpll{uEh5&%JE2XX)a diff --git a/test/jdk/java/util/jar/JarFile/Signed.jar b/test/jdk/java/util/jar/JarFile/Signed.jar index c20f60c73e6592a3234983ed6b000a5b0dda73f8..2122b30883d5db96b43c6acd56f4f14f91bb293d 100644 GIT binary patch delta 2119 zcmZ8ic|6ox8y}{b#t?bOB`HFdO7>)%Tcd_DSC+A4%hk+SCX6LpgWpwm6k2GQQDiHM zTy&?#OiUts#JwR~mdqeKL&)}y_tRVMea`3koaa2x`JQv0^T+o~lSz;hx50pSNP%E5 z7%1Nkj!hOn2oRbvqE}Dup$u^bfi!|*0*-j#d7CCaA9^pZTq~W}gt3zpMN@;FFb&BL5_n?Wp!exD!EZzw9J^^_cTA?70Mo9^)-=O4fl;Dlp zU#R=hnMJbsrVr__T*gv;c9!gtmRy3fWcPl4?yP4AjLPlDInYP^WM0i1KY zAX=sw94@9(mP3yd{#hdvttjG$e(#YQZf{nXYJIXT2u6D}kY5+m8SdrNR4<}whZCdq zv^#eI>#|to9-9CDCyAlttjhJbVnUL&BN@5TZxtDjdecTT$)O8oNc$>L=SK5!t;@7u zXb#tvY?H!zs6<2IVGsihQJ6efMWDleb>;#%k;wogP*{#l4c5 zUO6bS^~IA7Y6?n1Aka;L|MQEft3vXC9TuhMbFsy9xSh!NS$+4m;obA>_+y;{zZ;+Y zSJJ?5^jms4E!T8X?@{8DQ>%WH%Sj4CAsD#=FG3*@6T)7q=BldVap50^!}`zQpuX1% zaa<^oag1v)h{uT&JP}^-T?SmpeK0prgb|@aQ`rmOGaJk5tDf9|6hs0SH2bw7&D9#3 zdEEuj;7=9iaZqU}%^a!i3a!KD-#?cmo^Pg6g_~=34pHcUNZ0=~XZ1X9`9bPj?NtcTGlrms#*Le!lfBiL8GwFwG1&v3Fy(#d!qT*L zrJO`Tp?0ad&qurHd0<5*H4{>c7H0?_j*!-OrzT{Tb8ULydNXPvkI(mRER3T$|Y?k-Y@{d_wcs`TSN{XaN zPc&zjmIraa0=>KHS7Ta3jeVE+r4r>GE6NjVjJukzmV?|#>rKIP?iBzC>n9iWg(qLoFcV$^2>qXP9xgEG&abb7ubyF432O-{-KHO9iN%i>_U6q4uHlQ0$D)SR`yI(gqRrybsWz|c z*E1F1&L+mkqnh2=#3ceoi&7#_o+u8I2K@W->mve|P8Teq=i3`lNW^c zev__Y!KY5g1tprrG$H-ZE^p*K9ITw>l;-`CSYEWTqH!PTPbvelUp-`pcRgU$ow`RT zm(~Cd(+2tpQR~@%QFuqb$QtO(f%Ra=wU5h2*rnOn@@4FpZf%BdP72F^$!Lyi=x#p= zReVEikZ81wgT|@8HpTBFWG5ya)3Mi1I;D3-(dAsHg}S$n{YBe0i4CKwHr7$wcqa9^B)mnfA##b`HrQ;>4m`tJ;koQgRQgax zc}AUlrM|i0!ZF3#2{JP5nPT8c4>`ozDj!H*6oz&BaCVIn&=HBe zCFf4UyFfm_u<9?JxOrXoDQ9tpzt@%A<5VIs9kIC9_cHFz=tyFybzpi_%ZUoNr){Id zJcJ0}%MdflGCHqwl$hSt+A%kLyL6Mjl6QSGZK{iH6&x1hyOs&bx3g6n55b!(w}x#VH#j)|Xe!(CGnSrc0nwG(DERAv494iG31vYoQx z1&T*Cgcu0H7$k@|STM!Fa)ow()57mcLe+-r0^gF`xo=BEe%PuY{I{goV1$IFKtJSl z`!gheKn0Pj@W0Ul8r=pr25mid3nJL~KNA57`uT41JGbFCnzp+9|J77E(F3log1S8+ z;`3bu=i HZLR(b2M4AN delta 1499 zcmeB@o+i#0;LXe;!oUH9Y}wX^6Zur?W6wBpHyKDYJly@D{>DbWE;l(Ls~1yDF7XtX z{EZ4uv&@`5>A&6U7hhYSpLO^!OEXtcP4s4D6KQ^&9Ebm0G=$5di^ytJ-+^OQL?Z~HH8NxZUhP5-SAvEjTLUyn^Lk$?Xw z^xjF^$M3REocQ2a_c}ZMj`)6NkZ&)ZzM%;6>31n&eHYaDzt(r4FL2G!}?r^yFIJo+- z`TG2CsNfgwPG*^H7cfg!qxM`=tK* z4V#UE+-8H-#cqLV8yn|XtZ(dWTsm>*!if_%E=&~Z;7*z4xbsVqoABc@g=>wh49XLf z&tJK5;=^{k9f8|IJd9uLyDqcW+<#uZ@Ey67&-Yp%ZkSVhc$>pkpX(9qOAp+ixNWcC z{%`Vscb%?(aQo%Wg_hT)*Gi}OezISxnsa`h zIXquJdZW*j`A^F~Z$It+l+So(8;5(RugR~lUzKyq9+j^BK7Yy#)#q_v5^TkUtPUy z{zJPv+ur!TY@GP8cK14$U-sH5;u$$N9%+WH_;bkJ*{9-nrQhOt!l&hKb%d6-U-^<{ z6S2q7uln<*OP!V7uXomK&Qh!WGdJYuilo}KlgDednbb?xW$gQJ@akpFHqX16g}hf6 zuF~wWyY~NFb(W#|HUk4wvn%!Ib{wl;^ZRFGa*^7bO?%vb=< zsf(_c@`ubRvp;k9+s=P4O>1vYu6QS>|W1npk4#)tyWaSe2Uhb>jStnmZ-`i+9&= z{nT_?E0Dn z_xA)&{=e^o%F|`-ZN1gJQss=sU5oDl`!84tvGI=O;J z#to_r**;LNM1Z%9usrJLrtcE!?WzaNrUBlJOd<@Bf*9(z4(rn^fAe#V%gq>di diff --git a/test/jdk/java/util/jar/JarFile/test.jar b/test/jdk/java/util/jar/JarFile/test.jar index 1e3523346ab150eefac16e36e55d979d3f9bbd5a..6afd0d140c75044f803d1909ad42b0671ed3da64 100644 GIT binary patch delta 2040 zcmaJ?c{JN;7Y-_7Z>v??F#TF#$k>;n)>;OWGExjAnlt&~zjHMUlWGWKR-_eIZ~sp%izea}7beeZehJ@>tTJWtlyLQx@GYpzr0KoAH7 z^q)9hM8=RfVULF&IG zSku>#OfcgEe>KAVf;Z7yjF*3;%Sibmr@2;n_5s9HOix@f`dpKk$Hy#p`GmCSk+cz= zlqFie^mc~ZA95qO1kD@Qu;}yF%Sbt>7Pi-Ms)9d0NXQ!Si?2l*<)#x4`($jbc_3?< zNtQ_<5GbAP{~nl~_{UDOBe>ZO<8Ljmn=6~zTbn5%%)?XRHnA!o{MzOHcxlZFk-XW< z8^8C32yi%QtKWK5Uhn%Og+gs{N6!s+(+Jv8B^Mh0>!ryD@Xe6YgJuot<#GZ{ah_(9 zVlm4eU~$JAA(OF%b~i^5rv=|%fmA=i1WNdyG3sO9r0Oc1r>gqZfMs9<%!-cIFtn^X zoxb=uyeeQUxaR(WGwb1`pS?Z7t4RUR0MsSK;_unvqEnKrWL#kOa>L(*B~D3+vi6y) zn61p;&cXq5SAJVQ_>E40XX~%JawbcU1I}#|c8zFAliRTQ8Eu(_*Wv3qHUlkH4cc`W z!pFHrK}FTx%y?I+^`}`0Dvh_dzdd9xiU(q$0?yfCuSJjJ|1Iv!mx}|G>=4H4{+=&A z=0=fQ{(FN1{ew?R6E(-!o|%|2oIdk&ZmN3O%UIRy{J6x7?2ex$%hEB%BINsQuQnDD zS?2VGnnR&N_=xejThrfpfdgWzyy##gS(C0c>+L1v<00b9C#Xf|F5sev@RB2Cb7Up> z#MbXMPj>!!$V~#G+?1wOxT&2mrSb_9IQ0Efb39lSoMR4#g7LmTd|g{sc26hEnzR8= zvFaBB?-E)PGl(4WgFU0&{r&5ni7sz~Uzb~t$sRSQFKl27n0(^=m5RhpN2Paa^Q~KJ zp$ik(E!r*F=(jQTRu-$Y=N4D>?Ubx&?tM~d)$zu~Ho)&N7SlTcP99g01RuLt~ zspTeyxIa&-Bf1z~()Y=2nhq93OgB2ZZN||L8-Macw9S?!?I&eTT%8g})>eL$C=%XyR56d3RK3i|AFaJKdwfb-e zR-lhUHvy&X4_YGL6gT%?%lBy&1z-v}Gt)kI4@!sQ<`w@E*HYc!Qio`(Xp2YM<=OtQ zb-|9}^6E;L5vTNDMO1wM#HbPYVi&SMEh}3<@ca7$VP_sg@qFM=e>M#bJl}=P!|+xx zz8+km_7Op6#V2}nvN)c|=#SXT#jg2=;x(mRWE-35vuB=Ybc}TO&pzw}PA|s9X2bp5 z;MceFKS%>M2U9Ign}NF;Xg6RO+-}$~LUPMLi$oPnQfN{9hEGG9QLLP(2k-IPLyAqN zCCU$xH3MtSs)Zf49pVKopt6;A=;z$>UcT2Ltuyl&j3m7lLMB z_iR(eU`V9q!XTz4R8iO1+h%cN0;hKbk2&8^z`(em^1Qb2)9ph?sZfKLDJAW>mEK7- z@>mZ!w}JY~U_hQ3P&?k0TtbmF1nyu1JCVg)YZRXeO+z(@RGM>hvy$_26pi&u{wFG% zRGbInPJuun+$X85<`-VXCjlTVo|1y{K#pV1Pl=PL2bs#Szmx2XEWusPDaQk`47Owy zu)(G5uC~@3oaaEFh43H6Ax!b80e`FGNj5zeo6kmNhhIw1mn~0z;Fxhg8y9*SVM<;>9$2icH8&d%0&%mC8e0Nh I^B%wc2V$*$IRF3v delta 1518 zcmbO&Hbsapz?+#xgn0erI3-?6YG$xZf2R2(O-=l%c(~Z~CC|jPE1s#o&iqvLvFNAjvt?15Qy6?N zdY|*u(R=ok>sx`zmC}|BwWEfu?^W{Llv_ENf~dP!?_%FL(gVn3J73X^P$y3w?S znL#eVo1Np=+55fq3=9m-K#XwV3a|?$>;2qAJp6qfgY|;lLVI`fH5o84lu!ES>@J&8 zk>TSZ;nF;bLn@myd!=aC1*s^NA73B6C_8;OG0-!sZQgCm_ge#u8uW@9TKl7~-|Ozm zPF^0;b)1J$<;Zz^p8U9T5vz8@Tcu|x3uhvaM6LRI->6~vqX}wjUv<=M6PKy}vMX=J%KZ09JoUfC zK^`iLe2}pi=$RcD9s&x$fhdsW>l)&y>*?pF5BH@@u%mHCQr)RzE3ZDg_-*d=`iXNh z9fd!eHmg1J_UY+qyTdjoXU(meGd@9Uc-Zc6xb|?*nz2vX#ITm_QLm3qSSkN@#-%qK zFFn_Zn9-Q^_+Zpb=g1o^GrhVKW%v@8-EnbFWOfv2kDZ~ta*Kw#vHo5a`|}fyH*l+* zP(2e9!}Yw-xx$H!NkMM2LAs|~U0%{gr~0^EjdLv4H!f_P*tl}x&WW9kks>p)vl7^z zUb@HV+hg4j!Tv1MO~HNM%8e5r=GPW1&RIDj?LzH(%c}f&HviRj*q(T{m-}#{q)(r_lA4y*=_e>bat`h0*t!zLU$$bgS+j`m5;lO#4LUeR;i%y=J$+-Fs=fI{8dl z%lkERHr0LCUmfmif4Fu>?#k>&&G7-(f6%FJdm% z{7<}c`Df1LU6&t8t#S?xmZ)9xfA04yNqIS`3_Fu&T~Yct*S-JvNv&0XlQ&;oWhWN- z@~`2u%<5J@~9%sb1yYteJ(4cGY;iXaZGW>=TfAPc za@r}CMe#Q8pKW{|ta|THU6JOE-xvJeYEF)qFv~N~xWjZtmhGj9f9i!bt&=ztIs2wI zy7E8y^y|}yIzRWhb8C-9&)ZwGE^yU9k7T~d9#_+jOML8M=Kta4w|tGytDAX>CeHwb%++41lr>PzDS*8CVdx=HDp>24-lP0aguE?3w5J zeHKvl0+!8^>}#0B8JR>F5M>^`teO0V)2JS30jQWk&aWa+dmz+7AcdJngWUqW5ypZ{ zKz2MRUn9UWMrD)Qf-nsXA&vVZ6KIc5|^8MrU-H{$XDCuA;bU+pa zg+f8-G!dt~=L!JE%+4B(ayqMtK_6tBiKS@EC%xf$fAV1=+4mhB7rkRM?wb#hvEOZ| zD3>;4o&Zx1PjK3VbKhPa>D59}__!PzgW(`vd&OU-1pU!l2HYX;|B#wN5+RqBNb* zkyp)dDcYd4)uX$YVXX*K?J=u+LQ1!lLR`WK2*2>nnO#VdMquGSjBj>ac z=gp=oGSXexf?XYS%7YYdYr((o<@=OpNecqS)3&^`=3SKE==z5t=Lxs_*w}=n}Xt> z?edi|5%~Yw0sqlY`hUc8bTZQm@_p(vGZeBO#2a|hJ8++zX)w&s{LH-Pxl>6+IeJx3 zQ*}t!(=zi&9Z8B+xp*@f>aYB)Gn0{75)6Q&;c&_HsF9gVlU9C^;8cp=EF^?#Fl#vd zv!A5Dk4%85gyAdzE)kjy6QM?{6sjB+mFFZs_^tE9KDaiJR*%*~2yY*u z(;;$@LNo*pNe?)q)KFEGY+PVlyN0=9(<=$tA<{DQDg}-WFo(K(dpW+D?ys>gt8Ir> zK0U~tUkfk!D5@ZKOTDtwRr8JR9DRM2Fh3f;K7L6hVGKxYvawtl@3S;9b=0&O_hS7M zr!&&L$Ozm|#rKQ?Y$l915W7k*>UhXqt(~Xdk(ly$y|U!YtaH+Jb6FmGQM}Ly3#Ewi zB8L_>Q^q&Nbz5v;C#czs$ntK&I=pAr^g@kEo*^>&!pFBn8Lh;{7kKURZVxYP9&+si zt#g3}G+JP0oD#)6a>B&N7Jg9ndyhut1**1`>5n$VdHtNV9C+MwbH%=0QL2`r-E=Hy z!ZCphY#$<3fSD*ss-Rl5oW2J!tCBwJFea+Esv3Ulr!lLK$oBVh&Z8b`=Q?oPNV}OT zV;MbVp&4J4P>hh9cT*qtZpPgV{gP!0b!!pe%uU$TbLOIITBw7#m^8U1Ho1w8pWPXk zVDSrGPhSKG=PuA= z6a-MWyi~Dex4FDt#tc=h^-@_&p&QK`U%5M1+gRy-QrXnMsC5!6;WXLo>d8$5X7`)V z2RbpPtFm^p3Pw#P6hazq{rhk=_k7ex7lZgW$0l9k)Dz4zQ6z`Qti6iwMBRQs8pX5S zX(5~bwpwY8u(+iLyc`hvTMa83yLq~HYiM}lnp?f=e2isi2%{R03hXLHSgsRS((&2m ziT$Rb)?52kH>TS;jHc=zv*~rf{x+h-G!)kgklSw1qF$Fj=&`u&PnSce6;4h1$M2D! zr_HHvC>ZLj3F$$Nw2c&^9g7{#tRHf0aewx&u2X`rjWTw6@95Ae$dRs)-fIPO2+^8WQ!ki)xpO@C?2ma%@4AfjOo@OSd}{Kf&wOe# zYyMNl!^?&6pGxEv4C|4ca?H*KuCU*pT3TwXU_@=PdxSK;s-rnfkV@@ib{UveB;VN| zrkucu4aBx}P(FyTEOm0O^m8@dMyOy?|AGtn* zb$5HUQE$vySoNZf0unr!Ec`(4A;w^7Xhh%YL`PQ$H!VvvKRZo#IL7w-Ne-vw&Yp*?k}_5lzN$P`m{}r&iIA!&1L(XhD#Uy_ZGO-NoSgvH!mkt z2V;wAF+M9W=JCx$bOL_6t-G!ZpufXm7$YNoAw%Ypr^C&I4-QXUkJG@t_wYG`Yi!5B z+7Sl26#LiqRL1vAog2(q5BWbpCY~itNjd-mg@L~Y*u|6Y5R?Ud@yf67|4hp-Atm_tX+Ar@8V7^^cx4jw xu;2iMSO%3BfD)UbN-AQ)Adm$v5*wlEchM(2+`$$M`Ftptzx4RD&Jp>%`yC0CeEI+Y delta 1481 zcmca6`b&^6z?+#xgn-U(ctDkqx*F$ z>q`Z8h5&DN4xxm$C5;RW3@t#6?ncS_U{7~HH%}i|y*iUGGPmIA%A2g6H10XPr^vV2`b9CbbY-1Oo8bP0Ae&Pe)q_}I#;&n|wepF4fx z+)PK|&(Y0l&!+qI^t9b!o0GHVR?Qiopfx;fcQ{;o99(l8Tz%Mleb{G2yy07K%Ivk7 zdFlDc4F=3tmo;xSYTvYh)3}xGu!YPapL2a}PHapHe7g;n7iT(V1$w5%?NjV$6!+-y zo^kWy$(sQ;90ZO$7JJ5}q3d0;{7G%KDyUn(YjqVuzq zg!Bw4riG0=H+qW9$WF}Qd3x!*qHoXb#t3#Xjvj|To8V;S!}otZaJw0#cy__>xZ*GO zY%2fx7F16-TP@ypxab@2ZKkV6vB|PinCjhceRKPBtNzPtz2^Mo>Fv*A^0(woFg^Ky z%Crsjw$*6|E~$QgzCU55Sb)`&{nbyu*5B^;{J(*(zAopeQDEJ)`)BX#$xpRDlOm-g zqiS~XMfA((rMEh-Z@pI^lr(Kl^~L6o7Lzp&e`#r`3ru}yJX`H;PSlrOt-qaH&V*06 zyw5)7LRIdzw|g&FhaI2smg9b;W$NE|@nP#{)wTUDxV@>~d?~wI+xNG-gkJt%Ga+`t z#>DRB5eq+Y%kvsOeEZz8x5`haIzu_^s%+5Z)gKc+T3Nn5d)iC=neMvh|CVOV`tq?n zNOW=6*O{vF-`8@?xv+E5&wqzkEdP8{t#tWO(~$O6%M5-+{I`C;^5~r#hYno1ArN?c zdw$o9DbJ7IiukAUtbU?xeVw$$IoTh3K70L%3Ag^6H}y_a?0=mi6+PL%sa0h!Up2qY zd|vjaPGWma@3+m}&yHI!FK^d353>CB;P19OHPRUlohrXJdc*NLg^MVV8UT^XpHZw+s&BE->OajmX z4PJ~)UdCxu4;4hth$8Te2VxusV$94J>=xk7$RxsmC?`RVfVlybVG&>zBQ_I&*%xR8 zFWd~UYh$>iq+bC&0k`nqDUgp~Hcg($rJ$of(protocols)); } - private static void removeFromDisabledAlgs(String prop, List algs) { + /** + * Removes constraints that contain the specified constraint from the + * specified security property. For example, List.of("SHA1") will remove + * any constraint containing "SHA1". + */ + public static void removeFromDisabledAlgs(String prop, + List constraints) { String value = Security.getProperty(prop); value = Arrays.stream(value.split(",")) .map(s -> s.trim()) - .filter(s -> !algs.contains(s)) + .filter(s -> constraints.stream() + .allMatch(constraint -> !s.contains(constraint))) .collect(Collectors.joining(",")); Security.setProperty(prop, value); } -- GitLab From 0fc47e99d20a1ee886df878f1302769bdd913aab Mon Sep 17 00:00:00 2001 From: Pavel Rappo Date: Tue, 21 Sep 2021 15:53:35 +0000 Subject: [PATCH 051/544] 8266666: Implementation for snippets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jonathan Gibbons Co-authored-by: Hannes Wallnöfer Reviewed-by: jjg --- .../javax/tools/DocumentationTool.java | 9 +- .../com/sun/source/doctree/AttributeTree.java | 4 +- .../com/sun/source/doctree/DocTree.java | 8 +- .../sun/source/doctree/DocTreeVisitor.java | 15 + .../com/sun/source/doctree/SnippetTree.java | 69 + .../com/sun/source/util/DocTreeFactory.java | 14 +- .../com/sun/source/util/DocTreeScanner.java | 17 + .../sun/source/util/SimpleDocTreeVisitor.java | 15 + .../tools/javac/parser/DocCommentParser.java | 96 +- .../com/sun/tools/javac/tree/DCTree.java | 30 + .../com/sun/tools/javac/tree/DocPretty.java | 21 + .../sun/tools/javac/tree/DocTreeMaker.java | 11 +- .../formats/html/HtmlDocletWriter.java | 127 + .../formats/html/TagletWriterImpl.java | 80 + .../formats/html/markup/HtmlStyle.java | 6 + .../html/resources/standard.properties | 6 + .../doclets/toolkit/BaseConfiguration.java | 30 +- .../internal/doclets/toolkit/BaseOptions.java | 22 + .../toolkit/resources/doclets.properties | 52 +- .../doclets/toolkit/resources/stylesheet.css | 21 + .../toolkit/taglets/SnippetTaglet.java | 367 +++ .../toolkit/taglets/TagletManager.java | 1 + .../doclets/toolkit/taglets/TagletWriter.java | 12 + .../toolkit/taglets/snippet/Action.java | 43 + .../toolkit/taglets/snippet/AddStyle.java | 70 + .../toolkit/taglets/snippet/Attribute.java | 113 + .../toolkit/taglets/snippet/Attributes.java | 78 + .../toolkit/taglets/snippet/Bookmark.java | 56 + .../toolkit/taglets/snippet/MarkupParser.java | 236 ++ .../taglets/snippet/ParseException.java | 60 + .../toolkit/taglets/snippet/Parser.java | 531 ++++ .../toolkit/taglets/snippet/Replace.java | 85 + .../toolkit/taglets/snippet/Style.java | 58 + .../toolkit/taglets/snippet/StyledText.java | 343 +++ .../doclets/toolkit/util/CommentHelper.java | 41 +- .../jdk/javadoc/internal/doclint/Checker.java | 10 + .../CheckStylesheetClasses.java | 3 + .../doclet/testSnippetTag/TestSnippetTag.java | 2380 +++++++++++++++++ .../doclet/testTaglets/TestTaglets.out | 1 + .../basic/DocumentationToolLocationTest.java | 4 +- .../tools/doclint/EmptyHtmlTest.java | 9 +- .../tools/javac/doctree/DocCommentTester.java | 14 +- .../tools/javac/doctree/SnippetTest.java | 61 + 43 files changed, 5204 insertions(+), 25 deletions(-) create mode 100644 src/jdk.compiler/share/classes/com/sun/source/doctree/SnippetTree.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/SnippetTaglet.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Action.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/AddStyle.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Attribute.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Attributes.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Bookmark.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/MarkupParser.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/ParseException.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Parser.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Replace.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/Style.java create mode 100644 src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/snippet/StyledText.java create mode 100644 test/langtools/jdk/javadoc/doclet/testSnippetTag/TestSnippetTag.java create mode 100644 test/langtools/tools/javac/doctree/SnippetTest.java diff --git a/src/java.compiler/share/classes/javax/tools/DocumentationTool.java b/src/java.compiler/share/classes/javax/tools/DocumentationTool.java index b7e3af636d5..859ec424f5c 100644 --- a/src/java.compiler/share/classes/javax/tools/DocumentationTool.java +++ b/src/java.compiler/share/classes/javax/tools/DocumentationTool.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -184,7 +184,12 @@ public interface DocumentationTool extends Tool, OptionChecker { /** * Location to search for taglets. */ - TAGLET_PATH; + TAGLET_PATH, + + /** + * Location to search for snippets. + */ + SNIPPET_PATH; public String getName() { return name(); } diff --git a/src/jdk.compiler/share/classes/com/sun/source/doctree/AttributeTree.java b/src/jdk.compiler/share/classes/com/sun/source/doctree/AttributeTree.java index b3f3b324d1f..facdbb79567 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/doctree/AttributeTree.java +++ b/src/jdk.compiler/share/classes/com/sun/source/doctree/AttributeTree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ import java.util.List; import javax.lang.model.element.Name; /** - * A tree node for an attribute in an HTML element. + * A tree node for an attribute in an HTML element or tag. * * @since 1.8 */ diff --git a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java index be317c28bad..b0375d200c3 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java +++ b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java @@ -37,7 +37,7 @@ public interface DocTree { enum Kind { /** * Used for instances of {@link AttributeTree} - * representing an HTML attribute. + * representing an attribute in an HTML element or tag. */ ATTRIBUTE, @@ -204,6 +204,12 @@ public interface DocTree { */ SINCE("since"), + /** + * Used for instances of {@link SnippetTree} + * representing an {@code @snippet} tag. + */ + SNIPPET("snippet"), + /** * Used for instances of {@link EndElementTree} * representing the start of an HTML element. diff --git a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTreeVisitor.java b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTreeVisitor.java index 33ef57dd879..dc1e6a8deca 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTreeVisitor.java +++ b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTreeVisitor.java @@ -287,6 +287,21 @@ public interface DocTreeVisitor { */ R visitSince(SinceTree node, P p); + /** + * Visits a {@code SnippetTree} node. + * + * @implSpec Visits the provided {@code SnippetTree} node + * by calling {@code visitOther(node, p)}. + * + * @param node the node being visited + * @param p a parameter value + * @return a result value + * @since 18 + */ + default R visitSnippet(SnippetTree node, P p) { + return visitOther(node, p); + } + /** * Visits a {@code StartElementTree} node. * @param node the node being visited diff --git a/src/jdk.compiler/share/classes/com/sun/source/doctree/SnippetTree.java b/src/jdk.compiler/share/classes/com/sun/source/doctree/SnippetTree.java new file mode 100644 index 00000000000..9247b790fda --- /dev/null +++ b/src/jdk.compiler/share/classes/com/sun/source/doctree/SnippetTree.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.source.doctree; + +import java.util.List; + +/** + * A tree node for an {@code @snippet} inline tag. + * + *
+ *    {@snippet :
+ *     body
+ *    }
+ *
+ *    {@snippet attributes}
+ *
+ *    {@snippet attributes :
+ *     body
+ *    }
+ * 
+ * + * @since 18 + */ +public interface SnippetTree extends InlineTagTree { + + /** + * Returns the list of the attributes of the {@code @snippet} tag. + * + * @return the list of the attributes + */ + List getAttributes(); + + /** + * Returns the body of the {@code @snippet} tag, or {@code null} if there is no body. + * + * @apiNote + * An instance of {@code SnippetTree} with an empty body differs from an + * instance of {@code SnippetTree} with no body. + * If a tag has no body, then calling this method returns {@code null}. + * If a tag has an empty body, then this method returns a {@code TextTree} + * whose {@link TextTree#getBody()} returns an empty string. + * + * @return the body of the tag, or {@code null} if there is no body + */ + TextTree getBody(); +} diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeFactory.java b/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeFactory.java index 8499273e8ab..52c859fb728 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeFactory.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,7 @@ import com.sun.source.doctree.SerialDataTree; import com.sun.source.doctree.SerialFieldTree; import com.sun.source.doctree.SerialTree; import com.sun.source.doctree.SinceTree; +import com.sun.source.doctree.SnippetTree; import com.sun.source.doctree.StartElementTree; import com.sun.source.doctree.SummaryTree; import com.sun.source.doctree.SystemPropertyTree; @@ -79,7 +80,7 @@ import com.sun.source.doctree.VersionTree; */ public interface DocTreeFactory { /** - * Creates a new {@code AttributeTree} object, to represent an HTML attribute in an HTML tag. + * Creates a new {@code AttributeTree} object, to represent an attribute in an HTML element or tag. * @param name the name of the attribute * @param vkind the kind of the attribute value * @param value the value, if any, of the attribute @@ -326,6 +327,15 @@ public interface DocTreeFactory { */ SinceTree newSinceTree(List text); + /** + * Creates a new {@code SnippetTree} object, to represent a {@code {@snippet }} tag. + * @param attributes the attributes of the tag + * @param text the body of the tag, or {@code null} if the tag has no body (not to be confused with an empty body) + * @return a {@code SnippetTree} object + * @since 18 + */ + SnippetTree newSnippetTree(List attributes, TextTree text); + /** * Creates a new {@code StartElementTree} object, to represent the start of an HTML element. * @param name the name of the HTML element diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java b/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java index 54ce3b12ffa..ef92d0b52b5 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java @@ -492,6 +492,23 @@ public class DocTreeScanner implements DocTreeVisitor { return scan(node.getBody(), p); } + /** + * {@inheritDoc} + * + * @implSpec This implementation scans the children in left to right order. + * + * @param node {@inheritDoc} + * @param p {@inheritDoc} + * @return the result of scanning + * @since 18 + */ + @Override + public R visitSnippet(SnippetTree node, P p) { + R r = scan(node.getAttributes(), p); + r = scanAndReduce(node.getBody(), p, r); + return r; + } + /** * {@inheritDoc} * diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java b/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java index 2461ac4cf18..fea8778a9e0 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java @@ -448,6 +448,21 @@ public class SimpleDocTreeVisitor implements DocTreeVisitor { return defaultAction(node, p); } + /** + * {@inheritDoc} + * + * @implSpec This implementation calls {@code defaultAction}. + * + * @param node {@inheritDoc} + * @param p {@inheritDoc} + * @return the result of {@code defaultAction} + * @since 18 + */ + @Override + public R visitSnippet(SnippetTree node, P p) { + return defaultAction(node, p); + } + /** * {@inheritDoc} * diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/DocCommentParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/DocCommentParser.java index ac018124d11..ff29793cb11 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/DocCommentParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/DocCommentParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1062,6 +1062,13 @@ public class DocCommentParser { return Character.isWhitespace(ch); } + protected boolean isHorizontalWhitespace(char ch) { + // This parser treats `\f` as a line break (see `nextChar`). + // To be consistent with that behaviour, this method does the same. + // (see JDK-8273809) + return ch == ' ' || ch == '\t'; + } + protected void skipWhitespace() { while (bp < buflen && isWhitespace(ch)) { nextChar(); @@ -1397,6 +1404,93 @@ public class DocCommentParser { } }, + // {@snippet attributes : + // body} + new TagParser(TagParser.Kind.INLINE, DCTree.Kind.SNIPPET) { + @Override + DCTree parse(int pos) throws ParseException { + skipWhitespace(); + List attributes = tagAttrs(); + // expect "}" or ":" + if (ch == '}') { + nextChar(); + return m.at(pos).newSnippetTree(attributes, null); + } else if (ch == ':') { + newline = false; + // consume ':' + nextChar(); + // expect optional whitespace followed by mandatory newline + while (bp < buflen && isHorizontalWhitespace(ch)) { + nextChar(); + } + // check that we are looking at newline + if (!newline) { + if (bp >= buf.length - 1) { + throw new ParseException("dc.no.content"); + } + throw new ParseException("dc.unexpected.content"); + } + // consume newline + nextChar(); + DCText text = inlineText(WhitespaceRetentionPolicy.RETAIN_ALL); + nextChar(); + return m.at(pos).newSnippetTree(attributes, text); + } else if (bp >= buf.length - 1) { + throw new ParseException("dc.no.content"); + } else { + throw new ParseException("dc.unexpected.content"); + } + } + + /* + * Reads a series of inline snippet tag attributes. + * + * Attributes are terminated by the first of ":" (colon) or + * an unmatched "}" (closing curly). + */ + private List tagAttrs() { + ListBuffer attrs = new ListBuffer<>(); + skipWhitespace(); + while (bp < buflen && isIdentifierStart(ch)) { + int namePos = bp; + Name name = readAttributeName(); + skipWhitespace(); + List value = null; + ValueKind vkind = ValueKind.EMPTY; + if (ch == '=') { + ListBuffer v = new ListBuffer<>(); + nextChar(); + skipWhitespace(); + if (ch == '\'' || ch == '"') { + newline = false; + vkind = (ch == '\'') ? ValueKind.SINGLE : ValueKind.DOUBLE; + char quote = ch; + nextChar(); + textStart = bp; + while (bp < buflen && ch != quote) { + nextChar(); + } + addPendingText(v, bp - 1); + nextChar(); + } else { + vkind = ValueKind.UNQUOTED; + textStart = bp; + // Stop on '}' and ':' for them to be re-consumed by non-attribute parts of tag + while (bp < buflen && (ch != '}' && ch != ':' && !isUnquotedAttrValueTerminator(ch))) { + nextChar(); + } + addPendingText(v, bp - 1); + } + skipWhitespace(); + value = v.toList(); + } + DCAttribute attr = m.at(namePos).newAttributeTree(name, vkind, value); + attrs.add(attr); + } + return attrs.toList(); + } + }, + // {@summary summary-text} new TagParser(TagParser.Kind.INLINE, DCTree.Kind.SUMMARY) { @Override diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java index ec9443dc73a..079fc1577c4 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java @@ -857,6 +857,36 @@ public abstract class DCTree implements DocTree { } } + public static class DCSnippet extends DCInlineTag implements SnippetTree { + public final List attributes; + public final DCText body; + + public DCSnippet(List attributes, DCText body) { + this.body = body; + this.attributes = attributes; + } + + @Override @DefinedBy(Api.COMPILER_TREE) + public Kind getKind() { + return Kind.SNIPPET; + } + + @Override @DefinedBy(Api.COMPILER_TREE) + public R accept(DocTreeVisitor v, D d) { + return v.visitSnippet(this, d); + } + + @Override @DefinedBy(Api.COMPILER_TREE) + public List getAttributes() { + return attributes; + } + + @Override @DefinedBy(Api.COMPILER_TREE) + public TextTree getBody() { + return body; + } + } + public static class DCStartElement extends DCEndPosTree implements StartElementTree { public final Name name; public final List attrs; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocPretty.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocPretty.java index e2bf78c612a..8356c20bff2 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocPretty.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocPretty.java @@ -490,6 +490,27 @@ public class DocPretty implements DocTreeVisitor { return null; } + @Override @DefinedBy(Api.COMPILER_TREE) + public Void visitSnippet(SnippetTree node, Void p) { + try { + print("{"); + printTagName(node); + List attrs = node.getAttributes(); + if (!attrs.isEmpty()) { + print(" "); + print(attrs, " "); + } + if (node.getBody() != null) { + print(" :\n"); + print(node.getBody()); + } + print("}"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return null; + } + @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { try { diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java index f8d843ee93c..b885becb7d3 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * 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.text.BreakIterator; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.EnumSet; import java.util.List; import java.util.ListIterator; import java.util.Set; @@ -76,6 +75,7 @@ import com.sun.tools.javac.tree.DCTree.DCSerial; import com.sun.tools.javac.tree.DCTree.DCSerialData; import com.sun.tools.javac.tree.DCTree.DCSerialField; import com.sun.tools.javac.tree.DCTree.DCSince; +import com.sun.tools.javac.tree.DCTree.DCSnippet; import com.sun.tools.javac.tree.DCTree.DCStartElement; import com.sun.tools.javac.tree.DCTree.DCSummary; import com.sun.tools.javac.tree.DCTree.DCSystemProperty; @@ -431,6 +431,13 @@ public class DocTreeMaker implements DocTreeFactory { return tree; } + @Override @DefinedBy(Api.COMPILER_TREE) + public DCSnippet newSnippetTree(List attributes, TextTree text) { + DCSnippet tree = new DCSnippet(cast(attributes), (DCText) text); + tree.pos = pos; + return tree; + } + @Override @DefinedBy(Api.COMPILER_TREE) public DCStartElement newStartElementTree(Name name, List attrs, boolean selfClosing) { DCStartElement tree = new DCStartElement(name, cast(attrs), selfClosing); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java index 0d6400b871f..bca521bfe34 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java @@ -1142,6 +1142,133 @@ public class HtmlDocletWriter { } } + // TODO: this method and seeTagToContent share much of the code; consider factoring common pieces out + public Content linkToContent(Element referrer, Element target, String targetSignature, String text) { + CommentHelper ch = utils.getCommentHelper(referrer); + + boolean isLinkPlain = false; // TODO: for now + Content labelContent = plainOrCode(isLinkPlain, Text.of(text)); + + TypeElement refClass = ch.getReferencedClass(target); + Element refMem = ch.getReferencedMember(target); + String refMemName = ch.getReferencedMemberName(targetSignature); + + if (refMemName == null && refMem != null) { + refMemName = refMem.toString(); + } + if (refClass == null) { + ModuleElement refModule = ch.getReferencedModule(target); + if (refModule != null && utils.isIncluded(refModule)) { + return getModuleLink(refModule, labelContent); + } + //@see is not referencing an included class + PackageElement refPackage = ch.getReferencedPackage(target); + if (refPackage != null && utils.isIncluded(refPackage)) { + //@see is referencing an included package + if (labelContent.isEmpty()) + labelContent = plainOrCode(isLinkPlain, + Text.of(refPackage.getQualifiedName())); + return getPackageLink(refPackage, labelContent); + } else { + // @see is not referencing an included class, module or package. Check for cross links. + String refModuleName = ch.getReferencedModuleName(targetSignature); + DocLink elementCrossLink = (refPackage != null) ? getCrossPackageLink(refPackage) : + (configuration.extern.isModule(refModuleName)) + ? getCrossModuleLink(utils.elementUtils.getModuleElement(refModuleName)) + : null; + if (elementCrossLink != null) { + // Element cross link found + return links.createExternalLink(elementCrossLink, labelContent); + } else { + // No cross link found so print warning +// TODO: +// messages.warning(ch.getDocTreePath(see), +// "doclet.see.class_or_package_not_found", +// "@" + tagName, +// seeText); + return labelContent; + } + } + } else if (refMemName == null) { + // Must be a class reference since refClass is not null and refMemName is null. + if (labelContent.isEmpty()) { + if (!refClass.getTypeParameters().isEmpty() && targetSignature.contains("<")) { + // If this is a generic type link try to use the TypeMirror representation. + +// TODO: +// TypeMirror refType = ch.getReferencedType(target); + TypeMirror refType = target.asType(); + + if (refType != null) { + return plainOrCode(isLinkPlain, getLink( + new HtmlLinkInfo(configuration, HtmlLinkInfo.Kind.DEFAULT, refType))); + } + } + labelContent = plainOrCode(isLinkPlain, Text.of(utils.getSimpleName(refClass))); + } + return getLink(new HtmlLinkInfo(configuration, HtmlLinkInfo.Kind.DEFAULT, refClass) + .label(labelContent)); + } else if (refMem == null) { + // Must be a member reference since refClass is not null and refMemName is not null. + // However, refMem is null, so this referenced member does not exist. + return labelContent; + } else { + // Must be a member reference since refClass is not null and refMemName is not null. + // refMem is not null, so this @see tag must be referencing a valid member. + TypeElement containing = utils.getEnclosingTypeElement(refMem); + + // Find the enclosing type where the method is actually visible + // in the inheritance hierarchy. + ExecutableElement overriddenMethod = null; + if (refMem.getKind() == ElementKind.METHOD) { + VisibleMemberTable vmt = configuration.getVisibleMemberTable(containing); + overriddenMethod = vmt.getOverriddenMethod((ExecutableElement)refMem); + + if (overriddenMethod != null) + containing = utils.getEnclosingTypeElement(overriddenMethod); + } + if (targetSignature.trim().startsWith("#") && + ! (utils.isPublic(containing) || utils.isLinkable(containing))) { + // Since the link is relative and the holder is not even being + // documented, this must be an inherited link. Redirect it. + // The current class either overrides the referenced member or + // inherits it automatically. + if (this instanceof ClassWriterImpl writer) { + containing = writer.getTypeElement(); + } else if (!utils.isPublic(containing)) { +// TODO: +// messages.warning( +// ch.getDocTreePath(see), "doclet.see.class_or_package_not_accessible", +// tagName, utils.getFullyQualifiedName(containing)); + } else { +// TODO: +// messages.warning( +// ch.getDocTreePath(see), "doclet.see.class_or_package_not_found", +// tagName, seeText); + } + } + if (configuration.currentTypeElement != containing) { + refMemName = (utils.isConstructor(refMem)) + ? refMemName + : utils.getSimpleName(containing) + "." + refMemName; + } + if (utils.isExecutableElement(refMem)) { + if (refMemName.indexOf('(') < 0) { + refMemName += utils.makeSignature((ExecutableElement) refMem, null, true); + } + if (overriddenMethod != null) { + // The method to actually link. + refMem = overriddenMethod; + } + } + + return getDocLink(HtmlLinkInfo.Kind.SEE_TAG, containing, + refMem, (labelContent.isEmpty() + ? plainOrCode(isLinkPlain, Text.of(text)) + : labelContent), null, false); + } + } + private String removeTrailingSlash(String s) { return s.endsWith("/") ? s.substring(0, s.length() -1) : s; } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java index caa4a80a914..f4c352fe546 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java @@ -27,6 +27,7 @@ package jdk.javadoc.internal.doclets.formats.html; import java.util.ArrayList; import java.util.EnumSet; +import java.util.HashSet; import java.util.List; import java.util.Set; @@ -47,8 +48,10 @@ import com.sun.source.doctree.LiteralTree; import com.sun.source.doctree.ParamTree; import com.sun.source.doctree.ReturnTree; import com.sun.source.doctree.SeeTree; +import com.sun.source.doctree.SnippetTree; import com.sun.source.doctree.SystemPropertyTree; import com.sun.source.doctree.ThrowsTree; +import com.sun.source.util.DocTreePath; import jdk.javadoc.internal.doclets.formats.html.markup.ContentBuilder; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlId; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle; @@ -63,6 +66,8 @@ import jdk.javadoc.internal.doclets.toolkit.Resources; import jdk.javadoc.internal.doclets.toolkit.builders.SerializedFormBuilder; import jdk.javadoc.internal.doclets.toolkit.taglets.ParamTaglet; import jdk.javadoc.internal.doclets.toolkit.taglets.TagletWriter; +import jdk.javadoc.internal.doclets.toolkit.taglets.snippet.Style; +import jdk.javadoc.internal.doclets.toolkit.taglets.snippet.StyledText; import jdk.javadoc.internal.doclets.toolkit.util.CommentHelper; import jdk.javadoc.internal.doclets.toolkit.util.DocLink; import jdk.javadoc.internal.doclets.toolkit.util.DocPath; @@ -374,6 +379,81 @@ public class TagletWriterImpl extends TagletWriter { HtmlTree.DD(body)); } + @Override + protected Content snippetTagOutput(Element element, SnippetTree tag, StyledText content) { + HtmlTree result = new HtmlTree(TagName.PRE).setStyle(HtmlStyle.snippet); + result.add(Text.of(utils.normalizeNewlines("\n"))); + content.consumeBy((styles, sequence) -> { + CharSequence text = utils.normalizeNewlines(sequence); + if (styles.isEmpty()) { + result.add(text); + } else { + Element e = null; + String t = null; + boolean linkEncountered = false; + Set classes = new HashSet<>(); + for (Style s : styles) { + if (s instanceof Style.Name n) { + classes.add(n.name()); + } else if (s instanceof Style.Link l) { + assert !linkEncountered; // TODO: do not assert; pick the first link report on subsequent + linkEncountered = true; + t = l.target(); + e = getLinkedElement(element, t); + if (e == null) { + // TODO: diagnostic output + } + } else if (s instanceof Style.Markup) { + } else { + // TODO: transform this if...else into an exhaustive + // switch over the sealed Style hierarchy when "Pattern + // Matching for switch" has been implemented (JEP 406 + // and friends) + throw new AssertionError(styles); + } + } + Content c; + if (linkEncountered) { + assert e != null; + String line = sequence.toString(); + String strippedLine = line.strip(); + int idx = line.indexOf(strippedLine); + assert idx >= 0; // because the stripped line is a substring of the line being stripped + Text whitespace = Text.of(line.substring(0, idx)); + // If the leading whitespace is not excluded from the link, + // browsers might exhibit unwanted behavior. For example, a + // browser might display hand-click cursor while user hovers + // over that whitespace portion of the line; or use + // underline decoration. + c = new ContentBuilder(whitespace, htmlWriter.linkToContent(element, e, t, strippedLine)); + // We don't care about trailing whitespace. + } else { + c = HtmlTree.SPAN(Text.of(sequence)); + classes.forEach(((HtmlTree) c)::addStyle); + } + result.add(c); + } + }); + return result; + } + + /* + * Returns the element that is linked from the context of the referrer using + * the provided signature; returns null if such element could not be found. + * + * This method is to be used when it is the target of the link that is + * important, not the container of the link (e.g. was it an @see, + * @link/@linkplain or @snippet tags, etc.) + */ + public Element getLinkedElement(Element referer, String signature) { + var factory = utils.docTrees.getDocTreeFactory(); + var docCommentTree = utils.getDocCommentTree(referer); + var rootPath = new DocTreePath(utils.getTreePath(referer), docCommentTree); + var reference = factory.newReferenceTree(signature); + var fabricatedPath = new DocTreePath(rootPath, reference); + return utils.docTrees.getElement(fabricatedPath); + } + @Override protected Content systemPropertyTagOutput(Element element, SystemPropertyTree tag) { String tagText = tag.getPropertyName().toString(); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlStyle.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlStyle.java index f2bad722824..08900de9b7f 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlStyle.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlStyle.java @@ -75,6 +75,11 @@ public enum HtmlStyle { typeNameLabel, typeNameLink, + /** + * The class of the {@code pre} element presenting a snippet. + */ + snippet, + // // // The following constants are used for the main navigation bar that appears in the @@ -803,6 +808,7 @@ public enum HtmlStyle { * The class of the {@code body} element for the page for the class hierarchy. */ treePage, + // // diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties index 0bb526fabf5..312e42bcf04 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties @@ -538,6 +538,12 @@ doclet.usage.taglet.description=\ doclet.usage.tagletpath.description=\ The path to Taglets +doclet.usage.snippet-path.parameters=\ + + +doclet.usage.snippet-path.description=\ + The path for external snippets + doclet.usage.charset.parameters=\ doclet.usage.charset.description=\ diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java index f3943d5e610..e5f89ad2d3c 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * 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,13 @@ package jdk.javadoc.internal.doclets.toolkit; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -50,8 +54,10 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleElementVisitor14; +import javax.tools.DocumentationTool; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.DocTreePath; @@ -374,6 +380,28 @@ public abstract class BaseConfiguration { extern.checkPlatformLinks(options.linkPlatformProperties(), reporter); } typeElementCatalog = new TypeElementCatalog(includedTypeElements, this); + + String snippetPath = options.snippetPath(); + if (snippetPath != null) { + Messages messages = getMessages(); + JavaFileManager fm = getFileManager(); + if (fm instanceof StandardJavaFileManager) { + try { + List sp = Arrays.stream(snippetPath.split(File.pathSeparator)) + .map(Path::of) + .toList(); + StandardJavaFileManager sfm = (StandardJavaFileManager) fm; + sfm.setLocationFromPaths(DocumentationTool.Location.SNIPPET_PATH, sp); + } catch (IOException | InvalidPathException e) { + throw new SimpleDocletException(messages.getResources().getText( + "doclet.error_setting_snippet_path", snippetPath, e), e); + } + } else { + throw new SimpleDocletException(messages.getResources().getText( + "doclet.cannot_use_snippet_path", snippetPath)); + } + } + initTagletManager(options.customTagStrs()); options.groupPairs().forEach(grp -> { if (showModules) { diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseOptions.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseOptions.java index 492ff91a2fe..5fe0e514884 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseOptions.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseOptions.java @@ -282,6 +282,12 @@ public abstract class BaseOptions { */ private String tagletPath = null; + /** + * Argument for command-line option {@code --snippet-path}. + * The path for external snippets. + */ + private String snippetPath = null; + // private final BaseConfiguration config; @@ -554,6 +560,14 @@ public abstract class BaseOptions { } }, + new Option(resources, "--snippet-path", 1) { + @Override + public boolean process(String opt, List args) { + snippetPath = args.get(0); + return true; + } + }, + new Option(resources, "-version") { @Override public boolean process(String opt, List args) { @@ -962,6 +976,14 @@ public abstract class BaseOptions { return tagletPath; } + /** + * Argument for command-line option {@code --snippet-path}. + * The path for external snippets. + */ + public String snippetPath() { + return snippetPath; + } + protected abstract static class Option implements Doclet.Option, Comparable