From 8e29aab602560986277d72023443aa733b32799e Mon Sep 17 00:00:00 2001 From: Michail Chernov Date: Fri, 23 Dec 2016 20:44:48 +0300 Subject: [PATCH 001/130] 8171045: gc/stress/TestStressG1Humongous.java fails to allocate the heap Reviewed-by: tschatzl, kzhaldyb --- hotspot/test/ProblemList.txt | 1 - .../test/gc/stress/TestStressG1Humongous.java | 54 +++++++++++++++---- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/hotspot/test/ProblemList.txt b/hotspot/test/ProblemList.txt index 907597bd228..7a7f6a64e29 100644 --- a/hotspot/test/ProblemList.txt +++ b/hotspot/test/ProblemList.txt @@ -55,7 +55,6 @@ compiler/types/correctness/OffTest.java 8066173 generic-all gc/g1/humongousObjects/objectGraphTest/TestObjectGraphAfterGC.java 8156755 generic-all gc/survivorAlignment/TestPromotionToSurvivor.java 8129886 generic-all -gc/stress/TestStressG1Humongous.java 8171045 generic-all ############################################################################# diff --git a/hotspot/test/gc/stress/TestStressG1Humongous.java b/hotspot/test/gc/stress/TestStressG1Humongous.java index cd951ea31c6..37014295f99 100644 --- a/hotspot/test/gc/stress/TestStressG1Humongous.java +++ b/hotspot/test/gc/stress/TestStressG1Humongous.java @@ -28,14 +28,9 @@ * @summary Stress G1 by humongous allocations in situation near OOM * @requires vm.gc.G1 * @requires !vm.flightRecorder - * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=4m - * -Dtimeout=120 -Dthreads=3 -Dhumongoussize=1.1 -Dregionsize=4 TestStressG1Humongous - * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=16m - * -Dtimeout=120 -Dthreads=5 -Dhumongoussize=2.1 -Dregionsize=16 TestStressG1Humongous - * @run main/othervm/timeout=200 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=32m - * -Dtimeout=120 -Dthreads=4 -Dhumongoussize=0.6 -Dregionsize=32 TestStressG1Humongous - * @run main/othervm/timeout=700 -Xlog:gc=debug -Xmx1g -XX:+UseG1GC -XX:G1HeapRegionSize=1m - * -Dtimeout=600 -Dthreads=7 -Dhumongoussize=0.6 -Dregionsize=1 TestStressG1Humongous + * @library /test/lib + * @modules java.base/jdk.internal.misc + * @run driver/timeout=1300 TestStressG1Humongous */ import java.util.ArrayList; @@ -44,8 +39,45 @@ import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; -public class TestStressG1Humongous { +import jdk.test.lib.Platform; +import jdk.test.lib.Utils; +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.process.OutputAnalyzer; +public class TestStressG1Humongous{ + + public static void main(String[] args) throws Exception { + // Limit heap size on 32-bit platforms + int heapSize = Platform.is32bit() ? 512 : 1024; + // Heap size, region size, threads, humongous size, timeout + run(heapSize, 4, 3, 1.1, 120); + run(heapSize, 16, 5, 2.1, 120); + run(heapSize, 32, 4, 0.6, 120); + run(heapSize, 1, 7, 0.6, 600); + } + + private static void run(int heapSize, int regionSize, int threads, double humongousSize, int timeout) + throws Exception { + ArrayList options = new ArrayList<>(); + Collections.addAll(options, Utils.getTestJavaOpts()); + Collections.addAll(options, + "-Xlog:gc=debug", + "-Xmx" + heapSize + "m", + "-XX:+UseG1GC", + "-XX:G1HeapRegionSize=" + regionSize + "m", + "-Dtimeout=" + timeout, + "-Dthreads=" + threads, + "-Dhumongoussize=" + humongousSize, + "-Dregionsize=" + regionSize, + TestStressG1HumongousImpl.class.getName() + ); + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options.toArray(new String[options.size()])); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldHaveExitValue(0); + } +} + +class TestStressG1HumongousImpl { // Timeout in seconds private static final int TIMEOUT = Integer.getInteger("timeout", 60); private static final int THREAD_COUNT = Integer.getInteger("threads", 2); @@ -60,10 +92,10 @@ public class TestStressG1Humongous { public static final List GARBAGE = Collections.synchronizedList(new ArrayList<>()); public static void main(String[] args) throws InterruptedException { - new TestStressG1Humongous().run(); + new TestStressG1HumongousImpl().run(); } - public TestStressG1Humongous() { + public TestStressG1HumongousImpl() { isRunning = true; threads = new Thread[THREAD_COUNT]; alocatedObjectsCount = new AtomicInteger(0); From 37f332b8eeb1d3b1d7ac886ef17835e7faa39ace Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Thu, 15 Dec 2016 19:26:41 -0800 Subject: [PATCH 002/130] 8171809: Remove unused CDS code from JDK 9 Reviewed-by: jiangli, ccheung, mseledtsov --- hotspot/src/share/vm/classfile/classLoaderData.cpp | 2 +- hotspot/src/share/vm/classfile/classLoaderData.hpp | 12 ------------ .../share/vm/classfile/systemDictionaryShared.hpp | 3 --- hotspot/src/share/vm/memory/metaspaceShared.cpp | 4 ---- 4 files changed, 1 insertion(+), 20 deletions(-) diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp index fbafa936950..d1e37d82761 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.cpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp @@ -94,7 +94,7 @@ ClassLoaderData::ClassLoaderData(Handle h_class_loader, bool is_anonymous, Depen _metaspace(NULL), _unloading(false), _klasses(NULL), _modules(NULL), _packages(NULL), _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL), - _next(NULL), _dependencies(dependencies), _shared_class_loader_id(-1), + _next(NULL), _dependencies(dependencies), _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true, Monitor::_safepoint_check_never)) { TRACE_INIT_ID(this); diff --git a/hotspot/src/share/vm/classfile/classLoaderData.hpp b/hotspot/src/share/vm/classfile/classLoaderData.hpp index b69c4e681d4..8c8df5187a7 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.hpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp @@ -204,9 +204,6 @@ class ClassLoaderData : public CHeapObj { // Support for walking class loader data objects ClassLoaderData* _next; /// Next loader_datas created - // CDS - int _shared_class_loader_id; - // ReadOnly and ReadWrite metaspaces (static because only on the null // class loader for now). static Metaspace* _ro_metaspace; @@ -338,15 +335,6 @@ class ClassLoaderData : public CHeapObj { Metaspace* rw_metaspace(); void initialize_shared_metaspaces(); - int shared_class_loader_id() const { - return _shared_class_loader_id; - } - void set_shared_class_loader_id(int id) { - assert(id >= 0, "sanity"); - assert(_shared_class_loader_id <0, "cannot be assigned more than once"); - _shared_class_loader_id = id; - } - TRACE_DEFINE_TRACE_ID_METHODS; }; diff --git a/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp b/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp index 4da4869cef2..764e1eaa348 100644 --- a/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp +++ b/hotspot/src/share/vm/classfile/systemDictionaryShared.hpp @@ -29,7 +29,6 @@ #include "classfile/dictionary.hpp" class ClassFileStream; -class SerializeClosure; class SystemDictionaryShared: public SystemDictionary { public: @@ -79,8 +78,6 @@ public: return NULL; } - static void serialize(SerializeClosure* soc) {} - // The (non-application) CDS implementation supports only classes in the boot // class loader, which ensures that the verification constraints are the same // during archive creation time and runtime. Thus we can do the constraint checks diff --git a/hotspot/src/share/vm/memory/metaspaceShared.cpp b/hotspot/src/share/vm/memory/metaspaceShared.cpp index 61d6fa37b41..446517fd426 100644 --- a/hotspot/src/share/vm/memory/metaspaceShared.cpp +++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp @@ -145,10 +145,6 @@ void MetaspaceShared::serialize(SerializeClosure* soc, GrowableArray StringTable::serialize(soc, string_space, space_size); soc->do_tag(--tag); - // Dump/restore the misc information for system dictionary - SystemDictionaryShared::serialize(soc); - soc->do_tag(--tag); - soc->do_tag(666); } From f82263efb849653eb6234eca2d2f2fd37f8a57bb Mon Sep 17 00:00:00 2001 From: Dmitry Fazunenko Date: Thu, 22 Dec 2016 10:17:18 +0000 Subject: [PATCH 003/130] 8170860: Get rid of the humanReadableByteCount() method in openjdk/hotspot Reviewed-by: mgerdin, mchernov --- .../test/gc/g1/TestHumongousShrinkHeap.java | 26 +++++++------------ .../gc/g1/TestShrinkDefragmentedHeap.java | 24 +++++++---------- .../test/gc/parallel/TestDynShrinkHeap.java | 20 +++++--------- hotspot/test/gc/testlibrary/Helpers.java | 15 +++++++++++ 4 files changed, 41 insertions(+), 44 deletions(-) diff --git a/hotspot/test/gc/g1/TestHumongousShrinkHeap.java b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java index 47ea9450988..b65079020f4 100644 --- a/hotspot/test/gc/g1/TestHumongousShrinkHeap.java +++ b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java @@ -27,7 +27,7 @@ * @requires vm.gc.G1 * @summary Verify that heap shrinks after GC in the presence of fragmentation * due to humongous objects - * @library /test/lib + * @library /test/lib / * @modules java.base/jdk.internal.misc * @modules java.management/sun.management * @run main/othervm -XX:-ExplicitGCInvokesConcurrent -XX:MinHeapFreeRatio=10 @@ -40,6 +40,8 @@ import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.List; +import java.text.NumberFormat; +import gc.testlibrary.Helpers; import static jdk.test.lib.Asserts.*; public class TestHumongousShrinkHeap { @@ -70,9 +72,9 @@ public class TestHumongousShrinkHeap { System.out.format("Running with %s initial heap size of %s maximum heap size. " + "Will allocate humongous object of %s size %d times.%n", - MemoryUsagePrinter.humanReadableByteCount(TOTAL_MEMORY, false), - MemoryUsagePrinter.humanReadableByteCount(MAX_MEMORY, false), - MemoryUsagePrinter.humanReadableByteCount(HUMON_SIZE, false), + MemoryUsagePrinter.NF.format(TOTAL_MEMORY), + MemoryUsagePrinter.NF.format(MAX_MEMORY), + MemoryUsagePrinter.NF.format(HUMON_SIZE), HUMON_COUNT ); new TestHumongousShrinkHeap().test(); @@ -134,24 +136,16 @@ public class TestHumongousShrinkHeap { */ class MemoryUsagePrinter { - public static String humanReadableByteCount(long bytes, boolean si) { - int unit = si ? 1000 : 1024; - if (bytes < unit) { - return bytes + " B"; - } - int exp = (int) (Math.log(bytes) / Math.log(unit)); - String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); - return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); - } + public static final NumberFormat NF = Helpers.numberFormatter(); public static void printMemoryUsage(String label) { MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted(); System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n", label, - humanReadableByteCount(memusage.getInit(), false), - humanReadableByteCount(memusage.getUsed(), false), - humanReadableByteCount(memusage.getCommitted(), false), + NF.format(memusage.getInit()), + NF.format(memusage.getUsed()), + NF.format(memusage.getCommitted()), freeratio * 100 ); } diff --git a/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java b/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java index fa3126f2498..f15439e702f 100644 --- a/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java +++ b/hotspot/test/gc/g1/TestShrinkDefragmentedHeap.java @@ -31,7 +31,7 @@ * "..................................H" * 3. invoke gc and check that memory returned to the system (amount of committed memory got down) * - * @library /test/lib + * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management/sun.management */ @@ -39,10 +39,12 @@ import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.List; +import java.text.NumberFormat; import static jdk.test.lib.Asserts.*; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import com.sun.management.HotSpotDiagnosticMXBean; +import gc.testlibrary.Helpers; public class TestShrinkDefragmentedHeap { // Since we store all the small objects, they become old and old regions are also allocated at the bottom of the heap @@ -114,8 +116,8 @@ public class TestShrinkDefragmentedHeap { private void allocate() { System.out.format("Will allocate objects of small size = %s and humongous size = %s", - MemoryUsagePrinter.humanReadableByteCount(SMALL_OBJS_SIZE, false), - MemoryUsagePrinter.humanReadableByteCount(HUMONG_OBJS_SIZE, false) + MemoryUsagePrinter.NF.format(SMALL_OBJS_SIZE), + MemoryUsagePrinter.NF.format(HUMONG_OBJS_SIZE) ); for (int i = 0; i < ALLOCATE_COUNT; i++) { @@ -170,24 +172,16 @@ public class TestShrinkDefragmentedHeap { */ static class MemoryUsagePrinter { - public static String humanReadableByteCount(long bytes, boolean si) { - int unit = si ? 1000 : 1024; - if (bytes < unit) { - return bytes + " B"; - } - int exp = (int) (Math.log(bytes) / Math.log(unit)); - String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); - return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); - } + public static final NumberFormat NF = Helpers.numberFormatter(); public static void printMemoryUsage(String label) { MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted(); System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n", label, - humanReadableByteCount(memusage.getInit(), false), - humanReadableByteCount(memusage.getUsed(), false), - humanReadableByteCount(memusage.getCommitted(), false), + NF.format(memusage.getInit()), + NF.format(memusage.getUsed()), + NF.format(memusage.getCommitted()), freeratio * 100 ); } diff --git a/hotspot/test/gc/parallel/TestDynShrinkHeap.java b/hotspot/test/gc/parallel/TestDynShrinkHeap.java index 4b6e7d21d24..f5e78ab7346 100644 --- a/hotspot/test/gc/parallel/TestDynShrinkHeap.java +++ b/hotspot/test/gc/parallel/TestDynShrinkHeap.java @@ -28,15 +28,17 @@ * @summary Verify that the heap shrinks after full GC according to the current values of the Min/MaxHeapFreeRatio flags * @modules java.base/jdk.internal.misc * @modules jdk.management - * @library /test/lib + * @library /test/lib / * @run main/othervm -XX:+UseAdaptiveSizePolicyWithSystemGC -XX:+UseParallelGC -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -Xmx1g -verbose:gc TestDynShrinkHeap */ import jdk.test.lib.DynamicVMOption; import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.util.ArrayList; +import java.text.NumberFormat; import static jdk.test.lib.Asserts.assertLessThan; import com.sun.management.HotSpotDiagnosticMXBean; +import gc.testlibrary.Helpers; public class TestDynShrinkHeap { @@ -101,24 +103,16 @@ public class TestDynShrinkHeap { */ class MemoryUsagePrinter { - public static String humanReadableByteCount(long bytes, boolean si) { - int unit = si ? 1000 : 1024; - if (bytes < unit) { - return bytes + " B"; - } - int exp = (int) (Math.log(bytes) / Math.log(unit)); - String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); - return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); - } + public static final NumberFormat NF = Helpers.numberFormatter(); public static void printMemoryUsage(String label) { MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted(); System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n", label, - humanReadableByteCount(memusage.getInit(), true), - humanReadableByteCount(memusage.getUsed(), true), - humanReadableByteCount(memusage.getCommitted(), true), + NF.format(memusage.getInit()), + NF.format(memusage.getUsed()), + NF.format(memusage.getCommitted()), freeratio * 100 ); } diff --git a/hotspot/test/gc/testlibrary/Helpers.java b/hotspot/test/gc/testlibrary/Helpers.java index e18640fe39a..b70b1631859 100644 --- a/hotspot/test/gc/testlibrary/Helpers.java +++ b/hotspot/test/gc/testlibrary/Helpers.java @@ -31,6 +31,9 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; public class Helpers { @@ -320,4 +323,16 @@ public class Helpers { } } + /** + * @return a number formatter instance which prints numbers in a human + * readable form, like 9_223_372_036_854_775_807. + */ + public static NumberFormat numberFormatter() { + DecimalFormat df = new DecimalFormat(); + DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); + dfs.setGroupingSeparator('_'); + dfs.setDecimalSeparator('.'); + df.setDecimalFormatSymbols(dfs); + return df; + } } From 43b7b1bd770c79dc05464b838bce56267c58466d Mon Sep 17 00:00:00 2001 From: Arno Zeller Date: Thu, 22 Dec 2016 16:51:25 +0100 Subject: [PATCH 004/130] 8171924: Use SIZE_FORMAT to print size_t values Reviewed-by: dholmes, tschatzl, coleenp, goetz --- hotspot/src/share/vm/code/codeCache.cpp | 9 +++++---- hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp | 8 ++++---- hotspot/src/share/vm/prims/jniCheck.cpp | 4 ++-- hotspot/src/share/vm/prims/jvmtiEnter.xsl | 2 +- hotspot/src/share/vm/services/diagnosticCommand.cpp | 2 +- hotspot/src/share/vm/utilities/copy.cpp | 2 +- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/hotspot/src/share/vm/code/codeCache.cpp b/hotspot/src/share/vm/code/codeCache.cpp index 80ce54f847e..bfe643ab683 100644 --- a/hotspot/src/share/vm/code/codeCache.cpp +++ b/hotspot/src/share/vm/code/codeCache.cpp @@ -149,16 +149,17 @@ void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t total_size = non_nmethod_size + profiled_size + non_profiled_size; // Prepare error message const char* error = "Invalid code heap sizes"; - err_msg message("NonNMethodCodeHeapSize (%zuK) + ProfiledCodeHeapSize (%zuK) + NonProfiledCodeHeapSize (%zuK) = %zuK", + err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)" + " + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K", non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K); if (total_size > cache_size) { // Some code heap sizes were explicitly set: total_size must be <= cache_size - message.append(" is greater than ReservedCodeCacheSize (%zuK).", cache_size/K); + message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K); vm_exit_during_initialization(error, message); } else if (all_set && total_size != cache_size) { // All code heap sizes were explicitly set: total_size must equal cache_size - message.append(" is not equal to ReservedCodeCacheSize (%zuK).", cache_size/K); + message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K); vm_exit_during_initialization(error, message); } } @@ -267,7 +268,7 @@ void CodeCache::initialize_heaps() { uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3); if (non_nmethod_size < (min_code_cache_size + code_buffers_size)) { vm_exit_during_initialization(err_msg( - "Not enough space in non-nmethod code heap to run VM: %zuK < %zuK", + "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K", non_nmethod_size/K, (min_code_cache_size + code_buffers_size)/K)); } diff --git a/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp b/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp index 42069703b27..93b07b21e2d 100644 --- a/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp +++ b/hotspot/src/share/vm/gc/g1/g1BiasedArray.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,12 +69,12 @@ protected: void initialize(HeapWord* bottom, HeapWord* end, size_t target_elem_size_in_bytes, size_t mapping_granularity_in_bytes) { assert(mapping_granularity_in_bytes > 0, "just checking"); assert(is_power_of_2(mapping_granularity_in_bytes), - "mapping granularity must be power of 2, is %zd", mapping_granularity_in_bytes); + "mapping granularity must be power of 2, is " SIZE_FORMAT, mapping_granularity_in_bytes); assert((uintptr_t)bottom % mapping_granularity_in_bytes == 0, - "bottom mapping area address must be a multiple of mapping granularity %zd, is " PTR_FORMAT, + "bottom mapping area address must be a multiple of mapping granularity " SIZE_FORMAT ", is " PTR_FORMAT, mapping_granularity_in_bytes, p2i(bottom)); assert((uintptr_t)end % mapping_granularity_in_bytes == 0, - "end mapping area address must be a multiple of mapping granularity %zd, is " PTR_FORMAT, + "end mapping area address must be a multiple of mapping granularity " SIZE_FORMAT ", is " PTR_FORMAT, mapping_granularity_in_bytes, p2i(end)); size_t num_target_elems = pointer_delta(end, bottom, mapping_granularity_in_bytes); idx_t bias = (uintptr_t)bottom / mapping_granularity_in_bytes; diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp index ea80b5b8110..9ba9e1ad419 100644 --- a/hotspot/src/share/vm/prims/jniCheck.cpp +++ b/hotspot/src/share/vm/prims/jniCheck.cpp @@ -238,8 +238,8 @@ functionExit(JavaThread* thr) size_t live_handles = handles->get_number_of_live_handles(); if (live_handles > planned_capacity) { IN_VM( - tty->print_cr("WARNING: JNI local refs: %zu, exceeds capacity: %zu", - live_handles, planned_capacity); + tty->print_cr("WARNING: JNI local refs: " SIZE_FORMAT ", exceeds capacity: " SIZE_FORMAT, + live_handles, planned_capacity); thr->print_stack(); ) // Complain just the once, reset to current + warn threshold diff --git a/hotspot/src/share/vm/prims/jvmtiEnter.xsl b/hotspot/src/share/vm/prims/jvmtiEnter.xsl index 3ce93d1f289..3c426424f39 100644 --- a/hotspot/src/share/vm/prims/jvmtiEnter.xsl +++ b/hotspot/src/share/vm/prims/jvmtiEnter.xsl @@ -1246,7 +1246,7 @@ static jvmtiError JNICALL - =0x%zx + =" SIZE_FORMAT_HEX " diff --git a/hotspot/src/share/vm/services/diagnosticCommand.cpp b/hotspot/src/share/vm/services/diagnosticCommand.cpp index d9e8a628e8a..fd389322e4b 100644 --- a/hotspot/src/share/vm/services/diagnosticCommand.cpp +++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp @@ -292,7 +292,7 @@ void JVMTIAgentLoadDCmd::execute(DCmdSource source, TRAPS) { char *opt = (char *)os::malloc(opt_len, mtInternal); if (opt == NULL) { output()->print_cr("JVMTI agent attach failed: " - "Could not allocate %zu bytes for argument.", + "Could not allocate " SIZE_FORMAT " bytes for argument.", opt_len); return; } diff --git a/hotspot/src/share/vm/utilities/copy.cpp b/hotspot/src/share/vm/utilities/copy.cpp index b04d6519319..7ccf0059351 100644 --- a/hotspot/src/share/vm/utilities/copy.cpp +++ b/hotspot/src/share/vm/utilities/copy.cpp @@ -214,7 +214,7 @@ private: case 2: do_conjoint_swap(src, dst, byte_count); break; case 4: do_conjoint_swap(src, dst, byte_count); break; case 8: do_conjoint_swap(src, dst, byte_count); break; - default: guarantee(false, "do_conjoint_swap: Invalid elem_size %zd\n", elem_size); + default: guarantee(false, "do_conjoint_swap: Invalid elem_size " SIZE_FORMAT "\n", elem_size); } } }; From 9b98f88304ed9f18ccb9a7f57cc62cac5324f7db Mon Sep 17 00:00:00 2001 From: Lutz Schmidt Date: Thu, 22 Dec 2016 15:01:20 -0600 Subject: [PATCH 005/130] 8170981: Possible access to char array with negative index Check arithmetic before trying to access array by index. Reviewed-by: rprotacio, dholmes, gziemski --- hotspot/src/share/vm/runtime/globals.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/runtime/globals.cpp b/hotspot/src/share/vm/runtime/globals.cpp index 68ec6b058cc..3262ab279ab 100644 --- a/hotspot/src/share/vm/runtime/globals.cpp +++ b/hotspot/src/share/vm/runtime/globals.cpp @@ -469,14 +469,18 @@ void Flag::print_on(outputStream* st, bool withComments, bool printRanges) { } if (!printRanges) { + // Use some named constants to make code more readable. + const unsigned int nSpaces = 10; + const unsigned int maxFlagLen = 40 + nSpaces; + // The print below assumes that the flag name is 40 characters or less. // This works for most flags, but there are exceptions. Our longest flag // name right now is UseAdaptiveGenerationSizePolicyAtMajorCollection and // its minor collection buddy. These are 48 characters. We use a buffer of - // 10 spaces below to adjust the space between the flag value and the + // nSpaces spaces below to adjust the space between the flag value and the // column of flag type and origin that is printed in the end of the line. - char spaces[10 + 1] = " "; - st->print("%9s %-40s = ", _type, _name); + char spaces[nSpaces + 1] = " "; + st->print("%9s %-*s = ", _type, maxFlagLen-nSpaces, _name); if (is_bool()) { st->print("%-20s", get_bool() ? "true" : "false"); @@ -509,9 +513,12 @@ void Flag::print_on(outputStream* st, bool withComments, bool printRanges) { } else st->print("%-20s", ""); } - assert(strlen(_name) < 50, "Flag name is longer than expected"); - spaces[50 - MAX2((size_t)40, strlen(_name))] = '\0'; - st->print("%s", spaces); + // Make sure we do not punch a '\0' at a negative char array index. + unsigned int nameLen = (unsigned int)strlen(_name); + if (nameLen <= maxFlagLen) { + spaces[maxFlagLen - MAX2(maxFlagLen-nSpaces, nameLen)] = '\0'; + st->print("%s", spaces); + } print_kind_and_origin(st); #ifndef PRODUCT From 2d444d6f19fa6e356bfe540d601ebd40d2aebfa9 Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Thu, 22 Dec 2016 17:26:02 -0800 Subject: [PATCH 006/130] 8168792: [AOT] problems in MethodHandle with aot-compiled java.base Properly support assertions in AOT Reviewed-by: kvn --- .../jaotc/binformat/BinaryContainer.java | 44 ++++++++++--------- .../src/jdk/tools/jaotc/AOTBackend.java | 10 +++-- .../src/jdk/tools/jaotc/Main.java | 34 ++++++++++---- .../hotspot/meta/HotSpotNodePlugin.java | 6 --- hotspot/src/share/vm/aot/aotCodeHeap.cpp | 9 +++- hotspot/src/share/vm/aot/aotCodeHeap.hpp | 3 +- 6 files changed, 66 insertions(+), 40 deletions(-) diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java index 7be7a80192e..0c411fb7f1d 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java @@ -37,6 +37,7 @@ import jdk.tools.jaotc.binformat.Symbol.Binding; import jdk.tools.jaotc.binformat.Symbol.Kind; import jdk.tools.jaotc.binformat.elf.JELFRelocObject; import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig; +import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; /** * A format-agnostic container class that holds various components of a binary. @@ -257,9 +258,9 @@ public class BinaryContainer implements SymbolTable { * prefix {@code prefix}. It also initializes internal code container, symbol table and * relocation tables. */ - public BinaryContainer(GraalHotSpotVMConfig config, String jvmVersion) { - this.codeSegmentSize = config.codeSegmentSize; - this.codeEntryAlignment = config.codeEntryAlignment; + public BinaryContainer(GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig, String jvmVersion) { + this.codeSegmentSize = graalHotSpotVMConfig.codeSegmentSize; + this.codeEntryAlignment = graalHotSpotVMConfig.codeEntryAlignment; // read only, code codeContainer = new CodeContainer(".text", this); @@ -289,30 +290,31 @@ public class BinaryContainer implements SymbolTable { addGlobalSymbols(); - recordConfiguration(config); + recordConfiguration(graalHotSpotVMConfig, graphBuilderConfig); } - private void recordConfiguration(GraalHotSpotVMConfig config) { + private void recordConfiguration(GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig) { // @formatter:off - boolean[] booleanFlags = { config.cAssertions, // Debug VM - config.useCompressedOops, - config.useCompressedClassPointers, - config.compactFields, - config.useG1GC, - config.useCMSGC, - config.useTLAB, - config.useBiasedLocking, + boolean[] booleanFlags = { graalHotSpotVMConfig.cAssertions, // Debug VM + graalHotSpotVMConfig.useCompressedOops, + graalHotSpotVMConfig.useCompressedClassPointers, + graalHotSpotVMConfig.compactFields, + graalHotSpotVMConfig.useG1GC, + graalHotSpotVMConfig.useCMSGC, + graalHotSpotVMConfig.useTLAB, + graalHotSpotVMConfig.useBiasedLocking, TieredAOT.getValue(), - config.enableContended, - config.restrictContended, + graalHotSpotVMConfig.enableContended, + graalHotSpotVMConfig.restrictContended, + graphBuilderConfig.omitAssertions() }; - int[] intFlags = { config.narrowOopShift, - config.narrowKlassShift, - config.contendedPaddingWidth, - config.fieldsAllocationStyle, - config.objectAlignment, - config.codeSegmentSize, + int[] intFlags = { graalHotSpotVMConfig.narrowOopShift, + graalHotSpotVMConfig.narrowKlassShift, + graalHotSpotVMConfig.contendedPaddingWidth, + graalHotSpotVMConfig.fieldsAllocationStyle, + graalHotSpotVMConfig.objectAlignment, + graalHotSpotVMConfig.codeSegmentSize, }; // @formatter:on diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java index b5d081a51ca..3ba1067b959 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTBackend.java @@ -77,10 +77,14 @@ public class AOTBackend { this.filters = filters; providers = backend.getProviders(); codeCache = providers.getCodeCache(); - graphBuilderSuite = initGraphBuilderSuite(backend); + graphBuilderSuite = initGraphBuilderSuite(backend, main.options.compileWithAssertions); highTierContext = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.ALL); } + public PhaseSuite getGraphBuilderSuite() { + return graphBuilderSuite; + } + private Suites getSuites() { // create suites every time, as we modify options for the compiler return backend.getSuites().getDefaultSuites(); @@ -146,14 +150,14 @@ public class AOTBackend { return backend.getRuntime().getVMConfig().cAssertions; } - private static PhaseSuite initGraphBuilderSuite(HotSpotBackend backend) { + private static PhaseSuite initGraphBuilderSuite(HotSpotBackend backend, boolean compileWithAssertions) { PhaseSuite graphBuilderSuite = backend.getSuites().getDefaultGraphBuilderSuite().copy(); ListIterator> iterator = graphBuilderSuite.findPhase(GraphBuilderPhase.class); GraphBuilderConfiguration baseConfig = ((GraphBuilderPhase) iterator.previous()).getGraphBuilderConfig(); // Use all default plugins. Plugins plugins = baseConfig.getPlugins(); - GraphBuilderConfiguration aotConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true); + GraphBuilderConfiguration aotConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withOmitAssertions(!compileWithAssertions); iterator.next(); iterator.remove(); diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java index a1257b7a013..2af308732e4 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java @@ -45,6 +45,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; +import java.util.ListIterator; import java.util.Set; import java.util.stream.Stream; @@ -54,8 +55,14 @@ import jdk.tools.jaotc.collect.ClassCollector; import jdk.tools.jaotc.utils.Timer; import org.graalvm.compiler.api.runtime.GraalJVMCICompiler; +import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig; import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider; import org.graalvm.compiler.hotspot.HotSpotHostBackend; +import org.graalvm.compiler.java.GraphBuilderPhase; +import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; +import org.graalvm.compiler.phases.BasePhase; +import org.graalvm.compiler.phases.PhaseSuite; +import org.graalvm.compiler.phases.tiers.HighTierContext; import org.graalvm.compiler.runtime.RuntimeProvider; import jdk.vm.ci.meta.MetaAccessProvider; @@ -144,11 +151,16 @@ public class Main implements LogPrinter { void process(Main task, String opt, String arg) { task.options.methodList = arg; } - }, new Option(" --compile-for-tiered Generated profiling code for tiered compilation", false, "--compile-for-tiered") { + }, new Option(" --compile-for-tiered Generate profiling code for tiered compilation", false, "--compile-for-tiered") { @Override void process(Main task, String opt, String arg) { TieredAOT.setValue(true); } + }, new Option(" --compile-with-assertions Compile assertions", false, "--compile-with-assertions") { + @Override + void process(Main task, String opt, String arg) { + task.options.compileWithAssertions = true; + } }, new Option(" --classpath Specify where to find user class files", true, "--classpath", "--class-path") { @Override void process(Main task, String opt, String arg) { @@ -225,15 +237,16 @@ public class Main implements LogPrinter { */ private static final int COMPILER_THREADS = 16; - int threads = Integer.min(COMPILER_THREADS, Runtime.getRuntime().availableProcessors()); + public int threads = Integer.min(COMPILER_THREADS, Runtime.getRuntime().availableProcessors()); public boolean ignoreClassLoadingErrors; public boolean exitOnError; - boolean info; - boolean verbose; - boolean debug; - boolean help; - boolean version; + public boolean info; + public boolean verbose; + public boolean debug; + public boolean help; + public boolean version; + public boolean compileWithAssertions; } /* package */final Options options = new Options(); @@ -356,6 +369,11 @@ public class Main implements LogPrinter { AOTCompiler compiler = new AOTCompiler(this, aotBackend, options.threads); classes = compiler.compileClasses(classes); + GraalHotSpotVMConfig graalHotSpotVMConfig = runtime.getVMConfig(); + PhaseSuite graphBuilderSuite = aotBackend.getGraphBuilderSuite(); + ListIterator> iterator = graphBuilderSuite.findPhase(GraphBuilderPhase.class); + GraphBuilderConfiguration graphBuilderConfig = ((GraphBuilderPhase) iterator.previous()).getGraphBuilderConfig(); + // Free memory! try (Timer t = options.verbose ? new Timer(this, "Freeing memory") : null) { printMemoryUsage(); @@ -364,7 +382,7 @@ public class Main implements LogPrinter { System.gc(); } - BinaryContainer binaryContainer = new BinaryContainer(runtime.getVMConfig(), JVM_VERSION); + BinaryContainer binaryContainer = new BinaryContainer(graalHotSpotVMConfig, graphBuilderConfig, JVM_VERSION); DataBuilder dataBuilder = new DataBuilder(this, backend, classes, binaryContainer); dataBuilder.prepareData(); diff --git a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java index 89729e7e3f4..10b2255a3dc 100644 --- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java +++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/HotSpotNodePlugin.java @@ -22,7 +22,6 @@ */ package org.graalvm.compiler.hotspot.meta; -import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC; import static org.graalvm.compiler.core.common.GraalOptions.ImmutableCode; import static org.graalvm.compiler.hotspot.meta.HotSpotGraalConstantFieldProvider.FieldReadEnabledInImmutableCode; @@ -112,11 +111,6 @@ public final class HotSpotNodePlugin implements NodePlugin, TypePlugin { return true; } } - if (GeneratePIC.getValue()) { - if (field.isSynthetic() && field.getName().startsWith("$assertionsDisabled")) { - return tryReadField(b, field, null); - } - } if (b.parsingIntrinsic() && wordOperationPlugin.handleLoadStaticField(b, field)) { return true; } diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.cpp b/hotspot/src/share/vm/aot/aotCodeHeap.cpp index 08283a92fbe..3d0a22255da 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp @@ -25,6 +25,7 @@ #include "aot/aotCodeHeap.hpp" #include "aot/aotLoader.hpp" +#include "classfile/javaAssertions.hpp" #include "gc/g1/heapRegion.hpp" #include "gc/shared/gcLocker.hpp" #include "interpreter/abstractInterpreter.hpp" @@ -706,6 +707,12 @@ bool AOTCodeHeap::load_klass_data(instanceKlassHandle kh, Thread* thread) { return false; } + if (_lib->config()->_omitAssertions && JavaAssertions::enabled(kh->name()->as_C_string(), kh->class_loader() == NULL)) { + // Assertions are omitted in the compiled code, but are enabled right now. Bail out. + sweep_dependent_methods(klass_data); + return false; + } + NOT_PRODUCT( aot_klasses_found++; ) log_trace(aot, class, load)("found %s in %s for classloader %p tid=" INTPTR_FORMAT, kh->internal_name(), _lib->name(), kh->class_loader_data(), p2i(thread)); @@ -714,7 +721,7 @@ bool AOTCodeHeap::load_klass_data(instanceKlassHandle kh, Thread* thread) { // Set klass's Resolve (second) got cell. _metaspace_got[klass_data->_got_index] = kh(); - // Initialize global symbols of the DSO to the correspondingVM symbol values. + // Initialize global symbols of the DSO to the corresponding VM symbol values. link_global_lib_symbols(); int methods_offset = klass_data->_compiled_methods_offset; diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.hpp b/hotspot/src/share/vm/aot/aotCodeHeap.hpp index 21ce9a042f0..0e0d0038d10 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.hpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.hpp @@ -88,7 +88,7 @@ typedef struct { } AOTHeader; typedef struct { - enum { CONFIG_SIZE = 11 + 7 * 4 }; + enum { CONFIG_SIZE = 12 + 7 * 4 }; int _config_size; int _narrowOopShift; int _narrowKlassShift; @@ -108,6 +108,7 @@ typedef struct { bool _tieredAOT; bool _enableContended; bool _restrictContended; + bool _omitAssertions; } AOTConfiguration; class AOTLib : public CHeapObj { From 89bfef80d05d822e9ece715ff03f0612c4c43816 Mon Sep 17 00:00:00 2001 From: George Triantafillou Date: Thu, 22 Dec 2016 11:37:49 -0500 Subject: [PATCH 007/130] 8171318: serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java fails latest Jigsaw integration Reviewed-by: sspitsyn, dholmes --- .../sa/jmap-hprof/JMapHProfLargeHeapProc.java | 25 ++----------------- .../sa/jmap-hprof/JMapHProfLargeHeapTest.java | 3 +++ 2 files changed, 5 insertions(+), 23 deletions(-) diff --git a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java index c3dced229db..855fbad95c6 100644 --- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java +++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapProc.java @@ -21,12 +21,9 @@ * questions. */ -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +import jdk.test.lib.process.ProcessTools; import sun.management.VMManagement; @@ -38,7 +35,7 @@ public class JMapHProfLargeHeapProc { buildLargeHeap(args); // Print our pid on stdout - System.out.println("PID[" + getProcessId() + "]"); + System.out.println("PID[" + ProcessTools.getProcessId() + "]"); // Wait for input before termination System.in.read(); @@ -50,22 +47,4 @@ public class JMapHProfLargeHeapProc { } } - public static int getProcessId() throws Exception { - - // Get the current process id using a reflection hack - RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); - Field jvm = runtime.getClass().getDeclaredField("jvm"); - - jvm.setAccessible(true); - VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); - - Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); - - pid_method.setAccessible(true); - - int pid = (Integer) pid_method.invoke(mgmt); - - return pid; - } - } diff --git a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java index d2e64f75d34..a95ae0d4ff3 100644 --- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java +++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java @@ -90,6 +90,9 @@ public class JMapHProfLargeHeapTest { try (Scanner largeHeapScanner = new Scanner( largeHeapProc.getInputStream());) { String pidstring = null; + if (!largeHeapScanner.hasNext()) { + throw new RuntimeException ("Test failed: could not open largeHeapScanner."); + } while ((pidstring = largeHeapScanner.findInLine("PID\\[[0-9].*\\]")) == null) { Thread.sleep(500); } From f805a3a054059b94a25b5efbcf06e8e7510271fd Mon Sep 17 00:00:00 2001 From: Boris Molodenkov Date: Wed, 21 Dec 2016 15:01:01 +0300 Subject: [PATCH 008/130] 8170918: Remove shell script from test/compiler/c2/cr7200264/TestIntVect.java Reviewed-by: kvn --- hotspot/test/TEST.ROOT | 1 + .../test/compiler/c2/cr7200264/Test7200264.sh | 132 ------------------ .../compiler/c2/cr7200264/TestDriver.java | 68 +++++++++ .../compiler/c2/cr7200264/TestIntVect.java | 10 +- .../c2/cr7200264/TestSSE2IntVect.java | 48 +++++++ .../c2/cr7200264/TestSSE4IntVect.java | 41 ++++++ 6 files changed, 159 insertions(+), 141 deletions(-) delete mode 100644 hotspot/test/compiler/c2/cr7200264/Test7200264.sh create mode 100644 hotspot/test/compiler/c2/cr7200264/TestDriver.java create mode 100644 hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java create mode 100644 hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java diff --git a/hotspot/test/TEST.ROOT b/hotspot/test/TEST.ROOT index 45e21c61479..14d3a1c0135 100644 --- a/hotspot/test/TEST.ROOT +++ b/hotspot/test/TEST.ROOT @@ -46,6 +46,7 @@ requires.properties= \ vm.gc.Parallel \ vm.gc.ConcMarkSweep \ vm.jvmci \ + vm.cpu.features \ vm.debug # Tests using jtreg 4.2 b04 features diff --git a/hotspot/test/compiler/c2/cr7200264/Test7200264.sh b/hotspot/test/compiler/c2/cr7200264/Test7200264.sh deleted file mode 100644 index 7848bff2d70..00000000000 --- a/hotspot/test/compiler/c2/cr7200264/Test7200264.sh +++ /dev/null @@ -1,132 +0,0 @@ -#!/bin/sh -# -# Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# 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. -# -# - -## some tests require path to find test source dir -if [ "${TESTSRC}" = "" ] -then - TESTSRC=${PWD} - echo "TESTSRC not set. Using "${TESTSRC}" as default" -fi -echo "TESTSRC=${TESTSRC}" -## Adding common setup Variables for running shell tests. -. ${TESTSRC}/../../../test_env.sh - -${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -Xinternalversion | sed 's/amd64/x86/' | grep "x86" | grep "Server VM" | grep "debug" - -# Only test fastdebug Server VM on x86 -if [ $? != 0 ] -then - echo "Test Passed" - exit 0 -fi - -# grep for support integer multiply vectors (cpu with SSE4.1) -${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -XX:+PrintMiscellaneous -XX:+Verbose -version | grep "cores per cpu" | grep "sse4.1" - -if [ $? != 0 ] -then - SSE=2 -else - SSE=4 -fi - -cp ${TESTSRC}${FS}TestIntVect.java . -${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} -d . TestIntVect.java - -# CICompilerCount must be at least 2 with -TieredCompilation -${TESTJAVA}${FS}bin${FS}java ${TESTOPTS} -Xbatch -XX:-TieredCompilation \ - -XX:CICompilerCount=2 -XX:+PrintCompilation -XX:+TraceNewVectors \ - compiler.c2.cr7200264.TestIntVect > test.out 2>&1 - -COUNT=`grep AddVI test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 4 ] -then - echo "Test Failed: AddVI $COUNT < 4" - exit 1 -fi - -# AddVI is generated for test_subc -COUNT=`grep SubVI test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 4 ] -then - echo "Test Failed: SubVI $COUNT < 4" - exit 1 -fi - -# MulVI is only supported with SSE4.1. -if [ $SSE -gt 3 ] -then -# LShiftVI+SubVI is generated for test_mulc -COUNT=`grep MulVI test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 2 ] -then - echo "Test Failed: MulVI $COUNT < 2" - exit 1 -fi -fi - -COUNT=`grep AndV test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 3 ] -then - echo "Test Failed: AndV $COUNT < 3" - exit 1 -fi - -COUNT=`grep OrV test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 3 ] -then - echo "Test Failed: OrV $COUNT < 3" - exit 1 -fi - -COUNT=`grep XorV test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 3 ] -then - echo "Test Failed: XorV $COUNT < 3" - exit 1 -fi - -# LShiftVI+SubVI is generated for test_mulc -COUNT=`grep LShiftVI test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 5 ] -then - echo "Test Failed: LShiftVI $COUNT < 5" - exit 1 -fi - -COUNT=`grep RShiftVI test.out | sed '/URShiftVI/d' | wc -l | awk '{print $1}'` -if [ $COUNT -lt 3 ] -then - echo "Test Failed: RShiftVI $COUNT < 3" - exit 1 -fi - -COUNT=`grep URShiftVI test.out | wc -l | awk '{print $1}'` -if [ $COUNT -lt 3 ] -then - echo "Test Failed: URShiftVI $COUNT < 3" - exit 1 -fi - diff --git a/hotspot/test/compiler/c2/cr7200264/TestDriver.java b/hotspot/test/compiler/c2/cr7200264/TestDriver.java new file mode 100644 index 00000000000..558592ba693 --- /dev/null +++ b/hotspot/test/compiler/c2/cr7200264/TestDriver.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * 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 compiler.c2.cr7200264; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import jdk.test.lib.Asserts; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +public class TestDriver { + private final Map expectedVectorizationNumbers + = new HashMap<>(); + + public void addExpectedVectorization(String v, long num) { + expectedVectorizationNumbers.put(v, num); + } + + public void run() throws Throwable { + verifyVectorizationNumber(executeApplication()); + } + + private List executeApplication() throws Throwable { + OutputAnalyzer outputAnalyzer = ProcessTools.executeTestJvmAllArgs( + "-Xbatch", + "-XX:-TieredCompilation", + "-XX:+PrintCompilation", + "-XX:+TraceNewVectors", + TestIntVect.class.getName()); + outputAnalyzer.shouldHaveExitValue(0); + return outputAnalyzer.asLines(); + } + + private void verifyVectorizationNumber(List vectorizationLog) { + for (Map.Entry entry : expectedVectorizationNumbers.entrySet()) { + String v = "\t" + entry.getKey(); + long actualNum = vectorizationLog.stream() + .filter(s -> s.contains(v)).count(); + long expectedNum = entry.getValue(); + Asserts.assertGTE(actualNum, expectedNum, + "Unexpected " + entry.getKey() + " number"); + } + } +} diff --git a/hotspot/test/compiler/c2/cr7200264/TestIntVect.java b/hotspot/test/compiler/c2/cr7200264/TestIntVect.java index 088df3346b1..51226a8576e 100644 --- a/hotspot/test/compiler/c2/cr7200264/TestIntVect.java +++ b/hotspot/test/compiler/c2/cr7200264/TestIntVect.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * 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,14 +21,6 @@ * questions. */ -/** - * @test - * @bug 7200264 - * @summary 7192963 changes disabled shift vectors - * - * @run shell Test7200264.sh - */ - package compiler.c2.cr7200264; /* * Copy of test/compiler/6340864/TestIntVect.java without performance tests. diff --git a/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java b/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java new file mode 100644 index 00000000000..f8a3e6607d2 --- /dev/null +++ b/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * 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 7200264 + * @summary 7192963 changes disabled shift vectors + * @requires vm.cpu.features ~= ".*sse2.*" & vm.debug & vm.flavor == "server" + * @library /test/lib / + * @run driver compiler.c2.cr7200264.TestSSE2IntVect + */ + +package compiler.c2.cr7200264; + +public class TestSSE2IntVect { + public static void main(String[] args) throws Throwable { + TestDriver test = new TestDriver(); + test.addExpectedVectorization("AddVI", 4); + test.addExpectedVectorization("SubVI", 4); + test.addExpectedVectorization("AndV", 3); + test.addExpectedVectorization("OrV", 3); + test.addExpectedVectorization("XorV", 3); + test.addExpectedVectorization("LShiftVI", 5); + test.addExpectedVectorization("RShiftVI", 3); + test.addExpectedVectorization("URShiftVI", 3); + test.run(); + } +} diff --git a/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java b/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java new file mode 100644 index 00000000000..c3c2c6aa52a --- /dev/null +++ b/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * 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 7200264 + * @summary 7192963 changes disabled shift vectors + * @requires vm.cpu.features ~= ".*sse4\\.1.*" & vm.debug & vm.flavor == "server" + * @library /test/lib / + * @run driver compiler.c2.cr7200264.TestSSE4IntVect + */ + +package compiler.c2.cr7200264; + +public class TestSSE4IntVect { + public static void main(String[] args) throws Throwable { + TestDriver test = new TestDriver(); + test.addExpectedVectorization("MulVI", 2); + test.run(); + } +} From 475d592e3db89418b6a7d9ba6d71b765df26c699 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Fri, 30 Dec 2016 20:11:49 +0300 Subject: [PATCH 009/130] 8172149: CTW library should call System::exit Reviewed-by: vlivanov --- .../hotspot/tools/ctw/CompileTheWorld.java | 8 ++-- .../testlibrary_tests/ctw/ClassesDirTest.java | 10 ++--- .../ctw/ClassesListTest.java | 10 ++--- .../test/testlibrary_tests/ctw/CtwTest.java | 39 +++++++++++++++---- .../testlibrary_tests/ctw/JarDirTest.java | 10 ++--- .../test/testlibrary_tests/ctw/JarsTest.java | 10 ++--- 6 files changed, 56 insertions(+), 31 deletions(-) diff --git a/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java b/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java index 88a94f66cdf..98a3d29bfa4 100644 --- a/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java +++ b/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/CompileTheWorld.java @@ -59,6 +59,8 @@ public class CompileTheWorld { OUT = os; } + boolean passed = false; + try { try { if (ManagementFactory.getCompilationMXBean() == null) { @@ -84,10 +86,10 @@ public class CompileTheWorld { PathHandler.getClassCount(), Compiler.getMethodCount(), System.currentTimeMillis() - start); + passed = true; } finally { - if (os != null) { - os.close(); - } + // might have started new threads + System.exit(passed ? 0 : 1); } } diff --git a/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java b/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java index 31f24081fa1..e24461cdac9 100644 --- a/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java +++ b/hotspot/test/testlibrary_tests/ctw/ClassesDirTest.java @@ -30,11 +30,11 @@ * java.base/jdk.internal.reflect * java.management * @build sun.hotspot.WhiteBox Foo Bar - * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar - * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main ClassesDirTest prepare - * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld classes - * @run main ClassesDirTest check ctw.log + * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar + * sun.hotspot.WhiteBox$WhiteBoxPermission + * @run driver ClassesDirTest prepare + * @run driver ClassesDirTest compile classes + * @run driver ClassesDirTest check * @summary testing of CompileTheWorld :: classes in directory * @author igor.ignatyev@oracle.com */ diff --git a/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java b/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java index c2823de598c..5ffe27ba0c6 100644 --- a/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java +++ b/hotspot/test/testlibrary_tests/ctw/ClassesListTest.java @@ -30,11 +30,11 @@ * java.base/jdk.internal.reflect * java.management * @build sun.hotspot.WhiteBox Foo Bar - * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar - * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main ClassesListTest prepare - * @run main/othervm/timeout=600 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld classes.lst - * @run main ClassesListTest check ctw.log + * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar + * sun.hotspot.WhiteBox$WhiteBoxPermission + * @run driver ClassesListTest prepare + * @run driver/timeout=600 ClassesListTest compile classes.lst + * @run driver ClassesListTest check * @summary testing of CompileTheWorld :: list of classes in file * @author igor.ignatyev@oracle.com */ diff --git a/hotspot/test/testlibrary_tests/ctw/CtwTest.java b/hotspot/test/testlibrary_tests/ctw/CtwTest.java index 06b16b631b9..eb6aedc1fbe 100644 --- a/hotspot/test/testlibrary_tests/ctw/CtwTest.java +++ b/hotspot/test/testlibrary_tests/ctw/CtwTest.java @@ -21,6 +21,7 @@ * questions. */ +import java.util.Arrays; import java.util.List; import java.util.Collections; import java.util.ArrayList; @@ -38,8 +39,20 @@ import java.nio.charset.Charset; import jdk.test.lib.JDKToolFinder; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; public abstract class CtwTest { + private static final String LOG_FILE = "ctw.log"; + private static final String[] CTW_COMMAND = { + "-Xbootclasspath/a:.", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + "-Dsun.hotspot.tools.ctw.logfile=" + LOG_FILE, + "--add-exports", "java.base/jdk.internal.jimage=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", + sun.hotspot.tools.ctw.CompileTheWorld.class.getName(), + }; protected final String[] shouldContain; protected CtwTest(String[] shouldContain) { this.shouldContain = shouldContain; @@ -54,7 +67,10 @@ public abstract class CtwTest { prepare(); break; case "check": - check(args); + check(); + break; + case "compile": + compile(args); break; default: throw new Error("unregonized action -- " + args[0]); @@ -63,20 +79,27 @@ public abstract class CtwTest { protected void prepare() throws Exception { } - protected void check(String[] args) throws Exception { - if (args.length < 2) { - throw new Error("logfile isn't specified"); - } - String logfile = args[1]; - try (BufferedReader r = Files.newBufferedReader(Paths.get(logfile), + protected void check() throws Exception { + try (BufferedReader r = Files.newBufferedReader(Paths.get(LOG_FILE), Charset.defaultCharset())) { OutputAnalyzer output = readOutput(r); - for (String test : shouldContain) { + for (String test : shouldContain) { output.shouldContain(test); } } } + protected void compile(String[] args) throws Exception { + // concat CTW_COMMAND and args w/o 0th element + String[] cmd = Arrays.copyOf(CTW_COMMAND, CTW_COMMAND.length + args.length - 1); + System.arraycopy(args, 1, cmd, CTW_COMMAND.length, args.length - 1); + + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmd); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + dump(output, "compile"); + output.shouldHaveExitValue(0); + } + private static OutputAnalyzer readOutput(BufferedReader reader) throws IOException { StringBuilder builder = new StringBuilder(); diff --git a/hotspot/test/testlibrary_tests/ctw/JarDirTest.java b/hotspot/test/testlibrary_tests/ctw/JarDirTest.java index a784bda84ad..a5158554fa7 100644 --- a/hotspot/test/testlibrary_tests/ctw/JarDirTest.java +++ b/hotspot/test/testlibrary_tests/ctw/JarDirTest.java @@ -32,11 +32,11 @@ * java.management * jdk.jvmstat/sun.jvmstat.monitor * @build sun.hotspot.WhiteBox Foo Bar - * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar - * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main JarDirTest prepare - * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld jars/* - * @run main JarDirTest check ctw.log + * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar + * sun.hotspot.WhiteBox$WhiteBoxPermission + * @run driver JarDirTest prepare + * @run driver JarDirTest compile jars/* + * @run driver JarDirTest check * @summary testing of CompileTheWorld :: jars in directory * @author igor.ignatyev@oracle.com */ diff --git a/hotspot/test/testlibrary_tests/ctw/JarsTest.java b/hotspot/test/testlibrary_tests/ctw/JarsTest.java index 16af1639854..d0d40d49c4d 100644 --- a/hotspot/test/testlibrary_tests/ctw/JarsTest.java +++ b/hotspot/test/testlibrary_tests/ctw/JarsTest.java @@ -32,11 +32,11 @@ * java.management * jdk.jvmstat/sun.jvmstat.monitor * @build sun.hotspot.WhiteBox Foo Bar - * @run main ClassFileInstaller sun.hotspot.WhiteBox Foo Bar - * sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main JarsTest prepare - * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Dsun.hotspot.tools.ctw.logfile=ctw.log sun.hotspot.tools.ctw.CompileTheWorld foo.jar bar.jar - * @run main JarsTest check ctw.log + * @run driver ClassFileInstaller sun.hotspot.WhiteBox Foo Bar + * sun.hotspot.WhiteBox$WhiteBoxPermission + * @run driver JarsTest prepare + * @run driver JarsTest compile foo.jar bar.jar + * @run driver JarsTest check * @summary testing of CompileTheWorld :: jars * @author igor.ignatyev@oracle.com */ From 0f853d0c9477759e84d2a1d9a48f7a5d9f0f4372 Mon Sep 17 00:00:00 2001 From: Rahul Raghavan Date: Mon, 2 Jan 2017 00:26:40 -0800 Subject: [PATCH 010/130] 8156762: test/compiler/ciReplay/TestVMNoCompLevel.java fails with - 'Unexpected exit code for negative case: [-client]: expected 0 to not equal 0' Corrected CLIENT_VM_AVAILABLE case Reviewed-by: dpochepk, zmajo --- hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java b/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java index a7c195a64b1..97b74c7c87c 100644 --- a/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java +++ b/hotspot/test/compiler/ciReplay/TestVMNoCompLevel.java @@ -65,7 +65,11 @@ public class TestVMNoCompLevel extends CiReplayBase { throw new Error("Failed to read/write replay data: " + ioe, ioe); } if (CLIENT_VM_AVAILABLE) { - negativeTest(CLIENT_VM_OPTION); + if (SERVER_VM_AVAILABLE) { + negativeTest(CLIENT_VM_OPTION); + } else { + positiveTest(CLIENT_VM_OPTION); + } } if (SERVER_VM_AVAILABLE) { positiveTest(TIERED_DISABLED_VM_OPTION, SERVER_VM_OPTION); From 4559d9da014aa84bc3589f33a41a42f88f9e943f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rickard=20B=C3=A4ckman?= Date: Tue, 3 Jan 2017 08:54:29 +0100 Subject: [PATCH 011/130] 8171082: [AOT] AOT'd SystemModules.modules() fails to load when too large Reviewed-by: kvn, redestad --- hotspot/src/share/vm/aot/aotCodeHeap.cpp | 2 ++ hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp | 8 ++++---- hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.cpp b/hotspot/src/share/vm/aot/aotCodeHeap.cpp index 3d0a22255da..f473cc3e4fd 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp @@ -295,6 +295,8 @@ void AOTCodeHeap::publish_aot(const methodHandle& mh, AOTMethodData* method_data // When the AOT compiler compiles something big we fail to generate metadata // in CodeInstaller::gather_metadata. In that case the scopes_pcs_begin == scopes_pcs_end. // In all successful cases we always have 2 entries of scope pcs. + log_info(aot, class, resolve)("Failed to load %s (no metadata available)", mh->name_and_sig_as_C_string()); + _code_to_aot[code_id]._state = invalid; return; } diff --git a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp index 745fb5199ec..9e686ec1568 100644 --- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp +++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp @@ -554,7 +554,7 @@ JVMCIEnv::CodeInstallResult CodeInstaller::gather_metadata(Handle target, Handle _constants = buffer.consts(); initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK); - JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, CHECK_OK); + JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, false, CHECK_OK); if (result != JVMCIEnv::ok) { return result; } @@ -587,7 +587,7 @@ JVMCIEnv::CodeInstallResult CodeInstaller::install(JVMCICompiler* compiler, Hand _constants = buffer.consts(); initialize_fields(target(), JNIHandles::resolve(compiled_code_obj), CHECK_OK); - JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, CHECK_OK); + JVMCIEnv::CodeInstallResult result = initialize_buffer(buffer, true, CHECK_OK); if (result != JVMCIEnv::ok) { return result; } @@ -726,7 +726,7 @@ int CodeInstaller::estimate_stubs_size(TRAPS) { } // perform data and call relocation on the CodeBuffer -JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, TRAPS) { +JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS) { HandleMark hm; objArrayHandle sites = this->sites(); int locs_buffer_size = sites->length() * (relocInfo::length_limit + sizeof(relocInfo)); @@ -738,7 +738,7 @@ JVMCIEnv::CodeInstallResult CodeInstaller::initialize_buffer(CodeBuffer& buffer, int stubs_size = estimate_stubs_size(CHECK_OK); int total_size = round_to(_code_size, buffer.insts()->alignment()) + round_to(_constants_size, buffer.consts()->alignment()) + round_to(stubs_size, buffer.stubs()->alignment()); - if (total_size > JVMCINMethodSizeLimit) { + if (check_size && total_size > JVMCINMethodSizeLimit) { return JVMCIEnv::code_too_large; } diff --git a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp index 775a8c19f40..e3b38c0688d 100644 --- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp +++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp @@ -227,7 +227,7 @@ protected: int estimate_stubs_size(TRAPS); // perform data and call relocation on the CodeBuffer - JVMCIEnv::CodeInstallResult initialize_buffer(CodeBuffer& buffer, TRAPS); + JVMCIEnv::CodeInstallResult initialize_buffer(CodeBuffer& buffer, bool check_size, TRAPS); void assumption_NoFinalizableSubclass(Handle assumption); void assumption_ConcreteSubtype(Handle assumption); From b07b96aa7cd33b09d542c9bf7ef56ff43c25f6af Mon Sep 17 00:00:00 2001 From: Marcus Larsson Date: Tue, 3 Jan 2017 12:24:52 +0100 Subject: [PATCH 012/130] 8170855: Example for -Xlog:help do not contain one with multiple tags Reviewed-by: dholmes --- hotspot/src/share/vm/logging/logConfiguration.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/hotspot/src/share/vm/logging/logConfiguration.cpp b/hotspot/src/share/vm/logging/logConfiguration.cpp index b8a5932ba0e..e01daf7dd00 100644 --- a/hotspot/src/share/vm/logging/logConfiguration.cpp +++ b/hotspot/src/share/vm/logging/logConfiguration.cpp @@ -514,6 +514,14 @@ void LogConfiguration::print_command_line_help(FILE* out) { " -Xlog:gc\n" "\t Log messages tagged with 'gc' tag using 'info' level to stdout, with default decorations.\n\n" + " -Xlog:gc,safepoint\n" + "\t Log messages tagged either with 'gc' or 'safepoint' tags, both using 'info' level, to stdout, with default decorations.\n" + "\t (Messages tagged with both 'gc' and 'safepoint' will not be logged.)\n\n" + + " -Xlog:gc+ref=debug\n" + "\t Log messages tagged with both 'gc' and 'ref' tags, using 'debug' level, to stdout, with default decorations.\n" + "\t (Messages tagged only with one of the two tags will not be logged.)\n\n" + " -Xlog:gc=debug:file=gc.txt:none\n" "\t Log messages tagged with 'gc' tag using 'debug' level to file 'gc.txt' with no decorations.\n\n" From 6688dfcb492d42557368eb0bb5c1e50b553bbc43 Mon Sep 17 00:00:00 2001 From: Marcus Larsson Date: Tue, 3 Jan 2017 12:25:19 +0100 Subject: [PATCH 013/130] 8170857: Typo in -Xlog:help output Reviewed-by: dholmes --- hotspot/src/share/vm/logging/logConfiguration.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/logging/logConfiguration.cpp b/hotspot/src/share/vm/logging/logConfiguration.cpp index e01daf7dd00..9b77b220e70 100644 --- a/hotspot/src/share/vm/logging/logConfiguration.cpp +++ b/hotspot/src/share/vm/logging/logConfiguration.cpp @@ -478,7 +478,7 @@ void LogConfiguration::describe(outputStream* out) { void LogConfiguration::print_command_line_help(FILE* out) { jio_fprintf(out, "-Xlog Usage: -Xlog[:[what][:[output][:[decorators][:output-options]]]]\n" - "\t where 'what' is a combination of tags and levels on the form tag1[+tag2...][*][=level][,...]\n" + "\t where 'what' is a combination of tags and levels of the form tag1[+tag2...][*][=level][,...]\n" "\t Unless wildcard (*) is specified, only log messages tagged with exactly the tags specified will be matched.\n\n"); jio_fprintf(out, "Available log levels:\n"); From 3965a72bb30774b645c8047e178981883e78e550 Mon Sep 17 00:00:00 2001 From: Martin Doerr Date: Tue, 3 Jan 2017 11:22:37 +0100 Subject: [PATCH 014/130] 8172145: C2: anti dependence missed because store hidden by membar Reviewed-by: kvn --- hotspot/src/share/vm/adlc/formssel.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/src/share/vm/adlc/formssel.cpp b/hotspot/src/share/vm/adlc/formssel.cpp index d9e8726bb58..3bc1fa6aec8 100644 --- a/hotspot/src/share/vm/adlc/formssel.cpp +++ b/hotspot/src/share/vm/adlc/formssel.cpp @@ -650,6 +650,7 @@ bool InstructForm::is_wide_memory_kill(FormDict &globals) const { if( strcmp(_matrule->_opType,"MemBarReleaseLock") == 0 ) return true; if( strcmp(_matrule->_opType,"MemBarAcquireLock") == 0 ) return true; if( strcmp(_matrule->_opType,"MemBarStoreStore") == 0 ) return true; + if( strcmp(_matrule->_opType,"MemBarVolatile") == 0 ) return true; if( strcmp(_matrule->_opType,"StoreFence") == 0 ) return true; if( strcmp(_matrule->_opType,"LoadFence") == 0 ) return true; From 0d99993d6e953e15e3c054794d97d19c4256ea36 Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Tue, 27 Dec 2016 16:10:59 +0100 Subject: [PATCH 015/130] 8172049: [s390] Implement "JEP 270: Reserved Stack Areas for Critical Sections" Reviewed-by: mdoerr --- .../src/cpu/s390/vm/c1_LIRAssembler_s390.cpp | 12 ++-- .../cpu/s390/vm/globalDefinitions_s390.hpp | 2 + hotspot/src/cpu/s390/vm/globals_s390.hpp | 2 +- hotspot/src/cpu/s390/vm/interp_masm_s390.cpp | 25 ++++++++- .../src/cpu/s390/vm/macroAssembler_s390.cpp | 26 +++++++++ .../src/cpu/s390/vm/macroAssembler_s390.hpp | 5 ++ hotspot/src/cpu/s390/vm/s390.ad | 20 +++---- .../src/cpu/s390/vm/stubGenerator_s390.cpp | 7 +-- .../vm/templateInterpreterGenerator_s390.cpp | 21 ++++--- .../os_cpu/linux_s390/vm/os_linux_s390.cpp | 56 ++++++++++++++++++- .../ReservedStack/ReservedStackTest.java | 3 +- 11 files changed, 148 insertions(+), 31 deletions(-) diff --git a/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp b/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp index 524a91fe07f..84fb4205099 100644 --- a/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp +++ b/hotspot/src/cpu/s390/vm/c1_LIRAssembler_s390.cpp @@ -1105,16 +1105,16 @@ void LIR_Assembler::reg2mem(LIR_Opr from, LIR_Opr dest_opr, BasicType type, } case T_FLOAT : if (short_disp) { - __ z_ste(from->as_float_reg(), disp_value, disp_reg, dest); + __ z_ste(from->as_float_reg(), disp_value, disp_reg, dest); } else { - __ z_stey(from->as_float_reg(), disp_value, disp_reg, dest); + __ z_stey(from->as_float_reg(), disp_value, disp_reg, dest); } break; case T_DOUBLE: if (short_disp) { - __ z_std(from->as_double_reg(), disp_value, disp_reg, dest); + __ z_std(from->as_double_reg(), disp_value, disp_reg, dest); } else { - __ z_stdy(from->as_double_reg(), disp_value, disp_reg, dest); + __ z_stdy(from->as_double_reg(), disp_value, disp_reg, dest); } break; default: ShouldNotReachHere(); @@ -1148,6 +1148,10 @@ void LIR_Assembler::return_op(LIR_Opr result) { __ restore_return_pc(); } + if (StackReservedPages > 0 && compilation()->has_reserved_stack_access()) { + __ reserved_stack_check(Z_R14); + } + // We need to mark the code position where the load from the safepoint // polling page was emitted as relocInfo::poll_return_type here. __ relocate(relocInfo::poll_return_type); diff --git a/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp b/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp index 83261cfdf47..63a9cb5abef 100644 --- a/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp +++ b/hotspot/src/cpu/s390/vm/globalDefinitions_s390.hpp @@ -52,4 +52,6 @@ const bool CCallingConventionRequiresIntsAsLongs = true; // The expected size in bytes of a cache line, used to pad data structures. #define DEFAULT_CACHE_LINE_SIZE 256 +#define SUPPORT_RESERVED_STACK_AREA + #endif // CPU_S390_VM_GLOBALDEFINITIONS_S390_HPP diff --git a/hotspot/src/cpu/s390/vm/globals_s390.hpp b/hotspot/src/cpu/s390/vm/globals_s390.hpp index fcd3ff45227..cb5adff3ef5 100644 --- a/hotspot/src/cpu/s390/vm/globals_s390.hpp +++ b/hotspot/src/cpu/s390/vm/globals_s390.hpp @@ -56,7 +56,7 @@ define_pd_global(intx, InlineSmallCode, 2000); // Java_java_net_SocketOutputStream_socketWrite0() uses a 64k buffer on the // stack. To pass stack overflow tests we need 20 shadow pages. #define DEFAULT_STACK_SHADOW_PAGES (20 DEBUG_ONLY(+2)) -#define DEFAULT_STACK_RESERVED_PAGES (0) +#define DEFAULT_STACK_RESERVED_PAGES (1) #define MIN_STACK_YELLOW_PAGES DEFAULT_STACK_YELLOW_PAGES #define MIN_STACK_RED_PAGES DEFAULT_STACK_RED_PAGES diff --git a/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp b/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp index c53fa419a27..8cec2da25ac 100644 --- a/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp +++ b/hotspot/src/cpu/s390/vm/interp_masm_s390.cpp @@ -860,16 +860,39 @@ void InterpreterMacroAssembler::remove_activation(TosState state, bool throw_monitor_exception, bool install_monitor_exception, bool notify_jvmti) { - + BLOCK_COMMENT("remove_activation {"); unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception); // Save result (push state before jvmti call and pop it afterwards) and notify jvmti. notify_method_exit(false, state, notify_jvmti ? NotifyJVMTI : SkipNotifyJVMTI); + if (StackReservedPages > 0) { + BLOCK_COMMENT("reserved_stack_check:"); + // Test if reserved zone needs to be enabled. + Label no_reserved_zone_enabling; + + // Compare frame pointers. There is no good stack pointer, as with stack + // frame compression we can get different SPs when we do calls. A subsequent + // call could have a smaller SP, so that this compare succeeds for an + // inner call of the method annotated with ReservedStack. + z_lg(Z_R0, Address(Z_SP, (intptr_t)_z_abi(callers_sp))); + z_clg(Z_R0, Address(Z_thread, JavaThread::reserved_stack_activation_offset())); // Compare with frame pointer in memory. + z_brl(no_reserved_zone_enabling); + + // Enable reserved zone again, throw stack overflow exception. + call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread); + call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_delayed_StackOverflowError)); + + should_not_reach_here(); + + bind(no_reserved_zone_enabling); + } + verify_oop(Z_tos, state); verify_thread(); pop_interpreter_frame(return_pc, Z_ARG2, Z_ARG3); + BLOCK_COMMENT("} remove_activation"); } // lock object diff --git a/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp b/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp index a7cbd706255..0f78e5a6250 100644 --- a/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp +++ b/hotspot/src/cpu/s390/vm/macroAssembler_s390.cpp @@ -2666,6 +2666,32 @@ void MacroAssembler::bang_stack_with_offset(int offset) { } } +void MacroAssembler::reserved_stack_check(Register return_pc) { + // Test if reserved zone needs to be enabled. + Label no_reserved_zone_enabling; + assert(return_pc == Z_R14, "Return pc must be in R14 before z_br() to StackOverflow stub."); + BLOCK_COMMENT("reserved_stack_check {"); + + z_clg(Z_SP, Address(Z_thread, JavaThread::reserved_stack_activation_offset())); + z_brl(no_reserved_zone_enabling); + + // Enable reserved zone again, throw stack overflow exception. + save_return_pc(); + push_frame_abi160(0); + call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread); + pop_frame(); + restore_return_pc(); + + load_const_optimized(Z_R1, StubRoutines::throw_delayed_StackOverflowError_entry()); + // Don't use call() or z_basr(), they will invalidate Z_R14 which contains the return pc. + z_br(Z_R1); + + should_not_reach_here(); + + bind(no_reserved_zone_enabling); + BLOCK_COMMENT("} reserved_stack_check"); +} + // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes. void MacroAssembler::tlab_allocate(Register obj, Register var_size_in_bytes, diff --git a/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp b/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp index c9540860958..588bde6207e 100644 --- a/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp +++ b/hotspot/src/cpu/s390/vm/macroAssembler_s390.hpp @@ -627,6 +627,11 @@ class MacroAssembler: public Assembler { // Stack overflow checking void bang_stack_with_offset(int offset); + // Check for reserved stack access in method being exited. If the reserved + // stack area was accessed, protect it again and throw StackOverflowError. + // Uses Z_R1. + void reserved_stack_check(Register return_pc); + // Atomics // -- none? diff --git a/hotspot/src/cpu/s390/vm/s390.ad b/hotspot/src/cpu/s390/vm/s390.ad index 8ab6a5026d3..fd188525c46 100644 --- a/hotspot/src/cpu/s390/vm/s390.ad +++ b/hotspot/src/cpu/s390/vm/s390.ad @@ -909,15 +909,8 @@ void MachEpilogNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const { // If this does safepoint polling, then do it here. bool need_polling = do_polling() && C->is_method_compilation(); - // Touch the polling page. - // Part 1: get the page's address. - if (need_polling) { - AddressLiteral pp(os::get_polling_page()); - __ load_const_optimized(Z_R1_scratch, pp); - } - // Pop frame, restore return_pc, and all stuff needed by interpreter. - // Pop frame by add insted of load (a penny saved is a penny got :-). + // Pop frame by add instead of load (a penny saved is a penny got :-). int frame_size_in_bytes = Assembler::align((C->frame_slots() << LogBytesPerInt), frame::alignment_in_bytes); int retPC_offset = frame_size_in_bytes + _z_abi16(return_pc); if (Displacement::is_validDisp(retPC_offset)) { @@ -928,9 +921,14 @@ void MachEpilogNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const { __ restore_return_pc(); } - // Touch the polling page, - // part 2: touch the page now. + if (StackReservedPages > 0 && C->has_reserved_stack_access()) { + __ reserved_stack_check(Z_R14); + } + + // Touch the polling page. if (need_polling) { + AddressLiteral pp(os::get_polling_page()); + __ load_const_optimized(Z_R1_scratch, pp); // We need to mark the code position where the load from the safepoint // polling page was emitted as relocInfo::poll_return_type here. __ relocate(relocInfo::poll_return_type); @@ -939,7 +937,7 @@ void MachEpilogNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const { } uint MachEpilogNode::size(PhaseRegAlloc *ra_) const { - // variable size. determine dynamically. + // Variable size. determine dynamically. return MachNode::size(ra_); } diff --git a/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp b/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp index 8b872c5c922..be107222636 100644 --- a/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp +++ b/hotspot/src/cpu/s390/vm/stubGenerator_s390.cpp @@ -2433,13 +2433,12 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_throw_StackOverflowError_entry = generate_throw_exception("StackOverflowError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError), false); + StubRoutines::_throw_delayed_StackOverflowError_entry = + generate_throw_exception("delayed StackOverflowError throw_exception", + CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError), false); //---------------------------------------------------------------------- // Entry points that are platform specific. - // Build this early so it's available for the interpreter. - StubRoutines::_throw_StackOverflowError_entry = - generate_throw_exception("StackOverflowError throw_exception", - CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError), false); if (UseCRC32Intrinsics) { // We have no CRC32 table on z/Architecture. diff --git a/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp b/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp index de266db04fc..2084f36006f 100644 --- a/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp +++ b/hotspot/src/cpu/s390/vm/templateInterpreterGenerator_s390.cpp @@ -1112,16 +1112,21 @@ void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) { // top_frame_size = TOP_IJAVA_FRAME_ABI + max_stack + size of interpreter state __ add2reg(top_frame_size, frame::z_top_ijava_frame_abi_size + - frame::z_ijava_state_size + - frame::interpreter_frame_monitor_size() * wordSize, + frame::z_ijava_state_size + + frame::interpreter_frame_monitor_size() * wordSize, max_stack); - // Check if there's room for the new frame... - Register frame_size = max_stack; // Reuse the regiser for max_stack. - __ z_lgr(frame_size, Z_SP); - __ z_sgr(frame_size, sp_after_resize); - __ z_agr(frame_size, top_frame_size); - generate_stack_overflow_check(frame_size, fp/*tmp1*/); + if (!native_call) { + // Stack overflow check. + // Native calls don't need the stack size check since they have no + // expression stack and the arguments are already on the stack and + // we only add a handful of words to the stack. + Register frame_size = max_stack; // Reuse the regiser for max_stack. + __ z_lgr(frame_size, Z_SP); + __ z_sgr(frame_size, sp_after_resize); + __ z_agr(frame_size, top_frame_size); + generate_stack_overflow_check(frame_size, fp/*tmp1*/); + } DEBUG_ONLY(__ z_cg(Z_R14, _z_abi16(return_pc), Z_SP)); __ asm_assert_eq("killed Z_R14", 0); diff --git a/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp b/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp index 684853cfd34..e9120a8b696 100644 --- a/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp +++ b/hotspot/src/os_cpu/linux_s390/vm/os_linux_s390.cpp @@ -144,6 +144,42 @@ frame os::fetch_frame_from_context(const void* ucVoid) { return frame(sp, epc.pc()); } +bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* uc, frame* fr) { + address pc = (address) os::Linux::ucontext_get_pc(uc); + if (Interpreter::contains(pc)) { + // Interpreter performs stack banging after the fixed frame header has + // been generated while the compilers perform it before. To maintain + // semantic consistency between interpreted and compiled frames, the + // method returns the Java sender of the current frame. + *fr = os::fetch_frame_from_context(uc); + if (!fr->is_first_java_frame()) { + assert(fr->safe_for_sender(thread), "Safety check"); + *fr = fr->java_sender(); + } + } else { + // More complex code with compiled code. + assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above"); + CodeBlob* cb = CodeCache::find_blob(pc); + if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) { + // Not sure where the pc points to, fallback to default + // stack overflow handling. In compiled code, we bang before + // the frame is complete. + return false; + } else { + intptr_t* fp = os::Linux::ucontext_get_fp(uc); + intptr_t* sp = os::Linux::ucontext_get_sp(uc); + *fr = frame(sp, (address)*sp); + if (!fr->is_java_frame()) { + assert(fr->safe_for_sender(thread), "Safety check"); + assert(!fr->is_first_frame(), "Safety check"); + *fr = fr->java_sender(); + } + } + } + assert(fr->is_java_frame(), "Safety check"); + return true; +} + frame os::get_sender_for_C_frame(frame* fr) { if (*fr->sp() == 0) { // fr is the last C frame. @@ -279,13 +315,31 @@ JVM_handle_linux_signal(int sig, if (thread->on_local_stack(addr)) { // stack overflow if (thread->in_stack_yellow_reserved_zone(addr)) { - thread->disable_stack_yellow_reserved_zone(); if (thread->thread_state() == _thread_in_Java) { + if (thread->in_stack_reserved_zone(addr)) { + frame fr; + if (os::Linux::get_frame_at_stack_banging_point(thread, uc, &fr)) { + assert(fr.is_java_frame(), "Must be a Javac frame"); + frame activation = + SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr); + if (activation.sp() != NULL) { + thread->disable_stack_reserved_zone(); + if (activation.is_interpreted_frame()) { + thread->set_reserved_stack_activation((address)activation.fp()); + } else { + thread->set_reserved_stack_activation((address)activation.unextended_sp()); + } + return 1; + } + } + } // Throw a stack overflow exception. // Guard pages will be reenabled while unwinding the stack. + thread->disable_stack_yellow_reserved_zone(); stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW); } else { // Thread was in the vm or native code. Return and try to finish. + thread->disable_stack_yellow_reserved_zone(); return 1; } } else if (thread->in_stack_red_zone(addr)) { diff --git a/hotspot/test/runtime/ReservedStack/ReservedStackTest.java b/hotspot/test/runtime/ReservedStack/ReservedStackTest.java index 6a095155349..216f731d2b7 100644 --- a/hotspot/test/runtime/ReservedStack/ReservedStackTest.java +++ b/hotspot/test/runtime/ReservedStack/ReservedStackTest.java @@ -199,7 +199,8 @@ public class ReservedStackTest { // corruptions are still possible. boolean supportedPlatform = Platform.isAix() || - (Platform.isLinux() && (Platform.isPPC() || Platform.isX64() || Platform.isX86())) || + (Platform.isLinux() && + (Platform.isPPC() || Platform.isS390x() || Platform.isX64() || Platform.isX86())) || Platform.isOSX() || Platform.isSolaris(); if (supportedPlatform && !result.contains("PASSED")) { From 2e0248d2fc08e937cfd2d9c58e5aeb5148dc9302 Mon Sep 17 00:00:00 2001 From: Martin Doerr Date: Tue, 3 Jan 2017 17:17:14 +0100 Subject: [PATCH 016/130] 8172199: s390: Use same get_key_start_from_aescrypt_object implementation as PPC64 Reviewed-by: kvn --- hotspot/src/share/vm/opto/library_call.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp index c298e318ab5..5d837d6ecb0 100644 --- a/hotspot/src/share/vm/opto/library_call.cpp +++ b/hotspot/src/share/vm/opto/library_call.cpp @@ -6335,7 +6335,7 @@ bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) { //------------------------------get_key_start_from_aescrypt_object----------------------- Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) { -#ifdef PPC64 +#if defined(PPC64) || defined(S390) // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys. // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns. // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption. From 450472a24a3a1a590c73bae03986318ea1cad67e Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Tue, 3 Jan 2017 21:36:05 +0100 Subject: [PATCH 017/130] 8172169: Re-examine String field optionality Reviewed-by: kvn, thartmann --- .../src/share/vm/classfile/javaClasses.cpp | 12 ++++------ .../src/share/vm/classfile/javaClasses.hpp | 9 -------- .../share/vm/classfile/javaClasses.inline.hpp | 18 +++++---------- hotspot/src/share/vm/opto/graphKit.cpp | 22 ++++++++----------- 4 files changed, 19 insertions(+), 42 deletions(-) diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp index 91b51404489..b7fe590eee1 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.cpp +++ b/hotspot/src/share/vm/classfile/javaClasses.cpp @@ -163,8 +163,8 @@ void java_lang_String::compute_offsets() { Klass* k = SystemDictionary::String_klass(); compute_offset(value_offset, k, vmSymbols::value_name(), vmSymbols::byte_array_signature()); - compute_optional_offset(hash_offset, k, vmSymbols::hash_name(), vmSymbols::int_signature()); - compute_optional_offset(coder_offset, k, vmSymbols::coder_name(), vmSymbols::byte_signature()); + compute_offset(hash_offset, k, vmSymbols::hash_name(), vmSymbols::int_signature()); + compute_offset(coder_offset, k, vmSymbols::coder_name(), vmSymbols::byte_signature()); initialized = true; } @@ -3977,12 +3977,8 @@ void JavaClasses::check_offsets() { // java.lang.String CHECK_OFFSET("java/lang/String", java_lang_String, value, "[B"); - if (java_lang_String::has_hash_field()) { - CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I"); - } - if (java_lang_String::has_coder_field()) { - CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B"); - } + CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I"); + CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B"); // java.lang.Class diff --git a/hotspot/src/share/vm/classfile/javaClasses.hpp b/hotspot/src/share/vm/classfile/javaClasses.hpp index 0cf0090e851..f05db4c79b7 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.hpp +++ b/hotspot/src/share/vm/classfile/javaClasses.hpp @@ -81,15 +81,6 @@ class java_lang_String : AllStatic { static Handle create_from_platform_dependent_str(const char* str, TRAPS); static Handle char_converter(Handle java_string, jchar from_char, jchar to_char, TRAPS); - static bool has_hash_field() { - assert(initialized, "Must be initialized"); - return (hash_offset > 0); - } - static bool has_coder_field() { - assert(initialized, "Must be initialized"); - return (coder_offset > 0); - } - static void set_compact_strings(bool value); static int value_offset_in_bytes() { diff --git a/hotspot/src/share/vm/classfile/javaClasses.inline.hpp b/hotspot/src/share/vm/classfile/javaClasses.inline.hpp index b1c4a3f9224..b388bb157d3 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.inline.hpp +++ b/hotspot/src/share/vm/classfile/javaClasses.inline.hpp @@ -30,10 +30,8 @@ #include "oops/oopsHierarchy.hpp" void java_lang_String::set_coder(oop string, jbyte coder) { - assert(initialized, "Must be initialized"); - if (coder_offset > 0) { - string->byte_field_put(coder_offset, coder); - } + assert(initialized && (coder_offset > 0), "Must be initialized"); + string->byte_field_put(coder_offset, coder); } void java_lang_String::set_value_raw(oop string, typeArrayOop buffer) { @@ -61,15 +59,11 @@ unsigned int java_lang_String::hash(oop java_string) { return java_string->int_field(hash_offset); } bool java_lang_String::is_latin1(oop java_string) { - assert(initialized, "Must be initialized"); + assert(initialized && (coder_offset > 0), "Must be initialized"); assert(is_instance(java_string), "must be java_string"); - if (coder_offset > 0) { - jbyte coder = java_string->byte_field(coder_offset); - assert(CompactStrings || coder == CODER_UTF16, "Must be UTF16 without CompactStrings"); - return coder == CODER_LATIN1; - } else { - return false; - } + jbyte coder = java_string->byte_field(coder_offset); + assert(CompactStrings || coder == CODER_UTF16, "Must be UTF16 without CompactStrings"); + return coder == CODER_LATIN1; } int java_lang_String::length(oop java_string) { assert(initialized, "Must be initialized"); diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp index c879137d882..8a9f81e0564 100644 --- a/hotspot/src/share/vm/opto/graphKit.cpp +++ b/hotspot/src/share/vm/opto/graphKit.cpp @@ -4348,20 +4348,16 @@ Node* GraphKit::load_String_value(Node* ctrl, Node* str) { } Node* GraphKit::load_String_coder(Node* ctrl, Node* str) { - if (java_lang_String::has_coder_field()) { - if (!CompactStrings) { - return intcon(java_lang_String::CODER_UTF16); - } - int coder_offset = java_lang_String::coder_offset_in_bytes(); - const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), - false, NULL, 0); - const TypePtr* coder_field_type = string_type->add_offset(coder_offset); - int coder_field_idx = C->get_alias_index(coder_field_type); - return make_load(ctrl, basic_plus_adr(str, str, coder_offset), - TypeInt::BYTE, T_BYTE, coder_field_idx, MemNode::unordered); - } else { - return intcon(0); // false + if (!CompactStrings) { + return intcon(java_lang_String::CODER_UTF16); } + int coder_offset = java_lang_String::coder_offset_in_bytes(); + const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), + false, NULL, 0); + const TypePtr* coder_field_type = string_type->add_offset(coder_offset); + int coder_field_idx = C->get_alias_index(coder_field_type); + return make_load(ctrl, basic_plus_adr(str, str, coder_offset), + TypeInt::BYTE, T_BYTE, coder_field_idx, MemNode::unordered); } void GraphKit::store_String_value(Node* ctrl, Node* str, Node* value) { From 631dc215187649728144650639d1adcf8fa803fc Mon Sep 17 00:00:00 2001 From: Vivek Deshpande Date: Tue, 3 Jan 2017 14:56:51 -0800 Subject: [PATCH 018/130] 8171974: Fix for R10 Register clobbering with usage of ExternalAddress Reviewed-by: kvn, rbackman --- hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp | 6 +++--- hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp | 2 +- .../src/cpu/x86/vm/macroAssembler_x86_sha.cpp | 17 ++++++++++++----- hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp | 8 ++++---- 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp index 3d4dee751a5..b6d32631582 100644 --- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp @@ -3499,12 +3499,12 @@ void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) { } } -void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) { +void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) { if (reachable(src)) { movdqu(dst, as_Address(src)); } else { - lea(rscratch1, src); - movdqu(dst, Address(rscratch1, 0)); + lea(scratchReg, src); + movdqu(dst, Address(scratchReg, 0)); } } diff --git a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp index 02fb401511e..a3e81e58dc5 100644 --- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp +++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp @@ -1085,7 +1085,7 @@ public: void movdqu(Address dst, XMMRegister src); void movdqu(XMMRegister dst, Address src); void movdqu(XMMRegister dst, XMMRegister src); - void movdqu(XMMRegister dst, AddressLiteral src); + void movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg = rscratch1); // AVX Unaligned forms void vmovdqu(Address dst, XMMRegister src); void vmovdqu(XMMRegister dst, Address src); diff --git a/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp b/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp index 37d93a48f21..10935345f70 100644 --- a/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp +++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86_sha.cpp @@ -817,7 +817,7 @@ enum { movl(d, Address(CTX, 4*3)); movl(e, Address(CTX, 4*4)); movl(f, Address(CTX, 4*5)); - movl(g, Address(CTX, 4*6)); + // load g - r10 after it is used as scratch movl(h, Address(CTX, 4*7)); pshuffle_byte_flip_mask_addr = pshuffle_byte_flip_mask; @@ -825,6 +825,8 @@ enum { vmovdqu(SHUF_00BA, ExternalAddress(pshuffle_byte_flip_mask_addr + 32)); //[_SHUF_00BA wrt rip] vmovdqu(SHUF_DC00, ExternalAddress(pshuffle_byte_flip_mask_addr + 64)); //[_SHUF_DC00 wrt rip] + movl(g, Address(CTX, 4*6)); + movq(Address(rsp, _CTX), CTX); // store bind(loop0); @@ -977,7 +979,7 @@ bind(only_one_block); movl(d, Address(CTX, 4*3)); // 0xa54ff53a movl(e, Address(CTX, 4*4)); // 0x510e527f movl(f, Address(CTX, 4*5)); // 0x9b05688c - movl(g, Address(CTX, 4*6)); // 0x1f83d9ab + // load g - r10 after use as scratch movl(h, Address(CTX, 4*7)); // 0x5be0cd19 @@ -986,6 +988,8 @@ bind(only_one_block); vmovdqu(SHUF_00BA, ExternalAddress(pshuffle_byte_flip_mask_addr + 32)); //[_SHUF_00BA wrt rip] vmovdqu(SHUF_DC00, ExternalAddress(pshuffle_byte_flip_mask_addr + 64)); //[_SHUF_DC00 wrt rip] + movl(g, Address(CTX, 4*6)); // 0x1f83d9ab + movq(Address(rsp, _CTX), CTX); jmpb(do_last_block); @@ -1154,9 +1158,8 @@ void MacroAssembler::sha512_AVX2_one_round_and_schedule( // Move to appropriate lanes for calculating w[16] and w[17] vperm2f128(xmm4, xmm0, xmm0, 0); //xmm4 = W[-16] + W[-7] + s0{ BABA } - address MASK_YMM_LO = StubRoutines::x86::pshuffle_byte_flip_mask_addr_sha512(); //Move to appropriate lanes for calculating w[18] and w[19] - vpand(xmm0, xmm0, ExternalAddress(MASK_YMM_LO + 32), AVX_256bit); //xmm0 = W[-16] + W[-7] + s0{ DC00 } + vpand(xmm0, xmm0, xmm10, AVX_256bit); //xmm0 = W[-16] + W[-7] + s0{ DC00 } //Calculate w[16] and w[17] in both 128 bit lanes //Calculate sigma1 for w[16] and w[17] on both 128 bit lanes vperm2f128(xmm2, xmm7, xmm7, 17); //xmm2 = W[-2] {BABA} @@ -1250,6 +1253,7 @@ void MacroAssembler::sha512_AVX2(XMMRegister msg, XMMRegister state0, XMMRegiste const XMMRegister& XFER = xmm0; // YTMP0 const XMMRegister& BYTE_FLIP_MASK = xmm9; // ymm9 + const XMMRegister& YMM_MASK_LO = xmm10; // ymm10 #ifdef _WIN64 const Register& INP = rcx; //1st arg const Register& CTX = rdx; //2nd arg @@ -1368,11 +1372,14 @@ void MacroAssembler::sha512_AVX2(XMMRegister msg, XMMRegister state0, XMMRegiste movq(d, Address(CTX, 8 * 3)); movq(e, Address(CTX, 8 * 4)); movq(f, Address(CTX, 8 * 5)); - movq(g, Address(CTX, 8 * 6)); + // load g - r10 after it is used as scratch movq(h, Address(CTX, 8 * 7)); pshuffle_byte_flip_mask_addr = pshuffle_byte_flip_mask_sha512; vmovdqu(BYTE_FLIP_MASK, ExternalAddress(pshuffle_byte_flip_mask_addr + 0)); //PSHUFFLE_BYTE_FLIP_MASK wrt rip + vmovdqu(YMM_MASK_LO, ExternalAddress(pshuffle_byte_flip_mask_addr + 32)); + + movq(g, Address(CTX, 8 * 6)); bind(loop0); lea(TBL, ExternalAddress(K512_W)); diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 1853cf9a42a..48be33ae526 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -3207,7 +3207,7 @@ class StubGenerator: public StubCodeGenerator { const Register len_reg = c_rarg4; // src len (must be multiple of blocksize 16) #else const Address len_mem(rbp, 6 * wordSize); // length is on stack on Win64 - const Register len_reg = r10; // pick the first volatile windows register + const Register len_reg = r11; // pick the volatile windows register #endif const Register pos = rax; @@ -3404,7 +3404,7 @@ class StubGenerator: public StubCodeGenerator { const Register len_reg = c_rarg4; // src len (must be multiple of blocksize 16) #else const Address len_mem(rbp, 6 * wordSize); // length is on stack on Win64 - const Register len_reg = r10; // pick the first volatile windows register + const Register len_reg = r11; // pick the volatile windows register #endif const Register pos = rax; @@ -3930,7 +3930,7 @@ class StubGenerator: public StubCodeGenerator { __ push(rbx); // Save RBX __ movdqu(xmm_curr_counter, Address(counter, 0x00)); // initialize counter with initial counter - __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr())); + __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()), pos); // pos as scratch __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled __ movptr(pos, 0); @@ -3953,7 +3953,7 @@ class StubGenerator: public StubCodeGenerator { __ movl(Address(used_addr, 0), used); // key length could be only {11, 13, 15} * 4 = {44, 52, 60} - __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr())); + __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()), rbx); // rbx as scratch __ movl(rbx, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT))); __ cmpl(rbx, 52); __ jcc(Assembler::equal, L_multiBlock_loopTop[1]); From 1e918ed98c115c1f14f24b109e42f603ed285df1 Mon Sep 17 00:00:00 2001 From: Christian Tornqvist Date: Wed, 4 Jan 2017 10:57:26 -0500 Subject: [PATCH 019/130] 8168137: import-hotspot build target not removed from hotspot-ide-project Reviewed-by: erikj --- hotspot/make/ide/CreateVSProject.gmk | 4 ++-- .../build/tools/projectcreator/WinGammaPlatformVC10.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/hotspot/make/ide/CreateVSProject.gmk b/hotspot/make/ide/CreateVSProject.gmk index d6f5324adb8..db0aca87e28 100644 --- a/hotspot/make/ide/CreateVSProject.gmk +++ b/hotspot/make/ide/CreateVSProject.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -121,7 +121,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) -buildBase $(call FixPath, $(IDE_OUTPUTDIR)/vs-output) \ -buildSpace $(call FixPath, $(IDE_OUTPUTDIR)) \ -makeBinary $(call FixPath, $(MAKE)) \ - -makeOutput $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-%f/libjvm) \ + -makeOutput $(call FixPath, $(JDK_OUTPUTDIR)/bin/server) \ -absoluteInclude $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-server/gensrc) \ -absoluteSrcInclude $(call FixPath, $(HOTSPOT_OUTPUTDIR)/variant-server/gensrc) \ $(EXTRACTED_DEFINES_client) \ diff --git a/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java b/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java index d44fb04c588..50413e52792 100644 --- a/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java +++ b/hotspot/make/src/classes/build/tools/projectcreator/WinGammaPlatformVC10.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -114,8 +114,8 @@ public class WinGammaPlatformVC10 extends WinGammaPlatform { tag(cfg, "CodeAnalysisRuleAssemblies"); } for (BuildConfig cfg : allConfigs) { - tagData(cfg, "NMakeBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile import-hotspot LOG=info"); - tagData(cfg, "NMakeReBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot import-hotspot LOG=info"); + tagData(cfg, "NMakeBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile hotspot LOG=info"); + tagData(cfg, "NMakeReBuildCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot hotspot LOG=info"); tagData(cfg, "NMakeCleanCommandLine", cfg.get("MakeBinary") + " -f ../../Makefile clean-hotspot LOG=info"); tagData(cfg, "NMakeOutput", cfg.get("MakeOutput") + Util.sep + "jvm.dll"); tagData(cfg, "NMakePreprocessorDefinitions", Util.join(";", cfg.getDefines())); From b58bb4740e570ef3c95819ac0bc2e9b8ea44211e Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 4 Jan 2017 11:44:26 -0800 Subject: [PATCH 020/130] 8172054: Aot tests should include Java assertions into AOT compiled code Reviewed-by: iveresov --- hotspot/src/share/vm/aot/aotCodeHeap.cpp | 2 +- hotspot/test/compiler/aot/AotCompiler.java | 1 + hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.cpp b/hotspot/src/share/vm/aot/aotCodeHeap.cpp index f473cc3e4fd..1cd9576253f 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp @@ -710,7 +710,7 @@ bool AOTCodeHeap::load_klass_data(instanceKlassHandle kh, Thread* thread) { } if (_lib->config()->_omitAssertions && JavaAssertions::enabled(kh->name()->as_C_string(), kh->class_loader() == NULL)) { - // Assertions are omitted in the compiled code, but are enabled right now. Bail out. + log_trace(aot, class, load)("class %s in %s does not have java assertions in compiled code, but assertions are enabled for this execution.", kh->internal_name(), _lib->name()); sweep_dependent_methods(klass_data); return false; } diff --git a/hotspot/test/compiler/aot/AotCompiler.java b/hotspot/test/compiler/aot/AotCompiler.java index 68a22468763..b9ace71767b 100644 --- a/hotspot/test/compiler/aot/AotCompiler.java +++ b/hotspot/test/compiler/aot/AotCompiler.java @@ -93,6 +93,7 @@ public class AotCompiler { } } List args = new ArrayList<>(); + args.add("--compile-with-assertions"); args.add("--output"); args.add(libName); if (file != null) { diff --git a/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java b/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java index 06bca2a9292..e6136ba1b98 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java +++ b/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java @@ -44,6 +44,7 @@ public class JaotcTestHelper { for (String vmOpt : Utils.getTestJavaOpts()) { launcher.addVMArg(vmOpt); } + launcher.addToolArg("--compile-with-assertions"); for (String arg : args) { launcher.addToolArg(arg); } From 08aa21deb77b2f9589bddca40836a7960a49d9ff Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Wed, 4 Jan 2017 21:13:04 -0500 Subject: [PATCH 021/130] 8172246: [TESTBUG] runtime/RedefineTests/RedefinePreviousVersions.java 'Class unloading: has_previous_versions = true' missing from stdout/stderr Add boolean to gate redefinition start Reviewed-by: sspitsyn, dholmes --- .../RedefineTests/RedefinePreviousVersions.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java b/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java index 45555dcf4ab..dda3e872c72 100644 --- a/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java +++ b/hotspot/test/runtime/RedefineTests/RedefinePreviousVersions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,20 +48,23 @@ public class RedefinePreviousVersions { public static String newRunning = "class RedefinePreviousVersions$Running {" + " public static volatile boolean stop = true;" + + " public static volatile boolean running = true;" + " static void localSleep() { }" + " public static void infinite() { }" + "}"; static class Running { public static volatile boolean stop = false; + public static volatile boolean running = false; static void localSleep() { try{ - Thread.currentThread().sleep(10);//sleep for 10 ms + Thread.sleep(10); // sleep for 10 ms } catch(InterruptedException ie) { } } public static void infinite() { + running = true; while (!stop) { localSleep(); } } } @@ -70,8 +73,6 @@ public class RedefinePreviousVersions { if (args.length > 0) { - String jarFile = System.getProperty("test.src") + "/testcase.jar"; - // java -javaagent:redefineagent.jar -Xlog:stuff RedefinePreviousVersions ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( "-javaagent:redefineagent.jar", "-Xlog:redefine+class+iklass+add=trace,redefine+class+iklass+purge=trace", @@ -100,6 +101,10 @@ public class RedefinePreviousVersions { } }.start(); + while (!Running.running) { + Thread.sleep(10); // sleep for 10 ms + } + // Since a method of newRunning is running, this class should be added to the previous_version_list // of Running, and _has_previous_versions should return true at class unloading. RedefineClassHelper.redefineClass(Running.class, newRunning); From f238905f2b2ca50a59cee5907c3f7d2f764676fb Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Thu, 5 Jan 2017 09:25:36 +0100 Subject: [PATCH 022/130] 8172010: [AOT] RecompilationTest.java fails with "expected compilation level after compilation to be no less than 1" Disabled probabilistic profiling to ensure recompilation of AOT compiled method. Reviewed-by: kvn, iveresov --- hotspot/test/compiler/aot/RecompilationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/test/compiler/aot/RecompilationTest.java b/hotspot/test/compiler/aot/RecompilationTest.java index 466c8348e7e..dda00bc28e5 100644 --- a/hotspot/test/compiler/aot/RecompilationTest.java +++ b/hotspot/test/compiler/aot/RecompilationTest.java @@ -33,6 +33,7 @@ * @run main compiler.aot.AotCompiler -libname libRecompilationTest1.so * -class compiler.whitebox.SimpleTestCaseHelper * -extraopt -Dgraal.TieredAOT=true -extraopt -Dgraal.ProfileSimpleMethods=true + * -extraopt -Dgraal.ProbabilisticProfiling=false * -extraopt -XX:+UnlockDiagnosticVMOptions -extraopt -XX:+WhiteBoxAPI -extraopt -Xbootclasspath/a:. * -extraopt -XX:-UseCompressedOops * -extraopt -XX:CompileCommand=dontinline,compiler.whitebox.SimpleTestCaseHelper::* From b9b80751e2b76406a523c0a984604cef79d699bd Mon Sep 17 00:00:00 2001 From: Gustavo Romero Date: Thu, 15 Dec 2016 08:56:32 -0500 Subject: [PATCH 023/130] 8171266: PPC64: Add support to -XX:RTMSpinLoopCount=0 Reviewed-by: mdoerr, dholmes --- hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp | 21 ++++++++++++------- hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp | 5 ++++- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp index 2d1f0c7230b..a5d5613a414 100644 --- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp +++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp @@ -2569,7 +2569,7 @@ void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register } // Spin and retry if lock is busy. -// inputs: box_Reg (monitor address) +// inputs: owner_addr_Reg (monitor address) // : retry_count_Reg // output: retry_count_Reg decremented by 1 // CTR is killed @@ -2577,15 +2577,22 @@ void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register o Label SpinLoop, doneRetry; addic_(retry_count_Reg, retry_count_Reg, -1); blt(CCR0, doneRetry); - li(R0, RTMSpinLoopCount); - mtctr(R0); + + if (RTMSpinLoopCount > 1) { + li(R0, RTMSpinLoopCount); + mtctr(R0); + } bind(SpinLoop); smt_yield(); // Can't use waitrsv(). No permission (SIGILL). - bdz(retryLabel); - ld(R0, 0, owner_addr_Reg); - cmpdi(CCR0, R0, 0); - bne(CCR0, SpinLoop); + + if (RTMSpinLoopCount > 1) { + bdz(retryLabel); + ld(R0, 0, owner_addr_Reg); + cmpdi(CCR0, R0, 0); + bne(CCR0, SpinLoop); + } + b(retryLabel); bind(doneRetry); diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp index 6c6b83d257f..5e8be1425fa 100644 --- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp +++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp @@ -327,7 +327,10 @@ void VM_Version::initialize() { warning("RTMAbortRatio must be in the range 0 to 100, resetting it to 50"); FLAG_SET_DEFAULT(RTMAbortRatio, 50); } - guarantee(RTMSpinLoopCount > 0, "unsupported"); + if (RTMSpinLoopCount < 0) { + warning("RTMSpinLoopCount must not be a negative value, resetting it to 0"); + FLAG_SET_DEFAULT(RTMSpinLoopCount, 0); + } #else // Only C2 does RTM locking optimization. // Can't continue because UseRTMLocking affects UseBiasedLocking flag From 396af967d63efb78f4cb652f51dc247b92bc2c67 Mon Sep 17 00:00:00 2001 From: Boris Molodenkov Date: Wed, 21 Dec 2016 14:41:48 +0300 Subject: [PATCH 024/130] 8170918: Remove shell script from test/compiler/c2/cr7200264/TestIntVect.java Reviewed-by: kvn --- test/jtreg-ext/requires/VMProps.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/jtreg-ext/requires/VMProps.java b/test/jtreg-ext/requires/VMProps.java index 06299e7ecd5..15c854f964b 100644 --- a/test/jtreg-ext/requires/VMProps.java +++ b/test/jtreg-ext/requires/VMProps.java @@ -33,6 +33,8 @@ import java.util.Map; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; + +import sun.hotspot.cpuinfo.CPUInfo; import sun.hotspot.gc.GC; import sun.hotspot.WhiteBox; @@ -62,6 +64,7 @@ public class VMProps implements Callable> { map.put("vm.simpleArch", vmArch()); map.put("vm.debug", vmDebug()); map.put("vm.jvmci", vmJvmci()); + map.put("vm.cpu.features", cpuFeatures()); vmGC(map); // vm.gc.X = true/false VMProps.dump(map); @@ -165,6 +168,13 @@ public class VMProps implements Callable> { return "" + (WB.getBooleanVMFlag("EnableJVMCI") != null); } + /** + * @return supported CPU features + */ + protected String cpuFeatures() { + return CPUInfo.getFeatures().toString(); + } + /** * For all existing GC sets vm.gc.X property. * Example vm.gc.G1=true means: From 367c06b7f82721803272b31aff01a43f6820753a Mon Sep 17 00:00:00 2001 From: Ujwal Vangapally Date: Fri, 23 Dec 2016 12:15:21 +0530 Subject: [PATCH 025/130] 8170861: Remove DcmdMBeanPermissionsTest.java from ProblemList Removed DcmdMBeanPermissionsTest.java from ProblemList Reviewed-by: dholmes, fparain --- jdk/test/ProblemList.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index cc645799e09..53111b09448 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -150,8 +150,6 @@ java/io/pathNames/GeneralWin32.java 8156595 windows- com/sun/management/OperatingSystemMXBean/GetProcessCpuLoad.java 8030957 aix-all com/sun/management/OperatingSystemMXBean/GetSystemCpuLoad.java 8030957 aix-all -com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java 8169575 generic-all - ############################################################################ # jdk_jmx From fff8c7e7daa76db3370c80dc2ae2fad1954bc66c Mon Sep 17 00:00:00 2001 From: Dmitry Fazunenko Date: Tue, 27 Dec 2016 16:24:37 +0300 Subject: [PATCH 026/130] 8171441: tools/launcher/VersionCheck.java doesn't report names of tools which failed checks Reviewed-by: stsmirno, iignatyev, anazarov --- jdk/test/tools/launcher/VersionCheck.java | 104 ++++++++++++++-------- 1 file changed, 66 insertions(+), 38 deletions(-) diff --git a/jdk/test/tools/launcher/VersionCheck.java b/jdk/test/tools/launcher/VersionCheck.java index aa507b6da43..469c5bf6f45 100644 --- a/jdk/test/tools/launcher/VersionCheck.java +++ b/jdk/test/tools/launcher/VersionCheck.java @@ -36,6 +36,8 @@ import java.util.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.HashSet; +import java.util.Set; public class VersionCheck extends TestHelper { @@ -148,31 +150,44 @@ public class VersionCheck extends TestHelper { } /* - * this tests if the tool can take a version string and returns - * a 0 exit code, it is not possible to validate the contents - * of the -version output as they are inconsistent. + * Checks if the tools accept "-version" option (exit code is zero). + * The output of the tools run with "-version" is not verified. */ - static boolean testToolVersion() { - TestHelper.testExitValue = 0; + static String testToolVersion() { + System.out.println("=== testToolVersion === "); + Set failed = new HashSet<>(); for (File f : new File(JAVA_BIN).listFiles(new ToolFilter(BLACKLIST_VERSION))) { String x = f.getAbsolutePath(); - System.out.println("Testing (-version): " + x); TestResult tr = doExec(x, "-version"); - tr.checkPositive(); + System.out.println("Testing " + f.getName()); + System.out.println("#> " + x + " -version"); + tr.testOutput.forEach(System.out::println); + System.out.println("#> echo $?"); + System.out.println(tr.exitValue); + if (!tr.isOK()) { + System.out.println("failed"); + failed.add(f.getName()); + } } - return TestHelper.testExitValue == 0; + if (failed.isEmpty()) { + System.out.println("testToolVersion passed"); + return ""; + } else { + System.out.println("testToolVersion failed"); + return "testToolVersion: " + failed + "; "; + } + } - static boolean compareJVersionStrings() { - int failcount = 0; + static String testJVersionStrings() { + System.out.println("=== testJVersionStrings === "); + Set failed = new HashSet<>(); for (File f : new File(JAVA_BIN).listFiles(new ToolFilter(BLACKLIST_JOPTION))) { + System.out.println("Testing " + f.getName()); String x = f.getAbsolutePath(); - System.out.println("Testing (-J-version): " + x); - String testStr; - - testStr = getVersion(x, "-J-version"); + String testStr = getVersion(x, "-J-version"); if (refVersion.compareTo(testStr) != 0) { - failcount++; + failed.add(f.getName()); System.out.println("Error: " + x + " fails -J-version comparison"); System.out.println("Expected:"); @@ -183,7 +198,7 @@ public class VersionCheck extends TestHelper { testStr = getVersion(x, "-J-fullversion"); if (refFullVersion.compareTo(testStr) != 0) { - failcount++; + failed.add(f.getName()); System.out.println("Error: " + x + " fails -J-fullversion comparison"); System.out.println("Expected:"); @@ -192,12 +207,17 @@ public class VersionCheck extends TestHelper { System.out.print(testStr); } } - System.out.println("Version Test: " + failcount); - return failcount == 0; + if (failed.isEmpty()) { + System.out.println("testJVersionStrings passed"); + return ""; + } else { + System.out.println("testJVersionStrings failed"); + return "testJVersionStrings: " + failed + "; "; + } } - static boolean compareInternalStrings() { - int failcount = 0; + static String testInternalStrings() { + System.out.println("=== testInternalStrings === "); String bStr = refVersion.substring(refVersion.indexOf("build") + "build".length() + 1, refVersion.lastIndexOf(")")); @@ -208,20 +228,21 @@ public class VersionCheck extends TestHelper { envMap.put(TestHelper.JLDEBUG_KEY, "true"); TestHelper.TestResult tr = doExec(envMap, javaCmd, "-version"); List alist = new ArrayList<>(); - alist.addAll(tr.testOutput); - for (String x : tr.testOutput) { - alist.add(x.trim()); - } + tr.testOutput.stream().map(String::trim).forEach(alist::add); - if (!alist.contains(expectedFullVersion)) { + if (alist.contains(expectedFullVersion)) { + System.out.println("testInternalStrings passed"); + return ""; + } else { System.out.println("Error: could not find " + expectedFullVersion); - failcount++; + tr.testOutput.forEach(System.out::println); + System.out.println("testInternalStrings failed"); + return "testInternalStrings; "; } - System.out.println("Internal Strings Test: " + failcount); - return failcount == 0; } - static boolean testDebugVersion() { + static String testDebugVersion() { + System.out.println("=== testInternalStrings === "); String jdkType = System.getProperty("jdk.debug", "release"); String versionLines = getAllVersionLines(javaCmd, "-version"); if ("release".equals(jdkType)) { @@ -229,18 +250,23 @@ public class VersionCheck extends TestHelper { } else { jdkType = jdkType + " "; } + String tofind = "(" + jdkType + "build"; + int idx = versionLines.indexOf(tofind); if (idx < 0) { + System.out.println("versionLines " + versionLines); System.out.println("Did not find first instance of " + tofind); - return false; + return "testDebugVersion; "; } idx = versionLines.indexOf(tofind, idx + 1); if (idx < 0) { - System.out.println("Did not find first instance of " + tofind); - return false; + System.out.println("versionLines " + versionLines); + System.out.println("Did not find second instance of " + tofind); + return "testDebugVersion; "; } - return true; + System.out.println("testDebugVersion passed"); + return ""; } // Initialize @@ -251,13 +277,15 @@ public class VersionCheck extends TestHelper { public static void main(String[] args) { init(); - if (compareJVersionStrings() && - compareInternalStrings() && - testToolVersion() && - testDebugVersion()) { + String errorMessage = ""; + errorMessage += testJVersionStrings(); + errorMessage += testInternalStrings(); + errorMessage += testToolVersion(); + errorMessage += testDebugVersion(); + if (errorMessage.isEmpty()) { System.out.println("All Version string comparisons: PASS"); } else { - throw new AssertionError("Some tests failed"); + throw new AssertionError("VersionCheck failed: " + errorMessage); } } From dcb007ab96d2b9cf120a6caa554fc62241bc2cb2 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Wed, 28 Dec 2016 18:37:09 +0300 Subject: [PATCH 027/130] 8172094: 8171433 changes in generated-configure should be restored Reviewed-by: erikj, kzhaldyb --- common/autoconf/generated-configure.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 644f25ab435..13c74505795 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -5170,7 +5170,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1482309967 +DATE_WHEN_GENERATED=1483099656 ############################################################################### # @@ -52997,7 +52997,7 @@ $as_echo "yes, forced" >&6; } $as_echo "no, forced" >&6; } BUILD_GTEST="false" elif test "x$enable_hotspot_gtest" = "x"; then - if test "x$GTEST_DIR_EXISTS" = "xtrue" && test "x$OPENJDK_TARGET_OS" != "xaix"; then + if test "x$GTEST_DIR_EXISTS" = "xtrue"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } BUILD_GTEST="true" From 5b1d170debed17398aed5ec9a9f9ef16986c92a1 Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Fri, 6 Jan 2017 10:55:30 +0100 Subject: [PATCH 028/130] 8171435: "assert(is_single_cpu() && !is_virtual()) failed: type check" with -XX:+PatchALot on SPARC Fixed several issues with PatchALot or unaligned accesses on SPARC. Reviewed-by: kvn --- .../src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp | 16 ++++++++++------ .../compiler/c1/CanonicalizeArrayLength.java | 6 +++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp index 97fb2745a26..ae2942f19b5 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -694,6 +694,7 @@ void LIR_Assembler::vtable_call(LIR_OpJavaCall* op) { int LIR_Assembler::store(LIR_Opr from_reg, Register base, int offset, BasicType type, bool wide, bool unaligned) { int store_offset; if (!Assembler::is_simm13(offset + (type == T_LONG) ? wordSize : 0)) { + assert(base != O7, "destroying register"); assert(!unaligned, "can't handle this"); // for offsets larger than a simm13 we setup the offset in O7 __ set(offset, O7); @@ -712,9 +713,12 @@ int LIR_Assembler::store(LIR_Opr from_reg, Register base, int offset, BasicType case T_LONG : #ifdef _LP64 if (unaligned || PatchALot) { - __ srax(from_reg->as_register_lo(), 32, O7); + // Don't use O7 here because it may be equal to 'base' (see LIR_Assembler::reg2mem) + assert(G3_scratch != base, "can't handle this"); + assert(G3_scratch != from_reg->as_register_lo(), "can't handle this"); + __ srax(from_reg->as_register_lo(), 32, G3_scratch); __ stw(from_reg->as_register_lo(), base, offset + lo_word_offset_in_bytes); - __ stw(O7, base, offset + hi_word_offset_in_bytes); + __ stw(G3_scratch, base, offset + hi_word_offset_in_bytes); } else { __ stx(from_reg->as_register_lo(), base, offset); } @@ -821,7 +825,7 @@ int LIR_Assembler::load(Register base, int offset, LIR_Opr to_reg, BasicType typ case T_SHORT : __ ldsh(base, offset, to_reg->as_register()); break; case T_INT : __ ld(base, offset, to_reg->as_register()); break; case T_LONG : - if (!unaligned) { + if (!unaligned && !PatchALot) { #ifdef _LP64 __ ldx(base, offset, to_reg->as_register_lo()); #else @@ -1297,7 +1301,7 @@ void LIR_Assembler::mem2reg(LIR_Opr src_opr, LIR_Opr dest, BasicType type, disp_reg = O7; } } else if (unaligned || PatchALot) { - __ add(src, addr->index()->as_register(), O7); + __ add(src, addr->index()->as_pointer_register(), O7); src = O7; } else { disp_reg = addr->index()->as_pointer_register(); @@ -1424,7 +1428,7 @@ void LIR_Assembler::reg2mem(LIR_Opr from_reg, LIR_Opr dest, BasicType type, disp_reg = O7; } } else if (unaligned || PatchALot) { - __ add(src, addr->index()->as_register(), O7); + __ add(src, addr->index()->as_pointer_register(), O7); src = O7; } else { disp_reg = addr->index()->as_pointer_register(); diff --git a/hotspot/test/compiler/c1/CanonicalizeArrayLength.java b/hotspot/test/compiler/c1/CanonicalizeArrayLength.java index 64255c936ed..fb8f09028af 100644 --- a/hotspot/test/compiler/c1/CanonicalizeArrayLength.java +++ b/hotspot/test/compiler/c1/CanonicalizeArrayLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 8150102 8150514 8150534 + * @bug 8150102 8150514 8150534 8171435 * @summary C1 crashes in Canonicalizer::do_ArrayLength() after fix for JDK-8150102 * * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions @@ -31,7 +31,7 @@ * -XX:-BackgroundCompilation * compiler.c1.CanonicalizeArrayLength * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions - * -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=1 + * -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=3 * -XX:-BackgroundCompilation * -XX:+PatchALot * compiler.c1.CanonicalizeArrayLength From 482d791b2cbbf244e18c761c3ac531aae4d10d23 Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Sun, 8 Jan 2017 10:39:42 -0800 Subject: [PATCH 029/130] 8170959: unloading archived shared class caused crash Reviewed-by: coleenp, sspitsyn, mockner --- hotspot/src/share/vm/oops/instanceKlass.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index 5b2180f945c..41f5fd143a8 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -2139,8 +2139,6 @@ void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) { } void InstanceKlass::release_C_heap_structures() { - assert(!this->is_shared(), "should not be called for a shared class"); - // Can't release the constant pool here because the constant pool can be // deallocated separately from the InstanceKlass for default methods and // redefine classes. @@ -2191,7 +2189,7 @@ void InstanceKlass::release_C_heap_structures() { } // deallocate the cached class file - if (_cached_class_file != NULL) { + if (_cached_class_file != NULL && !MetaspaceShared::is_in_shared_space(_cached_class_file)) { os::free(_cached_class_file); _cached_class_file = NULL; } From 3dfc3e19ff8b5bb64b1e62c786103e3c1d590516 Mon Sep 17 00:00:00 2001 From: Kirill Zhaldybin Date: Wed, 28 Dec 2016 19:13:34 +0300 Subject: [PATCH 030/130] 8172098: A lot of gtests uses TEST instead of TEST_VM Reviewed-by: iignatyev --- .../native/code/test_dependencyContext.cpp | 2 +- .../native/gc/g1/test_workerDataArray.cpp | 40 +++++++++---------- hotspot/test/native/logging/test_log.cpp | 16 ++++---- .../native/logging/test_logConfiguration.cpp | 4 +- .../native/logging/test_logMessageTest.cpp | 16 ++++---- .../logging/test_logTagSetDescriptions.cpp | 4 +- 6 files changed, 41 insertions(+), 41 deletions(-) diff --git a/hotspot/test/native/code/test_dependencyContext.cpp b/hotspot/test/native/code/test_dependencyContext.cpp index 45b54d7cd80..fec730f9637 100644 --- a/hotspot/test/native/code/test_dependencyContext.cpp +++ b/hotspot/test/native/code/test_dependencyContext.cpp @@ -86,7 +86,7 @@ static void test_remove_dependent_nmethod(int id, bool delete_immediately) { NOT_PRODUCT(ASSERT_FALSE(depContext.is_dependent_nmethod(nm))); } -TEST(code, dependency_context) { +TEST_VM(code, dependency_context) { test_remove_dependent_nmethod(0, false); test_remove_dependent_nmethod(1, false); test_remove_dependent_nmethod(2, false); diff --git a/hotspot/test/native/gc/g1/test_workerDataArray.cpp b/hotspot/test/native/gc/g1/test_workerDataArray.cpp index 2895fecbec0..e950f1d480f 100644 --- a/hotspot/test/native/gc/g1/test_workerDataArray.cpp +++ b/hotspot/test/native/gc/g1/test_workerDataArray.cpp @@ -123,19 +123,19 @@ class BasicWorkerDataArrayTest : public WorkerDataArrayTest { } }; -TEST_F(BasicWorkerDataArrayTest, sum_test) { +TEST_VM_F(BasicWorkerDataArrayTest, sum_test) { ASSERT_EQ(15u, array.sum()); } -TEST_F(BasicWorkerDataArrayTest, average_test) { +TEST_VM_F(BasicWorkerDataArrayTest, average_test) { ASSERT_NEAR(5.0, array.average(), epsilon); } -TEST_F(BasicWorkerDataArrayTest, print_summary_on_test) { +TEST_VM_F(BasicWorkerDataArrayTest, print_summary_on_test) { ASSERT_STREQ(print_expected_summary(), print_summary()); } -TEST_F(BasicWorkerDataArrayTest, print_details_on_test) { +TEST_VM_F(BasicWorkerDataArrayTest, print_details_on_test) { ASSERT_STREQ(print_expected_details(), print_details()); } @@ -161,19 +161,19 @@ class AddWorkerDataArrayTest : public WorkerDataArrayTest { } }; -TEST_F(AddWorkerDataArrayTest, sum_test) { +TEST_VM_F(AddWorkerDataArrayTest, sum_test) { ASSERT_EQ(18u, array.sum()); } -TEST_F(AddWorkerDataArrayTest, average_test) { +TEST_VM_F(AddWorkerDataArrayTest, average_test) { ASSERT_NEAR(6.0, array.average(), epsilon); } -TEST_F(AddWorkerDataArrayTest, print_summary_on_test) { +TEST_VM_F(AddWorkerDataArrayTest, print_summary_on_test) { ASSERT_STREQ(print_expected_summary(), print_summary()); } -TEST_F(AddWorkerDataArrayTest, print_details_on_test) { +TEST_VM_F(AddWorkerDataArrayTest, print_details_on_test) { ASSERT_STREQ(print_expected_details(), print_details()); } @@ -195,19 +195,19 @@ class UninitializedElementWorkerDataArrayTest : public WorkerDataArrayTest { } }; -TEST_F(UninitializedWorkerDataArrayTest, sum_test) { +TEST_VM_F(UninitializedWorkerDataArrayTest, sum_test) { ASSERT_EQ(0u, array.sum()); } -TEST_F(UninitializedWorkerDataArrayTest, average_test) { +TEST_VM_F(UninitializedWorkerDataArrayTest, average_test) { ASSERT_NEAR(0.0, array.average(), epsilon); } -TEST_F(UninitializedWorkerDataArrayTest, print_summary_on_test) { +TEST_VM_F(UninitializedWorkerDataArrayTest, print_summary_on_test) { ASSERT_STREQ(print_expected_summary(), print_summary()); } -TEST_F(UninitializedWorkerDataArrayTest, print_details_on_test) { +TEST_VM_F(UninitializedWorkerDataArrayTest, print_details_on_test) { ASSERT_STREQ(print_expected_details(), print_details()); } @@ -265,18 +265,18 @@ class UninitializedDoubleElementWorkerDataArrayTest : public WorkerDataArrayTest } }; -TEST_F(UninitializedDoubleElementWorkerDataArrayTest, sum_test) { +TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, sum_test) { ASSERT_NEAR(12.3 / MILLIUNITS, array.sum(), epsilon); } -TEST_F(UninitializedDoubleElementWorkerDataArrayTest, average_test) { +TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, average_test) { ASSERT_NEAR(6.15 / MILLIUNITS, array.average(), epsilon); } -TEST_F(UninitializedDoubleElementWorkerDataArrayTest, print_summary_on_test) { +TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, print_summary_on_test) { ASSERT_STREQ(print_expected_summary(), print_summary()); } -TEST_F(UninitializedDoubleElementWorkerDataArrayTest, print_details_on_test) { +TEST_VM_F(UninitializedDoubleElementWorkerDataArrayTest, print_details_on_test) { ASSERT_STREQ(print_expected_details(), print_details()); } diff --git a/hotspot/test/native/logging/test_log.cpp b/hotspot/test/native/logging/test_log.cpp index 50a5c9ce724..f3bdacaf4bc 100644 --- a/hotspot/test/native/logging/test_log.cpp +++ b/hotspot/test/native/logging/test_log.cpp @@ -41,14 +41,14 @@ size_t Test_log_prefix_prefixer(char* buf, size_t len) { } #ifdef ASSERT // 'test' tag is debug only -TEST_F(LogTest, prefix) { +TEST_VM_F(LogTest, prefix) { set_log_config(TestLogFileName, "logging+test=trace"); log_trace(logging, test)(LOG_LINE_STR); EXPECT_TRUE(file_contains_substring(TestLogFileName, LOG_PREFIX_STR LOG_LINE_STR)); } #endif -TEST_F(LogTest, large_message) { +TEST_VM_F(LogTest, large_message) { char big_msg[4096] = {0}; char Xchar = '~'; @@ -68,7 +68,7 @@ TEST_F(LogTest, large_message) { EXPECT_EQ(sizeof(big_msg) - 1, count); } -TEST_F(LogTest, enabled_logtarget) { +TEST_VM_F(LogTest, enabled_logtarget) { set_log_config(TestLogFileName, "gc=debug"); LogTarget(Debug, gc) log; @@ -80,7 +80,7 @@ TEST_F(LogTest, enabled_logtarget) { EXPECT_TRUE(file_contains_substring(TestLogFileName, LOG_TEST_STRING_LITERAL)); } -TEST_F(LogTest, disabled_logtarget) { +TEST_VM_F(LogTest, disabled_logtarget) { set_log_config(TestLogFileName, "gc=info"); LogTarget(Debug, gc) log; @@ -95,7 +95,7 @@ TEST_F(LogTest, disabled_logtarget) { EXPECT_FALSE(file_contains_substring(TestLogFileName, LOG_TEST_STRING_LITERAL)); } -TEST_F(LogTest, enabled_loghandle) { +TEST_VM_F(LogTest, enabled_loghandle) { set_log_config(TestLogFileName, "gc=debug"); Log(gc) log; @@ -109,7 +109,7 @@ TEST_F(LogTest, enabled_loghandle) { EXPECT_TRUE(file_contains_substring(TestLogFileName, "3 workers")); } -TEST_F(LogTest, disabled_loghandle) { +TEST_VM_F(LogTest, disabled_loghandle) { set_log_config(TestLogFileName, "gc=info"); Log(gc) log; @@ -126,7 +126,7 @@ TEST_F(LogTest, disabled_loghandle) { EXPECT_FALSE(file_contains_substring(TestLogFileName, "3 workers")); } -TEST_F(LogTest, enabled_logtargethandle) { +TEST_VM_F(LogTest, enabled_logtargethandle) { set_log_config(TestLogFileName, "gc=debug"); LogTarget(Debug, gc) log; @@ -140,7 +140,7 @@ TEST_F(LogTest, enabled_logtargethandle) { EXPECT_TRUE(file_contains_substring(TestLogFileName, "3 workers")); } -TEST_F(LogTest, disabled_logtargethandle) { +TEST_VM_F(LogTest, disabled_logtargethandle) { set_log_config(TestLogFileName, "gc=info"); LogTarget(Debug, gc) log; diff --git a/hotspot/test/native/logging/test_logConfiguration.cpp b/hotspot/test/native/logging/test_logConfiguration.cpp index 92d595e8059..74ae2aab707 100644 --- a/hotspot/test/native/logging/test_logConfiguration.cpp +++ b/hotspot/test/native/logging/test_logConfiguration.cpp @@ -297,7 +297,7 @@ TEST_VM_F(LogConfigurationTest, parse_log_arguments) { } } -TEST_F(LogConfigurationTest, configure_stdout) { +TEST_VM_F(LogConfigurationTest, configure_stdout) { // Start out with all logging disabled LogConfiguration::disable_logging(); @@ -355,7 +355,7 @@ static void Test_logconfiguration_subscribe_helper() { Test_logconfiguration_subscribe_triggered++; } -TEST_F(LogConfigurationTest, subscribe) { +TEST_VM_F(LogConfigurationTest, subscribe) { ResourceMark rm; Log(logging) log; set_log_config("stdout", "logging*=trace"); diff --git a/hotspot/test/native/logging/test_logMessageTest.cpp b/hotspot/test/native/logging/test_logMessageTest.cpp index f23ba944426..9e567b79798 100644 --- a/hotspot/test/native/logging/test_logMessageTest.cpp +++ b/hotspot/test/native/logging/test_logMessageTest.cpp @@ -65,7 +65,7 @@ LogMessageTest::~LogMessageTest() { // Verify that messages with multiple levels are written // to outputs configured for all the corresponding levels -TEST_F(LogMessageTest, level_inclusion) { +TEST_VM_F(LogMessageTest, level_inclusion) { const size_t message_count = 10; LogMessageBuffer msg[message_count]; @@ -119,7 +119,7 @@ LOG_LEVEL_LIST } // Verify that messages are logged in the order they are added to the log message -TEST_F(LogMessageTest, line_order) { +TEST_VM_F(LogMessageTest, line_order) { LogMessageBuffer msg; msg.info("info line").error("error line").trace("trace line") .error("another error").warning("warning line").debug("debug line"); @@ -131,7 +131,7 @@ TEST_F(LogMessageTest, line_order) { << "output missing or in incorrect order"; } -TEST_F(LogMessageTest, long_message) { +TEST_VM_F(LogMessageTest, long_message) { // Write 10K bytes worth of log data LogMessageBuffer msg; const size_t size = 10 * K; @@ -155,7 +155,7 @@ TEST_F(LogMessageTest, long_message) { FREE_C_HEAP_ARRAY(char, data); } -TEST_F(LogMessageTest, message_with_many_lines) { +TEST_VM_F(LogMessageTest, message_with_many_lines) { const size_t lines = 100; const size_t line_length = 16; @@ -188,7 +188,7 @@ static size_t dummy_prefixer(char* buf, size_t len) { return prefix_len; } -TEST_F(LogMessageTest, prefixing) { +TEST_VM_F(LogMessageTest, prefixing) { LogMessageBuffer msg; msg.set_prefix(dummy_prefixer); for (int i = 0; i < 3; i++) { @@ -209,7 +209,7 @@ TEST_F(LogMessageTest, prefixing) { << "error in prefixed output"; } -TEST_F(LogMessageTest, scoped_messages) { +TEST_VM_F(LogMessageTest, scoped_messages) { { LogMessage(logging) msg; msg.info("scoped info"); @@ -223,7 +223,7 @@ TEST_F(LogMessageTest, scoped_messages) { << "missing output from scoped log message"; } -TEST_F(LogMessageTest, scoped_flushing) { +TEST_VM_F(LogMessageTest, scoped_flushing) { { LogMessage(logging) msg; msg.info("manual flush info"); @@ -236,7 +236,7 @@ TEST_F(LogMessageTest, scoped_flushing) { << "log file contains duplicate lines from single scoped log message"; } -TEST_F(LogMessageTest, scoped_reset) { +TEST_VM_F(LogMessageTest, scoped_reset) { { LogMessage(logging) msg, partial; msg.info("%s", "info reset msg"); diff --git a/hotspot/test/native/logging/test_logTagSetDescriptions.cpp b/hotspot/test/native/logging/test_logTagSetDescriptions.cpp index 1669f86c34a..77c0a3191dc 100644 --- a/hotspot/test/native/logging/test_logTagSetDescriptions.cpp +++ b/hotspot/test/native/logging/test_logTagSetDescriptions.cpp @@ -30,7 +30,7 @@ #include "unittest.hpp" #include "utilities/ostream.hpp" -TEST(LogTagSetDescriptions, describe) { +TEST_VM(LogTagSetDescriptions, describe) { for (LogTagSetDescription* d = tagset_descriptions; d->tagset != NULL; d++) { char expected[1 * K]; d->tagset->label(expected, sizeof(expected), "+"); @@ -46,7 +46,7 @@ TEST(LogTagSetDescriptions, describe) { } } -TEST(LogTagSetDescriptions, command_line_help) { +TEST_VM(LogTagSetDescriptions, command_line_help) { const char* filename = "logtagset_descriptions"; FILE* fp = fopen(filename, "w+"); ASSERT_NE((void*)NULL, fp); From 9b81c0637e114f9cd645e4c6883250f82a44cbde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rickard=20B=C3=A4ckman?= Date: Thu, 5 Jan 2017 08:37:10 +0100 Subject: [PATCH 031/130] 8169588: [AOT] jaotc --classpath option is confusing Reviewed-by: kvn, dlong --- .../src/jdk/tools/jaotc/LoadedClass.java | 64 ++++ .../src/jdk/tools/jaotc/Main.java | 95 +++-- .../tools/jaotc/collect/ClassCollector.java | 332 ------------------ .../jdk/tools/jaotc/collect/ClassSearch.java | 93 +++++ .../jdk/tools/jaotc/collect/ClassSource.java | 52 +++ .../jdk/tools/jaotc/collect/FileSupport.java | 90 +++++ .../tools/jaotc/collect/FileSystemFinder.java | 76 ++++ .../jdk/tools/jaotc/collect/SearchFor.java | 54 +++ .../jdk/tools/jaotc/collect/SearchPath.java | 87 +++++ .../tools/jaotc/collect/SourceProvider.java | 29 ++ .../collect/classname/ClassNameSource.java | 42 +++ .../classname/ClassNameSourceProvider.java | 62 ++++ .../collect/directory/DirectorySource.java | 53 +++ .../directory/DirectorySourceProvider.java | 68 ++++ .../jaotc/collect/jar/JarFileSource.java | 55 +++ .../jaotc/collect/jar/JarSourceProvider.java | 83 +++++ .../jaotc/collect/module/ModuleSource.java | 57 +++ .../collect/module/ModuleSourceProvider.java | 82 +++++ hotspot/test/compiler/aot/AotCompiler.java | 3 +- .../aot/cli/jaotc/ClasspathOptionTest.java | 63 ---- .../ClasspathOptionUnknownClassTest.java | 2 +- .../aot/cli/jaotc/CompileClassTest.java | 2 +- .../aot/cli/jaotc/CompileDirectoryTest.java | 2 +- .../aot/cli/jaotc/CompileJarTest.java | 2 +- .../aot/cli/jaotc/JaotcTestHelper.java | 6 +- .../cli/jaotc/ListOptionNotExistingTest.java | 2 +- .../aot/cli/jaotc/ListOptionTest.java | 2 +- .../cli/jaotc/ListOptionWrongFileTest.java | 7 +- .../jaotc/test/collect/ClassSearchTest.java | 143 ++++++++ .../jaotc/test/collect/ClassSourceTest.java | 52 +++ .../jaotc/test/collect/FakeFileSupport.java | 110 ++++++ .../jaotc/test/collect/FakeSearchPath.java | 47 +++ .../jaotc/test/collect/SearchPathTest.java | 102 ++++++ .../jdk/tools/jaotc/test/collect/Utils.java | 36 ++ .../DirectorySourceProviderTest.java | 77 ++++ .../collect/jar/JarSourceProviderTest.java | 112 ++++++ .../module/ModuleSourceProviderTest.java | 69 ++++ .../ClassAndLibraryNotMatchTest.java | 5 +- .../vmflags/BasicFlagsChange.java | 2 +- 39 files changed, 1884 insertions(+), 436 deletions(-) create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/LoadedClass.java delete mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassCollector.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSearch.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSource.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSupport.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSystemFinder.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchFor.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchPath.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SourceProvider.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSource.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSourceProvider.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySource.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySourceProvider.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarFileSource.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarSourceProvider.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSource.java create mode 100644 hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSourceProvider.java delete mode 100644 hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSearchTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSourceTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeFileSupport.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeSearchPath.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/SearchPathTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/Utils.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/directory/DirectorySourceProviderTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/jar/JarSourceProviderTest.java create mode 100644 hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/module/ModuleSourceProviderTest.java diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/LoadedClass.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/LoadedClass.java new file mode 100644 index 00000000000..a0a01f7c1c9 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/LoadedClass.java @@ -0,0 +1,64 @@ +package jdk.tools.jaotc;/* + * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +public class LoadedClass { + private final String name; + private final Class clz; + + public LoadedClass(String name, Class clz) { + this.name = name; + this.clz = clz; + } + + public String getName() { + return name; + } + + public Class getLoadedClass() { + return clz; + } + + @Override + public String toString() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof LoadedClass)) return false; + + LoadedClass that = (LoadedClass) o; + + if (name != null ? !name.equals(that.name) : that.name != null) return false; + return clz != null ? clz.equals(that.clz) : that.clz == null; + + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (clz != null ? clz.hashCode() : 0); + return result; + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java index 2af308732e4..8ea8ebf81c5 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,7 @@ import java.nio.file.Paths; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; @@ -51,7 +52,11 @@ import java.util.stream.Stream; import jdk.tools.jaotc.binformat.BinaryContainer; import jdk.tools.jaotc.binformat.ByteContainer; -import jdk.tools.jaotc.collect.ClassCollector; +import jdk.tools.jaotc.collect.*; +import jdk.tools.jaotc.collect.classname.ClassNameSourceProvider; +import jdk.tools.jaotc.collect.directory.DirectorySourceProvider; +import jdk.tools.jaotc.collect.jar.JarSourceProvider; +import jdk.tools.jaotc.collect.module.ModuleSourceProvider; import jdk.tools.jaotc.utils.Timer; import org.graalvm.compiler.api.runtime.GraalJVMCICompiler; @@ -127,17 +132,7 @@ public class Main implements LogPrinter { abstract void process(Main task, String opt, String arg) throws BadArgs; } - static Option[] recognizedOptions = {new Option(" --module Module to compile", true, "--module") { - @Override - void process(Main task, String opt, String arg) { - task.options.module = arg; - } - }, new Option(" --module-path Specify where to find module to compile", true, "--module-path") { - @Override - void process(Main task, String opt, String arg) { - task.options.modulepath = arg; - } - }, new Option(" --output Output file name", true, "--output") { + static Option[] recognizedOptions = { new Option(" --output Output file name", true, "--output") { @Override void process(Main task, String opt, String arg) { String name = arg; @@ -161,10 +156,25 @@ public class Main implements LogPrinter { void process(Main task, String opt, String arg) { task.options.compileWithAssertions = true; } - }, new Option(" --classpath Specify where to find user class files", true, "--classpath", "--class-path") { + }, new Option(" --classname > Class names to AOT compile (: separated list)", true, "--classname") { @Override void process(Main task, String opt, String arg) { - task.options.classpath = arg; + task.options.files.addAll(ClassSearch.makeList(ClassNameSourceProvider.TYPE, arg)); + } + }, new Option(" --directory Directories to search for class files. (: separated list)", true, "--directory") { + @Override + void process(Main task, String opt, String arg) { + task.options.files.addAll(ClassSearch.makeList(DirectorySourceProvider.TYPE, arg)); + } + }, new Option(" --jar Jar files to search for class files. (: separated list)", true, "--jar") { + @Override + void process(Main task, String opt, String arg) { + task.options.files.addAll(ClassSearch.makeList(JarSourceProvider.TYPE, arg)); + } + }, new Option(" --module module names to AOT compile (: separated list)", true, "--module") { + @Override + void process(Main task, String opt, String arg) { + task.options.files.addAll(ClassSearch.makeList(ModuleSourceProvider.TYPE, arg)); } }, new Option(" --threads Number of compilation threads to be used", true, "--threads") { @Override @@ -218,6 +228,12 @@ public class Main implements LogPrinter { void process(Main task, String opt, String arg) { task.options.version = true; } + }, new Option(" --search-path Where to search for jarfiles and modules", true, "--search-path") { + @Override + void process(Main task, String opt, String arg) { + String[] elements = arg.split(":"); + task.options.searchPath.add(elements); + } }, new Option(" -J Pass directly to the runtime system", false, "-J") { @Override void process(Main task, String opt, String arg) { @@ -225,12 +241,11 @@ public class Main implements LogPrinter { }}; public static class Options { - public List files = new LinkedList<>(); - public String module = null; - public String modulepath = "modules"; + public List files = new LinkedList<>(); public String outputName = "unnamed"; public String methodList; - public String classpath = "."; + public List sources = new ArrayList<>(); + public SearchPath searchPath = new SearchPath(); /** * We don't see scaling beyond 16 threads. @@ -288,7 +303,9 @@ public class Main implements LogPrinter { printlnInfo("Compiling " + options.outputName + "..."); final long start = System.currentTimeMillis(); - run(); + if (!run()) { + return EXIT_ABNORMAL; + } final long end = System.currentTimeMillis(); printlnInfo("Total time: " + (end - start) + " ms"); @@ -331,17 +348,34 @@ public class Main implements LogPrinter { } @SuppressWarnings("try") - private void run() throws Exception { + private boolean run() throws Exception { openLog(); try { CompilationSpec compilationRestrictions = collectSpecifiedMethods(); - Set> classesToCompile; + Set> classesToCompile = new HashSet<>(); try (Timer t = new Timer(this, "")) { - ClassCollector collector = new ClassCollector(this.options, this); - classesToCompile = collector.collectClassesToCompile(); + FileSupport fileSupport = new FileSupport(); + ClassSearch lookup = new ClassSearch(); + lookup.addProvider(new ModuleSourceProvider()); + lookup.addProvider(new ClassNameSourceProvider(fileSupport)); + lookup.addProvider(new JarSourceProvider()); + lookup.addProvider(new DirectorySourceProvider(fileSupport)); + + List found = null; + try { + found = lookup.search(options.files, options.searchPath); + } catch (InternalError e) { + reportError(e); + return false; + } + + for (LoadedClass loadedClass : found) { + classesToCompile.add(loadedClass.getLoadedClass()); + } + printInfo(classesToCompile.size() + " classes found"); } @@ -464,6 +498,7 @@ public class Main implements LogPrinter { } finally { closeLog(); } + return true; } private void addMethods(AOTCompiledClass aotClass, ResolvedJavaMethod[] methods, CompilationSpec compilationRestrictions, GraalFilters filters) { @@ -527,7 +562,7 @@ public class Main implements LogPrinter { break; } } else { - options.files.add(arg); + options.files.add(new SearchFor(arg)); } } } @@ -588,6 +623,12 @@ public class Main implements LogPrinter { log.flush(); } + private void reportError(Throwable e) { + log.println("Error: " + e.getMessage()); + e.printStackTrace(log); + log.flush(); + } + private void reportError(String key, Object... args) { printError(MessageFormat.format(key, args)); } @@ -603,9 +644,9 @@ public class Main implements LogPrinter { } private void showHelp() { - log.println("Usage: " + PROGNAME + " <--module name> | "); + log.println("Usage: " + PROGNAME + " | "); log.println(); - log.println(" list A list of class files, jar files or directories which"); + log.println(" list A list of class names, jar files or directories which"); log.println(" contains class files."); log.println(); log.println("where possible options include:"); diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassCollector.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassCollector.java deleted file mode 100644 index c46b3bfd062..00000000000 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassCollector.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * 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.tools.jaotc.collect; - -import jdk.tools.jaotc.LogPrinter; -import jdk.tools.jaotc.Main; - -import java.io.File; -import java.io.IOException; -import java.net.*; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.*; - -import static java.nio.file.FileVisitResult.CONTINUE; - -public class ClassCollector { - private final Main.Options options; - private final LogPrinter log; - - public ClassCollector(Main.Options options, LogPrinter log) { - this.options = options; - this.log = log; - } - - /** - * Collect all class names passed by the user. - * - * @return array list of classes - */ - public Set> collectClassesToCompile() { - Set> classes = new HashSet<>(); - List filesToScan = new LinkedList<>(options.files); - - if (options.module != null) { - classes.addAll(scanModule(filesToScan)); - } - - classes.addAll(scanFiles(filesToScan)); - return classes; - } - - private Set> scanModule(List filesToScan) { - String module = options.module; - // Search module in standard JDK installation. - Path dir = getModuleDirectory(options.modulepath, module); - - if (Files.isDirectory(dir)) { - return loadFromModuleDirectory(dir); - } else { - findFilesToScan(filesToScan, module); - return new HashSet<>(); - } - } - - private Set> loadFromModuleDirectory(Path dir) { - log.printInfo("Scanning module: " + dir + " ..."); - log.printlnVerbose(" "); // Break line - - FileSystemFinder finder = new FileSystemFinder(dir, pathname -> entryIsClassFile(pathname.toString())); - Set> cls = loadWithClassLoader(() -> ClassLoader.getSystemClassLoader(), dir, finder); - log.printlnInfo(" " + cls.size() + " classes loaded."); - return cls; - } - - private void findFilesToScan(List filesToScan, String module) { - // Try to search regular directory, .jar or .class files - Path path = Paths.get(options.modulepath, module); - - if (Files.isDirectory(path)) { - filesToScan.add("."); - options.classpath = path.toString(); - } else if (path.endsWith(".jar") || path.endsWith(".class")) { - filesToScan.add(path.toString()); - } else { - path = Paths.get(options.modulepath, module + ".jar"); - if (Files.exists(path)) { - filesToScan.add(path.toString()); - } else { - path = Paths.get(options.modulepath, module + ".class"); - if (Files.exists(path)) { - filesToScan.add(path.toString()); - } else { - throw new InternalError("Expecting a .class, .jar or directory: " + path); - } - } - } - } - - private boolean entryIsClassFile(String entry) { - return entry.endsWith(".class") && !entry.endsWith("module-info.class"); - } - - private Set> scanFiles(List filesToScan) { - Set> classes = new HashSet<>(); - for (String fileName : filesToScan) { - Set> loaded = scanFile(fileName); - log.printlnInfo(" " + loaded.size() + " classes loaded."); - classes.addAll(loaded); - } - return classes; - } - - interface ClassLoaderFactory { - ClassLoader create() throws IOException; - } - - private Set> loadWithClassLoader(ClassLoaderFactory factory, Path root, FileSystemFinder finder) { - ClassLoader loader = null; - try { - loader = factory.create(); - return loadClassFiles(root, finder, loader); - } catch (IOException e) { - throw new InternalError(e); - } finally { - if (loader instanceof AutoCloseable) { - try { - ((AutoCloseable) loader).close(); - } catch (Exception e) { - throw new InternalError(e); - } - } - } - } - - private Set> scanFile(String fileName) { - log.printInfo("Scanning: " + fileName + " ..."); - log.printlnVerbose(" "); // Break line - - if (fileName.endsWith(".jar")) { - return loadFromJarFile(fileName); - } else if (fileName.endsWith(".class")) { - Set> classes = new HashSet<>(); - loadFromClassFile(fileName, classes); - return classes; - } else { - return scanClassPath(fileName); - } - } - - private Set> loadFromJarFile(String fileName) { - FileSystem fs = makeFileSystem(fileName); - FileSystemFinder finder = new FileSystemFinder(fs.getPath("/"), pathname -> entryIsClassFile(pathname.toString())); - return loadWithClassLoader(() -> URLClassLoader.newInstance(buildUrls(fileName)), fs.getPath("/"), finder); - } - - private void loadFromClassFile(String fileName, Set> classes) { - Class result; - File file = new File(options.classpath); - try (URLClassLoader loader = URLClassLoader.newInstance(buildUrls(file))) { - result = loadClassFile(loader, fileName); - } catch (IOException e) { - throw new InternalError(e); - } - Class c = result; - addClass(classes, fileName, c); - } - - private Set> scanClassPath(String fileName) { - Path classPath = Paths.get(options.classpath); - if (!Files.exists(classPath)) { - throw new InternalError("Path does not exist: " + classPath); - } - if (!Files.isDirectory(classPath)) { - throw new InternalError("Path must be a directory: " + classPath); - } - - // Combine class path and file name and see what it is. - Path combinedPath = Paths.get(options.classpath + File.separator + fileName); - if (combinedPath.endsWith(".class")) { - throw new InternalError("unimplemented"); - } else if (Files.isDirectory(combinedPath)) { - return scanDirectory(classPath, combinedPath); - } else { - throw new InternalError("Expecting a .class, .jar or directory: " + fileName); - } - } - - private FileSystem makeFileSystem(String fileName) { - try { - return FileSystems.newFileSystem(makeJarFileURI(fileName), new HashMap<>()); - } catch (IOException e) { - throw new InternalError(e); - } - } - - private URI makeJarFileURI(String fileName) { - try { - return new URI("jar:file:" + Paths.get(fileName).toAbsolutePath() + "!/"); - } catch (URISyntaxException e) { - throw new InternalError(e); - } - } - - private PathMatcher combine(PathMatcher m1, PathMatcher m2) { - return path -> m1.matches(path) && m2.matches(path); - } - - private Set> scanDirectory(Path classPath, Path combinedPath) { - String dir = options.classpath; - - FileSystem fileSystem = FileSystems.getDefault(); - PathMatcher matcher = fileSystem.getPathMatcher("glob:" + "*.class"); - FileSystemFinder finder = new FileSystemFinder(combinedPath, - combine(matcher, pathname -> entryIsClassFile(pathname.toString()))); - - File file = new File(dir); - try (URLClassLoader loader = URLClassLoader.newInstance(buildUrls(file))) { - return loadClassFiles(classPath, finder, loader); - } catch (IOException e) { - throw new InternalError(e); - } - } - - private Set> loadClassFiles(Path root, FileSystemFinder finder, ClassLoader loader) { - Set> classes = new HashSet<>(); - for (Path name : finder.done()) { - // Now relativize to the class path so we get the actual class names. - String entry = root.relativize(name).normalize().toString(); - Class c = loadClassFile(loader, entry); - addClass(classes, entry, c); - } - return classes; - } - - private void addClass(Set> classes, String name, Class c) { - if (c != null) { - classes.add(c); - log.printlnVerbose(" loaded " + name); - } - } - - private URL[] buildUrls(String fileName) throws MalformedURLException { - return new URL[]{ new URL("jar:file:" + Paths.get(fileName).toAbsolutePath() + "!/") }; - } - - private URL[] buildUrls(File file) throws MalformedURLException { - return new URL[] {file.toURI().toURL() }; - } - - private Path getModuleDirectory(String modulepath, String module) { - FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); - return fs.getPath(modulepath, module); - } - - /** - * Loads a class with the given file name from the specified {@link URLClassLoader}. - */ - private Class loadClassFile(final ClassLoader loader, final String fileName) { - int start = 0; - if (fileName.startsWith("/")) { - start = 1; - } - String className = fileName.substring(start, fileName.length() - ".class".length()); - className = className.replace('/', '.'); - try { - return loader.loadClass(className); - } catch (Throwable e) { - // If we are running in JCK mode we ignore all exceptions. - if (options.ignoreClassLoadingErrors) { - log.printError(className + ": " + e); - return null; - } - throw new InternalError(e); - } - } - - /** - * {@link FileVisitor} implementation to find class files recursively. - */ - private static class FileSystemFinder extends SimpleFileVisitor { - private final ArrayList fileNames = new ArrayList<>(); - private final PathMatcher filter; - - FileSystemFinder(Path combinedPath, PathMatcher filter) { - this.filter = filter; - try { - Files.walkFileTree(combinedPath, this); - } catch (IOException e) { - throw new InternalError(e); - } - } - - /** - * Compares the glob pattern against the file name. - */ - void find(Path file) { - Path name = file.getFileName(); - if (name != null && filter.matches(name)) { - fileNames.add(file); - } - } - - List done() { - return fileNames; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - find(file); - return CONTINUE; - } - - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { - find(dir); - return CONTINUE; - } - - } -} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSearch.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSearch.java new file mode 100644 index 00000000000..3fd63b2c0b8 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSearch.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +import jdk.tools.jaotc.LoadedClass; + +import java.util.ArrayList; +import java.util.List; + +public class ClassSearch { + private List providers = new ArrayList<>(); + + public void addProvider(SourceProvider provider) { + providers.add(provider); + } + + public List search(List search, SearchPath searchPath) { + List loaded = new ArrayList<>(); + + List sources = new ArrayList<>(); + + for (SearchFor entry : search) { + sources.add(findSource(entry, searchPath)); + } + + for (ClassSource source : sources) { + source.eachClass((name, loader) -> loaded.add(loadClass(name, loader))); + } + + return loaded; + } + + private LoadedClass loadClass(String name, ClassLoader loader) { + try { + Class clzz = loader.loadClass(name); + return new LoadedClass(name, clzz); + } catch (ClassNotFoundException e) { + throw new InternalError("Failed to load with: " + loader, e); + } + } + + private ClassSource findSource(SearchFor searchFor, SearchPath searchPath) { + ClassSource found = null; + + for (SourceProvider provider : providers) { + if (!searchFor.isUnknown() && !provider.supports(searchFor.getType())) { + continue; + } + + ClassSource source = provider.findSource(searchFor.getName(), searchPath); + if (source != null) { + if (found != null) { + throw new InternalError("Multiple possible sources: " + source + " and: " + found); + } + found = source; + } + } + + if (found == null) { + throw new InternalError("Failed to find: " + searchFor.toString()); + } + return found; + } + + public static List makeList(String type, String argument) { + List list = new ArrayList<>(); + String[] elements = argument.split(":"); + for (String element : elements) { + list.add(new SearchFor(element, type)); + } + return list; + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSource.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSource.java new file mode 100644 index 00000000000..8d9b8439760 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/ClassSource.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +import java.nio.file.Path; +import java.util.function.BiConsumer; + +public interface ClassSource { + static boolean pathIsClassFile(Path entry) { + String fileName = entry.getFileName().toString(); + return fileName.endsWith(".class") && !fileName.endsWith("module-info.class"); + } + + static String makeClassName(Path path) { + String fileName = path.toString(); + + if (!fileName.endsWith(".class")) { + throw new IllegalArgumentException("File doesn't end with .class: '" + fileName + "'"); + } + + int start = 0; + if (fileName.startsWith("/")) { + start = 1; + } + + String className = fileName.substring(start, fileName.length() - ".class".length()); + className = className.replace('/', '.'); + return className; + } + + void eachClass(BiConsumer consumer); +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSupport.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSupport.java new file mode 100644 index 00000000000..0761c0ae8e1 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSupport.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +import java.io.IOException; +import java.net.*; +import java.nio.file.*; +import java.util.HashMap; + +public class FileSupport { + public boolean exists(Path path) { + return Files.exists(path); + } + + public boolean isDirectory(Path path) { + return Files.isDirectory(path); + } + + private FileSystem makeJarFileSystem(Path path) { + try { + return FileSystems.newFileSystem(makeJarFileURI(path), new HashMap<>()); + } catch (IOException e) { + throw new InternalError(e); + } + } + + private URI makeJarFileURI(Path path) { + try { + return new URI("jar:file:" + path.toAbsolutePath() + "!/"); + } catch (URISyntaxException e) { + throw new InternalError(e); + } + } + + public ClassLoader createClassLoader(Path path, ClassLoader parent) { + try { + return URLClassLoader.newInstance(buildUrls(path), parent); + } catch (MalformedURLException e) { + throw new InternalError(e); + } + } + + public ClassLoader createClassLoader(Path path) throws MalformedURLException { + return URLClassLoader.newInstance(buildUrls(path)); + } + + private URL[] buildUrls(Path path) throws MalformedURLException { + return new URL[] { path.toUri().toURL() }; + } + + public Path getJarFileSystemRoot(Path jarFile) { + FileSystem fileSystem = makeJarFileSystem(jarFile); + return fileSystem.getPath("/"); + } + + public boolean isAbsolute(Path entry) { + return entry.isAbsolute(); + } + + public Path getSubDirectory(FileSystem fileSystem, Path root, Path path) throws IOException { + DirectoryStream paths = fileSystem.provider().newDirectoryStream(root,null); + for (Path entry : paths) { + Path relative = root.relativize(entry); + if (relative.equals(path)) { + return entry; + } + } + return null; + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSystemFinder.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSystemFinder.java new file mode 100644 index 00000000000..7838104b89c --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/FileSystemFinder.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Iterator; + +import static java.nio.file.FileVisitResult.CONTINUE; + +/** + * {@link FileVisitor} implementation to find class files recursively. + */ +public class FileSystemFinder extends SimpleFileVisitor implements Iterable { + private final ArrayList fileNames = new ArrayList<>(); + private final PathMatcher filter; + + public FileSystemFinder(Path combinedPath, PathMatcher filter) { + this.filter = filter; + try { + Files.walkFileTree(combinedPath, this); + } catch (IOException e) { + throw new InternalError(e); + } + } + + /** + * Compares the glob pattern against the file name. + */ + private void find(Path file) { + Path name = file.getFileName(); + if (name != null && filter.matches(name)) { + fileNames.add(file); + } + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + find(file); + return CONTINUE; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + find(dir); + return CONTINUE; + } + + + @Override + public Iterator iterator() { + return fileNames.iterator(); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchFor.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchFor.java new file mode 100644 index 00000000000..49e0cdd9945 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchFor.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +public class SearchFor { + private final String name; + private final String type; + + public SearchFor(String name) { + this(name, "unknown"); + } + + public SearchFor(String name, String type) { + this.name = name; + this.type = type; + } + + public boolean isUnknown() { + return "unknown".equals(type); + } + + public String getType() { + return this.type; + } + + public String getName() { + return this.name; + } + + @Override + public String toString() { + return type + ":" + name; + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchPath.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchPath.java new file mode 100644 index 00000000000..19442069f16 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SearchPath.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class SearchPath { + private final List searchPaths = new ArrayList<>(); + private final FileSupport fileSupport; + + public SearchPath() { + this(new FileSupport()); + } + + public SearchPath(FileSupport fileSupport) { + this.fileSupport = fileSupport; + } + + public Path find(FileSystem fileSystem, Path entry, String... defaults) { + if (isAbsolute(entry)) { + if (exists(entry)) { + return entry; + } + return null; + } + + if (exists(entry)) { + return entry; + } + + for (String searchPath : defaults) { + Path newPath = fileSystem.getPath(searchPath, entry.toString()); + if (exists(newPath)) { + return newPath; + } + } + + for (Path searchPath : searchPaths) { + Path newPath = fileSystem.getPath(searchPath.toString(), entry.toString()); + if (exists(newPath)) { + return newPath; + } + } + + return null; + } + + private boolean isAbsolute(Path entry) { + return fileSupport.isAbsolute(entry); + } + + private boolean exists(Path entry) { + return fileSupport.exists(entry); + } + + public void add(String... paths) { + for (String name : paths) { + Path path = Paths.get(name); + searchPaths.add(path); + } + } +} + diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SourceProvider.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SourceProvider.java new file mode 100644 index 00000000000..5effa83c8fa --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/SourceProvider.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect; + +public interface SourceProvider { + ClassSource findSource(String name, SearchPath searchPath); + + boolean supports(String type); +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSource.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSource.java new file mode 100644 index 00000000000..22227d03882 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSource.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.classname; + +import jdk.tools.jaotc.collect.ClassSource; + +import java.util.function.BiConsumer; + +public class ClassNameSource implements ClassSource { + private final String name; + private final ClassLoader classLoader; + + public ClassNameSource(String name, ClassLoader classLoader) { + this.name = name; + this.classLoader = classLoader; + } + + @Override + public void eachClass(BiConsumer consumer) { + consumer.accept(name, classLoader); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSourceProvider.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSourceProvider.java new file mode 100644 index 00000000000..b5bc2804ed4 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/classname/ClassNameSourceProvider.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.classname; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSupport; +import jdk.tools.jaotc.collect.SearchPath; +import jdk.tools.jaotc.collect.SourceProvider; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public class ClassNameSourceProvider implements SourceProvider { + public final static String TYPE = "classname"; + private final ClassLoader classLoader; + + public ClassNameSourceProvider(FileSupport fileSupport) { + String classPath = System.getProperty("java.class.path"); + ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); + if (classPath != null && !classPath.isEmpty()) { + classLoader = systemClassLoader; + } else { + Path path = Paths.get(".").toAbsolutePath(); + classLoader = fileSupport.createClassLoader(path, systemClassLoader); + } + } + + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + try { + classLoader.loadClass(name); + return new ClassNameSource(name, classLoader); + } catch (ClassNotFoundException e) { + return null; + } + } + + @Override + public boolean supports(String type) { + return TYPE.equals(type); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySource.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySource.java new file mode 100644 index 00000000000..8e5cdb5bc47 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySource.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.directory; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSystemFinder; + +import java.nio.file.Path; +import java.util.function.BiConsumer; + +public class DirectorySource implements ClassSource { + private final Path directoryPath; + private final ClassLoader classLoader; + + public DirectorySource(Path directoryPath, ClassLoader classLoader) { + this.directoryPath = directoryPath; + this.classLoader = classLoader; + } + + @Override + public void eachClass(BiConsumer consumer) { + FileSystemFinder finder = new FileSystemFinder(directoryPath, ClassSource::pathIsClassFile); + + for (Path path : finder) { + consumer.accept(ClassSource.makeClassName(directoryPath.relativize(path).normalize()), classLoader); + } + } + + @Override + public String toString() { + return "directory:" + directoryPath.toString(); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySourceProvider.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySourceProvider.java new file mode 100644 index 00000000000..013e3858830 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/directory/DirectorySourceProvider.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.directory; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSupport; +import jdk.tools.jaotc.collect.SearchPath; +import jdk.tools.jaotc.collect.SourceProvider; + +import java.net.MalformedURLException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; + +public class DirectorySourceProvider implements SourceProvider { + private final FileSupport fileSupport; + private final FileSystem fileSystem; + public final static String TYPE = "directory"; + + public DirectorySourceProvider(FileSupport fileSupport) { + this.fileSupport = fileSupport; + fileSystem = FileSystems.getDefault(); + } + + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + Path directoryPath = fileSystem.getPath(name); + + if (!fileSupport.exists(directoryPath)) { + return null; + } + if (!fileSupport.isDirectory(directoryPath)) { + return null; + } + + try { + ClassLoader classLoader = fileSupport.createClassLoader(directoryPath); + return new DirectorySource(directoryPath, classLoader); + } catch (MalformedURLException e) { + return null; + } + } + + @Override + public boolean supports(String type) { + return TYPE.equals(type); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarFileSource.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarFileSource.java new file mode 100644 index 00000000000..af7330a53b8 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarFileSource.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.jar; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSystemFinder; + +import java.nio.file.Path; +import java.util.function.BiConsumer; + +public class JarFileSource implements ClassSource { + private final Path jarFile; + private final Path jarRootPath; + private final ClassLoader classLoader; + + + public JarFileSource(Path jarFile, Path jarRootPath, ClassLoader classLoader) { + this.jarFile = jarFile; + this.jarRootPath = jarRootPath; + this.classLoader = classLoader; + } + + public void eachClass(BiConsumer consumer) { + FileSystemFinder finder = new FileSystemFinder(jarRootPath, ClassSource::pathIsClassFile); + + for (Path path : finder) { + consumer.accept(ClassSource.makeClassName(jarRootPath.relativize(path).normalize()), classLoader); + } + } + + @Override + public String toString() { + return "jar:" + jarFile.toString(); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarSourceProvider.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarSourceProvider.java new file mode 100644 index 00000000000..f876c740b74 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/jar/JarSourceProvider.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.jar; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSupport; +import jdk.tools.jaotc.collect.SearchPath; +import jdk.tools.jaotc.collect.SourceProvider; + +import java.net.MalformedURLException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.ProviderNotFoundException; + +public class JarSourceProvider implements SourceProvider { + private final FileSystem fileSystem; + private final FileSupport fileSupport; + public final static String TYPE = "jar"; + + public JarSourceProvider() { + this(new FileSupport()); + } + + public JarSourceProvider(FileSupport fileSupport) { + this.fileSupport = fileSupport; + fileSystem = FileSystems.getDefault(); + } + + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + Path fileName = fileSystem.getPath(name); + Path jarFile = searchPath.find(fileSystem, fileName); + + if (!validPath(jarFile)) { + return null; + } + + return createSource(jarFile); + } + + private ClassSource createSource(Path jarFile) { + try { + Path jarRootPath = fileSupport.getJarFileSystemRoot(jarFile); + if (jarRootPath == null) { + return null; + } + ClassLoader classLoader = fileSupport.createClassLoader(jarFile); + return new JarFileSource(jarFile, jarRootPath, classLoader); + } catch (ProviderNotFoundException | MalformedURLException e) { + } + return null; + } + + @Override + public boolean supports(String type) { + return TYPE.equals(type); + } + + private boolean validPath(Path jarFile) { + return jarFile != null && !fileSupport.isDirectory(jarFile); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSource.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSource.java new file mode 100644 index 00000000000..bac5624ab6a --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSource.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.module; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSystemFinder; + +import java.nio.file.Path; +import java.util.function.BiConsumer; + +public class ModuleSource implements ClassSource { + private final Path modulePath; + private final ClassLoader classLoader; + + public ModuleSource(Path modulePath, ClassLoader classLoader) { + this.modulePath = modulePath; + this.classLoader = classLoader; + } + + @Override + public void eachClass(BiConsumer consumer) { + FileSystemFinder finder = new FileSystemFinder(modulePath, ClassSource::pathIsClassFile); + + for (Path path : finder) { + consumer.accept(ClassSource.makeClassName(modulePath.relativize(path).normalize()), classLoader); + } + } + + public Path getModulePath() { + return modulePath; + } + + @Override + public String toString() { + return "module:" + modulePath.toString(); + } +} diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSourceProvider.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSourceProvider.java new file mode 100644 index 00000000000..cd1a464b6f9 --- /dev/null +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/collect/module/ModuleSourceProvider.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.collect.module; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.collect.FileSupport; +import jdk.tools.jaotc.collect.SearchPath; +import jdk.tools.jaotc.collect.SourceProvider; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; + +public class ModuleSourceProvider implements SourceProvider { + private final FileSystem fileSystem; + private final ClassLoader classLoader; + private final FileSupport fileSupport; + public final static String TYPE = "module"; + + public ModuleSourceProvider() { + this(FileSystems.getFileSystem(URI.create("jrt:/")), ClassLoader.getSystemClassLoader(), new FileSupport()); + } + + public ModuleSourceProvider(FileSystem fileSystem, ClassLoader classLoader, FileSupport fileSupport) { + this.fileSystem = fileSystem; + this.classLoader = classLoader; + this.fileSupport = fileSupport; + } + + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + Path path = fileSystem.getPath(name); + Path dir = fileSystem.getPath("modules"); + + if (dir == null || !fileSupport.isDirectory(dir)) { + return null; + } + + Path found = findModuleDirectory(dir, path); + + if (found == null) { + return null; + } + + return new ModuleSource(found, classLoader); + } + + private Path findModuleDirectory(Path root, Path path) { + try { + return fileSupport.getSubDirectory(fileSystem, root, path); + } catch (IOException e) { + throw new InternalError(e); + } + } + + @Override + public boolean supports(String type) { + return TYPE.equals(type); + } +} diff --git a/hotspot/test/compiler/aot/AotCompiler.java b/hotspot/test/compiler/aot/AotCompiler.java index b9ace71767b..a9e4df91195 100644 --- a/hotspot/test/compiler/aot/AotCompiler.java +++ b/hotspot/test/compiler/aot/AotCompiler.java @@ -69,7 +69,7 @@ public class AotCompiler { extraopts.add("-classpath"); extraopts.add(Utils.TEST_CLASS_PATH + File.pathSeparator + Utils.TEST_SRC); if (className != null && libName != null) { - OutputAnalyzer oa = launchCompiler(libName, className + ".class", extraopts, compileList); + OutputAnalyzer oa = launchCompiler(libName, className, extraopts, compileList); oa.shouldHaveExitValue(0); } else { printUsage(); @@ -100,6 +100,7 @@ public class AotCompiler { args.add("--compile-commands"); args.add(file.toString()); } + args.add("--classname"); args.add(item); return launchJaotc(args, extraopts); } diff --git a/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionTest.java b/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionTest.java deleted file mode 100644 index eeee8db6cde..00000000000 --- a/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * 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 - * @library / /test/lib /testlibrary - * @modules java.base/jdk.internal.misc - * @requires vm.bits == "64" & os.arch == "amd64" & os.family == "linux" - * @build compiler.aot.cli.jaotc.ClasspathOptionTest - * @run driver ClassFileInstaller compiler.aot.cli.jaotc.data.HelloWorldOne - * @run driver compiler.aot.cli.jaotc.ClasspathOptionTest - * @summary check jaotc can compile class from classpath - */ - -package compiler.aot.cli.jaotc; - -import compiler.aot.cli.jaotc.data.HelloWorldOne; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import jdk.test.lib.Asserts; -import jdk.test.lib.process.OutputAnalyzer; - -public class ClasspathOptionTest { - public static void main(String[] args) { - Path cp = Paths.get("testClasspath"); - try { - Files.createDirectory(cp); - Files.move(Paths.get("compiler"), cp.resolve("compiler")); - } catch (IOException e) { - throw new Error("TESTBUG: can't create test data " + e, e); - } - OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--classpath", cp.toString(), - JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class)); - oa.shouldHaveExitValue(0); - File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); - Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); - Asserts.assertGT(compiledLibrary.length(), 0L, "Unexpected compiled library size"); - JaotcTestHelper.checkLibraryUsage(HelloWorldOne.class.getName()); - } -} diff --git a/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionUnknownClassTest.java b/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionUnknownClassTest.java index 1b99249abec..94af41f39bb 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionUnknownClassTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/ClasspathOptionUnknownClassTest.java @@ -39,7 +39,7 @@ import jdk.test.lib.process.OutputAnalyzer; public class ClasspathOptionUnknownClassTest { public static void main(String[] args) { - OutputAnalyzer oa = JaotcTestHelper.compileLibrary("HelloWorldOne.class"); + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--classname", "HelloWorldOne"); Asserts.assertNE(oa.getExitValue(), 0, "Unexpected compilation exit code"); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); Asserts.assertFalse(compiledLibrary.exists(), "Compiler library unexpectedly exists"); diff --git a/hotspot/test/compiler/aot/cli/jaotc/CompileClassTest.java b/hotspot/test/compiler/aot/cli/jaotc/CompileClassTest.java index a59e9e52b69..84ffa60c31e 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/CompileClassTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/CompileClassTest.java @@ -41,7 +41,7 @@ import jdk.test.lib.process.OutputAnalyzer; public class CompileClassTest { public static void main(String[] args) { - OutputAnalyzer oa = JaotcTestHelper.compileLibrary(JaotcTestHelper + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--classname", JaotcTestHelper .getClassAotCompilationName(HelloWorldOne.class)); oa.shouldHaveExitValue(0); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); diff --git a/hotspot/test/compiler/aot/cli/jaotc/CompileDirectoryTest.java b/hotspot/test/compiler/aot/cli/jaotc/CompileDirectoryTest.java index 7157294b9ad..051591bbe43 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/CompileDirectoryTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/CompileDirectoryTest.java @@ -42,7 +42,7 @@ import jdk.test.lib.process.OutputAnalyzer; public class CompileDirectoryTest { public static void main(String[] args) { - OutputAnalyzer oa =JaotcTestHelper.compileLibrary("."); + OutputAnalyzer oa =JaotcTestHelper.compileLibrary("--directory", "."); oa.shouldHaveExitValue(0); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); diff --git a/hotspot/test/compiler/aot/cli/jaotc/CompileJarTest.java b/hotspot/test/compiler/aot/cli/jaotc/CompileJarTest.java index b94265a4038..6253a4d55f3 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/CompileJarTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/CompileJarTest.java @@ -48,7 +48,7 @@ public class CompileJarTest { public static void main(String[] args) { createJar(); - OutputAnalyzer oa = JaotcTestHelper.compileLibrary(JAR_NAME); + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--jar", JAR_NAME); oa.shouldHaveExitValue(0); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); diff --git a/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java b/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java index e6136ba1b98..3cf87e61685 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java +++ b/hotspot/test/compiler/aot/cli/jaotc/JaotcTestHelper.java @@ -71,7 +71,11 @@ public class JaotcTestHelper { } } - public static String getClassAotCompilationName(Class classToCompile) { + public static String getClassAotCompilationFilename(Class classToCompile) { return classToCompile.getName().replaceAll("\\.", File.separator) + ".class"; } + + public static String getClassAotCompilationName(Class classToCompile) { + return classToCompile.getName(); + } } diff --git a/hotspot/test/compiler/aot/cli/jaotc/ListOptionNotExistingTest.java b/hotspot/test/compiler/aot/cli/jaotc/ListOptionNotExistingTest.java index 099554f3e13..9d3b6af5d22 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/ListOptionNotExistingTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/ListOptionNotExistingTest.java @@ -45,7 +45,7 @@ public class ListOptionNotExistingTest { public static void main(String[] args) { OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", "./notExisting.list", - COMPILE_ITEM); + "--classname", COMPILE_ITEM); int exitCode = oa.getExitValue(); Asserts.assertNE(exitCode, 0, "Unexpected compilation exit code"); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); diff --git a/hotspot/test/compiler/aot/cli/jaotc/ListOptionTest.java b/hotspot/test/compiler/aot/cli/jaotc/ListOptionTest.java index e0b52f5799c..9de50bfe649 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/ListOptionTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/ListOptionTest.java @@ -66,7 +66,7 @@ public class ListOptionTest { throw new Error("TESTBUG: can't write list file " + e, e); } OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", COMPILE_COMMAND_FILE.toString(), - JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class)); + "--classname", JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class)); oa.shouldHaveExitValue(0); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); diff --git a/hotspot/test/compiler/aot/cli/jaotc/ListOptionWrongFileTest.java b/hotspot/test/compiler/aot/cli/jaotc/ListOptionWrongFileTest.java index b3f0d1e626f..0f3fd1260fb 100644 --- a/hotspot/test/compiler/aot/cli/jaotc/ListOptionWrongFileTest.java +++ b/hotspot/test/compiler/aot/cli/jaotc/ListOptionWrongFileTest.java @@ -49,12 +49,15 @@ public class ListOptionWrongFileTest { private static final String COMPILE_ITEM = JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class); + private static final String COMPILE_FILE + = JaotcTestHelper.getClassAotCompilationFilename(HelloWorldOne.class); + public static void main(String[] args) { // expecting wrong file to be read but no compilation directive recognized, so, all compiled - OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", COMPILE_ITEM, COMPILE_ITEM); + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", COMPILE_FILE, "--classname", COMPILE_ITEM); oa.shouldHaveExitValue(0); File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); - Asserts.assertTrue(compiledLibrary.exists(), "Expecte compiler library to exist"); + Asserts.assertTrue(compiledLibrary.exists(), "Expected compiler library to exist"); JaotcTestHelper.checkLibraryUsage(HelloWorldOne.class.getName(), EXPECTED, null); } } diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSearchTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSearchTest.java new file mode 100644 index 00000000000..b212fc3139c --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSearchTest.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + + +import jdk.tools.jaotc.LoadedClass; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiConsumer; + +public class ClassSearchTest { + @Test(expected = InternalError.class) + public void itShouldThrowExceptionIfNoProvidersAvailable() { + ClassSearch target = new ClassSearch(); + SearchPath searchPath = new SearchPath(); + target.search(list("foo"), searchPath); + } + + @Test + public void itShouldFindAProviderForEachEntry() { + Set searched = new HashSet<>(); + ClassSearch target = new ClassSearch(); + target.addProvider(new SourceProvider() { + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + searched.add(name); + return new NoopSource(); + } + }); + target.search(list("foo", "bar", "foobar"), null); + Assert.assertEquals(hashset("foo", "bar", "foobar"), searched); + } + + @Test + public void itShouldSearchAllProviders() { + Set visited = new HashSet<>(); + ClassSearch target = new ClassSearch(); + target.addProvider((name, searchPath) -> { + visited.add("1"); + return null; + }); + target.addProvider((name, searchPath) -> { + visited.add("2"); + return null; + }); + + try { + target.search(list("foo"), null); + } catch (InternalError e) { + // throws because no provider gives a source + } + + Assert.assertEquals(hashset("1", "2"), visited); + } + + @Test + public void itShouldTryToLoadSaidClassFromClassLoader() { + Set loaded = new HashSet<>(); + + ClassSearch target = new ClassSearch(); + target.addProvider(new SourceProvider() { + @Override + public ClassSource findSource(String name, SearchPath searchPath) { + return new ClassSource() { + @Override + public void eachClass(BiConsumer consumer) { + consumer.accept("foo.Bar", new ClassLoader() { + @Override + public Class loadClass(String name) throws ClassNotFoundException { + loaded.add(name); + return null; + } + }); + } + }; + } + }); + + java.util.List search = target.search(list("/tmp/something"), null); + Assert.assertEquals(list(new LoadedClass("foo.Bar", null)), search); + } + + @Test(expected = InternalError.class) + public void itShouldThrowInternalErrorWhenClassLoaderFails() { + ClassLoader classLoader = new ClassLoader() { + @Override + public Class loadClass(String name1) throws ClassNotFoundException { + throw new ClassNotFoundException("failed to find " + name1); + } + }; + + ClassSearch target = new ClassSearch(); + target.addProvider((name, searchPath) -> consumer -> consumer.accept("foo.Bar", classLoader)); + target.search(list("foobar"), null); + } + + private List list(T... entries) { + List list = new ArrayList(); + for (T entry : entries) { + list.add(entry); + } + return list; + } + + private Set hashset(T... entries) { + Set set = new HashSet(); + for (T entry : entries) { + set.add(entry); + } + return set; + } + + private static class NoopSource implements ClassSource { + @Override + public void eachClass(BiConsumer consumer) { + } + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSourceTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSourceTest.java new file mode 100644 index 00000000000..5fad5f57d76 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/ClassSourceTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + +import org.junit.Assert; +import org.junit.Test; + +import java.nio.file.Paths; + +import static jdk.tools.jaotc.collect.ClassSource.makeClassName; + +public class ClassSourceTest { + @Test(expected=IllegalArgumentException.class) + public void itShouldThrowExceptionIfPathDoesntEndWithClass() { + makeClassName(Paths.get("Bar.clazz")); + } + + @Test + public void itShouldReplaceSlashesWithDots() { + Assert.assertEquals("foo.Bar", makeClassName(Paths.get("foo/Bar.class"))); + } + + @Test + public void itShouldStripLeadingSlash() { + Assert.assertEquals("Hello", makeClassName(Paths.get("/Hello.class"))); + } + + @Test + public void itShouldReplaceMultipleDots() { + Assert.assertEquals("some.foo.bar.FooBar", makeClassName(Paths.get("/some/foo/bar/FooBar.class"))); + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeFileSupport.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeFileSupport.java new file mode 100644 index 00000000000..178c3d47353 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeFileSupport.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + +import java.net.MalformedURLException; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; + +public class FakeFileSupport extends FileSupport { + private final Set exists = new HashSet<>(); + private final Set directories = new HashSet<>(); + + private final Set checkedExists = new HashSet<>(); + private final Set checkedDirectory = new HashSet<>(); + private final Set checkedJarFileSystemRoots = new HashSet<>(); + private final Set classloaderPaths = new HashSet<>(); + + private Path jarFileSystemRoot = null; + private final ClassLoader classLoader; + + public FakeFileSupport(Set existing, Set directories) { + this.exists.addAll(existing); + this.directories.addAll(directories); + + classLoader = new ClassLoader() { + @Override + public Class loadClass(String name) throws ClassNotFoundException { + return null; + } + }; + } + + public void setJarFileSystemRoot(Path path) { + jarFileSystemRoot = path; + } + + @Override + public boolean exists(Path path) { + checkedExists.add(path.toString()); + return exists.contains(path.toString()); + } + + @Override + public boolean isDirectory(Path path) { + checkedDirectory.add(path.toString()); + return directories.contains(path.toString()); + } + + @Override + public ClassLoader createClassLoader(Path path) throws MalformedURLException { + classloaderPaths.add(path.toString()); + return classLoader; + } + + @Override + public Path getJarFileSystemRoot(Path jarFile) { + checkedJarFileSystemRoots.add(jarFile.toString()); + return jarFileSystemRoot; + } + + @Override + public boolean isAbsolute(Path entry) { + return entry.toString().startsWith("/"); + } + + public void addExist(String name) { + exists.add(name); + } + + public void addDirectory(String name) { + directories.add(name); + } + + public Set getCheckedExists() { + return checkedExists; + } + + public Set getCheckedDirectory() { + return checkedDirectory; + } + + public Set getCheckedJarFileSystemRoots() { + return checkedJarFileSystemRoots; + } + + public Set getClassloaderPaths() { + return classloaderPaths; + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeSearchPath.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeSearchPath.java new file mode 100644 index 00000000000..9a7873ccf96 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/FakeSearchPath.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + +import java.nio.file.FileSystem; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Set; + +import static jdk.tools.jaotc.test.collect.Utils.set; + +public class FakeSearchPath extends SearchPath { + private Path path = null; + public Set entries = set(); + + public FakeSearchPath(String name) { + if (name != null) { + path = Paths.get(name); + } + } + + @Override + public Path find(FileSystem fileSystem, Path entry, String... defaults) { + entries.add(entry.toString()); + return path; + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/SearchPathTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/SearchPathTest.java new file mode 100644 index 00000000000..8ceca8dc5cf --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/SearchPathTest.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + +import org.junit.Before; +import org.junit.Test; + +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static jdk.tools.jaotc.test.collect.Utils.set; +import static org.junit.Assert.*; + +public class SearchPathTest { + private FakeFileSupport fileSupport; + private FileSystem fs; + + @Before + public void setUp() throws Exception { + fs = FileSystems.getDefault(); + } + + @Test + public void itShouldUsePathIfPathIsAbsoluteAndExisting() { + fileSupport = new FakeFileSupport(set("/foo"), set()); + SearchPath target = new SearchPath(fileSupport); + Path foo = Paths.get("/foo"); + Path result = target.find(fs, foo); + assertSame(result, foo); + } + + @Test + public void itShouldReturnNullIfPathIsAbsoluteAndNonExisting() { + fileSupport = new FakeFileSupport(set(), set()); + SearchPath target = new SearchPath(fileSupport); + Path result = target.find(fs, Paths.get("/bar")); + assertNull(result); + } + + @Test + public void itShouldUseRelativeExisting() { + fileSupport = new FakeFileSupport(set("hello", "tmp/hello", "search/hello"), set()); + SearchPath target = new SearchPath(fileSupport); + target.add("search"); + Path hello = Paths.get("hello"); + Path result = target.find(fs, hello, "tmp"); + assertSame(result, hello); + } + + @Test + public void itShouldSearchDefaultsBeforeSearchPaths() { + fileSupport = new FakeFileSupport(set("bar/foobar"), set()); + SearchPath target = new SearchPath(fileSupport); + Path result = target.find(fs, Paths.get("foobar"), "default1", "bar"); + assertEquals("bar/foobar", result.toString()); + assertEquals(set("foobar", "default1/foobar", "bar/foobar"), fileSupport.getCheckedExists()); + } + + @Test + public void itShouldUseSearchPathsIfNotInDefaults() { + fileSupport = new FakeFileSupport(set("bar/tmp/foobar"), set()); + SearchPath target = new SearchPath(fileSupport); + target.add("foo/tmp", "bar/tmp"); + + Path result = target.find(fs, Paths.get("foobar"), "foo", "bar"); + assertEquals("bar/tmp/foobar", result.toString()); + assertEquals(set("foobar", "foo/foobar", "bar/foobar", "bar/tmp/foobar", "foo/tmp/foobar"), fileSupport.getCheckedExists()); + } + + @Test + public void itShouldReturnNullIfNoExistingPathIsFound() { + fileSupport = new FakeFileSupport(set(), set()); + SearchPath target = new SearchPath(fileSupport); + target.add("dir1", "dir2"); + + Path result = target.find(fs, Paths.get("entry"), "dir3", "dir4"); + assertNull(result); + assertEquals(set("entry", "dir1/entry", "dir2/entry", "dir3/entry", "dir4/entry"), fileSupport.getCheckedExists()); + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/Utils.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/Utils.java new file mode 100644 index 00000000000..589027cde4c --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/Utils.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect; + +import java.util.HashSet; +import java.util.Set; + +public class Utils { + public static Set set(T... entries) { + Set set = new HashSet(); + for (T entry : entries) { + set.add(entry); + } + return set; + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/directory/DirectorySourceProviderTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/directory/DirectorySourceProviderTest.java new file mode 100644 index 00000000000..6608c01ab50 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/directory/DirectorySourceProviderTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.tools.jaotc.test.collect.directory; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.test.collect.FakeFileSupport; +import jdk.tools.jaotc.test.collect.FileSupport; +import org.junit.Assert; +import org.junit.Test; + +import java.net.MalformedURLException; +import java.nio.file.Path; +import java.util.Set; + +import static jdk.tools.jaotc.test.collect.Utils.set; + +public class DirectorySourceProviderTest { + @Test + public void itShouldReturnNullForNonExistantPath() { + DirectorySourceProvider target = new DirectorySourceProvider(new FakeFileSupport(set(), set())); + ClassSource result = target.findSource("hello", null); + Assert.assertNull(result); + } + + @Test + public void itShouldReturnNullForNonDirectory() { + DirectorySourceProvider target = new DirectorySourceProvider(new FakeFileSupport(set("foobar"), set())); + ClassSource result = target.findSource("foobar", null); + Assert.assertNull(result); + } + + @Test + public void itShouldReturnNullForMalformedURI() { + Set visited = set(); + DirectorySourceProvider target = new DirectorySourceProvider(new FakeFileSupport(set("foobar"), set("foobar")) { + @Override + public ClassLoader createClassLoader(Path path) throws MalformedURLException { + visited.add("1"); + throw new MalformedURLException("..."); + } + }); + ClassSource result = target.findSource("foobar", null); + Assert.assertNull(result); + Assert.assertEquals(set("1"), visited); + } + + @Test + public void itShouldCreateSourceIfNameExistsAndIsADirectory() { + FileSupport fileSupport = new FakeFileSupport(set("foo"), set("foo")); + DirectorySourceProvider target = new DirectorySourceProvider(fileSupport); + ClassSource foo = target.findSource("foo", null); + Assert.assertNotNull(foo); + Assert.assertEquals("directory:foo", foo.toString()); + } + +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/jar/JarSourceProviderTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/jar/JarSourceProviderTest.java new file mode 100644 index 00000000000..14059883538 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/jar/JarSourceProviderTest.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect.jar; + +import jdk.tools.jaotc.collect.ClassSource; +import jdk.tools.jaotc.test.collect.FakeFileSupport; +import jdk.tools.jaotc.test.collect.FakeSearchPath; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.ProviderNotFoundException; +import java.util.Set; + +import static jdk.tools.jaotc.test.collect.Utils.set; + +public class JarSourceProviderTest { + + private FakeFileSupport fileSupport; + private JarSourceProvider target; + + @Before + public void setUp() throws Exception { + fileSupport = new FakeFileSupport(set(), set()); + target = new JarSourceProvider(fileSupport); + } + + @Test + public void itShouldUseSearchPathToFindPath() { + Set visited = set(); + JarSourceProvider target = new JarSourceProvider(fileSupport); + FakeSearchPath searchPath = new FakeSearchPath(null); + ClassSource source = target.findSource("hello", searchPath); + + Assert.assertEquals(set("hello"), searchPath.entries); + } + + @Test + public void itShouldReturnNullIfPathIsNull() { + JarSourceProvider target = new JarSourceProvider(fileSupport); + ClassSource source = target.findSource("foobar", new FakeSearchPath(null)); + Assert.assertNull(source); + } + + @Test + public void itShouldReturnNullIfPathIsDirectory() { + fileSupport.addDirectory("hello/foobar"); + ClassSource source = target.findSource("foobar", new FakeSearchPath("hello/foobar")); + + Assert.assertNull(source); + Assert.assertEquals(set("hello/foobar"), fileSupport.getCheckedDirectory()); + } + + @Test + public void itShouldReturnNullIfUnableToMakeJarFileSystem() { + fileSupport.setJarFileSystemRoot(null); + ClassSource result = target.findSource("foobar", new FakeSearchPath("foo/bar")); + + Assert.assertEquals(set("foo/bar"), fileSupport.getCheckedJarFileSystemRoots()); + Assert.assertNull(result); + } + + @Test + public void itShouldReturnNullIfNotValidJarProvider() { + fileSupport = new FakeFileSupport(set(), set()) { + + @Override + public Path getJarFileSystemRoot(Path jarFile) { + super.getJarFileSystemRoot(jarFile); + throw new ProviderNotFoundException(); + } + }; + fileSupport.setJarFileSystemRoot(null); + target = new JarSourceProvider(fileSupport); + + ClassSource result = target.findSource("foobar", new FakeSearchPath("foo/bar")); + + Assert.assertEquals(set("foo/bar"), fileSupport.getCheckedJarFileSystemRoots()); + Assert.assertNull(result); + } + + @Test + public void itShouldReturnSourceWhenAllIsValid() { + fileSupport.setJarFileSystemRoot(Paths.get("some/bar")); + ClassSource result = target.findSource("foobar", new FakeSearchPath("this/bar")); + + Assert.assertEquals(set("this/bar"), fileSupport.getClassloaderPaths()); + Assert.assertEquals("jar:this/bar", result.toString()); + } +} diff --git a/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/module/ModuleSourceProviderTest.java b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/module/ModuleSourceProviderTest.java new file mode 100644 index 00000000000..80f06913269 --- /dev/null +++ b/hotspot/test/compiler/aot/jdk.tools.jaotc.test/src/jdk/tools/jaotc/test/collect/module/ModuleSourceProviderTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jaotc.test.collect.module; + +import jdk.tools.jaotc.*; +import jdk.tools.jaotc.test.collect.FakeSearchPath; +import jdk.tools.jaotc.test.collect.Utils; +import org.junit.Before; +import org.junit.Test; + +import java.nio.file.FileSystems; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ModuleSourceProviderTest { + private ClassLoader classLoader; + private ModuleSourceProvider target; + + @Before + public void setUp() { + classLoader = new FakeClassLoader(); + target = new ModuleSourceProvider(FileSystems.getDefault(), classLoader); + } + + @Test + public void itShouldUseSearchPath() { + FakeSearchPath searchPath = new FakeSearchPath("blah/java.base"); + ModuleSource source = (ModuleSource) target.findSource("java.base", searchPath); + assertEquals(Utils.set("java.base"), searchPath.entries); + assertEquals("blah/java.base", source.getModulePath().toString()); + assertEquals("module:blah/java.base", source.toString()); + } + + @Test + public void itShouldReturnNullIfSearchPathReturnsNull() { + FakeSearchPath searchPath = new FakeSearchPath(null); + ModuleSource source = (ModuleSource) target.findSource("jdk.base", searchPath); + assertEquals(Utils.set("jdk.base"), searchPath.entries); + assertNull(source); + } + + private static class FakeClassLoader extends ClassLoader { + @Override + public Class loadClass(String name) throws ClassNotFoundException { + return null; + } + } +} diff --git a/hotspot/test/compiler/aot/verification/ClassAndLibraryNotMatchTest.java b/hotspot/test/compiler/aot/verification/ClassAndLibraryNotMatchTest.java index b2741387fa7..c702de31ae8 100644 --- a/hotspot/test/compiler/aot/verification/ClassAndLibraryNotMatchTest.java +++ b/hotspot/test/compiler/aot/verification/ClassAndLibraryNotMatchTest.java @@ -85,9 +85,8 @@ public class ClassAndLibraryNotMatchTest { } private void compileAotLibrary() { - AotCompiler.launchCompiler(LIB_NAME, HELLO_WORLD_CLASS_NAME + ".class", - Arrays.asList("-classpath", Utils.TEST_CLASS_PATH + File.pathSeparator - + Utils.TEST_SRC), null); + AotCompiler.launchCompiler(LIB_NAME, HELLO_WORLD_CLASS_NAME, + Arrays.asList("-classpath", Utils.TEST_CLASS_PATH + ":."), null); } private void runAndCheckHelloWorld(String checkString) { diff --git a/hotspot/test/compiler/aot/verification/vmflags/BasicFlagsChange.java b/hotspot/test/compiler/aot/verification/vmflags/BasicFlagsChange.java index bc60c1cd1ef..f7fd37a5e4a 100644 --- a/hotspot/test/compiler/aot/verification/vmflags/BasicFlagsChange.java +++ b/hotspot/test/compiler/aot/verification/vmflags/BasicFlagsChange.java @@ -76,7 +76,7 @@ public class BasicFlagsChange { extraOpts.add(option); extraOpts.add("-classpath"); extraOpts.add(Utils.TEST_CLASS_PATH + File.pathSeparator + Utils.TEST_SRC); - AotCompiler.launchCompiler(libName, className + ".class", extraOpts, null); + AotCompiler.launchCompiler(libName, className, extraOpts, null); } private static void runAndCheck(String option, String libName, From 68447bd8a37d5189ac20b4b0026b66f13dda7ece Mon Sep 17 00:00:00 2001 From: Christian Tornqvist Date: Thu, 5 Jan 2017 16:46:28 -0500 Subject: [PATCH 032/130] 8172188: JDI tests fail due to "permission denied" when creating temp file Reviewed-by: hseigel, mseledtsov --- jdk/test/com/sun/jdi/ShellScaffold.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/jdk/test/com/sun/jdi/ShellScaffold.sh b/jdk/test/com/sun/jdi/ShellScaffold.sh index 7727a8f762d..c8af3a20755 100644 --- a/jdk/test/com/sun/jdi/ShellScaffold.sh +++ b/jdk/test/com/sun/jdi/ShellScaffold.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -276,10 +276,10 @@ setup() # treat them as control chars on mks (eg \t is tab) # Oops; windows mks really seems to want this cat line # to start in column 1 - if [ -w "$SystemRoot" ] ; then - tmpFile=$SystemRoot/tmp.$$ - elif [ -w "$SYSTEMROOT" ] ; then - tmpFile=$SYSTEMROOT/tmp.$$ + if [ -w "$Temp" ] ; then + tmpFile=$Temp/tmp.$$ + elif [ -w "$TEMP" ] ; then + tmpFile=$TEMP/tmp.$$ else tmpFile=tmp.$$ fi From 26a978276c3416212c1b06299b7de2498dd516e4 Mon Sep 17 00:00:00 2001 From: David Leopoldseder Date: Mon, 9 Jan 2017 19:36:47 +0000 Subject: [PATCH 033/130] 8166125: [JVMCI] Missing JVMCI flag default values Reviewed-by: twisti, kvn --- hotspot/src/share/vm/runtime/arguments.cpp | 40 +++++++++++++++++----- hotspot/src/share/vm/runtime/arguments.hpp | 1 + 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index e7e91083416..0ddbb30a8c5 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1854,6 +1854,34 @@ void Arguments::select_gc() { } } +#if INCLUDE_JVMCI +void Arguments::set_jvmci_specific_flags() { + if (UseJVMCICompiler) { + if (FLAG_IS_DEFAULT(TypeProfileWidth)) { + FLAG_SET_DEFAULT(TypeProfileWidth, 8); + } + if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) { + FLAG_SET_DEFAULT(OnStackReplacePercentage, 933); + } + if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) { + FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M); + } + if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) { + FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M); + } + if (FLAG_IS_DEFAULT(MetaspaceSize)) { + FLAG_SET_DEFAULT(MetaspaceSize, 12*M); + } + if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) { + FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K); + } + if (FLAG_IS_DEFAULT(TypeProfileLevel)) { + FLAG_SET_DEFAULT(TypeProfileLevel, 0); + } + } +} +#endif + void Arguments::set_ergonomics_flags() { select_gc(); @@ -2463,14 +2491,6 @@ bool Arguments::check_vm_args_consistency() { warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled"); ScavengeRootsInCode = 1; } - if (FLAG_IS_DEFAULT(TypeProfileLevel)) { - TypeProfileLevel = 0; - } - if (UseJVMCICompiler) { - if (FLAG_IS_DEFAULT(TypeProfileWidth)) { - TypeProfileWidth = 8; - } - } } #endif @@ -4420,6 +4440,10 @@ jint Arguments::apply_ergo() { // Set flags based on ergonomics. set_ergonomics_flags(); +#if INCLUDE_JVMCI + set_jvmci_specific_flags(); +#endif + set_shared_spaces_flags(); // Check the GC selections again. diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index ce94e553d04..36bf75c6b2a 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -638,6 +638,7 @@ class Arguments : AllStatic { #if INCLUDE_JVMCI // Check consistency of jvmci vm argument settings. static bool check_jvmci_args_consistency(); + static void set_jvmci_specific_flags(); #endif // Check for consistency in the selection of the garbage collector. static bool check_gc_consistency(); // Check user-selected gc From dbec733773fb3c12075f043711169a39afaa4c22 Mon Sep 17 00:00:00 2001 From: Dmitrij Pochepko Date: Tue, 10 Jan 2017 20:45:04 +0300 Subject: [PATCH 034/130] 8166374: compiler/loopopts/UseCountedLoopSafepointsTest.java fails with "Safepoint not found" Reviewed-by: thartmann --- .../test/compiler/loopopts/UseCountedLoopSafepointsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java b/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java index 741f0d93d67..25a2ad4e087 100644 --- a/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java +++ b/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java @@ -27,7 +27,7 @@ * @bug 6869327 * @summary Test that C2 flag UseCountedLoopSafepoints ensures a safepoint is kept in a CountedLoop * @library /test/lib / - * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4) + * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4) & vm.debug == true * @modules java.base/jdk.internal.misc * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox From 5b9a2a728bbfed473080eb4aceb52bc6f2bfe679 Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Tue, 10 Jan 2017 21:39:20 +0300 Subject: [PATCH 035/130] 8172310: [AOT] Fix unverified entry point Fix AOT code for the unverified entry point Reviewed-by: kvn --- .../jdk/tools/jaotc/binformat/BinaryContainer.java | 5 +++++ .../src/jdk/tools/jaotc/AOTCompiledClass.java | 14 ++++++++++---- .../src/jdk/tools/jaotc/MarkId.java | 1 + .../src/jdk/tools/jaotc/MarkProcessor.java | 4 ++++ .../hotspot/amd64/AMD64HotSpotBackend.java | 13 +++++++++---- .../compiler/hotspot/amd64/AMD64HotSpotMove.java | 13 ++++++++++--- .../compiler/hotspot/GraalHotSpotVMConfig.java | 7 ++++--- hotspot/src/share/vm/aot/aotCodeHeap.cpp | 1 + hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp | 1 + hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp | 7 ++++--- hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp | 1 + 11 files changed, 50 insertions(+), 17 deletions(-) diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java index 0c411fb7f1d..34ecf011e77 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/BinaryContainer.java @@ -397,6 +397,10 @@ public class BinaryContainer implements SymbolTable { return "_aot_narrow_klass_base_address"; } + public String getNarrowOopBaseAddressSymbolName() { + return "_aot_narrow_oop_base_address"; + } + public String getLogOfHeapRegionGrainBytesSymbolName() { return "_aot_log_of_heap_region_grain_bytes"; } @@ -447,6 +451,7 @@ public class BinaryContainer implements SymbolTable { createGotSymbol(getHeapTopAddressSymbolName()); createGotSymbol(getHeapEndAddressSymbolName()); createGotSymbol(getNarrowKlassBaseAddressSymbolName()); + createGotSymbol(getNarrowOopBaseAddressSymbolName()); createGotSymbol(getPollingPageSymbolName()); createGotSymbol(getLogOfHeapRegionGrainBytesSymbolName()); createGotSymbol(getInlineContiguousAllocationSupportedSymbolName()); diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java index cbf26294b0d..68fb146b8ce 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTCompiledClass.java @@ -293,12 +293,18 @@ public class AOTCompiledClass { // Record methods holder methodInfo.addDependentKlassData(binaryContainer, resolvedJavaType); // Record inlinee classes - for (ResolvedJavaMethod m : methodInfo.getCompilationResult().getMethods()) { - methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) m.getDeclaringClass()); + ResolvedJavaMethod[] inlinees = methodInfo.getCompilationResult().getMethods(); + if (inlinees != null) { + for (ResolvedJavaMethod m : inlinees) { + methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) m.getDeclaringClass()); + } } // Record classes of fields that were accessed - for (ResolvedJavaField f : methodInfo.getCompilationResult().getFields()) { - methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) f.getDeclaringClass()); + ResolvedJavaField[] fields = methodInfo.getCompilationResult().getFields(); + if (fields != null) { + for (ResolvedJavaField f : fields) { + methodInfo.addDependentKlassData(binaryContainer, (HotSpotResolvedObjectType) f.getDeclaringClass()); + } } } } diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java index 4bbd4665434..eedeac3b720 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkId.java @@ -48,6 +48,7 @@ enum MarkId { HEAP_TOP_ADDRESS("CodeInstaller::HEAP_TOP_ADDRESS"), HEAP_END_ADDRESS("CodeInstaller::HEAP_END_ADDRESS"), NARROW_KLASS_BASE_ADDRESS("CodeInstaller::NARROW_KLASS_BASE_ADDRESS"), + NARROW_OOP_BASE_ADDRESS("CodeInstaller::NARROW_OOP_BASE_ADDRESS"), CRC_TABLE_ADDRESS("CodeInstaller::CRC_TABLE_ADDRESS"), LOG_OF_HEAP_REGION_GRAIN_BYTES("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES"), INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED"); diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java index 1e1944bc274..7a833c13914 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/MarkProcessor.java @@ -57,6 +57,7 @@ class MarkProcessor { case HEAP_TOP_ADDRESS: case HEAP_END_ADDRESS: case NARROW_KLASS_BASE_ADDRESS: + case NARROW_OOP_BASE_ADDRESS: case CRC_TABLE_ADDRESS: case LOG_OF_HEAP_REGION_GRAIN_BYTES: case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED: @@ -78,6 +79,9 @@ class MarkProcessor { case NARROW_KLASS_BASE_ADDRESS: vmSymbolName = binaryContainer.getNarrowKlassBaseAddressSymbolName(); break; + case NARROW_OOP_BASE_ADDRESS: + vmSymbolName = binaryContainer.getNarrowOopBaseAddressSymbolName(); + break; case CRC_TABLE_ADDRESS: vmSymbolName = binaryContainer.getCrcTableAddressSymbolName(); break; diff --git a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java index 4ccc1bbc9ef..7cb4b03b27e 100644 --- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java +++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotBackend.java @@ -267,10 +267,15 @@ public class AMD64HotSpotBackend extends HotSpotHostBackend { if (config.useCompressedClassPointers) { Register register = r10; - AMD64HotSpotMove.decodeKlassPointer(asm, register, providers.getRegisters().getHeapBaseRegister(), src, config.getKlassEncoding()); - if (config.narrowKlassBase != 0) { - // The heap base register was destroyed above, so restore it - asm.movq(providers.getRegisters().getHeapBaseRegister(), config.narrowOopBase); + AMD64HotSpotMove.decodeKlassPointer(crb, asm, register, providers.getRegisters().getHeapBaseRegister(), src, config); + if (GeneratePIC.getValue()) { + asm.movq(providers.getRegisters().getHeapBaseRegister(), asm.getPlaceholder(-1)); + crb.recordMark(config.MARKID_NARROW_OOP_BASE_ADDRESS); + } else { + if (config.narrowKlassBase != 0) { + // The heap base register was destroyed above, so restore it + asm.movq(providers.getRegisters().getHeapBaseRegister(), config.narrowOopBase); + } } asm.cmpq(inlineCacheKlass, register); } else { diff --git a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java index f7a5f205c26..168282ebcbf 100644 --- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java +++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotMove.java @@ -265,14 +265,21 @@ public class AMD64HotSpotMove { } } - public static void decodeKlassPointer(AMD64MacroAssembler masm, Register register, Register scratch, AMD64Address address, CompressEncoding encoding) { + public static void decodeKlassPointer(CompilationResultBuilder crb, AMD64MacroAssembler masm, Register register, Register scratch, AMD64Address address, GraalHotSpotVMConfig config) { + CompressEncoding encoding = config.getKlassEncoding(); masm.movl(register, address); if (encoding.shift != 0) { assert encoding.alignment == encoding.shift : "Decode algorithm is wrong"; masm.shlq(register, encoding.alignment); } - if (encoding.base != 0) { - masm.movq(scratch, encoding.base); + if (GeneratePIC.getValue() || encoding.base != 0) { + if (GeneratePIC.getValue()) { + masm.movq(scratch, masm.getPlaceholder(-1)); + crb.recordMark(config.MARKID_NARROW_KLASS_BASE_ADDRESS); + } else { + assert encoding.base != 0; + masm.movq(scratch, encoding.base); + } masm.addq(register, scratch); } } diff --git a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java index e7ce8f68cce..4400099efc5 100644 --- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java +++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java @@ -773,9 +773,10 @@ public class GraalHotSpotVMConfig extends HotSpotVMConfigAccess { public final int MARKID_HEAP_TOP_ADDRESS = getConstant("CodeInstaller::HEAP_TOP_ADDRESS", Integer.class, 17); public final int MARKID_HEAP_END_ADDRESS = getConstant("CodeInstaller::HEAP_END_ADDRESS", Integer.class, 18); public final int MARKID_NARROW_KLASS_BASE_ADDRESS = getConstant("CodeInstaller::NARROW_KLASS_BASE_ADDRESS", Integer.class, 19); - public final int MARKID_CRC_TABLE_ADDRESS = getConstant("CodeInstaller::CRC_TABLE_ADDRESS", Integer.class, 20); - public final int MARKID_LOG_OF_HEAP_REGION_GRAIN_BYTES = getConstant("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES", Integer.class, 21); - public final int MARKID_INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = getConstant("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED", Integer.class, 22); + public final int MARKID_NARROW_OOP_BASE_ADDRESS = getConstant("CodeInstaller::NARROW_OOP_BASE_ADDRESS", Integer.class, 20); + public final int MARKID_CRC_TABLE_ADDRESS = getConstant("CodeInstaller::CRC_TABLE_ADDRESS", Integer.class, 21); + public final int MARKID_LOG_OF_HEAP_REGION_GRAIN_BYTES = getConstant("CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES", Integer.class, 22); + public final int MARKID_INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = getConstant("CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED", Integer.class, 23); // Checkstyle: resume diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.cpp b/hotspot/src/share/vm/aot/aotCodeHeap.cpp index 1cd9576253f..52e2c8d55b1 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp @@ -539,6 +539,7 @@ void AOTCodeHeap::link_global_lib_symbols() { SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_heap_end_address", address, (heap->supports_inline_contig_alloc() ? heap->end_addr() : NULL)); SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_polling_page", address, os::get_polling_page()); SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_klass_base_address", address, Universe::narrow_klass_base()); + SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_narrow_oop_base_address", address, Universe::narrow_oop_base()); SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_log_of_heap_region_grain_bytes", int, HeapRegion::LogOfHRGrainBytes); SET_AOT_GLOBAL_SYMBOL_VALUE("_aot_inline_contiguous_allocation_supported", bool, heap->supports_inline_contig_alloc()); link_shared_runtime_symbols(); diff --git a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp index 9e686ec1568..cca40f1aeb2 100644 --- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp +++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.cpp @@ -1258,6 +1258,7 @@ void CodeInstaller::site_Mark(CodeBuffer& buffer, jint pc_offset, Handle site, T case HEAP_TOP_ADDRESS: case HEAP_END_ADDRESS: case NARROW_KLASS_BASE_ADDRESS: + case NARROW_OOP_BASE_ADDRESS: case CRC_TABLE_ADDRESS: case LOG_OF_HEAP_REGION_GRAIN_BYTES: case INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED: diff --git a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp index e3b38c0688d..a700174de1d 100644 --- a/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp +++ b/hotspot/src/share/vm/jvmci/jvmciCodeInstaller.hpp @@ -133,9 +133,10 @@ private: HEAP_TOP_ADDRESS = 17, HEAP_END_ADDRESS = 18, NARROW_KLASS_BASE_ADDRESS = 19, - CRC_TABLE_ADDRESS = 20, - LOG_OF_HEAP_REGION_GRAIN_BYTES = 21, - INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = 22, + NARROW_OOP_BASE_ADDRESS = 20, + CRC_TABLE_ADDRESS = 21, + LOG_OF_HEAP_REGION_GRAIN_BYTES = 22, + INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED = 23, INVOKE_INVALID = -1 }; diff --git a/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp b/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp index 2dad27fdfd9..5c69ecb4d65 100644 --- a/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp +++ b/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp @@ -429,6 +429,7 @@ declare_constant(CodeInstaller::HEAP_TOP_ADDRESS) \ declare_constant(CodeInstaller::HEAP_END_ADDRESS) \ declare_constant(CodeInstaller::NARROW_KLASS_BASE_ADDRESS) \ + declare_constant(CodeInstaller::NARROW_OOP_BASE_ADDRESS) \ declare_constant(CodeInstaller::CRC_TABLE_ADDRESS) \ declare_constant(CodeInstaller::LOG_OF_HEAP_REGION_GRAIN_BYTES) \ declare_constant(CodeInstaller::INLINE_CONTIGUOUS_ALLOCATION_SUPPORTED) \ From 421bf2f22d4ebbdd92ba0476a7dc33b20528827a Mon Sep 17 00:00:00 2001 From: Zoltan Majo Date: Wed, 11 Jan 2017 09:40:42 +0100 Subject: [PATCH 036/130] 8168926: C2: Bytecode escape analyzer crashes due to stack overflow Whether current call site needs an appendix is determined only based on the target method and the current bytecode instruction. Reviewed-by: kvn, thartmann --- hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp | 28 ++++++++++++++++++-- hotspot/src/share/vm/ci/ciMethod.hpp | 12 ++++++--- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp index f7916cb1dab..e960d142abe 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp @@ -895,8 +895,32 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl ciMethod* target = s.get_method(ignored_will_link, &declared_signature); ciKlass* holder = s.get_declared_method_holder(); assert(declared_signature != NULL, "cannot be null"); - // Push appendix argument, if one. - if (s.has_appendix()) { + // If the current bytecode has an attached appendix argument, + // push an unknown object to represent that argument. (Analysis + // of dynamic call sites, especially invokehandle calls, needs + // the appendix argument on the stack, in addition to "regular" arguments + // pushed onto the stack by bytecode instructions preceding the call.) + // + // The escape analyzer does _not_ use the ciBytecodeStream::has_appendix(s) + // method to determine whether the current bytecode has an appendix argument. + // The has_appendix() method obtains the appendix from the + // ConstantPoolCacheEntry::_f1 field, which can happen concurrently with + // resolution of dynamic call sites. Callees in the + // ciBytecodeStream::get_method() call above also access the _f1 field; + // interleaving the get_method() and has_appendix() calls in the current + // method with call site resolution can lead to an inconsistent view of + // the current method's argument count. In particular, some interleaving(s) + // can cause the method's argument count to not include the appendix, which + // then leads to stack over-/underflow in the escape analyzer. + // + // Instead of pushing the argument if has_appendix() is true, the escape analyzer + // pushes an appendix for all call sites targeted by invokedynamic and invokehandle + // instructions, except if the call site is the _invokeBasic intrinsic + // (that intrinsic is always targeted by an invokehandle instruction but does + // not have an appendix argument). + if (target->is_loaded() && + Bytecodes::has_optional_appendix(s.cur_bc_raw()) && + target->intrinsic_id() != vmIntrinsics::_invokeBasic) { state.apush(unknown_obj); } // Pass in raw bytecode because we need to see invokehandle instructions. diff --git a/hotspot/src/share/vm/ci/ciMethod.hpp b/hotspot/src/share/vm/ci/ciMethod.hpp index 2580f40f3ea..f16948e71d7 100644 --- a/hotspot/src/share/vm/ci/ciMethod.hpp +++ b/hotspot/src/share/vm/ci/ciMethod.hpp @@ -136,15 +136,19 @@ class ciMethod : public ciMetadata { check_is_loaded(); return _signature->size() + (_flags.is_static() ? 0 : 1); } - // Report the number of elements on stack when invoking this method. - // This is different than the regular arg_size because invokedynamic - // has an implicit receiver. + // Report the number of elements on stack when invoking the current method. + // If the method is loaded, arg_size() gives precise information about the + // number of stack elements (using the method's signature and its flags). + // However, if the method is not loaded, the number of stack elements must + // be determined differently, as the method's flags are not yet available. + // The invoke_arg_size() method assumes in that case that all bytecodes except + // invokestatic and invokedynamic have a receiver that is also pushed onto the + // stack by the caller of the current method. int invoke_arg_size(Bytecodes::Code code) const { if (is_loaded()) { return arg_size(); } else { int arg_size = _signature->size(); - // Add a receiver argument, maybe: if (code != Bytecodes::_invokestatic && code != Bytecodes::_invokedynamic) { arg_size++; From b1c82624b9a700c74339139dee096b07c46db854 Mon Sep 17 00:00:00 2001 From: Robbin Ehn Date: Wed, 11 Jan 2017 12:47:16 +0100 Subject: [PATCH 037/130] 8079441: Intermittent failures on Windows with "Unexpected exit from test [exit code: 1080890248]" (0x406d1388) Do not raise (windows thread name) exception 0x406d1388 when no debugger is attached. Reviewed-by: iklam, stuefe --- hotspot/src/os/windows/vm/os_windows.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 5142cd37a25..23ad8e209cb 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -778,6 +778,11 @@ void os::set_native_thread_name(const char *name) { // is already attached to a debugger; debugger must observe // the exception below to show the correct name. + // If there is no debugger attached skip raising the exception + if (!IsDebuggerPresent()) { + return; + } + const DWORD MS_VC_EXCEPTION = 0x406D1388; struct { DWORD dwType; // must be 0x1000 From 8ab1255ff1dc9fe2856bceb876a5d7cc904cafa5 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Wed, 11 Jan 2017 17:43:36 +0300 Subject: [PATCH 038/130] 8172557: quarantine ctw/JarDirTest Reviewed-by: ctornqvi --- hotspot/test/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hotspot/test/ProblemList.txt b/hotspot/test/ProblemList.txt index 7a7f6a64e29..1acd8e90e2b 100644 --- a/hotspot/test/ProblemList.txt +++ b/hotspot/test/ProblemList.txt @@ -77,5 +77,7 @@ serviceability/sa/sadebugd/SADebugDTest.java 8163805 generic-all # :hotspot_misc +testlibrary_tests/ctw/JarDirTest.java 8172457 windows-all + ############################################################################# From b9f711fc74c1d54a07e8ce55e9d2b16f42523f61 Mon Sep 17 00:00:00 2001 From: Andrew Haley Date: Wed, 11 Jan 2017 15:09:58 +0000 Subject: [PATCH 039/130] 8172144: AArch64: Implement "JEP 270: Reserved Stack Areas for Critical Sections" Reviewed-by: fparain --- hotspot/src/cpu/aarch64/vm/aarch64.ad | 4 ++ .../aarch64/vm/c1_LIRAssembler_aarch64.cpp | 6 ++ hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp | 1 + hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp | 3 + .../aarch64/vm/globalDefinitions_aarch64.hpp | 2 + .../src/cpu/aarch64/vm/globals_aarch64.hpp | 2 +- .../cpu/aarch64/vm/interp_masm_aarch64.cpp | 16 +++++ .../cpu/aarch64/vm/macroAssembler_aarch64.cpp | 24 ++++++++ .../cpu/aarch64/vm/macroAssembler_aarch64.hpp | 3 + .../cpu/aarch64/vm/stubGenerator_aarch64.cpp | 7 ++- .../linux_aarch64/vm/os_linux_aarch64.cpp | 59 +++++++++++++++++++ .../ReservedStack/ReservedStackTest.java | 3 +- 12 files changed, 126 insertions(+), 4 deletions(-) diff --git a/hotspot/src/cpu/aarch64/vm/aarch64.ad b/hotspot/src/cpu/aarch64/vm/aarch64.ad index 2294bab8db8..87b0bc1e79e 100644 --- a/hotspot/src/cpu/aarch64/vm/aarch64.ad +++ b/hotspot/src/cpu/aarch64/vm/aarch64.ad @@ -3008,6 +3008,10 @@ void MachEpilogNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const { __ notify(Assembler::method_reentry); } + if (StackReservedPages > 0 && C->has_reserved_stack_access()) { + __ reserved_stack_check(); + } + if (do_polling() && C->is_method_compilation()) { __ read_polling_page(rscratch1, os::get_polling_page(), relocInfo::poll_return_type); } diff --git a/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp index 70c8f909337..b139a44f9a1 100644 --- a/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp @@ -532,8 +532,14 @@ void LIR_Assembler::poll_for_safepoint(relocInfo::relocType rtype, CodeEmitInfo* void LIR_Assembler::return_op(LIR_Opr result) { assert(result->is_illegal() || !result->is_single_cpu() || result->as_register() == r0, "word returns are in r0,"); + // Pop the stack before the safepoint code __ remove_frame(initial_frame_size_in_bytes()); + + if (StackReservedPages > 0 && compilation()->has_reserved_stack_access()) { + __ reserved_stack_check(); + } + address polling_page(os::get_polling_page()); __ read_polling_page(rscratch1, polling_page, relocInfo::poll_return_type); __ ret(lr); diff --git a/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp index b74bce2d415..924aab146c2 100644 --- a/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp @@ -629,6 +629,7 @@ void frame::describe_pd(FrameValues& values, int frame_no) { DESCRIBE_FP_OFFSET(interpreter_frame_last_sp); DESCRIBE_FP_OFFSET(interpreter_frame_method); DESCRIBE_FP_OFFSET(interpreter_frame_mdp); + DESCRIBE_FP_OFFSET(interpreter_frame_mirror); DESCRIBE_FP_OFFSET(interpreter_frame_cache); DESCRIBE_FP_OFFSET(interpreter_frame_locals); DESCRIBE_FP_OFFSET(interpreter_frame_bcp); diff --git a/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp index 5bcee325945..64a35bd3c30 100644 --- a/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/frame_aarch64.hpp @@ -46,6 +46,9 @@ // [pointer to locals ] = locals() locals_offset // [constant pool cache ] = cache() cache_offset +// [klass of method ] = mirror() mirror_offset +// [padding ] + // [methodData ] = mdp() mdx_offset // [methodOop ] = method() method_offset diff --git a/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp index 4c9d377ff09..0d78e2da1fe 100644 --- a/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/globalDefinitions_aarch64.hpp @@ -53,4 +53,6 @@ const bool CCallingConventionRequiresIntsAsLongs = false; // evidence that it's worth doing. #define DEOPTIMIZE_WHEN_PATCHING +#define SUPPORT_RESERVED_STACK_AREA + #endif // CPU_AARCH64_VM_GLOBALDEFINITIONS_AARCH64_HPP diff --git a/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp index 3226ef5cf72..2ba8d7f9e48 100644 --- a/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp @@ -47,7 +47,7 @@ define_pd_global(intx, InlineFrequencyCount, 100); #define DEFAULT_STACK_YELLOW_PAGES (2) #define DEFAULT_STACK_RED_PAGES (1) #define DEFAULT_STACK_SHADOW_PAGES (4 DEBUG_ONLY(+5)) -#define DEFAULT_STACK_RESERVED_PAGES (0) +#define DEFAULT_STACK_RESERVED_PAGES (1) #define MIN_STACK_YELLOW_PAGES DEFAULT_STACK_YELLOW_PAGES #define MIN_STACK_RED_PAGES DEFAULT_STACK_RED_PAGES diff --git a/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp index ed95d410e36..81636fb8ea1 100644 --- a/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp @@ -619,6 +619,22 @@ void InterpreterMacroAssembler::remove_activation( // get sender esp ldr(esp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); + if (StackReservedPages > 0) { + // testing if reserved zone needs to be re-enabled + Label no_reserved_zone_enabling; + + ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset())); + cmp(esp, rscratch1); + br(Assembler::LS, no_reserved_zone_enabling); + + call_VM_leaf( + CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), rthread); + call_VM(noreg, CAST_FROM_FN_PTR(address, + InterpreterRuntime::throw_delayed_StackOverflowError)); + should_not_reach_here(); + + bind(no_reserved_zone_enabling); + } // remove frame anchor leave(); // If we're returning to interpreted code we will shortly be diff --git a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp index dc90886ab68..1c955d5afe3 100644 --- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp @@ -402,6 +402,30 @@ void MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) { } } +void MacroAssembler::reserved_stack_check() { + // testing if reserved zone needs to be enabled + Label no_reserved_zone_enabling; + + ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset())); + cmp(sp, rscratch1); + br(Assembler::LO, no_reserved_zone_enabling); + + enter(); // LR and FP are live. + lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone)); + mov(c_rarg0, rthread); + blr(rscratch1); + leave(); + + // We have already removed our own frame. + // throw_delayed_StackOverflowError will think that it's been + // called by our caller. + lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry())); + br(rscratch1); + should_not_reach_here(); + + bind(no_reserved_zone_enabling); +} + int MacroAssembler::biased_locking_enter(Register lock_reg, Register obj_reg, Register swap_reg, diff --git a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp index 3418189f1b4..2f17699a262 100644 --- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp @@ -957,6 +957,9 @@ public: // stack overflow + shadow pages. Also, clobbers tmp void bang_stack_size(Register size, Register tmp); + // Check for reserved stack access in method being exited (for JIT) + void reserved_stack_check(); + virtual RegisterOrConstant delayed_value_impl(intptr_t* delayed_value_addr, Register tmp, int offset); diff --git a/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp index 681ecf34277..3143fe97d88 100644 --- a/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/stubGenerator_aarch64.cpp @@ -4676,8 +4676,11 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_throw_StackOverflowError_entry = generate_throw_exception("StackOverflowError throw_exception", CAST_FROM_FN_PTR(address, - SharedRuntime:: - throw_StackOverflowError)); + SharedRuntime::throw_StackOverflowError)); + StubRoutines::_throw_delayed_StackOverflowError_entry = + generate_throw_exception("delayed StackOverflowError throw_exception", + CAST_FROM_FN_PTR(address, + SharedRuntime::throw_delayed_StackOverflowError)); if (UseCRC32Intrinsics) { // set table address before stub generation which use it StubRoutines::_crc_table_adr = (address)StubRoutines::aarch64::_crc_table; diff --git a/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp b/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp index 4c425c4040d..989f8aef17e 100644 --- a/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp +++ b/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp @@ -87,6 +87,7 @@ #define SPELL_REG_FP "rbp" #else #define REG_FP 29 +#define REG_LR 30 #define SPELL_REG_SP "sp" #define SPELL_REG_FP "x29" @@ -182,6 +183,46 @@ frame os::fetch_frame_from_context(const void* ucVoid) { return frame(sp, fp, epc.pc()); } +bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* uc, frame* fr) { + address pc = (address) os::Linux::ucontext_get_pc(uc); + if (Interpreter::contains(pc)) { + // interpreter performs stack banging after the fixed frame header has + // been generated while the compilers perform it before. To maintain + // semantic consistency between interpreted and compiled frames, the + // method returns the Java sender of the current frame. + *fr = os::fetch_frame_from_context(uc); + if (!fr->is_first_java_frame()) { + assert(fr->safe_for_sender(thread), "Safety check"); + *fr = fr->java_sender(); + } + } else { + // more complex code with compiled code + assert(!Interpreter::contains(pc), "Interpreted methods should have been handled above"); + CodeBlob* cb = CodeCache::find_blob(pc); + if (cb == NULL || !cb->is_nmethod() || cb->is_frame_complete_at(pc)) { + // Not sure where the pc points to, fallback to default + // stack overflow handling + return false; + } else { + // In compiled code, the stack banging is performed before LR + // has been saved in the frame. LR is live, and SP and FP + // belong to the caller. + intptr_t* fp = os::Linux::ucontext_get_fp(uc); + intptr_t* sp = os::Linux::ucontext_get_sp(uc); + void* pc = (void*)(uc->uc_mcontext.regs[REG_LR] + - NativeInstruction::instruction_size); + *fr = frame(sp, fp, pc); + if (!fr->is_java_frame()) { + assert(fr->safe_for_sender(thread), "Safety check"); + assert(!fr->is_first_frame(), "Safety check"); + *fr = fr->java_sender(); + } + } + } + assert(fr->is_java_frame(), "Safety check"); + return true; +} + // By default, gcc always saves frame pointer rfp on this stack. This // may get turned off by -fomit-frame-pointer. frame os::get_sender_for_C_frame(frame* fr) { @@ -313,6 +354,24 @@ JVM_handle_linux_signal(int sig, if (thread->in_stack_yellow_reserved_zone(addr)) { thread->disable_stack_yellow_reserved_zone(); if (thread->thread_state() == _thread_in_Java) { + if (thread->in_stack_reserved_zone(addr)) { + frame fr; + if (os::Linux::get_frame_at_stack_banging_point(thread, uc, &fr)) { + assert(fr.is_java_frame(), "Must be a Java frame"); + frame activation = + SharedRuntime::look_for_reserved_stack_annotated_method(thread, fr); + if (activation.sp() != NULL) { + thread->disable_stack_reserved_zone(); + if (activation.is_interpreted_frame()) { + thread->set_reserved_stack_activation((address)( + activation.fp() + frame::interpreter_frame_initial_sp_offset)); + } else { + thread->set_reserved_stack_activation((address)activation.unextended_sp()); + } + return 1; + } + } + } // Throw a stack overflow exception. Guard pages will be reenabled // while unwinding the stack. stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW); diff --git a/hotspot/test/runtime/ReservedStack/ReservedStackTest.java b/hotspot/test/runtime/ReservedStack/ReservedStackTest.java index 216f731d2b7..c0ba4c1af9c 100644 --- a/hotspot/test/runtime/ReservedStack/ReservedStackTest.java +++ b/hotspot/test/runtime/ReservedStack/ReservedStackTest.java @@ -200,7 +200,8 @@ public class ReservedStackTest { boolean supportedPlatform = Platform.isAix() || (Platform.isLinux() && - (Platform.isPPC() || Platform.isS390x() || Platform.isX64() || Platform.isX86())) || + (Platform.isPPC() || Platform.isS390x() || Platform.isX64() || + Platform.isX86() || Platform.isAArch64())) || Platform.isOSX() || Platform.isSolaris(); if (supportedPlatform && !result.contains("PASSED")) { From 3ccbc26ee9dd89ef5443bbd0ba7bdcd7104de63f Mon Sep 17 00:00:00 2001 From: Dmitry Fazunenko Date: Thu, 12 Jan 2017 09:53:01 +0300 Subject: [PATCH 040/130] 8169643: [TESTBUG] GCBasher test fails with G1, CMS and Serial Reviewed-by: tschatzl, iignatyev, mchernov --- hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java | 4 ++-- hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java | 4 ++-- hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java index d22a7c49d62..c85acf5be82 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ import java.io.IOException; * @requires vm.gc.ConcMarkSweep * @requires vm.flavor == "server" * @summary Stress the CMS GC by trying to make old objects more likely to be garbage than young objects. - * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseConcMarkSweepGC TestGCBasherWithCMS 120000 + * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseConcMarkSweepGC TestGCBasherWithCMS 120000 */ public class TestGCBasherWithCMS { public static void main(String[] args) throws IOException { diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java index 6fe81c22ec7..0e87aa82c6b 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ import java.io.IOException; * @requires vm.gc.G1 * @requires vm.flavor == "server" * @summary Stress the G1 GC by trying to make old objects more likely to be garbage than young objects. - * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseG1GC TestGCBasherWithG1 120000 + * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseG1GC TestGCBasherWithG1 120000 */ public class TestGCBasherWithG1 { public static void main(String[] args) throws IOException { diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java index 0ba15ccb7cd..7ca865dd112 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ import java.io.IOException; * @requires vm.gc.Serial * @requires vm.flavor == "server" * @summary Stress the Serial GC by trying to make old objects more likely to be garbage than young objects. - * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx128m -server -XX:+UseSerialGC TestGCBasherWithSerial 120000 + * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseSerialGC TestGCBasherWithSerial 120000 */ public class TestGCBasherWithSerial { public static void main(String[] args) throws IOException { From 6037c36e675f773729e040e2c121ebd8040550b3 Mon Sep 17 00:00:00 2001 From: Andrew Haley Date: Thu, 12 Jan 2017 16:27:40 +0000 Subject: [PATCH 041/130] 8172721: Fix for 8172144 breaks AArch64 build Reviewed-by: dsamersoff --- hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp b/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp index 989f8aef17e..6d0a02fff6a 100644 --- a/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp +++ b/hotspot/src/os_cpu/linux_aarch64/vm/os_linux_aarch64.cpp @@ -209,7 +209,7 @@ bool os::Linux::get_frame_at_stack_banging_point(JavaThread* thread, ucontext_t* // belong to the caller. intptr_t* fp = os::Linux::ucontext_get_fp(uc); intptr_t* sp = os::Linux::ucontext_get_sp(uc); - void* pc = (void*)(uc->uc_mcontext.regs[REG_LR] + address pc = (address)(uc->uc_mcontext.regs[REG_LR] - NativeInstruction::instruction_size); *fr = frame(sp, fp, pc); if (!fr->is_java_frame()) { From f0136f8b692afb8657e29b9ae61f549a32c9266c Mon Sep 17 00:00:00 2001 From: Rachel Protacio Date: Thu, 12 Jan 2017 14:04:08 -0500 Subject: [PATCH 042/130] 8170821: Ensure access checks result in consistent answers Added jtreg test to verify consistent access check results even when access is added between checks Reviewed-by: hseigel, lfoltan --- .../AccessCheck/AccessExportTwice.java | 146 +++++++++++++++++ .../modules/AccessCheck/AccessReadTwice.java | 154 ++++++++++++++++++ .../runtime/modules/AccessCheck/p4/c4.java | 35 ++++ 3 files changed, 335 insertions(+) create mode 100644 hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java create mode 100644 hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java create mode 100644 hotspot/test/runtime/modules/AccessCheck/p4/c4.java diff --git a/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java b/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java new file mode 100644 index 00000000000..a1eb2cce85d --- /dev/null +++ b/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @summary Class p1.c1 in an unnamed module cannot read p2.c2 in module second_mod, + * even after p2 is exported to all unnamed. Ensures constant + * access check answers when not accessible due to exportedness. + * @library /test/lib + * @modules java.base/jdk.internal.misc + * @modules java.base/jdk.internal.module + * @compile myloaders/MySameClassLoader.java + * @compile p2/c2.java + * @compile p1/c1.java + * @run main/othervm AccessExportTwice + */ + +import static jdk.test.lib.Asserts.*; + +import java.lang.module.Configuration; +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleFinder; +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import myloaders.MySameClassLoader; + +// +// ClassLoader1 --> defines first_mod --> no packages +// defines second_mod --> packages p2 +// +// first_mod can read second_mod +// package p2 in second_mod is exported to first_mod +// +// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in second_mod +// Access is not allowed, even after p2 is exported to all unnamed modules. + +public class AccessExportTwice { + + // Create a Layer over the boot layer. + // Define modules within this layer to test access between + // publicly defined classes within packages of those modules. + public void createLayerOnBoot() throws Throwable { + + // Define module: first_mod + // Can read: java.base, second_mod + // Packages: none + // Packages exported: none + ModuleDescriptor descriptor_first_mod = + ModuleDescriptor.module("first_mod") + .requires("java.base") + .requires("second_mod") + .build(); + + // Define module: second_mod + // Can read: java.base + // Packages: p2 + // Packages exported: p2 is exported to first_mod + ModuleDescriptor descriptor_second_mod = + ModuleDescriptor.module("second_mod") + .requires("java.base") + .exports("p2", Set.of("first_mod")) + .build(); + + // Set up a ModuleFinder containing all modules for this layer + ModuleFinder finder = ModuleLibrary.of(descriptor_first_mod, descriptor_second_mod); + + // Resolves "first_mod" + Configuration cf = Layer.boot() + .configuration() + .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod")); + + // Map each module to the same class loader + Map map = new HashMap<>(); + map.put("first_mod", MySameClassLoader.loader1); + map.put("second_mod", MySameClassLoader.loader1); + + // Create Layer that contains first_mod & second_mod + Layer layer = Layer.boot().defineModules(cf, map::get); + + assertTrue(layer.findLoader("first_mod") == MySameClassLoader.loader1); + assertTrue(layer.findLoader("second_mod") == MySameClassLoader.loader1); + assertTrue(layer.findLoader("java.base") == null); + + Class p2_c2_class = MySameClassLoader.loader1.loadClass("p2.c2"); + // Use the same loader to load class p1.c1 + Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1"); + // First access check for p1.c1 + try { + p1_c1_class.newInstance(); + throw new RuntimeException("Test Failed, the unnamed module should not have access to public type p2.c2"); + } catch (IllegalAccessError e) { + String message = e.getMessage(); + if (!(message.contains("cannot access") && + message.contains("because module second_mod does not export p2 to unnamed module"))) { + throw new RuntimeException("Wrong message: " + message); + } else { + System.out.println("Test Succeeded at attempt #1"); + } + } + + // Export second_mod/p2 to all unnamed modules. + Module second_mod = p2_c2_class.getModule(); + jdk.internal.module.Modules.addExportsToAllUnnamed(second_mod, "p2"); + + // Second access check for p1.c1, should have same result as first + try { + p1_c1_class.newInstance(); + throw new RuntimeException("Test Failed, access should have been cached above"); + } catch (IllegalAccessError e) { + String message = e.getMessage(); + if (!(message.contains("cannot access") && + message.contains("because module second_mod does not export p2 to unnamed module"))) { + throw new RuntimeException("Wrong message: " + message); + } else { + System.out.println("Test Succeeded at attempt #2"); + } + } + } + + public static void main(String args[]) throws Throwable { + AccessExportTwice test = new AccessExportTwice(); + test.createLayerOnBoot(); + } +} diff --git a/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java b/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java new file mode 100644 index 00000000000..5d1a690a740 --- /dev/null +++ b/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @summary Class p1.c1 in module first_mod cannot read p2.c2 in module second_mod, + * even after a read edge is added between first_mod and second_mod. + * Ensures constant access check answers when not accessible due to readability. + * @library /test/lib + * @modules java.base/jdk.internal.misc + * @modules java.base/jdk.internal.module + * @compile p2/c2.java + * @compile p1/c1.java + * @compile p4/c4.java + * @run main/othervm AccessReadTwice + */ + +import static jdk.test.lib.Asserts.*; + +import java.lang.module.Configuration; +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleFinder; +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +// +// ClassLoader1 --> defines first_mod --> packages p1, p4 +// defines second_mod --> package p2 +// +// package p2 in second_mod is exported to first_mod +// +// class p1.c1 defined in first_mod tries to access p2.c2 defined in second_mod +// Access is not allowed, even after a read edge is added between first_mod and second_mod. + +public class AccessReadTwice { + + // Create a Layer over the boot layer. + // Define modules within this layer to test access between + // publicly defined classes within packages of those modules. + public void createLayerOnBoot() throws Throwable { + + // Define module: first_mod + // Can read: java.base + // Packages: p1, p4 + // Packages exported: none + ModuleDescriptor descriptor_first_mod = + ModuleDescriptor.module("first_mod") + .requires("java.base") + .contains(Set.of("p1", "p4")) + .build(); + + // Define module: second_mod + // Can read: java.base + // Packages: p2 + // Packages exported: p2 is exported to first_mod + ModuleDescriptor descriptor_second_mod = + ModuleDescriptor.module("second_mod") + .requires("java.base") + .exports("p2", Set.of("first_mod")) + .build(); + + // Set up a ModuleFinder containing all modules for this layer + ModuleFinder finder = ModuleLibrary.of(descriptor_first_mod, descriptor_second_mod); + + // Resolves "first_mod" and "second_mod" + Configuration cf = Layer.boot() + .configuration() + .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod", "second_mod")); + + // Map each module to this class loader + Map map = new HashMap<>(); + ClassLoader loader = AccessReadTwice.class.getClassLoader(); + map.put("first_mod", loader); + map.put("second_mod", loader); + + // Create Layer that contains first_mod & second_mod + Layer layer = Layer.boot().defineModules(cf, map::get); + + assertTrue(layer.findLoader("first_mod") == loader); + assertTrue(layer.findLoader("second_mod") == loader); + assertTrue(layer.findLoader("java.base") == null); + + Class p2_c2_class = loader.loadClass("p2.c2"); + Class p1_c1_class = loader.loadClass("p1.c1"); + Class p4_c4_class = loader.loadClass("p4.c4"); + + Module first_mod = p1_c1_class.getModule(); + Module second_mod = p2_c2_class.getModule(); + + // Export first_mod/p1 and first_mod/p4 to all unnamed modules so that + // this test can use them + jdk.internal.module.Modules.addExportsToAllUnnamed(first_mod, "p1"); + jdk.internal.module.Modules.addExportsToAllUnnamed(first_mod, "p4"); + + // First access check for p1.c1 + try { + p1_c1_class.newInstance(); + throw new RuntimeException("Test Failed, module first_mod should not have access to p2.c2"); + } catch (IllegalAccessError e) { + String message = e.getMessage(); + if (!(message.contains("cannot access") && + message.contains("because module first_mod does not read module second_mod"))) { + throw new RuntimeException("Wrong message: " + message); + } else { + System.out.println("Test Succeeded at attempt #1"); + } + } + + // Add a read edge from p4/c4's module (first_mod) to second_mod + p4.c4 c4_obj = new p4.c4(); + c4_obj.addReads(second_mod); + + // Second access check for p1.c1, should have same result as first + try { + p1_c1_class.newInstance(); + throw new RuntimeException("Test Failed, access should have been cached above"); + } catch (IllegalAccessError e) { + String message = e.getMessage(); + if (!(message.contains("cannot access") && + message.contains("because module first_mod does not read module second_mod"))) { + throw new RuntimeException("Wrong message: " + message); + } else { + System.out.println("Test Succeeded at attempt #2"); + } + } + } + + public static void main(String args[]) throws Throwable { + AccessReadTwice test = new AccessReadTwice(); + test.createLayerOnBoot(); + } +} diff --git a/hotspot/test/runtime/modules/AccessCheck/p4/c4.java b/hotspot/test/runtime/modules/AccessCheck/p4/c4.java new file mode 100644 index 00000000000..d0098674672 --- /dev/null +++ b/hotspot/test/runtime/modules/AccessCheck/p4/c4.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// Small class used by multiple hotspot/runtime/modules/AccessCheck/* tests. + +package p4; + +import java.lang.reflect.Module; + +public class c4 { + // Add a read edge from c4's module to given module m + public void addReads(Module m) { + c4.class.getModule().addReads(m); + } +} From c95329970d5361a541935c5a9a01b97127a1ba33 Mon Sep 17 00:00:00 2001 From: Harold Seigel Date: Fri, 13 Jan 2017 07:19:03 -0500 Subject: [PATCH 043/130] 8172288: Fix Jigsaw related module/package error messages and throw correct exceptions Reword error messages and throw IllegalStateExceptions where appropriate Reviewed-by: alanb, acorn, lfoltan, gtriantafill --- hotspot/src/share/vm/classfile/modules.cpp | 49 +++++++++++-------- .../runtime/modules/JVMAddModulePackage.java | 8 +-- .../test/runtime/modules/JVMDefineModule.java | 24 ++++----- 3 files changed, 44 insertions(+), 37 deletions(-) diff --git a/hotspot/src/share/vm/classfile/modules.cpp b/hotspot/src/share/vm/classfile/modules.cpp index becda5363a6..34f32df8ea3 100644 --- a/hotspot/src/share/vm/classfile/modules.cpp +++ b/hotspot/src/share/vm/classfile/modules.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -239,7 +239,7 @@ static void define_javabase_module(jobject module, jstring version, } } if (duplicate_javabase) { - THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), + THROW_MSG(vmSymbols::java_lang_InternalError(), "Module " JAVA_BASE_NAME " is already defined"); } @@ -262,6 +262,20 @@ static void define_javabase_module(jobject module, jstring version, } } +// Caller needs ResourceMark. +void throw_dup_pkg_exception(const char* module_name, PackageEntry* package, TRAPS) { + const char* package_name = package->name()->as_C_string(); + if (package->module()->is_named()) { + THROW_MSG(vmSymbols::java_lang_IllegalStateException(), + err_msg("Package %s for module %s is already in another module, %s, defined to the class loader", + package_name, module_name, package->module()->name()->as_C_string())); + } else { + THROW_MSG(vmSymbols::java_lang_IllegalStateException(), + err_msg("Package %s for module %s is already in the unnamed module defined to the class loader", + package_name, module_name)); + } +} + void Modules::define_module(jobject module, jstring version, jstring location, jobjectArray packages, TRAPS) { ResourceMark rm(THREAD); @@ -347,7 +361,6 @@ void Modules::define_module(jobject module, jstring version, // Create symbol* entry for module name. TempNewSymbol module_symbol = SymbolTable::new_symbol(module_name, CHECK); - int dupl_pkg_index = -1; bool dupl_modules = false; // Create symbol* entry for module version. @@ -373,6 +386,7 @@ void Modules::define_module(jobject module, jstring version, assert(loader_data != NULL, "class loader data shouldn't be null"); PackageEntryTable* package_table = NULL; + PackageEntry* existing_pkg = NULL; { MutexLocker ml(Module_lock, THREAD); @@ -382,13 +396,12 @@ void Modules::define_module(jobject module, jstring version, // Check that none of the packages exist in the class loader's package table. for (int x = 0; x < pkg_list->length(); x++) { - if (package_table->lookup_only(pkg_list->at(x)) != NULL) { + existing_pkg = package_table->lookup_only(pkg_list->at(x)); + if (existing_pkg != NULL) { // This could be because the module was already defined. If so, // report that error instead of the package error. if (module_table->lookup_only(module_symbol) != NULL) { dupl_modules = true; - } else { - dupl_pkg_index = x; } break; } @@ -396,9 +409,8 @@ void Modules::define_module(jobject module, jstring version, } // if (num_packages > 0)... // Add the module and its packages. - if (!dupl_modules && dupl_pkg_index == -1) { + if (!dupl_modules && existing_pkg == NULL) { // Create the entry for this module in the class loader's module entry table. - ModuleEntry* module_entry = module_table->locked_create_entry_or_null(module_handle, module_symbol, version_symbol, location_symbol, loader_data); @@ -426,13 +438,10 @@ void Modules::define_module(jobject module, jstring version, // any errors ? if (dupl_modules) { - THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), + THROW_MSG(vmSymbols::java_lang_IllegalStateException(), err_msg("Module %s is already defined", module_name)); - } - if (dupl_pkg_index != -1) { - THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), - err_msg("Package %s for module %s already exists for class loader", - pkg_list->at(dupl_pkg_index)->as_C_string(), module_name)); + } else if (existing_pkg != NULL) { + throw_dup_pkg_exception(module_name, existing_pkg, CHECK); } if (log_is_enabled(Debug, modules)) { @@ -776,21 +785,19 @@ void Modules::add_module_package(jobject module, jstring package, TRAPS) { PackageEntryTable* package_table = loader_data->packages(); assert(package_table != NULL, "Missing package_table"); - bool pkg_exists = false; + PackageEntry* existing_pkg = NULL; { MutexLocker ml(Module_lock, THREAD); // Check that the package does not exist in the class loader's package table. - if (!package_table->lookup_only(pkg_symbol)) { + existing_pkg = package_table->lookup_only(pkg_symbol); + if (existing_pkg == NULL) { PackageEntry* pkg = package_table->locked_create_entry_or_null(pkg_symbol, module_entry); assert(pkg != NULL, "Unable to create a module's package entry"); - } else { - pkg_exists = true; } } - if (pkg_exists) { - THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), - err_msg("Package %s already exists for class loader", package_name)); + if (existing_pkg != NULL) { + throw_dup_pkg_exception(module_entry->name()->as_C_string(), existing_pkg, CHECK); } } diff --git a/hotspot/test/runtime/modules/JVMAddModulePackage.java b/hotspot/test/runtime/modules/JVMAddModulePackage.java index 62106f8597f..3f7f2fd29a0 100644 --- a/hotspot/test/runtime/modules/JVMAddModulePackage.java +++ b/hotspot/test/runtime/modules/JVMAddModulePackage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,11 +84,11 @@ public class JVMAddModulePackage { // Expected } - // Existing package, expect an IAE + // Existing package, expect an ISE try { ModuleHelper.AddModulePackage(module1, "yourpackage"); - throw new RuntimeException("Failed to get the expected IAE"); - } catch(IllegalArgumentException e) { + throw new RuntimeException("Failed to get the expected ISE"); + } catch(IllegalStateException e) { // Expected } diff --git a/hotspot/test/runtime/modules/JVMDefineModule.java b/hotspot/test/runtime/modules/JVMDefineModule.java index dd19770ee98..9e44878490d 100644 --- a/hotspot/test/runtime/modules/JVMDefineModule.java +++ b/hotspot/test/runtime/modules/JVMDefineModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,27 +127,27 @@ public class JVMDefineModule { } } - // Duplicate module name, expect an IAE - m = ModuleHelper.ModuleObject("module.name", cl, new String[] { "mypackage6" }); + // Duplicate module name, expect an ISE + m = ModuleHelper.ModuleObject("Module_A", cl, new String[] { "mypackage6" }); assertNotNull(m, "Module should not be null"); ModuleHelper.DefineModule(m, "9.0", "module.name/here", new String[] { "mypackage6" }); try { ModuleHelper.DefineModule(m, "9.0", "module.name/here", new String[] { "mypackage6a" }); - throw new RuntimeException("Failed to get IAE for duplicate module"); - } catch(IllegalArgumentException e) { - if (!e.getMessage().contains("Module module.name is already defined")) { - throw new RuntimeException("Failed to get expected IAE message for duplicate module: " + e.getMessage()); + throw new RuntimeException("Failed to get ISE for duplicate module"); + } catch(IllegalStateException e) { + if (!e.getMessage().contains("Module Module_A is already defined")) { + throw new RuntimeException("Failed to get expected ISE message for duplicate module: " + e.getMessage()); } } - // Package is already defined for class loader, expect an IAE + // Package is already defined for class loader, expect an ISE m = ModuleHelper.ModuleObject("dupl.pkg.module", cl, new String[] { "mypackage6b" }); try { ModuleHelper.DefineModule(m, "9.0", "module.name/here", new String[] { "mypackage6" }); - throw new RuntimeException("Failed to get IAE for existing package"); - } catch(IllegalArgumentException e) { - if (!e.getMessage().contains("Package mypackage6 for module dupl.pkg.module already exists for class loader")) { - throw new RuntimeException("Failed to get expected IAE message for duplicate package: " + e.getMessage()); + throw new RuntimeException("Failed to get ISE for existing package"); + } catch(IllegalStateException e) { + if (!e.getMessage().contains("Package mypackage6 for module dupl.pkg.module is already in another module, Module_A, defined to the class loader")) { + throw new RuntimeException("Failed to get expected ISE message for duplicate package: " + e.getMessage()); } } From a3946e30e34206b16edb4bb702779519a50b4ad2 Mon Sep 17 00:00:00 2001 From: Harold Seigel Date: Fri, 13 Jan 2017 10:45:53 -0500 Subject: [PATCH 044/130] 8172288: Fix Jigsaw related module/package error messages and throw correct exceptions Reword error messages and throw IllegalStateExceptions where appropriate Reviewed-by: alanb, acorn, lfoltan, gtriantafill --- .../share/classes/java/lang/reflect/Layer.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java b/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java index 4b4588c3c01..9eaf90d0ca8 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -458,7 +458,7 @@ public final class Layer { loader.initRemotePackageMap(cf, parents); Layer layer = new Layer(cf, parents, mn -> loader); return new Controller(layer); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException | IllegalStateException e) { throw new LayerInstantiationException(e.getMessage()); } } @@ -526,7 +526,7 @@ public final class Layer { try { Layer layer = new Layer(cf, parents, pool::loaderFor); return new Controller(layer); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException | IllegalStateException e) { throw new LayerInstantiationException(e.getMessage()); } } @@ -610,9 +610,8 @@ public final class Layer { try { Layer layer = new Layer(cf, parents, clf); return new Controller(layer); - } catch (IllegalArgumentException iae) { - // IAE is thrown by VM when defining the module fails - throw new LayerInstantiationException(iae.getMessage()); + } catch (IllegalArgumentException | IllegalStateException e) { + throw new LayerInstantiationException(e.getMessage()); } } From cc5730af708ac0ff43db2051e474a8f748457610 Mon Sep 17 00:00:00 2001 From: Alexander Harlap Date: Fri, 13 Jan 2017 12:27:54 -0500 Subject: [PATCH 045/130] 8140588: Internal Error: gc/g1/ptrQueue.hpp:126 assert(_index == _sz) failed: invariant: queues are empty when activated Re-check queue active state before updating Reviewed-by: pliden, kbarrett, mdoerr --- .../src/cpu/aarch64/vm/c1_Runtime1_aarch64.cpp | 11 ++++++++++- hotspot/src/cpu/arm/vm/c1_Runtime1_arm.cpp | 9 ++++++++- hotspot/src/cpu/ppc/vm/c1_Runtime1_ppc.cpp | 18 ++++++++++++++++-- hotspot/src/cpu/s390/vm/c1_Runtime1_s390.cpp | 17 +++++++++++++++-- hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp | 17 +++++++++++++++-- hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp | 13 ++++++++++++- 6 files changed, 76 insertions(+), 9 deletions(-) diff --git a/hotspot/src/cpu/aarch64/vm/c1_Runtime1_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/c1_Runtime1_aarch64.cpp index 58ba9c0b613..8c83dc4125c 100644 --- a/hotspot/src/cpu/aarch64/vm/c1_Runtime1_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/c1_Runtime1_aarch64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Red Hat Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -1179,6 +1179,15 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Label done; Label runtime; + // Is marking still active? + if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) { + __ ldrw(tmp, in_progress); + } else { + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ ldrb(tmp, in_progress); + } + __ cbzw(tmp, done); + // Can we store original value in the thread's buffer? __ ldr(tmp, queue_index); __ cbz(tmp, runtime); diff --git a/hotspot/src/cpu/arm/vm/c1_Runtime1_arm.cpp b/hotspot/src/cpu/arm/vm/c1_Runtime1_arm.cpp index 937dfe91242..9f17c8fc810 100644 --- a/hotspot/src/cpu/arm/vm/c1_Runtime1_arm.cpp +++ b/hotspot/src/cpu/arm/vm/c1_Runtime1_arm.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -551,6 +551,8 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { const Register r_index_1 = R1; const Register r_buffer_2 = R2; + Address queue_active(Rthread, in_bytes(JavaThread::satb_mark_queue_offset() + + SATBMarkQueue::byte_offset_of_active())); Address queue_index(Rthread, in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_index())); Address buffer(Rthread, in_bytes(JavaThread::satb_mark_queue_offset() + @@ -559,6 +561,11 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Label done; Label runtime; + // Is marking still active? + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ ldrb(R1, queue_active); + __ cbz(R1, done); + __ ldr(r_index_1, queue_index); __ ldr(r_pre_val_0, Address(SP, nb_saved_regs*wordSize)); __ ldr(r_buffer_2, buffer); diff --git a/hotspot/src/cpu/ppc/vm/c1_Runtime1_ppc.cpp b/hotspot/src/cpu/ppc/vm/c1_Runtime1_ppc.cpp index 1aa158b4a8f..3562a79825f 100644 --- a/hotspot/src/cpu/ppc/vm/c1_Runtime1_ppc.cpp +++ b/hotspot/src/cpu/ppc/vm/c1_Runtime1_ppc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -741,7 +741,10 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Register tmp = R14; Register tmp2 = R15; - Label refill, restart; + Label refill, restart, marking_not_active; + int satb_q_active_byte_offset = + in_bytes(JavaThread::satb_mark_queue_offset() + + SATBMarkQueue::byte_offset_of_active()); int satb_q_index_byte_offset = in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_index()); @@ -753,6 +756,16 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { __ std(tmp, -16, R1_SP); __ std(tmp2, -24, R1_SP); + // Is marking still active? + if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) { + __ lwz(tmp, satb_q_active_byte_offset, R16_thread); + } else { + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ lbz(tmp, satb_q_active_byte_offset, R16_thread); + } + __ cmpdi(CCR0, tmp, 0); + __ beq(CCR0, marking_not_active); + __ bind(restart); // Load the index into the SATB buffer. SATBMarkQueue::_index is a // size_t so ld_ptr is appropriate. @@ -769,6 +782,7 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { __ std(tmp, satb_q_index_byte_offset, R16_thread); __ stdx(pre_val, tmp2, tmp); // [_buf + index] := + __ bind(marking_not_active); // Restore temp registers and return-from-leaf. __ ld(tmp2, -24, R1_SP); __ ld(tmp, -16, R1_SP); diff --git a/hotspot/src/cpu/s390/vm/c1_Runtime1_s390.cpp b/hotspot/src/cpu/s390/vm/c1_Runtime1_s390.cpp index c0fbee53da7..7b65476212f 100644 --- a/hotspot/src/cpu/s390/vm/c1_Runtime1_s390.cpp +++ b/hotspot/src/cpu/s390/vm/c1_Runtime1_s390.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2016 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -784,7 +784,10 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Register tmp = Z_R6; // Must be non-volatile because it is used to save pre_val. Register tmp2 = Z_R7; - Label refill, restart; + Label refill, restart, marking_not_active; + int satb_q_active_byte_offset = + in_bytes(JavaThread::satb_mark_queue_offset() + + SATBMarkQueue::byte_offset_of_active()); int satb_q_index_byte_offset = in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_index()); @@ -796,6 +799,15 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { __ z_stg(tmp, 0*BytesPerWord + FrameMap::first_available_sp_in_frame, Z_SP); __ z_stg(tmp2, 1*BytesPerWord + FrameMap::first_available_sp_in_frame, Z_SP); + // Is marking still active? + if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) { + __ load_and_test_int(tmp, Address(Z_thread, satb_q_active_byte_offset)); + } else { + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ load_and_test_byte(tmp, Address(Z_thread, satb_q_active_byte_offset)); + } + __ z_bre(marking_not_active); // Activity indicator is zero, so there is no marking going on currently. + __ bind(restart); // Load the index into the SATB buffer. SATBMarkQueue::_index is a // size_t so ld_ptr is appropriate. @@ -810,6 +822,7 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { __ z_stg(pre_val, 0, tmp, tmp2); // [_buf + index] := __ z_stg(tmp, satb_q_index_byte_offset, Z_thread); + __ bind(marking_not_active); // Restore tmp registers (see assertion in G1PreBarrierStub::emit_code()). __ z_lg(tmp, 0*BytesPerWord + FrameMap::first_available_sp_in_frame, Z_SP); __ z_lg(tmp2, 1*BytesPerWord + FrameMap::first_available_sp_in_frame, Z_SP); diff --git a/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp index 5530a85cb4c..40e30551967 100644 --- a/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -856,7 +856,9 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Register tmp2 = G3_scratch; Label refill, restart; - bool with_frame = false; // I don't know if we can do with-frame. + int satb_q_active_byte_offset = + in_bytes(JavaThread::satb_mark_queue_offset() + + SATBMarkQueue::byte_offset_of_active()); int satb_q_index_byte_offset = in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_index()); @@ -864,6 +866,17 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_buf()); + // Is marking still active? + if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) { + __ ld(G2_thread, satb_q_active_byte_offset, tmp); + } else { + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ ldsb(G2_thread, satb_q_active_byte_offset, tmp); + } + __ cmp_and_br_short(tmp, G0, Assembler::notEqual, Assembler::pt, restart); + __ retl(); + __ delayed()->nop(); + __ bind(restart); // Load the index into the SATB buffer. SATBMarkQueue::_index is a // size_t so ld_ptr is appropriate diff --git a/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp b/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp index 5fe455600d1..58db92dcd32 100644 --- a/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1623,6 +1623,8 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { NOT_LP64(__ get_thread(thread);) + Address queue_active(thread, in_bytes(JavaThread::satb_mark_queue_offset() + + SATBMarkQueue::byte_offset_of_active())); Address queue_index(thread, in_bytes(JavaThread::satb_mark_queue_offset() + SATBMarkQueue::byte_offset_of_index())); Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() + @@ -1631,6 +1633,15 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { Label done; Label runtime; + // Is marking still active? + if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) { + __ cmpl(queue_active, 0); + } else { + assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption"); + __ cmpb(queue_active, 0); + } + __ jcc(Assembler::equal, done); + // Can we store original value in the thread's buffer? __ movptr(tmp, queue_index); From 3cfbc5a63058554c31dc9c8f5eda011119e18fc2 Mon Sep 17 00:00:00 2001 From: Rachel Protacio Date: Fri, 13 Jan 2017 16:49:34 -0500 Subject: [PATCH 046/130] 8170827: Correct errant "java.base" string to macro Used JAVA_BASE_NAME instead of "java.base" string in one location Reviewed-by: coleenp, jiangli --- hotspot/src/share/vm/runtime/os.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 18359effe52..e3463ae56e5 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ #include "precompiled.hpp" #include "classfile/classLoader.hpp" #include "classfile/javaClasses.hpp" +#include "classfile/moduleEntry.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" #include "code/codeCache.hpp" @@ -1229,7 +1230,7 @@ bool os::set_boot_path(char fileSep, char pathSep) { FREE_C_HEAP_ARRAY(char, jimage); // check if developer build with exploded modules - char* base_classes = format_boot_path("%/modules/java.base", home, home_len, fileSep, pathSep); + char* base_classes = format_boot_path("%/modules/" JAVA_BASE_NAME, home, home_len, fileSep, pathSep); if (base_classes == NULL) return false; if (os::stat(base_classes, &st) == 0) { Arguments::set_sysclasspath(base_classes, false); From 09dee71ddd9358bdeb30051589112463d0717d26 Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Tue, 17 Jan 2017 08:53:42 +0100 Subject: [PATCH 047/130] 8172731: runtime/Thread/TooSmallStackSize.java fails on solaris-x64 with product build The C2 compiler threads require a large stack with the Solaris Studio C++ compiler version 5.13 and product VM build. Reviewed-by: sspitsyn, dcubed, goetz, dholmes --- hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp index f5c0ff370a0..5fcd2de83df 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp @@ -89,7 +89,10 @@ // Minimum usable stack sizes required to get to user code. Space for // HotSpot guard pages is added later. #ifdef _LP64 -size_t os::Posix::_compiler_thread_min_stack_allowed = 202 * K; +// The adlc generated method 'State::MachNodeGenerator(int)' used by the C2 compiler +// threads requires a large stack with the Solaris Studio C++ compiler version 5.13 +// and product VM builds (debug builds require significantly less stack space). +size_t os::Posix::_compiler_thread_min_stack_allowed = 325 * K; size_t os::Posix::_java_thread_min_stack_allowed = 48 * K; size_t os::Posix::_vm_internal_thread_min_stack_allowed = 224 * K; #else From 2bc33c2996c239ee8d912375e54ea7e36644d682 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Gr=C3=B6nlund?= Date: Tue, 17 Jan 2017 16:18:03 +0100 Subject: [PATCH 048/130] 8171960: Event-based tracing needs separate flag representation for Method Reviewed-by: hseigel, gtriantafill, dholmes --- .../hotspot/GraalHotSpotVMConfig.java | 1 - .../src/share/vm/jvmci/vmStructs_jvmci.cpp | 1 - hotspot/src/share/vm/oops/method.cpp | 1 - hotspot/src/share/vm/oops/method.hpp | 28 ++++++++----------- hotspot/src/share/vm/runtime/vmStructs.cpp | 1 - hotspot/src/share/vm/trace/traceMacros.hpp | 2 ++ 6 files changed, 14 insertions(+), 20 deletions(-) diff --git a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java index 4400099efc5..4bfd1fbbed3 100644 --- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java +++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/GraalHotSpotVMConfig.java @@ -479,7 +479,6 @@ public class GraalHotSpotVMConfig extends HotSpotVMConfigAccess { public final int methodCompiledEntryOffset = getFieldOffset("Method::_from_compiled_entry", Integer.class, "address"); public final int methodCodeOffset = getFieldOffset("Method::_code", Integer.class, isJDK8 ? "nmethod*" : "CompiledMethod*"); - public final int methodFlagsJfrTowrite = getConstant("Method::_jfr_towrite", Integer.class); public final int methodFlagsCallerSensitive = getConstant("Method::_caller_sensitive", Integer.class); public final int methodFlagsForceInline = getConstant("Method::_force_inline", Integer.class); public final int methodFlagsDontInline = getConstant("Method::_dont_inline", Integer.class); diff --git a/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp b/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp index 5c69ecb4d65..a01651f55aa 100644 --- a/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp +++ b/hotspot/src/share/vm/jvmci/vmStructs_jvmci.cpp @@ -535,7 +535,6 @@ \ declare_constant(markOopDesc::no_hash) \ \ - declare_constant(Method::_jfr_towrite) \ declare_constant(Method::_caller_sensitive) \ declare_constant(Method::_force_inline) \ declare_constant(Method::_dont_inline) \ diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp index 4e3dcf03bd8..f37278edd13 100644 --- a/hotspot/src/share/vm/oops/method.cpp +++ b/hotspot/src/share/vm/oops/method.cpp @@ -85,7 +85,6 @@ Method::Method(ConstMethod* xconst, AccessFlags access_flags) { set_constMethod(xconst); set_access_flags(access_flags); set_intrinsic_id(vmIntrinsics::_none); - set_jfr_towrite(false); set_force_inline(false); set_hidden(false); set_dont_inline(false); diff --git a/hotspot/src/share/vm/oops/method.hpp b/hotspot/src/share/vm/oops/method.hpp index 1c6e72df0fc..ebd5f0feef2 100644 --- a/hotspot/src/share/vm/oops/method.hpp +++ b/hotspot/src/share/vm/oops/method.hpp @@ -75,18 +75,19 @@ class Method : public Metadata { // Flags enum Flags { - _jfr_towrite = 1 << 0, - _caller_sensitive = 1 << 1, - _force_inline = 1 << 2, - _dont_inline = 1 << 3, - _hidden = 1 << 4, - _has_injected_profile = 1 << 5, - _running_emcp = 1 << 6, - _intrinsic_candidate = 1 << 7, - _reserved_stack_access = 1 << 8 + _caller_sensitive = 1 << 0, + _force_inline = 1 << 1, + _dont_inline = 1 << 2, + _hidden = 1 << 3, + _has_injected_profile = 1 << 4, + _running_emcp = 1 << 5, + _intrinsic_candidate = 1 << 6, + _reserved_stack_access = 1 << 7 }; mutable u2 _flags; + TRACE_DEFINE_FLAG; + #ifndef PRODUCT int _compiled_invocation_count; // Number of nmethod invocations so far (for perf. debugging) #endif @@ -833,13 +834,6 @@ class Method : public Metadata { void init_intrinsic_id(); // updates from _none if a match static vmSymbols::SID klass_id_for_intrinsics(const Klass* holder); - bool jfr_towrite() const { - return (_flags & _jfr_towrite) != 0; - } - void set_jfr_towrite(bool x) const { - _flags = x ? (_flags | _jfr_towrite) : (_flags & ~_jfr_towrite); - } - bool caller_sensitive() { return (_flags & _caller_sensitive) != 0; } @@ -890,6 +884,8 @@ class Method : public Metadata { _flags = x ? (_flags | _reserved_stack_access) : (_flags & ~_reserved_stack_access); } + TRACE_DEFINE_FLAG_ACCESSOR; + ConstMethod::MethodType method_type() const { return _constMethod->method_type(); } diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp index 46824eb7553..d5b9e3db03c 100644 --- a/hotspot/src/share/vm/runtime/vmStructs.cpp +++ b/hotspot/src/share/vm/runtime/vmStructs.cpp @@ -2453,7 +2453,6 @@ typedef CompactHashtable SymbolCompactHashTable; /* ConstMethod anon-enum */ \ /********************************/ \ \ - declare_constant(Method::_jfr_towrite) \ declare_constant(Method::_caller_sensitive) \ declare_constant(Method::_force_inline) \ declare_constant(Method::_dont_inline) \ diff --git a/hotspot/src/share/vm/trace/traceMacros.hpp b/hotspot/src/share/vm/trace/traceMacros.hpp index 32849885e14..65603e2609c 100644 --- a/hotspot/src/share/vm/trace/traceMacros.hpp +++ b/hotspot/src/share/vm/trace/traceMacros.hpp @@ -55,6 +55,8 @@ extern "C" void JNICALL trace_register_natives(JNIEnv*, jclass); #define TRACE_DEFINE_THREAD_ID_SIZE typedef int ___IGNORED_hs_trace_type6 #define TRACE_DEFINE_THREAD_DATA_WRITER_OFFSET typedef int ___IGNORED_hs_trace_type7 #define TRACE_THREAD_DATA_WRITER_OFFSET in_ByteSize(0); ShouldNotReachHere() +#define TRACE_DEFINE_FLAG typedef int ___IGNORED_hs_trace_type8 +#define TRACE_DEFINE_FLAG_ACCESSOR typedef int ___IGNORED_hs_trace_type9 #define TRACE_TEMPLATES(template) #define TRACE_INTRINSICS(do_intrinsic, do_class, do_name, do_signature, do_alias) From 197ce5bafabd12ec7ae6d8542188fea17358bacb Mon Sep 17 00:00:00 2001 From: Jamsheed Mohammed C M Date: Tue, 17 Jan 2017 21:38:07 -0800 Subject: [PATCH 049/130] 8166002: Emulate client build on platforms with reduced virtual address space The default VM ergonomics on Windows/x86 (32-bit) are changed to client like. Reviewed-by: kvn, iveresov --- .../share/vm/compiler/compilerDefinitions.cpp | 79 +++++++++++++++++++ .../share/vm/compiler/compilerDefinitions.hpp | 41 +++++----- .../share/vm/compiler/compilerDirectives.cpp | 4 +- .../src/share/vm/gc/shared/collectedHeap.cpp | 2 +- .../share/vm/gc/shared/genCollectedHeap.cpp | 2 +- .../share/vm/gc/shared/referenceProcessor.cpp | 10 +-- .../vm/gc/shared/threadLocalAllocBuffer.cpp | 8 +- hotspot/src/share/vm/oops/methodData.cpp | 18 ++--- hotspot/src/share/vm/prims/whitebox.cpp | 3 + hotspot/src/share/vm/runtime/arguments.cpp | 36 ++++++++- hotspot/src/share/vm/runtime/arguments.hpp | 4 + .../share/vm/runtime/compilationPolicy.cpp | 26 ++---- hotspot/src/share/vm/runtime/vm_version.cpp | 23 ++++-- hotspot/test/TEST.ROOT | 1 + .../arraycopy/TestArrayCopyNoInitDeopt.java | 6 +- .../c2/cr7200264/TestSSE2IntVect.java | 1 + .../c2/cr7200264/TestSSE4IntVect.java | 1 + .../stress/OverloadCompileQueueTest.java | 4 +- .../TestAESIntrinsicsOnSupportedConfig.java | 2 +- .../intrinsics/IntrinsicAvailableTest.java | 2 +- .../intrinsics/IntrinsicDisabledTest.java | 3 +- .../bigInteger/MontgomeryMultiplyTest.java | 6 +- .../intrinsics/bmi/verifycode/AndnTestI.java | 2 +- .../intrinsics/bmi/verifycode/AndnTestL.java | 2 +- .../intrinsics/bmi/verifycode/BlsiTestI.java | 2 +- .../intrinsics/bmi/verifycode/BlsiTestL.java | 2 +- .../bmi/verifycode/BlsmskTestI.java | 2 +- .../bmi/verifycode/BlsmskTestL.java | 2 +- .../intrinsics/bmi/verifycode/BlsrTestI.java | 2 +- .../intrinsics/bmi/verifycode/BlsrTestL.java | 2 +- .../bmi/verifycode/BmiIntrinsicBase.java | 2 +- .../intrinsics/bmi/verifycode/LZcntTestI.java | 2 +- .../intrinsics/bmi/verifycode/LZcntTestL.java | 2 +- .../intrinsics/bmi/verifycode/TZcntTestI.java | 2 +- .../intrinsics/bmi/verifycode/TZcntTestL.java | 2 +- .../klass/CastNullCheckDroppingsTest.java | 6 +- .../mathexact/sanity/IntrinsicBase.java | 2 +- .../TestCountedLoopSafepointBackedge.java | 2 +- .../UseCountedLoopSafepointsTest.java | 5 ++ .../rangechecks/TestExplicitRangeChecks.java | 2 +- .../compiler/testlibrary/CompilerUtils.java | 4 +- .../sha/predicate/IntrinsicPredicates.java | 2 +- .../compiler/tiered/NonTieredLevelsTest.java | 4 +- .../types/correctness/CorrectnessTest.java | 6 +- .../uncommontrap/TestUnstableIfTrap.java | 2 +- .../unsafe/UnsafeGetConstantField.java | 6 +- .../unsafe/UnsafeGetStableArrayElement.java | 6 +- .../whitebox/IsMethodCompilableTest.java | 7 +- .../stress/gcbasher/TestGCBasherWithCMS.java | 2 +- .../stress/gcbasher/TestGCBasherWithG1.java | 2 +- .../gcbasher/TestGCBasherWithParallel.java | 2 +- .../gcbasher/TestGCBasherWithSerial.java | 2 +- .../CDSCompressedKPtrs/XShareAuto.java | 3 +- .../ReservedStackTestCompiler.java | 2 +- .../compiler/CompilerDirectivesDCMDTest.java | 2 +- .../ctw/src/sun/hotspot/tools/ctw/Utils.java | 6 +- ...stMutuallyExclusivePlatformPredicates.java | 2 +- 57 files changed, 261 insertions(+), 124 deletions(-) diff --git a/hotspot/src/share/vm/compiler/compilerDefinitions.cpp b/hotspot/src/share/vm/compiler/compilerDefinitions.cpp index a0d379773eb..b6ebdec1310 100644 --- a/hotspot/src/share/vm/compiler/compilerDefinitions.cpp +++ b/hotspot/src/share/vm/compiler/compilerDefinitions.cpp @@ -23,6 +23,8 @@ */ #include "precompiled.hpp" +#include "runtime/globals.hpp" +#include "runtime/globals_extension.hpp" #include "compiler/compilerDefinitions.hpp" const char* compilertype2name_tab[compiler_number_of_types] = { @@ -32,3 +34,80 @@ const char* compilertype2name_tab[compiler_number_of_types] = { "jvmci", "shark" }; + +#if defined(COMPILER2) || defined(SHARK) +CompLevel CompLevel_highest_tier = CompLevel_full_optimization; // pure C2 and tiered or JVMCI and tiered +#elif defined(COMPILER1) +CompLevel CompLevel_highest_tier = CompLevel_simple; // pure C1 or JVMCI +#else +CompLevel CompLevel_highest_tier = CompLevel_none; +#endif + +#if defined(TIERED) +CompLevel CompLevel_initial_compile = CompLevel_full_profile; // tiered +#elif defined(COMPILER1) || INCLUDE_JVMCI +CompLevel CompLevel_initial_compile = CompLevel_simple; // pure C1 or JVMCI +#elif defined(COMPILER2) || defined(SHARK) +CompLevel CompLevel_initial_compile = CompLevel_full_optimization; // pure C2 +#else +CompLevel CompLevel_initial_compile = CompLevel_none; +#endif + +#if defined(COMPILER2) +CompMode Compilation_mode = CompMode_server; +#elif defined(COMPILER1) +CompMode Compilation_mode = CompMode_client; +#else +CompMode Compilation_mode = CompMode_none; +#endif + +#ifdef TIERED +void set_client_compilation_mode() { + Compilation_mode = CompMode_client; + CompLevel_highest_tier = CompLevel_simple; + CompLevel_initial_compile = CompLevel_simple; + FLAG_SET_ERGO(bool, TieredCompilation, false); + FLAG_SET_ERGO(bool, ProfileInterpreter, false); + FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true); +#if INCLUDE_JVMCI + FLAG_SET_ERGO(bool, EnableJVMCI, false); + FLAG_SET_ERGO(bool, UseJVMCICompiler, false); +#endif +#if INCLUDE_AOT + FLAG_SET_ERGO(bool, UseAOT, false); +#endif + if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) { + FLAG_SET_ERGO(uintx, InitialCodeCacheSize, 160*K); + } + if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) { + FLAG_SET_ERGO(uintx, ReservedCodeCacheSize, 32*M); + } + if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize)) { + FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, 27*M); + } + if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize)) { + FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, 0); + } + if (FLAG_IS_DEFAULT(NonNMethodCodeHeapSize)) { + FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, 5*M); + } + if (FLAG_IS_DEFAULT(CodeCacheExpansionSize)) { + FLAG_SET_ERGO(uintx, CodeCacheExpansionSize, 32*K); + } + if (FLAG_IS_DEFAULT(MetaspaceSize)) { + FLAG_SET_ERGO(size_t, MetaspaceSize, 12*M); + } + if (FLAG_IS_DEFAULT(MaxRAM)) { + FLAG_SET_ERGO(uint64_t, MaxRAM, 1ULL*G); + } + if (FLAG_IS_DEFAULT(CompileThreshold)) { + FLAG_SET_ERGO(intx, CompileThreshold, 1500); + } + if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) { + FLAG_SET_ERGO(intx, OnStackReplacePercentage, 933); + } + if (FLAG_IS_DEFAULT(CICompilerCount)) { + FLAG_SET_ERGO(intx, CICompilerCount, 1); + } +} +#endif // TIERED diff --git a/hotspot/src/share/vm/compiler/compilerDefinitions.hpp b/hotspot/src/share/vm/compiler/compilerDefinitions.hpp index 9a08a97b303..a2378ea1e92 100644 --- a/hotspot/src/share/vm/compiler/compilerDefinitions.hpp +++ b/hotspot/src/share/vm/compiler/compilerDefinitions.hpp @@ -54,27 +54,30 @@ enum CompLevel { CompLevel_simple = 1, // C1 CompLevel_limited_profile = 2, // C1, invocation & backedge counters CompLevel_full_profile = 3, // C1, invocation & backedge counters + mdo - CompLevel_full_optimization = 4, // C2, Shark or JVMCI - -#if defined(COMPILER2) || defined(SHARK) - CompLevel_highest_tier = CompLevel_full_optimization, // pure C2 and tiered or JVMCI and tiered -#elif defined(COMPILER1) - CompLevel_highest_tier = CompLevel_simple, // pure C1 or JVMCI -#else - CompLevel_highest_tier = CompLevel_none, -#endif - -#if defined(TIERED) - CompLevel_initial_compile = CompLevel_full_profile // tiered -#elif defined(COMPILER1) || INCLUDE_JVMCI - CompLevel_initial_compile = CompLevel_simple // pure C1 or JVMCI -#elif defined(COMPILER2) || defined(SHARK) - CompLevel_initial_compile = CompLevel_full_optimization // pure C2 -#else - CompLevel_initial_compile = CompLevel_none -#endif + CompLevel_full_optimization = 4 // C2, Shark or JVMCI }; +extern CompLevel CompLevel_highest_tier; +extern CompLevel CompLevel_initial_compile; + +enum CompMode { + CompMode_none = 0, + CompMode_client = 1, + CompMode_server = 2 +}; + +extern CompMode Compilation_mode; + +inline bool is_server_compilation_mode_vm() { + return Compilation_mode == CompMode_server; +} + +inline bool is_client_compilation_mode_vm() { + return Compilation_mode == CompMode_client; +} + +extern void set_client_compilation_mode(); + inline bool is_c1_compile(int comp_level) { return comp_level > CompLevel_none && comp_level < CompLevel_full_optimization; } diff --git a/hotspot/src/share/vm/compiler/compilerDirectives.cpp b/hotspot/src/share/vm/compiler/compilerDirectives.cpp index ed224cea90f..4388f348e92 100644 --- a/hotspot/src/share/vm/compiler/compilerDirectives.cpp +++ b/hotspot/src/share/vm/compiler/compilerDirectives.cpp @@ -445,7 +445,9 @@ void DirectivesStack::init() { _default_directives->_c1_store->EnableOption = true; #endif #ifdef COMPILER2 - _default_directives->_c2_store->EnableOption = true; + if (is_server_compilation_mode_vm()) { + _default_directives->_c2_store->EnableOption = true; + } #endif assert(error_msg == NULL, "Must succeed."); push(_default_directives); diff --git a/hotspot/src/share/vm/gc/shared/collectedHeap.cpp b/hotspot/src/share/vm/gc/shared/collectedHeap.cpp index 4f2c46913db..737c57c117d 100644 --- a/hotspot/src/share/vm/gc/shared/collectedHeap.cpp +++ b/hotspot/src/share/vm/gc/shared/collectedHeap.cpp @@ -233,7 +233,7 @@ void CollectedHeap::pre_initialize() { // Used for ReduceInitialCardMarks (when COMPILER2 is used); // otherwise remains unused. #if defined(COMPILER2) || INCLUDE_JVMCI - _defer_initial_card_mark = ReduceInitialCardMarks && can_elide_tlab_store_barriers() + _defer_initial_card_mark = is_server_compilation_mode_vm() && ReduceInitialCardMarks && can_elide_tlab_store_barriers() && (DeferInitialCardMark || card_mark_must_follow_store()); #else assert(_defer_initial_card_mark == false, "Who would set it?"); diff --git a/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp b/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp index 5248654f2f7..0119e115104 100644 --- a/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp +++ b/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp @@ -1209,7 +1209,7 @@ void GenCollectedHeap::gc_epilogue(bool full) { #if defined(COMPILER2) || INCLUDE_JVMCI assert(DerivedPointerTable::is_empty(), "derived pointer present"); size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr())); - guarantee(actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps"); + guarantee(is_client_compilation_mode_vm() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps"); #endif /* COMPILER2 || INCLUDE_JVMCI */ resize_all_tlabs(); diff --git a/hotspot/src/share/vm/gc/shared/referenceProcessor.cpp b/hotspot/src/share/vm/gc/shared/referenceProcessor.cpp index 38df96ddd4c..5d6d160a4ee 100644 --- a/hotspot/src/share/vm/gc/shared/referenceProcessor.cpp +++ b/hotspot/src/share/vm/gc/shared/referenceProcessor.cpp @@ -57,11 +57,11 @@ void ReferenceProcessor::init_statics() { java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock); _always_clear_soft_ref_policy = new AlwaysClearPolicy(); -#if defined(COMPILER2) || INCLUDE_JVMCI - _default_soft_ref_policy = new LRUMaxHeapPolicy(); -#else - _default_soft_ref_policy = new LRUCurrentHeapPolicy(); -#endif + if (is_server_compilation_mode_vm()) { + _default_soft_ref_policy = new LRUMaxHeapPolicy(); + } else { + _default_soft_ref_policy = new LRUCurrentHeapPolicy(); + } if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) { vm_exit_during_initialization("Could not allocate reference policy object"); } diff --git a/hotspot/src/share/vm/gc/shared/threadLocalAllocBuffer.cpp b/hotspot/src/share/vm/gc/shared/threadLocalAllocBuffer.cpp index 0df1ba020a2..b004ba58c89 100644 --- a/hotspot/src/share/vm/gc/shared/threadLocalAllocBuffer.cpp +++ b/hotspot/src/share/vm/gc/shared/threadLocalAllocBuffer.cpp @@ -233,9 +233,11 @@ void ThreadLocalAllocBuffer::startup_initialization() { // If the C2 compiler is not present, no space is reserved. // +1 for rounding up to next cache line, +1 to be safe - int lines = MAX2(AllocatePrefetchLines, AllocateInstancePrefetchLines) + 2; - _reserve_for_allocation_prefetch = (AllocatePrefetchDistance + AllocatePrefetchStepSize * lines) / - (int)HeapWordSize; + if (is_server_compilation_mode_vm()) { + int lines = MAX2(AllocatePrefetchLines, AllocateInstancePrefetchLines) + 2; + _reserve_for_allocation_prefetch = (AllocatePrefetchDistance + AllocatePrefetchStepSize * lines) / + (int)HeapWordSize; + } #endif // During jvm startup, the main (primordial) thread is initialized diff --git a/hotspot/src/share/vm/oops/methodData.cpp b/hotspot/src/share/vm/oops/methodData.cpp index 85f7c9b6098..a99000aabcf 100644 --- a/hotspot/src/share/vm/oops/methodData.cpp +++ b/hotspot/src/share/vm/oops/methodData.cpp @@ -717,9 +717,9 @@ MethodData* MethodData::allocate(ClassLoaderData* loader_data, const methodHandl } int MethodData::bytecode_cell_count(Bytecodes::Code code) { -#if defined(COMPILER1) && !(defined(COMPILER2) || INCLUDE_JVMCI) - return no_profile_data; -#else + if (is_client_compilation_mode_vm()) { + return no_profile_data; + } switch (code) { case Bytecodes::_checkcast: case Bytecodes::_instanceof: @@ -778,7 +778,6 @@ int MethodData::bytecode_cell_count(Bytecodes::Code code) { return variable_cell_count; } return no_profile_data; -#endif } // Compute the size of the profiling information corresponding to @@ -840,7 +839,9 @@ bool MethodData::is_speculative_trap_bytecode(Bytecodes::Code code) { case Bytecodes::_ifnonnull: case Bytecodes::_invokestatic: #ifdef COMPILER2 - return UseTypeSpeculation; + if (is_server_compilation_mode_vm()) { + return UseTypeSpeculation; + } #endif default: return false; @@ -942,9 +943,9 @@ int MethodData::compute_allocation_size_in_words(const methodHandle& method) { // the segment in bytes. int MethodData::initialize_data(BytecodeStream* stream, int data_index) { -#if defined(COMPILER1) && !(defined(COMPILER2) || INCLUDE_JVMCI) - return 0; -#else + if (is_client_compilation_mode_vm()) { + return 0; + } int cell_count = -1; int tag = DataLayout::no_tag; DataLayout* data_layout = data_layout_at(data_index); @@ -1061,7 +1062,6 @@ int MethodData::initialize_data(BytecodeStream* stream, assert(!bytecode_has_profile(c), "agree w/ !BHP"); return 0; } -#endif } // Get the data at an arbitrary (sort of) data index. diff --git a/hotspot/src/share/vm/prims/whitebox.cpp b/hotspot/src/share/vm/prims/whitebox.cpp index 0440fabb9c2..edea100cbe0 100644 --- a/hotspot/src/share/vm/prims/whitebox.cpp +++ b/hotspot/src/share/vm/prims/whitebox.cpp @@ -659,6 +659,9 @@ WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, j WB_END WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr)) + if (method == NULL || comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) { + return false; + } jmethodID jmid = reflected_method_to_jmid(thread, env, method); CHECK_JNI_EXCEPTION_(env, JNI_FALSE); MutexLockerEx mu(Compile_lock); diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 0ddbb30a8c5..c090e189be4 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1819,6 +1819,25 @@ bool Arguments::gc_selected() { #endif // INCLUDE_ALL_GCS } +#ifdef TIERED +bool Arguments::compilation_mode_selected() { + return !FLAG_IS_DEFAULT(TieredCompilation) || !FLAG_IS_DEFAULT(TieredStopAtLevel) || + !FLAG_IS_DEFAULT(UseAOT) JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler)); + +} + +void Arguments::select_compilation_mode_ergonomically() { +#if defined(_WINDOWS) && !defined(_LP64) + if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) { + NeverActAsServerClassMachine = true; + } +#endif + if (NeverActAsServerClassMachine) { + set_client_compilation_mode(); + } +} +#endif //TIERED + void Arguments::select_gc_ergonomically() { #if INCLUDE_ALL_GCS if (os::is_server_class_machine()) { @@ -1883,6 +1902,11 @@ void Arguments::set_jvmci_specific_flags() { #endif void Arguments::set_ergonomics_flags() { +#ifdef TIERED + if (!compilation_mode_selected()) { + select_compilation_mode_ergonomically(); + } +#endif select_gc(); #if defined(COMPILER2) || INCLUDE_JVMCI @@ -1891,7 +1915,7 @@ void Arguments::set_ergonomics_flags() { // server performance. When -server is specified, keep the default off // unless it is asked for. Future work: either add bytecode rewriting // at link time, or rewrite bytecodes in non-shared methods. - if (!DumpSharedSpaces && !RequireSharedSpaces && + if (is_server_compilation_mode_vm() && !DumpSharedSpaces && !RequireSharedSpaces && (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) { no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on."); } @@ -3711,6 +3735,12 @@ jint Arguments::finalize_vm_init_args() { return JNI_ERR; } +#if INCLUDE_JVMCI + if (UseJVMCICompiler) { + Compilation_mode = CompMode_server; + } +#endif + return JNI_OK; } @@ -4456,7 +4486,9 @@ jint Arguments::apply_ergo() { } else { int max_compilation_policy_choice = 1; #ifdef COMPILER2 - max_compilation_policy_choice = 2; + if (is_server_compilation_mode_vm()) { + max_compilation_policy_choice = 2; + } #endif // Check if the policy is valid. if (CompilationPolicyChoice >= max_compilation_policy_choice) { diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index 36bf75c6b2a..daa91c22bd7 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -455,6 +455,10 @@ class Arguments : AllStatic { static intx _Tier3InvokeNotifyFreqLog; static intx _Tier4InvocationThreshold; + // Compilation mode. + static bool compilation_mode_selected(); + static void select_compilation_mode_ergonomically(); + // Tiered static void set_tiered_flags(); // CMS/ParNew garbage collectors diff --git a/hotspot/src/share/vm/runtime/compilationPolicy.cpp b/hotspot/src/share/vm/runtime/compilationPolicy.cpp index 7333d0d1327..2044fdd8494 100644 --- a/hotspot/src/share/vm/runtime/compilationPolicy.cpp +++ b/hotspot/src/share/vm/runtime/compilationPolicy.cpp @@ -238,31 +238,17 @@ void NonTieredCompPolicy::initialize() { // Note: this policy is used ONLY if TieredCompilation is off. // compiler_count() behaves the following way: // - with TIERED build (with both COMPILER1 and COMPILER2 defined) it should return -// zero for the c1 compilation levels, hence the particular ordering of the -// statements. -// - the same should happen when COMPILER2 is defined and COMPILER1 is not -// (server build without TIERED defined). -// - if only COMPILER1 is defined (client build), zero should be returned for -// the c2 level. +// zero for the c1 compilation levels in server compilation mode runs +// and c2 compilation levels in client compilation mode runs. +// - with COMPILER2 not defined it should return zero for c2 compilation levels. +// - with COMPILER1 not defined it should return zero for c1 compilation levels. // - if neither is defined - always return zero. int NonTieredCompPolicy::compiler_count(CompLevel comp_level) { assert(!TieredCompilation, "This policy should not be used with TieredCompilation"); -#ifdef COMPILER2 - if (is_c2_compile(comp_level)) { + if (COMPILER2_PRESENT(is_server_compilation_mode_vm() && is_c2_compile(comp_level) ||) + is_client_compilation_mode_vm() && is_c1_compile(comp_level)) { return _compiler_count; - } else { - return 0; } -#endif - -#ifdef COMPILER1 - if (is_c1_compile(comp_level)) { - return _compiler_count; - } else { - return 0; - } -#endif - return 0; } diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index 7d7dcc47949..61a064703c2 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -131,19 +131,32 @@ const char* Abstract_VM_Version::vm_info_string() { return UseSharedSpaces ? "interpreted mode, sharing" : "interpreted mode"; case Arguments::_mixed: if (UseSharedSpaces) { - if (UseAOT) { - return "mixed mode, aot, sharing"; - } else { - return "mixed mode, sharing"; - } + if (UseAOT) { + return "mixed mode, aot, sharing"; +#ifdef TIERED + } else if(is_client_compilation_mode_vm()) { + return "mixed mode, emulated-client, sharing"; +#endif + } else { + return "mixed mode, sharing"; + } } else { if (UseAOT) { return "mixed mode, aot"; +#ifdef TIERED + } else if(is_client_compilation_mode_vm()) { + return "mixed mode, emulated-client"; +#endif } else { return "mixed mode"; } } case Arguments::_comp: +#ifdef TIERED + if (is_client_compilation_mode_vm()) { + return UseSharedSpaces ? "compiled mode, emulated-client, sharing" : "compiled mode, emulated-client"; + } +#endif return UseSharedSpaces ? "compiled mode, sharing" : "compiled mode"; }; ShouldNotReachHere(); diff --git a/hotspot/test/TEST.ROOT b/hotspot/test/TEST.ROOT index 14d3a1c0135..54b61ac1406 100644 --- a/hotspot/test/TEST.ROOT +++ b/hotspot/test/TEST.ROOT @@ -46,6 +46,7 @@ requires.properties= \ vm.gc.Parallel \ vm.gc.ConcMarkSweep \ vm.jvmci \ + vm.emulatedClient \ vm.cpu.features \ vm.debug diff --git a/hotspot/test/compiler/arraycopy/TestArrayCopyNoInitDeopt.java b/hotspot/test/compiler/arraycopy/TestArrayCopyNoInitDeopt.java index e121ab36b6b..023bd266f31 100644 --- a/hotspot/test/compiler/arraycopy/TestArrayCopyNoInitDeopt.java +++ b/hotspot/test/compiler/arraycopy/TestArrayCopyNoInitDeopt.java @@ -25,7 +25,7 @@ * @test * @bug 8072016 * @summary Infinite deoptimization/recompilation cycles in case of arraycopy with tightly coupled allocation - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management @@ -86,8 +86,8 @@ public class TestArrayCopyNoInitDeopt { } static public void main(String[] args) throws Exception { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } // Only execute if C2 is available if (TIERED_STOP_AT_LEVEL == CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION) { diff --git a/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java b/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java index f8a3e6607d2..a8d4144b489 100644 --- a/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java +++ b/hotspot/test/compiler/c2/cr7200264/TestSSE2IntVect.java @@ -26,6 +26,7 @@ * @bug 7200264 * @summary 7192963 changes disabled shift vectors * @requires vm.cpu.features ~= ".*sse2.*" & vm.debug & vm.flavor == "server" + * @requires !vm.emulatedClient * @library /test/lib / * @run driver compiler.c2.cr7200264.TestSSE2IntVect */ diff --git a/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java b/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java index c3c2c6aa52a..bab678e32b6 100644 --- a/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java +++ b/hotspot/test/compiler/c2/cr7200264/TestSSE4IntVect.java @@ -26,6 +26,7 @@ * @bug 7200264 * @summary 7192963 changes disabled shift vectors * @requires vm.cpu.features ~= ".*sse4\\.1.*" & vm.debug & vm.flavor == "server" + * @requires !vm.emulatedClient * @library /test/lib / * @run driver compiler.c2.cr7200264.TestSSE4IntVect */ diff --git a/hotspot/test/compiler/codecache/stress/OverloadCompileQueueTest.java b/hotspot/test/compiler/codecache/stress/OverloadCompileQueueTest.java index 535e7026a7f..72886587ec9 100644 --- a/hotspot/test/compiler/codecache/stress/OverloadCompileQueueTest.java +++ b/hotspot/test/compiler/codecache/stress/OverloadCompileQueueTest.java @@ -65,9 +65,9 @@ public class OverloadCompileQueueTest implements Runnable { AVAILABLE_LEVELS = IntStream .rangeClosed(LEVEL_SIMPLE, TIERED_STOP_AT_LEVEL) .toArray(); - } else if (Platform.isServer()) { + } else if (Platform.isServer() && !Platform.isEmulatedClient()) { AVAILABLE_LEVELS = new int[] { LEVEL_FULL_OPTIMIZATION }; - } else if (Platform.isClient() || Platform.isMinimal()) { + } else if (Platform.isClient() || Platform.isMinimal() || Platform.isEmulatedClient()) { AVAILABLE_LEVELS = new int[] { LEVEL_SIMPLE }; } else { throw new Error("TESTBUG: unknown VM: " + Platform.vmName); diff --git a/hotspot/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java b/hotspot/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java index 5fa126bad72..dd8c4aa6925 100644 --- a/hotspot/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java +++ b/hotspot/test/compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java @@ -75,7 +75,7 @@ public class TestAESIntrinsicsOnSupportedConfig extends AESIntrinsicsBase { prepareArguments(prepareBooleanFlag(AESIntrinsicsBase .USE_AES, true))); final String errorMessage = "Case testUseAES failed"; - if (Platform.isServer()) { + if (Platform.isServer() && !Platform.isEmulatedClient()) { verifyOutput(new String[]{AESIntrinsicsBase.CIPHER_INTRINSIC, AESIntrinsicsBase.AES_INTRINSIC}, null, errorMessage, outputAnalyzer); diff --git a/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java b/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java index 2be9bf6aca4..a2ca8d50837 100644 --- a/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java +++ b/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java @@ -114,7 +114,7 @@ public class IntrinsicAvailableTest extends CompilerWhiteBoxTest { public void test() throws Exception { Executable intrinsicMethod = testCase.getExecutable(); - if (Platform.isServer() && (TIERED_STOP_AT_LEVEL == COMP_LEVEL_FULL_OPTIMIZATION)) { + if (Platform.isServer() && !Platform.isEmulatedClient() && (TIERED_STOP_AT_LEVEL == COMP_LEVEL_FULL_OPTIMIZATION)) { if (TIERED_COMPILATION) { checkIntrinsicForCompilationLevel(intrinsicMethod, COMP_LEVEL_SIMPLE); } diff --git a/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java b/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java index 155956cb87f..aed0acab0ab 100644 --- a/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java +++ b/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java @@ -197,7 +197,8 @@ public class IntrinsicDisabledTest { } public static void main(String args[]) { - if (Platform.isServer() && (TIERED_STOP_AT_LEVEL == CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION)) { + if (Platform.isServer() && !Platform.isEmulatedClient() && + (TIERED_STOP_AT_LEVEL == CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION)) { if (TIERED_COMPILATION) { test(CompilerWhiteBoxTest.COMP_LEVEL_SIMPLE); } diff --git a/hotspot/test/compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java b/hotspot/test/compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java index a8c3455b322..0600ed22ec1 100644 --- a/hotspot/test/compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java +++ b/hotspot/test/compiler/intrinsics/bigInteger/MontgomeryMultiplyTest.java @@ -26,7 +26,7 @@ * @test * @bug 8130150 8131779 8139907 * @summary Verify that the Montgomery multiply and square intrinsic works and correctly checks their arguments. - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @modules java.base/jdk.internal.misc:open * @modules java.base/java.math:open * @library /test/lib / @@ -314,8 +314,8 @@ public class MontgomeryMultiplyTest { } public static void main(String args[]) { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } if (wb.isIntrinsicAvailable(getExecutable(true), CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION) && wb.isIntrinsicAvailable(getExecutable(false), CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION)) { diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestI.java index f307a3ec555..d0d1b9fa835 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestL.java index dd1bc571787..f485eda7109 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/AndnTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestI.java index a5e34b5f6a8..7bb38602598 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestL.java index 72eb85a322f..c5daec36435 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsiTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestI.java index a5829a7e931..4dc005a1dbd 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestL.java index 9198bc734fd..f043de26bbf 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsmskTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestI.java index 2ab1c78dfba..d7f75741384 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestL.java index 3addea222c1..7545802107f 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BlsrTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/BmiIntrinsicBase.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/BmiIntrinsicBase.java index 3533aa9ecdb..813053d85f1 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/BmiIntrinsicBase.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/BmiIntrinsicBase.java @@ -78,7 +78,7 @@ public class BmiIntrinsicBase extends CompilerWhiteBoxTest { System.out.println(testCase.name()); - if (TIERED_COMPILATION && TIERED_STOP_AT_LEVEL != CompilerWhiteBoxTest.COMP_LEVEL_MAX) { + if (TIERED_COMPILATION && TIERED_STOP_AT_LEVEL != CompilerWhiteBoxTest.COMP_LEVEL_MAX || Platform.isEmulatedClient()) { System.out.println("TieredStopAtLevel value (" + TIERED_STOP_AT_LEVEL + ") is too low, test SKIPPED"); return; } diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestI.java index 886d4623032..2fb39220aa4 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestL.java index b6bf6b5c48f..18b366e2ebb 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/LZcntTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestI.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestI.java index 8a5e86187b9..ce65f84151b 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestI.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestI.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestL.java b/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestL.java index 44f79d03012..4cc396373ce 100644 --- a/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestL.java +++ b/hotspot/test/compiler/intrinsics/bmi/verifycode/TZcntTestL.java @@ -24,7 +24,7 @@ /* * @test * @bug 8031321 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management diff --git a/hotspot/test/compiler/intrinsics/klass/CastNullCheckDroppingsTest.java b/hotspot/test/compiler/intrinsics/klass/CastNullCheckDroppingsTest.java index b2a9554060d..3285b904bf7 100644 --- a/hotspot/test/compiler/intrinsics/klass/CastNullCheckDroppingsTest.java +++ b/hotspot/test/compiler/intrinsics/klass/CastNullCheckDroppingsTest.java @@ -25,7 +25,7 @@ * @test NullCheckDroppingsTest * @bug 8054492 * @summary Casting can result in redundant null checks in generated code - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -84,8 +84,8 @@ public class CastNullCheckDroppingsTest { int[] asink; public static void main(String[] args) throws Exception { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } // Make sure background compilation is disabled if (WHITE_BOX.getBooleanVMFlag("BackgroundCompilation")) { diff --git a/hotspot/test/compiler/intrinsics/mathexact/sanity/IntrinsicBase.java b/hotspot/test/compiler/intrinsics/mathexact/sanity/IntrinsicBase.java index 10ae924c794..f9b2e156f0c 100644 --- a/hotspot/test/compiler/intrinsics/mathexact/sanity/IntrinsicBase.java +++ b/hotspot/test/compiler/intrinsics/mathexact/sanity/IntrinsicBase.java @@ -50,7 +50,7 @@ public abstract class IntrinsicBase extends CompilerWhiteBoxTest { int expectedIntrinsicCount = 0; - if (Platform.isServer()) { + if (Platform.isServer() && !Platform.isEmulatedClient()) { if (TIERED_COMPILATION) { int max_level = TIERED_STOP_AT_LEVEL; expectedIntrinsicCount = (max_level == COMP_LEVEL_MAX) ? 1 : 0; diff --git a/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java b/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java index 31c32f2cd2a..e277f15035a 100644 --- a/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java +++ b/hotspot/test/compiler/loopopts/TestCountedLoopSafepointBackedge.java @@ -24,7 +24,7 @@ /** * @test * @bug 8161147 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @summary Safepoint on backedge breaks UseCountedLoopSafepoints * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement -XX:+UseCountedLoopSafepoints TestCountedLoopSafepointBackedge * diff --git a/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java b/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java index 25a2ad4e087..b7cd0338d66 100644 --- a/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java +++ b/hotspot/test/compiler/loopopts/UseCountedLoopSafepointsTest.java @@ -28,6 +28,7 @@ * @summary Test that C2 flag UseCountedLoopSafepoints ensures a safepoint is kept in a CountedLoop * @library /test/lib / * @requires vm.compMode != "Xint" & vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4) & vm.debug == true + * @requires !vm.emulatedClient * @modules java.base/jdk.internal.misc * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox @@ -37,6 +38,7 @@ package compiler.loopopts; +import jdk.test.lib.Platform; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; import java.util.List; @@ -51,6 +53,9 @@ import jdk.test.lib.Asserts; public class UseCountedLoopSafepointsTest { public static void main (String args[]) { + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); + } check(true); // check ideal graph with UseCountedLoopSafepoint enabled check(false); // ... and disabled } diff --git a/hotspot/test/compiler/rangechecks/TestExplicitRangeChecks.java b/hotspot/test/compiler/rangechecks/TestExplicitRangeChecks.java index 75adaa3551b..f1736178b2d 100644 --- a/hotspot/test/compiler/rangechecks/TestExplicitRangeChecks.java +++ b/hotspot/test/compiler/rangechecks/TestExplicitRangeChecks.java @@ -445,7 +445,7 @@ public class TestExplicitRangeChecks { success = false; } // Only perform these additional checks if C2 is available - if (Platform.isServer() && + if (Platform.isServer() && !Platform.isEmulatedClient() && TIERED_STOP_AT_LEVEL == CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION) { if (deoptimize && WHITE_BOX.isMethodCompiled(m)) { System.out.println(name + " not deoptimized on invalid access"); diff --git a/hotspot/test/compiler/testlibrary/CompilerUtils.java b/hotspot/test/compiler/testlibrary/CompilerUtils.java index fea72bd4c4b..85607db8ee7 100644 --- a/hotspot/test/compiler/testlibrary/CompilerUtils.java +++ b/hotspot/test/compiler/testlibrary/CompilerUtils.java @@ -53,10 +53,10 @@ public class CompilerUtils { "TieredStopAtLevel has value out of int capacity"); return IntStream.rangeClosed(1, maxLevel).toArray(); } else { - if (Platform.isServer()) { + if (Platform.isServer() && !Platform.isEmulatedClient()) { return new int[]{4}; } - if (Platform.isClient() || Platform.isMinimal()) { + if (Platform.isClient() || Platform.isMinimal() || Platform.isEmulatedClient()) { return new int[]{1}; } } diff --git a/hotspot/test/compiler/testlibrary/sha/predicate/IntrinsicPredicates.java b/hotspot/test/compiler/testlibrary/sha/predicate/IntrinsicPredicates.java index 98612cdde42..d866377049b 100644 --- a/hotspot/test/compiler/testlibrary/sha/predicate/IntrinsicPredicates.java +++ b/hotspot/test/compiler/testlibrary/sha/predicate/IntrinsicPredicates.java @@ -55,7 +55,7 @@ public class IntrinsicPredicates { "TieredStopAtLevel"); boolean maxLevelIsReachable = (tieredMaxLevel == IntrinsicPredicates.TIERED_MAX_LEVEL); - return Platform.isServer() && (!isTiered || maxLevelIsReachable); + return Platform.isServer() && !Platform.isEmulatedClient() && (!isTiered || maxLevelIsReachable); }; public static final BooleanSupplier SHA1_INSTRUCTION_AVAILABLE diff --git a/hotspot/test/compiler/tiered/NonTieredLevelsTest.java b/hotspot/test/compiler/tiered/NonTieredLevelsTest.java index 45d039f7551..19a47753bde 100644 --- a/hotspot/test/compiler/tiered/NonTieredLevelsTest.java +++ b/hotspot/test/compiler/tiered/NonTieredLevelsTest.java @@ -47,10 +47,10 @@ public class NonTieredLevelsTest extends CompLevelsTest { private static final int AVAILABLE_COMP_LEVEL; private static final IntPredicate IS_AVAILABLE_COMPLEVEL; static { - if (Platform.isServer()) { + if (Platform.isServer() && !Platform.isEmulatedClient()) { AVAILABLE_COMP_LEVEL = COMP_LEVEL_FULL_OPTIMIZATION; IS_AVAILABLE_COMPLEVEL = x -> x == COMP_LEVEL_FULL_OPTIMIZATION; - } else if (Platform.isClient() || Platform.isMinimal()) { + } else if (Platform.isClient() || Platform.isMinimal() || Platform.isEmulatedClient()) { AVAILABLE_COMP_LEVEL = COMP_LEVEL_SIMPLE; IS_AVAILABLE_COMPLEVEL = x -> x >= COMP_LEVEL_SIMPLE && x <= COMP_LEVEL_FULL_PROFILE; diff --git a/hotspot/test/compiler/types/correctness/CorrectnessTest.java b/hotspot/test/compiler/types/correctness/CorrectnessTest.java index 6b588cfc3af..b4fc31062a8 100644 --- a/hotspot/test/compiler/types/correctness/CorrectnessTest.java +++ b/hotspot/test/compiler/types/correctness/CorrectnessTest.java @@ -25,7 +25,7 @@ * @test CorrectnessTest * @bug 8038418 * @summary Tests correctness of type usage with type profiling and speculations - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management @@ -88,8 +88,8 @@ public class CorrectnessTest { private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox(); public static void main(String[] args) { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } Asserts.assertGTE(args.length, 1); ProfilingType profilingType = ProfilingType.valueOf(args[0]); diff --git a/hotspot/test/compiler/uncommontrap/TestUnstableIfTrap.java b/hotspot/test/compiler/uncommontrap/TestUnstableIfTrap.java index 84f53c89246..5d6f8cbae6c 100644 --- a/hotspot/test/compiler/uncommontrap/TestUnstableIfTrap.java +++ b/hotspot/test/compiler/uncommontrap/TestUnstableIfTrap.java @@ -206,7 +206,7 @@ public class TestUnstableIfTrap { boolean isMethodCompiledAtMaxTier = WB.getMethodCompilationLevel(m) == MAX_TIER; - return Platform.isServer() && isMethodCompiled + return Platform.isServer() && !Platform.isEmulatedClient() && isMethodCompiled && (!isTiered || isMethodCompiledAtMaxTier); } diff --git a/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java b/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java index e2e315818c9..56913e307d3 100644 --- a/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java +++ b/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java @@ -28,7 +28,7 @@ * @summary tests on constant folding of unsafe get operations * @library /test/lib * - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * * @modules java.base/jdk.internal.org.objectweb.asm * java.base/jdk.internal.vm.annotation @@ -93,8 +93,8 @@ public class UnsafeGetConstantField { static final Unsafe U = Unsafe.getUnsafe(); public static void main(String[] args) { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } testUnsafeGetAddress(); testUnsafeGetField(); diff --git a/hotspot/test/compiler/unsafe/UnsafeGetStableArrayElement.java b/hotspot/test/compiler/unsafe/UnsafeGetStableArrayElement.java index bc321049b1d..b938bc6a4fd 100644 --- a/hotspot/test/compiler/unsafe/UnsafeGetStableArrayElement.java +++ b/hotspot/test/compiler/unsafe/UnsafeGetStableArrayElement.java @@ -28,7 +28,7 @@ * @summary tests on constant folding of unsafe get operations from stable arrays * @library /test/lib * - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * * @modules java.base/jdk.internal.vm.annotation * java.base/jdk.internal.misc @@ -332,8 +332,8 @@ public class UnsafeGetStableArrayElement { } public static void main(String[] args) throws Exception { - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } testUnsafeAccess(); System.out.println("TEST PASSED"); diff --git a/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java b/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java index c5f4687ffa9..0e5c20bcf87 100644 --- a/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java +++ b/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java @@ -25,7 +25,8 @@ * @test IsMethodCompilableTest * @bug 8007270 8006683 8007288 8022832 * @summary testing of WB::isMethodCompilable() - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & (vm.opt.TieredStopAtLevel == null | vm.opt.TieredStopAtLevel == 4) + * @requires !vm.emulatedClient * @library /test/lib / * @modules java.base/jdk.internal.misc * java.management @@ -82,8 +83,8 @@ public class IsMethodCompilableTest extends CompilerWhiteBoxTest { protected void test() throws Exception { // Only c2 compilations can be disabled through PerMethodRecompilationCutoff - if (!Platform.isServer()) { - throw new Error("TESTBUG: Not server VM"); + if (!Platform.isServer() || Platform.isEmulatedClient()) { + throw new Error("TESTBUG: Not server mode"); } if (skipXcompOSR()) { diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java index c85acf5be82..24a1b2d10d6 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithCMS.java @@ -29,7 +29,7 @@ import java.io.IOException; * @key gc * @key stress * @requires vm.gc.ConcMarkSweep - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @summary Stress the CMS GC by trying to make old objects more likely to be garbage than young objects. * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseConcMarkSweepGC TestGCBasherWithCMS 120000 */ diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java index 0e87aa82c6b..90e87534310 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithG1.java @@ -29,7 +29,7 @@ import java.io.IOException; * @key gc * @key stress * @requires vm.gc.G1 - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @summary Stress the G1 GC by trying to make old objects more likely to be garbage than young objects. * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseG1GC TestGCBasherWithG1 120000 */ diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithParallel.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithParallel.java index a60deeb00a7..ddda7d0caf7 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithParallel.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithParallel.java @@ -29,7 +29,7 @@ import java.io.IOException; * @key gc * @key stress * @requires vm.gc.Parallel - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @summary Stress the Parallel GC by trying to make old objects more likely to be garbage than young objects. * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseParallelGC -XX:-UseGCOverheadLimit TestGCBasherWithParallel 120000 */ diff --git a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java index 7ca865dd112..e69da5de2ef 100644 --- a/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java +++ b/hotspot/test/gc/stress/gcbasher/TestGCBasherWithSerial.java @@ -29,7 +29,7 @@ import java.io.IOException; * @key gc * @key stress * @requires vm.gc.Serial - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @summary Stress the Serial GC by trying to make old objects more likely to be garbage than young objects. * @run main/othervm/timeout=200 -Xlog:gc*=info -Xmx256m -server -XX:+UseSerialGC TestGCBasherWithSerial 120000 */ diff --git a/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java b/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java index 425a2e5ba4e..17fa71def6f 100644 --- a/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java +++ b/hotspot/test/runtime/CDSCompressedKPtrs/XShareAuto.java @@ -48,8 +48,9 @@ public class XShareAuto { "-server", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./XShareAuto.jsa", "-version"); output = new OutputAnalyzer(pb.start()); + String outputString = output.getOutput(); // We asked for server but it could be aliased to something else - if (output.getOutput().contains("Server VM")) { + if (outputString.contains("Server VM") && !outputString.contains("emulated-client")) { // In server case we don't expect to see sharing flag output.shouldNotContain("sharing"); output.shouldHaveExitValue(0); diff --git a/hotspot/test/runtime/ReservedStack/ReservedStackTestCompiler.java b/hotspot/test/runtime/ReservedStack/ReservedStackTestCompiler.java index 1bc41f61355..616788fe251 100644 --- a/hotspot/test/runtime/ReservedStack/ReservedStackTestCompiler.java +++ b/hotspot/test/runtime/ReservedStack/ReservedStackTestCompiler.java @@ -24,7 +24,7 @@ /* * @test ReservedStackTestCompiler * @summary Run ReservedStackTest with dedicated compilers C1 and C2. - * @requires vm.flavor == "server" + * @requires vm.flavor == "server" & !vm.emulatedClient * @library /test/lib * @modules java.base/jdk.internal.misc * @modules java.base/jdk.internal.vm.annotation diff --git a/hotspot/test/serviceability/dcmd/compiler/CompilerDirectivesDCMDTest.java b/hotspot/test/serviceability/dcmd/compiler/CompilerDirectivesDCMDTest.java index c43dfafa56f..8d40423b5e8 100644 --- a/hotspot/test/serviceability/dcmd/compiler/CompilerDirectivesDCMDTest.java +++ b/hotspot/test/serviceability/dcmd/compiler/CompilerDirectivesDCMDTest.java @@ -49,7 +49,7 @@ public class CompilerDirectivesDCMDTest { public void run(CommandExecutor executor) { - if (Platform.isServer()) { + if (Platform.isServer() && !Platform.isEmulatedClient()) { filename = System.getProperty("test.src", ".") + File.separator + "control2.txt"; } else { filename = System.getProperty("test.src", ".") + File.separator + "control1.txt"; diff --git a/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/Utils.java b/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/Utils.java index 4159c483408..75d82dd1ebd 100644 --- a/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/Utils.java +++ b/hotspot/test/testlibrary/ctw/src/sun/hotspot/tools/ctw/Utils.java @@ -101,10 +101,12 @@ public class Utils { INITIAL_COMP_LEVEL = 1; } else { String vmName = System.getProperty("java.vm.name"); - if (Utils.endsWithIgnoreCase(vmName, " Server VM")) { + String vmInfo = System.getProperty("java.vm.info"); + boolean isEmulatedClient = (vmInfo != null) && vmInfo.contains("emulated-client"); + if (Utils.endsWithIgnoreCase(vmName, " Server VM") && !isEmulatedClient) { INITIAL_COMP_LEVEL = 4; } else if (Utils.endsWithIgnoreCase(vmName, " Client VM") - || Utils.endsWithIgnoreCase(vmName, " Minimal VM")) { + || Utils.endsWithIgnoreCase(vmName, " Minimal VM") || isEmulatedClient) { INITIAL_COMP_LEVEL = 1; } else { throw new RuntimeException("Unknown VM: " + vmName); diff --git a/hotspot/test/testlibrary_tests/TestMutuallyExclusivePlatformPredicates.java b/hotspot/test/testlibrary_tests/TestMutuallyExclusivePlatformPredicates.java index 43c9715a95e..5e56d66bd4a 100644 --- a/hotspot/test/testlibrary_tests/TestMutuallyExclusivePlatformPredicates.java +++ b/hotspot/test/testlibrary_tests/TestMutuallyExclusivePlatformPredicates.java @@ -50,7 +50,7 @@ public class TestMutuallyExclusivePlatformPredicates { OS("isAix", "isLinux", "isOSX", "isSolaris", "isWindows"), VM_TYPE("isClient", "isServer", "isGraal", "isMinimal", "isZero", "isEmbedded"), MODE("isInt", "isMixed", "isComp"), - IGNORED("isDebugBuild", "isFastDebugBuild", "isSlowDebugBuild", + IGNORED("isEmulatedClient", "isDebugBuild", "isFastDebugBuild", "isSlowDebugBuild", "shouldSAAttach", "canPtraceAttachLinux", "canAttachOSX", "isTieredSupported"); From 0ac0d9ac29c0226fce7a965163e96e2a536d3716 Mon Sep 17 00:00:00 2001 From: Jamsheed Mohammed C M Date: Tue, 17 Jan 2017 21:39:22 -0800 Subject: [PATCH 050/130] 8166002: Emulate client build on platforms with reduced virtual address space The default VM ergonomics on Windows/x86 (32-bit) are changed to client like. Reviewed-by: kvn, iveresov --- test/jtreg-ext/requires/VMProps.java | 12 ++++++++++++ test/lib/jdk/test/lib/Platform.java | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/test/jtreg-ext/requires/VMProps.java b/test/jtreg-ext/requires/VMProps.java index 15c854f964b..8ac981d28b2 100644 --- a/test/jtreg-ext/requires/VMProps.java +++ b/test/jtreg-ext/requires/VMProps.java @@ -64,6 +64,7 @@ public class VMProps implements Callable> { map.put("vm.simpleArch", vmArch()); map.put("vm.debug", vmDebug()); map.put("vm.jvmci", vmJvmci()); + map.put("vm.emulatedClient", vmEmulatedClient()); map.put("vm.cpu.features", cpuFeatures()); vmGC(map); // vm.gc.X = true/false @@ -168,6 +169,17 @@ public class VMProps implements Callable> { return "" + (WB.getBooleanVMFlag("EnableJVMCI") != null); } + /** + * @return true if VM runs in emulated-client mode and false otherwise. + */ + protected String vmEmulatedClient() { + String vmInfo = System.getProperty("java.vm.info"); + if (vmInfo == null) { + return "false"; + } + return "" + vmInfo.contains(" emulated-client"); + } + /** * @return supported CPU features */ diff --git a/test/lib/jdk/test/lib/Platform.java b/test/lib/jdk/test/lib/Platform.java index 3f924371c43..26bbf1bae94 100644 --- a/test/lib/jdk/test/lib/Platform.java +++ b/test/lib/jdk/test/lib/Platform.java @@ -63,6 +63,10 @@ public class Platform { return vmName.contains("Embedded"); } + public static boolean isEmulatedClient() { + return vmInfo.contains(" emulated-client"); + } + public static boolean isTieredSupported() { return compiler.contains("Tiered Compilers"); } From a6092584f9c8e87c36ff4b31f645fe4efa92156f Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Wed, 18 Jan 2017 08:54:29 +0100 Subject: [PATCH 051/130] 8172884: TraceOptoPipelining and TraceOptoOutput are broken Compiler Control code needs not set the default values for the directive according to the flag value. Reviewed-by: neliasso, redestad --- hotspot/src/share/vm/compiler/compilerDirectives.hpp | 5 ++--- hotspot/src/share/vm/opto/compile.cpp | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/compiler/compilerDirectives.hpp b/hotspot/src/share/vm/compiler/compilerDirectives.hpp index 283fd48127e..7c4efa650a5 100644 --- a/hotspot/src/share/vm/compiler/compilerDirectives.hpp +++ b/hotspot/src/share/vm/compiler/compilerDirectives.hpp @@ -60,13 +60,12 @@ cflags(BlockLayoutByFrequency, bool, BlockLayoutByFrequency, BlockLayoutByFrequency) \ cflags(PrintOptoAssembly, bool, PrintOptoAssembly, PrintOptoAssembly) \ cflags(PrintIntrinsics, bool, PrintIntrinsics, PrintIntrinsics) \ - cflags(TraceOptoPipelining, bool, false, TraceOptoPipelining) \ - cflags(TraceOptoOutput, bool, false, TraceOptoOutput) \ +NOT_PRODUCT(cflags(TraceOptoPipelining, bool, TraceOptoPipelining, TraceOptoPipelining)) \ +NOT_PRODUCT(cflags(TraceOptoOutput, bool, TraceOptoOutput, TraceOptoOutput)) \ cflags(TraceSpilling, bool, TraceSpilling, TraceSpilling) \ cflags(Vectorize, bool, false, Vectorize) \ cflags(VectorizeDebug, uintx, 0, VectorizeDebug) \ cflags(CloneMapDebug, bool, false, CloneMapDebug) \ - cflags(DoReserveCopyInSuperWordDebug, bool, false, DoReserveCopyInSuperWordDebug) \ cflags(IGVPrintLevel, intx, PrintIdealGraphLevel, IGVPrintLevel) \ cflags(MaxNodeLimit, intx, MaxNodeLimit, MaxNodeLimit) #else diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 77e20b264cb..4c84b0339ec 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -971,7 +971,7 @@ Compile::Compile( ciEnv* ci_env, _java_calls(0), _inner_loops(0), #ifndef PRODUCT - _trace_opto_output(TraceOptoOutput), + _trace_opto_output(directive->TraceOptoOutputOption), _in_dump_cnt(0), _printer(NULL), #endif From 362fbe12e8a725d48f73acbebd37270d5ea3cf21 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Wed, 18 Jan 2017 10:30:56 -0500 Subject: [PATCH 052/130] 8144518: ClassVerboseTest crashes on Windows Simplify Bytecode_tableswitch code so windows doesn't generate bad code for it. Reviewed-by: ctornqvi, dholmes --- hotspot/src/share/vm/interpreter/bytecode.cpp | 4 ++-- hotspot/src/share/vm/interpreter/bytecode.hpp | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/hotspot/src/share/vm/interpreter/bytecode.cpp b/hotspot/src/share/vm/interpreter/bytecode.cpp index 80b95d627b5..6cc38a5a0cd 100644 --- a/hotspot/src/share/vm/interpreter/bytecode.cpp +++ b/hotspot/src/share/vm/interpreter/bytecode.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,7 +112,7 @@ void Bytecode::assert_native_index(Bytecodes::Code bc, bool is_wide) { // Implementation of Bytecode_tableupswitch int Bytecode_tableswitch::dest_offset_at(int i) const { - return get_Java_u4_at(aligned_offset(1 + (3 + i)*jintSize)); + return get_aligned_Java_u4_at(1 + (3 + i)*jintSize); } diff --git a/hotspot/src/share/vm/interpreter/bytecode.hpp b/hotspot/src/share/vm/interpreter/bytecode.hpp index f3fc9ea9d6a..5c53ab4121f 100644 --- a/hotspot/src/share/vm/interpreter/bytecode.hpp +++ b/hotspot/src/share/vm/interpreter/bytecode.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,11 +45,11 @@ class Bytecode: public StackObj { address addr_at (int offset) const { return (address)_bcp + offset; } u_char byte_at(int offset) const { return *addr_at(offset); } address aligned_addr_at (int offset) const { return (address)round_to((intptr_t)addr_at(offset), jintSize); } - int aligned_offset (int offset) const { return aligned_addr_at(offset) - addr_at(0); } // Word access: int get_Java_u2_at (int offset) const { return Bytes::get_Java_u2(addr_at(offset)); } int get_Java_u4_at (int offset) const { return Bytes::get_Java_u4(addr_at(offset)); } + int get_aligned_Java_u4_at(int offset) const { return Bytes::get_Java_u4(aligned_addr_at(offset)); } int get_native_u2_at (int offset) const { return Bytes::get_native_u2(addr_at(offset)); } int get_native_u4_at (int offset) const { return Bytes::get_native_u4(addr_at(offset)); } @@ -150,8 +150,8 @@ class Bytecode_lookupswitch: public Bytecode { void verify() const PRODUCT_RETURN; // Attributes - int default_offset() const { return get_Java_u4_at(aligned_offset(1 + 0*jintSize)); } - int number_of_pairs() const { return get_Java_u4_at(aligned_offset(1 + 1*jintSize)); } + int default_offset() const { return get_aligned_Java_u4_at(1 + 0*jintSize); } + int number_of_pairs() const { return get_aligned_Java_u4_at(1 + 1*jintSize); } LookupswitchPair pair_at(int i) const { assert(0 <= i && i < number_of_pairs(), "pair index out of bounds"); return LookupswitchPair(aligned_addr_at(1 + (1 + i)*2*jintSize)); @@ -166,9 +166,9 @@ class Bytecode_tableswitch: public Bytecode { void verify() const PRODUCT_RETURN; // Attributes - int default_offset() const { return get_Java_u4_at(aligned_offset(1 + 0*jintSize)); } - int low_key() const { return get_Java_u4_at(aligned_offset(1 + 1*jintSize)); } - int high_key() const { return get_Java_u4_at(aligned_offset(1 + 2*jintSize)); } + int default_offset() const { return get_aligned_Java_u4_at(1 + 0*jintSize); } + int low_key() const { return get_aligned_Java_u4_at(1 + 1*jintSize); } + int high_key() const { return get_aligned_Java_u4_at(1 + 2*jintSize); } int dest_offset_at(int i) const; int length() { return high_key()-low_key()+1; } }; From 3d5e2ddf611f78793f394fd602981aea508c3aa3 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 18 Jan 2017 14:36:54 -0800 Subject: [PATCH 053/130] 8172990: [AOT] Missing GC scan of _metaspace_got array containing Klass* Added back _metaspace_got array scan. Reviewed-by: dlong --- .../tools/jaotc/CallSiteRelocationSymbol.java | 6 ---- .../jaotc/JavaCallSiteRelocationSymbol.java | 16 +++++++-- hotspot/src/share/vm/aot/aotCodeHeap.cpp | 33 ++++--------------- .../src/share/vm/aot/aotCompiledMethod.cpp | 27 +++++++-------- .../src/share/vm/aot/aotCompiledMethod.hpp | 2 -- .../src/share/vm/runtime/deoptimization.cpp | 4 +-- 6 files changed, 35 insertions(+), 53 deletions(-) diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/CallSiteRelocationSymbol.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/CallSiteRelocationSymbol.java index 68f86ef65e3..5fce078a470 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/CallSiteRelocationSymbol.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/CallSiteRelocationSymbol.java @@ -59,12 +59,6 @@ abstract class CallSiteRelocationSymbol { addExternalPltToGotRelocation(binaryContainer, symbol, relocationOffset); } - protected static void addMetaspaceGotRelocation(BinaryContainer binaryContainer, String symbolName, int symbolOffset, int relocationOffset) { - ByteContainer container = binaryContainer.getMetaspaceGotContainer(); - Symbol symbol = container.createGotSymbol(symbolOffset, symbolName); - addExternalPltToGotRelocation(binaryContainer, symbol, relocationOffset); - } - /** * Add an {@link RelocType#EXTERNAL_GOT_TO_PLT} relocation to the * {@link BinaryContainer#getExtLinkageGOTContainer()}. diff --git a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/JavaCallSiteRelocationSymbol.java b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/JavaCallSiteRelocationSymbol.java index a14049dd87f..f589610ded8 100644 --- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/JavaCallSiteRelocationSymbol.java +++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/JavaCallSiteRelocationSymbol.java @@ -37,6 +37,7 @@ import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod; final class JavaCallSiteRelocationSymbol extends CallSiteRelocationSymbol { private static final byte[] zeroSlot = new byte[8]; + // -1 represents Universe::non_oop_word() value private static final byte[] minusOneSlot = {-1, -1, -1, -1, -1, -1, -1, -1}; public JavaCallSiteRelocationSymbol(CompiledMethodInfo mi, Call call, CallSiteRelocationInfo callSiteRelocation, BinaryContainer binaryContainer) { @@ -79,30 +80,39 @@ final class JavaCallSiteRelocationSymbol extends CallSiteRelocationSymbol { } // Add relocation to GOT cell for call resolution jump. + // This GOT cell will be initialized during JVM startup with address + // of JVM runtime call resolution function. String gotSymbolName = "got." + getResolveSymbolName(binaryContainer, mi, call); Symbol gotSymbol = binaryContainer.getGotSymbol(gotSymbolName); addExternalPltToGotRelocation(binaryContainer, gotSymbol, stub.getResolveJumpOffset()); // Add relocation to resolve call jump instruction address for GOT cell. + // This GOT cell will be initialized with address of resolution jump instruction and + // will be updated with call destination address by JVM runtime call resolution code. String pltJmpSymbolName = relocationSymbolName("plt.jmp", mi, call, callSiteRelocation); addCodeContainerRelocation(binaryContainer, pltJmpSymbolName, stub.getResolveJumpStart(), gotStartOffset); // Add relocation to GOT cell for dispatch jump. + // The dispatch jump loads destination address from this GOT cell. String gotEntrySymbolName = relocationSymbolName("got.entry", mi, call, callSiteRelocation); addExtLinkageGotContainerRelocation(binaryContainer, gotEntrySymbolName, gotStartOffset, stub.getDispatchJumpOffset()); - // Virtual call needs initial -1 value. + // Virtual call needs initial -1 value for Klass pointer. + // Non virtual call needs initial 0 value for Method pointer to call c2i adapter. byte[] slot = isVirtualCall ? minusOneSlot : zeroSlot; - final int gotMetaOffset = binaryContainer.appendMetaspaceGotBytes(slot, 0, slot.length); + final int gotMetaOffset = binaryContainer.appendExtLinkageGotBytes(slot, 0, slot.length); // Add relocation to GOT cell for move instruction (Klass* for virtual, Method* otherwise). String gotMoveSymbolName = relocationSymbolName("got.move", mi, call, callSiteRelocation); - addMetaspaceGotRelocation(binaryContainer, gotMoveSymbolName, gotMetaOffset, stub.getMovOffset()); + addExtLinkageGotContainerRelocation(binaryContainer, gotMoveSymbolName, gotMetaOffset, stub.getMovOffset()); if (isVirtualCall) { // Nothing. } else { // Add relocation to GOT cell for c2i adapter jump. + // The c2i jump instruction loads destination address from this GOT cell. + // This GOT cell is initialized with -1 and will be updated + // by JVM runtime call resolution code. String gotC2ISymbolName = relocationSymbolName("got.c2i", mi, call, callSiteRelocation); addExtLinkageGotContainerRelocation(binaryContainer, gotC2ISymbolName, gotStartOffset + 8, stub.getC2IJumpOffset()); } diff --git a/hotspot/src/share/vm/aot/aotCodeHeap.cpp b/hotspot/src/share/vm/aot/aotCodeHeap.cpp index 52e2c8d55b1..87d41f80777 100644 --- a/hotspot/src/share/vm/aot/aotCodeHeap.cpp +++ b/hotspot/src/share/vm/aot/aotCodeHeap.cpp @@ -830,38 +830,19 @@ void AOTCodeHeap::oops_do(OopClosure* f) { } } -// Yes, this is faster than going through the relocations, -// but there are two problems: -// 1) GOT slots are sometimes patched with non-Metadata values -// 2) We don't want to scan metadata for dead methods -// Unfortunately we don't know if the metadata belongs to -// live aot methods or not, so process them all. If this -// is for mark_on_stack, some old methods may stick around -// forever instead of getting cleaned up. +// Scan only metaspace_got cells which should have only Klass*, +// metadata_got cells are scanned only for alive AOT methods +// by AOTCompiledMethod::metadata_do(). void AOTCodeHeap::got_metadata_do(void f(Metadata*)) { for (int i = 1; i < _metaspace_got_size; i++) { Metadata** p = &_metaspace_got[i]; Metadata* md = *p; if (md == NULL) continue; // skip non-oops - intptr_t meta = (intptr_t)md; - if (meta == -1) continue; // skip non-oops if (Metaspace::contains(md)) { f(md); - } - } - for (int i = 1; i < _metadata_got_size; i++) { - Metadata** p = &_metadata_got[i]; - Metadata* md = *p; - intptr_t meta = (intptr_t)md; - if ((meta & 1) == 1) { - // already resolved - md = (Metadata*)(meta & ~1); } else { - continue; - } - if (md == NULL) continue; // skip non-oops - if (Metaspace::contains(md)) { - f(md); + intptr_t meta = (intptr_t)md; + fatal("Invalid value in _metaspace_got[%d] = " INTPTR_FORMAT, i, meta); } } } @@ -910,8 +891,6 @@ void AOTCodeHeap::metadata_do(void f(Metadata*)) { aot->metadata_do(f); } } -#if 0 - // With the marking above, this call doesn't seem to be needed + // Scan metaspace_got cells. got_metadata_do(f); -#endif } diff --git a/hotspot/src/share/vm/aot/aotCompiledMethod.cpp b/hotspot/src/share/vm/aot/aotCompiledMethod.cpp index 1f40284da7e..c501ce12e69 100644 --- a/hotspot/src/share/vm/aot/aotCompiledMethod.cpp +++ b/hotspot/src/share/vm/aot/aotCompiledMethod.cpp @@ -71,15 +71,6 @@ static void metadata_oops_do(Metadata** metadata_begin, Metadata **metadata_end, } #endif -void AOTCompiledMethod::oops_do(OopClosure* f) { - if (_oop != NULL) { - f->do_oop(&_oop); - } -#if 0 - metadata_oops_do(metadata_begin(), metadata_end(), f); -#endif -} - bool AOTCompiledMethod::do_unloading_oops(address low_boundary, BoolObjectClosure* is_alive, bool unloading_occurred) { return false; } @@ -161,9 +152,6 @@ Metadata* AOTCompiledMethod::metadata_at(int index) const { *entry = (Metadata*)meta; // Should be atomic on x64 return (Metadata*)m; } - // need to resolve it here..., patching of GOT need to be CAS or atomic operation. - // FIXIT: need methods for debuginfo. - // return _method; } ShouldNotReachHere(); return NULL; } @@ -288,11 +276,19 @@ void AOTCompiledMethod::metadata_do(void f(Metadata*)) { f(cichk->holder_method()); f(cichk->holder_klass()); } else { + // Get Klass* or NULL (if value is -1) from GOT cell of virtual call PLT stub. Metadata* ic_oop = ic->cached_metadata(); if (ic_oop != NULL) { f(ic_oop); } } + } else if (iter.type() == relocInfo::static_call_type || + iter.type() == relocInfo::opt_virtual_call_type){ + // Check Method* in AOT c2i stub for other calls. + Metadata* meta = (Metadata*)nativeLoadGot_at(nativePltCall_at(iter.addr())->plt_c2i_stub())->data(); + if (meta != NULL) { + f(meta); + } } } } @@ -332,7 +328,12 @@ void AOTCompiledMethod::print_on(outputStream* st, const char* msg) const { st->print("%4d ", _aot_id); // print compilation number st->print(" aot[%2d]", _heap->dso_id()); // Stubs have _method == NULL - st->print(" %s", (_method == NULL ? _name : _method->name_and_sig_as_C_string())); + if (_method == NULL) { + st->print(" %s", _name); + } else { + ResourceMark m; + st->print(" %s", _method->name_and_sig_as_C_string()); + } if (Verbose) { st->print(" entry at " INTPTR_FORMAT, p2i(_code)); } diff --git a/hotspot/src/share/vm/aot/aotCompiledMethod.hpp b/hotspot/src/share/vm/aot/aotCompiledMethod.hpp index 7fef6fdb433..723bbdb8d30 100644 --- a/hotspot/src/share/vm/aot/aotCompiledMethod.hpp +++ b/hotspot/src/share/vm/aot/aotCompiledMethod.hpp @@ -257,8 +257,6 @@ private: return (int) (*_state_adr); } - virtual void oops_do(OopClosure* f); - // inlined and non-virtual for AOTCodeHeap::oops_do void do_oops(OopClosure* f) { assert(_is_alive(), ""); diff --git a/hotspot/src/share/vm/runtime/deoptimization.cpp b/hotspot/src/share/vm/runtime/deoptimization.cpp index e3b88640768..aba4f3f478a 100644 --- a/hotspot/src/share/vm/runtime/deoptimization.cpp +++ b/hotspot/src/share/vm/runtime/deoptimization.cpp @@ -1596,9 +1596,9 @@ JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint tra get_method_data(thread, profiled_method, create_if_missing); // Log a message - Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d", + Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s", trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()), - trap_method->name_and_sig_as_C_string(), trap_bci); + trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name()); // Print a bunch of diagnostics, if requested. if (TraceDeoptimization || LogCompilation) { From 417f6a4ac86b5323527cb8fe570de76f65072545 Mon Sep 17 00:00:00 2001 From: David Holmes Date: Wed, 18 Jan 2017 19:54:18 -0500 Subject: [PATCH 054/130] 8172261: [JVMTI] Specification for early VM start event needs to lower expectations in relation class loading Reviewed-by: dcubed, sspitsyn, alanb --- hotspot/src/share/vm/prims/jvmti.xml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/hotspot/src/share/vm/prims/jvmti.xml b/hotspot/src/share/vm/prims/jvmti.xml index 0f390214eb2..7a0515c2bc4 100644 --- a/hotspot/src/share/vm/prims/jvmti.xml +++ b/hotspot/src/share/vm/prims/jvmti.xml @@ -1,7 +1,7 @@ 0; ) + q.poll(1L, TimeUnit.MICROSECONDS); + assertTrue(nodeCount(q) <= initialNodeCount + SWEEP_THRESHOLD); + + if (blockHead != null) { + blockHead.interrupt(); + blockHead.join(); + } + } + + /** Checks conditions which should always be true. */ + void assertInvariants(LinkedTransferQueue q) { + assertNotNull(head(q)); + assertNotNull(tail(q)); + // head is never self-linked (but tail may!) + for (Object h; next(h = head(q)) == h; ) + assertNotSame(h, head(q)); // must be update race + } +} diff --git a/jdk/test/java/util/concurrent/tck/Collection8Test.java b/jdk/test/java/util/concurrent/tck/Collection8Test.java index d58b367171f..e25f1dd750d 100644 --- a/jdk/test/java/util/concurrent/tck/Collection8Test.java +++ b/jdk/test/java/util/concurrent/tck/Collection8Test.java @@ -753,6 +753,31 @@ public class Collection8Test extends JSR166TestCase { }); } + /** + * Concurrent Spliterators, once exhausted, stay exhausted. + */ + public void testStickySpliteratorExhaustion() throws Throwable { + if (!impl.isConcurrent()) return; + if (!testImplementationDetails) return; + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); + final Consumer alwaysThrows = e -> { throw new AssertionError(); }; + final Collection c = impl.emptyCollection(); + final Spliterator s = c.spliterator(); + if (rnd.nextBoolean()) { + assertFalse(s.tryAdvance(alwaysThrows)); + } else { + s.forEachRemaining(alwaysThrows); + } + final Object one = impl.makeElement(1); + // Spliterator should not notice added element + c.add(one); + if (rnd.nextBoolean()) { + assertFalse(s.tryAdvance(alwaysThrows)); + } else { + s.forEachRemaining(alwaysThrows); + } + } + /** * Motley crew of threads concurrently randomly hammer the collection. */ From 030a779128c02293a940548a4d8f285e5dfef500 Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Fri, 3 Feb 2017 13:24:59 -0800 Subject: [PATCH 121/130] 8171886: Miscellaneous changes imported from jsr166 CVS 2017-02 Reviewed-by: martin, psandoz --- .../classes/java/util/PriorityQueue.java | 6 +- .../util/concurrent/ArrayBlockingQueue.java | 5 +- .../concurrent/ConcurrentSkipListSet.java | 12 +-- .../util/concurrent/CopyOnWriteArrayList.java | 10 +-- .../java/util/concurrent/DelayQueue.java | 17 ++-- .../util/concurrent/SynchronousQueue.java | 20 ++--- .../util/concurrent/ThreadLocalRandom.java | 12 +-- .../util/concurrent/locks/LockSupport.java | 6 +- .../AbstractList/CheckForComodification.java | 2 +- jdk/test/java/util/ArrayList/Bug6533203.java | 2 +- .../ArrayList/IteratorMicroBenchmark.java | 15 ++-- .../ArrayList/RangeCheckMicroBenchmark.java | 2 +- .../Collection/IteratorMicroBenchmark.java | 49 +++++++---- jdk/test/java/util/Collection/MOAT.java | 7 +- .../util/Collections/BigBinarySearch.java | 2 +- jdk/test/java/util/Collections/Disjoint.java | 2 +- .../util/Collections/RacingCollections.java | 17 ++-- .../java/util/Collections/ReverseOrder2.java | 6 +- .../java/util/Collections/SetFromMap.java | 2 +- jdk/test/java/util/Deque/ChorusLine.java | 6 +- .../java/util/IdentityHashMap/ToArray.java | 8 +- .../java/util/IdentityHashMap/ToString.java | 2 +- jdk/test/java/util/NavigableMap/LockStep.java | 4 +- .../java/util/PriorityQueue/ForgetMeNot.java | 2 +- jdk/test/java/util/PriorityQueue/NoNulls.java | 4 +- .../util/PriorityQueue/PriorityQueueSort.java | 12 +-- .../util/PriorityQueue/RemoveContains.java | 2 +- jdk/test/java/util/Random/DistinctSeeds.java | 4 +- jdk/test/java/util/TreeMap/NullAtEnd.java | 7 +- jdk/test/java/util/Vector/CopyInto.java | 2 +- .../IteratorConsistency.java | 55 ++++++------ .../CancelledProducerConsumerLoops.java | 5 +- .../BlockingQueue/DrainToFails.java | 2 +- .../concurrent/BlockingQueue/Interrupt.java | 2 +- .../BlockingQueue/PollMemoryLeak.java | 6 +- .../ConcurrentHashMap/MapCheck.java | 4 +- .../ConcurrentHashMap/MapLoops.java | 3 +- .../ConcurrentLinkedQueue/RemoveLeak.java | 6 +- .../ConcurrentMap/ConcurrentRemoveIf.java | 36 ++++---- .../ConcurrentQueueLoops.java | 4 +- .../ConcurrentQueues/GCRetention.java | 6 +- .../IteratorWeakConsistency.java | 4 +- .../ConcurrentQueues/RemovePollRace.java | 14 ++-- .../CopyOnWriteArrayList/EqualsRace.java | 2 +- .../CopyOnWriteArraySet/RacingCows.java | 10 +-- .../util/concurrent/CyclicBarrier/Basic.java | 4 +- .../util/concurrent/DelayQueue/Iterate.java | 2 +- .../concurrent/DelayQueue/PollUnexpired.java | 2 +- .../util/concurrent/DelayQueue/Stress.java | 2 +- .../concurrent/Exchanger/ExchangeLoops.java | 6 +- .../Executors/PrivilegedCallables.java | 6 +- .../FutureTask/BlockingTaskExecutor.java | 3 +- .../concurrent/FutureTask/Customized.java | 10 +-- .../concurrent/FutureTask/DoneMeansDone.java | 2 +- .../FutureTask/DoneTimedGetLoops.java | 4 +- .../LinkedBlockingQueue/ToArray.java | 2 +- .../java/util/concurrent/Phaser/Arrive.java | 2 +- .../java/util/concurrent/Phaser/Basic.java | 6 +- .../concurrent/Phaser/FickleRegister.java | 2 +- .../ThreadPoolExecutor/ConfigChanges.java | 32 ++++--- .../ThreadPoolExecutor/CoreThreadTimeOut.java | 3 +- .../ThreadPoolExecutor/ThrowingTasks.java | 27 ++++-- .../java/util/concurrent/atomic/Lazy.java | 4 +- .../locks/Lock/CheckedLockLoops.java | 7 +- .../locks/Lock/TimedAcquireLeak.java | 8 +- .../ReentrantLock/CancelledLockLoops.java | 7 +- .../ReentrantLock/LockOncePerThreadLoops.java | 9 +- .../SimpleReentrantLockLoops.java | 7 +- .../locks/ReentrantLock/TimeoutLockLoops.java | 7 +- .../tck/AbstractExecutorServiceTest.java | 28 +++---- .../AbstractQueuedLongSynchronizerTest.java | 6 +- .../tck/AbstractQueuedSynchronizerTest.java | 6 +- .../java/util/concurrent/tck/Atomic8Test.java | 8 +- .../tck/AtomicReferenceArrayTest.java | 8 +- .../concurrent/tck/CompletableFutureTest.java | 16 ++-- .../concurrent/tck/ConcurrentHashMapTest.java | 2 +- .../tck/ConcurrentLinkedDequeTest.java | 2 +- .../tck/ConcurrentLinkedQueueTest.java | 2 +- .../tck/CopyOnWriteArrayListTest.java | 6 +- .../tck/CopyOnWriteArraySetTest.java | 4 +- .../concurrent/tck/CountedCompleterTest.java | 2 +- .../util/concurrent/tck/DelayQueueTest.java | 30 ++----- .../util/concurrent/tck/ExecutorsTest.java | 2 +- .../util/concurrent/tck/ForkJoinPoolTest.java | 30 +++---- .../util/concurrent/tck/LinkedListTest.java | 2 +- .../tck/LinkedTransferQueueTest.java | 18 ++-- .../java/util/concurrent/tck/PhaserTest.java | 16 ++-- .../concurrent/tck/PriorityQueueTest.java | 2 +- .../concurrent/tck/ReentrantLockTest.java | 60 ++++++------- .../tck/ReentrantReadWriteLockTest.java | 84 ++++++++++--------- .../tck/ScheduledExecutorSubclassTest.java | 28 +++---- .../concurrent/tck/ScheduledExecutorTest.java | 28 +++---- .../tck/SubmissionPublisherTest.java | 37 ++++---- .../concurrent/tck/SynchronousQueueTest.java | 3 +- .../tck/ThreadPoolExecutorSubclassTest.java | 38 ++++----- .../tck/ThreadPoolExecutorTest.java | 34 ++++---- .../java/util/concurrent/tck/TreeSetTest.java | 2 +- .../util/concurrent/tck/TreeSubSetTest.java | 2 +- 98 files changed, 536 insertions(+), 540 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/PriorityQueue.java b/jdk/src/java.base/share/classes/java/util/PriorityQueue.java index db0cfd70913..829eb01efea 100644 --- a/jdk/src/java.base/share/classes/java/util/PriorityQueue.java +++ b/jdk/src/java.base/share/classes/java/util/PriorityQueue.java @@ -734,12 +734,12 @@ public class PriorityQueue extends AbstractQueue @SuppressWarnings("unchecked") private void heapify() { final Object[] es = queue; - final int half = (size >>> 1) - 1; + int i = (size >>> 1) - 1; if (comparator == null) - for (int i = half; i >= 0; i--) + for (; i >= 0; i--) siftDownComparable(i, (E) es[i]); else - for (int i = half; i >= 0; i--) + for (; i >= 0; i--) siftDownUsingComparator(i, (E) es[i]); } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java b/jdk/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java index d2eddf9af3f..6af7c7a98bc 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java @@ -72,9 +72,8 @@ import java.util.function.Predicate; * generally decreases throughput but reduces variability and avoids * starvation. * - *

This class and its iterator implement all of the - * optional methods of the {@link Collection} and {@link - * Iterator} interfaces. + *

This class and its iterator implement all of the optional + * methods of the {@link Collection} and {@link Iterator} interfaces. * *

This class is a member of the * diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java index 45bde4215c5..86be622c78b 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java @@ -72,12 +72,12 @@ import java.util.Spliterator; * asynchronous nature of these sets, determining the current number * of elements requires a traversal of the elements, and so may report * inaccurate results if this collection is modified during traversal. - * Additionally, the bulk operations {@code addAll}, - * {@code removeAll}, {@code retainAll}, {@code containsAll}, - * {@code equals}, and {@code toArray} are not guaranteed - * to be performed atomically. For example, an iterator operating - * concurrently with an {@code addAll} operation might view only some - * of the added elements. + * + *

Bulk operations that add, remove, or examine multiple elements, + * such as {@link #addAll}, {@link #removeIf} or {@link #forEach}, + * are not guaranteed to be performed atomically. + * For example, a {@code forEach} traversal concurrent with an {@code + * addAll} operation might observe only some of the added elements. * *

This class and its iterators implement all of the * optional methods of the {@link Set} and {@link Iterator} diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java index d52a515eb9a..63bd252868d 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java @@ -797,7 +797,7 @@ public class CopyOnWriteArrayList * @throws NullPointerException {@inheritDoc} */ public void forEach(Consumer action) { - if (action == null) throw new NullPointerException(); + Objects.requireNonNull(action); for (Object x : getArray()) { @SuppressWarnings("unchecked") E e = (E) x; action.accept(e); @@ -808,7 +808,7 @@ public class CopyOnWriteArrayList * @throws NullPointerException {@inheritDoc} */ public boolean removeIf(Predicate filter) { - if (filter == null) throw new NullPointerException(); + Objects.requireNonNull(filter); return bulkRemove(filter); } @@ -865,7 +865,7 @@ public class CopyOnWriteArrayList } public void replaceAll(UnaryOperator operator) { - if (operator == null) throw new NullPointerException(); + Objects.requireNonNull(operator); synchronized (lock) { replaceAll(operator, 0, getArray().length); } @@ -1329,7 +1329,7 @@ public class CopyOnWriteArrayList } public void forEach(Consumer action) { - if (action == null) throw new NullPointerException(); + Objects.requireNonNull(action); int i, end; final Object[] es; synchronized (l.lock) { es = getArrayChecked(); @@ -1341,7 +1341,7 @@ public class CopyOnWriteArrayList } public void replaceAll(UnaryOperator operator) { - if (operator == null) throw new NullPointerException(); + Objects.requireNonNull(operator); synchronized (l.lock) { checkForComodification(); l.replaceAll(operator, offset, offset + size); diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/DelayQueue.java b/jdk/src/java.base/share/classes/java/util/concurrent/DelayQueue.java index 03c52ff08a1..50997f7abda 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/DelayQueue.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/DelayQueue.java @@ -41,6 +41,7 @@ import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.PriorityQueue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; @@ -59,11 +60,11 @@ import java.util.concurrent.locks.ReentrantLock; * returns the count of both expired and unexpired elements. * This queue does not permit null elements. * - *

This class and its iterator implement all of the - * optional methods of the {@link Collection} and {@link - * Iterator} interfaces. The Iterator provided in method {@link - * #iterator()} is not guaranteed to traverse the elements of - * the DelayQueue in any particular order. + *

This class and its iterator implement all of the optional + * methods of the {@link Collection} and {@link Iterator} interfaces. + * The Iterator provided in method {@link #iterator()} is not + * guaranteed to traverse the elements of the DelayQueue in any + * particular order. * *

This class is a member of the * @@ -339,8 +340,7 @@ public class DelayQueue extends AbstractQueue * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection c) { - if (c == null) - throw new NullPointerException(); + Objects.requireNonNull(c); if (c == this) throw new IllegalArgumentException(); final ReentrantLock lock = this.lock; @@ -365,8 +365,7 @@ public class DelayQueue extends AbstractQueue * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection c, int maxElements) { - if (c == null) - throw new NullPointerException(); + Objects.requireNonNull(c); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/SynchronousQueue.java b/jdk/src/java.base/share/classes/java/util/concurrent/SynchronousQueue.java index e12d7afecc6..165198f97f8 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/SynchronousQueue.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/SynchronousQueue.java @@ -42,6 +42,7 @@ import java.util.AbstractQueue; import java.util.Collection; import java.util.Collections; import java.util.Iterator; +import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.locks.LockSupport; @@ -75,9 +76,8 @@ import java.util.concurrent.locks.ReentrantLock; * is not guaranteed. However, a queue constructed with fairness set * to {@code true} grants threads access in FIFO order. * - *

This class and its iterator implement all of the - * optional methods of the {@link Collection} and {@link - * Iterator} interfaces. + *

This class and its iterator implement all of the optional + * methods of the {@link Collection} and {@link Iterator} interfaces. * *

This class is a member of the * @@ -1112,15 +1112,12 @@ public class SynchronousQueue extends AbstractQueue * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection c) { - if (c == null) - throw new NullPointerException(); + Objects.requireNonNull(c); if (c == this) throw new IllegalArgumentException(); int n = 0; - for (E e; (e = poll()) != null;) { + for (E e; (e = poll()) != null; n++) c.add(e); - ++n; - } return n; } @@ -1131,15 +1128,12 @@ public class SynchronousQueue extends AbstractQueue * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection c, int maxElements) { - if (c == null) - throw new NullPointerException(); + Objects.requireNonNull(c); if (c == this) throw new IllegalArgumentException(); int n = 0; - for (E e; n < maxElements && (e = poll()) != null;) { + for (E e; n < maxElements && (e = poll()) != null; n++) c.add(e); - ++n; - } return n; } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java b/jdk/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java index e76f2d10597..cfc676aa39a 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java @@ -1059,17 +1059,17 @@ public class ThreadLocalRandom extends Random { static { try { SEED = U.objectFieldOffset - (Thread.class.getDeclaredField("threadLocalRandomSeed")); + (Thread.class.getDeclaredField("threadLocalRandomSeed")); PROBE = U.objectFieldOffset - (Thread.class.getDeclaredField("threadLocalRandomProbe")); + (Thread.class.getDeclaredField("threadLocalRandomProbe")); SECONDARY = U.objectFieldOffset - (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); + (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); THREADLOCALS = U.objectFieldOffset - (Thread.class.getDeclaredField("threadLocals")); + (Thread.class.getDeclaredField("threadLocals")); INHERITABLETHREADLOCALS = U.objectFieldOffset - (Thread.class.getDeclaredField("inheritableThreadLocals")); + (Thread.class.getDeclaredField("inheritableThreadLocals")); INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset - (Thread.class.getDeclaredField("inheritedAccessControlContext")); + (Thread.class.getDeclaredField("inheritedAccessControlContext")); } catch (ReflectiveOperationException e) { throw new Error(e); } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/locks/LockSupport.java b/jdk/src/java.base/share/classes/java/util/concurrent/locks/LockSupport.java index b1e40a338b9..7bf6e8a54cd 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/locks/LockSupport.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/locks/LockSupport.java @@ -425,11 +425,11 @@ public class LockSupport { static { try { PARKBLOCKER = U.objectFieldOffset - (Thread.class.getDeclaredField("parkBlocker")); + (Thread.class.getDeclaredField("parkBlocker")); SECONDARY = U.objectFieldOffset - (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); + (Thread.class.getDeclaredField("threadLocalRandomSecondarySeed")); TID = U.objectFieldOffset - (Thread.class.getDeclaredField("tid")); + (Thread.class.getDeclaredField("tid")); } catch (ReflectiveOperationException e) { throw new Error(e); diff --git a/jdk/test/java/util/AbstractList/CheckForComodification.java b/jdk/test/java/util/AbstractList/CheckForComodification.java index 06578d8aa82..9769ec3a91d 100644 --- a/jdk/test/java/util/AbstractList/CheckForComodification.java +++ b/jdk/test/java/util/AbstractList/CheckForComodification.java @@ -35,7 +35,7 @@ import java.util.*; public class CheckForComodification { private static final int LENGTH = 10; public static void main(String[] args) throws Exception { - List list = new ArrayList(); + List list = new ArrayList<>(); for (int i = 0; i < LENGTH; i++) list.add(i); try { diff --git a/jdk/test/java/util/ArrayList/Bug6533203.java b/jdk/test/java/util/ArrayList/Bug6533203.java index d4f56f55586..8c85c5bfe17 100644 --- a/jdk/test/java/util/ArrayList/Bug6533203.java +++ b/jdk/test/java/util/ArrayList/Bug6533203.java @@ -32,7 +32,7 @@ import java.util.*; @SuppressWarnings({"serial","unchecked"}) public class Bug6533203 { void test(String[] args) throws Throwable { - final List superstitious = new ArrayList() { + final List superstitious = new ArrayList<>() { public void add(int index, Integer i) { if (i == 13) throw new Error("unlucky"); else super.add(index, i); }}; diff --git a/jdk/test/java/util/ArrayList/IteratorMicroBenchmark.java b/jdk/test/java/util/ArrayList/IteratorMicroBenchmark.java index 03d0e3da204..11c617d4ac4 100644 --- a/jdk/test/java/util/ArrayList/IteratorMicroBenchmark.java +++ b/jdk/test/java/util/ArrayList/IteratorMicroBenchmark.java @@ -209,8 +209,8 @@ public class IteratorMicroBenchmark { // iterations, size, warmupSeconds, filter); final ConcurrentSkipListMap m - = new ConcurrentSkipListMap(); - final ArrayList al = new ArrayList(size); + = new ConcurrentSkipListMap<>(); + final ArrayList al = new ArrayList<>(size); // Populate collections with random data final ThreadLocalRandom rnd = ThreadLocalRandom.current(); @@ -218,16 +218,16 @@ public class IteratorMicroBenchmark { m.put(rnd.nextInt(size), rnd.nextInt(size)); al.add(rnd.nextInt(size)); } - final Vector v = new Vector(al); - final ArrayDeque ad = new ArrayDeque(al); + final Vector v = new Vector<>(al); + final ArrayDeque ad = new ArrayDeque<>(al); // shuffle ArrayDeque elements so they wrap for (int i = 0, n = rnd.nextInt(size); i < n; i++) ad.addLast(ad.removeFirst()); // Also test "short" collections final int shortSize = 5; - final Vector sv = new Vector(v.subList(0, shortSize)); - final ArrayList sal = new ArrayList(sv); + final Vector sv = new Vector<>(v.subList(0, shortSize)); + final ArrayList sal = new ArrayList<>(sv); // Checks for correctness *and* prevents loop optimizations class Check { @@ -613,8 +613,7 @@ public class IteratorMicroBenchmark { public void work() throws Throwable { for (int i = 0; i < iterations; i++) { int sum = 0; - List> its - = new ArrayList>(2); + List> its = new ArrayList<>(2); its.add(v.iterator()); its.add(al.iterator()); for (int k = 0; its.get(k).hasNext(); k = (k == 0) ? 1 : 0) diff --git a/jdk/test/java/util/ArrayList/RangeCheckMicroBenchmark.java b/jdk/test/java/util/ArrayList/RangeCheckMicroBenchmark.java index 7e9d959457f..eeaecb8716f 100644 --- a/jdk/test/java/util/ArrayList/RangeCheckMicroBenchmark.java +++ b/jdk/test/java/util/ArrayList/RangeCheckMicroBenchmark.java @@ -159,7 +159,7 @@ public class RangeCheckMicroBenchmark { final int size = intArg(args, "size", 1000); final Pattern filter = patternArg(args, "filter"); - final ArrayList list = new ArrayList(); + final ArrayList list = new ArrayList<>(); final Random rnd = new Random(); for (int i = 0; i < size; i++) list.add(rnd.nextInt()); diff --git a/jdk/test/java/util/Collection/IteratorMicroBenchmark.java b/jdk/test/java/util/Collection/IteratorMicroBenchmark.java index 263da155710..e0d98210e5d 100644 --- a/jdk/test/java/util/Collection/IteratorMicroBenchmark.java +++ b/jdk/test/java/util/Collection/IteratorMicroBenchmark.java @@ -255,7 +255,7 @@ public class IteratorMicroBenchmark { // "iterations=%d size=%d, warmup=%1g, filter=\"%s\"%n", // iterations, size, warmupSeconds, filter); - final ArrayList al = new ArrayList(size); + final ArrayList al = new ArrayList<>(size); // Populate collections with random data final ThreadLocalRandom rnd = ThreadLocalRandom.current(); @@ -307,14 +307,14 @@ public class IteratorMicroBenchmark { for (Integer n : x) sum += n; check.sum(sum);}}}, - new Job(klazz + " .iterator().forEachRemaining()") { + new Job(klazz + " iterator().forEachRemaining()") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { sum[0] = 0; x.iterator().forEachRemaining(n -> sum[0] += n); check.sum(sum[0]);}}}, - new Job(klazz + " .spliterator().tryAdvance()") { + new Job(klazz + " spliterator().tryAdvance()") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { @@ -322,28 +322,49 @@ public class IteratorMicroBenchmark { Spliterator spliterator = x.spliterator(); do {} while (spliterator.tryAdvance(n -> sum[0] += n)); check.sum(sum[0]);}}}, - new Job(klazz + " .spliterator().forEachRemaining()") { + new Job(klazz + " spliterator().forEachRemaining()") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { sum[0] = 0; x.spliterator().forEachRemaining(n -> sum[0] += n); check.sum(sum[0]);}}}, - new Job(klazz + " .removeIf") { + new Job(klazz + " removeIf") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { sum[0] = 0; - x.removeIf(n -> { sum[0] += n; return false; }); + if (x.removeIf(n -> { sum[0] += n; return false; })) + throw new AssertionError(); check.sum(sum[0]);}}}, - new Job(klazz + " .forEach") { + new Job(klazz + " contains") { + public void work() throws Throwable { + int[] sum = new int[1]; + Object y = new Object() { + public boolean equals(Object z) { + sum[0] += (int) z; return false; }}; + for (int i = 0; i < iterations; i++) { + sum[0] = 0; + if (x.contains(y)) throw new AssertionError(); + check.sum(sum[0]);}}}, + new Job(klazz + " remove(Object)") { + public void work() throws Throwable { + int[] sum = new int[1]; + Object y = new Object() { + public boolean equals(Object z) { + sum[0] += (int) z; return false; }}; + for (int i = 0; i < iterations; i++) { + sum[0] = 0; + if (x.remove(y)) throw new AssertionError(); + check.sum(sum[0]);}}}, + new Job(klazz + " forEach") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { sum[0] = 0; x.forEach(n -> sum[0] += n); check.sum(sum[0]);}}}, - new Job(klazz + " .toArray()") { + new Job(klazz + " toArray()") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { @@ -351,7 +372,7 @@ public class IteratorMicroBenchmark { for (Object o : x.toArray()) sum[0] += (Integer) o; check.sum(sum[0]);}}}, - new Job(klazz + " .toArray(a)") { + new Job(klazz + " toArray(a)") { public void work() throws Throwable { Integer[] a = new Integer[x.size()]; int[] sum = new int[1]; @@ -361,7 +382,7 @@ public class IteratorMicroBenchmark { for (Object o : a) sum[0] += (Integer) o; check.sum(sum[0]);}}}, - new Job(klazz + " .toArray(empty)") { + new Job(klazz + " toArray(empty)") { public void work() throws Throwable { Integer[] empty = new Integer[0]; int[] sum = new int[1]; @@ -370,12 +391,12 @@ public class IteratorMicroBenchmark { for (Integer o : x.toArray(empty)) sum[0] += o; check.sum(sum[0]);}}}, - new Job(klazz + " .stream().collect") { + new Job(klazz + " stream().collect") { public void work() throws Throwable { for (int i = 0; i < iterations; i++) { check.sum(x.stream() .collect(summingInt(e -> e)));}}}, - new Job(klazz + " .parallelStream().collect") { + new Job(klazz + " parallelStream().collect") { public void work() throws Throwable { for (int i = 0; i < iterations; i++) { check.sum(x.parallelStream() @@ -385,7 +406,7 @@ public class IteratorMicroBenchmark { List dequeJobs(Deque x) { String klazz = x.getClass().getSimpleName(); return List.of( - new Job(klazz + " .descendingIterator() loop") { + new Job(klazz + " descendingIterator() loop") { public void work() throws Throwable { for (int i = 0; i < iterations; i++) { int sum = 0; @@ -393,7 +414,7 @@ public class IteratorMicroBenchmark { while (it.hasNext()) sum += it.next(); check.sum(sum);}}}, - new Job(klazz + " .descendingIterator().forEachRemaining()") { + new Job(klazz + " descendingIterator().forEachRemaining()") { public void work() throws Throwable { int[] sum = new int[1]; for (int i = 0; i < iterations; i++) { diff --git a/jdk/test/java/util/Collection/MOAT.java b/jdk/test/java/util/Collection/MOAT.java index b007f69159e..2f89b2ddd1d 100644 --- a/jdk/test/java/util/Collection/MOAT.java +++ b/jdk/test/java/util/Collection/MOAT.java @@ -678,7 +678,7 @@ public class MOAT { private static void testQueueAddRemove(final Queue q, final Integer e) { - final List originalContents = new ArrayList(q); + final List originalContents = new ArrayList<>(q); final boolean isEmpty = q.isEmpty(); final boolean isList = (q instanceof List); final List asList = isList ? (List) q : null; @@ -1207,8 +1207,7 @@ public class MOAT { private static void throwsConsistently(Class k, Iterable fs) { - List> threw - = new ArrayList>(); + List> threw = new ArrayList<>(); for (Fun f : fs) try { f.f(); threw.add(null); } catch (Throwable t) { @@ -1224,7 +1223,7 @@ public class MOAT { final ConcurrentMap cm = (m instanceof ConcurrentMap) ? (ConcurrentMap) m : null; - List fs = new ArrayList(); + List fs = new ArrayList<>(); fs.add(() -> check(! m.containsKey(null))); fs.add(() -> equal(m.remove(null), null)); fs.add(() -> equal(m.get(null), null)); diff --git a/jdk/test/java/util/Collections/BigBinarySearch.java b/jdk/test/java/util/Collections/BigBinarySearch.java index 24385e49368..d08dad2aa85 100644 --- a/jdk/test/java/util/Collections/BigBinarySearch.java +++ b/jdk/test/java/util/Collections/BigBinarySearch.java @@ -38,7 +38,7 @@ public class BigBinarySearch { extends AbstractList implements RandomAccess { - private Map m = new HashMap(); + private Map m = new HashMap<>(); public Integer get(int i) { if (i < 0) throw new IndexOutOfBoundsException(""+i); diff --git a/jdk/test/java/util/Collections/Disjoint.java b/jdk/test/java/util/Collections/Disjoint.java index fcf93b2c203..61b763806a7 100644 --- a/jdk/test/java/util/Collections/Disjoint.java +++ b/jdk/test/java/util/Collections/Disjoint.java @@ -42,7 +42,7 @@ public class Disjoint { int x = 0; for (int i = 0; i < N; i++) { int size = rnd.nextInt(10) + 2; - List list = new ArrayList(size); + List list = new ArrayList<>(size); for (int j = 1; j < size; j++) list.add(x++); list.add(x); diff --git a/jdk/test/java/util/Collections/RacingCollections.java b/jdk/test/java/util/Collections/RacingCollections.java index 2948dd92c86..d95503b77f3 100644 --- a/jdk/test/java/util/Collections/RacingCollections.java +++ b/jdk/test/java/util/Collections/RacingCollections.java @@ -184,8 +184,7 @@ public class RacingCollections { } private static List> newConcurrentMaps() { - List> list = - new ArrayList>(); + List> list = new ArrayList<>(); list.add(new ConcurrentHashMap()); list.add(new ConcurrentSkipListMap()); return list; @@ -196,7 +195,7 @@ public class RacingCollections { list.add(new Hashtable()); list.add(new HashMap()); list.add(new TreeMap()); - Comparator cmp = new Comparator() { + Comparator cmp = new Comparator<>() { public int compare(Integer x, Integer y) { return x - y; }}; @@ -205,7 +204,7 @@ public class RacingCollections { } private static List> newConcurrentSets() { - List> list = new ArrayList>(); + List> list = new ArrayList<>(); list.add(new ConcurrentSkipListSet()); list.add(new CopyOnWriteArraySet()); return list; @@ -220,7 +219,7 @@ public class RacingCollections { } private static List> newConcurrentLists() { - List> list = new ArrayList>(); + List> list = new ArrayList<>(); list.add(new CopyOnWriteArrayList()); return list; } @@ -233,8 +232,7 @@ public class RacingCollections { } private static List> newConcurrentQueues() { - List> list = - new ArrayList>(newConcurrentDeques()); + List> list = new ArrayList<>(newConcurrentDeques()); list.add(new ArrayBlockingQueue(10)); list.add(new LinkedBlockingQueue(10)); list.add(new LinkedTransferQueue()); @@ -243,14 +241,13 @@ public class RacingCollections { } private static List> newQueues() { - List> list = - new ArrayList>(newDeques()); + List> list = new ArrayList<>(newDeques()); list.add(new LinkedBlockingQueue(10)); return list; } private static List> newConcurrentDeques() { - List> list = new ArrayList>(); + List> list = new ArrayList<>(); list.add(new LinkedBlockingDeque(10)); list.add(new ConcurrentLinkedDeque()); return list; diff --git a/jdk/test/java/util/Collections/ReverseOrder2.java b/jdk/test/java/util/Collections/ReverseOrder2.java index 8dde0027531..5b4238c2e08 100644 --- a/jdk/test/java/util/Collections/ReverseOrder2.java +++ b/jdk/test/java/util/Collections/ReverseOrder2.java @@ -67,7 +67,7 @@ public class ReverseOrder2 { equal(list, golden); } - private static Comparator cmp = new Comparator () { + private static Comparator cmp = new Comparator<>() { public int compare(String s1, String s2) { int i1 = Integer.parseInt(s1); int i2 = Integer.parseInt(s2); @@ -75,7 +75,7 @@ public class ReverseOrder2 { } }; - private static final List golden = new ArrayList(N); + private static final List golden = new ArrayList<>(N); static { for (int i = N-1; i >= 0; i--) golden.add(String.valueOf(i)); @@ -89,7 +89,7 @@ public class ReverseOrder2 { equal(list, golden2); } - private static final List golden2 = new ArrayList(N); + private static final List golden2 = new ArrayList<>(N); static { for (int i = N-1; i >= 0; i--) golden2.add(i); diff --git a/jdk/test/java/util/Collections/SetFromMap.java b/jdk/test/java/util/Collections/SetFromMap.java index b4aff35e887..c869c3af2f4 100644 --- a/jdk/test/java/util/Collections/SetFromMap.java +++ b/jdk/test/java/util/Collections/SetFromMap.java @@ -49,7 +49,7 @@ public class SetFromMap { private static void realMain() throws Throwable { try { - Map m = new IdentityHashMap(); + Map m = new IdentityHashMap<>(); Set s = Collections.newSetFromMap(m); String foo1 = new String("foo"); String foo2 = new String("foo"); diff --git a/jdk/test/java/util/Deque/ChorusLine.java b/jdk/test/java/util/Deque/ChorusLine.java index 9f0d6f89aa5..328ad3ec5fc 100644 --- a/jdk/test/java/util/Deque/ChorusLine.java +++ b/jdk/test/java/util/Deque/ChorusLine.java @@ -131,7 +131,7 @@ public class ChorusLine { }}}; private static void realMain(String[] args) throws Throwable { - Collection> deqs = new ArrayDeque>(3); + Collection> deqs = new ArrayDeque<>(3); deqs.add(new ArrayDeque()); deqs.add(new LinkedList()); deqs.add(new LinkedBlockingDeque()); @@ -157,12 +157,12 @@ public class ChorusLine { prev = deq; } - Deque> its = new ArrayDeque>(); + Deque> its = new ArrayDeque<>(); for (Deque deq : deqs) its.addLast(deq.iterator()); equal(its); - Deque> dits = new ArrayDeque>(); + Deque> dits = new ArrayDeque<>(); for (Deque deq : deqs) dits.addLast(deq.descendingIterator()); equal(dits); diff --git a/jdk/test/java/util/IdentityHashMap/ToArray.java b/jdk/test/java/util/IdentityHashMap/ToArray.java index db764c9e41a..84cb1a82dd5 100644 --- a/jdk/test/java/util/IdentityHashMap/ToArray.java +++ b/jdk/test/java/util/IdentityHashMap/ToArray.java @@ -36,11 +36,10 @@ public class ToArray { // new ArrayList(IdentityHashMap.entrySet()) // used to return bogus entries. //---------------------------------------------------------------- - Map mm = new IdentityHashMap(); + Map mm = new IdentityHashMap<>(); mm.put("foo", "bar"); mm.put("baz", "quux"); - List> lm - = new ArrayList>(mm.entrySet()); + List> lm = new ArrayList<>(mm.entrySet()); String s = lm.toString(); if (! (s.equals("[foo=bar, baz=quux]") || s.equals("[baz=quux, foo=bar]"))) @@ -65,8 +64,7 @@ public class ToArray { // IdentityHashMap.entrySet().toArray(T[] a) used to simply // return toArray() ! //---------------------------------------------------------------- - IdentityHashMap map - = new IdentityHashMap(); + IdentityHashMap map = new IdentityHashMap<>(); Set> es = map.entrySet(); if (es.toArray().length != 0) throw new Error("non-empty"); diff --git a/jdk/test/java/util/IdentityHashMap/ToString.java b/jdk/test/java/util/IdentityHashMap/ToString.java index f7e34b19cb6..706dd8d6e8d 100644 --- a/jdk/test/java/util/IdentityHashMap/ToString.java +++ b/jdk/test/java/util/IdentityHashMap/ToString.java @@ -32,7 +32,7 @@ import java.util.*; public class ToString { public static void main(String[] args) { - Map m = new IdentityHashMap(); + Map m = new IdentityHashMap<>(); Set> es = m.entrySet(); m.put("beer", "good"); Iterator> i = es.iterator(); diff --git a/jdk/test/java/util/NavigableMap/LockStep.java b/jdk/test/java/util/NavigableMap/LockStep.java index 957d5ee3231..3bf1ec2a2ea 100644 --- a/jdk/test/java/util/NavigableMap/LockStep.java +++ b/jdk/test/java/util/NavigableMap/LockStep.java @@ -753,7 +753,7 @@ public class LockStep { List maps = Arrays.asList(m1, m2); for (NavigableMap m : maps) testEmptyMap(m); - final Set ints = new HashSet(); + final Set ints = new HashSet<>(); while (ints.size() < size) ints.add(rnd.nextInt(1024)); final Integer[] elts = ints.toArray(new Integer[size]); @@ -795,7 +795,7 @@ public class LockStep { List sets = Arrays.asList(s1, s2); for (NavigableSet s : sets) testEmptySet(s); - final Set ints = new HashSet(); + final Set ints = new HashSet<>(); while (ints.size() < size) ints.add(rnd.nextInt(1024)); final Integer[] elts = ints.toArray(new Integer[size]); diff --git a/jdk/test/java/util/PriorityQueue/ForgetMeNot.java b/jdk/test/java/util/PriorityQueue/ForgetMeNot.java index 6f9f65d529e..0a6be86cf53 100644 --- a/jdk/test/java/util/PriorityQueue/ForgetMeNot.java +++ b/jdk/test/java/util/PriorityQueue/ForgetMeNot.java @@ -61,7 +61,7 @@ public class ForgetMeNot { } private static void realMain(String[] args) throws Throwable { - final PriorityQueue q = new PriorityQueue(); + final PriorityQueue q = new PriorityQueue<>(); Iterator it; //---------------------------------------------------------------- diff --git a/jdk/test/java/util/PriorityQueue/NoNulls.java b/jdk/test/java/util/PriorityQueue/NoNulls.java index f2e147a34b6..ffbe4f2a607 100644 --- a/jdk/test/java/util/PriorityQueue/NoNulls.java +++ b/jdk/test/java/util/PriorityQueue/NoNulls.java @@ -51,7 +51,7 @@ import java.util.concurrent.PriorityBlockingQueue; public class NoNulls { void test(String[] args) throws Throwable { final Comparator nullTolerantComparator - = new Comparator() { + = new Comparator<>() { public int compare(String x, String y) { return (x == null ? -1 : y == null ? 1 : @@ -63,7 +63,7 @@ public class NoNulls { nullSortedSet.add(null); final PriorityQueue nullPriorityQueue - = new PriorityQueue() { + = new PriorityQueue<>() { public Object[] toArray() { return new Object[] { null };}}; final Collection nullCollection = new ArrayList<>(); diff --git a/jdk/test/java/util/PriorityQueue/PriorityQueueSort.java b/jdk/test/java/util/PriorityQueue/PriorityQueueSort.java index 24229639163..3500b88cca0 100644 --- a/jdk/test/java/util/PriorityQueue/PriorityQueueSort.java +++ b/jdk/test/java/util/PriorityQueue/PriorityQueueSort.java @@ -62,31 +62,31 @@ public class PriorityQueueSort { if (args.length > 0) n = Integer.parseInt(args[0]); - List sorted = new ArrayList(n); + List sorted = new ArrayList<>(n); for (int i = 0; i < n; i++) sorted.add(new Integer(i)); - List shuffled = new ArrayList(sorted); + List shuffled = new ArrayList<>(sorted); Collections.shuffle(shuffled); - Queue pq = new PriorityQueue(n, new MyComparator()); + Queue pq = new PriorityQueue<>(n, new MyComparator()); for (Iterator i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next()); - List recons = new ArrayList(); + List recons = new ArrayList<>(); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); recons.clear(); - pq = new PriorityQueue(shuffled); + pq = new PriorityQueue<>(shuffled); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); // Remove all odd elements from queue - pq = new PriorityQueue(shuffled); + pq = new PriorityQueue<>(shuffled); for (Iterator i = pq.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); diff --git a/jdk/test/java/util/PriorityQueue/RemoveContains.java b/jdk/test/java/util/PriorityQueue/RemoveContains.java index 809478221dd..eca8b89b033 100644 --- a/jdk/test/java/util/PriorityQueue/RemoveContains.java +++ b/jdk/test/java/util/PriorityQueue/RemoveContains.java @@ -69,7 +69,7 @@ public class RemoveContains { } public static void main(String[] args) { - final Comparator firstChar = new Comparator() { + final Comparator firstChar = new Comparator<>() { public int compare(String x, String y) { return x.charAt(0) - y.charAt(0); }}; diff --git a/jdk/test/java/util/Random/DistinctSeeds.java b/jdk/test/java/util/Random/DistinctSeeds.java index ddd541b3c60..2f6e7f8fbe8 100644 --- a/jdk/test/java/util/Random/DistinctSeeds.java +++ b/jdk/test/java/util/Random/DistinctSeeds.java @@ -61,7 +61,7 @@ public class DistinctSeeds { } final int threadCount = 2; List collectors = new ArrayList<>(); - List threads = new ArrayList(); + List threads = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { RandomCollector r = new RandomCollector(); collectors.add(r); @@ -72,7 +72,7 @@ public class DistinctSeeds { for (Thread thread : threads) thread.join(); int collisions = 0; - HashSet s = new HashSet(); + HashSet s = new HashSet<>(); for (RandomCollector r : collectors) { for (long x : r.randoms) { if (s.contains(x)) diff --git a/jdk/test/java/util/TreeMap/NullAtEnd.java b/jdk/test/java/util/TreeMap/NullAtEnd.java index b4eac749682..6c1f8d1502e 100644 --- a/jdk/test/java/util/TreeMap/NullAtEnd.java +++ b/jdk/test/java/util/TreeMap/NullAtEnd.java @@ -64,7 +64,7 @@ public class NullAtEnd { } private static final Comparator NULL_AT_END - = new Comparator() { + = new Comparator<>() { /** * Allows for nulls. Null is greater than anything non-null. */ @@ -78,14 +78,13 @@ public class NullAtEnd { public static void main(String[] args) { try { - SortedMap m1 - = new TreeMap(NULL_AT_END); + SortedMap m1 = new TreeMap<>(NULL_AT_END); check(eq(m1.put("a", "a"), null)); check(eq(m1.put("b", "b"), null)); check(eq(m1.put("c", "c"), null)); check(eq(m1.put(null, "d"), null)); - SortedMap m2 = new TreeMap(m1); + SortedMap m2 = new TreeMap<>(m1); check(eq(m1.lastKey(), null)); check(eq(m1.get(m1.lastKey()), "d")); diff --git a/jdk/test/java/util/Vector/CopyInto.java b/jdk/test/java/util/Vector/CopyInto.java index 66197eb85ae..efcadee2fce 100644 --- a/jdk/test/java/util/Vector/CopyInto.java +++ b/jdk/test/java/util/Vector/CopyInto.java @@ -36,7 +36,7 @@ import java.util.concurrent.atomic.*; public class CopyInto { private static void realMain(String[] args) throws Throwable { try { - Vector v = new Vector(); + Vector v = new Vector<>(); v.add("foo"); v.copyInto(new Integer[3]); fail("Expected ArrayStoreException"); diff --git a/jdk/test/java/util/concurrent/ArrayBlockingQueue/IteratorConsistency.java b/jdk/test/java/util/concurrent/ArrayBlockingQueue/IteratorConsistency.java index d7abe4dfb1f..0068e3804e3 100644 --- a/jdk/test/java/util/concurrent/ArrayBlockingQueue/IteratorConsistency.java +++ b/jdk/test/java/util/concurrent/ArrayBlockingQueue/IteratorConsistency.java @@ -86,26 +86,24 @@ public class IteratorConsistency { } Object itrs(ArrayBlockingQueue q) { - try { - return itrsField.get(q); - } catch (Throwable t) { throw new Error(); } + try { return itrsField.get(q); } + catch (Throwable ex) { throw new AssertionError(ex); } } int takeIndex(ArrayBlockingQueue q) { - try { - return takeIndexField.getInt(q); - } catch (Throwable t) { throw new Error(); } + try { return takeIndexField.getInt(q); } + catch (Throwable ex) { throw new AssertionError(ex); } } List trackedIterators(Object itrs) { try { - List its = new ArrayList(); + List its = new ArrayList<>(); if (itrs != null) for (Object p = headField.get(itrs); p != null; p = nextField.get(p)) its.add(((WeakReference)(p)).get()); Collections.reverse(its); return its; - } catch (Throwable t) { throw new Error(); } + } catch (Throwable ex) { throw new AssertionError(ex); } } List trackedIterators(ArrayBlockingQueue q) { @@ -114,7 +112,7 @@ public class IteratorConsistency { List attachedIterators(Object itrs) { try { - List its = new ArrayList(); + List its = new ArrayList<>(); if (itrs != null) for (Object p = headField.get(itrs); p != null; p = nextField.get(p)) { Iterator it = ((WeakReference)(p)).get(); @@ -123,7 +121,7 @@ public class IteratorConsistency { } Collections.reverse(its); return its; - } catch (Throwable t) { unexpected(t); return null; } + } catch (Throwable ex) { unexpected(ex); return null; } } List attachedIterators(ArrayBlockingQueue q) { @@ -131,9 +129,8 @@ public class IteratorConsistency { } Object[] internalArray(ArrayBlockingQueue q) { - try { - return (Object[]) itemsField.get(q); - } catch (Throwable t) { throw new Error(t); } + try { return (Object[]) itemsField.get(q); } + catch (Throwable ex) { throw new AssertionError(ex); } } void printInternalArray(ArrayBlockingQueue q) { @@ -242,7 +239,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) check(q.add(i)); check(itrs(q) == null); @@ -268,7 +265,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); check(itrs(q) == null); @@ -295,7 +292,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); check(itrs(q) == null); @@ -366,7 +363,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); for (int i = 0; i < capacity; i++) { @@ -404,7 +401,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); // Move takeIndex to middle for (int i = 0; i < capacity/2; i++) { check(q.add(i)); @@ -444,7 +441,7 @@ public class IteratorConsistency { } equal(attachedIterators(q), its); break; - default: throw new Error(); + default: throw new AssertionError(); } for (int i = 0; i < capacity; i++) { @@ -478,7 +475,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); for (int i = 0; i < capacity; i++) { @@ -501,8 +498,8 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); - List retained = new ArrayList(); + List its = new ArrayList<>(); + List retained = new ArrayList<>(); final int size = 1 + rnd.nextInt(capacity); for (int i = 0; i < size; i++) q.add(i); @@ -537,7 +534,7 @@ public class IteratorConsistency { // Expect around 8 sweeps per PROBE_HOP final int SWEEPS_PER_PROBE_HOP = 8; ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); for (int i = 0; i < PROBE_HOP_COUNT * PROBE_HOP; i++) { @@ -568,7 +565,7 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - List its = new ArrayList(); + List its = new ArrayList<>(); for (int i = 0; i < capacity/2; i++) { q.add(i); q.remove(); @@ -621,7 +618,7 @@ public class IteratorConsistency { check(!q.contains(i)); equal(q.size(), size - 1); break; - default: throw new Error(); + default: throw new AssertionError(); } checkRemoveThrowsISE(it); check(isDetached(it)); @@ -638,11 +635,9 @@ public class IteratorConsistency { //---------------------------------------------------------------- try { ArrayBlockingQueue q = new ArrayBlockingQueue(capacity, fair); - Queue its0 - = new ArrayDeque(); - Queue itsMid - = new ArrayDeque(); - List its = new ArrayList(); + Queue its0 = new ArrayDeque<>(); + Queue itsMid = new ArrayDeque<>(); + List its = new ArrayList<>(); for (int i = 0; i < capacity; i++) q.add(i); for (int i = 0; i < 2 * capacity + 1; i++) { diff --git a/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java b/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java index db72bfc44d2..ae5548c9fb9 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java @@ -42,7 +42,6 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.ArrayList; import java.util.List; -import java.util.SplittableRandom; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; @@ -55,6 +54,7 @@ import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import jdk.testlibrary.Utils; @@ -89,7 +89,6 @@ public class CancelledProducerConsumerLoops { final CountDownLatch consumersInterrupted; final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); final CyclicBarrier barrier; - final SplittableRandom rnd = new SplittableRandom(); volatile boolean done = false; CancelledProducerConsumerLoops(int npairs, BlockingQueue queue) { @@ -109,7 +108,7 @@ public class CancelledProducerConsumerLoops { cons[i] = pool.submit(new Consumer()); } barrier.await(); - Thread.sleep(rnd.nextInt(5)); + Thread.sleep(ThreadLocalRandom.current().nextInt(5)); for (int i = 1; i < npairs; i++) { if (!prods[i].cancel(true) || diff --git a/jdk/test/java/util/concurrent/BlockingQueue/DrainToFails.java b/jdk/test/java/util/concurrent/BlockingQueue/DrainToFails.java index 8654f4c6ae1..d011daac4f4 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/DrainToFails.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/DrainToFails.java @@ -148,7 +148,7 @@ public class DrainToFails { System.err.println(q.getClass().getSimpleName()); for (int i = 0; i < CAPACITY; i++) q.add(i); - List putters = new ArrayList(); + List putters = new ArrayList<>(); for (int i = 0; i < 4; i++) { Thread putter = new Thread(putter(q, 42 + i)); putters.add(putter); diff --git a/jdk/test/java/util/concurrent/BlockingQueue/Interrupt.java b/jdk/test/java/util/concurrent/BlockingQueue/Interrupt.java index 9677ea5d2e6..ddeeb0ed774 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/Interrupt.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/Interrupt.java @@ -82,7 +82,7 @@ public class Interrupt { (q instanceof BlockingDeque) ? (BlockingDeque) q : null; q.clear(); - List fs = new ArrayList(); + List fs = new ArrayList<>(); fs.add(() -> q.take()); fs.add(() -> q.poll(LONG_DELAY_MS, MILLISECONDS)); if (deq != null) { diff --git a/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java b/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java index 22d080d215f..02bbfeab188 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java @@ -105,13 +105,13 @@ public class PollMemoryLeak { } ConcurrentHashMap, Collection> classFields - = new ConcurrentHashMap, Collection>(); + = new ConcurrentHashMap<>(); Collection referenceFieldsOf(Class k) { Collection fields = classFields.get(k); if (fields == null) { fields = new ArrayDeque(); - ArrayDeque allFields = new ArrayDeque(); + ArrayDeque allFields = new ArrayDeque<>(); for (Class c = k; c != null; c = c.getSuperclass()) for (Field field : c.getDeclaredFields()) if (!Modifier.isStatic(field.getModifiers()) @@ -130,7 +130,7 @@ public class PollMemoryLeak { } Set retainedObjects(Object x) { - ArrayDeque todo = new ArrayDeque() { + ArrayDeque todo = new ArrayDeque<>() { public void push(Object x) { if (x != null) super.push(x); }}; Set uniqueObjects = Collections.newSetFromMap( new IdentityHashMap()); diff --git a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java index 6337436a2cd..4d8f007f29f 100644 --- a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java +++ b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java @@ -51,7 +51,7 @@ import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.SplittableRandom; +import java.util.concurrent.ThreadLocalRandom; public class MapCheck { @@ -612,7 +612,7 @@ public class MapCheck { } static void shuffle(Object[] keys) { - SplittableRandom rnd = new SplittableRandom(); + ThreadLocalRandom rnd = ThreadLocalRandom.current(); int size = keys.length; for (int i=size; i>1; i--) { int r = rnd.nextInt(i); diff --git a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java index 6ce67ccf8ff..9ac21a75dd3 100644 --- a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java +++ b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java @@ -68,8 +68,7 @@ public class MapLoops { static final ExecutorService pool = Executors.newCachedThreadPool(); - static final List throwables - = new CopyOnWriteArrayList(); + static final List throwables = new CopyOnWriteArrayList<>(); public static void main(String[] args) throws Exception { diff --git a/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java b/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java index b3c77e09854..30a283f8a03 100644 --- a/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java +++ b/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java @@ -101,13 +101,13 @@ public class RemoveLeak { } ConcurrentHashMap, Collection> classFields - = new ConcurrentHashMap, Collection>(); + = new ConcurrentHashMap<>(); Collection referenceFieldsOf(Class k) { Collection fields = classFields.get(k); if (fields == null) { fields = new ArrayDeque(); - ArrayDeque allFields = new ArrayDeque(); + ArrayDeque allFields = new ArrayDeque<>(); for (Class c = k; c != null; c = c.getSuperclass()) for (Field field : c.getDeclaredFields()) if (!Modifier.isStatic(field.getModifiers()) @@ -126,7 +126,7 @@ public class RemoveLeak { } Set retainedObjects(Object x) { - ArrayDeque todo = new ArrayDeque() { + ArrayDeque todo = new ArrayDeque<>() { public void push(Object x) { if (x != null) super.push(x); }}; Set uniqueObjects = Collections.newSetFromMap( new IdentityHashMap()); diff --git a/jdk/test/java/util/concurrent/ConcurrentMap/ConcurrentRemoveIf.java b/jdk/test/java/util/concurrent/ConcurrentMap/ConcurrentRemoveIf.java index e7eed159abb..8fe7046061a 100644 --- a/jdk/test/java/util/concurrent/ConcurrentMap/ConcurrentRemoveIf.java +++ b/jdk/test/java/util/concurrent/ConcurrentMap/ConcurrentRemoveIf.java @@ -28,7 +28,7 @@ * @summary Test removeIf on views of concurrent maps */ -import org.testng.Assert; +import static org.testng.Assert.assertEquals; import org.testng.annotations.AfterClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -54,8 +54,8 @@ public class ConcurrentRemoveIf { static final int SIZE = 1000; static final int HALF_SIZE = SIZE / 2; - @DataProvider(name = "String,Supplier,Runnable") - public static Object[][] spliteratorDataProvider() { + @DataProvider() + public static Object[][] concurrentMapViewRemoveIfActions() { List rows = new ArrayList<>(); // ConcurrentMap classes to test @@ -95,24 +95,17 @@ public class ConcurrentRemoveIf { dm.values().removeIf(v -> v == 0); }); - for (Map.Entry>> mapSupplier : maps.entrySet()) { - Supplier> sm = mapSupplier.getValue(); - for (Map.Entry>> action : actions.entrySet()) { - rows.add(new Object[]{ - mapSupplier.getKey() + action.getKey(), - sm, - action.getValue()}); - } + maps.forEach((mapDescription, sm) -> { + actions.forEach((actionDescription, action) -> { + rows.add(new Object[] {mapDescription + actionDescription, sm, action}); + }); if (sm.get() instanceof ConcurrentNavigableMap) { - for (Map.Entry>> action : navActions.entrySet()) { - rows.add(new Object[]{ - mapSupplier.getKey() + action.getKey(), - sm, - action.getValue()}); - } + navActions.forEach((actionDescription, action) -> { + rows.add(new Object[] {mapDescription + actionDescription, sm, action}); + }); } - } + }); return rows.toArray(new Object[0][]); } @@ -124,7 +117,7 @@ public class ConcurrentRemoveIf { executorService.shutdown(); } - @Test(dataProvider = "String,Supplier,Runnable") + @Test(dataProvider = "concurrentMapViewRemoveIfActions") public void testMap(String desc, Supplier> ms, Consumer> action) throws InterruptedException { for (int i = 0; i < K; i++) { @@ -140,7 +133,7 @@ public class ConcurrentRemoveIf { // To start working simultaneously CyclicBarrier threadStarted = new CyclicBarrier(2); - // This task put 1's into map + // This task puts 1's into map CompletableFuture putter = CompletableFuture.runAsync( awaitOn(threadStarted, () -> fillMap(map, 1)), executorService); @@ -153,7 +146,8 @@ public class ConcurrentRemoveIf { // Wait for both tasks to complete CompletableFuture.allOf(putter, remover).join(); - Assert.assertEquals(map.size(), SIZE, "Map size incorrect"); + assertEquals(map.size(), SIZE, "Map size incorrect"); + map.forEach((k, v) -> assertEquals(v, (Integer)1)); } static void fillMap(ConcurrentMap map, int value) { diff --git a/jdk/test/java/util/concurrent/ConcurrentQueues/ConcurrentQueueLoops.java b/jdk/test/java/util/concurrent/ConcurrentQueues/ConcurrentQueueLoops.java index 8ecc8f84f5e..3c8d72e4bb5 100644 --- a/jdk/test/java/util/concurrent/ConcurrentQueues/ConcurrentQueueLoops.java +++ b/jdk/test/java/util/concurrent/ConcurrentQueues/ConcurrentQueueLoops.java @@ -73,7 +73,7 @@ public class ConcurrentQueueLoops { int items = 1024 * 1024; Collection> concurrentQueues() { - List> queues = new ArrayList>(); + List> queues = new ArrayList<>(); queues.add(new ConcurrentLinkedDeque()); queues.add(new ConcurrentLinkedQueue()); queues.add(new ArrayBlockingQueue(items, false)); @@ -166,7 +166,7 @@ public class ConcurrentQueueLoops { LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); CyclicBarrier barrier = new CyclicBarrier(n + 1, timer); totalItems = new AtomicInteger(n * items); - ArrayList> results = new ArrayList>(n); + ArrayList> results = new ArrayList<>(n); for (int i = 0; i < n; ++i) results.add(pool.submit(new Stage(q, barrier, items))); diff --git a/jdk/test/java/util/concurrent/ConcurrentQueues/GCRetention.java b/jdk/test/java/util/concurrent/ConcurrentQueues/GCRetention.java index 314166b8689..67039a302d8 100644 --- a/jdk/test/java/util/concurrent/ConcurrentQueues/GCRetention.java +++ b/jdk/test/java/util/concurrent/ConcurrentQueues/GCRetention.java @@ -82,10 +82,10 @@ public class GCRetention { throw new AssertionError("failed to do a \"full\" gc"); } - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); Collection> queues() { - List> queues = new ArrayList>(); + List> queues = new ArrayList<>(); queues.add(new ConcurrentLinkedDeque()); queues.add(new ConcurrentLinkedQueue()); queues.add(new ArrayBlockingQueue(count, false)); @@ -107,7 +107,7 @@ public class GCRetention { } void prettyPrintResults() { - List classNames = new ArrayList(results.keySet()); + List classNames = new ArrayList<>(results.keySet()); Collections.sort(classNames); int maxClassNameLength = 0; int maxNanosLength = 0; diff --git a/jdk/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java b/jdk/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java index f1811744d8c..4b7fa6d72cf 100644 --- a/jdk/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java +++ b/jdk/test/java/util/concurrent/ConcurrentQueues/IteratorWeakConsistency.java @@ -195,7 +195,7 @@ public class IteratorWeakConsistency { ((BlockingQueue)q).remainingCapacity() : Integer.MAX_VALUE; final int capacity = Math.min(20, remainingCapacity); - List its = new ArrayList(); + List its = new ArrayList<>(); // Move to "middle" for (int i = 0; i < capacity/2; i++) { check(q.add(i)); @@ -229,7 +229,7 @@ public class IteratorWeakConsistency { it.remove(); } break; - default: throw new Error(); + default: throw new AssertionError(); } for (int i = 0; i < capacity; i++) { diff --git a/jdk/test/java/util/concurrent/ConcurrentQueues/RemovePollRace.java b/jdk/test/java/util/concurrent/ConcurrentQueues/RemovePollRace.java index abcae1d398a..f0a8df78e80 100644 --- a/jdk/test/java/util/concurrent/ConcurrentQueues/RemovePollRace.java +++ b/jdk/test/java/util/concurrent/ConcurrentQueues/RemovePollRace.java @@ -59,10 +59,10 @@ public class RemovePollRace { // Suitable for benchmarking. Overridden by args[0] for testing. int count = 1024 * 1024; - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); Collection> concurrentQueues() { - List> queues = new ArrayList>(); + List> queues = new ArrayList<>(); queues.add(new ConcurrentLinkedDeque()); queues.add(new ConcurrentLinkedQueue()); queues.add(new ArrayBlockingQueue(count, false)); @@ -81,7 +81,7 @@ public class RemovePollRace { } void prettyPrintResults() { - List classNames = new ArrayList(results.keySet()); + List classNames = new ArrayList<>(results.keySet()); Collections.sort(classNames); int maxClassNameLength = 0; int maxNanosLength = 0; @@ -173,9 +173,9 @@ public class RemovePollRace { addersDone.countDown(); }}; - final List adders = new ArrayList(); - final List removers = new ArrayList(); - final List pollers = new ArrayList(); + final List adders = new ArrayList<>(); + final List removers = new ArrayList<>(); + final List pollers = new ArrayList<>(); for (int i = 0; i < adderCount; i++) adders.add(checkedThread(adder)); for (int i = 0; i < removerCount; i++) @@ -183,7 +183,7 @@ public class RemovePollRace { for (int i = 0; i < pollerCount; i++) pollers.add(checkedThread(poller)); - final List allThreads = new ArrayList(); + final List allThreads = new ArrayList<>(); allThreads.addAll(removers); allThreads.addAll(pollers); allThreads.addAll(adders); diff --git a/jdk/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java b/jdk/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java index be883b11aa1..a64228116a4 100644 --- a/jdk/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java +++ b/jdk/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java @@ -36,7 +36,7 @@ import java.util.concurrent.CopyOnWriteArrayList; public class EqualsRace { private static void realMain(String[] args) throws Throwable { final int iterations = 100000; - final List list = new CopyOnWriteArrayList(); + final List list = new CopyOnWriteArrayList<>(); final Integer one = Integer.valueOf(1); final List oneElementList = Arrays.asList(one); final Thread t = new CheckedThread() { public void realRun() { diff --git a/jdk/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java b/jdk/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java index 66f57a377f4..0b3771d6ec9 100644 --- a/jdk/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java +++ b/jdk/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java @@ -40,8 +40,8 @@ public class RacingCows { final Integer three = Integer.valueOf(3); //------------ CopyOnWriteArraySet ------------------------------- - final Set s1 = new CopyOnWriteArraySet(); - final Set s2 = new CopyOnWriteArraySet(); + final Set s1 = new CopyOnWriteArraySet<>(); + final Set s2 = new CopyOnWriteArraySet<>(); s1.add(1); final Thread t1 = new CheckedThread() { public void realRun() { @@ -58,9 +58,9 @@ public class RacingCows { t1.join(); //------------ CopyOnWriteArrayList ------------------------------ - final List l1 = new CopyOnWriteArrayList(); - final List l2 = new CopyOnWriteArrayList(); - final List l3 = new CopyOnWriteArrayList(); + final List l1 = new CopyOnWriteArrayList<>(); + final List l2 = new CopyOnWriteArrayList<>(); + final List l3 = new CopyOnWriteArrayList<>(); l1.add(1); final Thread t2 = new CheckedThread() { public void realRun() { diff --git a/jdk/test/java/util/concurrent/CyclicBarrier/Basic.java b/jdk/test/java/util/concurrent/CyclicBarrier/Basic.java index 146347ed502..7bf93b3c168 100644 --- a/jdk/test/java/util/concurrent/CyclicBarrier/Basic.java +++ b/jdk/test/java/util/concurrent/CyclicBarrier/Basic.java @@ -332,7 +332,7 @@ public class Basic { //---------------------------------------------------------------- try { final CountDownLatch doneSignal = new CountDownLatch(1); - final List waiters = new ArrayList(N); + final List waiters = new ArrayList<>(N); // work around finality of closed-over variables final Runnable[] realAction = new Runnable[1]; @@ -379,7 +379,7 @@ public class Basic { try { final CountDownLatch doneSignal = new CountDownLatch(1); final CyclicBarrier barrier = new CyclicBarrier(N+1); - final List waiters = new ArrayList(N); + final List waiters = new ArrayList<>(N); for (int i = 0; i < N; i++) { Waiter waiter = new Waiter(i < N/2, doneSignal, barrier); waiter.start(); diff --git a/jdk/test/java/util/concurrent/DelayQueue/Iterate.java b/jdk/test/java/util/concurrent/DelayQueue/Iterate.java index 7639fcb2bd8..d63592f6bcc 100644 --- a/jdk/test/java/util/concurrent/DelayQueue/Iterate.java +++ b/jdk/test/java/util/concurrent/DelayQueue/Iterate.java @@ -42,7 +42,7 @@ public class Iterate { private static void realMain(String[] args) throws Throwable { Godot[] godots = new Godot[] { new Godot(), new Godot(), new Godot() }; - DelayQueue q = new DelayQueue(Arrays.asList(godots)); + DelayQueue q = new DelayQueue<>(Arrays.asList(godots)); Iterator it = q.iterator(); q.clear(); check(it.hasNext()); diff --git a/jdk/test/java/util/concurrent/DelayQueue/PollUnexpired.java b/jdk/test/java/util/concurrent/DelayQueue/PollUnexpired.java index 0d00c31403e..e131e58dcee 100644 --- a/jdk/test/java/util/concurrent/DelayQueue/PollUnexpired.java +++ b/jdk/test/java/util/concurrent/DelayQueue/PollUnexpired.java @@ -39,7 +39,7 @@ public class PollUnexpired { } private static void realMain(String[] args) throws Throwable { - DelayQueue q = new DelayQueue(); + DelayQueue q = new DelayQueue<>(); for (int i = 0; i < 3; i++) { equal(q.size(), i); equal(q.poll(), null); diff --git a/jdk/test/java/util/concurrent/DelayQueue/Stress.java b/jdk/test/java/util/concurrent/DelayQueue/Stress.java index 44a20fff936..ad3b3c090eb 100644 --- a/jdk/test/java/util/concurrent/DelayQueue/Stress.java +++ b/jdk/test/java/util/concurrent/DelayQueue/Stress.java @@ -38,7 +38,7 @@ public class Stress { public static void main(String[] args) throws Throwable { - final DelayQueue q = new DelayQueue(); + final DelayQueue q = new DelayQueue<>(); final long t0 = System.nanoTime(); for (long i = 0; i < 1000; i++) { final long expiry = t0 + i*10L*1000L*1000L; diff --git a/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java b/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java index 5a20b6b9e2f..f2ef41a9475 100644 --- a/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java +++ b/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java @@ -116,8 +116,8 @@ public class ExchangeLoops { barrier.await(); } - catch (Exception ie) { - ie.printStackTrace(); + catch (Exception ex) { + ex.printStackTrace(); return; } } @@ -127,7 +127,7 @@ public class ExchangeLoops { LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); CyclicBarrier barrier = new CyclicBarrier(nthreads + 1, timer); Exchanger l = null; - Exchanger r = new Exchanger(); + Exchanger r = new Exchanger<>(); for (int i = 0; i < nthreads; ++i) { pool.execute(new Stage(l, r, barrier, iters)); l = r; diff --git a/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java b/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java index afe3a475410..9119a20328f 100644 --- a/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java +++ b/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java @@ -45,7 +45,7 @@ import java.util.concurrent.Callable; public class PrivilegedCallables { Callable real; - final Callable realCaller = new Callable() { + final Callable realCaller = new Callable<>() { public Integer call() throws Exception { return real.call(); }}; @@ -132,7 +132,7 @@ public class PrivilegedCallables { for (int i = 0; i < 20; i++) if (rnd.nextBoolean()) { final Throwable t = randomThrowable(); - real = new Callable() { + real = new Callable<>() { public Integer call() throws Exception { throwThrowable(t); return null; }}; @@ -142,7 +142,7 @@ public class PrivilegedCallables { } catch (Throwable tt) { check(t == tt); } } else { final int n = rnd.nextInt(); - real = new Callable() { + real = new Callable<>() { public Integer call() { return n; }}; equal(c.call(), n); } diff --git a/jdk/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java b/jdk/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java index ad92d063da2..4545284f893 100644 --- a/jdk/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java +++ b/jdk/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java @@ -55,8 +55,7 @@ public class BlockingTaskExecutor { final NotificationReceiver notifiee1 = new NotificationReceiver(); final NotificationReceiver notifiee2 = new NotificationReceiver(); - final Collection> tasks = - new ArrayList>(); + final Collection> tasks = new ArrayList<>(); tasks.add(new BlockingTask(notifiee1)); tasks.add(new BlockingTask(notifiee2)); tasks.add(new NonBlockingTask()); diff --git a/jdk/test/java/util/concurrent/FutureTask/Customized.java b/jdk/test/java/util/concurrent/FutureTask/Customized.java index 91223bb03ff..fca52ef466c 100644 --- a/jdk/test/java/util/concurrent/FutureTask/Customized.java +++ b/jdk/test/java/util/concurrent/FutureTask/Customized.java @@ -119,7 +119,7 @@ public class Customized { public void run() { throw new Error(); }}; try { - final MyFutureTask task = new MyFutureTask(nop, 42L); + final MyFutureTask task = new MyFutureTask<>(nop, 42L); checkReady(task); equalCounts(0,0,0); check(task.runAndReset()); @@ -136,7 +136,7 @@ public class Customized { } catch (Throwable t) { unexpected(t); } try { - final MyFutureTask task = new MyFutureTask(nop, 42L); + final MyFutureTask task = new MyFutureTask<>(nop, 42L); cancel(task, false); equalCounts(2,1,0); cancel(task, false); @@ -147,7 +147,7 @@ public class Customized { } catch (Throwable t) { unexpected(t); } try { - final MyFutureTask task = new MyFutureTask(bad, 42L); + final MyFutureTask task = new MyFutureTask<>(bad, 42L); checkReady(task); run(task); checkThrew(task); @@ -157,7 +157,7 @@ public class Customized { } catch (Throwable t) { unexpected(t); } try { - final MyFutureTask task = new MyFutureTask(nop, 42L); + final MyFutureTask task = new MyFutureTask<>(nop, 42L); checkReady(task); task.set(99L); checkDone(task); @@ -170,7 +170,7 @@ public class Customized { } catch (Throwable t) { unexpected(t); } try { - final MyFutureTask task = new MyFutureTask(nop, 42L); + final MyFutureTask task = new MyFutureTask<>(nop, 42L); checkReady(task); task.setException(new Throwable()); checkThrew(task); diff --git a/jdk/test/java/util/concurrent/FutureTask/DoneMeansDone.java b/jdk/test/java/util/concurrent/FutureTask/DoneMeansDone.java index 7874107d40a..38239f72e24 100644 --- a/jdk/test/java/util/concurrent/FutureTask/DoneMeansDone.java +++ b/jdk/test/java/util/concurrent/FutureTask/DoneMeansDone.java @@ -63,7 +63,7 @@ public class DoneMeansDone { final AtomicBoolean done = new AtomicBoolean(false); final AtomicReference> a = new AtomicReference<>(); final CountDownLatch threadsStarted = new CountDownLatch(nThreads); - final Callable alwaysTrue = new Callable() { + final Callable alwaysTrue = new Callable<>() { public Boolean call() { return true; }}; diff --git a/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java b/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java index 8c0e21984f8..2a94f8f389e 100644 --- a/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java +++ b/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java @@ -66,9 +66,9 @@ public class DoneTimedGetLoops { final long timeoutMillis = 10L * 1000L; final AtomicReference normalRef - = new AtomicReference(); + = new AtomicReference<>(); final AtomicReference abnormalRef - = new AtomicReference(); + = new AtomicReference<>(); final Throwable throwable = new Throwable(); diff --git a/jdk/test/java/util/concurrent/LinkedBlockingQueue/ToArray.java b/jdk/test/java/util/concurrent/LinkedBlockingQueue/ToArray.java index 8933ad95dab..824857106d7 100644 --- a/jdk/test/java/util/concurrent/LinkedBlockingQueue/ToArray.java +++ b/jdk/test/java/util/concurrent/LinkedBlockingQueue/ToArray.java @@ -33,7 +33,7 @@ import java.util.concurrent.LinkedBlockingQueue; public class ToArray { public static void main(String[] args) throws Throwable { - Collection c = new LinkedBlockingQueue(); + Collection c = new LinkedBlockingQueue<>(); if (c.toArray(new Integer[]{42})[0] != null) throw new Error("should be null"); } diff --git a/jdk/test/java/util/concurrent/Phaser/Arrive.java b/jdk/test/java/util/concurrent/Phaser/Arrive.java index 1a931530a56..c94ee1b15ee 100644 --- a/jdk/test/java/util/concurrent/Phaser/Arrive.java +++ b/jdk/test/java/util/concurrent/Phaser/Arrive.java @@ -52,7 +52,7 @@ public class Arrive { final int n = ThreadLocalRandom.current().nextInt(1, 10); final Phaser startingGate = new Phaser(n); final Phaser phaser = new Phaser(n); - final List threads = new ArrayList(); + final List threads = new ArrayList<>(); final AtomicInteger count0 = new AtomicInteger(0); final AtomicInteger count1 = new AtomicInteger(0); final Runnable task = new Runnable() { public void run() { diff --git a/jdk/test/java/util/concurrent/Phaser/Basic.java b/jdk/test/java/util/concurrent/Phaser/Basic.java index b3acc0bd798..99356cd7c7a 100644 --- a/jdk/test/java/util/concurrent/Phaser/Basic.java +++ b/jdk/test/java/util/concurrent/Phaser/Basic.java @@ -69,8 +69,8 @@ public class Basic { try { equal(phase, phaser.awaitAdvanceInterruptibly(0)); equal(phase, phaser.awaitAdvanceInterruptibly(0, 10, SECONDS)); - } catch (Exception ie) { - unexpected(ie); + } catch (Exception ex) { + unexpected(ex); } equal(phaser.getUnarrivedParties(), unarriverParties); equal(phaser.getRegisteredParties(), registeredParties); @@ -323,7 +323,7 @@ public class Basic { try { Phaser phaser = new Phaser(1); Iterator arrivers = arriverIterator(phaser); - LinkedList arriverList = new LinkedList(); + LinkedList arriverList = new LinkedList<>(); int phase = phaser.getPhase(); for (int i = 1; i < 5; i++) { startingGate = new Phaser(1+(3*i)); diff --git a/jdk/test/java/util/concurrent/Phaser/FickleRegister.java b/jdk/test/java/util/concurrent/Phaser/FickleRegister.java index 9ee00946f1d..a2632406292 100644 --- a/jdk/test/java/util/concurrent/Phaser/FickleRegister.java +++ b/jdk/test/java/util/concurrent/Phaser/FickleRegister.java @@ -93,7 +93,7 @@ public class FickleRegister { }; int reps = 4; - ArrayList threads = new ArrayList(); + ArrayList threads = new ArrayList<>(); for (int j = 0; j < reps; ++j) { threads.add(new Thread(new Runner(subchild1))); threads.add(new Thread(new Runner(child1))); diff --git a/jdk/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java b/jdk/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java index ce5561e4d40..7457e6cc252 100644 --- a/jdk/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java +++ b/jdk/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java @@ -44,6 +44,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; +import java.util.function.Supplier; import jdk.testlibrary.RandomFactory; public class ConfigChanges { @@ -124,6 +125,22 @@ public class ConfigChanges { } } + /** + * Waits for condition to become true, first spin-polling, then sleep-polling. + */ + static void spinAwait(Supplier waitingForGodot) { + for (int spins = 0; !waitingForGodot.get(); ) { + if ((spins = (spins + 1) & 3) > 0) { + Thread.yield(); + } else { + try { Thread.sleep(4); } + catch (InterruptedException unexpected) { + throw new AssertionError(unexpected); + } + } + } + } + private static void realMain(String[] args) throws Throwable { if (rnd.nextBoolean()) System.setSecurityManager(new PermissiveSecurityManger()); @@ -210,10 +227,7 @@ public class ConfigChanges { pumpedUp2.await(); pumpedUp.await(); - while (tg.activeCount() != 2*n && - tg.activeCount() != 2*n) - Thread.yield(); - equal(2*n, tg.activeCount()); + spinAwait(() -> tg.activeCount() == 2*n); equal(2*n, tpe.getMaximumPoolSize()); equal(4*n, tpe.getLargestPoolSize()); @@ -232,10 +246,7 @@ public class ConfigChanges { long t0 = System.nanoTime(); tpe.setKeepAliveTime(7L, MILLISECONDS); equal(7L, tpe.getKeepAliveTime(MILLISECONDS)); - while (tg.activeCount() > n && - tg.activeCount() > n) - Thread.sleep(4); - equal(n, tg.activeCount()); + spinAwait(() -> tg.activeCount() == n); check(System.nanoTime() - t0 >= tpe.getKeepAliveTime(NANOSECONDS)); //report("idle", tpe); @@ -243,10 +254,7 @@ public class ConfigChanges { t0 = System.nanoTime(); tpe.allowCoreThreadTimeOut(true); check(tpe.allowsCoreThreadTimeOut()); - while (tg.activeCount() > 0 && - tg.activeCount() > 0) - Thread.sleep(4); - equal(tg.activeCount(), 0); + spinAwait(() -> tg.activeCount() == 0); // The following assertion is almost always true, but may // exceptionally not be during a transition from core count diff --git a/jdk/test/java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java b/jdk/test/java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java index a8bb4c29615..0bbb5141224 100644 --- a/jdk/test/java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java +++ b/jdk/test/java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java @@ -72,8 +72,7 @@ public class CoreThreadTimeOut { void test(String[] args) throws Throwable { final int threadCount = 10; final int timeoutMillis = 30; - BlockingQueue q - = new ArrayBlockingQueue(2*threadCount); + BlockingQueue q = new ArrayBlockingQueue<>(2*threadCount); ThreadPoolExecutor tpe = new ThreadPoolExecutor(threadCount, threadCount, timeoutMillis, TimeUnit.MILLISECONDS, diff --git a/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java b/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java index 8a492e715ea..7f7d5bc9134 100644 --- a/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java +++ b/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java @@ -45,6 +45,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; public class ThrowingTasks { static final Random rnd = new Random(); @@ -139,7 +140,7 @@ public class ThrowingTasks { public void run() { execute.run(); } } - static final List flakes = new ArrayList(); + static final List flakes = new ArrayList<>(); static { for (Thrower x : throwers) for (Thrower y : throwers) @@ -167,6 +168,22 @@ public class ThrowingTasks { } catch (Throwable t) { unexpected(t); } } + /** + * Waits for condition to become true, first spin-polling, then sleep-polling. + */ + static void spinAwait(Supplier waitingForGodot) { + for (int spins = 0; !waitingForGodot.get(); ) { + if ((spins = (spins + 1) & 3) > 0) { + Thread.yield(); + } else { + try { Thread.sleep(4); } + catch (InterruptedException unexpected) { + throw new AssertionError(unexpected); + } + } + } + } + static class CheckingExecutor extends ThreadPoolExecutor { private final ReentrantLock lock = new ReentrantLock(); CheckingExecutor() { @@ -238,10 +255,7 @@ public class ThrowingTasks { //System.out.printf("thread count = %d%n", tg.activeCount()); uncaughtExceptionsLatch.await(); - while (tg.activeCount() != tpe.getCorePoolSize() || - tg.activeCount() != tpe.getCorePoolSize()) - Thread.sleep(10); - equal(tg.activeCount(), tpe.getCorePoolSize()); + spinAwait(() -> tg.activeCount() == tpe.getCorePoolSize()); tpe.shutdown(); @@ -250,8 +264,7 @@ public class ThrowingTasks { //while (tg.activeCount() > 0) Thread.sleep(10); //System.out.println(uncaughtExceptions); - List, Integer>> maps - = new ArrayList, Integer>>(); + List, Integer>> maps = new ArrayList<>(); maps.add(uncaughtExceptions); maps.add(uncaughtExceptionsTable); for (Map, Integer> map : maps) { diff --git a/jdk/test/java/util/concurrent/atomic/Lazy.java b/jdk/test/java/util/concurrent/atomic/Lazy.java index a528589534d..d576e2c84d2 100644 --- a/jdk/test/java/util/concurrent/atomic/Lazy.java +++ b/jdk/test/java/util/concurrent/atomic/Lazy.java @@ -48,11 +48,11 @@ public class Lazy { final AtomicBoolean b = new AtomicBoolean(); final AtomicInteger i = new AtomicInteger(); final AtomicLong l = new AtomicLong(); - final AtomicReference r = new AtomicReference(); + final AtomicReference r = new AtomicReference<>(); final AtomicIntegerArray ia = new AtomicIntegerArray(1); final AtomicLongArray la = new AtomicLongArray(1); - final AtomicReferenceArray ra = new AtomicReferenceArray(1); + final AtomicReferenceArray ra = new AtomicReferenceArray<>(1); final AtomicIntegerFieldUpdater iu = AtomicIntegerFieldUpdater.newUpdater(Lazy.class, "ii"); diff --git a/jdk/test/java/util/concurrent/locks/Lock/CheckedLockLoops.java b/jdk/test/java/util/concurrent/locks/Lock/CheckedLockLoops.java index 2e3d4b28e12..ba7116c27b2 100644 --- a/jdk/test/java/util/concurrent/locks/Lock/CheckedLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/Lock/CheckedLockLoops.java @@ -40,11 +40,11 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.SplittableRandom; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -53,7 +53,6 @@ import jdk.testlibrary.Utils; public final class CheckedLockLoops { static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000); static ExecutorService pool; - static final SplittableRandom rnd = new SplittableRandom(); public static void main(String[] args) throws Exception { final int maxThreads = (args.length > 0) @@ -73,7 +72,7 @@ public final class CheckedLockLoops { static void oneTest(int nthreads, int iters) throws Exception { System.out.println("Threads: " + nthreads); - int v = rnd.nextInt(); + int v = ThreadLocalRandom.current().nextInt(); System.out.print("builtin lock "); new BuiltinLockLoop().test(v, nthreads, iters); @@ -151,7 +150,7 @@ public final class CheckedLockLoops { result += loop(iters); barrier.await(); } - catch (Exception ie) { + catch (Exception ex) { return; } } diff --git a/jdk/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java b/jdk/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java index 630f3796b8c..636f8d151df 100644 --- a/jdk/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java +++ b/jdk/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java @@ -42,7 +42,6 @@ import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import java.lang.ref.WeakReference; -import java.util.SplittableRandom; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -52,6 +51,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; @@ -192,7 +192,7 @@ public class TimedAcquireLeak { final String childClassName = Job.class.getName(); final String classToCheckForLeaks = Job.classToCheckForLeaks(); final String uniqueID = - String.valueOf(new SplittableRandom().nextInt(Integer.MAX_VALUE)); + String.valueOf(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); final String[] jobCmd = { java, "-Xmx8m", "-XX:+UsePerfData", @@ -259,7 +259,7 @@ public class TimedAcquireLeak { = rwlock.writeLock(); rwlock.writeLock().lock(); - final BlockingQueue q = new LinkedBlockingQueue(); + final BlockingQueue q = new LinkedBlockingQueue<>(); final Semaphore fairSem = new Semaphore(0, true); final Semaphore unfairSem = new Semaphore(0, false); //final int threads = @@ -275,7 +275,7 @@ public class TimedAcquireLeak { for (int i = 0; i < threads; i++) new Thread() { public void run() { try { - final SplittableRandom rnd = new SplittableRandom(); + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); for (int j = 0; j < iterations; j++) { if (j == iterations/10 || j == iterations - 1) { cb.await(); // Quiesce diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java index dbbc2fbb638..49d5360824b 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java @@ -40,13 +40,11 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; -import java.util.SplittableRandom; import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.ReentrantLock; public final class CancelledLockLoops { - static final SplittableRandom rnd = new SplittableRandom(); - public static void main(String[] args) throws Exception { final int maxThreads = (args.length > 0) ? Integer.parseInt(args[0]) : 5; final int reps = 1; // increase for stress testing @@ -61,7 +59,7 @@ public final class CancelledLockLoops { static final class Loops implements Runnable { private final boolean print = false; private volatile boolean done = false; - private int v = rnd.nextInt(); + private int v = ThreadLocalRandom.current().nextInt(); private int completed = 0; private volatile int result = 17; private final ReentrantLock lock = new ReentrantLock(); @@ -76,6 +74,7 @@ public final class CancelledLockLoops { } final void test() throws Exception { + final ThreadLocalRandom rnd = ThreadLocalRandom.current(); Thread[] threads = new Thread[nthreads]; for (int i = 0; i < threads.length; ++i) threads[i] = new Thread(this); diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java index de9f765b733..43963e3554e 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java @@ -40,17 +40,16 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.SplittableRandom; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.ReentrantLock; import jdk.testlibrary.Utils; public final class LockOncePerThreadLoops { static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000); static final ExecutorService pool = Executors.newCachedThreadPool(); - static final SplittableRandom rnd = new SplittableRandom(); static boolean print = false; static int nlocks = 20_000; static int nthreads = 20; @@ -75,7 +74,7 @@ public final class LockOncePerThreadLoops { } static final class ReentrantLockLoop implements Runnable { - private int v = rnd.nextInt(); + private int v = ThreadLocalRandom.current().nextInt(); private volatile int result = 17; final ReentrantLock[]locks = new ReentrantLock[nlocks]; @@ -112,7 +111,7 @@ public final class LockOncePerThreadLoops { for (int i = 0; i < locks.length; ++i) { locks[i].lock(); try { - v = x += ~(v - i); + v = x += ~(v - i); } finally { locks[i].unlock(); @@ -127,7 +126,7 @@ public final class LockOncePerThreadLoops { barrier.await(); result += sum; } - catch (Exception ie) { + catch (Exception ex) { return; } } diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java index 8534a391594..85e403970d5 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java @@ -40,17 +40,16 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.SplittableRandom; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.ThreadLocalRandom; import jdk.testlibrary.Utils; public final class SimpleReentrantLockLoops { static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000); static final ExecutorService pool = Executors.newCachedThreadPool(); - static final SplittableRandom rnd = new SplittableRandom(); static boolean print = false; static int iters = 100_000; @@ -76,7 +75,7 @@ public final class SimpleReentrantLockLoops { } static final class ReentrantLockLoop implements Runnable { - private int v = rnd.nextInt(); + private int v = ThreadLocalRandom.current().nextInt(); private volatile int result = 17; private final ReentrantLock lock = new ReentrantLock(); private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); @@ -132,7 +131,7 @@ public final class SimpleReentrantLockLoops { barrier.await(); result += sum; } - catch (Exception ie) { + catch (Exception ex) { return; } } diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java index 8dc02e4f570..d0b9ff1c1e4 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java @@ -40,10 +40,10 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; -import java.util.SplittableRandom; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import jdk.testlibrary.Utils; @@ -51,7 +51,6 @@ import jdk.testlibrary.Utils; public final class TimeoutLockLoops { static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000); static final ExecutorService pool = Executors.newCachedThreadPool(); - static final SplittableRandom rnd = new SplittableRandom(); static boolean print = false; static final long TIMEOUT = 10; @@ -72,7 +71,7 @@ public final class TimeoutLockLoops { } static final class ReentrantLockLoop implements Runnable { - private int v = rnd.nextInt(); + private int v = ThreadLocalRandom.current().nextInt(); private volatile int result = 17; private final ReentrantLock lock = new ReentrantLock(); private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); @@ -91,7 +90,7 @@ public final class TimeoutLockLoops { lock.unlock(); } barrier.await(); - Thread.sleep(rnd.nextInt(5)); + Thread.sleep(ThreadLocalRandom.current().nextInt(5)); while (!lock.tryLock()); // Jam lock // lock.lock(); barrier.await(); diff --git a/jdk/test/java/util/concurrent/tck/AbstractExecutorServiceTest.java b/jdk/test/java/util/concurrent/tck/AbstractExecutorServiceTest.java index 9e140da9f72..3578227f813 100644 --- a/jdk/test/java/util/concurrent/tck/AbstractExecutorServiceTest.java +++ b/jdk/test/java/util/concurrent/tck/AbstractExecutorServiceTest.java @@ -294,7 +294,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAny3() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new Callable() { public Long call() { throw new ArithmeticException(); }}); l.add(null); @@ -311,7 +311,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAny4() throws InterruptedException { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -328,7 +328,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAny5() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -366,7 +366,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAll3() throws InterruptedException { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -382,7 +382,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAll4() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -401,7 +401,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testInvokeAll5() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -430,7 +430,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAnyNullTimeUnit() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -459,7 +459,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAny3() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new Callable() { public Long call() { throw new ArithmeticException(); }}); l.add(null); @@ -477,7 +477,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -496,7 +496,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -524,7 +524,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAllNullTimeUnit() throws InterruptedException { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -550,7 +550,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAll3() throws InterruptedException { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -566,7 +566,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAll4() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); @@ -586,7 +586,7 @@ public class AbstractExecutorServiceTest extends JSR166TestCase { public void testTimedInvokeAll5() throws Exception { final ExecutorService e = new DirectExecutorService(); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = diff --git a/jdk/test/java/util/concurrent/tck/AbstractQueuedLongSynchronizerTest.java b/jdk/test/java/util/concurrent/tck/AbstractQueuedLongSynchronizerTest.java index 88bdd13b4dc..fd8746d4fa4 100644 --- a/jdk/test/java/util/concurrent/tck/AbstractQueuedLongSynchronizerTest.java +++ b/jdk/test/java/util/concurrent/tck/AbstractQueuedLongSynchronizerTest.java @@ -262,8 +262,8 @@ public class AbstractQueuedLongSynchronizerTest extends JSR166TestCase { * default timeout duration). */ void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) { - long timeoutMillis = timeoutMillis(); - long startTime; + final long timeoutMillis = timeoutMillis(); + final long startTime; try { switch (awaitMethod) { case awaitTimed: @@ -282,7 +282,7 @@ public class AbstractQueuedLongSynchronizerTest extends JSR166TestCase { case awaitUntil: // We shouldn't assume that nanoTime and currentTimeMillis // use the same time source, so don't use nanoTime here. - java.util.Date delayedDate = delayedDate(timeoutMillis()); + java.util.Date delayedDate = delayedDate(timeoutMillis); assertFalse(c.awaitUntil(delayedDate(timeoutMillis))); assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); break; diff --git a/jdk/test/java/util/concurrent/tck/AbstractQueuedSynchronizerTest.java b/jdk/test/java/util/concurrent/tck/AbstractQueuedSynchronizerTest.java index 8341a7e296c..3c13a452d5f 100644 --- a/jdk/test/java/util/concurrent/tck/AbstractQueuedSynchronizerTest.java +++ b/jdk/test/java/util/concurrent/tck/AbstractQueuedSynchronizerTest.java @@ -265,8 +265,8 @@ public class AbstractQueuedSynchronizerTest extends JSR166TestCase { * default timeout duration). */ void assertAwaitTimesOut(ConditionObject c, AwaitMethod awaitMethod) { - long timeoutMillis = timeoutMillis(); - long startTime; + final long timeoutMillis = timeoutMillis(); + final long startTime; try { switch (awaitMethod) { case awaitTimed: @@ -285,7 +285,7 @@ public class AbstractQueuedSynchronizerTest extends JSR166TestCase { case awaitUntil: // We shouldn't assume that nanoTime and currentTimeMillis // use the same time source, so don't use nanoTime here. - java.util.Date delayedDate = delayedDate(timeoutMillis()); + java.util.Date delayedDate = delayedDate(timeoutMillis); assertFalse(c.awaitUntil(delayedDate(timeoutMillis))); assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); break; diff --git a/jdk/test/java/util/concurrent/tck/Atomic8Test.java b/jdk/test/java/util/concurrent/tck/Atomic8Test.java index c4a43941c32..4784aa7901e 100644 --- a/jdk/test/java/util/concurrent/tck/Atomic8Test.java +++ b/jdk/test/java/util/concurrent/tck/Atomic8Test.java @@ -316,7 +316,7 @@ public class Atomic8Test extends JSR166TestCase { * result of supplied function */ public void testReferenceArrayGetAndUpdate() { - AtomicReferenceArray a = new AtomicReferenceArray(1); + AtomicReferenceArray a = new AtomicReferenceArray<>(1); a.set(0, one); assertEquals((Integer) 1, a.getAndUpdate(0, Atomic8Test::addInteger17)); assertEquals((Integer) 18, a.getAndUpdate(0, Atomic8Test::addInteger17)); @@ -328,7 +328,7 @@ public class Atomic8Test extends JSR166TestCase { * returns result. */ public void testReferenceArrayUpdateAndGet() { - AtomicReferenceArray a = new AtomicReferenceArray(1); + AtomicReferenceArray a = new AtomicReferenceArray<>(1); a.set(0, one); assertEquals((Integer) 18, a.updateAndGet(0, Atomic8Test::addInteger17)); assertEquals((Integer) 35, a.updateAndGet(0, Atomic8Test::addInteger17)); @@ -339,7 +339,7 @@ public class Atomic8Test extends JSR166TestCase { * with supplied function. */ public void testReferenceArrayGetAndAccumulate() { - AtomicReferenceArray a = new AtomicReferenceArray(1); + AtomicReferenceArray a = new AtomicReferenceArray<>(1); a.set(0, one); assertEquals((Integer) 1, a.getAndAccumulate(0, 2, Atomic8Test::sumInteger)); assertEquals((Integer) 3, a.getAndAccumulate(0, 3, Atomic8Test::sumInteger)); @@ -351,7 +351,7 @@ public class Atomic8Test extends JSR166TestCase { * returns result. */ public void testReferenceArrayAccumulateAndGet() { - AtomicReferenceArray a = new AtomicReferenceArray(1); + AtomicReferenceArray a = new AtomicReferenceArray<>(1); a.set(0, one); assertEquals((Integer) 7, a.accumulateAndGet(0, 6, Atomic8Test::sumInteger)); assertEquals((Integer) 10, a.accumulateAndGet(0, 3, Atomic8Test::sumInteger)); diff --git a/jdk/test/java/util/concurrent/tck/AtomicReferenceArrayTest.java b/jdk/test/java/util/concurrent/tck/AtomicReferenceArrayTest.java index 8e7bf10642f..019446cc14d 100644 --- a/jdk/test/java/util/concurrent/tck/AtomicReferenceArrayTest.java +++ b/jdk/test/java/util/concurrent/tck/AtomicReferenceArrayTest.java @@ -51,7 +51,7 @@ public class AtomicReferenceArrayTest extends JSR166TestCase { * constructor creates array of given size with all elements null */ public void testConstructor() { - AtomicReferenceArray aa = new AtomicReferenceArray(SIZE); + AtomicReferenceArray aa = new AtomicReferenceArray<>(SIZE); for (int i = 0; i < SIZE; i++) { assertNull(aa.get(i)); } @@ -73,7 +73,7 @@ public class AtomicReferenceArrayTest extends JSR166TestCase { */ public void testConstructor2() { Integer[] a = { two, one, three, four, seven }; - AtomicReferenceArray aa = new AtomicReferenceArray(a); + AtomicReferenceArray aa = new AtomicReferenceArray<>(a); assertEquals(a.length, aa.length()); for (int i = 0; i < a.length; i++) assertEquals(a[i], aa.get(i)); @@ -98,7 +98,7 @@ public class AtomicReferenceArrayTest extends JSR166TestCase { * get and set for out of bound indices throw IndexOutOfBoundsException */ public void testIndexing() { - AtomicReferenceArray aa = new AtomicReferenceArray(SIZE); + AtomicReferenceArray aa = new AtomicReferenceArray<>(SIZE); for (int index : new int[] { -1, SIZE }) { try { aa.get(index); @@ -240,7 +240,7 @@ public class AtomicReferenceArrayTest extends JSR166TestCase { */ public void testToString() { Integer[] a = { two, one, three, four, seven }; - AtomicReferenceArray aa = new AtomicReferenceArray(a); + AtomicReferenceArray aa = new AtomicReferenceArray<>(a); assertEquals(Arrays.toString(a), aa.toString()); } diff --git a/jdk/test/java/util/concurrent/tck/CompletableFutureTest.java b/jdk/test/java/util/concurrent/tck/CompletableFutureTest.java index bc81edfad81..6def2fffb3a 100644 --- a/jdk/test/java/util/concurrent/tck/CompletableFutureTest.java +++ b/jdk/test/java/util/concurrent/tck/CompletableFutureTest.java @@ -120,10 +120,10 @@ public class CompletableFutureTest extends JSR166TestCase { * Returns the "raw" internal exceptional completion of f, * without any additional wrapping with CompletionException. */ - Throwable exceptionalCompletion(CompletableFuture f) { - // handle (and whenComplete) can distinguish between "direct" - // and "wrapped" exceptional completion - return f.handle((U u, Throwable t) -> t).join(); + Throwable exceptionalCompletion(CompletableFuture f) { + // handle (and whenComplete and exceptionally) can distinguish + // between "direct" and "wrapped" exceptional completion + return f.handle((u, t) -> t).join(); } void checkCompletedExceptionally(CompletableFuture f, @@ -3559,7 +3559,7 @@ public class CompletableFutureTest extends JSR166TestCase { */ public void testCompletedStage() { AtomicInteger x = new AtomicInteger(0); - AtomicReference r = new AtomicReference(); + AtomicReference r = new AtomicReference<>(); CompletionStage f = CompletableFuture.completedStage(1); f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); assertEquals(x.get(), 1); @@ -3661,7 +3661,7 @@ public class CompletableFutureTest extends JSR166TestCase { CompletableFuture f = new CompletableFuture<>(); CompletionStage g = f.minimalCompletionStage(); AtomicInteger x = new AtomicInteger(0); - AtomicReference r = new AtomicReference(); + AtomicReference r = new AtomicReference<>(); checkIncomplete(f); g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); f.complete(1); @@ -3678,7 +3678,7 @@ public class CompletableFutureTest extends JSR166TestCase { CompletableFuture f = new CompletableFuture<>(); CompletionStage g = f.minimalCompletionStage(); AtomicInteger x = new AtomicInteger(0); - AtomicReference r = new AtomicReference(); + AtomicReference r = new AtomicReference<>(); g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); checkIncomplete(f); CFException ex = new CFException(); @@ -3696,7 +3696,7 @@ public class CompletableFutureTest extends JSR166TestCase { CFException ex = new CFException(); CompletionStage f = CompletableFuture.failedStage(ex); AtomicInteger x = new AtomicInteger(0); - AtomicReference r = new AtomicReference(); + AtomicReference r = new AtomicReference<>(); f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); assertEquals(x.get(), 0); assertEquals(r.get(), ex); diff --git a/jdk/test/java/util/concurrent/tck/ConcurrentHashMapTest.java b/jdk/test/java/util/concurrent/tck/ConcurrentHashMapTest.java index b6e6f72d854..1485d2c4dca 100644 --- a/jdk/test/java/util/concurrent/tck/ConcurrentHashMapTest.java +++ b/jdk/test/java/util/concurrent/tck/ConcurrentHashMapTest.java @@ -61,7 +61,7 @@ public class ConcurrentHashMapTest extends JSR166TestCase { * Returns a new map from Integers 1-5 to Strings "A"-"E". */ private static ConcurrentHashMap map5() { - ConcurrentHashMap map = new ConcurrentHashMap(5); + ConcurrentHashMap map = new ConcurrentHashMap<>(5); assertTrue(map.isEmpty()); map.put(one, "A"); map.put(two, "B"); diff --git a/jdk/test/java/util/concurrent/tck/ConcurrentLinkedDequeTest.java b/jdk/test/java/util/concurrent/tck/ConcurrentLinkedDequeTest.java index bf1c055dc7f..aac0bb73910 100644 --- a/jdk/test/java/util/concurrent/tck/ConcurrentLinkedDequeTest.java +++ b/jdk/test/java/util/concurrent/tck/ConcurrentLinkedDequeTest.java @@ -68,7 +68,7 @@ public class ConcurrentLinkedDequeTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private ConcurrentLinkedDeque populatedDeque(int n) { - ConcurrentLinkedDeque q = new ConcurrentLinkedDeque(); + ConcurrentLinkedDeque q = new ConcurrentLinkedDeque<>(); assertTrue(q.isEmpty()); for (int i = 0; i < n; ++i) assertTrue(q.offer(new Integer(i))); diff --git a/jdk/test/java/util/concurrent/tck/ConcurrentLinkedQueueTest.java b/jdk/test/java/util/concurrent/tck/ConcurrentLinkedQueueTest.java index 1c3a65bb424..57689cce48d 100644 --- a/jdk/test/java/util/concurrent/tck/ConcurrentLinkedQueueTest.java +++ b/jdk/test/java/util/concurrent/tck/ConcurrentLinkedQueueTest.java @@ -66,7 +66,7 @@ public class ConcurrentLinkedQueueTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private ConcurrentLinkedQueue populatedQueue(int n) { - ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(); + ConcurrentLinkedQueue q = new ConcurrentLinkedQueue<>(); assertTrue(q.isEmpty()); for (int i = 0; i < n; ++i) assertTrue(q.offer(new Integer(i))); diff --git a/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java b/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java index 5863cd29cd2..329010b308b 100644 --- a/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java +++ b/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java @@ -54,7 +54,7 @@ public class CopyOnWriteArrayListTest extends JSR166TestCase { public static Test suite() { class Implementation implements CollectionImplementation { - public Class klazz() { return ArrayList.class; } + public Class klazz() { return CopyOnWriteArrayList.class; } public List emptyCollection() { return new CopyOnWriteArrayList(); } public Object makeElement(int i) { return i; } public boolean isConcurrent() { return true; } @@ -72,7 +72,7 @@ public class CopyOnWriteArrayListTest extends JSR166TestCase { } static CopyOnWriteArrayList populatedArray(int n) { - CopyOnWriteArrayList a = new CopyOnWriteArrayList(); + CopyOnWriteArrayList a = new CopyOnWriteArrayList<>(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) a.add(i); @@ -82,7 +82,7 @@ public class CopyOnWriteArrayListTest extends JSR166TestCase { } static CopyOnWriteArrayList populatedArray(Integer[] elements) { - CopyOnWriteArrayList a = new CopyOnWriteArrayList(); + CopyOnWriteArrayList a = new CopyOnWriteArrayList<>(); assertTrue(a.isEmpty()); for (int i = 0; i < elements.length; i++) a.add(elements[i]); diff --git a/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java b/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java index db7536856fe..2595589cc78 100644 --- a/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java +++ b/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java @@ -53,7 +53,7 @@ public class CopyOnWriteArraySetTest extends JSR166TestCase { } static CopyOnWriteArraySet populatedSet(int n) { - CopyOnWriteArraySet a = new CopyOnWriteArraySet(); + CopyOnWriteArraySet a = new CopyOnWriteArraySet<>(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) a.add(i); @@ -63,7 +63,7 @@ public class CopyOnWriteArraySetTest extends JSR166TestCase { } static CopyOnWriteArraySet populatedSet(Integer[] elements) { - CopyOnWriteArraySet a = new CopyOnWriteArraySet(); + CopyOnWriteArraySet a = new CopyOnWriteArraySet<>(); assertTrue(a.isEmpty()); for (int i = 0; i < elements.length; i++) a.add(elements[i]); diff --git a/jdk/test/java/util/concurrent/tck/CountedCompleterTest.java b/jdk/test/java/util/concurrent/tck/CountedCompleterTest.java index afd4ccf7aa6..3113b57a563 100644 --- a/jdk/test/java/util/concurrent/tck/CountedCompleterTest.java +++ b/jdk/test/java/util/concurrent/tck/CountedCompleterTest.java @@ -238,7 +238,7 @@ public class CountedCompleterTest extends JSR166TestCase { final AtomicInteger onCompletionN = new AtomicInteger(0); final AtomicInteger onExceptionalCompletionN = new AtomicInteger(0); final AtomicInteger setRawResultN = new AtomicInteger(0); - final AtomicReference rawResult = new AtomicReference(null); + final AtomicReference rawResult = new AtomicReference<>(null); int computeN() { return computeN.get(); } int onCompletionN() { return onCompletionN.get(); } int onExceptionalCompletionN() { return onExceptionalCompletionN.get(); } diff --git a/jdk/test/java/util/concurrent/tck/DelayQueueTest.java b/jdk/test/java/util/concurrent/tck/DelayQueueTest.java index 41fd569c47a..5711d32f3d1 100644 --- a/jdk/test/java/util/concurrent/tck/DelayQueueTest.java +++ b/jdk/test/java/util/concurrent/tck/DelayQueueTest.java @@ -79,20 +79,15 @@ public class DelayQueueTest extends JSR166TestCase { } /** - * A delayed implementation for testing. - * Most tests use Pseudodelays, where delays are all elapsed + * A fake Delayed implementation for testing. + * Most tests use PDelays, where delays are all elapsed * (so, no blocking solely for delays) but are still ordered */ static class PDelay implements Delayed { - int pseudodelay; - PDelay(int i) { pseudodelay = i; } - public int compareTo(PDelay other) { - int a = this.pseudodelay; - int b = other.pseudodelay; - return (a < b) ? -1 : (a > b) ? 1 : 0; - } + final int pseudodelay; + PDelay(int pseudodelay) { this.pseudodelay = pseudodelay; } public int compareTo(Delayed y) { - return compareTo((PDelay)y); + return Integer.compare(this.pseudodelay, ((PDelay)y).pseudodelay); } public boolean equals(Object other) { return (other instanceof PDelay) && @@ -112,20 +107,13 @@ public class DelayQueueTest extends JSR166TestCase { * Delayed implementation that actually delays */ static class NanoDelay implements Delayed { - long trigger; + final long trigger; NanoDelay(long i) { trigger = System.nanoTime() + i; } - public int compareTo(NanoDelay y) { - long i = trigger; - long j = y.trigger; - if (i < j) return -1; - if (i > j) return 1; - return 0; - } public int compareTo(Delayed y) { - return compareTo((NanoDelay)y); + return Long.compare(trigger, ((NanoDelay)y).trigger); } public boolean equals(Object other) { @@ -155,7 +143,7 @@ public class DelayQueueTest extends JSR166TestCase { * PDelays 0 ... n - 1. */ private DelayQueue populatedQueue(int n) { - DelayQueue q = new DelayQueue(); + DelayQueue q = new DelayQueue<>(); assertTrue(q.isEmpty()); for (int i = n - 1; i >= 0; i -= 2) assertTrue(q.offer(new PDelay(i))); @@ -713,7 +701,7 @@ public class DelayQueueTest extends JSR166TestCase { * Delayed actions do not occur until their delay elapses */ public void testDelay() throws InterruptedException { - DelayQueue q = new DelayQueue(); + DelayQueue q = new DelayQueue<>(); for (int i = 0; i < SIZE; ++i) q.add(new NanoDelay(1000000L * (SIZE - i))); diff --git a/jdk/test/java/util/concurrent/tck/ExecutorsTest.java b/jdk/test/java/util/concurrent/tck/ExecutorsTest.java index ec17b54b507..441a52a5922 100644 --- a/jdk/test/java/util/concurrent/tck/ExecutorsTest.java +++ b/jdk/test/java/util/concurrent/tck/ExecutorsTest.java @@ -308,7 +308,7 @@ public class ExecutorsTest extends JSR166TestCase { delay(LONG_DELAY_MS); }}; - List threads = new ArrayList(); + List threads = new ArrayList<>(); for (final ExecutorService executor : executors) { threads.add(newStartedThread(new CheckedRunnable() { public void realRun() { diff --git a/jdk/test/java/util/concurrent/tck/ForkJoinPoolTest.java b/jdk/test/java/util/concurrent/tck/ForkJoinPoolTest.java index 70004764a78..bf5a3652f09 100644 --- a/jdk/test/java/util/concurrent/tck/ForkJoinPoolTest.java +++ b/jdk/test/java/util/concurrent/tck/ForkJoinPoolTest.java @@ -658,7 +658,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAny3() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(null); try { e.invokeAny(l); @@ -674,7 +674,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { CountDownLatch latch = new CountDownLatch(1); ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -691,7 +691,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAny5() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -708,7 +708,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAny6() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -747,7 +747,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAll3() throws InterruptedException { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -764,7 +764,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAll4() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -783,7 +783,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testInvokeAll5() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -812,7 +812,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testTimedInvokeAnyNullTimeUnit() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -842,7 +842,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { CountDownLatch latch = new CountDownLatch(1); ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -860,7 +860,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -879,7 +879,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -907,7 +907,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testTimedInvokeAllNullTimeUnit() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -935,7 +935,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testTimedInvokeAll3() throws InterruptedException { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -951,7 +951,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testTimedInvokeAll4() throws Throwable { ExecutorService e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); @@ -971,7 +971,7 @@ public class ForkJoinPoolTest extends JSR166TestCase { public void testTimedInvokeAll5() throws Throwable { ForkJoinPool e = new ForkJoinPool(1); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures diff --git a/jdk/test/java/util/concurrent/tck/LinkedListTest.java b/jdk/test/java/util/concurrent/tck/LinkedListTest.java index 471d52db14d..08a2ddd9dab 100644 --- a/jdk/test/java/util/concurrent/tck/LinkedListTest.java +++ b/jdk/test/java/util/concurrent/tck/LinkedListTest.java @@ -71,7 +71,7 @@ public class LinkedListTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private LinkedList populatedQueue(int n) { - LinkedList q = new LinkedList(); + LinkedList q = new LinkedList<>(); assertTrue(q.isEmpty()); for (int i = 0; i < n; ++i) assertTrue(q.offer(new Integer(i))); diff --git a/jdk/test/java/util/concurrent/tck/LinkedTransferQueueTest.java b/jdk/test/java/util/concurrent/tck/LinkedTransferQueueTest.java index 6abec8a37d5..55965e6188a 100644 --- a/jdk/test/java/util/concurrent/tck/LinkedTransferQueueTest.java +++ b/jdk/test/java/util/concurrent/tck/LinkedTransferQueueTest.java @@ -209,7 +209,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { * all elements successfully put are contained */ public void testPut() { - LinkedTransferQueue q = new LinkedTransferQueue(); + LinkedTransferQueue q = new LinkedTransferQueue<>(); for (int i = 0; i < SIZE; ++i) { assertEquals(i, q.size()); q.put(i); @@ -442,7 +442,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { */ public void testContainsAll() { LinkedTransferQueue q = populatedQueue(SIZE); - LinkedTransferQueue p = new LinkedTransferQueue(); + LinkedTransferQueue p = new LinkedTransferQueue<>(); for (int i = 0; i < SIZE; ++i) { assertTrue(q.containsAll(p)); assertFalse(p.containsAll(q)); @@ -571,8 +571,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { * iterator ordering is FIFO */ public void testIteratorOrdering() { - final LinkedTransferQueue q - = new LinkedTransferQueue(); + final LinkedTransferQueue q = new LinkedTransferQueue<>(); assertEquals(Integer.MAX_VALUE, q.remainingCapacity()); q.add(one); q.add(two); @@ -794,8 +793,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { * is returned by this associated poll. */ public void testTransfer2() throws InterruptedException { - final LinkedTransferQueue q - = new LinkedTransferQueue(); + final LinkedTransferQueue q = new LinkedTransferQueue<>(); final CountDownLatch threadStarted = new CountDownLatch(1); Thread t = newStartedThread(new CheckedRunnable() { @@ -817,8 +815,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { * transfer waits until a poll occurs, and then transfers in fifo order */ public void testTransfer3() throws InterruptedException { - final LinkedTransferQueue q - = new LinkedTransferQueue(); + final LinkedTransferQueue q = new LinkedTransferQueue<>(); Thread first = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -874,8 +871,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { * is returned by this associated take. */ public void testTransfer5() throws InterruptedException { - final LinkedTransferQueue q - = new LinkedTransferQueue(); + final LinkedTransferQueue q = new LinkedTransferQueue<>(); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { @@ -1056,7 +1052,7 @@ public class LinkedTransferQueueTest extends JSR166TestCase { } private LinkedTransferQueue populatedQueue(int n) { - LinkedTransferQueue q = new LinkedTransferQueue(); + LinkedTransferQueue q = new LinkedTransferQueue<>(); checkEmpty(q); for (int i = 0; i < n; i++) { assertEquals(i, q.size()); diff --git a/jdk/test/java/util/concurrent/tck/PhaserTest.java b/jdk/test/java/util/concurrent/tck/PhaserTest.java index 69b6c808ff8..1b4d083d73c 100644 --- a/jdk/test/java/util/concurrent/tck/PhaserTest.java +++ b/jdk/test/java/util/concurrent/tck/PhaserTest.java @@ -329,7 +329,7 @@ public class PhaserTest extends JSR166TestCase { public void testArrive2() { final Phaser phaser = new Phaser(); assertEquals(0, phaser.register()); - List threads = new ArrayList(); + List threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { assertEquals(0, phaser.register()); threads.add(newStartedThread(new CheckedRunnable() { @@ -647,7 +647,7 @@ public class PhaserTest extends JSR166TestCase { public void testAwaitAdvance4() { final Phaser phaser = new Phaser(4); final AtomicInteger count = new AtomicInteger(0); - List threads = new ArrayList(); + List threads = new ArrayList<>(); for (int i = 0; i < 4; i++) threads.add(newStartedThread(new CheckedRunnable() { public void realRun() { @@ -671,7 +671,7 @@ public class PhaserTest extends JSR166TestCase { assertEquals(1, phaser.awaitAdvance(phaser.arrive())); assertEquals(1, phaser.getPhase()); assertEquals(1, phaser.register()); - List threads = new ArrayList(); + List threads = new ArrayList<>(); for (int i = 0; i < 8; i++) { final CountDownLatch latch = new CountDownLatch(1); final boolean goesFirst = ((i & 1) == 0); @@ -699,13 +699,13 @@ public class PhaserTest extends JSR166TestCase { */ public void testAwaitAdvanceTieredPhaser() throws Exception { final Phaser parent = new Phaser(); - final List zeroPartyChildren = new ArrayList(3); - final List onePartyChildren = new ArrayList(3); + final List zeroPartyChildren = new ArrayList<>(3); + final List onePartyChildren = new ArrayList<>(3); for (int i = 0; i < 3; i++) { zeroPartyChildren.add(new Phaser(parent, 0)); onePartyChildren.add(new Phaser(parent, 1)); } - final List phasers = new ArrayList(); + final List phasers = new ArrayList<>(); phasers.addAll(zeroPartyChildren); phasers.addAll(onePartyChildren); phasers.add(parent); @@ -747,7 +747,7 @@ public class PhaserTest extends JSR166TestCase { public void testAwaitAdvance6() { final Phaser phaser = new Phaser(3); final CountDownLatch pleaseForceTermination = new CountDownLatch(2); - final List threads = new ArrayList(); + final List threads = new ArrayList<>(); for (int i = 0; i < 2; i++) { Runnable r = new CheckedRunnable() { public void realRun() { @@ -791,7 +791,7 @@ public class PhaserTest extends JSR166TestCase { final Phaser phaser = new Phaser(1); final int THREADS = 3; final CountDownLatch pleaseArrive = new CountDownLatch(THREADS); - final List threads = new ArrayList(); + final List threads = new ArrayList<>(); for (int i = 0; i < THREADS; i++) threads.add(newStartedThread(new CheckedRunnable() { public void realRun() { diff --git a/jdk/test/java/util/concurrent/tck/PriorityQueueTest.java b/jdk/test/java/util/concurrent/tck/PriorityQueueTest.java index 91e155dd85b..c1564730cdf 100644 --- a/jdk/test/java/util/concurrent/tck/PriorityQueueTest.java +++ b/jdk/test/java/util/concurrent/tck/PriorityQueueTest.java @@ -71,7 +71,7 @@ public class PriorityQueueTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private PriorityQueue populatedQueue(int n) { - PriorityQueue q = new PriorityQueue(n); + PriorityQueue q = new PriorityQueue<>(n); assertTrue(q.isEmpty()); for (int i = n - 1; i >= 0; i -= 2) assertTrue(q.offer(new Integer(i))); diff --git a/jdk/test/java/util/concurrent/tck/ReentrantLockTest.java b/jdk/test/java/util/concurrent/tck/ReentrantLockTest.java index 8088498562a..9b032171103 100644 --- a/jdk/test/java/util/concurrent/tck/ReentrantLockTest.java +++ b/jdk/test/java/util/concurrent/tck/ReentrantLockTest.java @@ -236,7 +236,7 @@ public class ReentrantLockTest extends JSR166TestCase { public void testUnlock_IMSE() { testUnlock_IMSE(false); } public void testUnlock_IMSE_fair() { testUnlock_IMSE(true); } public void testUnlock_IMSE(boolean fair) { - ReentrantLock lock = new ReentrantLock(fair); + final ReentrantLock lock = new ReentrantLock(fair); try { lock.unlock(); shouldThrow(); @@ -426,11 +426,11 @@ public class ReentrantLockTest extends JSR166TestCase { public void testTryLock_Timeout_fair() { testTryLock_Timeout(true); } public void testTryLock_Timeout(boolean fair) { final PublicReentrantLock lock = new PublicReentrantLock(fair); + final long timeoutMillis = timeoutMillis(); lock.lock(); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { long startTime = System.nanoTime(); - long timeoutMillis = 10; assertFalse(lock.tryLock(timeoutMillis, MILLISECONDS)); assertTrue(millisElapsedSince(startTime) >= timeoutMillis); }}); @@ -445,7 +445,7 @@ public class ReentrantLockTest extends JSR166TestCase { public void testGetHoldCount() { testGetHoldCount(false); } public void testGetHoldCount_fair() { testGetHoldCount(true); } public void testGetHoldCount(boolean fair) { - ReentrantLock lock = new ReentrantLock(fair); + final ReentrantLock lock = new ReentrantLock(fair); for (int i = 1; i <= SIZE; i++) { lock.lock(); assertEquals(i, lock.getHoldCount()); @@ -462,8 +462,8 @@ public class ReentrantLockTest extends JSR166TestCase { public void testIsLocked() { testIsLocked(false); } public void testIsLocked_fair() { testIsLocked(true); } public void testIsLocked(boolean fair) { + final ReentrantLock lock = new ReentrantLock(fair); try { - final ReentrantLock lock = new ReentrantLock(fair); assertFalse(lock.isLocked()); lock.lock(); assertTrue(lock.isLocked()); @@ -550,18 +550,18 @@ public class ReentrantLockTest extends JSR166TestCase { public void testAwaitNanos_Timeout() { testAwaitNanos_Timeout(false); } public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); } public void testAwaitNanos_Timeout(boolean fair) { + final ReentrantLock lock = new ReentrantLock(fair); + final Condition c = lock.newCondition(); + final long timeoutMillis = timeoutMillis(); + final long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis); + lock.lock(); + final long startTime = System.nanoTime(); try { - final ReentrantLock lock = new ReentrantLock(fair); - final Condition c = lock.newCondition(); - lock.lock(); - long startTime = System.nanoTime(); - long timeoutMillis = 10; - long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis); long nanosRemaining = c.awaitNanos(timeoutNanos); assertTrue(nanosRemaining <= 0); - assertTrue(millisElapsedSince(startTime) >= timeoutMillis); - lock.unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + lock.unlock(); } /** @@ -570,16 +570,16 @@ public class ReentrantLockTest extends JSR166TestCase { public void testAwait_Timeout() { testAwait_Timeout(false); } public void testAwait_Timeout_fair() { testAwait_Timeout(true); } public void testAwait_Timeout(boolean fair) { + final ReentrantLock lock = new ReentrantLock(fair); + final Condition c = lock.newCondition(); + final long timeoutMillis = timeoutMillis(); + lock.lock(); + final long startTime = System.nanoTime(); try { - final ReentrantLock lock = new ReentrantLock(fair); - final Condition c = lock.newCondition(); - lock.lock(); - long startTime = System.nanoTime(); - long timeoutMillis = 10; assertFalse(c.await(timeoutMillis, MILLISECONDS)); - assertTrue(millisElapsedSince(startTime) >= timeoutMillis); - lock.unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + lock.unlock(); } /** @@ -588,17 +588,17 @@ public class ReentrantLockTest extends JSR166TestCase { public void testAwaitUntil_Timeout() { testAwaitUntil_Timeout(false); } public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); } public void testAwaitUntil_Timeout(boolean fair) { + final ReentrantLock lock = new ReentrantLock(fair); + final Condition c = lock.newCondition(); + lock.lock(); + // We shouldn't assume that nanoTime and currentTimeMillis + // use the same time source, so don't use nanoTime here. + final java.util.Date delayedDate = delayedDate(timeoutMillis()); try { - final ReentrantLock lock = new ReentrantLock(fair); - final Condition c = lock.newCondition(); - lock.lock(); - // We shouldn't assume that nanoTime and currentTimeMillis - // use the same time source, so don't use nanoTime here. - java.util.Date delayedDate = delayedDate(timeoutMillis()); assertFalse(c.awaitUntil(delayedDate)); - assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); - lock.unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); + lock.unlock(); } /** @@ -1127,7 +1127,7 @@ public class ReentrantLockTest extends JSR166TestCase { public void testSerialization() { testSerialization(false); } public void testSerialization_fair() { testSerialization(true); } public void testSerialization(boolean fair) { - ReentrantLock lock = new ReentrantLock(fair); + final ReentrantLock lock = new ReentrantLock(fair); lock.lock(); ReentrantLock clone = serialClone(lock); @@ -1153,10 +1153,10 @@ public class ReentrantLockTest extends JSR166TestCase { public void testToString() { testToString(false); } public void testToString_fair() { testToString(true); } public void testToString(boolean fair) { - ReentrantLock lock = new ReentrantLock(fair); + final ReentrantLock lock = new ReentrantLock(fair); assertTrue(lock.toString().contains("Unlocked")); lock.lock(); - assertTrue(lock.toString().contains("Locked")); + assertTrue(lock.toString().contains("Locked by")); lock.unlock(); assertTrue(lock.toString().contains("Unlocked")); } diff --git a/jdk/test/java/util/concurrent/tck/ReentrantReadWriteLockTest.java b/jdk/test/java/util/concurrent/tck/ReentrantReadWriteLockTest.java index a2e597e5eb7..55dc5dbca78 100644 --- a/jdk/test/java/util/concurrent/tck/ReentrantReadWriteLockTest.java +++ b/jdk/test/java/util/concurrent/tck/ReentrantReadWriteLockTest.java @@ -258,7 +258,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testGetWriteHoldCount() { testGetWriteHoldCount(false); } public void testGetWriteHoldCount_fair() { testGetWriteHoldCount(true); } public void testGetWriteHoldCount(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); for (int i = 1; i <= SIZE; i++) { lock.writeLock().lock(); assertEquals(i,lock.getWriteHoldCount()); @@ -275,7 +275,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testGetHoldCount() { testGetHoldCount(false); } public void testGetHoldCount_fair() { testGetHoldCount(true); } public void testGetHoldCount(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); for (int i = 1; i <= SIZE; i++) { lock.writeLock().lock(); assertEquals(i,lock.writeLock().getHoldCount()); @@ -292,7 +292,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testGetReadHoldCount() { testGetReadHoldCount(false); } public void testGetReadHoldCount_fair() { testGetReadHoldCount(true); } public void testGetReadHoldCount(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); for (int i = 1; i <= SIZE; i++) { lock.readLock().lock(); assertEquals(i,lock.getReadHoldCount()); @@ -309,7 +309,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testWriteUnlock_IMSE() { testWriteUnlock_IMSE(false); } public void testWriteUnlock_IMSE_fair() { testWriteUnlock_IMSE(true); } public void testWriteUnlock_IMSE(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); try { lock.writeLock().unlock(); shouldThrow(); @@ -322,7 +322,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testReadUnlock_IMSE() { testReadUnlock_IMSE(false); } public void testReadUnlock_IMSE_fair() { testReadUnlock_IMSE(true); } public void testReadUnlock_IMSE(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); try { lock.readLock().unlock(); shouldThrow(); @@ -815,11 +815,11 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testWriteTryLock_Timeout(boolean fair) { final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock(fair); + final long timeoutMillis = timeoutMillis(); lock.writeLock().lock(); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { long startTime = System.nanoTime(); - long timeoutMillis = 10; assertFalse(lock.writeLock().tryLock(timeoutMillis, MILLISECONDS)); assertTrue(millisElapsedSince(startTime) >= timeoutMillis); }}); @@ -839,7 +839,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { Thread t = newStartedThread(new CheckedRunnable() { public void realRun() throws InterruptedException { long startTime = System.nanoTime(); - long timeoutMillis = 10; + long timeoutMillis = timeoutMillis(); assertFalse(lock.readLock().tryLock(timeoutMillis, MILLISECONDS)); assertTrue(millisElapsedSince(startTime) >= timeoutMillis); }}); @@ -951,19 +951,18 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testAwaitNanos_Timeout() { testAwaitNanos_Timeout(false); } public void testAwaitNanos_Timeout_fair() { testAwaitNanos_Timeout(true); } public void testAwaitNanos_Timeout(boolean fair) { + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final Condition c = lock.writeLock().newCondition(); + final long timeoutMillis = timeoutMillis(); + lock.writeLock().lock(); + final long startTime = System.nanoTime(); + final long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis); try { - final ReentrantReadWriteLock lock = - new ReentrantReadWriteLock(fair); - final Condition c = lock.writeLock().newCondition(); - lock.writeLock().lock(); - long startTime = System.nanoTime(); - long timeoutMillis = 10; - long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis); long nanosRemaining = c.awaitNanos(timeoutNanos); assertTrue(nanosRemaining <= 0); - assertTrue(millisElapsedSince(startTime) >= timeoutMillis); - lock.writeLock().unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + lock.writeLock().unlock(); } /** @@ -972,17 +971,16 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testAwait_Timeout() { testAwait_Timeout(false); } public void testAwait_Timeout_fair() { testAwait_Timeout(true); } public void testAwait_Timeout(boolean fair) { + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final Condition c = lock.writeLock().newCondition(); + final long timeoutMillis = timeoutMillis(); + lock.writeLock().lock(); + final long startTime = System.nanoTime(); try { - final ReentrantReadWriteLock lock = - new ReentrantReadWriteLock(fair); - final Condition c = lock.writeLock().newCondition(); - lock.writeLock().lock(); - long startTime = System.nanoTime(); - long timeoutMillis = 10; assertFalse(c.await(timeoutMillis, MILLISECONDS)); - assertTrue(millisElapsedSince(startTime) >= timeoutMillis); - lock.writeLock().unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + lock.writeLock().unlock(); } /** @@ -991,18 +989,17 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testAwaitUntil_Timeout() { testAwaitUntil_Timeout(false); } public void testAwaitUntil_Timeout_fair() { testAwaitUntil_Timeout(true); } public void testAwaitUntil_Timeout(boolean fair) { + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final Condition c = lock.writeLock().newCondition(); + lock.writeLock().lock(); + // We shouldn't assume that nanoTime and currentTimeMillis + // use the same time source, so don't use nanoTime here. + final java.util.Date delayedDate = delayedDate(timeoutMillis()); try { - final ReentrantReadWriteLock lock = - new ReentrantReadWriteLock(fair); - final Condition c = lock.writeLock().newCondition(); - lock.writeLock().lock(); - // We shouldn't assume that nanoTime and currentTimeMillis - // use the same time source, so don't use nanoTime here. - java.util.Date delayedDate = delayedDate(timeoutMillis()); assertFalse(c.awaitUntil(delayedDate)); - assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); - lock.writeLock().unlock(); } catch (InterruptedException fail) { threadUnexpectedException(fail); } + assertTrue(new java.util.Date().getTime() >= delayedDate.getTime()); + lock.writeLock().unlock(); } /** @@ -1258,7 +1255,7 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testSerialization() { testSerialization(false); } public void testSerialization_fair() { testSerialization(true); } public void testSerialization(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); lock.writeLock().lock(); lock.readLock().lock(); @@ -1660,14 +1657,20 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testToString() { testToString(false); } public void testToString_fair() { testToString(true); } public void testToString(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); assertTrue(lock.toString().contains("Write locks = 0")); assertTrue(lock.toString().contains("Read locks = 0")); lock.writeLock().lock(); assertTrue(lock.toString().contains("Write locks = 1")); assertTrue(lock.toString().contains("Read locks = 0")); + lock.writeLock().lock(); + assertTrue(lock.toString().contains("Write locks = 2")); + assertTrue(lock.toString().contains("Read locks = 0")); + lock.writeLock().unlock(); lock.writeLock().unlock(); lock.readLock().lock(); + assertTrue(lock.toString().contains("Write locks = 0")); + assertTrue(lock.toString().contains("Read locks = 1")); lock.readLock().lock(); assertTrue(lock.toString().contains("Write locks = 0")); assertTrue(lock.toString().contains("Read locks = 2")); @@ -1679,11 +1682,16 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testReadLockToString() { testReadLockToString(false); } public void testReadLockToString_fair() { testReadLockToString(true); } public void testReadLockToString(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); assertTrue(lock.readLock().toString().contains("Read locks = 0")); lock.readLock().lock(); + assertTrue(lock.readLock().toString().contains("Read locks = 1")); lock.readLock().lock(); assertTrue(lock.readLock().toString().contains("Read locks = 2")); + lock.readLock().unlock(); + assertTrue(lock.readLock().toString().contains("Read locks = 1")); + lock.readLock().unlock(); + assertTrue(lock.readLock().toString().contains("Read locks = 0")); } /** @@ -1692,10 +1700,10 @@ public class ReentrantReadWriteLockTest extends JSR166TestCase { public void testWriteLockToString() { testWriteLockToString(false); } public void testWriteLockToString_fair() { testWriteLockToString(true); } public void testWriteLockToString(boolean fair) { - ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); + final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair); assertTrue(lock.writeLock().toString().contains("Unlocked")); lock.writeLock().lock(); - assertTrue(lock.writeLock().toString().contains("Locked")); + assertTrue(lock.writeLock().toString().contains("Locked by")); lock.writeLock().unlock(); assertTrue(lock.writeLock().toString().contains("Unlocked")); } diff --git a/jdk/test/java/util/concurrent/tck/ScheduledExecutorSubclassTest.java b/jdk/test/java/util/concurrent/tck/ScheduledExecutorSubclassTest.java index aaad2c93679..cd50421fea2 100644 --- a/jdk/test/java/util/concurrent/tck/ScheduledExecutorSubclassTest.java +++ b/jdk/test/java/util/concurrent/tck/ScheduledExecutorSubclassTest.java @@ -967,7 +967,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { final CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -984,7 +984,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testInvokeAny4() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -1001,7 +1001,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testInvokeAny5() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -1039,7 +1039,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testInvokeAll3() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1055,7 +1055,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testInvokeAll4() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1074,7 +1074,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testInvokeAll5() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -1103,7 +1103,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testTimedInvokeAnyNullTimeUnit() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -1132,7 +1132,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1150,7 +1150,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1169,7 +1169,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1197,7 +1197,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testTimedInvokeAllNullTimeUnit() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -1223,7 +1223,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testTimedInvokeAll3() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1239,7 +1239,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testTimedInvokeAll4() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS); @@ -1259,7 +1259,7 @@ public class ScheduledExecutorSubclassTest extends JSR166TestCase { public void testTimedInvokeAll5() throws Exception { final ExecutorService e = new CustomExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = diff --git a/jdk/test/java/util/concurrent/tck/ScheduledExecutorTest.java b/jdk/test/java/util/concurrent/tck/ScheduledExecutorTest.java index 0946d006276..46bb2c392ff 100644 --- a/jdk/test/java/util/concurrent/tck/ScheduledExecutorTest.java +++ b/jdk/test/java/util/concurrent/tck/ScheduledExecutorTest.java @@ -915,7 +915,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -932,7 +932,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testInvokeAny4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -949,7 +949,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testInvokeAny5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -987,7 +987,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testInvokeAll3() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1003,7 +1003,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testInvokeAll4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1022,7 +1022,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testInvokeAll5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -1051,7 +1051,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testTimedInvokeAnyNullTimeUnit() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -1080,7 +1080,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { CountDownLatch latch = new CountDownLatch(1); final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1098,7 +1098,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1117,7 +1117,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1145,7 +1145,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testTimedInvokeAllNullTimeUnit() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -1172,7 +1172,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testTimedInvokeAll3() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1188,7 +1188,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testTimedInvokeAll4() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); @@ -1208,7 +1208,7 @@ public class ScheduledExecutorTest extends JSR166TestCase { public void testTimedInvokeAll5() throws Exception { final ExecutorService e = new ScheduledThreadPoolExecutor(2); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = diff --git a/jdk/test/java/util/concurrent/tck/SubmissionPublisherTest.java b/jdk/test/java/util/concurrent/tck/SubmissionPublisherTest.java index 51279254bcd..2b4fea03a84 100644 --- a/jdk/test/java/util/concurrent/tck/SubmissionPublisherTest.java +++ b/jdk/test/java/util/concurrent/tck/SubmissionPublisherTest.java @@ -173,7 +173,7 @@ public class SubmissionPublisherTest extends JSR166TestCase { * defaultExecutor */ public void testConstructor1() { - SubmissionPublisher p = new SubmissionPublisher(); + SubmissionPublisher p = new SubmissionPublisher<>(); checkInitialState(p); assertEquals(p.getMaxBufferCapacity(), Flow.defaultBufferSize()); Executor e = p.getExecutor(), c = ForkJoinPool.commonPool(); @@ -189,7 +189,7 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testConstructor2() { Executor e = Executors.newFixedThreadPool(1); - SubmissionPublisher p = new SubmissionPublisher(e, 8); + SubmissionPublisher p = new SubmissionPublisher<>(e, 8); checkInitialState(p); assertSame(p.getExecutor(), e); assertEquals(8, p.getMaxBufferCapacity()); @@ -471,9 +471,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testThrowOnNextHandler() { AtomicInteger calls = new AtomicInteger(); - SubmissionPublisher p = new SubmissionPublisher - (basicExecutor, 8, - (s, e) -> calls.getAndIncrement()); + SubmissionPublisher p = new SubmissionPublisher<>( + basicExecutor, 8, (s, e) -> calls.getAndIncrement()); TestSubscriber s1 = new TestSubscriber(); TestSubscriber s2 = new TestSubscriber(); p.subscribe(s1); @@ -654,8 +653,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { * submit eventually issues requested items when buffer capacity is 1 */ public void testCap1Submit() { - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 1); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 1); TestSubscriber s1 = new TestSubscriber(); TestSubscriber s2 = new TestSubscriber(); p.subscribe(s1); @@ -733,8 +732,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { * offer reports drops if saturated */ public void testDroppedOffer() { - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); @@ -762,8 +761,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testHandledDroppedOffer() { AtomicInteger calls = new AtomicInteger(); - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); @@ -790,8 +789,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testRecoveredHandledDroppedOffer() { AtomicInteger calls = new AtomicInteger(); - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); @@ -871,8 +870,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { * Timed offer reports drops if saturated */ public void testDroppedTimedOffer() { - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); @@ -903,8 +902,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testHandledDroppedTimedOffer() { AtomicInteger calls = new AtomicInteger(); - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); @@ -933,8 +932,8 @@ public class SubmissionPublisherTest extends JSR166TestCase { */ public void testRecoveredHandledDroppedTimedOffer() { AtomicInteger calls = new AtomicInteger(); - SubmissionPublisher p = new SubmissionPublisher( - basicExecutor, 4); + SubmissionPublisher p + = new SubmissionPublisher<>(basicExecutor, 4); TestSubscriber s1 = new TestSubscriber(); s1.request = false; TestSubscriber s2 = new TestSubscriber(); diff --git a/jdk/test/java/util/concurrent/tck/SynchronousQueueTest.java b/jdk/test/java/util/concurrent/tck/SynchronousQueueTest.java index b4529801928..345ac9c7305 100644 --- a/jdk/test/java/util/concurrent/tck/SynchronousQueueTest.java +++ b/jdk/test/java/util/concurrent/tck/SynchronousQueueTest.java @@ -428,8 +428,7 @@ public class SynchronousQueueTest extends JSR166TestCase { public void testToArray2() { testToArray2(false); } public void testToArray2_fair() { testToArray2(true); } public void testToArray2(boolean fair) { - final SynchronousQueue q - = new SynchronousQueue(fair); + final SynchronousQueue q = new SynchronousQueue<>(fair); Integer[] a; a = new Integer[0]; diff --git a/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorSubclassTest.java b/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorSubclassTest.java index 83a4f42412c..38862ceee5d 100644 --- a/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorSubclassTest.java +++ b/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorSubclassTest.java @@ -678,7 +678,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { */ public void testGetQueue() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); - final BlockingQueue q = new ArrayBlockingQueue(10); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -687,7 +687,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { final CountDownLatch threadStarted = new CountDownLatch(1); FutureTask[] tasks = new FutureTask[5]; for (int i = 0; i < tasks.length; i++) { - Callable task = new CheckedCallable() { + Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); assertSame(q, p.getQueue()); @@ -710,7 +710,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { */ public void testRemove() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); - BlockingQueue q = new ArrayBlockingQueue(10); + BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -745,7 +745,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { public void testPurge() throws InterruptedException { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - final BlockingQueue q = new ArrayBlockingQueue(10); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -753,7 +753,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { try (PoolCleaner cleaner = cleaner(p, done)) { FutureTask[] tasks = new FutureTask[5]; for (int i = 0; i < tasks.length; i++) { - Callable task = new CheckedCallable() { + Callable task = new CheckedCallable() { public Boolean realCall() throws InterruptedException { threadStarted.countDown(); await(done); @@ -1532,7 +1532,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1552,7 +1552,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -1572,7 +1572,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -1619,7 +1619,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1638,7 +1638,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1660,7 +1660,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -1695,7 +1695,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -1731,7 +1731,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1752,7 +1752,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1774,7 +1774,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1808,7 +1808,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -1841,7 +1841,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1860,7 +1860,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); @@ -1883,7 +1883,7 @@ public class ThreadPoolExecutorSubclassTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = diff --git a/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorTest.java b/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorTest.java index 8a72586f3ae..cf0b0971270 100644 --- a/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorTest.java +++ b/jdk/test/java/util/concurrent/tck/ThreadPoolExecutorTest.java @@ -563,7 +563,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { */ public void testGetQueue() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); - final BlockingQueue q = new ArrayBlockingQueue(10); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -595,7 +595,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { */ public void testRemove() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); - BlockingQueue q = new ArrayBlockingQueue(10); + BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -630,7 +630,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { public void testPurge() throws InterruptedException { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); - final BlockingQueue q = new ArrayBlockingQueue(10); + final BlockingQueue q = new ArrayBlockingQueue<>(10); final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, @@ -1534,7 +1534,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1554,7 +1554,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l); @@ -1574,7 +1574,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l); @@ -1621,7 +1621,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1640,7 +1640,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l); assertEquals(1, futures.size()); @@ -1662,7 +1662,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = e.invokeAll(l); @@ -1697,7 +1697,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAny(l, MEDIUM_DELAY_MS, null); @@ -1733,7 +1733,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(latchAwaitingStringTask(latch)); l.add(null); try { @@ -1754,7 +1754,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); try { e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1776,7 +1776,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { long startTime = System.nanoTime(); - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS); @@ -1810,7 +1810,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); try { e.invokeAll(l, MEDIUM_DELAY_MS, null); @@ -1843,7 +1843,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(null); try { @@ -1862,7 +1862,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new NPETask()); List> futures = e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS); @@ -1885,7 +1885,7 @@ public class ThreadPoolExecutorTest extends JSR166TestCase { LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue(10)); try (PoolCleaner cleaner = cleaner(e)) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); List> futures = diff --git a/jdk/test/java/util/concurrent/tck/TreeSetTest.java b/jdk/test/java/util/concurrent/tck/TreeSetTest.java index af37e4c0550..a37922e525b 100644 --- a/jdk/test/java/util/concurrent/tck/TreeSetTest.java +++ b/jdk/test/java/util/concurrent/tck/TreeSetTest.java @@ -70,7 +70,7 @@ public class TreeSetTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private TreeSet populatedSet(int n) { - TreeSet q = new TreeSet(); + TreeSet q = new TreeSet<>(); assertTrue(q.isEmpty()); for (int i = n - 1; i >= 0; i -= 2) assertTrue(q.add(new Integer(i))); diff --git a/jdk/test/java/util/concurrent/tck/TreeSubSetTest.java b/jdk/test/java/util/concurrent/tck/TreeSubSetTest.java index b8cc70ae83d..37edc1fb04c 100644 --- a/jdk/test/java/util/concurrent/tck/TreeSubSetTest.java +++ b/jdk/test/java/util/concurrent/tck/TreeSubSetTest.java @@ -61,7 +61,7 @@ public class TreeSubSetTest extends JSR166TestCase { * Integers 0 ... n - 1. */ private NavigableSet populatedSet(int n) { - TreeSet q = new TreeSet(); + TreeSet q = new TreeSet<>(); assertTrue(q.isEmpty()); for (int i = n - 1; i >= 0; i -= 2) From b1af5af0c8b26951498210ff228c35790e1bb33e Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Fri, 3 Feb 2017 18:06:45 -0800 Subject: [PATCH 122/130] 8173412: @Test in java/lang/annotation and java/lang/reflect/Proxy tests not run Reviewed-by: redestad --- jdk/test/java/lang/annotation/AnnotationWithLambda.java | 2 +- jdk/test/java/lang/reflect/Proxy/ProxyForMethodHandle.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/test/java/lang/annotation/AnnotationWithLambda.java b/jdk/test/java/lang/annotation/AnnotationWithLambda.java index ac213522923..1ca2e0950e8 100644 --- a/jdk/test/java/lang/annotation/AnnotationWithLambda.java +++ b/jdk/test/java/lang/annotation/AnnotationWithLambda.java @@ -43,7 +43,7 @@ import static org.testng.Assert.*; public class AnnotationWithLambda { @Test - void testAnnotationWithLambda() { + public void testAnnotationWithLambda() { Method[] methods = AnnotationWithLambda.MethodsWithAnnotations.class.getDeclaredMethods(); for (Method method : methods) { assertTrue((method.isAnnotationPresent(LambdaWithParameter.class)) && diff --git a/jdk/test/java/lang/reflect/Proxy/ProxyForMethodHandle.java b/jdk/test/java/lang/reflect/Proxy/ProxyForMethodHandle.java index bbe74b66ecf..1c45901783d 100644 --- a/jdk/test/java/lang/reflect/Proxy/ProxyForMethodHandle.java +++ b/jdk/test/java/lang/reflect/Proxy/ProxyForMethodHandle.java @@ -46,7 +46,7 @@ public class ProxyForMethodHandle { * to a dynamic module */ @Test - static void testRunnableMethodHandle() throws Exception { + public static void testRunnableMethodHandle() throws Exception { MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodType mt = MethodType.methodType(void.class); MethodHandle mh = lookup.findStatic(ProxyForMethodHandle.class, "runForRunnable", mt); From 08bae4d771e4ecd70ab450b28832914068a1cf91 Mon Sep 17 00:00:00 2001 From: Lance Andersen Date: Sat, 4 Feb 2017 14:02:14 -0500 Subject: [PATCH 123/130] 8173604: Rename module 8173604 java.annotations.common to java.xml.ws.annoations Reviewed-by: dfuchs, alanb, psandoz, mchung --- common/bin/unshuffle_list.txt | 2 +- make/common/Modules.gmk | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/common/bin/unshuffle_list.txt b/common/bin/unshuffle_list.txt index 0b5d6a5d61a..e5fe5af121d 100644 --- a/common/bin/unshuffle_list.txt +++ b/common/bin/unshuffle_list.txt @@ -60,7 +60,7 @@ jaxp/src/java.xml/share/classes/org/xml/sax : jaxp/src/org/xml/sax jaxws/src/java.activation/share/classes/com/sun/activation/registries : jaxws/src/share/jaf_classes/com/sun/activation/registries jaxws/src/java.activation/share/classes/javax/activation : jaxws/src/share/jaf_classes/javax/activation jaxws/src/java.activation/share/classes/META-INF : jaxws/src/share/jaf_classes/META-INF -jaxws/src/java.annotations.common/share/classes/javax/annotation : jaxws/src/share/jaxws_classes/javax/annotation +jaxws/src/java.xml.ws.annotation/share/classes/javax/annotation : jaxws/src/share/jaxws_classes/javax/annotation jaxws/src/java.xml.bind/share/classes/com/sun/istack/internal : jaxws/src/share/jaxws_classes/com/sun/istack/internal jaxws/src/java.xml.bind/share/classes/com/sun/istack/internal/localization : jaxws/src/share/jaxws_classes/com/sun/istack/internal/localization jaxws/src/java.xml.bind/share/classes/com/sun/istack/internal/logging/Logger.java : jaxws/src/share/jaxws_classes/com/sun/istack/internal/logging/Logger.java diff --git a/make/common/Modules.gmk b/make/common/Modules.gmk index 087bcefec89..4ceb4513623 100644 --- a/make/common/Modules.gmk +++ b/make/common/Modules.gmk @@ -73,11 +73,11 @@ BOOT_MODULES += \ UPGRADEABLE_MODULES += \ java.activation \ - java.annotations.common \ java.corba \ java.transaction \ java.xml.bind \ java.xml.ws \ + java.xml.ws.annotation \ # # Modules explicitly declared as not being upgradeable even though they require From 5f5028bec091a0b5406f47dbc5512c34aa51cc16 Mon Sep 17 00:00:00 2001 From: Lance Andersen Date: Sat, 4 Feb 2017 14:04:28 -0500 Subject: [PATCH 124/130] 8173604: Rename module 8173604 java.annotations.common to java.xml.ws.annoations Reviewed-by: dfuchs, alanb, psandoz, mchung --- jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java | 4 ++-- .../src/classes/build/tools/jigsaw/technology-summary.html | 2 +- jdk/src/java.se.ee/share/classes/module-info.java | 4 ++-- jdk/test/tools/launcher/modules/addmods/AddModsTest.java | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java index 99f6d0f8bd7..4de7b5c719a 100644 --- a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java +++ b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -126,7 +126,7 @@ public class GenGraphs { ranks.add(Set.of("java.compiler", "java.instrument")); ranks.add(Set.of("java.desktop", "java.management")); ranks.add(Set.of("java.corba", "java.xml.ws")); - ranks.add(Set.of("java.xml.bind", "java.annotations.common")); + ranks.add(Set.of("java.xml.bind", "java.xml.ws.annotation")); } diff --git a/jdk/make/src/classes/build/tools/jigsaw/technology-summary.html b/jdk/make/src/classes/build/tools/jigsaw/technology-summary.html index 8414f3521ec..e42ed25b728 100644 --- a/jdk/make/src/classes/build/tools/jigsaw/technology-summary.html +++ b/jdk/make/src/classes/build/tools/jigsaw/technology-summary.html @@ -588,7 +588,7 @@ td { font-family: monospace; padding: 4px; border: 1px solid; } Common Annotations 250 Java SE,EE -java.annotations.common +java.xml.ws.annotation Original JSR Formerly a Standalone Technology (unlisted) SE diff --git a/jdk/src/java.se.ee/share/classes/module-info.java b/jdk/src/java.se.ee/share/classes/module-info.java index 6e2bc056afa..a9caf752162 100644 --- a/jdk/src/java.se.ee/share/classes/module-info.java +++ b/jdk/src/java.se.ee/share/classes/module-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,10 +36,10 @@ module java.se.ee { // Upgradeable modules for Java EE technologies requires transitive java.activation; - requires transitive java.annotations.common; requires transitive java.corba; requires transitive java.transaction; requires transitive java.xml.bind; requires transitive java.xml.ws; + requires transitive java.xml.ws.annotation; } diff --git a/jdk/test/tools/launcher/modules/addmods/AddModsTest.java b/jdk/test/tools/launcher/modules/addmods/AddModsTest.java index 3a7a320bafa..d60c2ea7446 100644 --- a/jdk/test/tools/launcher/modules/addmods/AddModsTest.java +++ b/jdk/test/tools/launcher/modules/addmods/AddModsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,7 +98,7 @@ public class AddModsTest { } /** - * Basic test of --add-modules ALL-DEFAULT. Module java.annotations.common + * Basic test of --add-modules ALL-DEFAULT. Module java.xml.ws.annotation * should not resolved and so the types in that module should not be * visible. */ From 996177e4f01b4f7f88524cb4dd1c6092611cfe9e Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Mon, 6 Feb 2017 11:07:09 +0100 Subject: [PATCH 125/130] 8173653: jshell tool: ctrl-C when in external editor aborts jshell -- history lost Adding ability for WindowsTerminal subclasses to get and set console mode. Reviewed-by: rfield --- .../share/classes/jdk/internal/jline/WindowsTerminal.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/WindowsTerminal.java b/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/WindowsTerminal.java index 09b1f2f95ab..c9d471d2ae5 100644 --- a/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/WindowsTerminal.java +++ b/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/WindowsTerminal.java @@ -314,9 +314,9 @@ public class WindowsTerminal private static native void initIDs(); - private native int getConsoleMode(); + protected native int getConsoleMode(); - private native void setConsoleMode(int mode); + protected native void setConsoleMode(int mode); private byte[] readConsoleInput() { KEY_EVENT_RECORD keyEvent = readKeyEvent(); From 779401fbbff093e3878f8df1c1880f627f14f2a5 Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Mon, 6 Feb 2017 08:59:00 -0500 Subject: [PATCH 126/130] 8173827: Remove forRemoval=true from several deprecated security APIs Reviewed-by: redestad, xuelei --- .../classes/com/sun/net/ssl/HostnameVerifier.java | 5 ++--- .../com/sun/net/ssl/HttpsURLConnection.java | 5 ++--- .../share/classes/com/sun/net/ssl/KeyManager.java | 5 ++--- .../classes/com/sun/net/ssl/KeyManagerFactory.java | 5 ++--- .../com/sun/net/ssl/KeyManagerFactorySpi.java | 5 ++--- .../share/classes/com/sun/net/ssl/SSLContext.java | 5 ++--- .../classes/com/sun/net/ssl/SSLContextSpi.java | 5 ++--- .../classes/com/sun/net/ssl/SSLPermission.java | 5 ++--- .../classes/com/sun/net/ssl/TrustManager.java | 5 ++--- .../com/sun/net/ssl/TrustManagerFactory.java | 5 ++--- .../com/sun/net/ssl/TrustManagerFactorySpi.java | 5 ++--- .../classes/com/sun/net/ssl/X509KeyManager.java | 5 ++--- .../classes/com/sun/net/ssl/X509TrustManager.java | 5 ++--- .../com/sun/net/ssl/internal/ssl/Provider.java | 6 ++---- .../ssl/internal/ssl/X509ExtendedTrustManager.java | 5 ++--- .../protocol/https/DelegateHttpsURLConnection.java | 5 ++--- .../ssl/internal/www/protocol/https/Handler.java | 5 ++--- .../protocol/https/HttpsURLConnectionOldImpl.java | 5 ++--- .../share/classes/java/security/Certificate.java | 5 ++--- .../share/classes/java/security/Identity.java | 11 +++++------ .../share/classes/java/security/IdentityScope.java | 14 +++++--------- .../share/classes/java/security/Signer.java | 11 +++++------ .../share/classes/java/security/acl/Acl.java | 5 ++--- .../share/classes/java/security/acl/AclEntry.java | 5 ++--- .../java/security/acl/AclNotFoundException.java | 5 ++--- .../share/classes/java/security/acl/Group.java | 5 ++--- .../java/security/acl/LastOwnerException.java | 5 ++--- .../java/security/acl/NotOwnerException.java | 5 ++--- .../share/classes/java/security/acl/Owner.java | 5 ++--- .../classes/java/security/acl/Permission.java | 5 ++--- .../classes/java/security/acl/package-info.java | 5 ++--- .../javax/net/ssl/HandshakeCompletedEvent.java | 9 ++++----- .../share/classes/javax/net/ssl/SSLSession.java | 9 ++++----- .../share/classes/javax/security/auth/Policy.java | 5 ++--- .../classes/javax/security/cert/Certificate.java | 5 ++--- .../cert/CertificateEncodingException.java | 5 ++--- .../javax/security/cert/CertificateException.java | 5 ++--- .../security/cert/CertificateExpiredException.java | 5 ++--- .../cert/CertificateNotYetValidException.java | 5 ++--- .../security/cert/CertificateParsingException.java | 5 ++--- .../javax/security/cert/X509Certificate.java | 5 ++--- 41 files changed, 95 insertions(+), 140 deletions(-) diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/HostnameVerifier.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/HostnameVerifier.java index 1a78995ec01..f6413802395 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/HostnameVerifier.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/HostnameVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,9 +38,8 @@ package com.sun.net.ssl; * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.HostnameVerifier} and * {@link javax.net.ssl.CertificateHostnameVerifier}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public interface HostnameVerifier { /** * Verify that the hostname from the URL is an acceptable diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java index 895b17ac578..8a1e69f9d5f 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,9 +44,8 @@ import javax.net.ssl.SSLPeerUnverifiedException; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.HttpsURLConnection}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public abstract class HttpsURLConnection extends HttpURLConnection { diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java index 814d619db8d..903e2578e79 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,8 +36,7 @@ package com.sun.net.ssl; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.KeyManager}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public interface KeyManager { } diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java index 8c0caed6b0e..c79ef43c2b6 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,9 +39,8 @@ import java.security.*; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.KeyManagerFactory}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public class KeyManagerFactory { // The provider private Provider provider; diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactorySpi.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactorySpi.java index 19b2a68b6f5..eb72c96954d 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactorySpi.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactorySpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,9 +41,8 @@ import java.security.*; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.KeyManagerFactorySpi}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public abstract class KeyManagerFactorySpi { /** * Initializes this factory with a source of key material. The diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java index 6f0cbf9fd9b..d23148b18f8 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,9 +44,8 @@ import sun.security.ssl.SSLServerSocketFactoryImpl; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.SSLContext}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public class SSLContext { private Provider provider; diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContextSpi.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContextSpi.java index 0a663b8ff3f..993f86f614d 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContextSpi.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLContextSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,9 +43,8 @@ import javax.net.ssl.*; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.SSLContextSpi}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public abstract class SSLContextSpi { /** * Initializes this context. diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLPermission.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLPermission.java index 9fd480b93f3..93469a0c867 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLPermission.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/SSLPermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,9 +97,8 @@ import java.lang.SecurityManager; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.SSLPermission}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public final class SSLPermission extends BasicPermission { private static final long serialVersionUID = -2583684302506167542L; diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java index 2856e30be40..376b111fd81 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,8 +36,7 @@ package com.sun.net.ssl; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.TrustManager}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public interface TrustManager { } diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java index 934210c618b..d011ce74ed1 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,9 +39,8 @@ import java.security.*; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.TrustManagerFactory}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public class TrustManagerFactory { // The provider private Provider provider; diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java index 62698a42d32..8ab1901c4ea 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,9 +41,8 @@ import java.security.*; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.TrustManagerFactorySpi}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public abstract class TrustManagerFactorySpi { /** * Initializes this factory with a source of certificate diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java index cb4903171a7..8d4019c8721 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,9 +41,8 @@ import java.security.cert.X509Certificate; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.X509KeyManager}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public interface X509KeyManager extends KeyManager { /** * Get the matching aliases for authenticating the client side of a secure diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java index 024d33a16f5..041c3e6f587 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,9 +40,8 @@ import java.security.cert.X509Certificate; * * @deprecated As of JDK 1.4, this implementation-specific class was * replaced by {@link javax.net.ssl.X509TrustManager}. - * This class is subject to removal in a future version of JDK. */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public interface X509TrustManager extends TrustManager { /** * Given the partial or complete certificate chain diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java index f438e6401fd..f158f88bda1 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,10 +31,8 @@ import sun.security.ssl.SunJSSE; * Main class for the SunJSSE provider. The actual code was moved to the * class sun.security.ssl.SunJSSE, but for backward compatibility we * continue to use this class as the main Provider class. - * - * @deprecated This class is subject to removal in a future version of JDK. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public final class Provider extends SunJSSE { private static final long serialVersionUID = 3231825739635378733L; diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java index 3db161b83e4..2af41b97fe5 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,9 +54,8 @@ import java.security.cert.CertificateException; * * @since 1.6 * @author Xuelei Fan - * @deprecated This class is subject to removal in a future version of JDK. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public abstract class X509ExtendedTrustManager implements X509TrustManager { /** * Constructor used by subclasses only. diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java index 8cb1de2b22c..872694f6176 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,9 +52,8 @@ import sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection; * of protocol implementation (this one) * com.sun.net.ssl.HttpURLConnection is used in the com.sun version. * - * @deprecated This class is subject to removal in a future version of JDK. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") @SuppressWarnings("deprecation") // HttpsURLConnection is deprecated public class DelegateHttpsURLConnection extends AbstractDelegateHttpsURLConnection { diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java index d52e972646e..42874841bfc 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,9 +34,8 @@ import java.net.Proxy; * only. The HTTPS implementation can now be found in * sun.net.www.protocol.https. * - * @deprecated This class is subject to removal in a future version of JDK. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class Handler extends sun.net.www.protocol.https.Handler { public Handler() { diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java index 7ae757fe6f2..fc9f7ce861b 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,13 +60,12 @@ import sun.net.www.http.HttpClient; * needs to implement all public methods in it's super class and all * the way to Object. * - * @deprecated This class is subject to removal in a future version of JDK. */ // For both copies of the file, uncomment one line and comment the other // public class HttpsURLConnectionImpl // extends javax.net.ssl.HttpsURLConnection { -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") @SuppressWarnings("deprecation") // HttpsURLConnection is deprecated public class HttpsURLConnectionOldImpl extends com.sun.net.ssl.HttpsURLConnection { diff --git a/jdk/src/java.base/share/classes/java/security/Certificate.java b/jdk/src/java.base/share/classes/java/security/Certificate.java index 4fe278aa431..2d3db8f0383 100644 --- a/jdk/src/java.base/share/classes/java/security/Certificate.java +++ b/jdk/src/java.base/share/classes/java/security/Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,10 +60,9 @@ import java.util.Date; * This Certificate interface is entirely deprecated and * is here to allow for a smooth transition to the new * package. - * This class is subject to removal in a future version of Java SE. * @see java.security.cert.Certificate */ -@Deprecated(since="1.2", forRemoval=true) +@Deprecated(since="1.2") public interface Certificate { /** diff --git a/jdk/src/java.base/share/classes/java/security/Identity.java b/jdk/src/java.base/share/classes/java/security/Identity.java index 44713c4906f..d091b942e26 100644 --- a/jdk/src/java.base/share/classes/java/security/Identity.java +++ b/jdk/src/java.base/share/classes/java/security/Identity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,12 +52,11 @@ import java.util.*; * * @author Benjamin Renaud * @deprecated This class is no longer used. Its functionality has been - * replaced by {@link java.security.KeyStore}, the - * {@link java.security.cert} package, and - * {@link java.security.Principal}. - * This class is subject to removal in a future version of Java SE. + * replaced by {@code java.security.KeyStore}, the + * {@code java.security.cert} package, and + * {@code java.security.Principal}. */ -@Deprecated(since="1.2", forRemoval=true) +@Deprecated(since="1.2") public abstract class Identity implements Principal, Serializable { /** use serialVersionUID from JDK 1.1.x for interoperability */ diff --git a/jdk/src/java.base/share/classes/java/security/IdentityScope.java b/jdk/src/java.base/share/classes/java/security/IdentityScope.java index e07d724438a..107fe0861ad 100644 --- a/jdk/src/java.base/share/classes/java/security/IdentityScope.java +++ b/jdk/src/java.base/share/classes/java/security/IdentityScope.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,15 +57,11 @@ import java.util.Properties; * @author Benjamin Renaud * * @deprecated This class is no longer used. Its functionality has been - * replaced by {@link java.security.KeyStore}, the - * {@link java.security.cert} package, and - * {@link java.security.Principal}. - * This class is subject to removal in a future version of Java SE. - * - * Note that the security property {@code policy.ignoreIdentityScope} - * is only applicable to these APIs and is also a candidate for removal. + * replaced by {@code java.security.KeyStore}, the + * {@code java.security.cert} package, and + * {@code java.security.Principal}. */ -@Deprecated(since="1.2", forRemoval=true) +@Deprecated(since="1.2") public abstract class IdentityScope extends Identity { diff --git a/jdk/src/java.base/share/classes/java/security/Signer.java b/jdk/src/java.base/share/classes/java/security/Signer.java index 93c6ff73af5..3c53f6c055f 100644 --- a/jdk/src/java.base/share/classes/java/security/Signer.java +++ b/jdk/src/java.base/share/classes/java/security/Signer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,12 +40,11 @@ import java.io.*; * @author Benjamin Renaud * * @deprecated This class is no longer used. Its functionality has been - * replaced by {@link java.security.KeyStore}, the - * {@link java.security.cert} package, and - * {@link java.security.Principal}. - * This class is subject to removal in a future version of Java SE. + * replaced by {@code java.security.KeyStore}, the + * {@code java.security.cert} package, and + * {@code java.security.Principal}. */ -@Deprecated(since="1.2", forRemoval=true) +@Deprecated(since="1.2") public abstract class Signer extends Identity { private static final long serialVersionUID = -1763464102261361480L; diff --git a/jdk/src/java.base/share/classes/java/security/acl/Acl.java b/jdk/src/java.base/share/classes/java/security/acl/Acl.java index 1a00125879c..0b2f374a2c9 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/Acl.java +++ b/jdk/src/java.base/share/classes/java/security/acl/Acl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -85,10 +85,9 @@ import java.security.Principal; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public interface Acl extends Owner { /** diff --git a/jdk/src/java.base/share/classes/java/security/acl/AclEntry.java b/jdk/src/java.base/share/classes/java/security/acl/AclEntry.java index 212b7341784..b785a05f3d7 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/AclEntry.java +++ b/jdk/src/java.base/share/classes/java/security/acl/AclEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,9 +53,8 @@ import java.security.Principal; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public interface AclEntry extends Cloneable { /** diff --git a/jdk/src/java.base/share/classes/java/security/acl/AclNotFoundException.java b/jdk/src/java.base/share/classes/java/security/acl/AclNotFoundException.java index c1bf55a3aa8..c07852c5490 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/AclNotFoundException.java +++ b/jdk/src/java.base/share/classes/java/security/acl/AclNotFoundException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,9 +33,8 @@ package java.security.acl; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class AclNotFoundException extends Exception { private static final long serialVersionUID = 5684295034092681791L; diff --git a/jdk/src/java.base/share/classes/java/security/acl/Group.java b/jdk/src/java.base/share/classes/java/security/acl/Group.java index 50bf2dd4e38..f68d5dae13c 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/Group.java +++ b/jdk/src/java.base/share/classes/java/security/acl/Group.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,9 +42,8 @@ import java.security.Principal; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public interface Group extends Principal { /** diff --git a/jdk/src/java.base/share/classes/java/security/acl/LastOwnerException.java b/jdk/src/java.base/share/classes/java/security/acl/LastOwnerException.java index bae12d06795..dab93db9c1e 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/LastOwnerException.java +++ b/jdk/src/java.base/share/classes/java/security/acl/LastOwnerException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,9 +35,8 @@ package java.security.acl; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class LastOwnerException extends Exception { private static final long serialVersionUID = -5141997548211140359L; diff --git a/jdk/src/java.base/share/classes/java/security/acl/NotOwnerException.java b/jdk/src/java.base/share/classes/java/security/acl/NotOwnerException.java index 74519606bf6..3c7da3ebc8a 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/NotOwnerException.java +++ b/jdk/src/java.base/share/classes/java/security/acl/NotOwnerException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,9 +34,8 @@ package java.security.acl; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class NotOwnerException extends Exception { private static final long serialVersionUID = -5555597911163362399L; diff --git a/jdk/src/java.base/share/classes/java/security/acl/Owner.java b/jdk/src/java.base/share/classes/java/security/acl/Owner.java index 8f88a1150a9..476af4a0a80 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/Owner.java +++ b/jdk/src/java.base/share/classes/java/security/acl/Owner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,9 +38,8 @@ import java.security.Principal; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public interface Owner { /** diff --git a/jdk/src/java.base/share/classes/java/security/acl/Permission.java b/jdk/src/java.base/share/classes/java/security/acl/Permission.java index bcccf167cce..15b77429413 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/Permission.java +++ b/jdk/src/java.base/share/classes/java/security/acl/Permission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,9 +34,8 @@ package java.security.acl; * * @deprecated This package has been replaced by {@code java.security.Policy} * and related classes since 1.2. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public interface Permission { /** diff --git a/jdk/src/java.base/share/classes/java/security/acl/package-info.java b/jdk/src/java.base/share/classes/java/security/acl/package-info.java index fdbb6dcd268..25c17392241 100644 --- a/jdk/src/java.base/share/classes/java/security/acl/package-info.java +++ b/jdk/src/java.base/share/classes/java/security/acl/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,7 @@ * The classes and interfaces in this package have been deprecated. New * classes should not be added to this package. The {@code java.security} * package contains suitable replacements. See {@link java.security.Policy} - * and related classes for details. This package is subject to removal in a - * future version of Java SE. + * and related classes for details. * * @since 1.1 */ diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/HandshakeCompletedEvent.java b/jdk/src/java.base/share/classes/javax/net/ssl/HandshakeCompletedEvent.java index 67e8d7548a7..711589022d5 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/HandshakeCompletedEvent.java +++ b/jdk/src/java.base/share/classes/javax/net/ssl/HandshakeCompletedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -159,11 +159,10 @@ public class HandshakeCompletedEvent extends EventObject * @exception SSLPeerUnverifiedException if the peer is not verified. * @see #getPeerPrincipal() * @deprecated The {@link #getPeerCertificates()} method that returns an - * array of {@code java.security.cert.Certificate} should - * be used instead. This method is subject to removal in - * a future version of Java SE. + * array of {@code java.security.cert.Certificate} should + * be used instead. */ - @Deprecated(since="9", forRemoval=true) + @Deprecated(since="9") public javax.security.cert.X509Certificate [] getPeerCertificateChain() throws SSLPeerUnverifiedException { diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/SSLSession.java b/jdk/src/java.base/share/classes/javax/net/ssl/SSLSession.java index a355d187889..f5dd05f6666 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/SSLSession.java +++ b/jdk/src/java.base/share/classes/javax/net/ssl/SSLSession.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -279,11 +279,10 @@ public interface SSLSession { * has not been verified * @see #getPeerPrincipal() * @deprecated The {@link #getPeerCertificates()} method that returns an - * array of {@code java.security.cert.Certificate} should - * be used instead. This method is subject to removal in - * a future version of Java SE. + * array of {@code java.security.cert.Certificate} should + * be used instead. */ - @Deprecated(since="9", forRemoval=true) + @Deprecated(since="9") public javax.security.cert.X509Certificate [] getPeerCertificateChain() throws SSLPeerUnverifiedException; diff --git a/jdk/src/java.base/share/classes/javax/security/auth/Policy.java b/jdk/src/java.base/share/classes/javax/security/auth/Policy.java index 7180025c043..605161e363a 100644 --- a/jdk/src/java.base/share/classes/javax/security/auth/Policy.java +++ b/jdk/src/java.base/share/classes/javax/security/auth/Policy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -152,11 +152,10 @@ import sun.security.util.Debug; * * These two APIs provide callers the means to query the * Policy for Principal-based Permission entries. - * This class is subject to removal in a future version of Java SE. * * @see java.security.Security security properties */ -@Deprecated(since="1.4", forRemoval=true) +@Deprecated(since="1.4") public abstract class Policy { private static Policy policy; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/Certificate.java b/jdk/src/java.base/share/classes/javax/security/cert/Certificate.java index 9021a6244cb..bc188c8285f 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/Certificate.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,11 +58,10 @@ import java.security.SignatureException; * @since 1.4 * @see X509Certificate * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. * * @author Hemma Prafullchandra */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public abstract class Certificate { /** diff --git a/jdk/src/java.base/share/classes/javax/security/cert/CertificateEncodingException.java b/jdk/src/java.base/share/classes/javax/security/cert/CertificateEncodingException.java index dfbf56bfcfa..b39afa653a1 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/CertificateEncodingException.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/CertificateEncodingException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,9 +39,8 @@ package javax.security.cert; * @since 1.4 * @author Hemma Prafullchandra * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class CertificateEncodingException extends CertificateException { private static final long serialVersionUID = -8187642723048403470L; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/CertificateException.java b/jdk/src/java.base/share/classes/javax/security/cert/CertificateException.java index f26efb87172..8cb717d9212 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/CertificateException.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/CertificateException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,9 +39,8 @@ package javax.security.cert; * @since 1.4 * @see Certificate * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class CertificateException extends Exception { private static final long serialVersionUID = -5757213374030785290L; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/CertificateExpiredException.java b/jdk/src/java.base/share/classes/javax/security/cert/CertificateExpiredException.java index c3303009c8f..3014f0840f9 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/CertificateExpiredException.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/CertificateExpiredException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,9 +41,8 @@ package javax.security.cert; * @since 1.4 * @author Hemma Prafullchandra * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class CertificateExpiredException extends CertificateException { private static final long serialVersionUID = 5091601212177261883L; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/CertificateNotYetValidException.java b/jdk/src/java.base/share/classes/javax/security/cert/CertificateNotYetValidException.java index be076e09c86..a9640212db3 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/CertificateNotYetValidException.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/CertificateNotYetValidException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,9 +41,8 @@ package javax.security.cert; * @since 1.4 * @author Hemma Prafullchandra * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class CertificateNotYetValidException extends CertificateException { private static final long serialVersionUID = -8976172474266822818L; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/CertificateParsingException.java b/jdk/src/java.base/share/classes/javax/security/cert/CertificateParsingException.java index b099673277a..6378f32f8f4 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/CertificateParsingException.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/CertificateParsingException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,9 +40,8 @@ package javax.security.cert; * @since 1.4 * @author Hemma Prafullchandra * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public class CertificateParsingException extends CertificateException { private static final long serialVersionUID = -8449352422951136229L; diff --git a/jdk/src/java.base/share/classes/javax/security/cert/X509Certificate.java b/jdk/src/java.base/share/classes/javax/security/cert/X509Certificate.java index 83587e233b6..232134037b6 100644 --- a/jdk/src/java.base/share/classes/javax/security/cert/X509Certificate.java +++ b/jdk/src/java.base/share/classes/javax/security/cert/X509Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -125,9 +125,8 @@ import java.util.Date; * @see java.security.cert.X509Extension * @see java.security.Security security properties * @deprecated Use the classes in {@code java.security.cert} instead. - * This class is subject to removal in a future version of Java SE. */ -@Deprecated(since="9", forRemoval=true) +@Deprecated(since="9") public abstract class X509Certificate extends Certificate { /* From eb16b1cd819d11865aa8887bb168d8e5348a606b Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Mon, 6 Feb 2017 08:03:33 -0800 Subject: [PATCH 127/130] 8173947: jconsole does not show local running VMs to attach Reviewed-by: alanb, dholmes, dfuchs --- .../classes/sun/tools/jconsole/JConsole.java | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java b/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java index bc2b171978d..f1e518f258e 100644 --- a/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java +++ b/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java @@ -949,23 +949,12 @@ public class JConsole extends JFrame } } - private static final boolean localAttachmentSupported; - static { - boolean supported; - try { - Class.forName("com.sun.tools.attach.VirtualMachine"); - Class.forName("sun.management.ConnectorAddressLink"); - supported = true; - } catch (NoClassDefFoundError x) { - supported = false; - } catch (ClassNotFoundException x) { - supported = false; - } - localAttachmentSupported = supported; - } - + /** + * local attach is supported in this implementation as jdk.jconsole + * requires jdk.attach and jdk.management.agent + */ public static boolean isLocalAttachAvailable() { - return localAttachmentSupported; + return true; } From 3d412e1c5027731fcc6841ded0d7b9134543d18c Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Mon, 6 Feb 2017 17:28:33 +0000 Subject: [PATCH 128/130] 8173956: KeyStore regression due to default keystore being changed to PKCS12 Reviewed-by: xuelei --- .../sun/security/pkcs12/PKCS12KeyStore.java | 4 +- .../sun/security/pkcs12/MixedcaseAlias.java | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 jdk/test/sun/security/pkcs12/MixedcaseAlias.java diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java index 4e7d546583f..baf3b541756 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -982,7 +982,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { new CertEntry((X509Certificate) cert, null, alias, AnyUsage, attributes); certificateCount++; - entries.put(alias, certEntry); + entries.put(alias.toLowerCase(Locale.ENGLISH), certEntry); if (debug != null) { debug.println("Setting a trusted certificate at alias '" + alias + diff --git a/jdk/test/sun/security/pkcs12/MixedcaseAlias.java b/jdk/test/sun/security/pkcs12/MixedcaseAlias.java new file mode 100644 index 00000000000..520da009b75 --- /dev/null +++ b/jdk/test/sun/security/pkcs12/MixedcaseAlias.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8173956 + * @summary KeyStore regression due to default keystore being changed to PKCS12 + */ + +import java.io.*; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +/** + * Test that a PKCS12 keystore entry with mixed-case alias can be retrieved. + */ +public class MixedcaseAlias { + private static final String DIR = System.getProperty("test.src", "."); + private static final String CERT = DIR + "/trusted.pem"; + private static final String ALIAS = "Mixed-case Alias"; + + public static void main(String[] ignored) throws Exception { + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, null); + + keystore.setCertificateEntry(ALIAS, loadCertificate(CERT)); + KeyStore.Entry entry = keystore.getEntry(ALIAS, null); + + if (entry == null) { + throw new Exception( + "Error retrieving keystore entry using a mixed-case alias"); + } + + System.out.println("OK"); + } + + private static Certificate loadCertificate(String certFile) + throws Exception { + X509Certificate cert = null; + try (FileInputStream certStream = new FileInputStream(certFile)) { + CertificateFactory factory = + CertificateFactory.getInstance("X.509"); + return factory.generateCertificate(certStream); + } + } +} From 19a0529e40f6f8f6e0f2b8c887b164bdae445d2e Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Mon, 6 Feb 2017 22:23:46 +0100 Subject: [PATCH 129/130] 8173982: (fs) DefaultFileSystemProvider should be split into platform specific versions Reviewed-by: alanb --- .../sun/nio/fs/DefaultFileSystemProvider.java | 31 +------------ .../sun/nio/fs/DefaultFileSystemProvider.java | 43 +++++++++++++++++++ .../sun/nio/fs/DefaultFileSystemProvider.java | 43 +++++++++++++++++++ .../sun/nio/fs/DefaultFileSystemProvider.java | 43 +++++++++++++++++++ 4 files changed, 131 insertions(+), 29 deletions(-) rename jdk/src/java.base/{unix => aix}/classes/sun/nio/fs/DefaultFileSystemProvider.java (53%) create mode 100644 jdk/src/java.base/linux/classes/sun/nio/fs/DefaultFileSystemProvider.java create mode 100644 jdk/src/java.base/macosx/classes/sun/nio/fs/DefaultFileSystemProvider.java create mode 100644 jdk/src/java.base/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/DefaultFileSystemProvider.java b/jdk/src/java.base/aix/classes/sun/nio/fs/DefaultFileSystemProvider.java similarity index 53% rename from jdk/src/java.base/unix/classes/sun/nio/fs/DefaultFileSystemProvider.java rename to jdk/src/java.base/aix/classes/sun/nio/fs/DefaultFileSystemProvider.java index 42064456453..8c33d7e5a59 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/DefaultFileSystemProvider.java +++ b/jdk/src/java.base/aix/classes/sun/nio/fs/DefaultFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,6 @@ package sun.nio.fs; import java.nio.file.spi.FileSystemProvider; -import sun.security.action.GetPropertyAction; /** * Creates this platform's default FileSystemProvider. @@ -35,36 +34,10 @@ import sun.security.action.GetPropertyAction; public class DefaultFileSystemProvider { private DefaultFileSystemProvider() { } - @SuppressWarnings("unchecked") - private static FileSystemProvider createProvider(String cn) { - Class c; - try { - c = (Class)Class.forName(cn); - } catch (ClassNotFoundException x) { - throw new AssertionError(x); - } - try { - @SuppressWarnings("deprecation") - FileSystemProvider result = c.newInstance(); - return result; - } catch (IllegalAccessException | InstantiationException x) { - throw new AssertionError(x); - } - } - /** * Returns the default FileSystemProvider. */ public static FileSystemProvider create() { - String osname = GetPropertyAction.privilegedGetProperty("os.name"); - if (osname.equals("SunOS")) - return createProvider("sun.nio.fs.SolarisFileSystemProvider"); - if (osname.equals("Linux")) - return createProvider("sun.nio.fs.LinuxFileSystemProvider"); - if (osname.contains("OS X")) - return createProvider("sun.nio.fs.MacOSXFileSystemProvider"); - if (osname.equals("AIX")) - return createProvider("sun.nio.fs.AixFileSystemProvider"); - throw new AssertionError("Platform not recognized"); + return new AixFileSystemProvider(); } } diff --git a/jdk/src/java.base/linux/classes/sun/nio/fs/DefaultFileSystemProvider.java b/jdk/src/java.base/linux/classes/sun/nio/fs/DefaultFileSystemProvider.java new file mode 100644 index 00000000000..82a06b7ea50 --- /dev/null +++ b/jdk/src/java.base/linux/classes/sun/nio/fs/DefaultFileSystemProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.nio.fs; + +import java.nio.file.spi.FileSystemProvider; + +/** + * Creates this platform's default FileSystemProvider. + */ + +public class DefaultFileSystemProvider { + private DefaultFileSystemProvider() { } + + /** + * Returns the default FileSystemProvider. + */ + public static FileSystemProvider create() { + return new LinuxFileSystemProvider(); + } +} diff --git a/jdk/src/java.base/macosx/classes/sun/nio/fs/DefaultFileSystemProvider.java b/jdk/src/java.base/macosx/classes/sun/nio/fs/DefaultFileSystemProvider.java new file mode 100644 index 00000000000..917d9f3a25b --- /dev/null +++ b/jdk/src/java.base/macosx/classes/sun/nio/fs/DefaultFileSystemProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.nio.fs; + +import java.nio.file.spi.FileSystemProvider; + +/** + * Creates this platform's default FileSystemProvider. + */ + +public class DefaultFileSystemProvider { + private DefaultFileSystemProvider() { } + + /** + * Returns the default FileSystemProvider. + */ + public static FileSystemProvider create() { + return new MacOSXFileSystemProvider(); + } +} diff --git a/jdk/src/java.base/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java b/jdk/src/java.base/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java new file mode 100644 index 00000000000..83fddff2a54 --- /dev/null +++ b/jdk/src/java.base/solaris/classes/sun/nio/fs/DefaultFileSystemProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.nio.fs; + +import java.nio.file.spi.FileSystemProvider; + +/** + * Creates this platform's default FileSystemProvider. + */ + +public class DefaultFileSystemProvider { + private DefaultFileSystemProvider() { } + + /** + * Returns the default FileSystemProvider. + */ + public static FileSystemProvider create() { + return new SolarisFileSystemProvider(); + } +} From ecabcca746407c52c3587920f74647cbf7defaab Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Tue, 7 Feb 2017 00:38:22 -0800 Subject: [PATCH 130/130] 8172726: ForkJoin common pool retains a reference to the thread context class loader Reviewed-by: martin, psandoz, chegar --- .../java/util/concurrent/ForkJoinPool.java | 79 +++++++++++------- .../util/concurrent/ForkJoinWorkerThread.java | 48 +++++++---- .../concurrent/tck/ForkJoinPool9Test.java | 81 +++++++++++++++++++ .../util/concurrent/tck/JSR166TestCase.java | 11 ++- jdk/test/java/util/concurrent/tck/tck.policy | 15 ++++ 5 files changed, 185 insertions(+), 49 deletions(-) create mode 100644 jdk/test/java/util/concurrent/tck/ForkJoinPool9Test.java create mode 100644 jdk/test/java/util/concurrent/tck/tck.policy diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java index c549dbdb30f..330f4fb78a3 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java @@ -40,6 +40,7 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; import java.security.AccessController; import java.security.AccessControlContext; +import java.security.Permission; import java.security.Permissions; import java.security.PrivilegedAction; import java.security.ProtectionDomain; @@ -132,24 +133,30 @@ import java.util.concurrent.locks.LockSupport; * * * - *

The common pool is by default constructed with default - * parameters, but these may be controlled by setting the following - * {@linkplain System#getProperty system properties}: + *

The parameters used to construct the common pool may be controlled by + * setting the following {@linkplain System#getProperty system properties}: *

    *
  • {@code java.util.concurrent.ForkJoinPool.common.parallelism} * - the parallelism level, a non-negative integer *
  • {@code java.util.concurrent.ForkJoinPool.common.threadFactory} - * - the class name of a {@link ForkJoinWorkerThreadFactory} + * - the class name of a {@link ForkJoinWorkerThreadFactory}. + * The {@linkplain ClassLoader#getSystemClassLoader() system class loader} + * is used to load this class. *
  • {@code java.util.concurrent.ForkJoinPool.common.exceptionHandler} - * - the class name of a {@link UncaughtExceptionHandler} + * - the class name of a {@link UncaughtExceptionHandler}. + * The {@linkplain ClassLoader#getSystemClassLoader() system class loader} + * is used to load this class. *
  • {@code java.util.concurrent.ForkJoinPool.common.maximumSpares} * - the maximum number of allowed extra threads to maintain target * parallelism (default 256). *
- * If a {@link SecurityManager} is present and no factory is - * specified, then the default pool uses a factory supplying - * threads that have no {@link Permissions} enabled. - * The system class loader is used to load these classes. + * If no thread factory is supplied via a system property, then the + * common pool uses a factory that uses the system class loader as the + * {@linkplain Thread#getContextClassLoader() thread context class loader}. + * In addition, if a {@link SecurityManager} is present, then + * the common pool uses a factory supplying threads that have no + * {@link Permissions} enabled. + * * Upon any error in establishing these settings, default parameters * are used. It is possible to disable or limit the use of threads in * the common pool by setting the parallelism property to zero, and/or @@ -638,20 +645,38 @@ public class ForkJoinPool extends AbstractExecutorService { * * @param pool the pool this thread works in * @return the new worker thread, or {@code null} if the request - * to create a thread is rejected. + * to create a thread is rejected * @throws NullPointerException if the pool is null */ public ForkJoinWorkerThread newThread(ForkJoinPool pool); } + static AccessControlContext contextWithPermissions(Permission ... perms) { + Permissions permissions = new Permissions(); + for (Permission perm : perms) + permissions.add(perm); + return new AccessControlContext( + new ProtectionDomain[] { new ProtectionDomain(null, permissions) }); + } + /** * Default ForkJoinWorkerThreadFactory implementation; creates a - * new ForkJoinWorkerThread. + * new ForkJoinWorkerThread using the system class loader as the + * thread context class loader. */ private static final class DefaultForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory { + private static final AccessControlContext ACC = contextWithPermissions( + new RuntimePermission("getClassLoader"), + new RuntimePermission("setContextClassLoader")); + public final ForkJoinWorkerThread newThread(ForkJoinPool pool) { - return new ForkJoinWorkerThread(pool); + return AccessController.doPrivileged( + new PrivilegedAction<>() { + public ForkJoinWorkerThread run() { + return new ForkJoinWorkerThread( + pool, ClassLoader.getSystemClassLoader()); }}, + ACC); } } @@ -3244,26 +3269,20 @@ public class ForkJoinPool extends AbstractExecutorService { * An ACC to restrict permissions for the factory itself. * The constructed workers have no permissions set. */ - private static final AccessControlContext INNOCUOUS_ACC; - static { - Permissions innocuousPerms = new Permissions(); - innocuousPerms.add(modifyThreadPermission); - innocuousPerms.add(new RuntimePermission( - "enableContextClassLoaderOverride")); - innocuousPerms.add(new RuntimePermission( - "modifyThreadGroup")); - INNOCUOUS_ACC = new AccessControlContext(new ProtectionDomain[] { - new ProtectionDomain(null, innocuousPerms) - }); - } + private static final AccessControlContext ACC = contextWithPermissions( + modifyThreadPermission, + new RuntimePermission("enableContextClassLoaderOverride"), + new RuntimePermission("modifyThreadGroup"), + new RuntimePermission("getClassLoader"), + new RuntimePermission("setContextClassLoader")); public final ForkJoinWorkerThread newThread(ForkJoinPool pool) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - public ForkJoinWorkerThread run() { - return new ForkJoinWorkerThread. - InnocuousForkJoinWorkerThread(pool); - }}, INNOCUOUS_ACC); + return AccessController.doPrivileged( + new PrivilegedAction<>() { + public ForkJoinWorkerThread run() { + return new ForkJoinWorkerThread. + InnocuousForkJoinWorkerThread(pool); }}, + ACC); } } - } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java index 93bb08dd48f..a3054b865ba 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java @@ -36,6 +36,8 @@ package java.util.concurrent; import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.security.ProtectionDomain; /** @@ -87,12 +89,27 @@ public class ForkJoinWorkerThread extends Thread { this.workQueue = pool.registerWorker(this); } + /** + * Version for use by the default pool. Supports setting the + * context class loader. This is a separate constructor to avoid + * affecting the protected constructor. + */ + ForkJoinWorkerThread(ForkJoinPool pool, ClassLoader ccl) { + super("aForkJoinWorkerThread"); + super.setContextClassLoader(ccl); + this.pool = pool; + this.workQueue = pool.registerWorker(this); + } + /** * Version for InnocuousForkJoinWorkerThread. */ - ForkJoinWorkerThread(ForkJoinPool pool, ThreadGroup threadGroup, + ForkJoinWorkerThread(ForkJoinPool pool, + ClassLoader ccl, + ThreadGroup threadGroup, AccessControlContext acc) { super(threadGroup, null, "aForkJoinWorkerThread"); + super.setContextClassLoader(ccl); ThreadLocalRandom.setInheritedAccessControlContext(this, acc); ThreadLocalRandom.eraseThreadLocals(this); // clear before registering this.pool = pool; @@ -179,20 +196,21 @@ public class ForkJoinWorkerThread extends Thread { /** * A worker thread that has no permissions, is not a member of any - * user-defined ThreadGroup, and erases all ThreadLocals after + * user-defined ThreadGroup, uses the system class loader as + * thread context class loader, and erases all ThreadLocals after * running each top-level task. */ static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread { /** The ThreadGroup for all InnocuousForkJoinWorkerThreads */ private static final ThreadGroup innocuousThreadGroup = - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public ThreadGroup run() { - ThreadGroup group = Thread.currentThread().getThreadGroup(); - for (ThreadGroup p; (p = group.getParent()) != null; ) - group = p; - return new ThreadGroup(group, "InnocuousForkJoinWorkerThreadGroup"); - }}); + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction<>() { + public ThreadGroup run() { + ThreadGroup group = Thread.currentThread().getThreadGroup(); + for (ThreadGroup p; (p = group.getParent()) != null; ) + group = p; + return new ThreadGroup(group, "InnocuousForkJoinWorkerThreadGroup"); + }}); /** An AccessControlContext supporting no privileges */ private static final AccessControlContext INNOCUOUS_ACC = @@ -202,7 +220,10 @@ public class ForkJoinWorkerThread extends Thread { }); InnocuousForkJoinWorkerThread(ForkJoinPool pool) { - super(pool, innocuousThreadGroup, INNOCUOUS_ACC); + super(pool, + ClassLoader.getSystemClassLoader(), + innocuousThreadGroup, + INNOCUOUS_ACC); } @Override // to erase ThreadLocals @@ -210,11 +231,6 @@ public class ForkJoinWorkerThread extends Thread { ThreadLocalRandom.eraseThreadLocals(this); } - @Override // to always report system loader - public ClassLoader getContextClassLoader() { - return ClassLoader.getSystemClassLoader(); - } - @Override // to silently fail public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) { } diff --git a/jdk/test/java/util/concurrent/tck/ForkJoinPool9Test.java b/jdk/test/java/util/concurrent/tck/ForkJoinPool9Test.java new file mode 100644 index 00000000000..08cdfeb86dc --- /dev/null +++ b/jdk/test/java/util/concurrent/tck/ForkJoinPool9Test.java @@ -0,0 +1,81 @@ +/* + * 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. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file: + * + * Written by Doug Lea and Martin Buchholz with assistance from + * members of JCP JSR-166 Expert Group and released to the public + * domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.util.concurrent.CompletableFuture; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class ForkJoinPool9Test extends JSR166TestCase { + public static void main(String[] args) { + main(suite(), args); + } + + public static Test suite() { + return new TestSuite(ForkJoinPool9Test.class); + } + + /** + * Check handling of common pool thread context class loader + */ + public void testCommonPoolThreadContextClassLoader() throws Throwable { + if (!testImplementationDetails) return; + VarHandle CCL = + MethodHandles.privateLookupIn(Thread.class, MethodHandles.lookup()) + .findVarHandle(Thread.class, "contextClassLoader", ClassLoader.class); + ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); + boolean haveSecurityManager = (System.getSecurityManager() != null); + CompletableFuture.runAsync( + () -> { + assertSame(systemClassLoader, + Thread.currentThread().getContextClassLoader()); + assertSame(systemClassLoader, + CCL.get(Thread.currentThread())); + if (haveSecurityManager) + assertThrows( + SecurityException.class, + () -> System.getProperty("foo"), + () -> Thread.currentThread().setContextClassLoader(null)); + + // TODO ? +// if (haveSecurityManager +// && Thread.currentThread().getClass().getSimpleName() +// .equals("InnocuousForkJoinWorkerThread")) +// assertThrows(SecurityException.class, /* ?? */); + }).join(); + } + +} diff --git a/jdk/test/java/util/concurrent/tck/JSR166TestCase.java b/jdk/test/java/util/concurrent/tck/JSR166TestCase.java index ff686081cd2..80eb346db4e 100644 --- a/jdk/test/java/util/concurrent/tck/JSR166TestCase.java +++ b/jdk/test/java/util/concurrent/tck/JSR166TestCase.java @@ -46,6 +46,7 @@ * @summary JSR-166 tck tests (whitebox tests allowed) * @build * * @modules java.base/java.util.concurrent:open + * java.base/java.lang:open * java.management * @run junit/othervm/timeout=1000 * -Djsr166.testImplementationDetails=true @@ -59,6 +60,9 @@ * -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 * -Djava.util.secureRandomSeed=true * JSR166TestCase + * @run junit/othervm/timeout=1000/policy=tck.policy + * -Djsr166.testImplementationDetails=true + * JSR166TestCase */ import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -584,6 +588,7 @@ public class JSR166TestCase extends TestCase { "AtomicReference9Test", "AtomicReferenceArray9Test", "ExecutorCompletionService9Test", + "ForkJoinPool9Test", }; addNamedTestClasses(suite, java9TestClassNames); } @@ -594,7 +599,7 @@ public class JSR166TestCase extends TestCase { /** Returns list of junit-style test method names in given class. */ public static ArrayList testMethodNames(Class testClass) { Method[] methods = testClass.getDeclaredMethods(); - ArrayList names = new ArrayList(methods.length); + ArrayList names = new ArrayList<>(methods.length); for (Method method : methods) { if (method.getName().startsWith("test") && Modifier.isPublic(method.getModifiers()) @@ -700,7 +705,7 @@ public class JSR166TestCase extends TestCase { * The first exception encountered if any threadAssertXXX method fails. */ private final AtomicReference threadFailure - = new AtomicReference(null); + = new AtomicReference<>(null); /** * Records an exception so that it can be rethrown later in the test @@ -1262,7 +1267,7 @@ public class JSR166TestCase extends TestCase { } public void refresh() {} public String toString() { - List ps = new ArrayList(); + List ps = new ArrayList<>(); for (Enumeration e = perms.elements(); e.hasMoreElements();) ps.add(e.nextElement()); return "AdjustablePolicy with permissions " + ps; diff --git a/jdk/test/java/util/concurrent/tck/tck.policy b/jdk/test/java/util/concurrent/tck/tck.policy new file mode 100644 index 00000000000..5816ab31c50 --- /dev/null +++ b/jdk/test/java/util/concurrent/tck/tck.policy @@ -0,0 +1,15 @@ +grant { + // Permissions j.u.c. needs directly + permission java.lang.RuntimePermission "modifyThread"; + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "setContextClassLoader"; + permission java.util.PropertyPermission "*", "read"; + // Permissions needed to change permissions! + permission java.security.SecurityPermission "getPolicy"; + permission java.security.SecurityPermission "setPolicy"; + permission java.security.SecurityPermission "setSecurityManager"; + // Permissions needed by the junit test harness + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.io.FilePermission "<>", "read"; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; +};