From 04eb6a6783d18a7ed75acbe8f56054fc246d965d Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Mon, 31 Oct 2016 14:13:03 +0100 Subject: [PATCH 01/45] 8166837: [TESTBUG] Fix tests on Linux/s390x Reviewed-by: simonis --- jdk/test/java/awt/JAWT/JAWT.sh | 2 +- jdk/test/sun/tools/jhsdb/BasicLauncherTest.java | 5 ++--- jdk/test/sun/tools/jhsdb/HeapDumpTest.java | 5 ++--- jdk/test/sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/jdk/test/java/awt/JAWT/JAWT.sh b/jdk/test/java/awt/JAWT/JAWT.sh index ab511d8a71e..d01ff022a42 100644 --- a/jdk/test/java/awt/JAWT/JAWT.sh +++ b/jdk/test/java/awt/JAWT/JAWT.sh @@ -122,7 +122,7 @@ esac # Skip unsupported platforms case `uname -m` in - arm* | ppc* ) + arm* | ppc* | s390* ) echo "Test passed. Not supported on current architecture." exit 0 ;; diff --git a/jdk/test/sun/tools/jhsdb/BasicLauncherTest.java b/jdk/test/sun/tools/jhsdb/BasicLauncherTest.java index 998e1b2eed2..9285044b358 100644 --- a/jdk/test/sun/tools/jhsdb/BasicLauncherTest.java +++ b/jdk/test/sun/tools/jhsdb/BasicLauncherTest.java @@ -44,7 +44,7 @@ import jdk.testlibrary.Utils; import jdk.testlibrary.OutputAnalyzer; import jdk.testlibrary.ProcessTools; import jdk.test.lib.apps.LingeredApp; -import jdk.testlibrary.Platform; +import jdk.test.lib.Platform; public class BasicLauncherTest { @@ -230,8 +230,7 @@ public class BasicLauncherTest { Arrays.asList(toolArgs)); } - public static void main(String[] args) - throws IOException { + public static void main(String[] args) throws Exception { if (!Platform.shouldSAAttach()) { // Silently skip the test if we don't have enough permissions to attach diff --git a/jdk/test/sun/tools/jhsdb/HeapDumpTest.java b/jdk/test/sun/tools/jhsdb/HeapDumpTest.java index 59772a3c421..bc1d6553885 100644 --- a/jdk/test/sun/tools/jhsdb/HeapDumpTest.java +++ b/jdk/test/sun/tools/jhsdb/HeapDumpTest.java @@ -41,7 +41,7 @@ import jdk.testlibrary.JDKToolLauncher; import jdk.testlibrary.OutputAnalyzer; import jdk.testlibrary.ProcessTools; import jdk.test.lib.apps.LingeredApp; -import jdk.testlibrary.Platform; +import jdk.test.lib.Platform; public class HeapDumpTest { @@ -109,8 +109,7 @@ public class HeapDumpTest { dump.delete(); } - public static void main(String[] args) - throws IOException { + public static void main(String[] args) throws Exception { if (!Platform.shouldSAAttach()) { // Silently skip the test if we don't have enough permissions to attach diff --git a/jdk/test/sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java b/jdk/test/sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java index 1f88fd325b1..75437fa4ed3 100644 --- a/jdk/test/sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java +++ b/jdk/test/sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java @@ -30,7 +30,7 @@ import java.util.Map; import jdk.test.lib.apps.LingeredApp; import jdk.testlibrary.Utils; -import jdk.testlibrary.Platform; +import jdk.test.lib.Platform; /* * @test From 145cb85e75a24e00e249a3d81db72e60b072f56e Mon Sep 17 00:00:00 2001 From: Serguei Spitsyn Date: Mon, 7 Nov 2016 16:14:18 -0800 Subject: [PATCH 02/45] 8160024: jdb returns invalid argument count if first parameter to Arrays.asList is null Adjust com/sun/jdi/MethodImpl.java for null argument Reviewed-by: dcubed, dsamersoff --- .../classes/com/sun/tools/jdi/MethodImpl.java | 10 ++- jdk/test/com/sun/jdi/EvalArraysAsList.sh | 85 +++++++++++++++++++ 2 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 jdk/test/com/sun/jdi/EvalArraysAsList.sh diff --git a/jdk/src/jdk.jdi/share/classes/com/sun/tools/jdi/MethodImpl.java b/jdk/src/jdk.jdi/share/classes/com/sun/tools/jdi/MethodImpl.java index b5cd9c67abd..2cd645345c7 100644 --- a/jdk/src/jdk.jdi/share/classes/com/sun/tools/jdi/MethodImpl.java +++ b/jdk/src/jdk.jdi/share/classes/com/sun/tools/jdi/MethodImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -315,10 +315,14 @@ public abstract class MethodImpl extends TypeComponentImpl return; } Value nthArgValue = arguments.get(paramCount - 1); - if (nthArgValue == null) { + if (nthArgValue == null && argCount == paramCount) { + // We have one varargs parameter and it is null + // so we don't have to do anything. return; } - Type nthArgType = nthArgValue.type(); + // If the first varargs parameter is null, then don't + // access its type since it can't be an array. + Type nthArgType = (nthArgValue == null) ? null : nthArgValue.type(); if (nthArgType instanceof ArrayTypeImpl) { if (argCount == paramCount && ((ArrayTypeImpl)nthArgType).isAssignableTo(lastParamType)) { diff --git a/jdk/test/com/sun/jdi/EvalArraysAsList.sh b/jdk/test/com/sun/jdi/EvalArraysAsList.sh new file mode 100644 index 00000000000..fa5cd93c53a --- /dev/null +++ b/jdk/test/com/sun/jdi/EvalArraysAsList.sh @@ -0,0 +1,85 @@ +#!/bin/sh +# +# 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 8160024 +# @summary jdb returns invalid argument count if first parameter to Arrays.asList is null +# +# @run shell/timeout=300 EvalArraysAsList.sh +# +# The test checks if evaluation of the expression java.util.Arrays.asList(null, "a") +# works normally and does not throw an IllegalArgumentException. + +classname=EvalArraysAsList + +createJavaFile() +{ + cat < $classname.java.1 +public class $classname { + public static void main(String[] args) { + java.util.List l = java.util.Arrays.asList(null, "a"); + System.out.println("java.util.Arrays.asList(null, \"a\") returns: " + l); + return; // @1 breakpoint + } +} +EOF +} + +# drive jdb by sending cmds to it and examining its output +dojdbCmds() +{ + setBkpts @1 + runToBkpt @1 + + cmd eval "java.util.Arrays.asList(null, null)" + jdbFailIfPresent "IllegalArgumentException" 3 + + cmd eval "java.util.Arrays.asList(null, \"a\")" + jdbFailIfPresent "IllegalArgumentException" 3 + + cmd eval "java.util.Arrays.asList(\"a\", null)" + jdbFailIfPresent "IllegalArgumentException" 3 +} + + +mysetup() +{ + if [ -z "$TESTSRC" ] ; then + TESTSRC=. + fi + + for ii in . $TESTSRC $TESTSRC/.. ; do + if [ -r "$ii/ShellScaffold.sh" ] ; then + . $ii/ShellScaffold.sh + break + fi + done +} + +# You could replace this next line with the contents +# of ShellScaffold.sh and this script will run just the same. +mysetup + +runit +pass From 34af3661d3fe5d2037d2a6407ea23e349b822c55 Mon Sep 17 00:00:00 2001 From: Ujwal Vangapally Date: Mon, 14 Nov 2016 12:05:26 +0530 Subject: [PATCH 03/45] 8168141: javax/management/remote/mandatory/notif/EmptyDomainNotificationTest.java: No notif received! Changed the time limit of 2 seconds for getting notification to default jtreg timeout. Reviewed-by: rehn, dholmes --- .../notif/EmptyDomainNotificationTest.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/jdk/test/javax/management/remote/mandatory/notif/EmptyDomainNotificationTest.java b/jdk/test/javax/management/remote/mandatory/notif/EmptyDomainNotificationTest.java index ebc0ab239d6..7301c4faa0b 100644 --- a/jdk/test/javax/management/remote/mandatory/notif/EmptyDomainNotificationTest.java +++ b/jdk/test/javax/management/remote/mandatory/notif/EmptyDomainNotificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -103,20 +103,13 @@ public class EmptyDomainNotificationTest { mbsc.invoke(mbean, "emitNotification", null, null); System.out.println("EmptyDomainNotificationTest-main: waiting notif..."); - final long stopTime = System.currentTimeMillis() + 2000; synchronized(li) { - long toWait = stopTime - System.currentTimeMillis(); - - while (li.received < 1 && toWait > 0) { - li.wait(toWait); - - toWait = stopTime - System.currentTimeMillis(); + while (li.received < 1) { + li.wait(); } } - if (li.received < 1) { - throw new RuntimeException("No notif received!"); - } else if (li.received > 1) { + if (li.received != 1) { throw new RuntimeException("Wait one notif but got: "+li.received); } From b5aa3c60c0dbb26cd6a9f583666bcc1d7e6e5298 Mon Sep 17 00:00:00 2001 From: Rahul Raghavan Date: Thu, 17 Nov 2016 01:17:26 -0800 Subject: [PATCH 04/45] 8159035: com/sun/crypto/provider/Cipher/CTS/CTSMode.java test crashed due to unhandled case of cipher length value as 0 Handled 0 length input case in Java wrapper method Reviewed-by: alanb, ascarpino, kvn, sherman, thartmann --- .../com/sun/crypto/provider/CipherBlockChaining.java | 10 ++++++---- .../classes/com/sun/crypto/provider/CounterMode.java | 10 ++++++---- .../java.base/share/classes/sun/nio/cs/ISO_8859_1.java | 7 +++---- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherBlockChaining.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherBlockChaining.java index f903754fb48..4e93d6fe03a 100644 --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherBlockChaining.java +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherBlockChaining.java @@ -142,6 +142,9 @@ class CipherBlockChaining extends FeedbackCipher { */ int encrypt(byte[] plain, int plainOffset, int plainLen, byte[] cipher, int cipherOffset) { + if (plainLen <= 0) { + return plainLen; + } cryptBlockSizeCheck(plainLen); cryptNullAndBoundsCheck(plain, plainOffset, plainLen); cryptNullAndBoundsCheck(cipher, cipherOffset, plainLen); @@ -190,6 +193,9 @@ class CipherBlockChaining extends FeedbackCipher { */ int decrypt(byte[] cipher, int cipherOffset, int cipherLen, byte[] plain, int plainOffset) { + if (cipherLen <= 0) { + return cipherLen; + } cryptBlockSizeCheck(cipherLen); cryptNullAndBoundsCheck(cipher, cipherOffset, cipherLen); cryptNullAndBoundsCheck(plain, plainOffset, cipherLen); @@ -220,10 +226,6 @@ class CipherBlockChaining extends FeedbackCipher { } private static void cryptNullAndBoundsCheck(byte[] array, int offset, int len) { - if (len <= 0) { - return; // not an error because cryptImpl/decryptImpl won't execute if len <= 0 - } - Objects.requireNonNull(array); if (offset < 0 || offset >= array.length) { diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/CounterMode.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/CounterMode.java index da6c10a7956..a1c33ae1593 100644 --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/CounterMode.java +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/CounterMode.java @@ -172,10 +172,12 @@ final class CounterMode extends FeedbackCipher { * are encrypted on demand. */ private int crypt(byte[] in, int inOff, int len, byte[] out, int outOff) { - - Objects.checkFromIndexSize(inOff, len, in.length); - Objects.checkFromIndexSize(outOff, len, out.length); - return implCrypt(in, inOff, len, out, outOff); + if (len == 0) { + return 0; + } + Objects.checkFromIndexSize(inOff, len, in.length); + Objects.checkFromIndexSize(outOff, len, out.length); + return implCrypt(in, inOff, len, out, outOff); } // Implementation of crpyt() method. Possibly replaced with a compiler intrinsic. diff --git a/jdk/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java b/jdk/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java index b5d93a8f677..f1dadedaf53 100644 --- a/jdk/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java +++ b/jdk/src/java.base/share/classes/sun/nio/cs/ISO_8859_1.java @@ -157,6 +157,9 @@ class ISO_8859_1 // Method possible replaced with a compiler intrinsic. private static int encodeISOArray(char[] sa, int sp, byte[] da, int dp, int len) { + if (len <= 0) { + return 0; + } encodeISOArrayCheck(sa, sp, da, dp, len); return implEncodeISOArray(sa, sp, da, dp, len); } @@ -177,10 +180,6 @@ class ISO_8859_1 private static void encodeISOArrayCheck(char[] sa, int sp, byte[] da, int dp, int len) { - if (len <= 0) { - return; // not an error because encodeISOArrayImpl won't execute if len <= 0 - } - Objects.requireNonNull(sa); Objects.requireNonNull(da); From 44f0e6e48205e7f10f1481a460a1fdfe015126f3 Mon Sep 17 00:00:00 2001 From: Harsha Wardhana B Date: Mon, 21 Nov 2016 12:13:39 +0530 Subject: [PATCH 05/45] 8169575: com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java failing with jtreg tip Reviewed-by: rriggs, fparain --- .../DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/test/com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java b/jdk/test/com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java index 368731e9d85..748e49a0915 100644 --- a/jdk/test/com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java +++ b/jdk/test/com/sun/management/DiagnosticCommandMBean/DcmdMBeanPermissionsTest.java @@ -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 @@ -226,9 +226,10 @@ public class DcmdMBeanPermissionsTest { sm.grantPermission(new RuntimePermission("createClassLoader")); sm.grantPermission(new ReflectPermission("suppressAccessChecks")); sm.grantPermission(new java.util.logging.LoggingPermission("control", "")); - sm.grantPermission(new java.lang.RuntimePermission("exitVM.97")); + sm.grantPermission(new java.lang.RuntimePermission("exitVM.*")); sm.grantPermission(new java.lang.RuntimePermission("modifyThreadGroup")); sm.grantPermission(new java.lang.RuntimePermission("modifyThread")); + sm.grantPermission(new java.security.SecurityPermission("getProperty.jdk.jar.disabledAlgorithms")); for(MBeanOperationInfo opInfo : info.getOperations()) { Permission opPermission = new MBeanPermission(info.getClassName(), opInfo.getName(), From fdedfbc0f35d2b275db6c181a92eb451565f0334 Mon Sep 17 00:00:00 2001 From: Harsha Wardhana B Date: Thu, 24 Nov 2016 12:04:44 +0530 Subject: [PATCH 06/45] 8141591: javax/management/remote/mandatory/threads/ExecutorTest.java fails intermittently Reviewed-by: dfuchs --- .../remote/internal/ClientNotifForwarder.java | 36 ++++- .../threads/ExecutorShutdownTest.java | 148 ++++++++++++++++++ 2 files changed, 181 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/management/remote/mandatory/threads/ExecutorShutdownTest.java diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java index e0860f8e1f0..f2014eee794 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -51,7 +51,9 @@ import javax.management.remote.TargetedNotification; import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; +import java.lang.reflect.UndeclaredThrowableException; import java.rmi.UnmarshalException; +import java.util.concurrent.RejectedExecutionException; public abstract class ClientNotifForwarder { @@ -559,10 +561,38 @@ public abstract class ClientNotifForwarder { } } } else { - executor.execute(this); + try { + executor.execute(this); + } catch (Exception e) { + if (isRejectedExecutionException(e)) { + // We reached here because the executor was shutdown. + // If executor was supplied by client, then it was shutdown + // abruptly or JMXConnector was shutdown along with executor + // while this thread was suspended at L564. + if (!(executor instanceof LinearExecutor)) { + // Spawn new executor that will do cleanup if JMXConnector is closed + // or keep notif system running otherwise + executor = new LinearExecutor(); + executor.execute(this); + } + } else { + throw e; + } + } } } + private boolean isRejectedExecutionException(Exception e) { + Throwable cause = e; + while (cause != null) { + if (cause instanceof RejectedExecutionException) { + return true; + } + cause = cause.getCause(); + } + return false; + } + void dispatchNotification(TargetedNotification tn, Integer myListenerID, Map listeners) { @@ -866,7 +896,7 @@ public abstract class ClientNotifForwarder { // ------------------------------------------------- private final ClassLoader defaultClassLoader; - private final Executor executor; + private Executor executor; private final Map infoList = new HashMap(); diff --git a/jdk/test/javax/management/remote/mandatory/threads/ExecutorShutdownTest.java b/jdk/test/javax/management/remote/mandatory/threads/ExecutorShutdownTest.java new file mode 100644 index 00000000000..003780cc474 --- /dev/null +++ b/jdk/test/javax/management/remote/mandatory/threads/ExecutorShutdownTest.java @@ -0,0 +1,148 @@ +/* + * 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 8141591 + * @summary Tests if notifications are received after executor is shutdown + * @author Harsha Wardhana B + * @modules java.management + * @run clean ExecutorShutdownTest + * @run build ExecutorShutdownTest + * @run main ExecutorShutdownTest + */ +import java.util.*; +import java.util.concurrent.*; +import javax.management.*; +import javax.management.remote.*; + +/* + When you create a JMXConnector client, you can supply a + "fetch-notifications Executor", which is a + java.util.concurrent.Executor that will be used each time the + connector client wants to call RMIConnection.fetchNotifications. + If such executor is not supplies, the connector client will fallback + on default LinearExecutor. This test checks if user supplied executor + is shutdown abruptly, LinearExecutor is used to handle notifications. + */ +public class ExecutorShutdownTest { + + private static final String EXECUTOR_PROPERTY + = "jmx.remote.x.fetch.notifications.executor"; + private static final String NOTIF_TYPE = "test.type"; + + public static void main(String[] args) throws Exception { + + // Start JMXConnector Server + JMXServiceURL url = new JMXServiceURL("rmi", null, 0); + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName emitName = new ObjectName("blah:type=Emitter"); + mbs.registerMBean(new Emitter(), emitName); + JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, + null, + mbs); + cs.start(); + + // Create executor to provide to JMXConnector client + ExecutorService executor = Executors.newCachedThreadPool(); + Map env = new HashMap<>(); + env.put(EXECUTOR_PROPERTY, executor); + JMXServiceURL addr = cs.getAddress(); + + try (JMXConnector cc = JMXConnectorFactory.connect(addr, env)) { + MBeanServerConnection mbsc = cc.getMBeanServerConnection(); + EmitterMBean emitter = (EmitterMBean) MBeanServerInvocationHandler.newProxyInstance(mbsc, + emitName, + EmitterMBean.class, + false); + SemaphoreListener listener = new SemaphoreListener(); + NotificationFilterSupport filter = new NotificationFilterSupport(); + filter.enableType(NOTIF_TYPE); + mbsc.addNotificationListener(emitName, listener, filter, null); + + final int NOTIF_COUNT = 3; + for (int i = 0; i < NOTIF_COUNT; i++) { + emitter.emit(); + listener.await(); + } + Thread.sleep(1); + listener.checkUnavailable(); + System.out.println("Got notifications with client provided executor"); + + // After shutting down executor, notifications are handled by linear executor + executor.shutdown(); + for (int i = 0; i < NOTIF_COUNT; i++) { + emitter.emit(); + listener.await(); + } + Thread.sleep(1); + listener.checkUnavailable(); + System.out.println("Got notifications with linear executor"); + } + cs.stop(); + System.out.println("TEST PASSED !!!"); + } + + /* Simple MBean that sends a notification every time we ask it to. */ + public static interface EmitterMBean { + + public void emit(); + } + + public static class Emitter + extends NotificationBroadcasterSupport implements EmitterMBean { + + public void emit() { + sendNotification(new Notification(NOTIF_TYPE, this, seq++)); + } + + private long seq = 1; + } + + /* Simple NotificationListener that allows you to wait until a + notification has been received. Since it uses a semaphore, you + can wait either before or after the notification has in fact + been received and it will work in either case. */ + private static class SemaphoreListener implements NotificationListener { + + void await() throws InterruptedException { + semaphore.acquire(); + } + + /* Ensure no extra notifications were received. If we can acquire + the semaphore, that means its release() method was called more + times than its acquire() method, which means there were too + many notifications. */ + void checkUnavailable() throws Exception { + if (semaphore.tryAcquire()) { + throw new Exception("Got extra notifications!"); + } + } + + public void handleNotification(Notification n, Object h) { + semaphore.release(); + } + + private final Semaphore semaphore = new Semaphore(0); + } +} From 96fc05b6726cb530d314340e03737a8fa56c2c46 Mon Sep 17 00:00:00 2001 From: Brent Christian Date: Tue, 13 Dec 2016 12:35:59 -0800 Subject: [PATCH 07/45] 8169389: Use a bitmap to control StackTraceElement::toString format and save footprint Reviewed-by: dfuchs, mchung --- .../classes/java/lang/StackTraceElement.java | 155 +++++++++--------- .../lang/StackTraceElement/ModuleFrames.java | 26 ++- 2 files changed, 98 insertions(+), 83 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java b/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java index 04ba817a553..98536259a92 100644 --- a/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java +++ b/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java @@ -30,7 +30,6 @@ import jdk.internal.misc.SharedSecrets; import jdk.internal.misc.VM; import jdk.internal.module.ModuleHashes; -import java.lang.module.ModuleDescriptor.Version; import java.lang.reflect.Layer; import java.lang.reflect.Module; import java.util.HashSet; @@ -51,12 +50,13 @@ import java.util.Set; * @author Josh Bloch */ public final class StackTraceElement implements java.io.Serializable { - // This field is set to the compacted String representation used - // by StackTraceElement::toString and stored in serial form. + + // For Throwables and StackWalker, the VM initially sets this field to a + // reference to the declaring Class. The Class reference is used to + // construct the 'format' bitmap, and then is cleared. // - // This field is of Object type. VM initially sets this field to - // the Class object of the declaring class to build the compacted string. - private Object classOrLoaderModuleClassName; + // For STEs constructed using the public constructors, this field is not used. + private transient Class declaringClassObject; // Normally initialized by VM private String classLoaderName; @@ -66,6 +66,7 @@ public final class StackTraceElement implements java.io.Serializable { private String methodName; private String fileName; private int lineNumber; + private byte format = 0; // Default to show all /** * Creates a stack trace element representing the specified execution @@ -256,9 +257,10 @@ public final class StackTraceElement implements java.io.Serializable { } /** - * Returns a string representation of this stack trace element. The - * format of this string depends on the implementation, but the following - * examples may be regarded as typical: + * Returns a string representation of this stack trace element. + * + * @apiNote The format of this string depends on the implementation, but the + * following examples may be regarded as typical: *
    *
  • * "{@code com.foo.loader/foo@9.0/com.foo.Main.run(Main.java:101)}" @@ -309,7 +311,7 @@ public final class StackTraceElement implements java.io.Serializable { * then the second element is omitted as shown in * "{@code com.foo.loader//com.foo.bar.App.run(App.java:12)}". * - * If the class loader is a + *

    If the class loader is a * built-in class loader or is not named then the first element * and its following {@code "/"} are omitted as shown in * "{@code acme@2.1/org.acme.Lib.test(Lib.java:80)}". @@ -317,25 +319,30 @@ public final class StackTraceElement implements java.io.Serializable { * the second element and its following {@code "/"} are also omitted * as shown in "{@code MyClass.mash(MyClass.java:9)}". * + *

    The {@code toString} method may return two different values on two + * {@code StackTraceElement} instances that are + * {@linkplain #equals(Object) equal}, for example one created via the + * constructor, and one obtained from {@link java.lang.Throwable} or + * {@link java.lang.StackWalker.StackFrame}, where an implementation may + * choose to omit some element in the returned string. + * * @see Throwable#printStackTrace() */ public String toString() { - String s = buildLoaderModuleClassName(); - if (s == null) { - // all elements will be included - s = ""; - if (classLoaderName != null && !classLoaderName.isEmpty()) { - s += classLoaderName + "/"; - } - if (moduleName != null && !moduleName.isEmpty()) { - s += moduleName; - - if (moduleVersion != null && !moduleVersion.isEmpty()) { - s += "@" + moduleVersion; - } - } - s = s.isEmpty() ? declaringClass : s + "/" + declaringClass; + String s = ""; + if (!dropClassLoaderName() && classLoaderName != null && + !classLoaderName.isEmpty()) { + s += classLoaderName + "/"; } + if (moduleName != null && !moduleName.isEmpty()) { + s += moduleName; + + if (!dropModuleVersion() && moduleVersion != null && + !moduleVersion.isEmpty()) { + s += "@" + moduleVersion; + } + } + s = s.isEmpty() ? declaringClass : s + "/" + declaringClass; return s + "." + methodName + "(" + (isNativeMethod() ? "Native Method)" : @@ -397,67 +404,53 @@ public final class StackTraceElement implements java.io.Serializable { /** - * Build the compacted String representation to be returned by - * toString method from the declaring Class object. + * Called from of() methods to set the 'format' bitmap using the Class + * reference stored in declaringClassObject, and then clear the reference. + * + *

    + * If the module is a non-upgradeable JDK module, then set + * JDK_NON_UPGRADEABLE_MODULE to omit its version string. + *

    + * If the loader is one of the built-in loaders (`boot`, `platform`, or `app`) + * then set BUILTIN_CLASS_LOADER to omit the first element (`/`). */ - synchronized String buildLoaderModuleClassName() { - if (classOrLoaderModuleClassName == null) - return null; + private synchronized void computeFormat() { + try { + Class cls = (Class) declaringClassObject; + ClassLoader loader = cls.getClassLoader0(); + Module m = cls.getModule(); + byte bits = 0; - if (classOrLoaderModuleClassName instanceof Class) { - Class cls = (Class)classOrLoaderModuleClassName; - classOrLoaderModuleClassName = toLoaderModuleClassName(cls); + // First element - class loader name + // Call package-private ClassLoader::name method + + if (loader instanceof BuiltinClassLoader) { + bits |= BUILTIN_CLASS_LOADER; + } + + // Second element - module name and version + + // Omit if is a JDK non-upgradeable module (recorded in the hashes + // in java.base) + if (isHashedInJavaBase(m)) { + bits |= JDK_NON_UPGRADEABLE_MODULE; + } + format = bits; + } finally { + // Class reference no longer needed, clear it + declaringClassObject = null; } - return (String)classOrLoaderModuleClassName; } - /** - * Returns // string - * representation of the given class. - *

    - * If the module is a non-upgradeable JDK module then omit - * its version string. - *

    - * If the loader has no name, or if the loader is one of the built-in - * loaders (`boot`, `platform`, or `app`) then drop the first element - * (`/`). - *

    - * If the first element has been dropped and the module is unnamed - * then drop the second element (`/`). - *

    - * If the first element is not dropped and the module is unnamed - * then drop ``. - */ - private static String toLoaderModuleClassName(Class cls) { - ClassLoader loader = cls.getClassLoader0(); - Module m = cls.getModule(); + private static final byte BUILTIN_CLASS_LOADER = 0x1; + private static final byte JDK_NON_UPGRADEABLE_MODULE = 0x2; - // First element - class loader name - // Call package-private ClassLoader::name method - String s = ""; - if (loader != null && loader.name() != null && - !(loader instanceof BuiltinClassLoader)) { - s = loader.name() + "/"; - } + private boolean dropClassLoaderName() { + return (format & BUILTIN_CLASS_LOADER) == BUILTIN_CLASS_LOADER; + } - // Second element - module name and version - if (m != null && m.isNamed()) { - s += m.getName(); - // Include version if it is a user module or upgradeable module - // - // If it is JDK non-upgradeable module which is recorded - // in the hashes in java.base, omit the version. - if (!isHashedInJavaBase(m)) { - Optional ov = m.getDescriptor().version(); - if (ov.isPresent()) { - String version = "@" + ov.get().toString(); - s += version; - } - } - } - - // fully-qualified class name - return s.isEmpty() ? cls.getName() : s + "/" + cls.getName(); + private boolean dropModuleVersion() { + return (format & JDK_NON_UPGRADEABLE_MODULE) == JDK_NON_UPGRADEABLE_MODULE; } /** @@ -519,7 +512,7 @@ public final class StackTraceElement implements java.io.Serializable { // ensure the proper StackTraceElement initialization for (StackTraceElement ste : stackTrace) { - ste.buildLoaderModuleClassName(); + ste.computeFormat(); } return stackTrace; } @@ -531,7 +524,7 @@ public final class StackTraceElement implements java.io.Serializable { StackTraceElement ste = new StackTraceElement(); initStackTraceElement(ste, sfi); - ste.buildLoaderModuleClassName(); + ste.computeFormat(); return ste; } diff --git a/jdk/test/java/lang/StackTraceElement/ModuleFrames.java b/jdk/test/java/lang/StackTraceElement/ModuleFrames.java index a3b66759a13..6f23160fdee 100644 --- a/jdk/test/java/lang/StackTraceElement/ModuleFrames.java +++ b/jdk/test/java/lang/StackTraceElement/ModuleFrames.java @@ -27,6 +27,9 @@ * @run testng ModuleFrames */ +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Arrays; import org.testng.annotations.Test; @@ -47,11 +50,30 @@ public class ModuleFrames { assertEquals(topFrame.getModuleName(), "java.base", "Expected top frame to be in module java.base"); - assertTrue(topFrame.toString().contains("java.base"), - "Expected toString of top frame to include java.base"); + assertTrue(topFrame.toString().startsWith("java.base"), + "Expected toString of top frame to omit loader name, start with module name: java.base"); + + assertTrue(!topFrame.toString().contains("@"), + "Expected toString of top frame not to include module version ('@')"); + + Path home = Paths.get(System.getProperty("java.home")); + boolean isImage = Files.exists(home.resolve("lib").resolve("modules")); + if (isImage) { + assertTrue(!topFrame.getModuleVersion().isEmpty(), + "Expected non-empty STE.getModuleVersion() for top frame"); + } assertNull(thisFrame.getModuleName(), "Expected frame for test not to have a module name"); + + assertTrue(thisFrame.toString().startsWith(this.getClass().getName()), + "Expected toString to start with class name (no loader or module name"); + + ClassLoader testCL = this.getClass().getClassLoader(); + if (ClassLoader.getSystemClassLoader().getClass().isInstance(testCL)) { + assertEquals(thisFrame.getClassLoaderName(), "app", + "Expect STE to have loader name of \"app\""); + } } } From 8a155cc86f02052965163ba5c46eabf13a7bd937 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Tue, 13 Dec 2016 17:40:53 -0800 Subject: [PATCH 08/45] 8171072: java/rmi/transport/handshake*/Handshake*.java, exception is not thrown when reach failure test case Reviewed-by: rriggs --- .../transport/handshakeFailure/HandshakeFailure.java | 12 +++++------- .../transport/handshakeTimeout/HandshakeTimeout.java | 12 +++++------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java b/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java index fc7341f7be3..d99e967cc7f 100644 --- a/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java +++ b/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -30,12 +30,10 @@ * java.rmi.ConnectException or ConnectIOException, not a MarshalException. * @author Peter Jones * - * @library ../../testlibrary * @modules java.rmi/sun.rmi.registry * java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport * java.rmi/sun.rmi.transport.tcp - * @build TestLibrary * @run main/othervm HandshakeFailure */ @@ -49,7 +47,6 @@ import java.rmi.registry.Registry; public class HandshakeFailure { - private static final int PORT = TestLibrary.getUnusedRandomPort(); private static final int TIMEOUT = 10000; public static void main(String[] args) throws Exception { @@ -57,12 +54,13 @@ public class HandshakeFailure { /* * Listen on port... */ - ServerSocket serverSocket = new ServerSocket(PORT); + ServerSocket serverSocket = new ServerSocket(0); + int port = serverSocket.getLocalPort(); /* * (Attempt RMI call to port in separate thread.) */ - Registry registry = LocateRegistry.getRegistry(PORT); + Registry registry = LocateRegistry.getRegistry(port); Connector connector = new Connector(registry); Thread t = new Thread(connector); t.setDaemon(true); @@ -93,7 +91,7 @@ public class HandshakeFailure { System.err.println(); if (connector.exception instanceof MarshalException) { - System.err.println( + throw new RuntimeException( "TEST FAILED: MarshalException thrown, expecting " + "java.rmi.ConnectException or ConnectIOException"); } else if (connector.exception instanceof ConnectException || diff --git a/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java b/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java index 7a20f20234c..d763b55c455 100644 --- a/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java +++ b/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -33,12 +33,10 @@ * this point (because no data for the invocation has yet been written). * @author Peter Jones * - * @library ../../testlibrary * @modules java.rmi/sun.rmi.registry * java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport * java.rmi/sun.rmi.transport.tcp - * @build TestLibrary * @run main/othervm HandshakeTimeout */ @@ -51,7 +49,6 @@ import java.rmi.registry.Registry; public class HandshakeTimeout { - private static final int PORT = TestLibrary.getUnusedRandomPort(); private static final int TIMEOUT = 10000; public static void main(String[] args) throws Exception { @@ -62,12 +59,13 @@ public class HandshakeTimeout { /* * Listen on port, but never process connections made to it. */ - ServerSocket serverSocket = new ServerSocket(PORT); + ServerSocket serverSocket = new ServerSocket(0); + int port = serverSocket.getLocalPort(); /* * Attempt RMI call to port in separate thread. */ - Registry registry = LocateRegistry.getRegistry(PORT); + Registry registry = LocateRegistry.getRegistry(port); Connector connector = new Connector(registry); Thread t = new Thread(connector); t.setDaemon(true); @@ -91,7 +89,7 @@ public class HandshakeTimeout { System.err.println(); if (connector.exception instanceof MarshalException) { - System.err.println( + throw new RuntimeException( "TEST FAILED: MarshalException thrown, expecting " + "java.rmi.ConnectException or ConnectIOException"); } else if (connector.exception instanceof ConnectException || From 292fe71e60f2c50bf9f1fd9177188b1fe3dd93c0 Mon Sep 17 00:00:00 2001 From: Stuart Marks Date: Tue, 13 Dec 2016 17:45:37 -0800 Subject: [PATCH 09/45] 8170943: Collectors.partitioningBy should specify that false and true entries are always present Reviewed-by: psandoz --- .../classes/java/util/stream/Collectors.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/java/util/stream/Collectors.java b/jdk/src/java.base/share/classes/java/util/stream/Collectors.java index 8a53a27589e..17c743a9064 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/Collectors.java +++ b/jdk/src/java.base/share/classes/java/util/stream/Collectors.java @@ -1268,10 +1268,16 @@ public final class Collectors { * to a {@code Predicate}, and organizes them into a * {@code Map>}. * + * The returned {@code Map} always contains mappings for both + * {@code false} and {@code true} keys. * There are no guarantees on the type, mutability, * serializability, or thread-safety of the {@code Map} or {@code List} * returned. * + * @apiNote + * If a partition has no elements, its value in the result Map will be + * an empty List. + * * @param the type of the input elements * @param predicate a predicate used for classifying input elements * @return a {@code Collector} implementing the partitioning operation @@ -1290,9 +1296,17 @@ public final class Collectors { * {@code Map} whose values are the result of the downstream * reduction. * - *

    There are no guarantees on the type, mutability, + *

    + * The returned {@code Map} always contains mappings for both + * {@code false} and {@code true} keys. + * There are no guarantees on the type, mutability, * serializability, or thread-safety of the {@code Map} returned. * + * @apiNote + * If a partition has no elements, its value in the result Map will be + * obtained by calling the downstream collector's supplier function and then + * applying the finisher function. + * * @param the type of the input elements * @param the intermediate accumulation type of the downstream collector * @param the result type of the downstream reduction From 3c750bc54fdd621c0a7c03730a1ace14236718ff Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 14 Dec 2016 10:40:59 +0800 Subject: [PATCH 10/45] 8168979: @implNote for invalid FilePermission Reviewed-by: xuelei --- .../share/classes/java/io/FilePermission.java | 54 +++++++++++-------- jdk/test/java/io/FilePermission/Invalid.java | 6 +++ 2 files changed, 38 insertions(+), 22 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/io/FilePermission.java b/jdk/src/java.base/share/classes/java/io/FilePermission.java index c3d51135905..5bd29603edb 100644 --- a/jdk/src/java.base/share/classes/java/io/FilePermission.java +++ b/jdk/src/java.base/share/classes/java/io/FilePermission.java @@ -206,12 +206,6 @@ public final class FilePermission extends Permission implements Serializable { DefaultFileSystemProvider.create() .getFileSystem(URI.create("file:///")); - /** - * Creates FilePermission objects with special internals. - * See {@link FilePermCompat#newPermPlusAltPath(Permission)} and - * {@link FilePermCompat#newPermUsingAltPath(Permission)}. - */ - private static final Path here = builtInFS.getPath( GetPropertyAction.privilegedGetProperty("user.dir")); @@ -261,9 +255,14 @@ public final class FilePermission extends Permission implements Serializable { static { SharedSecrets.setJavaIOFilePermissionAccess( + /** + * Creates FilePermission objects with special internals. + * See {@link FilePermCompat#newPermPlusAltPath(Permission)} and + * {@link FilePermCompat#newPermUsingAltPath(Permission)}. + */ new JavaIOFilePermissionAccess() { public FilePermission newPermPlusAltPath(FilePermission input) { - if (input.npath2 == null && !input.allFiles) { + if (!input.invalid && input.npath2 == null && !input.allFiles) { Path npath2 = altPath(input.npath); if (npath2 != null) { // Please note the name of the new permission is @@ -281,7 +280,7 @@ public final class FilePermission extends Permission implements Serializable { return input; } public FilePermission newPermUsingAltPath(FilePermission input) { - if (!input.allFiles) { + if (!input.invalid && !input.allFiles) { Path npath2 = altPath(input.npath); if (npath2 != null) { // New name, see above. @@ -340,6 +339,16 @@ public final class FilePermission extends Permission implements Serializable { // Windows. Some JDK codes generate such illegal names. npath = builtInFS.getPath(new File(name).getPath()) .normalize(); + // lastName should always be non-null now + Path lastName = npath.getFileName(); + if (lastName != null && lastName.toString().equals("-")) { + directory = true; + recursive = !rememberStar; + npath = npath.getParent(); + } + if (npath == null) { + npath = builtInFS.getPath(""); + } invalid = false; } catch (InvalidPathException ipe) { // Still invalid. For compatibility reason, accept it @@ -348,16 +357,6 @@ public final class FilePermission extends Permission implements Serializable { invalid = true; } - // lastName should always be non-null now - Path lastName = npath.getFileName(); - if (lastName != null && lastName.toString().equals("-")) { - directory = true; - recursive = !rememberStar; - npath = npath.getParent(); - } - if (npath == null) { - npath = builtInFS.getPath(""); - } } else { if ((cpath = getName()) == null) throw new NullPointerException("name can't be null"); @@ -452,6 +451,8 @@ public final class FilePermission extends Permission implements Serializable { * is converted to a {@link java.nio.file.Path} object named {@code npath} * after {@link Path#normalize() normalization}. No canonicalization is * performed which means the underlying file system is not accessed. + * If an {@link InvalidPathException} is thrown during the conversion, + * this {@code FilePermission} will be labeled as invalid. *

    * In either case, the "*" or "-" character at the end of a wildcard * {@code path} is removed before canonicalization or normalization. @@ -532,7 +533,12 @@ public final class FilePermission extends Permission implements Serializable { * {@code simple_npath.relativize(wildcard_npath)} is exactly "..", * a simple {@code npath} is recursively inside a wildcard {@code npath} * if and only if {@code simple_npath.relativize(wildcard_npath)} - * is a series of one or more "..". + * is a series of one or more "..". An invalid {@code FilePermission} does + * not imply any object except for itself. An invalid {@code FilePermission} + * is not implied by any object except for itself or a {@code FilePermission} + * on {@literal "<>"} whose actions is a superset of this + * invalid {@code FilePermission}. Even if two {@code FilePermission} + * are created with the same invalid path, one does not imply the other. * * @param p the permission to check against. * @@ -566,12 +572,12 @@ public final class FilePermission extends Permission implements Serializable { if (this == that) { return true; } - if (this.invalid || that.invalid) { - return false; - } if (allFiles) { return true; } + if (this.invalid || that.invalid) { + return false; + } if (that.allFiles) { return false; } @@ -699,6 +705,10 @@ public final class FilePermission extends Permission implements Serializable { * (if {@code jdk.io.permissionsUseCanonicalPath} is {@code true}) or * {@code npath} (if {@code jdk.io.permissionsUseCanonicalPath} * is {@code false}) are equal. Or they are both {@literal "<>"}. + *

    + * When {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, an + * invalid {@code FilePermission} does not equal to any object except + * for itself, even if they are created using the same invalid path. * * @param obj the object we are testing for equality with this object. * @return true if obj is a FilePermission, and has the same diff --git a/jdk/test/java/io/FilePermission/Invalid.java b/jdk/test/java/io/FilePermission/Invalid.java index 38c6a98b46c..2a343d7049c 100644 --- a/jdk/test/java/io/FilePermission/Invalid.java +++ b/jdk/test/java/io/FilePermission/Invalid.java @@ -37,6 +37,9 @@ public class Invalid { public static void main(String args[]) throws Exception { + // Allmighty + FilePermission af = new FilePermission("<>", "read"); + // Normal FilePermission fp = new FilePermission("a", "read"); @@ -57,6 +60,9 @@ public class Invalid { // Invalid implies itself Asserts.assertTrue(fp1.implies(fp1)); + // <> implies invalid + Asserts.assertTrue(af.implies(fp1)); + // and not implies or implied by anything else, including other // invalid ones Asserts.assertFalse(fp.implies(fp1)); From af3e32041522dc2e64e100d74bddec434f951434 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 14 Dec 2016 10:41:06 +0800 Subject: [PATCH 11/45] 8171190: Bump reference of NIST 800-57 Part 1 Rev 3 to Rev 4 in JarSigner API spec Reviewed-by: xuelei --- .../share/classes/sun/security/x509/AlgorithmId.java | 4 ++-- .../share/classes/jdk/security/jarsigner/JarSigner.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index 3ff90bf483a..a7754e67301 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -1024,7 +1024,7 @@ public class AlgorithmId implements Serializable, DerEncoder { } } - // Values from SP800-57 part 1 rev 3 tables 2 and three + // Values from SP800-57 part 1 rev 4 tables 2 and 3 private static String ecStrength (int bitLength) { if (bitLength >= 512) { // 256 bits of strength return "SHA512"; @@ -1035,7 +1035,7 @@ public class AlgorithmId implements Serializable, DerEncoder { } } - // same values for RSA and DSA + // Same values for RSA and DSA private static String ifcFfcStrength (int bitLength) { if (bitLength > 7680) { // 256 bits return "SHA512"; diff --git a/jdk/src/jdk.jartool/share/classes/jdk/security/jarsigner/JarSigner.java b/jdk/src/jdk.jartool/share/classes/jdk/security/jarsigner/JarSigner.java index d74edd570e8..3c6061cf18b 100644 --- a/jdk/src/jdk.jartool/share/classes/jdk/security/jarsigner/JarSigner.java +++ b/jdk/src/jdk.jartool/share/classes/jdk/security/jarsigner/JarSigner.java @@ -430,7 +430,7 @@ public final class JarSigner { * SHA384withECDSA for a 384-bit EC key. * * @implNote This implementation makes use of comparable strengths - * as defined in Tables 2 and 3 of NIST SP 800-57 Part 1-Rev.3. + * as defined in Tables 2 and 3 of NIST SP 800-57 Part 1-Rev.4. * Specifically, if a DSA or RSA key with a key size greater than 7680 * bits, or an EC key with a key size greater than or equal to 512 bits, * SHA-512 will be used as the hash function for the signature. From 213a2bc257d389eab996d16e6fa68f560eaae7e7 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Tue, 13 Dec 2016 18:47:23 -0800 Subject: [PATCH 12/45] 8171076: improve rmi tests by replacing TestLibrary.createRegistryOnUnusedPort, getUnusedRandomPort Reviewed-by: rriggs --- jdk/test/java/rmi/Naming/LookupNameWithColon.java | 4 ++-- jdk/test/java/rmi/Naming/RmiIsNoScheme.java | 4 ++-- jdk/test/java/rmi/Naming/UnderscoreHost.java | 4 ++-- .../stubClassesPermitted/StubClassesPermitted.java | 2 +- jdk/test/java/rmi/registry/emptyName/EmptyName.java | 4 ++-- .../java/rmi/reliability/juicer/AppleUserImpl.java | 4 ++-- .../activatable/UseCustomSocketFactory.java | 11 ++++++----- .../useSocketFactory/activatable/security.policy | 7 +++++++ .../registry/UseCustomSocketFactory.java | 7 ++++--- .../useSocketFactory/registry/security.policy | 7 +++++++ .../unicast/UseCustomSocketFactory.java | 4 ++-- .../keepAliveDuringCall/KeepAliveDuringCall.java | 4 ++-- .../unexportObject/UnexportLeak.java | 4 ++-- .../Unreferenced/finiteGCLatency/FiniteGCLatency.java | 4 ++-- .../unreferencedContext/UnreferencedContext.java | 4 ++-- jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java | 4 ++-- .../transport/checkLeaseInfoLeak/CheckLeaseLeak.java | 5 +++-- .../rapidExportUnexport/RapidExportUnexport.java | 5 ++--- .../rmi/rmic/newrmic/equivalence/AppleUserImpl.java | 4 ++-- .../rmi/runtime/Log/checkLogging/CheckLogging.java | 4 ++-- 20 files changed, 56 insertions(+), 40 deletions(-) diff --git a/jdk/test/java/rmi/Naming/LookupNameWithColon.java b/jdk/test/java/rmi/Naming/LookupNameWithColon.java index a0d1e9389a0..cdd2473a490 100644 --- a/jdk/test/java/rmi/Naming/LookupNameWithColon.java +++ b/jdk/test/java/rmi/Naming/LookupNameWithColon.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -45,7 +45,7 @@ public class LookupNameWithColon { "multiple:colons:in:name" }; - Registry reg = TestLibrary.createRegistryOnUnusedPort(); + Registry reg = TestLibrary.createRegistryOnEphemeralPort(); int port = TestLibrary.getRegistryPort(reg); for (int i = 0; i < names.length; i++) { diff --git a/jdk/test/java/rmi/Naming/RmiIsNoScheme.java b/jdk/test/java/rmi/Naming/RmiIsNoScheme.java index a044ff10207..1f202cfc43c 100644 --- a/jdk/test/java/rmi/Naming/RmiIsNoScheme.java +++ b/jdk/test/java/rmi/Naming/RmiIsNoScheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -49,7 +49,7 @@ public class RmiIsNoScheme implements Remote, Serializable { System.err.println("\nRegression test for bug 4626311\n"); try { - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); int registryPort = TestLibrary.getRegistryPort(registry); Naming.rebind("//:" + registryPort + "/RmiIsNoScheme", new RmiIsNoScheme()); diff --git a/jdk/test/java/rmi/Naming/UnderscoreHost.java b/jdk/test/java/rmi/Naming/UnderscoreHost.java index c253ec20441..6cfa9c9f8b7 100644 --- a/jdk/test/java/rmi/Naming/UnderscoreHost.java +++ b/jdk/test/java/rmi/Naming/UnderscoreHost.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -80,7 +80,7 @@ public class UnderscoreHost extends UnicastRemoteObject implements Remote { try { HostVerifyingSocketFactory hvf = new HostVerifyingSocketFactory(); RMISocketFactory.setSocketFactory(hvf); - Registry r = TestLibrary.createRegistryOnUnusedPort(); + Registry r = TestLibrary.createRegistryOnEphemeralPort(); int port = TestLibrary.getRegistryPort(r); t = new UnderscoreHost(); r.rebind(NAME, t); diff --git a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java index ecc5e398e7f..43318ce0eb0 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java @@ -85,7 +85,7 @@ public class StubClassesPermitted try { TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); - registry = TestLibrary.createRegistryOnUnusedPort(); + registry = TestLibrary.createRegistryOnEphemeralPort(); registryPort = TestLibrary.getRegistryPort(registry); // must run with java.lang.SecurityManager or the test diff --git a/jdk/test/java/rmi/registry/emptyName/EmptyName.java b/jdk/test/java/rmi/registry/emptyName/EmptyName.java index e3f271ae589..97b82a188e5 100644 --- a/jdk/test/java/rmi/registry/emptyName/EmptyName.java +++ b/jdk/test/java/rmi/registry/emptyName/EmptyName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -38,7 +38,7 @@ import java.rmi.server.RemoteObject; public class EmptyName { public static void main(String[] args) throws Exception { - Registry impl = TestLibrary.createRegistryOnUnusedPort(); + Registry impl = TestLibrary.createRegistryOnEphemeralPort(); Registry stub = (Registry) RemoteObject.toStub(impl); stub.bind("", stub); stub.lookup(""); diff --git a/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java b/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java index 8aeba6dd6aa..a8e9f1e93aa 100644 --- a/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java +++ b/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -313,7 +313,7 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { synchronized (user) { // create new registry and bind new AppleUserImpl in registry - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); registryPort = TestLibrary.getRegistryPort(registry); LocateRegistry.getRegistry(registryPort).rebind("AppleUser", user); diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java index 5c48efb0989..3509a3fbae5 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java @@ -43,7 +43,7 @@ import java.rmi.*; import java.rmi.registry.*; public class UseCustomSocketFactory { - static final int REGISTRY_PORT = TestLibrary.getUnusedRandomPort(); + static int registryPort = -1; static String[] protocol = new String[] { "", "compress", "xor" }; @@ -54,7 +54,8 @@ public class UseCustomSocketFactory { TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); try { - LocateRegistry.createRegistry(REGISTRY_PORT); + Registry reg = LocateRegistry.createRegistry(0); + registryPort = TestLibrary.getRegistryPort(reg); } catch (RemoteException e) { TestLibrary.bomb("creating registry", e); } @@ -90,7 +91,7 @@ public class UseCustomSocketFactory { "-Djava.security.policy=" + TestParams.defaultPolicy + " -Drmi.registry.port=" + - REGISTRY_PORT + + registryPort + " -Djava.rmi.activation.port=" + rmidPort, protocol[i]); @@ -108,7 +109,7 @@ public class UseCustomSocketFactory { long stopTime = System.currentTimeMillis() + 24000; do { try { - echo[i] = (Echo) Naming.lookup("//:" + REGISTRY_PORT + + echo[i] = (Echo) Naming.lookup("//:" + registryPort + "/EchoServer"); break; } catch (NotBoundException e) { @@ -138,7 +139,7 @@ public class UseCustomSocketFactory { } finally { serverVM.destroy(); try { - Naming.unbind("//:" + REGISTRY_PORT + "/EchoServer"); + Naming.unbind("//:" + registryPort + "/EchoServer"); } catch (RemoteException | NotBoundException | MalformedURLException e) { TestLibrary.bomb("unbinding EchoServer", e); } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy index 6c8a471c993..324624d5bc7 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/security.policy @@ -20,6 +20,13 @@ grant { permission java.util.PropertyPermission "java.security.policy", "read"; permission java.util.PropertyPermission "java.security.manager", "read"; + // used by TestLibrary to get the RMI Registry port + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.registry"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.server"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport.proxy"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport.tcp"; + // used by TestLibrary to determine test environment permission java.util.PropertyPermission "test.*", "read"; permission java.util.PropertyPermission "user.dir", "read"; diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java index 1a39bc79b64..0b6dc76a3b0 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -58,7 +58,7 @@ public class UseCustomSocketFactory { System.out.println("\nRegression test for bug 4148850\n"); TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - int registryPort = TestLibrary.getUnusedRandomPort(); + int registryPort = -1; try { impl = new HelloImpl(); @@ -68,9 +68,10 @@ public class UseCustomSocketFactory { * allow the rmiregistry to be secure. */ registry = LocateRegistry. - createRegistry(registryPort, + createRegistry(0, new Compress.CompressRMIClientSocketFactory(), new Compress.CompressRMIServerSocketFactory()); + registryPort = TestLibrary.getRegistryPort(registry); registry.rebind("/HelloServer", impl); checkStub(registry, "RMIServerSocket"); diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy index 523ea94a7a2..70bf79ac69e 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/security.policy @@ -22,6 +22,13 @@ grant { permission java.util.PropertyPermission "java.security.policy", "read"; permission java.util.PropertyPermission "java.security.manager", "read"; + // used by TestLibrary to get the RMI Registry port + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.registry"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.server"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport.proxy"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.transport.tcp"; + // test needs to export rmid and communicate with objects on arbitrary ports permission java.net.SocketPermission "*:1024-", "connect,accept,listen"; }; diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java index 21ff49ce8ec..4df810af015 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -55,7 +55,7 @@ public class UseCustomSocketFactory { TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); try { - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); registryPort = TestLibrary.getRegistryPort(registry); } catch (RemoteException e) { TestLibrary.bomb("creating registry", e); diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java index 27530b99bae..9c46f36b6cf 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -80,7 +80,7 @@ public class KeepAliveDuringCall implements ShutdownMonitor { UnicastRemoteObject.exportObject(obj); System.err.println("exported shutdown monitor"); - Registry localRegistry = TestLibrary.createRegistryOnUnusedPort(); + Registry localRegistry = TestLibrary.createRegistryOnEphemeralPort(); int registryPort = TestLibrary.getRegistryPort(localRegistry); System.err.println("created local registry"); diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java index f529f64ce0f..9979b6934ec 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -49,7 +49,7 @@ public class UnexportLeak implements Ping { public static void main(String[] args) { try { System.err.println("\nRegression test for bug 4331349\n"); - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); int registryPort = TestLibrary.getRegistryPort(registry); Remote obj = new UnexportLeak(); WeakReference wr = new WeakReference(obj); diff --git a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java index 0694209dffe..df3dde5ee29 100644 --- a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java +++ b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -81,7 +81,7 @@ public class FiniteGCLatency implements Remote, Unreferenced { try { UnicastRemoteObject.exportObject(obj); System.err.println("exported remote object"); - Registry registry1 = TestLibrary.createRegistryOnUnusedPort(); + Registry registry1 = TestLibrary.createRegistryOnEphemeralPort(); int port = TestLibrary.getRegistryPort(registry1); System.err.println("created registry"); diff --git a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java index f468779c9a7..2c4bb4d6b9f 100644 --- a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java +++ b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -122,7 +122,7 @@ public class UnreferencedContext implements Remote, Unreferenced, Runnable { UnicastRemoteObject.exportObject(obj); System.err.println("exported remote object"); - Registry registry1 = TestLibrary.createRegistryOnUnusedPort(); + Registry registry1 = TestLibrary.createRegistryOnEphemeralPort(); int port = TestLibrary.getRegistryPort(registry1); System.err.println("created registry"); diff --git a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java index 19d4d6cc808..359e971b002 100644 --- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java +++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -81,7 +81,7 @@ public class CheckFQDN extends UnicastRemoteObject System.err.println ("\nRegression test for bug/rfe 4115683\n"); - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); REGISTRY_PORT = TestLibrary.getRegistryPort(registry); registry.bind("CheckFQDN", checkFQDN); diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java index b54cbfb3d2c..8e35c8b65a8 100644 --- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java +++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -30,6 +30,7 @@ * @library ../../testlibrary * @modules java.rmi/sun.rmi.registry * java.rmi/sun.rmi.server + * java.rmi/sun.rmi.transport:open * java.rmi/sun.rmi.transport * java.rmi/sun.rmi.transport.tcp * @build TestLibrary CheckLeaseLeak_Stub LeaseLeakClient LeaseLeak @@ -90,7 +91,7 @@ public class CheckLeaseLeak extends UnicastRemoteObject implements LeaseLeak { try { Registry registry = - TestLibrary.createRegistryOnUnusedPort(); + TestLibrary.createRegistryOnEphemeralPort(); int registryPort = TestLibrary.getRegistryPort(registry); leakServer = new CheckLeaseLeak(); diff --git a/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java b/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java index 38c2e2a0042..5e2da339922 100644 --- a/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java +++ b/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -44,7 +44,6 @@ import java.rmi.Remote; import java.rmi.server.UnicastRemoteObject; public class RapidExportUnexport { - private static final int PORT = TestLibrary.getUnusedRandomPort(); private static final int REPS = 100; private static final long TIMEOUT = 60000; @@ -55,7 +54,7 @@ public class RapidExportUnexport { long start = System.currentTimeMillis(); for (int i = 0; i < REPS; i++) { System.err.println(i); - UnicastRemoteObject.exportObject(impl, PORT); + UnicastRemoteObject.exportObject(impl, 0); UnicastRemoteObject.unexportObject(impl, true); Thread.sleep(1); // work around BindException (bug?) } diff --git a/jdk/test/sun/rmi/rmic/newrmic/equivalence/AppleUserImpl.java b/jdk/test/sun/rmi/rmic/newrmic/equivalence/AppleUserImpl.java index ee34213340d..ca31273f809 100644 --- a/jdk/test/sun/rmi/rmic/newrmic/equivalence/AppleUserImpl.java +++ b/jdk/test/sun/rmi/rmic/newrmic/equivalence/AppleUserImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -253,7 +253,7 @@ public class AppleUserImpl int port = -1; // create new registry and bind new AppleUserImpl in registry try { - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); port = TestLibrary.getRegistryPort(registry); Naming.rebind("rmi://localhost:" + port + "/AppleUser",user); } catch (RemoteException e) { diff --git a/jdk/test/sun/rmi/runtime/Log/checkLogging/CheckLogging.java b/jdk/test/sun/rmi/runtime/Log/checkLogging/CheckLogging.java index dc23b4894eb..2b3d2d5b808 100644 --- a/jdk/test/sun/rmi/runtime/Log/checkLogging/CheckLogging.java +++ b/jdk/test/sun/rmi/runtime/Log/checkLogging/CheckLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -103,7 +103,7 @@ public class CheckLogging { private static Registry registry; static { try { - registry = TestLibrary.createRegistryOnUnusedPort(); + registry = TestLibrary.createRegistryOnEphemeralPort(); REGISTRY_PORT = TestLibrary.getRegistryPort(registry); LOCATION = "rmi://localhost:" + REGISTRY_PORT + "/"; } catch (Exception e) { From 7172c36a8d0dcfe3a13dda1dbbbc9c5173f34da8 Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Fri, 2 Dec 2016 15:02:10 +0100 Subject: [PATCH 13/45] 8170663: Fix minor issues in corelib and servicabilty coding Co-authored-by: David CARLIER Reviewed-by: dsamersoff, dholmes --- .../native/libjimage/imageDecompressor.cpp | 2 +- .../unix/native/libjli/java_md_solinux.c | 17 +++++++++-------- .../jdk.jdwp.agent/share/native/libjdwp/SDE.c | 9 ++++++--- .../unix/native/libdt_socket/socket_md.c | 18 +++++------------- .../share/native/common-unpack/unpack.cpp | 10 ++++++++-- 5 files changed, 29 insertions(+), 27 deletions(-) diff --git a/jdk/src/java.base/share/native/libjimage/imageDecompressor.cpp b/jdk/src/java.base/share/native/libjimage/imageDecompressor.cpp index 72de36db0ef..e2dbb79ce6f 100644 --- a/jdk/src/java.base/share/native/libjimage/imageDecompressor.cpp +++ b/jdk/src/java.base/share/native/libjimage/imageDecompressor.cpp @@ -181,7 +181,7 @@ void ImageDecompressor::decompress_resource(u1* compressed, u1* uncompressed, } } while (has_header); memcpy(uncompressed, decompressed_resource, (size_t) uncompressed_size); - delete decompressed_resource; + delete[] decompressed_resource; } // Zip decompressor diff --git a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c index b9091aaead3..538c0a7d249 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c +++ b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c @@ -444,13 +444,13 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, return; } #else - JLI_MemFree(newargv); - return; + JLI_MemFree(newargv); + return; #endif /* SETENV_REQUIRED */ - } else { /* do the same speculatively or exit */ + } else { /* do the same speculatively or exit */ JLI_ReportErrorMessage(JRE_ERROR2, wanted); exit(1); - } + } #ifdef SETENV_REQUIRED if (mustsetenv) { /* @@ -516,14 +516,14 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, /* runpath contains current effective LD_LIBRARY_PATH setting */ - jvmpath = JLI_StringDup(jvmpath); + char *new_jvmpath = JLI_StringDup(jvmpath); new_runpath_size = ((runpath != NULL) ? JLI_StrLen(runpath) : 0) + 2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) + #ifdef AIX /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */ JLI_StrLen(jrepath) + JLI_StrLen(arch) + JLI_StrLen("/lib//jli:") + #endif - JLI_StrLen(jvmpath) + 52; + JLI_StrLen(new_jvmpath) + 52; new_runpath = JLI_MemAlloc(new_runpath_size); newpath = new_runpath + JLI_StrLen(LD_LIBRARY_PATH "="); @@ -533,7 +533,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, */ { /* remove the name of the .so from the JVM path */ - lastslash = JLI_StrRChr(jvmpath, '/'); + lastslash = JLI_StrRChr(new_jvmpath, '/'); if (lastslash) *lastslash = '\0'; @@ -544,7 +544,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, "%s/lib/%s/jli:" /* Needed on AIX because ld doesn't support $ORIGIN. */ #endif "%s/../lib/%s", - jvmpath, + new_jvmpath, jrepath, arch, #ifdef AIX jrepath, arch, @@ -552,6 +552,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, jrepath, arch ); + JLI_MemFree(new_jvmpath); /* * Check to make sure that the prefix of the current path is the diff --git a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/SDE.c b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/SDE.c index 6ff7025bbf6..1f3aa41f65b 100644 --- a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/SDE.c +++ b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/SDE.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -249,16 +249,19 @@ private jboolean isValid(void); int lastLn = 0; int sti; + if (cnt < 0) { + return; + } loadDebugInfo(env, clazz); if (!isValid()) { return; /* no SDE or not SourceMap - return unchanged */ } sti = stratumTableIndex(globalDefaultStratumId); - if (sti == baseStratumIndex) { + if (sti == baseStratumIndex || sti < 0) { return; /* Java stratum - return unchanged */ } LOG_MISC(("SDE is re-ordering the line table")); - for (; cnt-->0; ++fromEntry) { + for (; cnt-- > 0; ++fromEntry) { int jplsLine = fromEntry->line_number; int lti = stiLineTableIndex(sti, jplsLine); if (lti >= 0) { diff --git a/jdk/src/jdk.jdwp.agent/unix/native/libdt_socket/socket_md.c b/jdk/src/jdk.jdwp.agent/unix/native/libdt_socket/socket_md.c index 33e062e087d..9692f4f83ae 100644 --- a/jdk/src/jdk.jdwp.agent/unix/native/libdt_socket/socket_md.c +++ b/jdk/src/jdk.jdwp.agent/unix/native/libdt_socket/socket_md.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -196,18 +196,10 @@ dbgsysSetSocketOption(int fd, jint cmd, jboolean on, jvalue value) } else if (cmd == SO_LINGER) { struct linger arg; arg.l_onoff = on; - - if(on) { - arg.l_linger = (unsigned short)value.i; - if(setsockopt(fd, SOL_SOCKET, SO_LINGER, - (char*)&arg, sizeof(arg)) < 0) { - return SYS_ERR; - } - } else { - if (setsockopt(fd, SOL_SOCKET, SO_LINGER, - (char*)&arg, sizeof(arg)) < 0) { - return SYS_ERR; - } + arg.l_linger = (on) ? (unsigned short)value.i : 0; + if (setsockopt(fd, SOL_SOCKET, SO_LINGER, + (char*)&arg, sizeof(arg)) < 0) { + return SYS_ERR; } } else if (cmd == SO_SNDBUF) { jint buflen = value.i; diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp b/jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp index 435d5ddcf0f..8f7a09d1243 100644 --- a/jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp +++ b/jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp @@ -2293,10 +2293,15 @@ void unpacker::read_ics() { number.set(null,0); name = n.slice(dollar2+1, nlen); } - if (number.ptr == null) + if (number.ptr == null) { + if (dollar1 < 0) { + abort(); + return; + } pkgOuter = n.slice(0, dollar1); - else + } else { pkgOuter.set(null,0); + } PRINTCR((5,"=> %s$ 0%s $%s", pkgOuter.string(), number.string(), name.string())); @@ -4197,6 +4202,7 @@ void unpacker::write_bc_ops() { // Note that insnMap has one entry for all these bytes. --wp; // not really part of the code int size = bc_escsize.getInt(); + if (size < 0) { assert(false); continue; } ensure_put_space(size); for (int j = 0; j < size; j++) putu1_fast(bc_escbyte.getByte()); From 1ba6d00a720be6b9579d76d844b1536b0ea81a89 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Mon, 5 Dec 2016 17:56:20 +0100 Subject: [PATCH 14/45] 8066474: Remove the lib/ directory from Linux and Solaris images Reviewed-by: tbell, ihse --- jdk/make/copy/Copy-java.base.gmk | 3 +- jdk/make/copy/Copy-java.desktop.gmk | 4 +- jdk/make/launcher/Launcher-java.base.gmk | 4 +- jdk/make/launcher/LauncherCommon.gmk | 8 +-- jdk/make/lib/CoreLibraries.gmk | 3 - .../macosx/native/libjli/java_md_macosx.c | 31 +++------- .../unix/classes/java/lang/ProcessImpl.java | 6 +- jdk/src/java.base/unix/native/libjli/ergo.c | 2 +- .../java.base/unix/native/libjli/ergo_i586.c | 4 +- .../java.base/unix/native/libjli/java_md.h | 6 +- .../unix/native/libjli/java_md_solinux.c | 61 ++++++++----------- .../java.base/windows/native/libjli/java_md.c | 20 +----- jdk/test/java/awt/JAWT/Makefile.unix | 4 +- jdk/test/tools/launcher/RunpathTest.java | 4 +- 14 files changed, 57 insertions(+), 103 deletions(-) diff --git a/jdk/make/copy/Copy-java.base.gmk b/jdk/make/copy/Copy-java.base.gmk index f736866e208..5d75ddfcf41 100644 --- a/jdk/make/copy/Copy-java.base.gmk +++ b/jdk/make/copy/Copy-java.base.gmk @@ -100,8 +100,7 @@ else # Allow override by ALT_JVMCFG_SRC if it exists JVMCFG_SRC := $(if $(wildcard $(ALT_JVMCFG_SRC)),$(ALT_JVMCFG_SRC),$(JVMCFG_SRC)) endif -JVMCFG_DIR := $(LIB_DST_DIR)$(OPENJDK_TARGET_CPU_LIBDIR) -JVMCFG := $(JVMCFG_DIR)/jvm.cfg +JVMCFG := $(LIB_DST_DIR)/jvm.cfg # To do: should this also support -zeroshark? diff --git a/jdk/make/copy/Copy-java.desktop.gmk b/jdk/make/copy/Copy-java.desktop.gmk index 51db98a356a..49d6b86aeb2 100644 --- a/jdk/make/copy/Copy-java.desktop.gmk +++ b/jdk/make/copy/Copy-java.desktop.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 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 @@ -64,7 +64,7 @@ ifneq ($(FREETYPE_BUNDLE_LIB_PATH), ) ifeq ($(OPENJDK_TARGET_OS), windows) FREETYPE_TARGET_LIB := $(LIB_DST_DIR)/$(call SHARED_LIBRARY,freetype) else - FREETYPE_TARGET_LIB := $(LIB_DST_DIR)$(OPENJDK_TARGET_CPU_LIBDIR)/$(call SHARED_LIBRARY,freetype).6 + FREETYPE_TARGET_LIB := $(LIB_DST_DIR)/$(call SHARED_LIBRARY,freetype).6 endif # We can't use $(install-file) in this rule because it preserves symbolic links and diff --git a/jdk/make/launcher/Launcher-java.base.gmk b/jdk/make/launcher/Launcher-java.base.gmk index 4d4b981c097..f70d90029a6 100644 --- a/jdk/make/launcher/Launcher-java.base.gmk +++ b/jdk/make/launcher/Launcher-java.base.gmk @@ -74,7 +74,7 @@ $(eval $(call SetupBuildLauncher, keytool, \ BUILD_JEXEC := BUILD_JEXEC_SRC := BUILD_JEXEC_INC := -BUILD_JEXEC_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base$(OPENJDK_TARGET_CPU_LIBDIR) +BUILD_JEXEC_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base # # UNHANDLED: @@ -138,7 +138,7 @@ endif BUILD_JSPAWNHELPER := BUILD_JSPAWNHELPER_SRC := $(JDK_TOPDIR)/src/java.base/unix/native/jspawnhelper JSPAWNHELPER_CFLAGS := -I$(JDK_TOPDIR)/src/java.base/unix/native/libjava -BUILD_JSPAWNHELPER_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base$(OPENJDK_TARGET_CPU_LIBDIR) +BUILD_JSPAWNHELPER_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base LINK_JSPAWNHELPER_OBJECTS := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjava/childproc.o BUILD_JSPAWNHELPER_LDFLAGS := diff --git a/jdk/make/launcher/LauncherCommon.gmk b/jdk/make/launcher/LauncherCommon.gmk index 1bef88f8a42..a4178039d6e 100644 --- a/jdk/make/launcher/LauncherCommon.gmk +++ b/jdk/make/launcher/LauncherCommon.gmk @@ -32,13 +32,13 @@ else ifeq ($(OPENJDK_TARGET_OS), windows) DISABLE_MAPFILES := true endif - ORIGIN_ARG := $(call SET_EXECUTABLE_ORIGIN,/../lib$(OPENJDK_TARGET_CPU_LIBDIR)/jli) + ORIGIN_ARG := $(call SET_EXECUTABLE_ORIGIN,/../lib/jli) # Applications expect to be able to link against libjawt without invoking # System.loadLibrary("jawt") first. This was the behaviour described in the # devloper documentation of JAWT and what worked with OpenJDK6. ifneq ($(findstring $(OPENJDK_TARGET_OS), linux solaris), ) - ORIGIN_ARG += $(call SET_EXECUTABLE_ORIGIN,/../lib$(OPENJDK_TARGET_CPU_LIBDIR)) + ORIGIN_ARG += $(call SET_EXECUTABLE_ORIGIN,/../lib) endif endif @@ -190,9 +190,9 @@ define SetupBuildLauncherBody $$(ORIGIN_ARG) \ $$($1_LDFLAGS), \ LDFLAGS_linux := \ - -L$(SUPPORT_OUTPUTDIR)/modules_libs/java.base$(OPENJDK_TARGET_CPU_LIBDIR)/jli, \ + -L$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/jli, \ LDFLAGS_solaris := $$($1_LDFLAGS_solaris) \ - -L$(SUPPORT_OUTPUTDIR)/modules_libs/java.base$(OPENJDK_TARGET_CPU_LIBDIR)/jli, \ + -L$(SUPPORT_OUTPUTDIR)/modules_libs/java.base/jli, \ MAPFILE := $$($1_MAPFILE), \ LIBS := $(JDKEXE_LIBS) $$($1_LIBS), \ LIBS_unix := $$($1_LIBS_unix), \ diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk index 345c4253389..18e4349c257 100644 --- a/jdk/make/lib/CoreLibraries.gmk +++ b/jdk/make/lib/CoreLibraries.gmk @@ -324,9 +324,6 @@ endif LIBJLI_CFLAGS += $(addprefix -I, $(LIBJLI_SRC_DIRS)) -# Append defines depending on target platform -LIBJLI_CFLAGS += $(OPENJDK_TARGET_CPU_JLI_CFLAGS) - ifneq ($(USE_EXTERNAL_LIBZ), true) LIBJLI_CFLAGS += $(ZLIB_CPPFLAGS) LIBJLI_EXTRA_FILES += \ diff --git a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c index 8205f12f5d4..e299a7e8671 100644 --- a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c +++ b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c @@ -171,8 +171,6 @@ struct NSAppArgs { * Main */ -#define GetArch() GetArchPath(CURRENT_DATA_MODEL) - /* Store the name of the executable once computed */ static char *execname = NULL; @@ -184,16 +182,6 @@ GetExecName() { return execname; } -const char * -GetArchPath(int nbits) -{ - switch(nbits) { - default: - return LIBARCHNAME; - } -} - - /* * Exports the JNI interface from libjli * @@ -211,7 +199,7 @@ static InvocationFunctions *GetExportedJNIFunctions() { if (sExportedJNIFunctions != NULL) return sExportedJNIFunctions; char jrePath[PATH_MAX]; - jboolean gotJREPath = GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE); + jboolean gotJREPath = GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE); if (!gotJREPath) { JLI_ReportErrorMessage("Failed to GetJREPath()"); return NULL; @@ -229,7 +217,7 @@ static InvocationFunctions *GetExportedJNIFunctions() { } char jvmPath[PATH_MAX]; - jboolean gotJVMPath = GetJVMPath(jrePath, preferredJVM, jvmPath, sizeof(jvmPath), GetArch(), CURRENT_DATA_MODEL); + jboolean gotJVMPath = GetJVMPath(jrePath, preferredJVM, jvmPath, sizeof(jvmPath), CURRENT_DATA_MODEL); if (!gotJVMPath) { JLI_ReportErrorMessage("Failed to GetJVMPath()"); return NULL; @@ -390,7 +378,6 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, /* Check data model flags, and exec process, if needed */ { - char *arch = (char *)GetArch(); /* like sparc or sparcv9 */ char * jvmtype = NULL; int argc = *pargc; char **argv = *pargv; @@ -462,7 +449,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, jvmpath does not exist */ if (wanted == running) { /* Find out where the JRE is that we will be using. */ - if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) { + if (!GetJREPath(jrepath, so_jrepath, JNI_FALSE) ) { JLI_ReportErrorMessage(JRE_ERROR1); exit(2); } @@ -481,7 +468,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, exit(4); } - if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch, wanted)) { + if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, wanted)) { JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath); exit(4); } @@ -502,7 +489,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, #if defined(DUAL_MODE) if (running != wanted) { /* Find out where the JRE is that we will be using. */ - if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) { + if (!GetJREPath(jrepath, so_jrepath, JNI_TRUE)) { /* give up and let other code report error message */ JLI_ReportErrorMessage(JRE_ERROR2, wanted); exit(1); @@ -526,7 +513,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, } /* exec child can do error checking on the existence of the path */ - jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted), wanted); + jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, wanted); } #else /* ! DUAL_MODE */ JLI_ReportErrorMessage(JRE_ERROR2, wanted); @@ -579,7 +566,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, */ static jboolean GetJVMPath(const char *jrepath, const char *jvmtype, - char *jvmpath, jint jvmpathsize, const char * arch, int bitsWanted) + char *jvmpath, jint jvmpathsize, int bitsWanted) { struct stat s; @@ -613,7 +600,7 @@ GetJVMPath(const char *jrepath, const char *jvmtype, * Find path to JRE based on .exe's location or registry settings. */ static jboolean -GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) +GetJREPath(char *path, jint pathsize, jboolean speculative) { char libjava[MAXPATHLEN]; @@ -841,7 +828,7 @@ static void* hSplashLib = NULL; void* SplashProcAddress(const char* name) { if (!hSplashLib) { char jrePath[PATH_MAX]; - if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) { + if (!GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE)) { JLI_ReportErrorMessage(JRE_ERROR1); return NULL; } diff --git a/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java b/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java index f26b0108fed..78d9f7fc061 100644 --- a/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java +++ b/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -109,13 +109,9 @@ final class ProcessImpl extends Process { private String helperPath(String javahome, String osArch) { switch (this) { case SOLARIS: - if (osArch.equals("x86")) { osArch = "i386"; } - else if (osArch.equals("x86_64")) { osArch = "amd64"; } // fall through... case LINUX: case AIX: - return javahome + "/lib/" + osArch + "/jspawnhelper"; - case BSD: return javahome + "/lib/jspawnhelper"; diff --git a/jdk/src/java.base/unix/native/libjli/ergo.c b/jdk/src/java.base/unix/native/libjli/ergo.c index 2047087e7c5..461303a2930 100644 --- a/jdk/src/java.base/unix/native/libjli/ergo.c +++ b/jdk/src/java.base/unix/native/libjli/ergo.c @@ -91,7 +91,7 @@ ServerClassMachineImpl(void) { result = JNI_TRUE; } } - JLI_TraceLauncher("unix_" LIBARCHNAME "_ServerClassMachine: %s\n", + JLI_TraceLauncher("unix_ServerClassMachine: %s\n", (result == JNI_TRUE ? "JNI_TRUE" : "JNI_FALSE")); return result; } diff --git a/jdk/src/java.base/unix/native/libjli/ergo_i586.c b/jdk/src/java.base/unix/native/libjli/ergo_i586.c index f2421700289..0df40da0b09 100644 --- a/jdk/src/java.base/unix/native/libjli/ergo_i586.c +++ b/jdk/src/java.base/unix/native/libjli/ergo_i586.c @@ -99,7 +99,7 @@ ServerClassMachineImpl(void) { result = JNI_TRUE; } } - JLI_TraceLauncher("solaris_" LIBARCHNAME "_ServerClassMachine: %s\n", + JLI_TraceLauncher("solaris_ServerClassMachine: %s\n", (result == JNI_TRUE ? "true" : "false")); return result; } @@ -193,7 +193,7 @@ ServerClassMachineImpl(void) { result = JNI_TRUE; } } - JLI_TraceLauncher("linux_" LIBARCHNAME "_ServerClassMachine: %s\n", + JLI_TraceLauncher("linux_ServerClassMachine: %s\n", (result == JNI_TRUE ? "true" : "false")); return result; } diff --git a/jdk/src/java.base/unix/native/libjli/java_md.h b/jdk/src/java.base/unix/native/libjli/java_md.h index 8e95aced972..f0eaa302bd3 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md.h +++ b/jdk/src/java.base/unix/native/libjli/java_md.h @@ -54,10 +54,8 @@ char *FindExecName(char *program); const char *SetExecname(char **argv); const char *GetExecName(); static jboolean GetJVMPath(const char *jrepath, const char *jvmtype, - char *jvmpath, jint jvmpathsize, const char * arch, - int bitsWanted); -static jboolean GetJREPath(char *path, jint pathsize, const char * arch, - jboolean speculative); + char *jvmpath, jint jvmpathsize, int bitsWanted); +static jboolean GetJREPath(char *path, jint pathsize, jboolean speculative); #if defined(_AIX) #include "java_md_aix.h" diff --git a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c index b9091aaead3..30ee9b975a2 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c +++ b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c @@ -52,9 +52,6 @@ #endif #ifdef __solaris__ -# ifndef LIBARCHNAME -# error "The macro LIBARCHNAME was not defined on the compile line" -# endif # include # include # include @@ -188,12 +185,13 @@ JvmExists(const char *path) { return JNI_FALSE; } /* - * contains a lib/$LIBARCHNAME/{server,client}/libjvm.so ? + * contains a lib/{server,client}/libjvm.so ? */ static jboolean ContainsLibJVM(const char *env) { - char clientPattern[PATH_MAX + 1]; - char serverPattern[PATH_MAX + 1]; + /* the usual suspects */ + char clientPattern[] = "lib/client"; + char serverPattern[] = "lib/server"; char *envpath; char *path; jboolean clientPatternFound; @@ -204,10 +202,6 @@ ContainsLibJVM(const char *env) { return JNI_FALSE; } - /* the usual suspects */ - JLI_Snprintf(clientPattern, PATH_MAX, "lib/%s/client", LIBARCHNAME); - JLI_Snprintf(serverPattern, PATH_MAX, "lib/%s/server", LIBARCHNAME); - /* to optimize for time, test if any of our usual suspects are present. */ clientPatternFound = JLI_StrStr(env, clientPattern) != NULL; serverPatternFound = JLI_StrStr(env, serverPattern) != NULL; @@ -322,7 +316,6 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, /* Check data model flags, and exec process, if needed */ { - char *arch = LIBARCHNAME; /* like sparc or sparcv9 */ char * jvmtype = NULL; int argc = *pargc; char **argv = *pargv; @@ -408,12 +401,12 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, jvmpath does not exist */ if (wanted == running) { /* Find out where the JRE is that we will be using. */ - if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) { + if (!GetJREPath(jrepath, so_jrepath, JNI_FALSE) ) { JLI_ReportErrorMessage(JRE_ERROR1); exit(2); } - JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg", - jrepath, FILESEP, FILESEP, arch, FILESEP); + JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%sjvm.cfg", + jrepath, FILESEP, FILESEP, FILESEP); /* Find the specified JVM type */ if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) { JLI_ReportErrorMessage(CFG_ERROR7); @@ -427,7 +420,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, exit(4); } - if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch, 0 )) { + if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, 0 )) { JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath); exit(4); } @@ -457,8 +450,8 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, * We will set the LD_LIBRARY_PATH as follows: * * o $JVMPATH (directory portion only) - * o $JRE/lib/$LIBARCHNAME - * o $JRE/../lib/$LIBARCHNAME + * o $JRE/lib + * o $JRE/../lib * * followed by the user's previous effective LD_LIBRARY_PATH, if * any. @@ -518,10 +511,10 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, jvmpath = JLI_StringDup(jvmpath); new_runpath_size = ((runpath != NULL) ? JLI_StrLen(runpath) : 0) + - 2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) + + 2 * JLI_StrLen(jrepath) + #ifdef AIX /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */ - JLI_StrLen(jrepath) + JLI_StrLen(arch) + JLI_StrLen("/lib//jli:") + + JLI_StrLen(jrepath) + JLI_StrLen("/lib//jli:") + #endif JLI_StrLen(jvmpath) + 52; new_runpath = JLI_MemAlloc(new_runpath_size); @@ -539,17 +532,17 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, sprintf(new_runpath, LD_LIBRARY_PATH "=" "%s:" - "%s/lib/%s:" + "%s/lib:" #ifdef AIX - "%s/lib/%s/jli:" /* Needed on AIX because ld doesn't support $ORIGIN. */ + "%s/lib/jli:" /* Needed on AIX because ld doesn't support $ORIGIN. */ #endif - "%s/../lib/%s", + "%s/../lib", jvmpath, - jrepath, arch, + jrepath, #ifdef AIX - jrepath, arch, + jrepath, #endif - jrepath, arch + jrepath ); @@ -638,14 +631,14 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, */ static jboolean GetJVMPath(const char *jrepath, const char *jvmtype, - char *jvmpath, jint jvmpathsize, const char * arch, int bitsWanted) + char *jvmpath, jint jvmpathsize, int bitsWanted) { struct stat s; if (JLI_StrChr(jvmtype, '/')) { JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype); } else { - JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype); + JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtype); } JLI_TraceLauncher("Does `%s' exist ... ", jvmpath); @@ -663,14 +656,14 @@ GetJVMPath(const char *jrepath, const char *jvmtype, * Find path to JRE based on .exe's location or registry settings. */ static jboolean -GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) +GetJREPath(char *path, jint pathsize, jboolean speculative) { char libjava[MAXPATHLEN]; struct stat s; if (GetApplicationHome(path, pathsize)) { /* Is JRE co-located with the application? */ - JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/%s/" JAVA_DLL, path, arch); + JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path); if (access(libjava, F_OK) == 0) { JLI_TraceLauncher("JRE path is %s\n", path); return JNI_TRUE; @@ -681,7 +674,7 @@ GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) return JNI_FALSE; } /* Does the app ship a private JRE in /jre directory? */ - JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/%s/" JAVA_DLL, path, arch); + JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path); if (access(libjava, F_OK) == 0) { JLI_StrCat(path, "/jre"); JLI_TraceLauncher("JRE path is %s\n", path); @@ -690,7 +683,7 @@ GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) } if (GetApplicationHomeFromDll(path, pathsize)) { - JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/%s/" JAVA_DLL, path, arch); + JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path); if (stat(libjava, &s) == 0) { JLI_TraceLauncher("JRE path is %s\n", path); return JNI_TRUE; @@ -856,12 +849,12 @@ void* SplashProcAddress(const char* name) { char jrePath[MAXPATHLEN]; char splashPath[MAXPATHLEN]; - if (!GetJREPath(jrePath, sizeof(jrePath), LIBARCHNAME, JNI_FALSE)) { + if (!GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE)) { JLI_ReportErrorMessage(JRE_ERROR1); return NULL; } - ret = JLI_Snprintf(splashPath, sizeof(splashPath), "%s/lib/%s/%s", - jrePath, LIBARCHNAME, SPLASHSCREEN_SO); + ret = JLI_Snprintf(splashPath, sizeof(splashPath), "%s/lib/%s", + jrePath, SPLASHSCREEN_SO); if (ret >= (int) sizeof(splashPath)) { JLI_ReportErrorMessage(JRE_ERROR11); diff --git a/jdk/src/java.base/windows/native/libjli/java_md.c b/jdk/src/java.base/windows/native/libjli/java_md.c index 1db3c408740..b08bef3b744 100644 --- a/jdk/src/java.base/windows/native/libjli/java_md.c +++ b/jdk/src/java.base/windows/native/libjli/java_md.c @@ -150,22 +150,6 @@ IsJavaw() return _isjavaw; } -/* - * Returns the arch path, to get the current arch use the - * macro GetArch, nbits here is ignored for now. - */ -const char * -GetArchPath(int nbits) -{ -#ifdef _M_AMD64 - return "amd64"; -#elif defined(_M_IA64) - return "ia64"; -#else - return "i386"; -#endif -} - /* * */ @@ -207,8 +191,8 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, exit(2); } - JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg", - jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP); + JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg", + jrepath, FILESEP, FILESEP); /* Find the specified JVM type */ if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) { diff --git a/jdk/test/java/awt/JAWT/Makefile.unix b/jdk/test/java/awt/JAWT/Makefile.unix index b3be2f9a624..978d6cee043 100644 --- a/jdk/test/java/awt/JAWT/Makefile.unix +++ b/jdk/test/java/awt/JAWT/Makefile.unix @@ -1,4 +1,4 @@ -# Copyright (c) 2012, 2013, 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 @@ -32,7 +32,7 @@ LINK = ld J_INC = $(TESTJAVA)/include INCLUDES = -I$(J_INC) -I$(J_INC)/$(SYST) -I. -LIBS = -L$(TESTJAVA)/lib/$(ARCH) -ljawt -lX11 +LIBS = -L$(TESTJAVA)/lib -ljawt -lX11 all: $(CLASSES) libmylib.so diff --git a/jdk/test/tools/launcher/RunpathTest.java b/jdk/test/tools/launcher/RunpathTest.java index 00e757343c3..2730f5da464 100644 --- a/jdk/test/tools/launcher/RunpathTest.java +++ b/jdk/test/tools/launcher/RunpathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, 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 @@ -64,7 +64,7 @@ public class RunpathTest extends TestHelper { } void testRpath() { - String expectedRpath = ".*RPATH.*\\$ORIGIN/../lib/" + getJreArch() + ".*"; + String expectedRpath = ".*RPATH.*\\$ORIGIN/../lib.*"; elfCheck(javaCmd, expectedRpath); } From b0ec3b0ab48fb871943260923e6c9185b94c4072 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Sun, 11 Dec 2016 12:06:55 -0800 Subject: [PATCH 15/45] 8166417: Integrate Graal-core into JDK for AOT compiler Reviewed-by: iveresov, erikj, ihse, mchung --- .../unix/classes/module-info.java.extra | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 jdk/src/java.base/unix/classes/module-info.java.extra diff --git a/jdk/src/java.base/unix/classes/module-info.java.extra b/jdk/src/java.base/unix/classes/module-info.java.extra new file mode 100644 index 00000000000..c48962703e5 --- /dev/null +++ b/jdk/src/java.base/unix/classes/module-info.java.extra @@ -0,0 +1,33 @@ +/* + * 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. 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. + */ + +// jdk.vm.compiler uses Unsafe and VM classes from jdk.internal.misc +exports jdk.internal.misc to jdk.vm.compiler; +opens jdk.internal.misc to jdk.vm.compiler; + +// jdk.vm.compiler uses com.sun.crypto.provider to generate crypto intrinsics +opens com.sun.crypto.provider to jdk.vm.compiler; + +exports jdk.internal.module to jdk.vm.compiler; From 3c6287a42cfbf6cd22007ccd4f4eaf7ba43f3354 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Sun, 11 Dec 2016 18:47:11 -0800 Subject: [PATCH 16/45] 8171008: Integrate AOT compiler into JDK Reviewed-by: erikj, mchung, twisti, simonis --- jdk/make/launcher/Launcher-jdk.aot.gmk | 37 +++++++++++++++++++ .../unix/classes/module-info.java.extra | 3 ++ 2 files changed, 40 insertions(+) create mode 100644 jdk/make/launcher/Launcher-jdk.aot.gmk diff --git a/jdk/make/launcher/Launcher-jdk.aot.gmk b/jdk/make/launcher/Launcher-jdk.aot.gmk new file mode 100644 index 00000000000..a827a66bc35 --- /dev/null +++ b/jdk/make/launcher/Launcher-jdk.aot.gmk @@ -0,0 +1,37 @@ +# +# 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. 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. +# + +include LauncherCommon.gmk + +$(eval $(call SetupBuildLauncher, jaotc, \ + MAIN_CLASS := jdk.tools.jaotc.Main, \ + JAVA_ARGS := -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI \ + -XX:+UseAOT \ + -Djvmci.UseProfilingInformation=false \ + -Dgraal.UseExceptionProbability=false \ + -Djvmci.Compiler=graal \ + --add-modules ALL-DEFAULT \ + , \ +)) diff --git a/jdk/src/java.base/unix/classes/module-info.java.extra b/jdk/src/java.base/unix/classes/module-info.java.extra index c48962703e5..43f85b0309a 100644 --- a/jdk/src/java.base/unix/classes/module-info.java.extra +++ b/jdk/src/java.base/unix/classes/module-info.java.extra @@ -31,3 +31,6 @@ opens jdk.internal.misc to jdk.vm.compiler; opens com.sun.crypto.provider to jdk.vm.compiler; exports jdk.internal.module to jdk.vm.compiler; + +// AOT uses jdk.internal.misc.Unsafe +exports jdk.internal.misc to jdk.aot; From d98371fcfec13857bf695dd6206f69e54e51fdc9 Mon Sep 17 00:00:00 2001 From: Pavel Rappo Date: Tue, 13 Dec 2016 12:26:18 +0000 Subject: [PATCH 17/45] 8038079: Re-examine integration of SPNEGO authentication @module tags have been removed from the HttpNegotiateServer.java as it turns out exactly the same lines have been already defined in TEST.properties sitting in the same folder Reviewed-by: chegar, dfuchs --- .../classes/sun/net/www/protocol/http/Negotiator.java | 4 +++- jdk/src/java.security.jgss/share/classes/module-info.java | 6 ++++++ jdk/test/ProblemList.txt | 2 -- jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java | 7 ------- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/Negotiator.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/Negotiator.java index 856efe16f41..7993b9d284d 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/Negotiator.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/Negotiator.java @@ -48,7 +48,9 @@ public abstract class Negotiator { Class clazz; Constructor c; try { - clazz = Class.forName("sun.net.www.protocol.http.spnego.NegotiatorImpl", true, null); + clazz = Class.forName("sun.net.www.protocol.http.spnego.NegotiatorImpl", + true, + ClassLoader.getPlatformClassLoader()); c = clazz.getConstructor(HttpCallerInfo.class); } catch (ClassNotFoundException cnfe) { finest(cnfe); diff --git a/jdk/src/java.security.jgss/share/classes/module-info.java b/jdk/src/java.security.jgss/share/classes/module-info.java index 6380721852c..78a72496ace 100644 --- a/jdk/src/java.security.jgss/share/classes/module-info.java +++ b/jdk/src/java.security.jgss/share/classes/module-info.java @@ -42,6 +42,12 @@ module java.security.jgss { jdk.security.jgss; exports sun.security.krb5.internal.ktab to jdk.security.auth; + + // Opens for reflective instantiation of sun.net.www.protocol.http.spnego.NegotiatorImpl + // to sun.net.www.protocol.http.HttpURLConnection + opens sun.net.www.protocol.http.spnego to + java.base; + provides java.security.Provider with sun.security.jgss.SunProvider; provides sun.security.ssl.ClientKeyExchangeService with sun.security.krb5.internal.ssl.Krb5KeyExchangeService; diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 69c91f02c57..e39299b7b97 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -215,8 +215,6 @@ sun/security/tools/keytool/ListKeychainStore.sh 8156889 macosx-a sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java 8026393 generic-all -sun/security/krb5/auto/HttpNegotiateServer.java 8038079 generic-all - sun/security/ssl/SSLSocketImpl/AsyncSSLSocketClose.java 8161232 macosx-all sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java 8171043 windows-all diff --git a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java index 2ef37651374..96245002874 100644 --- a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java +++ b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java @@ -24,13 +24,6 @@ /* * @test * @bug 6578647 6829283 - * @modules java.base/sun.security.util - * java.security.jgss/sun.security.jgss - * java.security.jgss/sun.security.krb5 - * java.security.jgss/sun.security.krb5.internal - * java.security.jgss/sun.security.krb5.internal.ccache - * java.security.jgss/sun.security.krb5.internal.crypto - * java.security.jgss/sun.security.krb5.internal.ktab * @run main/othervm HttpNegotiateServer * @summary Undefined requesting URL in java.net.Authenticator.getPasswordAuthentication() * @summary HTTP/Negotiate: Authenticator triggered again when user cancels the first one From e578c73e8296d1e655266368d5c3a154b0a13e89 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Thu, 15 Dec 2016 22:01:05 +0530 Subject: [PATCH 18/45] 8171316: Add IMPLEMENTOR property to the release file Reviewed-by: jlaskey, erikj, mchung --- .../tools/jlink/ReleaseImplementorTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 jdk/test/tools/jlink/ReleaseImplementorTest.java diff --git a/jdk/test/tools/jlink/ReleaseImplementorTest.java b/jdk/test/tools/jlink/ReleaseImplementorTest.java new file mode 100644 index 00000000000..7f935ea5a1c --- /dev/null +++ b/jdk/test/tools/jlink/ReleaseImplementorTest.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; + +/* + * @test + * @bug 8171316 + * @summary Add IMPLEMENTOR property to the release file + * @run main ReleaseImplementorTest + */ +public class ReleaseImplementorTest { + public static void main(String[] args) throws Exception { + Properties props = new Properties(); + Path release = Paths.get(System.getProperty("test.jdk"), "release"); + try (InputStream in = Files.newInputStream(release)) { + props.load(in); + } + + if (!props.containsKey("IMPLEMENTOR")) { + throw new RuntimeException("IMPLEMENTOR key is missing"); + } + + String implementor = props.getProperty("IMPLEMENTOR"); + if (implementor.length() < 3) { + throw new RuntimeException("IMPLEMENTOR value is not expected length"); + } + + if (implementor.charAt(0) != '"' || + implementor.charAt(implementor.length() - 1) != '"') { + throw new RuntimeException("IMPLEMENTOR value not quoted property"); + } + + System.out.println("IMPLEMENTOR is " + implementor); + } +} From 49393dbb14a0c7d32ef80429f3f856c48bd4e7b1 Mon Sep 17 00:00:00 2001 From: Lance Andersen Date: Thu, 15 Dec 2016 16:24:33 -0500 Subject: [PATCH 19/45] 8169806: DriverManager javadoc clarifications Reviewed-by: mchung --- .../share/classes/java/sql/DriverManager.java | 111 +++++++----------- 1 file changed, 45 insertions(+), 66 deletions(-) diff --git a/jdk/src/java.sql/share/classes/java/sql/DriverManager.java b/jdk/src/java.sql/share/classes/java/sql/DriverManager.java index a32cf8f564d..7fe59001940 100644 --- a/jdk/src/java.sql/share/classes/java/sql/DriverManager.java +++ b/jdk/src/java.sql/share/classes/java/sql/DriverManager.java @@ -41,46 +41,41 @@ import jdk.internal.reflect.Reflection; /** - *

    The basic service for managing a set of JDBC drivers.
    - * NOTE: The {@link javax.sql.DataSource} interface, new in the - * JDBC 2.0 API, provides another way to connect to a data source. - * The use of a DataSource object is the preferred means of + * The basic service for managing a set of JDBC drivers. + *

    + * NOTE: The {@link javax.sql.DataSource} interface, provides + * another way to connect to a data source. + * The use of a {@code DataSource} object is the preferred means of * connecting to a data source. - * - *

    As part of its initialization, the DriverManager class will - * attempt to load the driver classes referenced in the "jdbc.drivers" - * system property. This allows a user to customize the JDBC Drivers - * used by their applications. For example in your - * ~/.hotjava/properties file you might specify: - *

    - * jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver
    - * 
    - *

    The DriverManager methods getConnection and - * getDrivers have been enhanced to support the Java Standard Edition - * Service Provider mechanism. JDBC 4.0 Drivers must - * include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers - * implementation of java.sql.Driver. For example, to load the my.sql.Driver class, - * the META-INF/services/java.sql.Driver file would contain the entry: - *

    - * my.sql.Driver
    - * 
    - * - *

    Applications no longer need to explicitly load JDBC drivers using Class.forName(). Existing programs - * which currently load JDBC drivers using Class.forName() will continue to work without - * modification. - * - *

    When the method getConnection is called, - * the DriverManager will attempt to - * locate a suitable driver from amongst those loaded at - * initialization and those loaded explicitly using the same classloader - * as the current applet or application. - * *

    - * Starting with the Java 2 SDK, Standard Edition, version 1.3, a - * logging stream can be set only if the proper - * permission has been granted. Normally this will be done with - * the tool PolicyTool, which can be used to grant permission - * java.sql.SQLPermission "setLog". + * As part of its initialization, the {@code DriverManager} class will + * attempt to load available JDBC drivers by using: + *

      + *
    • The {@code jdbc.drivers} system property which contains a + * colon separated list of fully qualified class names of JDBC drivers. Each + * driver is loaded using the {@linkplain ClassLoader#getSystemClassLoader + * system class loader}: + *
        + *
      • {@code jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver} + *
      + * + *
    • Service providers of the {@code java.sql.Driver} class, that are loaded + * via the {@linkplain ServiceLoader#load service-provider loading} mechanism. + *
    + * + *

    + * @ImplNote + * {@code DriverManager} initialization is done lazily and looks up service + * providers using the thread context class loader. The drivers loaded and + * available to an application will depend on the thread context class loader of + * the thread that triggers driver initialization by {@code DriverManager}. + * + *

    When the method {@code getConnection} is called, + * the {@code DriverManager} will attempt to + * locate a suitable driver from amongst those loaded at + * initialization and those loaded explicitly using the same class loader + * as the current application. + * * @see Driver * @see Connection */ @@ -137,29 +132,15 @@ public class DriverManager { /** * Sets the logging/tracing PrintWriter object * that is used by the DriverManager and all drivers. - *

    - * There is a minor versioning problem created by the introduction - * of the method setLogWriter. The - * method setLogWriter cannot create a PrintStream object - * that will be returned by getLogStream---the Java platform does - * not provide a backward conversion. As a result, a new application - * that uses setLogWriter and also uses a JDBC 1.0 driver that uses - * getLogStream will likely not see debugging information written - * by that driver. *

    - * Starting with the Java 2 SDK, Standard Edition, version 1.3 release, this method checks - * to see that there is an SQLPermission object before setting - * the logging stream. If a SecurityManager exists and its - * checkPermission method denies setting the log writer, this - * method throws a java.lang.SecurityException. + * If a security manager exists, its {@code checkPermission} + * method is first called with a {@code SQLPermission("setLog")} + * permission to check that the caller is allowed to call {@code setLogWriter}. * * @param out the new logging/tracing PrintStream object; * null to disable logging and tracing - * @throws SecurityException - * if a security manager exists and its - * checkPermission method denies - * setting the log writer - * + * @throws SecurityException if a security manager exists and its + * {@code checkPermission} method denies permission to set the log writer. * @see SecurityManager#checkPermission * @see #getLogWriter * @since 1.2 @@ -374,8 +355,9 @@ public class DriverManager { * If a {@code null} value is specified for the driver to be removed, then no * action is taken. *

    - * If a security manager exists and its {@code checkPermission} denies - * permission, then a {@code SecurityException} will be thrown. + * If a security manager exists, its {@code checkPermission} + * method is first called with a {@code SQLPermission("deregisterDriver")} + * permission to check that the caller is allowed to deregister a JDBC Driver. *

    * If the specified driver is not found in the list of registered drivers, * then no action is taken. If the driver was found, it will be removed @@ -501,17 +483,14 @@ public class DriverManager { * by the DriverManager * and all drivers. *

    - * In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks - * to see that there is an SQLPermission object before setting - * the logging stream. If a SecurityManager exists and its - * checkPermission method denies setting the log writer, this - * method throws a java.lang.SecurityException. + * If a security manager exists, its {@code checkPermission} + * method is first called with a {@code SQLPermission("setLog")} + * permission to check that the caller is allowed to call {@code setLogStream}. * * @param out the new logging/tracing PrintStream; to disable, set to null * @deprecated Use {@code setLogWriter} * @throws SecurityException if a security manager exists and its - * checkPermission method denies setting the log stream - * + * {@code checkPermission} method denies permission to set the log stream. * @see SecurityManager#checkPermission * @see #getLogStream */ From 79a8c66551de1a8f2acdff99969545114c132f75 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Thu, 15 Dec 2016 17:49:13 -0800 Subject: [PATCH 20/45] 8171323: generate dot file for java.se and java.se.ee with only API dependences Reviewed-by: psandoz --- .../classes/build/tools/jigsaw/GenGraphs.java | 161 +++++++++++------- 1 file changed, 96 insertions(+), 65 deletions(-) diff --git a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java index 3b81f6b421f..5fbc5b5f9e2 100644 --- a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java +++ b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java @@ -26,6 +26,7 @@ package build.tools.jigsaw; import java.io.IOException; +import java.io.OutputStream; import java.io.PrintStream; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; @@ -44,7 +45,8 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; -import java.util.stream.Collectors; + +import static java.util.stream.Collectors.*; import static java.lang.module.ModuleDescriptor.Requires.Modifier.TRANSITIVE; /** @@ -69,42 +71,25 @@ public class GenGraphs { .map(ModuleReference::descriptor) .filter(m -> (m.name().startsWith("java.") && !m.name().equals("java.smartcardio"))) - .collect(Collectors.toSet())); + .collect(toSet())); Set jdkModules = new TreeSet<>(finder.findAll().stream() .map(ModuleReference::descriptor) .filter(m -> !javaSEModules.contains(m)) - .collect(Collectors.toSet())); + .collect(toSet())); - GenGraphs genGraphs = new GenGraphs(javaSEModules, jdkModules); + GenGraphs genGraphs = new GenGraphs(dir, javaSEModules, jdkModules); Set mods = new HashSet<>(); for (ModuleReference mref: finder.findAll()) { - ModuleDescriptor descriptor = mref.descriptor(); - String name = descriptor.name(); - mods.add(name); - Configuration cf = Configuration.empty() - .resolveRequires(finder, - ModuleFinder.of(), - Set.of(name)); - genGraphs.genDotFile(dir, name, cf); + mods.add(mref.descriptor().name()); + genGraphs.genDotFile(mref); } - Configuration cf = Configuration.empty() - .resolveRequires(finder, - ModuleFinder.of(), - mods); - genGraphs.genDotFile(dir, "jdk", cf); + // all modules + genGraphs.genDotFile("jdk", mods); } - private final Set javaGroup; - private final Set jdkGroup; - - GenGraphs(Set javaGroup, Set jdkGroup) { - this.javaGroup = Collections.unmodifiableSet(javaGroup); - this.jdkGroup = Collections.unmodifiableSet(jdkGroup); - } - private static final String ORANGE = "#e76f00"; private static final String BLUE = "#437291"; private static final String GRAY = "#dddddd"; @@ -145,23 +130,70 @@ public class GenGraphs { } - private void genDotFile(Path dir, String name, Configuration cf) throws IOException { - try (PrintStream out - = new PrintStream(Files.newOutputStream(dir.resolve(name + ".dot")))) { + private final Path dir; + private final Set javaGroup; + private final Set jdkGroup; - Map nameToModule; - if (name.equals("java.se.ee")) { - nameToModule = cf.modules().stream() - .map(ResolvedModule::reference) - .map(ModuleReference::descriptor) - .filter(md -> !md.name().startsWith("jdk.")) - .collect(Collectors.toMap(ModuleDescriptor::name, Function.identity())); - } else { - nameToModule = cf.modules().stream() - .map(ResolvedModule::reference) - .map(ModuleReference::descriptor) - .collect(Collectors.toMap(ModuleDescriptor::name, Function.identity())); + GenGraphs(Path dir, Set javaGroup, Set jdkGroup) { + this.dir = dir; + this.javaGroup = Collections.unmodifiableSet(javaGroup); + this.jdkGroup = Collections.unmodifiableSet(jdkGroup); + } + + /** + * Generates a dot file for the given module reference as the root. + */ + void genDotFile(ModuleReference mref) throws IOException { + String name = mref.descriptor().name(); + genDotFile(name, Set.of(name)); + } + + /** + * Generates a dot file for the given set of root modules. + */ + void genDotFile(String name, Set roots) throws IOException { + Configuration cf = + Configuration.empty().resolveRequires(ModuleFinder.ofSystem(), + ModuleFinder.of(), + roots); + + Set mds = cf.modules().stream() + .map(ResolvedModule::reference) + .map(ModuleReference::descriptor) + .collect(toSet()); + + // generate a dot file for the resolved graph + try (OutputStream os = Files.newOutputStream(dir.resolve(name + ".dot")); + PrintStream out = new PrintStream(os)) { + printGraph(out, name, gengraph(cf), + mds.stream() + .collect(toMap(ModuleDescriptor::name, Function.identity())) + ); + } + + if (name.equals("java.se") || name.equals("java.se.ee")) { + // generate a dot file for Java SE module graph + try (OutputStream os = Files.newOutputStream(dir.resolve(name + "-spec.dot")); + PrintStream out = new PrintStream(os)) { + // transitive reduction on the graph of `requires transitive` edges + // filter out jdk.* modules which are implementation dependences + Graph graph = requiresTransitiveGraph(cf, true); + printGraph(out, name, graph, + mds.stream() + .filter(md -> !md.name().startsWith("jdk.") && + graph.nodes().contains(md.name())) + .collect(toMap(ModuleDescriptor::name, Function.identity())) + ); } + } + } + + private void printGraph(PrintStream out, + String name, + Graph graph, + Map nameToModule) + throws IOException + { Set descriptors = new TreeSet<>(nameToModule.values()); out.format("digraph \"%s\" {%n", name); @@ -187,7 +219,7 @@ public class GenGraphs { .map(ModuleDescriptor::name) .filter(group::contains) .map(mn -> "\"" + mn + "\"") - .collect(Collectors.joining(",")) + .collect(joining(",")) )); descriptors.stream() @@ -196,30 +228,28 @@ public class GenGraphs { .forEach(mn -> out.format(" \"%s\" [fontcolor=\"%s\", group=%s];%n", mn, BLUE, "jdk")); - // transitive reduction - Graph graph = gengraph(cf); - descriptors.forEach(md -> { - String mn = md.name(); - Set requiresTransitive = md.requires().stream() - .filter(d -> d.modifiers().contains(TRANSITIVE)) - .map(d -> d.name()) - .collect(Collectors.toSet()); + descriptors.stream() + .forEach(md -> { + String mn = md.name(); + Set requiresTransitive = md.requires().stream() + .filter(d -> d.modifiers().contains(TRANSITIVE)) + .map(d -> d.name()) + .collect(toSet()); - graph.adjacentNodes(mn) - .stream() - .filter(nameToModule::containsKey) - .forEach(dn -> { - String attr = dn.equals("java.base") ? REQUIRES_BASE - : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES); - int w = weightOf(mn, dn); - if (w > 1) - attr += "weight=" + w; - out.format(" \"%s\" -> \"%s\" [%s];%n", mn, dn, attr); - }); - }); + graph.adjacentNodes(mn) + .stream() + .filter(nameToModule::containsKey) + .forEach(dn -> { + String attr = dn.equals("java.base") ? REQUIRES_BASE + : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES); + int w = weightOf(mn, dn); + if (w > 1) + attr += "weight=" + w; + out.format(" \"%s\" -> \"%s\" [%s];%n", mn, dn, attr); + }); + }); out.println("}"); - } } /** @@ -239,7 +269,7 @@ public class GenGraphs { .map(ResolvedModule::name) .forEach(target -> builder.addEdge(mn, target)); } - Graph rpg = requiresTransitiveGraph(cf); + Graph rpg = requiresTransitiveGraph(cf, false); return builder.build().reduce(rpg); } @@ -247,13 +277,14 @@ public class GenGraphs { * Returns a Graph containing only requires transitive edges * with transitive reduction. */ - private Graph requiresTransitiveGraph(Configuration cf) { + private Graph requiresTransitiveGraph(Configuration cf, boolean includeBase) { Graph.Builder builder = new Graph.Builder<>(); for (ResolvedModule resolvedModule : cf.modules()) { ModuleDescriptor descriptor = resolvedModule.reference().descriptor(); String mn = descriptor.name(); descriptor.requires().stream() - .filter(d -> d.modifiers().contains(TRANSITIVE)) + .filter(d -> d.modifiers().contains(TRANSITIVE) + || (includeBase && d.name().equals("java.base"))) .map(d -> d.name()) .forEach(d -> builder.addEdge(mn, d)); } From d75381730e9488e2463eeef8f6c91e5d714814ef Mon Sep 17 00:00:00 2001 From: John Jiang Date: Fri, 16 Dec 2016 12:57:16 +0800 Subject: [PATCH 21/45] 8171297: ProblemList javax/net/ssl/DTLS/PacketLossRetransmission.java due to JDK-8169086 Puts javax/net/ssl/DTLS/PacketLossRetransmission.java into ProblemList due to JDK-8169086 Reviewed-by: xuelei --- jdk/test/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 4329ffb0f27..9f5e3fee58b 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -217,6 +217,8 @@ sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java 8026393 generic- sun/security/ssl/SSLSocketImpl/AsyncSSLSocketClose.java 8161232 macosx-all +javax/net/ssl/DTLS/PacketLossRetransmission.java 8169086 macosx-x64 + ############################################################################ # jdk_sound From 1e82db676a015bcf937d47499d28189fad3ce8e0 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Fri, 16 Dec 2016 06:19:16 +0000 Subject: [PATCH 22/45] 8170987: Module system implementation refresh (12/2016) 8170859: Run time and tool support for ModuleResolution Co-authored-by: Mandy Chung Co-authored-by: Chris Hegarty Co-authored-by: Mark Reinhold Co-authored-by: John Rose Reviewed-by: redestad, mchung, alanb --- .../sun/java/util/jar/pack/PackerImpl.java | 2 +- .../java/util/jar/pack/intrinsic.properties | 9 - .../classes/java/lang/StackTraceElement.java | 19 +- .../java/lang/invoke/MethodHandles.java | 43 +- .../java/lang/module/ModuleDescriptor.java | 291 +++++---- .../java/lang/module/ModuleFinder.java | 6 +- .../java/lang/module/ModuleReference.java | 194 +----- .../classes/java/lang/module/Resolver.java | 25 +- .../java/lang/reflect/AccessibleObject.java | 49 +- .../classes/java/lang/reflect/Layer.java | 3 +- .../classes/java/lang/reflect/Module.java | 25 +- .../StringSharingDecompressor.java | 6 +- .../internal/misc/JavaLangModuleAccess.java | 47 +- .../misc/JavaLangReflectModuleAccess.java | 8 + .../classes/jdk/internal/module/Builder.java | 75 +-- .../classes/jdk/internal/module/Checks.java | 219 +++++-- .../internal/module/ClassFileAttributes.java | 299 +++++---- .../internal/module/ClassFileConstants.java | 8 +- .../jdk/internal/module/ModuleBootstrap.java | 91 ++- .../jdk/internal/module/ModuleHashes.java | 37 +- .../internal}/module/ModuleInfo.java | 370 ++++++++--- .../internal/module/ModuleInfoExtender.java | 18 +- .../jdk/internal/module/ModuleInfoWriter.java | 12 +- .../jdk/internal/module/ModulePatcher.java | 19 +- .../internal}/module/ModulePath.java | 39 +- .../internal/module/ModuleReferenceImpl.java | 169 +++++ .../internal}/module/ModuleReferences.java | 29 +- .../jdk/internal/module/ModuleResolution.java | 114 ++++ .../internal}/module/SystemModuleFinder.java | 238 ++++--- .../jdk/internal/module/SystemModules.java | 29 +- .../org/objectweb/asm/ClassReader.java | 36 ++ .../org/objectweb/asm/ClassWriter.java | 54 ++ .../jdk/internal/org/objectweb/asm/Item.java | 4 + .../jdk/internal/reflect/Reflection.java | 68 +- .../share/classes/module-info.java | 1 + .../share/classes/module-info.java | 1 + .../share/classes/module-info.java | 1 + .../share/classes/module-info.java | 1 + .../sun/tools/jar/GNUStyleOptions.java | 62 +- .../share/classes/sun/tools/jar/Main.java | 46 +- .../sun/tools/jar/resources/jar.properties | 10 + .../jdk/tools/jlink/internal/JlinkTask.java | 41 +- .../internal/ResourcePoolConfiguration.java | 11 +- .../jdk/tools/jlink/internal/TaskHelper.java | 6 +- ...orPlugin.java => SystemModulesPlugin.java} | 608 +++++++++++------- .../classes/jdk/tools/jmod/JmodTask.java | 115 +++- .../jdk/tools/jmod/resources/jmod.properties | 6 + .../jdk.jlink/share/classes/module-info.java | 2 +- .../share/classes/module-info.java | 1 + .../java/lang/invoke/DropLookupModeTest.java | 152 +++++ .../test/p/PrivateLookupInTests.java | 3 +- .../lang/module/ModuleDescriptorTest.java | 124 ++-- .../java/lang/module/ModuleNamesTest.java | 261 ++++++++ .../module/ModuleReader/ModuleReaderTest.java | 8 +- .../java/lang/module/ModuleReferenceTest.java | 72 +-- .../lang/reflect/Module/AnnotationsTest.java | 1 - .../jdk/modules/incubator/DefaultImage.java | 158 +++++ .../jdk/modules/incubator/ImageModules.java | 382 +++++++++++ .../src/cp/listmods/ListModules.java | 39 ++ .../src/cp/test/ConvertToLowerCase.java | 40 ++ .../incubator/src/cp/test/WriteUpperCase.java | 40 ++ .../converter/MessageConverter.java | 34 + .../src/message.converter/module-info.java | 26 + .../src/message.writer/module-info.java | 27 + .../message.writer/writer/MessageWriter.java | 38 ++ jdk/test/lib/testlibrary/ModuleUtils.java | 10 +- .../tools/jar/compat/CLICompatibility.java | 18 +- .../modularJar/src/bar/jdk/test/bar/Bar.java | 19 +- jdk/test/tools/jimage/VerifyJimage.java | 2 +- .../CompiledVersionTest.java | 129 ++++ .../SystemModulesTest.java | 2 +- .../UserModuleTest.java | 2 +- .../src/test/jdk/test/Main.java | 104 +++ .../src/test/module-info.java | 28 + jdk/test/tools/jmod/JmodTest.java | 19 +- jdk/test/tools/jmod/hashes/HashesTest.java | 38 +- .../src/xmlkit/ClassReader.java | 52 +- 77 files changed, 4039 insertions(+), 1356 deletions(-) rename jdk/src/java.base/share/classes/{java/lang => jdk/internal}/module/ModuleInfo.java (69%) rename jdk/src/java.base/share/classes/{java/lang => jdk/internal}/module/ModulePath.java (95%) create mode 100644 jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java rename jdk/src/java.base/share/classes/{java/lang => jdk/internal}/module/ModuleReferences.java (92%) create mode 100644 jdk/src/java.base/share/classes/jdk/internal/module/ModuleResolution.java rename jdk/src/java.base/share/classes/{java/lang => jdk/internal}/module/SystemModuleFinder.java (79%) rename jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/{SystemModuleDescriptorPlugin.java => SystemModulesPlugin.java} (67%) create mode 100644 jdk/test/java/lang/invoke/DropLookupModeTest.java create mode 100644 jdk/test/java/lang/module/ModuleNamesTest.java create mode 100644 jdk/test/jdk/modules/incubator/DefaultImage.java create mode 100644 jdk/test/jdk/modules/incubator/ImageModules.java create mode 100644 jdk/test/jdk/modules/incubator/src/cp/listmods/ListModules.java create mode 100644 jdk/test/jdk/modules/incubator/src/cp/test/ConvertToLowerCase.java create mode 100644 jdk/test/jdk/modules/incubator/src/cp/test/WriteUpperCase.java create mode 100644 jdk/test/jdk/modules/incubator/src/message.converter/converter/MessageConverter.java create mode 100644 jdk/test/jdk/modules/incubator/src/message.converter/module-info.java create mode 100644 jdk/test/jdk/modules/incubator/src/message.writer/module-info.java create mode 100644 jdk/test/jdk/modules/incubator/src/message.writer/writer/MessageWriter.java create mode 100644 jdk/test/tools/jlink/plugins/SystemModuleDescriptors/CompiledVersionTest.java create mode 100644 jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/jdk/test/Main.java create mode 100644 jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/module-info.java diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java index 203fde39335..fa36c3feda4 100644 --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackerImpl.java @@ -317,7 +317,7 @@ public class PackerImpl extends TLGlobals implements Pack200.Packer { this(null, je); } boolean isClassFile() { - if (!name.endsWith(".class")) { + if (!name.endsWith(".class") || name.endsWith("module-info.class")) { return false; } for (String prefix = name;;) { diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/intrinsic.properties b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/intrinsic.properties index 14bc2ad8831..c31b1a03a50 100644 --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/intrinsic.properties +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/intrinsic.properties @@ -14,15 +14,6 @@ pack.code.attribute.CharacterRangeTable = NH[PHPOHIIH] pack.class.attribute.SourceID = RUH pack.class.attribute.CompilationID = RUH -# Module attributes, supported by the tool and not JSR-200 -pack.class.attribute.Module = RUHFHNH[RUHFH]NH[RUHFHNH[RUH]]NH[RUHFHNH[RUH]]NH[RCH]NH[RCHNH[RCH]] -pack.class.attribute.ModulePackages = NH[RUH] -pack.class.attribute.ModuleVersion = RUH -pack.class.attribute.ModuleMainClass = RCH -pack.class.attribute.ModuleTarget = RUHRUHRUH -pack.class.attribute.ModuleHashes = RUHNH[RUHNH[B]] - - # Note: Zero-length ("marker") attributes do not need to be specified here. # They are automatically defined to have an empty layout. #pack.class.attribute.Deprecated = diff --git a/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java b/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java index 04ba817a553..b84a0ba2385 100644 --- a/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java +++ b/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java @@ -26,11 +26,13 @@ package java.lang; import jdk.internal.loader.BuiltinClassLoader; -import jdk.internal.misc.SharedSecrets; import jdk.internal.misc.VM; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleReferenceImpl; import java.lang.module.ModuleDescriptor.Version; +import java.lang.module.ModuleReference; +import java.lang.module.ResolvedModule; import java.lang.reflect.Layer; import java.lang.reflect.Module; import java.util.HashSet; @@ -484,13 +486,16 @@ public final class StackTraceElement implements java.io.Serializable { static Set HASHED_MODULES = hashedModules(); static Set hashedModules() { - Module javaBase = Layer.boot().findModule("java.base").get(); - Optional ohashes = - SharedSecrets.getJavaLangModuleAccess() - .hashes(javaBase.getDescriptor()); - if (ohashes.isPresent()) { - Set names = new HashSet<>(ohashes.get().names()); + Optional resolvedModule = Layer.boot() + .configuration() + .findModule("java.base"); + assert resolvedModule.isPresent(); + ModuleReference mref = resolvedModule.get().reference(); + assert mref instanceof ModuleReferenceImpl; + ModuleHashes hashes = ((ModuleReferenceImpl)mref).recordedHashes(); + if (hashes != null) { + Set names = new HashSet<>(hashes.names()); names.add("java.base"); return names; } diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java index 0c9da2c9e80..d195d3d3db8 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java @@ -172,6 +172,7 @@ public class MethodHandles { * @throws IllegalAccessException if the access check specified above fails * @throws SecurityException if denied by the security manager * @since 9 + * @see Lookup#dropLookupMode */ public static Lookup privateLookupIn(Class targetClass, Lookup lookup) throws IllegalAccessException { SecurityManager sm = System.getSecurityManager(); @@ -691,10 +692,15 @@ public class MethodHandles { * A lookup object on a new lookup class * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} * may have some mode bits set to zero. + * Mode bits can also be + * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. + * Once cleared, mode bits cannot be restored from the downgraded lookup object. * The purpose of this is to restrict access via the new lookup object, * so that it can access only names which can be reached by the original * lookup object, and also by the new lookup class. * @return the lookup modes, which limit the kinds of access performed by this lookup object + * @see #in + * @see #dropLookupMode */ public int lookupModes() { return allowedModes & ALL_MODES; @@ -748,7 +754,8 @@ public class MethodHandles { * which may change due to this operation. * * @param requestedLookupClass the desired lookup class for the new lookup object - * @return a lookup object which reports the desired lookup class + * @return a lookup object which reports the desired lookup class, or the same object + * if there is no change * @throws NullPointerException if the argument is null */ public Lookup in(Class requestedLookupClass) { @@ -788,6 +795,40 @@ public class MethodHandles { return new Lookup(requestedLookupClass, newModes); } + + /** + * Creates a lookup on the same lookup class which this lookup object + * finds members, but with a lookup mode that has lost the given lookup mode. + * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE + * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}. + * {@link #PROTECTED PROTECTED} is always dropped and so the resulting lookup + * mode will never have this access capability. When dropping {@code PACKAGE} + * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} + * access. When dropping {@code MODULE} then the resulting lookup will not + * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code + * PUBLIC} is dropped then the resulting lookup has no access. + * @param modeToDrop the lookup mode to drop + * @return a lookup object which lacks the indicated mode, or the same object if there is no change + * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, + * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED} or {@code PRIVATE} + * @since 9 + * @see MethodHandles#privateLookupIn + */ + public Lookup dropLookupMode(int modeToDrop) { + int oldModes = lookupModes(); + int newModes = oldModes & ~(modeToDrop | PROTECTED); + switch (modeToDrop) { + case PUBLIC: newModes &= ~(ALL_MODES); break; + case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; + case PACKAGE: newModes &= ~(PRIVATE); break; + case PROTECTED: + case PRIVATE: break; + default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); + } + if (newModes == oldModes) return this; // return self if no change + return new Lookup(lookupClass(), newModes); + } + // Make sure outer class is initialized first. static { IMPL_NAMES.getClass(); } diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java b/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java index b527ffaeafb..b10d986ade9 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java +++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java @@ -29,7 +29,6 @@ import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.io.UncheckedIOException; -import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.ArrayList; @@ -38,7 +37,6 @@ import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -52,7 +50,7 @@ import static jdk.internal.module.Checks.*; import static java.util.Objects.*; import jdk.internal.module.Checks; -import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleInfo; /** @@ -123,8 +121,9 @@ public class ModuleDescriptor private final Set mods; private final String name; + private final Version compiledVersion; - private Requires(Set ms, String mn) { + private Requires(Set ms, String mn, Version v) { if (ms.isEmpty()) { ms = Collections.emptySet(); } else { @@ -132,11 +131,13 @@ public class ModuleDescriptor } this.mods = ms; this.name = mn; + this.compiledVersion = v; } - private Requires(Set ms, String mn, boolean unused) { + private Requires(Set ms, String mn, Version v, boolean unused) { this.mods = ms; this.name = mn; + this.compiledVersion = v; } /** @@ -157,13 +158,27 @@ public class ModuleDescriptor return name; } + /** + * Returns the version of the module if recorded at compile-time. + * + * @return The version of the module if recorded at compile-time + */ + public Optional compiledVersion() { + return Optional.ofNullable(compiledVersion); + } + /** * Compares this module dependence to another. * *

    Two {@code Requires} objects are compared by comparing their * module name lexicographically. Where the module names are equal then * the sets of modifiers are compared based on a value computed from the - * ordinal of each modifier.

    + * ordinal of each modifier. Where the module names are equal and the + * set of modifiers are equal then the version of the modules recorded + * at compile-time are compared. When comparing the versions recorded + * at compile-time then a dependence that has a recorded version is + * considered to succeed a dependence that does not have a recorded + * version.

    * * @return A negative integer, zero, or a positive integer if this module * dependence is less than, equal to, or greater than the given @@ -174,8 +189,24 @@ public class ModuleDescriptor int c = this.name().compareTo(that.name()); if (c != 0) return c; - // same name, compare by modifiers - return Long.compare(this.modsValue(), that.modsValue()); + + // modifiers + c = Long.compare(this.modsValue(), that.modsValue()); + if (c != 0) + return c; + + // compiledVersion + if (this.compiledVersion != null) { + if (that.compiledVersion != null) + c = this.compiledVersion.compareTo(that.compiledVersion); + else + c = 1; + } else { + if (that.compiledVersion != null) + c = -1; + } + + return c; } /** @@ -195,7 +226,9 @@ public class ModuleDescriptor * *

    If the given object is not a {@code Requires} then this method * returns {@code false}. Two module dependence objects are equal if - * the module names are equal and set of modifiers are equal.

    + * the module names are equal, set of modifiers are equal, and the + * compiled version of both modules is equal or not recorded for + * both modules.

    * *

    This method satisfies the general contract of the {@link * java.lang.Object#equals(Object) Object.equals} method.

    @@ -211,21 +244,25 @@ public class ModuleDescriptor if (!(ob instanceof Requires)) return false; Requires that = (Requires)ob; - return (name.equals(that.name) && mods.equals(that.mods)); + return name.equals(that.name) && mods.equals(that.mods) + && Objects.equals(compiledVersion, that.compiledVersion); } /** * Computes a hash code for this module dependence. * - *

    The hash code is based upon the module name and modifiers. It - * satisfies the general contract of the {@link Object#hashCode - * Object.hashCode} method.

    + *

    The hash code is based upon the module name, modifiers, and the + * module version if recorded at compile time. It satisfies the general + * contract of the {@link Object#hashCode Object.hashCode} method.

    * * @return The hash-code value for this module dependence */ @Override public int hashCode() { - return name.hashCode() * 43 + mods.hashCode(); + int hash = name.hashCode() * 43 + mods.hashCode(); + if (compiledVersion != null) + hash = hash * 43 + compiledVersion.hashCode(); + return hash; } /** @@ -235,7 +272,13 @@ public class ModuleDescriptor */ @Override public String toString() { - return ModuleDescriptor.toString(mods, name); + String what; + if (compiledVersion != null) { + what = name() + " (@" + compiledVersion + ")"; + } else { + what = name(); + } + return ModuleDescriptor.toString(mods, what); } } @@ -967,9 +1010,8 @@ public class ModuleDescriptor } - - // From module declarations private final String name; + private final Version version; private final boolean open; // Indicates if synthesised for a JAR file found on the module path @@ -984,17 +1026,16 @@ public class ModuleDescriptor private final Set uses; private final Set provides; - // "Extended" information, added post-compilation by tools - private final Version version; + // Added post-compilation by tools + private final Set packages; private final String mainClass; private final String osName; private final String osArch; private final String osVersion; - private final Set packages; - private final ModuleHashes hashes; private ModuleDescriptor(String name, + Version version, boolean open, boolean automatic, boolean synthetic, @@ -1003,16 +1044,14 @@ public class ModuleDescriptor Set opens, Set uses, Set provides, - Version version, + Set packages, String mainClass, String osName, String osArch, - String osVersion, - Set packages, - ModuleHashes hashes) + String osVersion) { - this.name = name; + this.version = version; this.open = open; this.automatic = automatic; this.synthetic = synthetic; @@ -1020,18 +1059,16 @@ public class ModuleDescriptor assert (requires.stream().map(Requires::name).distinct().count() == requires.size()); this.requires = emptyOrUnmodifiableSet(requires); - this.exports = emptyOrUnmodifiableSet(exports); this.opens = emptyOrUnmodifiableSet(opens); this.uses = emptyOrUnmodifiableSet(uses); this.provides = emptyOrUnmodifiableSet(provides); - this.version = version; + + this.packages = emptyOrUnmodifiableSet(packages); this.mainClass = mainClass; this.osName = osName; this.osArch = osArch; this.osVersion = osVersion; - this.hashes = hashes; - this.packages = emptyOrUnmodifiableSet(packages); } /** @@ -1039,6 +1076,7 @@ public class ModuleDescriptor */ ModuleDescriptor(ModuleDescriptor md, Set pkgs) { this.name = md.name; + this.version = md.version; this.open = md.open; this.automatic = md.automatic; this.synthetic = md.synthetic; @@ -1049,16 +1087,14 @@ public class ModuleDescriptor this.uses = md.uses; this.provides = md.provides; - this.version = md.version; + Set packages = new HashSet<>(md.packages); + packages.addAll(pkgs); + this.packages = emptyOrUnmodifiableSet(packages); + this.mainClass = md.mainClass; this.osName = md.osName; this.osArch = md.osArch; this.osVersion = md.osVersion; - this.hashes = null; // need to ignore - - Set packages = new HashSet<>(md.packages); - packages.addAll(pkgs); - this.packages = emptyOrUnmodifiableSet(packages); } /** @@ -1066,6 +1102,7 @@ public class ModuleDescriptor * The arguments are pre-validated and sets are unmodifiable sets. */ ModuleDescriptor(String name, + Version version, boolean open, boolean automatic, boolean synthetic, @@ -1074,16 +1111,15 @@ public class ModuleDescriptor Set opens, Set uses, Set provides, - Version version, + Set packages, String mainClass, String osName, String osArch, String osVersion, - Set packages, - ModuleHashes hashes, int hashCode, boolean unused) { this.name = name; + this.version = version; this.open = open; this.automatic = automatic; this.synthetic = synthetic; @@ -1093,12 +1129,10 @@ public class ModuleDescriptor this.uses = uses; this.provides = provides; this.packages = packages; - this.version = version; this.mainClass = mainClass; this.osName = osName; this.osArch = osArch; this.osVersion = osVersion; - this.hashes = hashes; this.hash = hashCode; } @@ -1284,13 +1318,6 @@ public class ModuleDescriptor return packages; } - /** - * Returns the object with the hashes of other modules - */ - Optional hashes() { - return Optional.ofNullable(hashes); - } - /** * A builder used for building {@link ModuleDescriptor} objects. @@ -1317,15 +1344,13 @@ public class ModuleDescriptor public static final class Builder { final String name; final boolean strict; // true if module names are checked - boolean open; + final boolean open; + final boolean synthetic; boolean automatic; - boolean synthetic; final Map requires = new HashMap<>(); - final Map exports = new HashMap<>(); final Map opens = new HashMap<>(); final Set concealedPackages = new HashSet<>(); - final Set uses = new HashSet<>(); final Map provides = new HashMap<>(); Version version; @@ -1333,7 +1358,6 @@ public class ModuleDescriptor String osArch; String osVersion; String mainClass; - ModuleHashes hashes; /** * Initializes a new builder with the given module name. @@ -1341,14 +1365,11 @@ public class ModuleDescriptor * @param strict * Indicates whether module names are checked or not */ - Builder(String name, boolean strict) { - this.strict = strict; + Builder(String name, boolean strict, boolean open, boolean synthetic) { this.name = (strict) ? requireModuleName(name) : name; - } - - /* package */ Builder open(boolean open) { + this.strict = strict; this.open = open; - return this; + this.synthetic = synthetic; } /* package */ Builder automatic(boolean automatic) { @@ -1356,10 +1377,20 @@ public class ModuleDescriptor return this; } - /* package */ boolean isOpen() { return open; } + /** + * Returns the set of packages that are exported (unconditionally or + * unconditionally). + */ + /* package */ Set exportedPackages() { + return exports.keySet(); + } - /* package */ boolean isAutomatic() { - return automatic; + /** + * Returns the set of packages that are opened (unconditionally or + * unconditionally). + */ + /* package */Set openPackages() { + return opens.keySet(); } /** @@ -1387,6 +1418,36 @@ public class ModuleDescriptor return this; } + /** + * Adds a dependence on a module with the given (and possibly empty) + * set of modifiers. The dependence includes the version of the + * module that that was recorded at compile-time. + * + * @param ms + * The set of modifiers + * @param mn + * The module name + * @param compiledVersion + * The version of the module recorded at compile-time + * + * @return This builder + * + * @throws IllegalArgumentException + * If the module name is {@code null}, is not a legal Java + * identifier, or is equal to the module name that this builder + * was initialized to build + * @throws IllegalStateException + * If the dependence on the module has already been declared + */ + public Builder requires(Set ms, + String mn, + Version compiledVersion) { + Objects.requireNonNull(compiledVersion); + if (strict) + mn = requireModuleName(mn); + return requires(new Requires(ms, mn, compiledVersion)); + } + /** * Adds a dependence on a module with the given (and possibly empty) * set of modifiers. @@ -1408,7 +1469,7 @@ public class ModuleDescriptor public Builder requires(Set ms, String mn) { if (strict) mn = requireModuleName(mn); - return requires(new Requires(ms, mn)); + return requires(new Requires(ms, mn, null)); } /** @@ -1705,17 +1766,6 @@ public class ModuleDescriptor return opens(Collections.emptySet(), pn); } - - // Used by ModuleInfo, after a packageFinder is invoked - /* package */ Set exportedAndOpenPackages() { - if (opens.isEmpty()) - return exports.keySet(); - Set result = new HashSet<>(); - result.addAll(exports.keySet()); - result.addAll(opens.keySet()); - return result; - } - /** * Adds a service dependence. * @@ -1789,7 +1839,6 @@ public class ModuleDescriptor if (providerNames.isEmpty()) throw new IllegalArgumentException("Empty providers set"); providerNames.forEach(Checks::requireServiceProviderName); - provides.put(service, p); return this; } @@ -1914,7 +1963,7 @@ public class ModuleDescriptor * If {@code mainClass} is null or is not a legal Java identifier */ public Builder mainClass(String mc) { - mainClass = requireJavaIdentifier("main class name", mc); + mainClass = requireBinaryName("main class name", mc); return this; } @@ -1972,16 +2021,6 @@ public class ModuleDescriptor return this; } - /* package */ Builder hashes(ModuleHashes hashes) { - this.hashes = hashes; - return this; - } - - /* package */ Builder synthetic(boolean v) { - this.synthetic = v; - return this; - } - /** * Builds and returns a {@code ModuleDescriptor} from its components. * @@ -1990,7 +2029,9 @@ public class ModuleDescriptor public ModuleDescriptor build() { Set requires = new HashSet<>(this.requires.values()); - Set packages = new HashSet<>(exportedAndOpenPackages()); + Set packages = new HashSet<>(); + packages.addAll(exports.keySet()); + packages.addAll(opens.keySet()); packages.addAll(concealedPackages); Set exports = new HashSet<>(this.exports.values()); @@ -1999,6 +2040,7 @@ public class ModuleDescriptor Set provides = new HashSet<>(this.provides.values()); return new ModuleDescriptor(name, + version, open, automatic, synthetic, @@ -2007,13 +2049,11 @@ public class ModuleDescriptor opens, uses, provides, - version, + packages, mainClass, osName, osArch, - osVersion, - packages, - hashes); + osVersion); } } @@ -2088,8 +2128,7 @@ public class ModuleDescriptor && Objects.equals(osName, that.osName) && Objects.equals(osArch, that.osArch) && Objects.equals(osVersion, that.osVersion) - && Objects.equals(packages, that.packages) - && Objects.equals(hashes, that.hashes)); + && Objects.equals(packages, that.packages)); } private transient int hash; // cached hash code @@ -2122,7 +2161,6 @@ public class ModuleDescriptor hc = hc * 43 + Objects.hashCode(osArch); hc = hc * 43 + Objects.hashCode(osVersion); hc = hc * 43 + Objects.hashCode(packages); - hc = hc * 43 + Objects.hashCode(hashes); if (hc == 0) hc = -1; hash = hc; @@ -2145,7 +2183,7 @@ public class ModuleDescriptor if (!requires.isEmpty()) sb.append(", ").append(requires); if (!uses.isEmpty()) - sb.append(", ").append(uses); + sb.append(", uses: ").append(uses); if (!exports.isEmpty()) sb.append(", exports: ").append(exports); if (!opens.isEmpty()) @@ -2171,7 +2209,7 @@ public class ModuleDescriptor * identifier */ public static Builder module(String name) { - return new Builder(name, true); + return new Builder(name, true, false, false); } /** @@ -2199,7 +2237,7 @@ public class ModuleDescriptor * identifier */ public static Builder openModule(String name) { - return new Builder(name, true).open(true); + return new Builder(name, true, true, false); } /** @@ -2221,7 +2259,7 @@ public class ModuleDescriptor * @see ModuleFinder#of(Path[]) */ public static Builder automaticModule(String name) { - return new Builder(name, true).automatic(true); + return new Builder(name, true, false, false).automatic(true); } @@ -2263,7 +2301,7 @@ public class ModuleDescriptor Supplier> packageFinder) throws IOException { - return ModuleInfo.read(in, requireNonNull(packageFinder)); + return ModuleInfo.read(in, requireNonNull(packageFinder)).descriptor(); } /** @@ -2281,7 +2319,7 @@ public class ModuleDescriptor * If an I/O error occurs reading from the input stream */ public static ModuleDescriptor read(InputStream in) throws IOException { - return ModuleInfo.read(in, null); + return ModuleInfo.read(in, null).descriptor(); } /** @@ -2320,7 +2358,7 @@ public class ModuleDescriptor public static ModuleDescriptor read(ByteBuffer bb, Supplier> packageFinder) { - return ModuleInfo.read(bb, requireNonNull(packageFinder)); + return ModuleInfo.read(bb, requireNonNull(packageFinder)).descriptor(); } /** @@ -2336,7 +2374,7 @@ public class ModuleDescriptor * If an invalid module descriptor is detected */ public static ModuleDescriptor read(ByteBuffer bb) { - return ModuleInfo.read(bb, null); + return ModuleInfo.read(bb, null).descriptor(); } private static Map emptyOrUnmodifiableMap(Map map) { @@ -2377,18 +2415,26 @@ public class ModuleDescriptor jdk.internal.misc.SharedSecrets .setJavaLangModuleAccess(new jdk.internal.misc.JavaLangModuleAccess() { @Override - public Builder newModuleBuilder(String mn, boolean strict) { - return new Builder(mn, strict); + public Builder newModuleBuilder(String mn, + boolean strict, + boolean open, + boolean synthetic) { + return new Builder(mn, strict, open, synthetic); } @Override - public Builder newOpenModuleBuilder(String mn, boolean strict) { - return new Builder(mn, strict).open(true); + public Set exportedPackages(ModuleDescriptor.Builder builder) { + return builder.exportedPackages(); } @Override - public Requires newRequires(Set ms, String mn) { - return new Requires(ms, mn, true); + public Set openPackages(ModuleDescriptor.Builder builder) { + return builder.openPackages(); + } + + @Override + public Requires newRequires(Set ms, String mn, Version v) { + return new Requires(ms, mn, v, true); } @Override @@ -2433,6 +2479,7 @@ public class ModuleDescriptor @Override public ModuleDescriptor newModuleDescriptor(String name, + Version version, boolean open, boolean automatic, boolean synthetic, @@ -2441,15 +2488,14 @@ public class ModuleDescriptor Set opens, Set uses, Set provides, - Version version, + Set packages, String mainClass, String osName, String osArch, String osVersion, - Set packages, - ModuleHashes hashes, int hashCode) { return new ModuleDescriptor(name, + version, open, automatic, synthetic, @@ -2458,22 +2504,15 @@ public class ModuleDescriptor opens, uses, provides, - version, + packages, mainClass, osName, osArch, osVersion, - packages, - hashes, hashCode, false); } - @Override - public Optional hashes(ModuleDescriptor descriptor) { - return descriptor.hashes(); - } - @Override public Configuration resolveRequiresAndUses(ModuleFinder finder, Collection roots, @@ -2482,20 +2521,6 @@ public class ModuleDescriptor { return Configuration.resolveRequiresAndUses(finder, roots, check, traceOutput); } - - @Override - public ModuleReference newPatchedModule(ModuleDescriptor descriptor, - URI location, - Supplier s) { - return new ModuleReference(descriptor, location, s, true, null); - } - - @Override - public ModuleFinder newModulePath(Runtime.Version version, - boolean isLinkPhase, - Path... entries) { - return new ModulePath(version, isLinkPhase, entries); - } }); } diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java b/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java index 4b98bf48416..5d01f698806 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java +++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java @@ -42,6 +42,8 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import jdk.internal.module.ModulePath; +import jdk.internal.module.SystemModuleFinder; import sun.security.action.GetPropertyAction; /** @@ -137,7 +139,7 @@ public interface ModuleFinder { /** * Returns a module finder that locates the system modules. The - * system modules are typically linked into the Java run-time image. + * system modules are the modules in the Java run-time image. * The module finder will always find {@code java.base}. * *

    If there is a security manager set then its {@link @@ -166,7 +168,7 @@ public interface ModuleFinder { Path modules = Paths.get(home, "lib", "modules"); if (Files.isRegularFile(modules)) { - return new SystemModuleFinder(); + return SystemModuleFinder.getInstance(); } else { Path mlib = Paths.get(home, "modules"); if (Files.isDirectory(mlib)) { diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java b/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java index cbf84cf938d..09a5acec219 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java +++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java @@ -26,96 +26,42 @@ package java.lang.module; import java.io.IOException; -import java.io.UncheckedIOException; import java.net.URI; import java.util.Objects; import java.util.Optional; -import java.util.function.Supplier; - -import jdk.internal.module.ModuleHashes.HashSupplier; /** * A reference to a module's content. * - *

    A module reference contains the module's descriptor and its location, if - * known. It also has the ability to create a {@link ModuleReader} in order to - * access the module's content, which may be inside the Java run-time system - * itself or in an artifact such as a modular JAR file. + *

    A module reference is a concrete implementation of this class that + * implements the abstract methods defined by this class. It contains the + * module's descriptor and its location, if known. It also has the ability to + * create a {@link ModuleReader} in order to access the module's content, which + * may be inside the Java run-time system itself or in an artifact such as a + * modular JAR file. * * @see ModuleFinder * @see ModuleReader * @since 9 */ -public final class ModuleReference { +public abstract class ModuleReference { private final ModuleDescriptor descriptor; private final URI location; - private final Supplier readerSupplier; - - // true if this is a reference to a patched module - private boolean patched; - - // the function that computes the hash of this module reference - private final HashSupplier hasher; - - // cached hash to avoid needing to compute it many times - private byte[] cachedHash; - /** * Constructs a new instance of this class. - */ - ModuleReference(ModuleDescriptor descriptor, - URI location, - Supplier readerSupplier, - boolean patched, - HashSupplier hasher) - - { - this.descriptor = Objects.requireNonNull(descriptor); - this.location = location; - this.readerSupplier = Objects.requireNonNull(readerSupplier); - this.patched = patched; - this.hasher = hasher; - } - - /** - * Constructs a new instance of this class. - */ - ModuleReference(ModuleDescriptor descriptor, - URI location, - Supplier readerSupplier, - HashSupplier hasher) - - { - this(descriptor, location, readerSupplier, false, hasher); - } - - - /** - * Constructs a new instance of this class. - * - *

    The {@code readSupplier} parameter is the supplier of the {@link - * ModuleReader} that may be used to read the module content. Its {@link - * Supplier#get() get()} method throws {@link UncheckedIOException} if an - * I/O error occurs opening the module content. The {@code get()} method - * throws {@link SecurityException} if opening the module is denied by the - * security manager. * * @param descriptor * The module descriptor * @param location * The module location or {@code null} if not known - * @param readerSupplier - * The {@code Supplier} of the {@code ModuleReader} */ - public ModuleReference(ModuleDescriptor descriptor, - URI location, - Supplier readerSupplier) - { - this(descriptor, location, readerSupplier, false, null); + protected ModuleReference(ModuleDescriptor descriptor, URI location) { + this.descriptor = Objects.requireNonNull(descriptor); + this.location = location; } /** @@ -123,11 +69,10 @@ public final class ModuleReference { * * @return The module descriptor */ - public ModuleDescriptor descriptor() { + public final ModuleDescriptor descriptor() { return descriptor; } - /** * Returns the location of this module's content, if known. * @@ -139,18 +84,13 @@ public final class ModuleReference { * * @return The location or an empty {@code Optional} if not known */ - public Optional location() { + public final Optional location() { return Optional.ofNullable(location); } - /** * Opens the module content for reading. * - *

    This method opens the module content by invoking the {@link - * Supplier#get() get()} method of the {@code readSupplier} specified at - * construction time.

    - * * @return A {@code ModuleReader} to read the module * * @throws IOException @@ -158,113 +98,5 @@ public final class ModuleReference { * @throws SecurityException * If denied by the security manager */ - public ModuleReader open() throws IOException { - try { - return readerSupplier.get(); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - - } - - - /** - * Returns {@code true} if this module has been patched via --patch-module. - */ - boolean isPatched() { - return patched; - } - - /** - * Returns the hash supplier for this module. - */ - HashSupplier hasher() { - return hasher; - } - - /** - * Computes the hash of this module. Returns {@code null} if the hash - * cannot be computed. - * - * @throws java.io.UncheckedIOException if an I/O error occurs - */ - byte[] computeHash(String algorithm) { - byte[] result = cachedHash; - if (result != null) - return result; - if (hasher == null) - return null; - cachedHash = result = hasher.generate(algorithm); - return result; - } - - /** - * Computes a hash code for this module reference. - * - *

    The hash code is based upon the components of the reference, and - * satisfies the general contract of the {@link Object#hashCode - * Object.hashCode} method.

    - * - * @return The hash-code value for this module reference - */ - @Override - public int hashCode() { - int hc = hash; - if (hc == 0) { - hc = descriptor.hashCode(); - hc = 43 * hc + readerSupplier.hashCode(); - hc = 43 * hc + Objects.hashCode(location); - hc = 43 * hc + Objects.hashCode(hasher); - hc = 43 * hc + Boolean.hashCode(patched); - if (hc == 0) - hc = -1; - hash = hc; - } - return hc; - } - - private int hash; - - /** - * Tests this module reference for equality with the given object. - * - *

    If the given object is not a {@code ModuleReference} then this - * method returns {@code false}. Two module references are equal if their - * module descriptors are equal, their locations are equal or both unknown, - * and were created with equal supplier objects to access the module - * content.

    - * - *

    This method satisfies the general contract of the {@link - * java.lang.Object#equals(Object) Object.equals} method.

    - * - * @param ob - * the object to which this object is to be compared - * - * @return {@code true} if, and only if, the given object is a module - * reference that is equal to this module reference - */ - @Override - public boolean equals(Object ob) { - if (!(ob instanceof ModuleReference)) - return false; - ModuleReference that = (ModuleReference)ob; - - return Objects.equals(this.descriptor, that.descriptor) - && Objects.equals(this.location, that.location) - && Objects.equals(this.readerSupplier, that.readerSupplier) - && Objects.equals(this.hasher, that.hasher) - && this.patched == that.patched; - } - - /** - * Returns a string describing this module reference. - * - * @return A string describing this module reference - */ - @Override - public String toString() { - return ("[module " + descriptor().name() - + ", location=" + location + "]"); - } - + public abstract ModuleReader open() throws IOException; } diff --git a/jdk/src/java.base/share/classes/java/lang/module/Resolver.java b/jdk/src/java.base/share/classes/java/lang/module/Resolver.java index 5f716b131b7..d2aafdc5d87 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/Resolver.java +++ b/jdk/src/java.base/share/classes/java/lang/module/Resolver.java @@ -46,6 +46,7 @@ import java.util.StringJoiner; import java.util.stream.Collectors; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleReferenceImpl; /** * The resolver used by {@link Configuration#resolveRequires} and @@ -438,24 +439,32 @@ final class Resolver { */ private void checkHashes() { for (ModuleReference mref : nameToReference.values()) { - ModuleDescriptor descriptor = mref.descriptor(); - // get map of module hashes - Optional ohashes = descriptor.hashes(); - if (!ohashes.isPresent()) + // get the recorded hashes, if any + if (!(mref instanceof ModuleReferenceImpl)) + continue; + ModuleHashes hashes = ((ModuleReferenceImpl)mref).recordedHashes(); + if (hashes == null) continue; - ModuleHashes hashes = ohashes.get(); + ModuleDescriptor descriptor = mref.descriptor(); String algorithm = hashes.algorithm(); for (String dn : hashes.names()) { - ModuleReference other = nameToReference.get(dn); - if (other == null) { + ModuleReference mref2 = nameToReference.get(dn); + if (mref2 == null) { ResolvedModule resolvedModule = findInParent(dn); if (resolvedModule != null) - other = resolvedModule.reference(); + mref2 = resolvedModule.reference(); + } + if (mref2 == null) + continue; + + if (!(mref2 instanceof ModuleReferenceImpl)) { + fail("Unable to compute the hash of module %s", dn); } // skip checking the hash if the module has been patched + ModuleReferenceImpl other = (ModuleReferenceImpl)mref2; if (other != null && !other.isPatched()) { byte[] recordedHash = hashes.hashFor(dn); byte[] actualHash = other.computeHash(algorithm); diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java b/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java index a046a748f7c..f585b476504 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java @@ -28,9 +28,11 @@ package java.lang.reflect; import java.lang.annotation.Annotation; import java.security.AccessController; +import jdk.internal.misc.VM; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; import jdk.internal.reflect.ReflectionFactory; +import sun.security.action.GetPropertyAction; /** * The AccessibleObject class is the base class for Field, Method and @@ -172,8 +174,10 @@ public class AccessibleObject implements AnnotatedElement { // package is open to caller String pn = packageName(declaringClass); - if (declaringModule.isOpen(pn, callerModule)) + if (declaringModule.isOpen(pn, callerModule)) { + printStackTraceIfOpenedReflectively(declaringModule, pn, callerModule); return; + } // package is exported to caller and class/member is public boolean isExported = declaringModule.isExported(pn, callerModule); @@ -185,8 +189,10 @@ public class AccessibleObject implements AnnotatedElement { modifiers = ((Field) this).getModifiers(); } boolean isMemberPublic = Modifier.isPublic(modifiers); - if (isExported && isClassPublic && isMemberPublic) + if (isExported && isClassPublic && isMemberPublic) { + printStackTraceIfExportedReflectively(declaringModule, pn, callerModule); return; + } // not accessible String msg = "Unable to make "; @@ -198,7 +204,44 @@ public class AccessibleObject implements AnnotatedElement { else msg += "opens"; msg += " " + pn + "\" to " + callerModule; - Reflection.throwInaccessibleObjectException(msg); + InaccessibleObjectException e = new InaccessibleObjectException(msg); + if (Reflection.printStackTraceWhenAccessFails()) { + e.printStackTrace(System.err); + } + throw e; + } + + private void printStackTraceIfOpenedReflectively(Module module, + String pn, + Module other) { + printStackTraceIfExposedReflectively(module, pn, other, true); + } + + private void printStackTraceIfExportedReflectively(Module module, + String pn, + Module other) { + printStackTraceIfExposedReflectively(module, pn, other, false); + } + + private void printStackTraceIfExposedReflectively(Module module, + String pn, + Module other, + boolean open) + { + if (Reflection.printStackTraceWhenAccessSucceeds() + && !module.isStaticallyExportedOrOpen(pn, other, open)) + { + String msg = other + " allowed to invoke setAccessible on "; + if (this instanceof Field) + msg += "field "; + msg += this; + new Exception(msg) { + private static final long serialVersionUID = 42L; + public String toString() { + return "WARNING: " + getMessage(); + } + }.printStackTrace(System.err); + } } /** 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 7466c57ae22..df48c1e707a 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 @@ -245,7 +245,6 @@ public final class Layer { * @see Module#addOpens */ public Controller addOpens(Module source, String pn, Module target) { - Objects.requireNonNull(source); Objects.requireNonNull(source); Objects.requireNonNull(target); ensureInLayer(source); @@ -541,7 +540,7 @@ public final class Layer { * {@link ClassLoader#registerAsParallelCapable parallel-capable} so as to * avoid deadlocks during class loading. In addition, the entity creating * a new layer with this method should arrange that the class loaders are - * ready to load from these module before there are any attempts to load + * ready to load from these modules before there are any attempts to load * classes or resources. * *

    Creating a {@code Layer} can fail for the following reasons:

    diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Module.java b/jdk/src/java.base/share/classes/java/lang/reflect/Module.java index 29f21cc0108..a71b4b320ab 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Module.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Module.java @@ -559,7 +559,7 @@ public final class Module implements AnnotatedElement { * Returns {@code true} if this module exports or opens a package to * the given module via its module declaration. */ - private boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) { + boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) { // package is open to everyone or Map> openPackages = this.openPackages; if (openPackages != null) { @@ -643,6 +643,12 @@ public final class Module implements AnnotatedElement { * open) to the given module. It also has no effect if * invoked on an {@link ModuleDescriptor#isOpen open} module.

    * + * @apiNote As specified in section 5.4.3 of the The Java™ + * Virtual Machine Specification , if an attempt to resolve a + * symbolic reference fails because of a linkage error, then subsequent + * attempts to resolve the reference always fail with the same error that + * was thrown as a result of the initial resolution attempt. + * * @param pn * The package name * @param other @@ -656,6 +662,7 @@ public final class Module implements AnnotatedElement { * @throws IllegalStateException * If this is a named module and the caller is not this module * + * @jvms 5.4.3 Resolution * @see #isExported(String,Module) */ @CallerSensitive @@ -676,8 +683,8 @@ public final class Module implements AnnotatedElement { } /** - * If the caller's module is this module then update this module to - * open the given package to the given module. + * If this module has opened a package to at least the caller + * module then update this module to open the package to the given module. * Opening a package with this method allows all types in the package, * and all their members, not just public types and their public members, * to be reflected on by the given module when using APIs that support @@ -699,7 +706,8 @@ public final class Module implements AnnotatedElement { * If {@code pn} is {@code null}, or this is a named module and the * package {@code pn} is not a package in this module * @throws IllegalStateException - * If this is a named module and the caller is not this module + * If this is a named module and this module has not opened the + * package to at least the caller * * @see #isOpen(String,Module) * @see AccessibleObject#setAccessible(boolean) @@ -713,9 +721,8 @@ public final class Module implements AnnotatedElement { if (isNamed() && !descriptor.isOpen()) { Module caller = Reflection.getCallerClass().getModule(); - if (caller != this) { - throw new IllegalStateException(caller + " != " + this); - } + if (caller != this && !isOpen(pn, caller)) + throw new IllegalStateException(pn + " is not open to " + caller); implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true); } @@ -1568,6 +1575,10 @@ public final class Module implements AnnotatedElement { public Stream layers(ClassLoader loader) { return Layer.layers(loader); } + @Override + public boolean isStaticallyExported(Module module, String pn, Module other) { + return module.isStaticallyExportedOrOpen(pn, other, false); + } }); } } diff --git a/jdk/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java b/jdk/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java index d979f984da3..1284a3f129f 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java +++ b/jdk/src/java.base/share/classes/jdk/internal/jimage/decompressor/StringSharingDecompressor.java @@ -64,8 +64,10 @@ public class StringSharingDecompressor implements ResourceDecompressor { private static final int CONSTANT_MethodHandle = 15; private static final int CONSTANT_MethodType = 16; private static final int CONSTANT_InvokeDynamic = 18; + private static final int CONSTANT_Module = 19; + private static final int CONSTANT_Package = 20; - private static final int[] SIZES = new int[20]; + private static final int[] SIZES = new int[21]; static { @@ -83,6 +85,8 @@ public class StringSharingDecompressor implements ResourceDecompressor { SIZES[CONSTANT_MethodHandle] = 3; SIZES[CONSTANT_MethodType] = 2; SIZES[CONSTANT_InvokeDynamic] = 4; + SIZES[CONSTANT_Module] = 2; + SIZES[CONSTANT_Package] = 2; } public static int[] getSizes() { diff --git a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java index d0b1c19232f..eed7a2d2aff 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java +++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java @@ -38,10 +38,8 @@ import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.net.URI; import java.nio.file.Path; -import java.util.Map; import java.util.Collection; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.function.Supplier; @@ -59,21 +57,28 @@ public interface JavaLangModuleAccess { * @param strict * Indicates whether module names are checked or not */ - ModuleDescriptor.Builder newModuleBuilder(String mn, boolean strict); + ModuleDescriptor.Builder newModuleBuilder(String mn, + boolean strict, + boolean open, + boolean synthetic); /** - * Creates a builder for building an open module with the given module name. - * - * @param strict - * Indicates whether module names are checked or not + * Returns the set of packages that are exported (unconditionally or + * unconditionally). */ - ModuleDescriptor.Builder newOpenModuleBuilder(String mn, boolean strict); + Set exportedPackages(ModuleDescriptor.Builder builder); + + /** + * Returns the set of packages that are opened (unconditionally or + * unconditionally). + */ + Set openPackages(ModuleDescriptor.Builder builder); /** * Returns a {@code ModuleDescriptor.Requires} of the given modifiers * and module name. */ - Requires newRequires(Set ms, String mn); + Requires newRequires(Set ms, String mn, Version v); /** * Returns an unqualified {@code ModuleDescriptor.Exports} @@ -122,6 +127,7 @@ public interface JavaLangModuleAccess { * Returns a new {@code ModuleDescriptor} instance. */ ModuleDescriptor newModuleDescriptor(String name, + Version version, boolean open, boolean automatic, boolean synthetic, @@ -130,20 +136,13 @@ public interface JavaLangModuleAccess { Set opens, Set uses, Set provides, - Version version, + Set packages, String mainClass, String osName, String osArch, String osVersion, - Set packages, - ModuleHashes hashes, int hashCode); - /** - * Returns the object with the hashes of other modules - */ - Optional hashes(ModuleDescriptor descriptor); - /** * Resolves a collection of root modules, with service binding * and the empty configuration as the parent. The post resolution @@ -154,18 +153,4 @@ public interface JavaLangModuleAccess { boolean check, PrintStream traceOutput); - /** - * Creates a ModuleReference to a "patched" module. - */ - ModuleReference newPatchedModule(ModuleDescriptor descriptor, - URI location, - Supplier readerSupplier); - - /** - * Creates a ModuleFinder for a module path. - */ - ModuleFinder newModulePath(Runtime.Version version, - boolean isLinkPhase, - Path... entries); - } diff --git a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangReflectModuleAccess.java b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangReflectModuleAccess.java index 55772793111..7bf6a1f3977 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangReflectModuleAccess.java +++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangReflectModuleAccess.java @@ -123,4 +123,12 @@ public interface JavaLangReflectModuleAccess { * given class loader. */ Stream layers(ClassLoader loader); + + /** + * Tests if a module exports a package at least {@code other} via its + * module declaration. + * + * @apiNote This is a temporary method for debugging features. + */ + boolean isStaticallyExported(Module module, String pn, Module other); } \ No newline at end of file diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java b/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java index 961dd08f28e..2ef9c11d248 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java @@ -30,11 +30,8 @@ import java.lang.module.ModuleDescriptor.Opens; import java.lang.module.ModuleDescriptor.Provides; import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Version; -import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Set; import jdk.internal.misc.JavaLangModuleAccess; @@ -52,7 +49,7 @@ import jdk.internal.misc.SharedSecrets; * SystemModules should contain modules for the boot layer. */ final class Builder { - private static final JavaLangModuleAccess jlma = + private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess(); // Static cache of the most recently seen Version to cheaply deduplicate @@ -60,13 +57,36 @@ final class Builder { static Version cachedVersion; /** - * Returns a {@link Requires} for a dependence on a module - * with the given (and possibly empty) set of modifiers. + * Returns a {@link Requires} for a dependence on a module with the given + * (and possibly empty) set of modifiers, and optionally the version + * recorded at compile time. + */ + public static Requires newRequires(Set mods, + String mn, + String compiledVersion) + { + Version version = null; + if (compiledVersion != null) { + // use the cached version if the same version string + Version ver = cachedVersion; + if (ver != null && compiledVersion.equals(ver.toString())) { + version = ver; + } else { + version = Version.parse(compiledVersion); + } + } + return JLMA.newRequires(mods, mn, version); + } + + /** + * Returns a {@link Requires} for a dependence on a module with the given + * (and possibly empty) set of modifiers, and optionally the version + * recorded at compile time. */ public static Requires newRequires(Set mods, String mn) { - return jlma.newRequires(mods, mn); + return newRequires(mods, mn, null); } /** @@ -77,7 +97,7 @@ final class Builder { public static Exports newExports(Set ms, String pn, Set targets) { - return jlma.newExports(ms, pn, targets); + return JLMA.newExports(ms, pn, targets); } /** @@ -85,7 +105,7 @@ final class Builder { * modifiers. */ public static Opens newOpens(Set ms, String pn) { - return jlma.newOpens(ms, pn); + return JLMA.newOpens(ms, pn); } /** @@ -96,7 +116,7 @@ final class Builder { public static Opens newOpens(Set ms, String pn, Set targets) { - return jlma.newOpens(ms, pn, targets); + return JLMA.newOpens(ms, pn, targets); } /** @@ -104,7 +124,7 @@ final class Builder { * of modifiers. */ public static Exports newExports(Set ms, String pn) { - return jlma.newExports(ms, pn); + return JLMA.newExports(ms, pn); } /** @@ -112,7 +132,7 @@ final class Builder { * implementation classes. */ public static Provides newProvides(String st, List pcs) { - return jlma.newProvides(st, pcs); + return JLMA.newProvides(st, pcs); } final String name; @@ -130,8 +150,6 @@ final class Builder { String osName; String osArch; String osVersion; - String algorithm; - Map hashes; Builder(String name) { this.name = name; @@ -274,35 +292,14 @@ final class Builder { return this; } - /** - * Sets the algorithm of the module hashes - */ - public Builder algorithm(String algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Sets the module hash for the given module name - */ - public Builder moduleHash(String mn, byte[] hash) { - if (hashes == null) - hashes = new HashMap<>(); - - hashes.put(mn, hash); - return this; - } - /** * Builds a {@code ModuleDescriptor} from the components. */ public ModuleDescriptor build(int hashCode) { assert name != null; - ModuleHashes moduleHashes = - hashes != null ? new ModuleHashes(algorithm, hashes) : null; - - return jlma.newModuleDescriptor(name, + return JLMA.newModuleDescriptor(name, + version, open, automatic, synthetic, @@ -311,13 +308,11 @@ final class Builder { opens, uses, provides, - version, + packages, mainClass, osName, osArch, osVersion, - packages, - moduleHashes, hashCode); } } diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java b/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java index 9f02048b5c8..2fdeaab6211 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java @@ -25,79 +25,200 @@ package jdk.internal.module; +/** + * Utility class for checking module name and binary names. + */ + public final class Checks { private Checks() { } - private static void fail(String what, String id, int i) { - throw new IllegalArgumentException(id - + ": Invalid " + what + ": " - + " Illegal character" - + " at index " + i); + /** + * Checks a name to ensure that it's a legal module name. + * + * @throws IllegalArgumentException if name is null or not a legal + * module name + */ + public static String requireModuleName(String name) { + if (name == null) + throw new IllegalArgumentException("Null module name"); + int next; + int off = 0; + while ((next = name.indexOf('.', off)) != -1) { + if (isJavaIdentifier(name, off, (next - off)) == -1) { + String id = name.substring(off, next); + throw new IllegalArgumentException(name + ": Invalid module name" + + ": '" + id + "' is not a Java identifier"); + } + off = next+1; + } + int last = isJavaIdentifier(name, off, name.length() - off); + if (last == -1) { + String id = name.substring(off); + throw new IllegalArgumentException(name + ": Invalid module name" + + ": '" + id + "' is not a Java identifier"); + } + //if (!Character.isJavaIdentifierStart(last)) + // throw new IllegalArgumentException(name + ": Module name ends in digit"); + return name; } /** - * Returns {@code true} if the given identifier is a legal Java identifier. + * Returns {@code true} if the given name is a legal module name. */ - public static boolean isJavaIdentifier(String id) { - int n = id.length(); - if (n == 0) - return false; - if (!Character.isJavaIdentifierStart(id.codePointAt(0))) - return false; - int cp = id.codePointAt(0); - int i = Character.charCount(cp); - for (; i < n; i += Character.charCount(cp)) { - cp = id.codePointAt(i); - if (!Character.isJavaIdentifierPart(cp) && id.charAt(i) != '.') + public static boolean isModuleName(String name) { + int next; + int off = 0; + while ((next = name.indexOf('.', off)) != -1) { + if (isJavaIdentifier(name, off, (next - off)) == -1) return false; + off = next+1; } - if (cp == '.') + int last = isJavaIdentifier(name, off, name.length() - off); + if (last == -1) return false; - + //if (!Character.isJavaIdentifierStart(last)) + // return false; return true; } /** - * Checks if a given identifier is a legal Java identifier. + * Checks a name to ensure that it's a legal package name. + * + * @throws IllegalArgumentException if name is null or not a legal + * package name */ - public static String requireJavaIdentifier(String what, String id) { - if (id == null) - throw new IllegalArgumentException("Null " + what); - int n = id.length(); - if (n == 0) - throw new IllegalArgumentException("Empty " + what); - if (!Character.isJavaIdentifierStart(id.codePointAt(0))) - fail(what, id, 0); - int cp = id.codePointAt(0); - int i = Character.charCount(cp); - int last = 0; - for (; i < n; i += Character.charCount(cp)) { - cp = id.codePointAt(i); - if (!Character.isJavaIdentifierPart(cp) && id.charAt(i) != '.') - fail(what, id, i); - last = i; + public static String requirePackageName(String name) { + return requireBinaryName("package name", name); + } + + /** + * Checks a name to ensure that it's a legal type name. + * + * @throws IllegalArgumentException if name is null or not a legal + * type name + */ + public static String requireServiceTypeName(String name) { + return requireBinaryName("service type name", name); + } + + /** + * Checks a name to ensure that it's a legal type name. + * + * @throws IllegalArgumentException if name is null or not a legal + * type name + */ + public static String requireServiceProviderName(String name) { + return requireBinaryName("service provider name", name); + } + + /** + * Returns {@code true} if the given name is a legal binary name. + */ + public static boolean isJavaIdentifier(String name) { + return isBinaryName(name); + } + + /** + * Returns {@code true} if the given name is a legal binary name. + */ + public static boolean isBinaryName(String name) { + int next; + int off = 0; + while ((next = name.indexOf('.', off)) != -1) { + if (isJavaIdentifier(name, off, (next - off)) == -1) + return false; + off = next+1; } - if (cp == '.') - fail(what, id, last); - - return id; + int count = name.length() - off; + return (isJavaIdentifier(name, off, count) != -1); } - public static String requireModuleName(String id) { - return requireJavaIdentifier("module name", id); + /** + * Checks if the given name is a legal binary name. + * + * @throws IllegalArgumentException if name is null or not a legal + * binary name + */ + public static String requireBinaryName(String what, String name) { + if (name == null) + throw new IllegalArgumentException("Null " + what); + int next; + int off = 0; + while ((next = name.indexOf('.', off)) != -1) { + if (isJavaIdentifier(name, off, (next - off)) == -1) { + String id = name.substring(off, next); + throw new IllegalArgumentException(name + ": Invalid " + what + + ": '" + id + "' is not a Java identifier"); + } + off = next + 1; + } + if (isJavaIdentifier(name, off, name.length() - off) == -1) { + String id = name.substring(off, name.length()); + throw new IllegalArgumentException(name + ": Invalid " + what + + ": '" + id + "' is not a Java identifier"); + } + return name; } - public static String requirePackageName(String id) { - return requireJavaIdentifier("package name", id); + /** + * Returns {@code true} if the last character of the given name is legal + * as the last character of a module name. + * + * @throws IllegalArgumentException if name is empty + */ + public static boolean hasLegalModuleNameLastCharacter(String name) { + if (name.isEmpty()) + throw new IllegalArgumentException("name is empty"); + int len = name.length(); + if (isASCIIString(name)) { + char c = name.charAt(len-1); + return Character.isJavaIdentifierStart(c); + } else { + int i = 0; + int cp = -1; + while (i < len) { + cp = name.codePointAt(i); + i += Character.charCount(cp); + } + return Character.isJavaIdentifierStart(cp); + } } - public static String requireServiceTypeName(String id) { - return requireJavaIdentifier("service type name", id); + /** + * Returns true if the given string only contains ASCII characters. + */ + private static boolean isASCIIString(String s) { + int i = 0; + while (i < s.length()) { + int c = s.charAt(i); + if (c > 0x7F) + return false; + i++; + } + return true; } - public static String requireServiceProviderName(String id) { - return requireJavaIdentifier("service provider name", id); - } + /** + * Checks if a char sequence is a legal Java identifier, returning the code + * point of the last character if legal or {@code -1} if not legal. + */ + private static int isJavaIdentifier(CharSequence cs, int offset, int count) { + if (count == 0) + return -1; + int first = Character.codePointAt(cs, offset); + if (!Character.isJavaIdentifierStart(first)) + return -1; + int cp = first; + int i = Character.charCount(first); + while (i < count) { + cp = Character.codePointAt(cs, offset+i); + if (!Character.isJavaIdentifierPart(cp)) + return -1; + i += Character.charCount(cp); + } + + return cp; + } } diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java b/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java index 908b137eb5a..69c7ee670dd 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java @@ -68,12 +68,18 @@ public final class ClassFileAttributes { = SharedSecrets.getJavaLangModuleAccess(); private ModuleDescriptor descriptor; + private Version replacementVersion; public ModuleAttribute(ModuleDescriptor descriptor) { super(MODULE); this.descriptor = descriptor; } + public ModuleAttribute(Version v) { + super(MODULE); + this.replacementVersion = v; + } + public ModuleAttribute() { super(MODULE); } @@ -86,46 +92,70 @@ public final class ClassFileAttributes { int codeOff, Label[] labels) { - ModuleAttribute attr = new ModuleAttribute(); - - // module_name - String mn = cr.readUTF8(off, buf).replace('/', '.'); + // module_name (CONSTANT_Module_info) + String mn = cr.readModule(off, buf); off += 2; // module_flags int module_flags = cr.readUnsignedShort(off); boolean open = ((module_flags & ACC_OPEN) != 0); + boolean synthetic = ((module_flags & ACC_SYNTHETIC) != 0); off += 2; - ModuleDescriptor.Builder builder; - if (open) { - builder = JLMA.newOpenModuleBuilder(mn, false); - } else { - builder = JLMA.newModuleBuilder(mn, false); + ModuleDescriptor.Builder builder = JLMA.newModuleBuilder(mn, + false, + open, + synthetic); + + // module_version + String module_version = cr.readUTF8(off, buf); + off += 2; + if (replacementVersion != null) { + builder.version(replacementVersion); + } else if (module_version != null) { + builder.version(module_version); } // requires_count and requires[requires_count] int requires_count = cr.readUnsignedShort(off); off += 2; for (int i=0; i mods; - if (flags == 0) { + if (requires_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_TRANSITIVE) != 0) + if ((requires_flags & ACC_TRANSITIVE) != 0) mods.add(Requires.Modifier.TRANSITIVE); - if ((flags & ACC_STATIC_PHASE) != 0) + if ((requires_flags & ACC_STATIC_PHASE) != 0) mods.add(Requires.Modifier.STATIC); - if ((flags & ACC_SYNTHETIC) != 0) + if ((requires_flags & ACC_SYNTHETIC) != 0) mods.add(Requires.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((requires_flags & ACC_MANDATED) != 0) mods.add(Requires.Modifier.MANDATED); } - builder.requires(mods, dn); - off += 4; + + + // requires_version + Version compiledVersion = null; + String requires_version = cr.readUTF8(off, buf); + off += 2; + if (requires_version != null) { + compiledVersion = Version.parse(requires_version); + } + + if (compiledVersion == null) { + builder.requires(mods, dn); + } else { + builder.requires(mods, dn, compiledVersion); + } } // exports_count and exports[exports_count] @@ -133,19 +163,20 @@ public final class ClassFileAttributes { off += 2; if (exports_count > 0) { for (int i=0; i mods; - if (flags == 0) { + if (exports_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_SYNTHETIC) != 0) + if ((exports_flags & ACC_SYNTHETIC) != 0) mods.add(Exports.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((exports_flags & ACC_MANDATED) != 0) mods.add(Exports.Modifier.MANDATED); } @@ -154,7 +185,7 @@ public final class ClassFileAttributes { if (exports_to_count > 0) { Set targets = new HashSet<>(); for (int j=0; j 0) { for (int i=0; i mods; - if (flags == 0) { + if (opens_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_SYNTHETIC) != 0) + if ((opens_flags & ACC_SYNTHETIC) != 0) mods.add(Opens.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((opens_flags & ACC_MANDATED) != 0) mods.add(Opens.Modifier.MANDATED); } @@ -191,7 +223,7 @@ public final class ClassFileAttributes { if (opens_to_count > 0) { Set targets = new HashSet<>(); for (int j=0; j ts = e.targets(); attr.putShort(ts.size()); - ts.forEach(t -> attr.putShort(cw.newUTF8(t.replace('.', '/')))); + ts.forEach(target -> attr.putShort(cw.newModule(target))); } else { attr.putShort(0); } } - // opens_counts and opens[opens_counts] attr.putShort(descriptor.opens().size()); for (Opens obj : descriptor.opens()) { String pkg = obj.source().replace('.', '/'); - attr.putShort(cw.newUTF8(pkg)); + attr.putShort(cw.newPackage(pkg)); - int flags = 0; + int opens_flags = 0; if (obj.modifiers().contains(Opens.Modifier.SYNTHETIC)) - flags |= ACC_SYNTHETIC; + opens_flags |= ACC_SYNTHETIC; if (obj.modifiers().contains(Opens.Modifier.MANDATED)) - flags |= ACC_MANDATED; - attr.putShort(flags); + opens_flags |= ACC_MANDATED; + attr.putShort(opens_flags); if (obj.isQualified()) { Set ts = obj.targets(); attr.putShort(ts.size()); - ts.forEach(t -> attr.putShort(cw.newUTF8(t.replace('.', '/')))); + ts.forEach(target -> attr.putShort(cw.newModule(target))); } else { attr.putShort(0); } @@ -369,7 +417,7 @@ public final class ClassFileAttributes { * * // the number of entries in the packages table * u2 packages_count; - * { // index to CONSTANT_CONSTANT_utf8_info structure with the package name + * { // index to CONSTANT_Package_info structure with the package name * u2 package_index * } packages[package_count]; * @@ -402,7 +450,7 @@ public final class ClassFileAttributes { // packages Set packages = new HashSet<>(); for (int i=0; i p.replace('.', '/')) - .forEach(p -> attr.putShort(cw.newUTF8(p))); + .forEach(p -> attr.putShort(cw.newPackage(p))); return attr; } } - /** - * ModuleVersion attribute. - * - *
     {@code
    -     *
    -     * ModuleVersion_attribute {
    -     *   // index to CONSTANT_utf8_info structure in constant pool representing
    -     *   // the string "ModuleVersion"
    -     *   u2 attribute_name_index;
    -     *   u4 attribute_length;
    -     *
    -     *   // index to CONSTANT_CONSTANT_utf8_info structure with the version
    -     *   u2 version_index;
    -     * }
    -     *
    -     * } 
    - */ - public static class ModuleVersionAttribute extends Attribute { - private final Version version; - - public ModuleVersionAttribute(Version version) { - super(MODULE_VERSION); - this.version = version; - } - - public ModuleVersionAttribute() { - this(null); - } - - @Override - protected Attribute read(ClassReader cr, - int off, - int len, - char[] buf, - int codeOff, - Label[] labels) - { - String value = cr.readUTF8(off, buf); - return new ModuleVersionAttribute(Version.parse(value)); - } - - @Override - protected ByteVector write(ClassWriter cw, - byte[] code, - int len, - int maxStack, - int maxLocals) - { - ByteVector attr = new ByteVector(); - int index = cw.newUTF8(version.toString()); - attr.putShort(index); - return attr; - } - } - /** * ModuleMainClass attribute. * @@ -526,7 +519,7 @@ public final class ClassFileAttributes { int codeOff, Label[] labels) { - String value = cr.readClass(off, buf); + String value = cr.readClass(off, buf).replace('/', '.'); return new ModuleMainClassAttribute(value); } @@ -538,7 +531,7 @@ public final class ClassFileAttributes { int maxLocals) { ByteVector attr = new ByteVector(); - int index = cw.newClass(mainClass); + int index = cw.newClass(mainClass.replace('.', '/')); attr.putShort(index); return attr; } @@ -555,11 +548,11 @@ public final class ClassFileAttributes { * u2 attribute_name_index; * u4 attribute_length; * - * // index to CONSTANT_CONSTANT_utf8_info structure with the OS name + * // index to CONSTANT_utf8_info structure with the OS name * u2 os_name_index; - * // index to CONSTANT_CONSTANT_utf8_info structure with the OS arch + * // index to CONSTANT_utf8_info structure with the OS arch * u2 os_arch_index - * // index to CONSTANT_CONSTANT_utf8_info structure with the OS version + * // index to CONSTANT_utf8_info structure with the OS version * u2 os_version_index; * } * @@ -656,7 +649,7 @@ public final class ClassFileAttributes { * * // the number of entries in the hashes table * u2 hashes_count; - * { u2 module_name_index + * { u2 module_name_index (index to CONSTANT_Module_info structure) * u2 hash_length; * u1 hash[hash_length]; * } hashes[hashes_count]; @@ -691,7 +684,7 @@ public final class ClassFileAttributes { Map map = new HashMap<>(); for (int i=0; i !ModuleResolution.doNotResolveByDefault(mref)) .map(ModuleReference::descriptor) .map(ModuleDescriptor::name) .filter(mn -> f.find(mn).isPresent()) // observable @@ -277,6 +288,8 @@ public final class ModuleBootstrap { // time to create configuration PerfCounters.resolveTime.addElapsedTimeFrom(t3); + // check module names and incubating status + checkModuleNamesAndStatus(cf); // mapping of modules to class loaders Function clf = ModuleLoaderMap.mappingFunction(cf); @@ -496,8 +509,49 @@ public final class ModuleBootstrap { if (!extraOpens.isEmpty()) { addExtraExportsOrOpens(bootLayer, extraOpens, true); } + + // DEBUG_ADD_OPENS is for debugging purposes only + String home = System.getProperty("java.home"); + Path file = Paths.get(home, "conf", "DEBUG_ADD_OPENS"); + if (Files.exists(file)) { + warn(file + " detected; may break encapsulation"); + try (Stream lines = Files.lines(file)) { + lines.map(line -> line.trim()) + .filter(line -> (!line.isEmpty() && !line.startsWith("#"))) + .forEach(line -> { + String[] s = line.split("/"); + if (s.length != 2) { + fail("Unable to parse as /: " + line); + } else { + String mn = s[0]; + String pkg = s[1]; + openPackage(bootLayer, mn, pkg); + } + }); + } catch (IOException ioe) { + throw new UncheckedIOException(ioe); + } + Reflection.enableStackTraces(); + } } + private static void openPackage(Layer bootLayer, String mn, String pkg) { + if (mn.equals("ALL-RESOLVED") && pkg.equals("ALL-PACKAGES")) { + bootLayer.modules().stream().forEach(m -> + m.getDescriptor().packages().forEach(pn -> openPackage(m, pn))); + } else { + bootLayer.findModule(mn) + .filter(m -> m.getDescriptor().packages().contains(pkg)) + .ifPresent(m -> openPackage(m, pkg)); + } + } + + private static void openPackage(Module m, String pn) { + Modules.addOpensToAllUnnamed(m, pn); + warn("Opened for deep reflection: " + m.getName() + "/" + pn); + } + + private static void addExtraExportsOrOpens(Layer bootLayer, Map> map, boolean opens) @@ -508,12 +562,12 @@ public final class ModuleBootstrap { String key = e.getKey(); String[] s = key.split("/"); if (s.length != 2) - fail("Unable to parse: " + key); + fail("Unable to parse as /: " + key); String mn = s[0]; String pn = s[1]; if (mn.isEmpty() || pn.isEmpty()) - fail("Module and package name must be specified:" + key); + fail("Module and package name must be specified: " + key); // The exporting module is in the boot layer Module m; @@ -585,7 +639,7 @@ public final class ModuleBootstrap { int pos = value.indexOf('='); if (pos == -1) - fail("Unable to parse: " + value); + fail("Unable to parse as =: " + value); if (pos == 0) fail("Missing module name in: " + value); @@ -594,7 +648,7 @@ public final class ModuleBootstrap { String rhs = value.substring(pos+1); if (rhs.isEmpty()) - fail("Unable to parse: " + value); + fail("Unable to parse as =: " + value); // value is (,)* or ()* if (!allowDuplicates && map.containsKey(key)) @@ -626,6 +680,33 @@ public final class ModuleBootstrap { return (String)System.getProperties().remove(key); } + /** + * Checks the names and resolution bit of each module in the configuration, + * emitting warnings if needed. + */ + private static void checkModuleNamesAndStatus(Configuration cf) { + String incubating = null; + for (ResolvedModule rm : cf.modules()) { + ModuleReference mref = rm.reference(); + String mn = mref.descriptor().name(); + + // emit warning if module name ends with a non-Java letter + //if (!Checks.hasLegalModuleNameLastCharacter(mn)) + // warn("Module name \"" + mn + "\" may soon be illegal"); + + // emit warning if the WARN_INCUBATING module resolution bit set + if (ModuleResolution.hasIncubatingWarning(mref)) { + if (incubating == null) { + incubating = mn; + } else { + incubating += ", " + mn; + } + } + } + if (incubating != null) + warn("Using incubator modules: " + incubating); + } + /** * Throws a RuntimeException with the given message */ diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java index 107305e0c79..641127b894f 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java @@ -35,6 +35,7 @@ import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -50,7 +51,6 @@ public final class ModuleHashes { byte[] generate(String algorithm); } - private final String algorithm; private final Map nameToHash; @@ -142,4 +142,39 @@ public final class ModuleHashes { } return new ModuleHashes(algorithm, nameToHash); } + + /** + * This is used by jdk.internal.module.SystemModules class + * generated at link time. + */ + public static class Builder { + final String algorithm; + Map nameToHash; + + Builder(String algorithm) { + this.algorithm = Objects.requireNonNull(algorithm); + } + + /** + * Sets the module hash for the given module name + */ + public Builder hashForModule(String mn, byte[] hash) { + if (nameToHash == null) + nameToHash = new HashMap<>(); + + nameToHash.put(mn, hash); + return this; + } + + /** + * Builds a {@code ModuleHashes}. + */ + public ModuleHashes build() { + if (nameToHash != null) { + return new ModuleHashes(algorithm, nameToHash); + } else { + return null; + } + } + } } diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModuleInfo.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java similarity index 69% rename from jdk/src/java.base/share/classes/java/lang/module/ModuleInfo.java rename to jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java index b1c82819aa9..3aac651577c 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModuleInfo.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java @@ -23,7 +23,7 @@ * questions. */ -package java.lang.module; +package jdk.internal.module; import java.io.DataInput; import java.io.DataInputStream; @@ -31,10 +31,13 @@ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; +import java.lang.module.InvalidModuleDescriptorException; +import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Builder; import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Exports; import java.lang.module.ModuleDescriptor.Opens; +import java.lang.module.ModuleDescriptor.Version; import java.nio.ByteBuffer; import java.nio.BufferUnderflowException; import java.util.ArrayList; @@ -46,7 +49,9 @@ import java.util.Map; import java.util.Set; import java.util.function.Supplier; -import jdk.internal.module.ModuleHashes; +import jdk.internal.misc.JavaLangModuleAccess; +import jdk.internal.misc.SharedSecrets; +import jdk.internal.module.ModuleResolution; import static jdk.internal.module.ClassFileConstants.*; @@ -58,7 +63,10 @@ import static jdk.internal.module.ClassFileConstants.*; * and fine control over the throwing of InvalidModuleDescriptorException. */ -final class ModuleInfo { +public final class ModuleInfo { + + private static final JavaLangModuleAccess JLMA + = SharedSecrets.getJavaLangModuleAccess(); // supplies the set of packages when ModulePackages attribute not present private final Supplier> packageFinder; @@ -75,14 +83,42 @@ final class ModuleInfo { this(pf, true); } + /** + * A holder class for the ModuleDescriptor that is created by reading the + * Module and other standard class file attributes. It also holds the objects + * that represent the non-standard class file attributes that are read from + * the class file. + */ + public static final class Attributes { + private final ModuleDescriptor descriptor; + private final ModuleHashes recordedHashes; + private final ModuleResolution moduleResolution; + Attributes(ModuleDescriptor descriptor, + ModuleHashes recordedHashes, + ModuleResolution moduleResolution) { + this.descriptor = descriptor; + this.recordedHashes = recordedHashes; + this.moduleResolution = moduleResolution; + } + public ModuleDescriptor descriptor() { + return descriptor; + } + public ModuleHashes recordedHashes() { + return recordedHashes; + } + public ModuleResolution moduleResolution() { + return moduleResolution; + } + } + + /** * Reads a {@code module-info.class} from the given input stream. * * @throws InvalidModuleDescriptorException * @throws IOException */ - public static ModuleDescriptor read(InputStream in, - Supplier> pf) + public static Attributes read(InputStream in, Supplier> pf) throws IOException { try { @@ -100,9 +136,7 @@ final class ModuleInfo { * @throws InvalidModuleDescriptorException * @throws UncheckedIOException */ - public static ModuleDescriptor read(ByteBuffer bb, - Supplier> pf) - { + public static Attributes read(ByteBuffer bb, Supplier> pf) { try { return new ModuleInfo(pf).doRead(new DataInputWrapper(bb)); } catch (IllegalArgumentException | IllegalStateException e) { @@ -121,9 +155,7 @@ final class ModuleInfo { * @throws InvalidModuleDescriptorException * @throws UncheckedIOException */ - static ModuleDescriptor readIgnoringHashes(ByteBuffer bb, - Supplier> pf) - { + public static Attributes readIgnoringHashes(ByteBuffer bb, Supplier> pf) { try { return new ModuleInfo(pf, false).doRead(new DataInputWrapper(bb)); } catch (IllegalArgumentException | IllegalStateException e) { @@ -144,7 +176,7 @@ final class ModuleInfo { * because an identifier is not a legal Java identifier, duplicate * exports, and many other reasons */ - private ModuleDescriptor doRead(DataInput in) throws IOException { + private Attributes doRead(DataInput in) throws IOException { int magic = in.readInt(); if (magic != 0xCAFEBABE) @@ -163,8 +195,9 @@ final class ModuleInfo { throw invalidModuleDescriptor("access_flags should be ACC_MODULE"); int this_class = in.readUnsignedShort(); - if (this_class != 0) - throw invalidModuleDescriptor("this_class must be 0"); + String mn = cpool.getClassName(this_class); + if (!"module-info".equals(mn)) + throw invalidModuleDescriptor("this_class should be module-info"); int super_class = in.readUnsignedShort(); if (super_class > 0) @@ -189,10 +222,10 @@ final class ModuleInfo { Builder builder = null; Set packages = null; - String version = null; String mainClass = null; String[] osValues = null; ModuleHashes hashes = null; + ModuleResolution moduleResolution = null; for (int i = 0; i < attributes_count ; i++) { int name_index = in.readUnsignedShort(); @@ -215,10 +248,6 @@ final class ModuleInfo { packages = readModulePackagesAttribute(in, cpool); break; - case MODULE_VERSION : - version = readModuleVersionAttribute(in, cpool); - break; - case MODULE_MAIN_CLASS : mainClass = readModuleMainClassAttribute(in, cpool); break; @@ -235,6 +264,10 @@ final class ModuleInfo { } break; + case MODULE_RESOLUTION : + moduleResolution = readModuleResolution(in, cpool); + break; + default: if (isAttributeDisallowed(attribute_name)) { throw invalidModuleDescriptor(attribute_name @@ -263,23 +296,33 @@ final class ModuleInfo { usedPackageFinder = true; } if (packages != null) { - for (String pn : builder.exportedAndOpenPackages()) { - if (!packages.contains(pn)) { - String tail; - if (usedPackageFinder) { - tail = " not found by package finder"; - } else { - tail = " missing from ModulePackages attribute"; + Set exportedPackages = JLMA.exportedPackages(builder); + Set openPackages = JLMA.openPackages(builder); + if (packages.containsAll(exportedPackages) + && packages.containsAll(openPackages)) { + packages.removeAll(exportedPackages); + packages.removeAll(openPackages); + } else { + // the set of packages is not complete + Set exportedAndOpenPackages = new HashSet<>(); + exportedAndOpenPackages.addAll(exportedPackages); + exportedAndOpenPackages.addAll(openPackages); + for (String pn : exportedAndOpenPackages) { + if (!packages.contains(pn)) { + String tail; + if (usedPackageFinder) { + tail = " not found by package finder"; + } else { + tail = " missing from ModulePackages attribute"; + } + throw invalidModuleDescriptor("Package " + pn + tail); } - throw invalidModuleDescriptor("Package " + pn + tail); } - packages.remove(pn); + assert false; // should not get here } builder.contains(packages); } - if (version != null) - builder.version(version); if (mainClass != null) builder.mainClass(mainClass); if (osValues != null) { @@ -287,10 +330,9 @@ final class ModuleInfo { if (osValues[1] != null) builder.osArch(osValues[1]); if (osValues[2] != null) builder.osVersion(osValues[2]); } - if (hashes != null) - builder.hashes(hashes); - return builder.build(); + ModuleDescriptor descriptor = builder.build(); + return new Attributes(descriptor, hashes, moduleResolution); } /** @@ -302,38 +344,55 @@ final class ModuleInfo { { // module_name int module_name_index = in.readUnsignedShort(); - String mn = cpool.getUtf8AsBinaryName(module_name_index); - - Builder builder = new ModuleDescriptor.Builder(mn, /*strict*/ false); + String mn = cpool.getModuleName(module_name_index); int module_flags = in.readUnsignedShort(); boolean open = ((module_flags & ACC_OPEN) != 0); - if (open) - builder.open(true); - if ((module_flags & ACC_SYNTHETIC) != 0) - builder.synthetic(true); + boolean synthetic = ((module_flags & ACC_SYNTHETIC) != 0); + + Builder builder = JLMA.newModuleBuilder(mn, false, open, synthetic); + + int module_version_index = in.readUnsignedShort(); + if (module_version_index != 0) { + String vs = cpool.getUtf8(module_version_index); + builder.version(vs); + } int requires_count = in.readUnsignedShort(); boolean requiresJavaBase = false; for (int i=0; i mods; - if (flags == 0) { + if (requires_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_TRANSITIVE) != 0) + if ((requires_flags & ACC_TRANSITIVE) != 0) mods.add(Requires.Modifier.TRANSITIVE); - if ((flags & ACC_STATIC_PHASE) != 0) + if ((requires_flags & ACC_STATIC_PHASE) != 0) mods.add(Requires.Modifier.STATIC); - if ((flags & ACC_SYNTHETIC) != 0) + if ((requires_flags & ACC_SYNTHETIC) != 0) mods.add(Requires.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((requires_flags & ACC_MANDATED) != 0) mods.add(Requires.Modifier.MANDATED); } - builder.requires(mods, dn); + + int requires_version_index = in.readUnsignedShort(); + Version compiledVersion = null; + if (requires_version_index != 0) { + String vs = cpool.getUtf8(requires_version_index); + compiledVersion = Version.parse(vs); + } + + if (compiledVersion == null) { + builder.requires(mods, dn); + } else { + builder.requires(mods, dn, compiledVersion); + } + if (dn.equals("java.base")) requiresJavaBase = true; } @@ -350,18 +409,18 @@ final class ModuleInfo { int exports_count = in.readUnsignedShort(); if (exports_count > 0) { for (int i=0; i mods; - int flags = in.readUnsignedShort(); - if (flags == 0) { + int exports_flags = in.readUnsignedShort(); + if (exports_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_SYNTHETIC) != 0) + if ((exports_flags & ACC_SYNTHETIC) != 0) mods.add(Exports.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((exports_flags & ACC_MANDATED) != 0) mods.add(Exports.Modifier.MANDATED); } @@ -370,7 +429,7 @@ final class ModuleInfo { Set targets = new HashSet<>(exports_to_count); for (int j=0; j mods; - int flags = in.readUnsignedShort(); - if (flags == 0) { + int opens_flags = in.readUnsignedShort(); + if (opens_flags == 0) { mods = Collections.emptySet(); } else { mods = new HashSet<>(); - if ((flags & ACC_SYNTHETIC) != 0) + if ((opens_flags & ACC_SYNTHETIC) != 0) mods.add(Opens.Modifier.SYNTHETIC); - if ((flags & ACC_MANDATED) != 0) + if ((opens_flags & ACC_MANDATED) != 0) mods.add(Opens.Modifier.MANDATED); } @@ -406,7 +465,7 @@ final class ModuleInfo { Set targets = new HashSet<>(open_to_count); for (int j=0; j 0) { for (int i=0; i 0) { for (int i=0; i providers = new ArrayList<>(with_count); for (int j=0; j packages = new HashSet<>(package_count); for (int i=0; i map = new HashMap<>(hash_count); for (int i=0; i binary name } - String getClassNameAsBinaryName(int index) { - String value = getClassName(index); + String getPackageName(int index) { + checkIndex(index); + Entry e = pool[index]; + if (e.tag != CONSTANT_Package) { + throw invalidModuleDescriptor("CONSTANT_Package expected at entry: " + + index); + } + String value = getUtf8(((IndexEntry) e).index); + checkUnqualifiedName("CONSTANT_Package", index, value); return value.replace('/', '.'); // internal form -> binary name } + String getModuleName(int index) { + checkIndex(index); + Entry e = pool[index]; + if (e.tag != CONSTANT_Module) { + throw invalidModuleDescriptor("CONSTANT_Module expected at entry: " + + index); + } + String value = getUtf8(((IndexEntry) e).index); + return decodeModuleName(index, value); + } + String getUtf8(int index) { checkIndex(index); Entry e = pool[index]; @@ -733,15 +835,103 @@ final class ModuleInfo { return (String) (((ValueEntry) e).value); } - String getUtf8AsBinaryName(int index) { - String value = getUtf8(index); - return value.replace('/', '.'); // internal -> binary name - } - void checkIndex(int index) { if (index < 1 || index >= pool.length) throw invalidModuleDescriptor("Index into constant pool out of range"); } + + void checkUnqualifiedName(String what, int index, String value) { + int len = value.length(); + if (len == 0) { + throw invalidModuleDescriptor(what + " at entry " + index + + " has zero length"); + } + for (int i=0; i= len) { + throw invalidModuleDescriptor("CONSTANT_Module at entry " + + index + " has illegal " + + "escape sequence"); + } + int next = value.codePointAt(j); + if (next != '\\' && next != ':' && next != '@') { + throw invalidModuleDescriptor("CONSTANT_Module at entry " + + index + " has illegal " + + "escape sequence"); + } + sb.appendCodePoint(next); + i += Character.charCount(next); + } else { + sb.appendCodePoint(cp); + } + + i += Character.charCount(cp); + } + return sb.toString(); + } } /** diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java index 07bb40205cf..952a328b71b 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java @@ -70,6 +70,9 @@ public final class ModuleInfoExtender { // the hashes for the Hashes attribute private ModuleHashes hashes; + // the value of the ModuleResolution attribute + private ModuleResolution moduleResolution; + private ModuleInfoExtender(InputStream in) { this.in = in; } @@ -120,6 +123,14 @@ public final class ModuleInfoExtender { return this; } + /** + * Sets the value for the ModuleResolution attribute. + */ + public ModuleInfoExtender moduleResolution(ModuleResolution mres) { + this.moduleResolution = mres; + return this; + } + /** * A ClassVisitor that supports adding class file attributes. If an * attribute already exists then the first occurence of the attribute @@ -183,21 +194,20 @@ public final class ModuleInfoExtender { if (packages != null) cv.addAttribute(new ModulePackagesAttribute(packages)); - if (version != null) - cv.addAttribute(new ModuleVersionAttribute(version)); if (mainClass != null) cv.addAttribute(new ModuleMainClassAttribute(mainClass)); if (osName != null || osArch != null || osVersion != null) cv.addAttribute(new ModuleTargetAttribute(osName, osArch, osVersion)); if (hashes != null) cv.addAttribute(new ModuleHashesAttribute(hashes)); + if (moduleResolution != null) + cv.addAttribute(new ModuleResolutionAttribute(moduleResolution.value())); List attrs = new ArrayList<>(); // prototypes of attributes that should be parsed - attrs.add(new ModuleAttribute()); + attrs.add(new ModuleAttribute(version)); attrs.add(new ModulePackagesAttribute()); - attrs.add(new ModuleVersionAttribute()); attrs.add(new ModuleMainClassAttribute()); attrs.add(new ModuleTargetAttribute()); attrs.add(new ModuleHashesAttribute()); diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java index 5e4efff1486..5a17442106c 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoWriter.java @@ -49,13 +49,12 @@ public final class ModuleInfoWriter { * returning it in a byte array. */ private static byte[] toModuleInfo(ModuleDescriptor md) { - ClassWriter cw = new ClassWriter(0); - cw.visit(Opcodes.V1_9, ACC_MODULE, null, null, null, null); + cw.visit(Opcodes.V1_9, ACC_MODULE, "module-info", null, null, null); cw.visitAttribute(new ModuleAttribute(md)); - // for tests: write the Packages attribute when there are packages that - // aren't exported or open + // for tests: write the ModulePackages attribute when there are packages + // that aren't exported or open Stream exported = md.exports().stream() .map(ModuleDescriptor.Exports::source); Stream open = md.opens().stream() @@ -64,10 +63,10 @@ public final class ModuleInfoWriter { if (md.packages().size() > exportedOrOpen) cw.visitAttribute(new ModulePackagesAttribute(md.packages())); - md.version().ifPresent(v -> cw.visitAttribute(new ModuleVersionAttribute(v))); + // write ModuleMainClass if the module has a main class md.mainClass().ifPresent(mc -> cw.visitAttribute(new ModuleMainClassAttribute(mc))); - // write the TargetPlatform attribute if have any of OS name/arch/version + // write ModuleTarget attribute if have any of OS name/arch/version String osName = md.osName().orElse(null); String osArch = md.osArch().orElse(null); String osVersion = md.osVersion().orElse(null); @@ -76,7 +75,6 @@ public final class ModuleInfoWriter { } cw.visitEnd(); - return cw.toByteArray(); } diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java index 97966bd0012..a80b407d809 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java @@ -149,9 +149,22 @@ public final class ModulePatcher { // return a module reference to the patched module URI location = mref.location().orElse(null); - return JLMA.newPatchedModule(descriptor, - location, - () -> new PatchedModuleReader(paths, mref)); + + ModuleHashes recordedHashes = null; + ModuleResolution mres = null; + if (mref instanceof ModuleReferenceImpl) { + ModuleReferenceImpl impl = (ModuleReferenceImpl)mref; + recordedHashes = impl.recordedHashes(); + mres = impl.moduleResolution(); + } + + return new ModuleReferenceImpl(descriptor, + location, + () -> new PatchedModuleReader(paths, mref), + this, + recordedHashes, + null, + mres); } diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModulePath.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePath.java similarity index 95% rename from jdk/src/java.base/share/classes/java/lang/module/ModulePath.java rename to jdk/src/java.base/share/classes/jdk/internal/module/ModulePath.java index 15df0307180..fb7871d3c31 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModulePath.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePath.java @@ -23,7 +23,7 @@ * questions. */ -package java.lang.module; +package jdk.internal.module; import java.io.BufferedInputStream; import java.io.BufferedReader; @@ -32,7 +32,12 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; +import java.lang.module.FindException; +import java.lang.module.InvalidModuleDescriptorException; +import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Requires; +import java.lang.module.ModuleFinder; +import java.lang.module.ModuleReference; import java.net.URI; import java.nio.file.DirectoryStream; import java.nio.file.Files; @@ -59,7 +64,6 @@ import java.util.zip.ZipFile; import jdk.internal.jmod.JmodFile; import jdk.internal.jmod.JmodFile.Section; -import jdk.internal.module.Checks; import jdk.internal.perf.PerfCounter; import jdk.internal.util.jar.VersionedStream; @@ -74,7 +78,7 @@ import jdk.internal.util.jar.VersionedStream; * modules in JMOD files. */ -class ModulePath implements ModuleFinder { +public class ModulePath implements ModuleFinder { private static final String MODULE_INFO = "module-info.class"; // the version to use for multi-release modular JARs @@ -90,7 +94,7 @@ class ModulePath implements ModuleFinder { // map of module name to module reference map for modules already located private final Map cachedModules = new HashMap<>(); - ModulePath(Runtime.Version version, boolean isLinkPhase, Path... entries) { + public ModulePath(Runtime.Version version, boolean isLinkPhase, Path... entries) { this.releaseVersion = version; this.isLinkPhase = isLinkPhase; this.entries = entries.clone(); @@ -99,7 +103,7 @@ class ModulePath implements ModuleFinder { } } - ModulePath(Path... entries) { + public ModulePath(Path... entries) { this(JarFile.runtimeVersion(), false, entries); } @@ -343,11 +347,11 @@ class ModulePath implements ModuleFinder { */ private ModuleReference readJMod(Path file) throws IOException { try (JmodFile jf = new JmodFile(file)) { - ModuleDescriptor md; + ModuleInfo.Attributes attrs; try (InputStream in = jf.getInputStream(Section.CLASSES, MODULE_INFO)) { - md = ModuleDescriptor.read(in, () -> jmodPackages(jf)); + attrs = ModuleInfo.read(in, () -> jmodPackages(jf)); } - return ModuleReferences.newJModModule(md, file); + return ModuleReferences.newJModModule(attrs, file); } } @@ -557,13 +561,14 @@ class ModulePath implements ModuleFinder { ZipFile.OPEN_READ, releaseVersion)) { - ModuleDescriptor md; + ModuleInfo.Attributes attrs; JarEntry entry = jf.getJarEntry(MODULE_INFO); if (entry == null) { // no module-info.class so treat it as automatic module try { - md = deriveModuleDescriptor(jf); + ModuleDescriptor md = deriveModuleDescriptor(jf); + attrs = new ModuleInfo.Attributes(md, null, null); } catch (IllegalArgumentException iae) { throw new FindException( "Unable to derive module descriptor for: " @@ -571,11 +576,11 @@ class ModulePath implements ModuleFinder { } } else { - md = ModuleDescriptor.read(jf.getInputStream(entry), - () -> jarPackages(jf)); + attrs = ModuleInfo.read(jf.getInputStream(entry), + () -> jarPackages(jf)); } - return ModuleReferences.newJarModule(md, file); + return ModuleReferences.newJarModule(attrs, file); } } @@ -604,15 +609,15 @@ class ModulePath implements ModuleFinder { */ private ModuleReference readExplodedModule(Path dir) throws IOException { Path mi = dir.resolve(MODULE_INFO); - ModuleDescriptor md; + ModuleInfo.Attributes attrs; try (InputStream in = Files.newInputStream(mi)) { - md = ModuleDescriptor.read(new BufferedInputStream(in), - () -> explodedPackages(dir)); + attrs = ModuleInfo.read(new BufferedInputStream(in), + () -> explodedPackages(dir)); } catch (NoSuchFileException e) { // for now return null; } - return ModuleReferences.newExplodedModule(md, dir); + return ModuleReferences.newExplodedModule(attrs, dir); } /** diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java new file mode 100644 index 00000000000..2ab42bdb4a2 --- /dev/null +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java @@ -0,0 +1,169 @@ +/* + * 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.internal.module; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleReader; +import java.lang.module.ModuleReference; +import java.net.URI; +import java.util.Objects; +import java.util.function.Supplier; + +/** + * A ModuleReference implementation that supports referencing a module that + * is patched and/or can be tied to other modules by means of hashes. + */ + +public class ModuleReferenceImpl extends ModuleReference { + + private final Supplier readerSupplier; + + // non-null if the module is patched + private final ModulePatcher patcher; + + // the hashes of other modules recorded in this module + private final ModuleHashes recordedHashes; + + // the function that computes the hash of this module + private final ModuleHashes.HashSupplier hasher; + + // ModuleResolution flags + private final ModuleResolution moduleResolution; + + // cached hash of this module to avoid needing to compute it many times + private byte[] cachedHash; + + /** + * Constructs a new instance of this class. + */ + ModuleReferenceImpl(ModuleDescriptor descriptor, + URI location, + Supplier readerSupplier, + ModulePatcher patcher, + ModuleHashes recordedHashes, + ModuleHashes.HashSupplier hasher, + ModuleResolution moduleResolution) + { + super(descriptor, Objects.requireNonNull(location)); + this.readerSupplier = readerSupplier; + this.patcher = patcher; + this.recordedHashes = recordedHashes; + this.hasher = hasher; + this.moduleResolution = moduleResolution; + } + + @Override + public ModuleReader open() throws IOException { + try { + return readerSupplier.get(); + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + + /** + * Returns {@code true} if this module has been patched via --patch-module. + */ + public boolean isPatched() { + return (patcher != null); + } + + /** + * Returns the hashes recorded in this module or {@code null} if there + * are no hashes recorded. + */ + public ModuleHashes recordedHashes() { + return recordedHashes; + } + + /** + * Returns the supplier that computes the hash of this module. + */ + ModuleHashes.HashSupplier hasher() { + return hasher; + } + + /** + * Returns the ModuleResolution flags. + */ + public ModuleResolution moduleResolution() { + return moduleResolution; + } + + /** + * Computes the hash of this module. Returns {@code null} if the hash + * cannot be computed. + * + * @throws java.io.UncheckedIOException if an I/O error occurs + */ + public byte[] computeHash(String algorithm) { + byte[] result = cachedHash; + if (result != null) + return result; + if (hasher == null) + return null; + cachedHash = result = hasher.generate(algorithm); + return result; + } + + @Override + public int hashCode() { + int hc = hash; + if (hc == 0) { + hc = descriptor().hashCode(); + hc = 43 * hc + Objects.hashCode(location()); + hc = 43 * hc + Objects.hashCode(patcher); + if (hc == 0) + hc = -1; + hash = hc; + } + return hc; + } + + private int hash; + + @Override + public boolean equals(Object ob) { + if (!(ob instanceof ModuleReferenceImpl)) + return false; + ModuleReferenceImpl that = (ModuleReferenceImpl)ob; + + // assume module content, recorded hashes, etc. are the same + // when the modules have equal module descriptors, are at the + // same location, and are patched by the same patcher. + return Objects.equals(this.descriptor(), that.descriptor()) + && Objects.equals(this.location(), that.location()) + && Objects.equals(this.patcher, that.patcher); + } + + @Override + public String toString() { + return super.toString(); + } + +} diff --git a/jdk/src/java.base/share/classes/java/lang/module/ModuleReferences.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java similarity index 92% rename from jdk/src/java.base/share/classes/java/lang/module/ModuleReferences.java rename to jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java index e53ba0441d3..a2aff8f76be 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReferences.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java @@ -23,13 +23,15 @@ * questions. */ -package java.lang.module; +package jdk.internal.module; import java.io.File; import java.io.IOError; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; +import java.lang.module.ModuleReader; +import java.lang.module.ModuleReference; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Files; @@ -51,10 +53,7 @@ import java.util.zip.ZipFile; import jdk.internal.jmod.JmodFile; import jdk.internal.misc.JavaLangAccess; import jdk.internal.misc.SharedSecrets; -import jdk.internal.module.ModuleBootstrap; -import jdk.internal.module.ModuleHashes; import jdk.internal.module.ModuleHashes.HashSupplier; -import jdk.internal.module.ModulePatcher; import jdk.internal.util.jar.VersionedStream; import sun.net.www.ParseUtil; @@ -75,12 +74,18 @@ class ModuleReferences { * Creates a ModuleReference to a module or to patched module when * creating modules for the boot Layer and --patch-module is specified. */ - private static ModuleReference newModule(ModuleDescriptor md, + private static ModuleReference newModule(ModuleInfo.Attributes attrs, URI uri, Supplier supplier, HashSupplier hasher) { - ModuleReference mref = new ModuleReference(md, uri, supplier, hasher); + ModuleReference mref = new ModuleReferenceImpl(attrs.descriptor(), + uri, + supplier, + null, + attrs.recordedHashes(), + hasher, + attrs.moduleResolution()); if (JLA.getBootLayer() == null) mref = ModuleBootstrap.patcher().patchIfNeeded(mref); @@ -90,29 +95,29 @@ class ModuleReferences { /** * Creates a ModuleReference to a module packaged as a modular JAR. */ - static ModuleReference newJarModule(ModuleDescriptor md, Path file) { + static ModuleReference newJarModule(ModuleInfo.Attributes attrs, Path file) { URI uri = file.toUri(); Supplier supplier = () -> new JarModuleReader(file, uri); HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a); - return newModule(md, uri, supplier, hasher); + return newModule(attrs, uri, supplier, hasher); } /** * Creates a ModuleReference to a module packaged as a JMOD. */ - static ModuleReference newJModModule(ModuleDescriptor md, Path file) { + static ModuleReference newJModModule(ModuleInfo.Attributes attrs, Path file) { URI uri = file.toUri(); Supplier supplier = () -> new JModModuleReader(file, uri); HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a); - return newModule(md, file.toUri(), supplier, hasher); + return newModule(attrs, uri, supplier, hasher); } /** * Creates a ModuleReference to an exploded module. */ - static ModuleReference newExplodedModule(ModuleDescriptor md, Path dir) { + static ModuleReference newExplodedModule(ModuleInfo.Attributes attrs, Path dir) { Supplier supplier = () -> new ExplodedModuleReader(dir); - return newModule(md, dir.toUri(), supplier, null); + return newModule(attrs, dir.toUri(), supplier, null); } diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleResolution.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleResolution.java new file mode 100644 index 00000000000..76c42368c63 --- /dev/null +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleResolution.java @@ -0,0 +1,114 @@ +/* + * 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.internal.module; + +import java.lang.module.ModuleReference; +import static jdk.internal.module.ClassFileConstants.*; + +/** + * Represents the Module Resolution flags. + */ +public final class ModuleResolution { + + final int value; + + ModuleResolution(int value) { + this.value = value; + } + + public static ModuleResolution empty() { + return new ModuleResolution(0); + } + + public boolean doNotResolveByDefault() { + return (value & DO_NOT_RESOLVE_BY_DEFAULT) != 0; + } + + public boolean hasDeprecatedWarning() { + return (value & WARN_DEPRECATED) != 0; + } + + public boolean hasDeprecatedForRemovalWarning() { + return (value & WARN_DEPRECATED_FOR_REMOVAL) != 0; + } + + public boolean hasIncubatingWarning() { + return (value & WARN_INCUBATING) != 0; + } + + public ModuleResolution withDoNotResolveByDefault() { + return new ModuleResolution(value | DO_NOT_RESOLVE_BY_DEFAULT); + } + + public ModuleResolution withDeprecated() { + if ((value & (WARN_DEPRECATED_FOR_REMOVAL | WARN_INCUBATING)) != 0) + throw new InternalError("cannot add deprecated to " + value); + return new ModuleResolution(value | WARN_DEPRECATED); + } + + public ModuleResolution withDeprecatedForRemoval() { + if ((value & (WARN_DEPRECATED | WARN_INCUBATING)) != 0) + throw new InternalError("cannot add deprecated for removal to " + value); + return new ModuleResolution(value | WARN_DEPRECATED_FOR_REMOVAL); + } + public ModuleResolution withIncubating() { + if ((value & (WARN_DEPRECATED | WARN_DEPRECATED_FOR_REMOVAL)) != 0) + throw new InternalError("cannot add incubating to " + value); + return new ModuleResolution(value | WARN_INCUBATING); + } + + public int value() { + return value; + } + + public static boolean doNotResolveByDefault(ModuleReference mref) { + // get the DO_NOT_RESOLVE_BY_DEFAULT flag, if any + if (!(mref instanceof ModuleReferenceImpl)) + return false; + + ModuleResolution mres = ((ModuleReferenceImpl)mref).moduleResolution(); + if (mres != null) + return mres.doNotResolveByDefault(); + + return false; + } + + public static boolean hasIncubatingWarning(ModuleReference mref) { + if (!(mref instanceof ModuleReferenceImpl)) + return false; + + ModuleResolution mres = ((ModuleReferenceImpl)mref).moduleResolution(); + if (mres != null) + return mres.hasIncubatingWarning(); + + return false; + } + + @Override + public String toString() { + return super.toString() + "[value=" + value + "]"; + } +} diff --git a/jdk/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java similarity index 79% rename from jdk/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java rename to jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java index 6de8ce824cf..cb7fa0a8d13 100644 --- a/jdk/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java @@ -23,12 +23,16 @@ * questions. */ -package java.lang.module; +package jdk.internal.module; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleFinder; +import java.lang.module.ModuleReader; +import java.lang.module.ModuleReference; import java.net.URI; import java.net.URLConnection; import java.nio.ByteBuffer; @@ -36,7 +40,6 @@ import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; @@ -54,11 +57,7 @@ import jdk.internal.jimage.ImageReader; import jdk.internal.jimage.ImageReaderFactory; import jdk.internal.misc.JavaNetUriAccess; import jdk.internal.misc.SharedSecrets; -import jdk.internal.module.ModuleBootstrap; -import jdk.internal.module.ModuleHashes; import jdk.internal.module.ModuleHashes.HashSupplier; -import jdk.internal.module.SystemModules; -import jdk.internal.module.ModulePatcher; import jdk.internal.perf.PerfCounter; /** @@ -69,7 +68,7 @@ import jdk.internal.perf.PerfCounter; * Packages attribute. */ -class SystemModuleFinder implements ModuleFinder { +public class SystemModuleFinder implements ModuleFinder { private static final JavaNetUriAccess JNUA = SharedSecrets.getJavaNetUriAccess(); @@ -84,11 +83,12 @@ class SystemModuleFinder implements ModuleFinder { // ImageReader used to access all modules in the image private static final ImageReader imageReader; - // the set of modules in the run-time image - private static final Set modules; + // singleton finder to find modules in the run-time images + private static final SystemModuleFinder INSTANCE; - // maps module name to module reference - private static final Map nameToModule; + public static SystemModuleFinder getInstance() { + return INSTANCE; + } /** * For now, the module references are created eagerly on the assumption @@ -98,72 +98,11 @@ class SystemModuleFinder implements ModuleFinder { long t0 = System.nanoTime(); imageReader = ImageReaderFactory.getImageReader(); - String[] names = moduleNames(); - ModuleDescriptor[] descriptors = descriptors(names); - - int n = names.length; - moduleCount.add(n); - - ModuleReference[] mods = new ModuleReference[n]; - - @SuppressWarnings(value = {"rawtypes", "unchecked"}) - Entry[] map - = (Entry[])new Entry[n]; - - for (int i = 0; i < n; i++) { - ModuleDescriptor md = descriptors[i]; - - // create the ModuleReference - ModuleReference mref = toModuleReference(md, hashSupplier(i, names[i])); - - mods[i] = mref; - map[i] = Map.entry(names[i], mref); - - // counters - packageCount.add(md.packages().size()); - exportsCount.add(md.exports().size()); - } - - modules = Set.of(mods); - nameToModule = Map.ofEntries(map); + INSTANCE = new SystemModuleFinder(); initTime.addElapsedTimeFrom(t0); } - /* - * Returns an array of ModuleDescriptor of the given module names. - * - * This obtains ModuleDescriptors from SystemModules class that is generated - * from the jlink system-modules plugin. ModuleDescriptors have already - * been validated at link time. - * - * If java.base is patched, or fastpath is disabled for troubleshooting - * purpose, it will fall back to find system modules via jrt file system. - */ - private static ModuleDescriptor[] descriptors(String[] names) { - // fastpath is enabled by default. - // It can be disabled for troubleshooting purpose. - boolean disabled = - System.getProperty("jdk.system.module.finder.disabledFastPath") != null; - - // fast loading of ModuleDescriptor of system modules - if (isFastPathSupported() && !disabled) - return SystemModules.modules(); - - // if fast loading of ModuleDescriptors is disabled - // fallback to read module-info.class - ModuleDescriptor[] descriptors = new ModuleDescriptor[names.length]; - for (int i = 0; i < names.length; i++) { - String mn = names[i]; - ImageLocation loc = imageReader.findLocation(mn, "module-info.class"); - descriptors[i] = ModuleDescriptor.read(imageReader.getResourceBuffer(loc)); - - // add the recorded hashes of tied modules - Hashes.add(descriptors[i]); - } - return descriptors; - } - private static boolean isFastPathSupported() { return SystemModules.MODULE_NAMES.length > 0; } @@ -178,69 +117,83 @@ class SystemModuleFinder implements ModuleFinder { return imageReader.getModuleNames(); } - private static ModuleReference toModuleReference(ModuleDescriptor md, - HashSupplier hash) - { - String mn = md.name(); - URI uri = JNUA.create("jrt", "/".concat(mn)); + // the set of modules in the run-time image + private final Set modules; - Supplier readerSupplier = new Supplier<>() { - @Override - public ModuleReader get() { - return new ImageModuleReader(mn, uri); - } - }; + // maps module name to module reference + private final Map nameToModule; - ModuleReference mref = - new ModuleReference(md, uri, readerSupplier, hash); + // module name to hashes + private final Map hashes = new HashMap<>(); - // may need a reference to a patched module if --patch-module specified - mref = ModuleBootstrap.patcher().patchIfNeeded(mref); + private SystemModuleFinder() { + String[] names = moduleNames(); + int n = names.length; + moduleCount.add(n); - return mref; - } + // fastpath is enabled by default. + // It can be disabled for troubleshooting purpose. + boolean disabled = + System.getProperty("jdk.system.module.finder.disabledFastPath") != null; - private static HashSupplier hashSupplier(int index, String name) { - if (isFastPathSupported()) { - return new HashSupplier() { - @Override - public byte[] generate(String algorithm) { - return SystemModules.MODULES_TO_HASH[index]; - } - }; + ModuleDescriptor[] descriptors; + ModuleHashes[] recordedHashes; + ModuleResolution[] moduleResolutions; + + // fast loading of ModuleDescriptor of system modules + if (isFastPathSupported() && !disabled) { + descriptors = SystemModules.descriptors(); + recordedHashes = SystemModules.hashes(); + moduleResolutions = SystemModules.moduleResolutions(); } else { - return Hashes.hashFor(name); - } - } - - /* - * This helper class is only used when SystemModules is patched. - * It will get the recorded hashes from module-info.class. - */ - private static class Hashes { - static Map hashes = new HashMap<>(); - - static void add(ModuleDescriptor descriptor) { - Optional ohashes = descriptor.hashes(); - if (ohashes.isPresent()) { - hashes.putAll(ohashes.get().hashes()); + // if fast loading of ModuleDescriptors is disabled + // fallback to read module-info.class + descriptors = new ModuleDescriptor[n]; + recordedHashes = new ModuleHashes[n]; + moduleResolutions = new ModuleResolution[n]; + for (int i = 0; i < names.length; i++) { + String mn = names[i]; + ImageLocation loc = imageReader.findLocation(mn, "module-info.class"); + ModuleInfo.Attributes attrs = + ModuleInfo.read(imageReader.getResourceBuffer(loc), null); + descriptors[i] = attrs.descriptor(); + recordedHashes[i] = attrs.recordedHashes(); + moduleResolutions[i] = attrs.moduleResolution(); } } - static HashSupplier hashFor(String name) { - if (!hashes.containsKey(name)) - return null; - - return new HashSupplier() { - @Override - public byte[] generate(String algorithm) { - return hashes.get(name); - } - }; + // record the hashes to build HashSupplier + for (ModuleHashes mh : recordedHashes) { + if (mh != null) { + hashes.putAll(mh.hashes()); + } } - } - SystemModuleFinder() { } + ModuleReference[] mods = new ModuleReference[n]; + + @SuppressWarnings(value = {"rawtypes", "unchecked"}) + Entry[] map + = (Entry[])new Entry[n]; + + for (int i = 0; i < n; i++) { + ModuleDescriptor md = descriptors[i]; + + // create the ModuleReference + ModuleReference mref = toModuleReference(md, + recordedHashes[i], + hashSupplier(names[i]), + moduleResolutions[i]); + mods[i] = mref; + map[i] = Map.entry(names[i], mref); + + // counters + packageCount.add(md.packages().size()); + exportsCount.add(md.exports().size()); + } + + modules = Set.of(mods); + nameToModule = Map.ofEntries(map); + } @Override public Optional find(String name) { @@ -253,6 +206,41 @@ class SystemModuleFinder implements ModuleFinder { return modules; } + private ModuleReference toModuleReference(ModuleDescriptor md, + ModuleHashes recordedHashes, + HashSupplier hasher, + ModuleResolution mres) { + String mn = md.name(); + URI uri = JNUA.create("jrt", "/".concat(mn)); + + Supplier readerSupplier = new Supplier<>() { + @Override + public ModuleReader get() { + return new ImageModuleReader(mn, uri); + } + }; + + ModuleReference mref = + new ModuleReferenceImpl(md, uri, readerSupplier, null, + recordedHashes, hasher, mres); + + // may need a reference to a patched module if --patch-module specified + mref = ModuleBootstrap.patcher().patchIfNeeded(mref); + + return mref; + } + + private HashSupplier hashSupplier(String name) { + if (!hashes.containsKey(name)) + return null; + + return new HashSupplier() { + @Override + public byte[] generate(String algorithm) { + return hashes.get(name); + } + }; + } /** * A ModuleReader for reading resources from a module linked into the diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/SystemModules.java b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModules.java index 299c6220450..7f2dbd0aad1 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/SystemModules.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModules.java @@ -29,14 +29,14 @@ import java.lang.module.ModuleDescriptor; /* * SystemModules class will be generated at link time to create - * ModuleDescriptor for the installed modules directly to improve + * ModuleDescriptor for the system modules directly to improve * the module descriptor reconstitution time. * * This will skip parsing of module-info.class file and validating * names such as module name, package name, service and provider type names. * It also avoids taking a defensive copy of any collection. * - * @see jdk.tools.jlink.internal.plugins.SystemModuleDescriptorPlugin + * @see jdk.tools.jlink.internal.plugins.SystemModulesPlugin */ public final class SystemModules { /** @@ -48,11 +48,6 @@ public final class SystemModules { */ public static final String[] MODULE_NAMES = new String[0]; - /** - * Hash of system modules. - */ - public static byte[][] MODULES_TO_HASH = new byte[0][]; - /** * Number of packages in the boot layer from the installed modules. * @@ -66,8 +61,24 @@ public final class SystemModules { * * When running an exploded image it returns an empty array. */ - public static ModuleDescriptor[] modules() { - throw new InternalError("should not reach here"); + public static ModuleDescriptor[] descriptors() { + throw new InternalError("expected to be overridden at link time"); } + /** + * Returns a non-empty array of ModuleHashes recorded in each module + * in the run-time image. + * + * When running an exploded image it returns an empty array. + */ + public static ModuleHashes[] hashes() { + throw new InternalError("expected to be overridden at link time"); + } + + /** + * Returns a non-empty array of ModuleResolutions in the run-time image. + */ + public static ModuleResolution[] moduleResolutions() { + throw new InternalError("expected to be overridden at link time"); + } } diff --git a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java index 90593f58fc3..4d91a001690 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java +++ b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassReader.java @@ -2490,6 +2490,40 @@ public class ClassReader { return readUTF8(items[readUnsignedShort(index)], buf); } + /** + * Reads a CONSTANT_Module_info item in {@code b}. This method is intended + * for {@link Attribute} sub classes, and is normally not needed by class + * generators or adapters. + * + * @param index + * the start index of an unsigned short value in {@link #b b}, + * whose value is the index of a module constant pool item. + * @param buf + * buffer to be used to read the item. This buffer must be + * sufficiently large. It is not automatically resized. + * @return the String corresponding to the specified module item. + */ + public String readModule(int index, char[] buf) { + return readUTF8(items[readUnsignedShort(index)], buf); + } + + /** + * Reads a CONSTANT_Pakcage_info item in {@code b}. This method is + * intended for {@link Attribute} sub slasses, and is normally not needed + * by class generators or adapters. + * + * @param index + * the start index of an unsigned short value in {@link #b b}, + * whose value is the index of a package constant pool item. + * @param buf + * buffer to be used to read the item. This buffer must be + * sufficiently large. It is not automatically resized. + * @return the String corresponding to the specified package item. + */ + public String readPackage(int index, char[] buf) { + return readUTF8(items[readUnsignedShort(index)], buf); + } + /** * Reads a numeric or string constant pool item in {@link #b b}. This * method is intended for {@link Attribute} sub classes, and is normally not @@ -2516,6 +2550,8 @@ public class ClassReader { case ClassWriter.DOUBLE: return Double.longBitsToDouble(readLong(index)); case ClassWriter.CLASS: + case ClassWriter.MODULE: + case ClassWriter.PACKAGE: return Type.getObjectType(readUTF8(index, buf)); case ClassWriter.STR: return readUTF8(index, buf); diff --git a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java index a577f933270..bd0978c0c09 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java +++ b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java @@ -271,6 +271,16 @@ public class ClassWriter extends ClassVisitor { */ static final int INDY = 18; + /** + * The type of CONSTANT_Module constant pool items. + */ + static final int MODULE = 19; + + /** + * The type of CONSTANT_Package constant pool items. + */ + static final int PACKAGE = 20; + /** * The base value for all CONSTANT_MethodHandle constant pool items. * Internally, ASM store the 9 variations of CONSTANT_MethodHandle into 9 @@ -1160,6 +1170,50 @@ public class ClassWriter extends ClassVisitor { return newClassItem(value).index; } + /** + * Adds a module name to the constant pool. + * + * Does nothing if the constant pool already contains a similar item. + * This method is intended for {@link Attribute} sub classes, and is + * normally not needed by class generators or adapters. + * + * @param value + * the module name + * @return the index of a new or already existing module reference item. + */ + public int newModule(String value) { + key2.set(MODULE, value, null, null); + Item result = get(key2); + if (result == null) { + pool.put12(MODULE, newUTF8(value)); + result = new Item(index++, key2); + put(result); + } + return result.index; + } + + /** + * Adds a package name to the constant pool. + * + * Does nothing if the constant pool already contains a similar item. + * This method is intended for {@link Attribute} sub classes, and is + * normally not needed by class generators or adapters. + * + * @param value + * the internal name of the package. + * @return the index of a new or already existing package reference item. + */ + public int newPackage(String value) { + key2.set(PACKAGE, value, null, null); + Item result = get(key2); + if (result == null) { + pool.put12(PACKAGE, newUTF8(value)); + result = new Item(index++, key2); + put(result); + } + return result.index; + } + /** * Adds a method type reference to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. diff --git a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Item.java b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Item.java index 25ed37718dd..b0b80907d9d 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Item.java +++ b/jdk/src/java.base/share/classes/jdk/internal/org/objectweb/asm/Item.java @@ -239,6 +239,8 @@ final class Item { this.strVal3 = strVal3; switch (type) { case ClassWriter.CLASS: + case ClassWriter.MODULE: + case ClassWriter.PACKAGE: this.intVal = 0; // intVal of a class must be zero, see visitInnerClass case ClassWriter.UTF8: case ClassWriter.STR: @@ -311,6 +313,8 @@ final class Item { case ClassWriter.UTF8: case ClassWriter.STR: case ClassWriter.CLASS: + case ClassWriter.MODULE: + case ClassWriter.PACKAGE: case ClassWriter.MTYPE: case ClassWriter.TYPE_NORMAL: return i.strVal1.equals(strVal1); diff --git a/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java b/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java index 0c4cb744578..9a410049188 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java +++ b/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java @@ -31,6 +31,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; import jdk.internal.HotSpotIntrinsicCandidate; +import jdk.internal.misc.SharedSecrets; import jdk.internal.misc.VM; import sun.security.action.GetPropertyAction; @@ -218,8 +219,16 @@ public class Reflection { if (c.isPrimitive()) return true; - // check that memberModule exports the package to currentModule - return memberModule.isExported(c.getPackageName(), currentModule); + String pkg = c.getPackageName(); + boolean allowed = memberModule.isExported(pkg, currentModule); + if (allowed && memberModule.isNamed() && printStackTraceWhenAccessSucceeds()) { + if (!SharedSecrets.getJavaLangReflectModuleAccess() + .isStaticallyExported(memberModule, pkg, currentModule)) { + String msg = currentModule + " allowed access to member of " + memberClass; + new Exception(msg).printStackTrace(System.err); + } + } + return allowed; } /** @@ -348,25 +357,43 @@ public class Reflection { } - // true to print a stack trace when IAE is thrown + // true to print a stack trace when access fails private static volatile boolean printStackWhenAccessFails; - // true if printStackWhenAccessFails has been initialized - private static volatile boolean printStackWhenAccessFailsSet; + // true to print a stack trace when access succeeds + private static volatile boolean printStackWhenAccessSucceeds; - private static void printStackTraceIfNeeded(Throwable e) { - if (!printStackWhenAccessFailsSet && VM.initLevel() >= 1) { + // true if printStack* values are initialized + private static volatile boolean printStackPropertiesSet; + + private static void ensurePrintStackPropertiesSet() { + if (!printStackPropertiesSet && VM.initLevel() >= 1) { String s = GetPropertyAction.privilegedGetProperty( "sun.reflect.debugModuleAccessChecks"); - printStackWhenAccessFails = - (s != null && !s.equalsIgnoreCase("false")); - printStackWhenAccessFailsSet = true; - } - if (printStackWhenAccessFails) { - e.printStackTrace(); + if (s != null) { + printStackWhenAccessFails = !s.equalsIgnoreCase("false"); + printStackWhenAccessSucceeds = s.equalsIgnoreCase("access"); + } + printStackPropertiesSet = true; } } + public static void enableStackTraces() { + printStackWhenAccessFails = true; + printStackWhenAccessSucceeds = true; + printStackPropertiesSet = true; + } + + public static boolean printStackTraceWhenAccessFails() { + ensurePrintStackPropertiesSet(); + return printStackWhenAccessFails; + } + + public static boolean printStackTraceWhenAccessSucceeds() { + ensurePrintStackPropertiesSet(); + return printStackWhenAccessSucceeds; + } + /** * Throws IllegalAccessException with the an exception message based on * the access that is denied. @@ -416,17 +443,10 @@ public class Reflection { throws IllegalAccessException { IllegalAccessException e = new IllegalAccessException(msg); - printStackTraceIfNeeded(e); + ensurePrintStackPropertiesSet(); + if (printStackWhenAccessFails) { + e.printStackTrace(System.err); + } throw e; } - - /** - * Throws InaccessibleObjectException with the given exception message. - */ - public static void throwInaccessibleObjectException(String msg) { - InaccessibleObjectException e = new InaccessibleObjectException(msg); - printStackTraceIfNeeded(e); - throw e; - } - } diff --git a/jdk/src/java.compact1/share/classes/module-info.java b/jdk/src/java.compact1/share/classes/module-info.java index 72d4357759a..29a70780f5d 100644 --- a/jdk/src/java.compact1/share/classes/module-info.java +++ b/jdk/src/java.compact1/share/classes/module-info.java @@ -26,6 +26,7 @@ /** * Aggregates {@code java.base}, {@code java.logging}, and {@code java.scripting}. */ +@SuppressWarnings("module") module java.compact1 { requires transitive java.logging; requires transitive java.scripting; diff --git a/jdk/src/java.compact2/share/classes/module-info.java b/jdk/src/java.compact2/share/classes/module-info.java index 0666be8fc10..8a283cef0db 100644 --- a/jdk/src/java.compact2/share/classes/module-info.java +++ b/jdk/src/java.compact2/share/classes/module-info.java @@ -26,6 +26,7 @@ /** * Supplements {@code java.compact1} with JDBC, JAXP, and RMI. */ +@SuppressWarnings("module") module java.compact2 { requires transitive java.compact1; requires transitive java.rmi; diff --git a/jdk/src/java.compact3/share/classes/module-info.java b/jdk/src/java.compact3/share/classes/module-info.java index 9783a406a54..d61c56e429d 100644 --- a/jdk/src/java.compact3/share/classes/module-info.java +++ b/jdk/src/java.compact3/share/classes/module-info.java @@ -27,6 +27,7 @@ * Supplements {@code java.compact2} with JDBC RowSet, JMX, JNDI, Compiler, * Instrumentation, Preferences, Security, and XML cryptography APIs. */ +@SuppressWarnings("module") module java.compact3 { requires transitive java.compact2; requires transitive java.compiler; diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java b/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java index 07f4c1bf3e1..31aaebf5e4d 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java @@ -23,6 +23,7 @@ * questions. */ +@SuppressWarnings("module") module jdk.crypto.pkcs11 { // Depends on SunEC provider for EC related functionality requires jdk.crypto.ec; diff --git a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java index 62992138361..1b5d48a6b4a 100644 --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java @@ -34,6 +34,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import jdk.internal.module.ModuleResolution; /** * Parser for GNU Style Options. @@ -158,6 +159,31 @@ class GNUStyleOptions { ModuleFinder.of(paths)); } }, + new Option(false, OptionType.CREATE_UPDATE, "--do-not-resolve-by-default") { + void process(Main jartool, String opt, String arg) { + ModuleResolution mres = jartool.moduleResolution; + jartool.moduleResolution = mres.withDoNotResolveByDefault(); + } + boolean isExtra() { return true; } + }, + new Option(true, OptionType.CREATE_UPDATE, "--warn-if-resolved") { + void process(Main jartool, String opt, String arg) throws BadArgs { + ModuleResolution mres = ModuleResolution.empty(); + if (jartool.moduleResolution.doNotResolveByDefault()) + mres.withDoNotResolveByDefault(); + + if (arg.equals("deprecated")) { + jartool.moduleResolution = mres.withDeprecated(); + } else if (arg.equals("deprecated-for-removal")) { + jartool.moduleResolution = mres.withDeprecatedForRemoval(); + } else if (arg.equals("incubating")) { + jartool.moduleResolution = mres.withIncubating(); + } else { + throw new BadArgs("error.bad.reason", arg); + } + } + boolean isExtra() { return true; } + }, new Option(false, OptionType.CREATE_UPDATE_INDEX, "--no-compress", "-0") { void process(Main jartool, String opt, String arg) { jartool.flag0 = true; @@ -175,17 +201,20 @@ class GNUStyleOptions { // Other options new Option(true, true, OptionType.OTHER, "--help", "-h") { void process(Main jartool, String opt, String arg) throws BadArgs { - if (jartool.info == null) { - if (arg == null) { - jartool.info = Main.Info.HELP; - return; - } - - if (!arg.equals("compat")) - throw new BadArgs("error.illegal.option", arg).showUsage(true); - - jartool.info = Main.Info.COMPAT_HELP; + if (arg == null) { + jartool.info = Main.Info.HELP; + return; } + + if (!arg.equals("compat")) + throw new BadArgs("error.illegal.option", arg).showUsage(true); + + jartool.info = Main.Info.COMPAT_HELP; + } + }, + new Option(false, OptionType.OTHER, "--help-extra") { + void process(Main jartool, String opt, String arg) throws BadArgs { + jartool.info = Main.Info.HELP_EXTRA; } }, new Option(false, OptionType.OTHER, "--version") { @@ -229,6 +258,8 @@ class GNUStyleOptions { boolean isHidden() { return false; } + boolean isExtra() { return false; } + boolean matches(String opt) { for (String a : aliases) { if (a.equals(opt)) { @@ -292,6 +323,14 @@ class GNUStyleOptions { } static void printHelp(PrintWriter out) { + printHelp(out, false); + } + + static void printHelpExtra(PrintWriter out) { + printHelp(out, true); + } + + private static void printHelp(PrintWriter out, boolean printExtra) { out.format("%s%n", Main.getMsg("main.help.preopt")); for (OptionType type : OptionType.values()) { boolean typeHeadingWritten = false; @@ -304,6 +343,9 @@ class GNUStyleOptions { if (o.isHidden() || name.equals("h")) { continue; } + if (o.isExtra() && !printExtra) { + continue; + } if (!typeHeadingWritten) { out.format("%n%s%n", Main.getMsg("main.help.opt." + type.name)); typeHeadingWritten = true; diff --git a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java index 6d00af822ff..8e0fc0160de 100644 --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java @@ -47,7 +47,6 @@ import java.nio.file.StandardCopyOption; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; -import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -57,11 +56,11 @@ import java.util.jar.Pack200.*; import java.util.jar.Manifest; import java.text.MessageFormat; -import jdk.internal.misc.JavaLangModuleAccess; -import jdk.internal.misc.SharedSecrets; import jdk.internal.module.Checks; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleInfo; import jdk.internal.module.ModuleInfoExtender; +import jdk.internal.module.ModuleResolution; import jdk.internal.util.jar.JarIndex; import static jdk.internal.util.jar.JarIndex.INDEX_NAME; @@ -211,6 +210,7 @@ class Main { /* To support additional GNU Style informational options */ enum Info { HELP(GNUStyleOptions::printHelp), + HELP_EXTRA(GNUStyleOptions::printHelpExtra), COMPAT_HELP(GNUStyleOptions::printCompatHelp), USAGE_TRYHELP(GNUStyleOptions::printUsageTryHelp), VERSION(GNUStyleOptions::printVersion); @@ -225,6 +225,7 @@ class Main { /* Modular jar related options */ Version moduleVersion; Pattern modulesToHash; + ModuleResolution moduleResolution = ModuleResolution.empty(); ModuleFinder moduleFinder = ModuleFinder.of(); private static final String MODULE_INFO = "module-info.class"; @@ -1991,12 +1992,13 @@ class Main { .collect(joining(" ")); } - private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess(); - private void printModuleDescriptor(InputStream entryInputStream) throws IOException { - ModuleDescriptor md = ModuleDescriptor.read(entryInputStream); + ModuleInfo.Attributes attrs = ModuleInfo.read(entryInputStream, null); + ModuleDescriptor md = attrs.descriptor(); + ModuleHashes hashes = attrs.recordedHashes(); + StringBuilder sb = new StringBuilder(); sb.append("\n"); if (md.isOpen()) @@ -2043,15 +2045,24 @@ class Main { md.osVersion().ifPresent(v -> sb.append("\n operating-system-version " + v)); - JLMA.hashes(md).ifPresent(hashes -> - hashes.names().stream().sorted().forEach( + if (hashes != null) { + hashes.names().stream().sorted().forEach( mod -> sb.append("\n hashes ").append(mod).append(" ") .append(hashes.algorithm()).append(" ") - .append(hashes.hashFor(mod)))); + .append(toHex(hashes.hashFor(mod)))); + } output(sb.toString()); } + private static String toHex(byte[] ba) { + StringBuilder sb = new StringBuilder(ba.length); + for (byte b: ba) { + sb.append(String.format("%02x", b & 0xff)); + } + return sb.toString(); + } + private static String toBinaryName(String classname) { return (classname.replace('.', '/')) + ".class"; } @@ -2212,6 +2223,10 @@ class Main { } } + if (moduleResolution.value() != 0) { + extender.moduleResolution(moduleResolution); + } + extender.write(baos); return baos.toByteArray(); } @@ -2228,13 +2243,12 @@ class Main { // Create a module finder that finds the modular JAR // being created/updated URI uri = Paths.get(fname).toUri(); - ModuleReference mref = new ModuleReference(descriptor, uri, - new Supplier<>() { - @Override - public ModuleReader get() { - throw new UnsupportedOperationException("should not reach here"); - } - }); + ModuleReference mref = new ModuleReference(descriptor, uri) { + @Override + public ModuleReader open() { + throw new UnsupportedOperationException("should not reach here"); + } + }; // Compose a module finder with the module path and // the modular JAR being created or updated diff --git a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties index dd1d0ff4ee0..c575f3b3c00 100644 --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties @@ -46,6 +46,8 @@ error.bad.eflag=\ together! error.bad.dflag=\ '-d, --print-module-descriptor' option requires no input file(s) to be specified: {0} +error.bad.reason=\ + bad reason: {0}, must be one of deprecated, deprecated-for-removal, or incubating error.nosuch.fileordir=\ {0} : no such file or directory error.write.file=\ @@ -246,6 +248,12 @@ main.help.opt.create.update.hash-modules=\ main.help.opt.create.update.module-path=\ \ -p, --module-path Location of module dependence for generating\n\ \ the hash +main.help.opt.create.update.do-not-resolve-by-default=\ +\ --do-not-resolve-by-default Exclude from the default root set of modules +main.help.opt.create.update.warn-if-resolved=\ +\ --warn-if-resolved Hint for a tool to issue a warning if the module\n\ +\ is resolved. One of deprecated, deprecated-for-removal,\n\ +\ or incubating main.help.opt.create.update.index=\ \ Operation modifiers valid only in create, update, and generate-index mode:\n main.help.opt.create.update.index.no-compress=\ @@ -254,6 +262,8 @@ main.help.opt.other=\ \ Other options:\n main.help.opt.other.help=\ \ -?, --help[:compat] Give this, or optionally the compatibility, help +main.help.opt.other.help-extra=\ +\ --help-extra Give help on extra options main.help.opt.other.version=\ \ --version Print program version main.help.postopt=\ diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java index 4a5cbffe579..f5e429fed43 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java @@ -53,7 +53,9 @@ import jdk.tools.jlink.internal.ImagePluginStack.ImageProvider; import jdk.tools.jlink.plugin.PluginException; import jdk.tools.jlink.builder.DefaultImageBuilder; import jdk.tools.jlink.plugin.Plugin; -import jdk.internal.misc.SharedSecrets; +import jdk.internal.module.Checks; +import jdk.internal.module.ModulePath; +import jdk.internal.module.ModuleResolution; /** * Implementation for the jlink tool. @@ -260,7 +262,8 @@ public class JlinkTask { config.getModules(), config.getByteOrder(), null, - IGNORE_SIGNING_DEFAULT); + IGNORE_SIGNING_DEFAULT, + null); // Then create the Plugin Stack ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins); @@ -328,7 +331,8 @@ public class JlinkTask { roots, options.endian, options.packagedModulesPath, - options.ignoreSigning); + options.ignoreSigning, + log); // Then create the Plugin Stack ImagePluginStack stack = ImagePluginConfiguration. @@ -344,9 +348,7 @@ public class JlinkTask { */ private ModuleFinder modulePathFinder() { Path[] entries = options.modulePath.toArray(new Path[0]); - ModuleFinder finder = SharedSecrets.getJavaLangModuleAccess() - .newModulePath(Runtime.version(), true, entries); - + ModuleFinder finder = new ModulePath(Runtime.version(), true, entries); if (!options.limitMods.isEmpty()) { finder = limitFinder(finder, options.limitMods, Collections.emptySet()); } @@ -364,8 +366,7 @@ public class JlinkTask { Set roots) { Path[] entries = paths.toArray(new Path[0]); - ModuleFinder finder = SharedSecrets.getJavaLangModuleAccess() - .newModulePath(Runtime.version(), true, entries); + ModuleFinder finder = new ModulePath(Runtime.version(), true, entries); // if limitmods is specified then limit the universe if (!limitMods.isEmpty()) { @@ -386,7 +387,8 @@ public class JlinkTask { Set roots, ByteOrder order, Path retainModulesPath, - boolean ignoreSigning) + boolean ignoreSigning, + PrintWriter log) throws IOException { if (roots.isEmpty()) { @@ -398,6 +400,27 @@ public class JlinkTask { ModuleFinder.of(), roots); + // emit warning for modules that end with a digit + cf.modules().stream() + .map(ResolvedModule::name) + .filter(mn -> !Checks.hasLegalModuleNameLastCharacter(mn)) + .forEach(mn -> System.err.println("WARNING: Module name \"" + + mn + "\" may soon be illegal")); + + // emit a warning for any incubating modules in the configuration + if (log != null) { + String im = cf.modules() + .stream() + .map(ResolvedModule::reference) + .filter(ModuleResolution::hasIncubatingWarning) + .map(ModuleReference::descriptor) + .map(ModuleDescriptor::name) + .collect(Collectors.joining(", ")); + + if (!"".equals(im)) + log.println("WARNING: Using incubator modules: " + im); + } + Map mods = cf.modules().stream() .collect(Collectors.toMap(ResolvedModule::name, JlinkTask::toPathLocation)); return new ImageHelper(cf, mods, order, retainModulesPath, ignoreSigning); diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java index 63ce3cd7593..9c81c7740c6 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java @@ -28,6 +28,7 @@ package jdk.tools.jlink.internal; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; +import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.io.IOException; import java.io.UncheckedIOException; @@ -78,10 +79,12 @@ final class ResourcePoolConfiguration { } private static ModuleReference moduleReference(ModuleDescriptor desc) { - return new ModuleReference(desc, null, () -> { - IOException ioe = new IOException(""); - throw new UncheckedIOException(ioe); - }); + return new ModuleReference(desc, null) { + @Override + public ModuleReader open() { + throw new UnsupportedOperationException(); + } + }; } private static Map allModRefs(ResourcePool pool) { diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java index fc7d85fbff7..4ae1af566a0 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java @@ -58,7 +58,7 @@ import jdk.tools.jlink.internal.Jlink.PluginsConfiguration; import jdk.tools.jlink.internal.plugins.PluginsResourceBundle; import jdk.tools.jlink.internal.plugins.DefaultCompressPlugin; import jdk.tools.jlink.internal.plugins.StripDebugPlugin; -import jdk.internal.misc.SharedSecrets; +import jdk.internal.module.ModulePath; /** * @@ -765,9 +765,7 @@ public final class TaskHelper { static Layer createPluginsLayer(List paths) { Path[] dirs = paths.toArray(new Path[0]); - ModuleFinder finder = SharedSecrets.getJavaLangModuleAccess() - .newModulePath(Runtime.version(), true, dirs); - + ModuleFinder finder = new ModulePath(Runtime.version(), true, dirs); Configuration bootConfiguration = Layer.boot().configuration(); try { Configuration cf = bootConfiguration diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModuleDescriptorPlugin.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java similarity index 67% rename from jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModuleDescriptorPlugin.java rename to jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java index 6be8c5f2acf..6adb3d699b5 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModuleDescriptorPlugin.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 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 @@ -34,17 +34,19 @@ import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; +import java.util.TreeSet; import java.util.function.IntSupplier; import jdk.internal.misc.JavaLangModuleAccess; import jdk.internal.misc.SharedSecrets; import jdk.internal.module.Checks; +import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleInfo.Attributes; import jdk.internal.module.ModuleInfoExtender; +import jdk.internal.module.ModuleResolution; import jdk.internal.module.SystemModules; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.MethodVisitor; @@ -55,7 +57,6 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; import jdk.tools.jlink.plugin.PluginException; import jdk.tools.jlink.plugin.ResourcePool; import jdk.tools.jlink.plugin.Plugin; -import jdk.tools.jlink.internal.plugins.SystemModuleDescriptorPlugin.SystemModulesClassGenerator.*; import jdk.tools.jlink.plugin.ResourcePoolBuilder; import jdk.tools.jlink.plugin.ResourcePoolEntry; @@ -67,10 +68,10 @@ import jdk.tools.jlink.plugin.ResourcePoolEntry; * * This plugin will override jdk.internal.module.SystemModules class * - * @see java.lang.module.SystemModuleFinder + * @see jdk.internal.module.SystemModuleFinder * @see SystemModules */ -public final class SystemModuleDescriptorPlugin implements Plugin { +public final class SystemModulesPlugin implements Plugin { private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess(); @@ -79,7 +80,7 @@ public final class SystemModuleDescriptorPlugin implements Plugin { PluginsResourceBundle.getDescription(NAME); private boolean enabled; - public SystemModuleDescriptorPlugin() { + public SystemModulesPlugin() { this.enabled = true; } @@ -126,20 +127,18 @@ public final class SystemModuleDescriptorPlugin implements Plugin { assert module.name().equals(data.moduleName()); try { - ByteArrayInputStream bain = new ByteArrayInputStream(data.contentBytes()); - ModuleDescriptor md = ModuleDescriptor.read(bain); - validateNames(md); + ModuleInfo moduleInfo = new ModuleInfo(data.contentBytes(), module.packages()); + generator.addModule(moduleInfo); - Set packages = module.packages(); - generator.addModule(md, module.packages()); + // link-time validation + moduleInfo.validateNames(); + // check if any exported or open package is not present + moduleInfo.validatePackages(); - // add Packages attribute if not exist - if (md.packages().isEmpty() && packages.size() > 0) { - bain.reset(); - ModuleInfoRewriter minfoWriter = - new ModuleInfoRewriter(bain, module.packages()); + // Packages attribute needs update + if (moduleInfo.shouldAddPackagesAttribute()) { // replace with the overridden version - data = data.copyWithContent(minfoWriter.getBytes()); + data = data.copyWithContent(moduleInfo.getBytes()); } out.add(data); } catch (IOException e) { @@ -164,61 +163,119 @@ public final class SystemModuleDescriptorPlugin implements Plugin { return out.build(); } - /* - * Add Packages attribute - */ - class ModuleInfoRewriter extends ByteArrayOutputStream { - final ModuleInfoExtender extender; - ModuleInfoRewriter(InputStream in, Set packages) throws IOException { - this.extender = ModuleInfoExtender.newExtender(in); - // Add Packages attribute - this.extender.packages(packages); - this.extender.write(this); + class ModuleInfo { + final ModuleDescriptor descriptor; + final ModuleHashes recordedHashes; + final ModuleResolution moduleResolution; + final Set packages; + final ByteArrayInputStream bain; + + ModuleInfo(byte[] bytes, Set packages) throws IOException { + this.bain = new ByteArrayInputStream(bytes); + this.packages = packages; + + Attributes attrs = jdk.internal.module.ModuleInfo.read(bain, null); + this.descriptor = attrs.descriptor(); + this.recordedHashes = attrs.recordedHashes(); + this.moduleResolution = attrs.moduleResolution(); + + if (descriptor.isAutomatic()) { + throw new InternalError("linking automatic module is not supported"); + } } - byte[] getBytes() { - return buf; + String moduleName() { + return descriptor.name(); } - } - void validateNames(ModuleDescriptor md) { - Checks.requireModuleName(md.name()); - for (Requires req : md.requires()) { - Checks.requireModuleName(req.name()); + /** + * Validates names in ModuleDescriptor + */ + void validateNames() { + Checks.requireModuleName(descriptor.name()); + for (Requires req : descriptor.requires()) { + Checks.requireModuleName(req.name()); + } + for (Exports e : descriptor.exports()) { + Checks.requirePackageName(e.source()); + if (e.isQualified()) + e.targets().forEach(Checks::requireModuleName); + } + for (Opens opens : descriptor.opens()) { + Checks.requirePackageName(opens.source()); + if (opens.isQualified()) + opens.targets().forEach(Checks::requireModuleName); + } + for (Provides provides : descriptor.provides()) { + Checks.requireServiceTypeName(provides.service()); + provides.providers().forEach(Checks::requireServiceProviderName); + } + for (String service : descriptor.uses()) { + Checks.requireServiceTypeName(service); + } + for (String pn : descriptor.packages()) { + Checks.requirePackageName(pn); + } } - for (Exports e : md.exports()) { - Checks.requirePackageName(e.source()); - if (e.isQualified()) - e.targets().forEach(Checks::requireModuleName); - } - for (Opens opens : md.opens()) { - Checks.requirePackageName(opens.source()); - if (opens.isQualified()) - opens.targets().forEach(Checks::requireModuleName); - } - for (Provides provides : md.provides()) { - Checks.requireServiceTypeName(provides.service()); - provides.providers().forEach(Checks::requireServiceProviderName); - } - for (String service : md.uses()) { - Checks.requireServiceTypeName(service); - } - for (String pn : md.packages()) { - Checks.requirePackageName(pn); - } - } - /* - * Returns the initial capacity for a new Set or Map of the given size - * to avoid resizing. - */ - static final int initialCapacity(int size) { - if (size == 0) { - return 0; - } else { - // Adjust to try and get size/capacity as close to the - // HashSet/HashMap default load factor without going over. - return (int)(Math.ceil((double)size / 0.75)); + + /** + * Validates if exported and open packages are present + */ + void validatePackages() { + Set nonExistPackages = new TreeSet<>(); + descriptor.exports().stream() + .map(Exports::source) + .filter(pn -> !packages.contains(pn)) + .forEach(nonExistPackages::add); + + descriptor.opens().stream() + .map(Opens::source) + .filter(pn -> !packages.contains(pn)) + .forEach(nonExistPackages::add); + + if (!nonExistPackages.isEmpty()) { + throw new PluginException("Packages that are exported or open in " + + descriptor.name() + " are not present: " + nonExistPackages); + } + } + + /** + * Returns true if the PackagesAttribute should be written + */ + boolean shouldAddPackagesAttribute() { + return descriptor.packages().isEmpty() && packages.size() > 0; + } + + /** + * Returns the bytes for the module-info.class with PackagesAttribute + * if it contains at least one package + */ + byte[] getBytes() throws IOException { + bain.reset(); + + // add Packages attribute if not exist + if (shouldAddPackagesAttribute()) { + return new ModuleInfoRewriter(bain, packages).getBytes(); + } else { + return bain.readAllBytes(); + } + } + + class ModuleInfoRewriter extends ByteArrayOutputStream { + final ModuleInfoExtender extender; + ModuleInfoRewriter(InputStream in, Set packages) throws IOException { + this.extender = ModuleInfoExtender.newExtender(in); + // Add Packages attribute + if (packages.size() > 0) { + this.extender.packages(packages); + } + this.extender.write(this); + } + + byte[] getBytes() { + return buf; + } } } @@ -239,30 +296,31 @@ public final class SystemModuleDescriptorPlugin implements Plugin { "java/lang/module/ModuleDescriptor$Exports$Modifier"; private static final String OPENS_MODIFIER_CLASSNAME = "java/lang/module/ModuleDescriptor$Opens$Modifier"; + private static final String MODULE_HASHES_ARRAY_SIGNATURE = + "[Ljdk/internal/module/ModuleHashes;"; + private static final String MODULE_RESOLUTION_CLASSNAME = + "jdk/internal/module/ModuleResolution"; + private static final String MODULE_RESOLUTIONS_ARRAY_SIGNATURE = + "[Ljdk/internal/module/ModuleResolution;"; // static variables in SystemModules class private static final String MODULE_NAMES = "MODULE_NAMES"; - private static final String MODULES_TO_HASH = "MODULES_TO_HASH"; private static final String PACKAGE_COUNT = "PACKAGES_IN_BOOT_LAYER"; private static final int MAX_LOCAL_VARS = 256; private final int BUILDER_VAR = 0; private final int MD_VAR = 1; // variable for ModuleDescriptor + private final int MH_VAR = 1; // variable for ModuleHashes private int nextLocalVar = 2; // index to next local variable private final ClassWriter cw; + + // Method visitor for generating the SystemModules::modules() method private MethodVisitor mv; - private int nextModulesIndex = 0; // list of all ModuleDescriptorBuilders, invoked in turn when building. - private final List builders = new ArrayList<>(); - - // module name to hash - private final Map modulesToHash = new HashMap<>(); - - // module name to index in MODULES_TO_HASH - private final Map modulesToHashIndex = new HashMap<>(); + private final List moduleInfos = new ArrayList<>(); // A builder to create one single Set instance for a given set of // names or modifiers to reduce the footprint @@ -293,66 +351,34 @@ public final class SystemModuleDescriptorPlugin implements Plugin { "[Ljava/lang/String;", null, null) .visitEnd(); - // public static byte[][] MODULES_TO_HASH - cw.visitField(ACC_PUBLIC+ACC_FINAL+ACC_STATIC, MODULES_TO_HASH, - "[[B", null, null) - .visitEnd(); - // public static int PACKAGES_IN_BOOT_LAYER; cw.visitField(ACC_PUBLIC+ACC_FINAL+ACC_STATIC, PACKAGE_COUNT, "I", null, numPackages) .visitEnd(); - this.mv = cw.visitMethod(ACC_STATIC, "", "()V", - null, null); - mv.visitCode(); + MethodVisitor clinit = + cw.visitMethod(ACC_STATIC, "", "()V", + null, null); + clinit.visitCode(); // create the MODULE_NAMES array - pushInt(numModules); - mv.visitTypeInsn(ANEWARRAY, "java/lang/String"); + pushInt(clinit, numModules); + clinit.visitTypeInsn(ANEWARRAY, "java/lang/String"); int index = 0; - for (ModuleDescriptorBuilder builder : builders) { - mv.visitInsn(DUP); // arrayref - pushInt(index++); - mv.visitLdcInsn(builder.md.name()); // value - mv.visitInsn(AASTORE); + for (ModuleInfo minfo : moduleInfos) { + clinit.visitInsn(DUP); // arrayref + pushInt(clinit, index++); + clinit.visitLdcInsn(minfo.moduleName()); // value + clinit.visitInsn(AASTORE); } - mv.visitFieldInsn(PUTSTATIC, CLASSNAME, MODULE_NAMES, + clinit.visitFieldInsn(PUTSTATIC, CLASSNAME, MODULE_NAMES, "[Ljava/lang/String;"); - // create the MODULES_TO_HASH array - pushInt(numModules); - mv.visitTypeInsn(ANEWARRAY, "[B"); - - index = 0; - for (ModuleDescriptorBuilder builder : builders) { - String mn = builder.md.name(); - byte[] recordedHash = modulesToHash.get(mn); - if (recordedHash != null) { - mv.visitInsn(DUP); // arrayref - pushInt(index); - pushInt(recordedHash.length); - mv.visitIntInsn(NEWARRAY, T_BYTE); - for (int i = 0; i < recordedHash.length; i++) { - mv.visitInsn(DUP); // arrayref - pushInt(i); - mv.visitIntInsn(BIPUSH, recordedHash[i]); - mv.visitInsn(BASTORE); - } - mv.visitInsn(AASTORE); - modulesToHashIndex.put(mn, index); - } - index++; - } - - mv.visitFieldInsn(PUTSTATIC, CLASSNAME, MODULES_TO_HASH, "[[B"); - - mv.visitInsn(RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - + clinit.visitInsn(RETURN); + clinit.visitMaxs(0, 0); + clinit.visitEnd(); } /* @@ -360,9 +386,9 @@ public final class SystemModuleDescriptorPlugin implements Plugin { * prepares mapping from various Sets to SetBuilders to emit an * optimized number of sets during build. */ - public void addModule(ModuleDescriptor md, Set packages) { - ModuleDescriptorBuilder builder = new ModuleDescriptorBuilder(md, packages); - builders.add(builder); + public void addModule(ModuleInfo moduleInfo) { + ModuleDescriptor md = moduleInfo.descriptor; + moduleInfos.add(moduleInfo); // exports for (Exports e : md.exports()) { @@ -383,45 +409,129 @@ public final class SystemModuleDescriptorPlugin implements Plugin { // uses dedupSetBuilder.stringSet(md.uses()); - - // hashes - JLMA.hashes(md).ifPresent(mh -> modulesToHash.putAll(mh.hashes())); } /* * Generate bytecode for SystemModules */ public ClassWriter getClassWriter() { - int numModules = builders.size(); + int numModules = moduleInfos.size(); int numPackages = 0; - for (ModuleDescriptorBuilder builder : builders) { - numPackages += builder.md.packages().size(); + for (ModuleInfo minfo : moduleInfos) { + numPackages += minfo.packages.size(); } - this.clinit(numModules, numPackages); - this.mv = cw.visitMethod(ACC_PUBLIC+ACC_STATIC, - "modules", "()" + MODULE_DESCRIPTOR_ARRAY_SIGNATURE, - "()" + MODULE_DESCRIPTOR_ARRAY_SIGNATURE, null); + clinit(numModules, numPackages); + + // generate SystemModules::descriptors + genDescriptorsMethod(); + // generate SystemModules::hashes + genHashesMethod(); + // generate SystemModules::moduleResolutions + genModuleResolutionsMethod(); + + return cw; + } + + /* + * Generate bytecode for SystemModules::descriptors method + */ + private void genDescriptorsMethod() { + this.mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, + "descriptors", + "()" + MODULE_DESCRIPTOR_ARRAY_SIGNATURE, + "()" + MODULE_DESCRIPTOR_ARRAY_SIGNATURE, + null); mv.visitCode(); - pushInt(numModules); + pushInt(mv, moduleInfos.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/module/ModuleDescriptor"); mv.visitVarInsn(ASTORE, MD_VAR); - for (ModuleDescriptorBuilder builder : builders) { - builder.build(); + for (int index = 0; index < moduleInfos.size(); index++) { + ModuleInfo minfo = moduleInfos.get(index); + new ModuleDescriptorBuilder(minfo.descriptor, + minfo.packages, + index).build(); } mv.visitVarInsn(ALOAD, MD_VAR); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); - return cw; + + } + + /* + * Generate bytecode for SystemModules::hashes method + */ + private void genHashesMethod() { + MethodVisitor hmv = + cw.visitMethod(ACC_PUBLIC + ACC_STATIC, + "hashes", + "()" + MODULE_HASHES_ARRAY_SIGNATURE, + "()" + MODULE_HASHES_ARRAY_SIGNATURE, + null); + hmv.visitCode(); + pushInt(hmv, moduleInfos.size()); + hmv.visitTypeInsn(ANEWARRAY, "jdk/internal/module/ModuleHashes"); + hmv.visitVarInsn(ASTORE, MH_VAR); + + for (int index = 0; index < moduleInfos.size(); index++) { + ModuleInfo minfo = moduleInfos.get(index); + if (minfo.recordedHashes != null) { + new ModuleHashesBuilder(minfo.recordedHashes, + index, + hmv).build(); + } + } + + hmv.visitVarInsn(ALOAD, MH_VAR); + hmv.visitInsn(ARETURN); + hmv.visitMaxs(0, 0); + hmv.visitEnd(); + + } + + /* + * Generate bytecode for SystemModules::methodResoultions method + */ + private void genModuleResolutionsMethod() { + MethodVisitor mresmv = + cw.visitMethod(ACC_PUBLIC+ACC_STATIC, + "moduleResolutions", + "()" + MODULE_RESOLUTIONS_ARRAY_SIGNATURE, + "()" + MODULE_RESOLUTIONS_ARRAY_SIGNATURE, + null); + mresmv.visitCode(); + pushInt(mresmv, moduleInfos.size()); + mresmv.visitTypeInsn(ANEWARRAY, MODULE_RESOLUTION_CLASSNAME); + mresmv.visitVarInsn(ASTORE, 0); + + for (int index=0; index < moduleInfos.size(); index++) { + ModuleInfo minfo = moduleInfos.get(index); + if (minfo.moduleResolution != null) { + mresmv.visitVarInsn(ALOAD, 0); + pushInt(mresmv, index); + mresmv.visitTypeInsn(NEW, MODULE_RESOLUTION_CLASSNAME); + mresmv.visitInsn(DUP); + mresmv.visitLdcInsn(minfo.moduleResolution.value()); + mresmv.visitMethodInsn(INVOKESPECIAL, + MODULE_RESOLUTION_CLASSNAME, + "", + "(I)V", false); + mresmv.visitInsn(AASTORE); + } + } + mresmv.visitVarInsn(ALOAD, 0); + mresmv.visitInsn(ARETURN); + mresmv.visitMaxs(0, 0); + mresmv.visitEnd(); } public boolean isOverriddenClass(String path) { return path.equals("/java.base/" + CLASSNAME + ".class"); } - void pushInt(int num) { + void pushInt(MethodVisitor mv, int num) { if (num <= 5) { mv.visitInsn(ICONST_0 + num); } else if (num < Byte.MAX_VALUE) { @@ -460,6 +570,8 @@ public final class SystemModuleDescriptorPlugin implements Plugin { "(Ljava/lang/String;Ljava/util/List;)" + PROVIDES_TYPE; static final String REQUIRES_SET_STRING_SIG = "(Ljava/util/Set;Ljava/lang/String;)" + REQUIRES_TYPE; + static final String REQUIRES_SET_STRING_STRING_SIG = + "(Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;)" + REQUIRES_TYPE; // method signature for Builder instance methods that // return this Builder instance @@ -473,20 +585,18 @@ public final class SystemModuleDescriptorPlugin implements Plugin { "([" + REQUIRES_TYPE + ")" + BUILDER_TYPE; static final String SET_SIG = "(Ljava/util/Set;)" + BUILDER_TYPE; static final String STRING_SIG = "(Ljava/lang/String;)" + BUILDER_TYPE; - static final String STRING_BYTE_ARRAY_SIG = - "(Ljava/lang/String;[B)" + BUILDER_TYPE; static final String BOOLEAN_SIG = "(Z)" + BUILDER_TYPE; - final ModuleDescriptor md; final Set packages; - - ModuleDescriptorBuilder(ModuleDescriptor md, Set packages) { + final int index; + ModuleDescriptorBuilder(ModuleDescriptor md, Set packages, int index) { if (md.isAutomatic()) { throw new InternalError("linking automatic module is not supported"); } this.md = md; this.packages = packages; + this.index = index; } void build() { @@ -517,12 +627,6 @@ public final class SystemModuleDescriptorPlugin implements Plugin { // main class md.mainClass().ifPresent(this::mainClass); - // hashes - JLMA.hashes(md).ifPresent(mh -> { - algorithm(mh.algorithm()); - mh.names().forEach(mn -> moduleHash(mn, mh.hashFor(mn))); - }); - putModuleDescriptor(); } @@ -554,7 +658,7 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitInsn(ICONST_0); } mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - methodName, BOOLEAN_SIG, false); + methodName, BOOLEAN_SIG, false); mv.visitInsn(POP); } @@ -563,12 +667,12 @@ public final class SystemModuleDescriptorPlugin implements Plugin { */ void putModuleDescriptor() { mv.visitVarInsn(ALOAD, MD_VAR); - pushInt(nextModulesIndex++); + pushInt(mv, index); mv.visitVarInsn(ALOAD, BUILDER_VAR); mv.visitLdcInsn(md.hashCode()); mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "build", "(I)Ljava/lang/module/ModuleDescriptor;", - false); + "build", "(I)Ljava/lang/module/ModuleDescriptor;", + false); mv.visitInsn(AASTORE); } @@ -580,31 +684,42 @@ public final class SystemModuleDescriptorPlugin implements Plugin { */ void requires(Set requires) { mv.visitVarInsn(ALOAD, BUILDER_VAR); - pushInt(requires.size()); + pushInt(mv, requires.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/module/ModuleDescriptor$Requires"); int arrayIndex = 0; for (Requires require : requires) { - mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex++); - newRequires(require.modifiers(), require.name()); + String compiledVersion = null; + if (require.compiledVersion().isPresent()) { + compiledVersion = require.compiledVersion().get().toString(); + } + + mv.visitInsn(DUP); // arrayref + pushInt(mv, arrayIndex++); + newRequires(require.modifiers(), require.name(), compiledVersion); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "requires", REQUIRES_ARRAY_SIG, false); + "requires", REQUIRES_ARRAY_SIG, false); } /* - * Invoke Builder.newRequires(Set mods, String mn) + * Invoke Builder.newRequires(Set mods, String mn, String compiledVersion) * * Set mods = ... - * Builder.newRequires(mods, mn); + * Builder.newRequires(mods, mn, compiledVersion); */ - void newRequires(Set mods, String name) { + void newRequires(Set mods, String name, String compiledVersion) { int varIndex = dedupSetBuilder.indexOfRequiresModifiers(mods); mv.visitVarInsn(ALOAD, varIndex); mv.visitLdcInsn(name); - mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, - "newRequires", REQUIRES_SET_STRING_SIG, false); + if (compiledVersion != null) { + mv.visitLdcInsn(compiledVersion); + mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, + "newRequires", REQUIRES_SET_STRING_STRING_SIG, false); + } else { + mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, + "newRequires", REQUIRES_SET_STRING_SIG, false); + } } /* @@ -615,17 +730,17 @@ public final class SystemModuleDescriptorPlugin implements Plugin { */ void exports(Set exports) { mv.visitVarInsn(ALOAD, BUILDER_VAR); - pushInt(exports.size()); + pushInt(mv, exports.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/module/ModuleDescriptor$Exports"); int arrayIndex = 0; for (Exports export : exports) { mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex++); + pushInt(mv, arrayIndex++); newExports(export.modifiers(), export.source(), export.targets()); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "exports", EXPORTS_ARRAY_SIG, false); + "exports", EXPORTS_ARRAY_SIG, false); } /* @@ -664,22 +779,21 @@ public final class SystemModuleDescriptorPlugin implements Plugin { /** * Call Builder::newOpens to create Opens instances and * then pass it to the builder by calling: - * Builder.opens(Opens[]) - * + * Builder.opens(Opens[]) */ void opens(Set opens) { mv.visitVarInsn(ALOAD, BUILDER_VAR); - pushInt(opens.size()); + pushInt(mv, opens.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/module/ModuleDescriptor$Opens"); int arrayIndex = 0; for (Opens open : opens) { mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex++); + pushInt(mv, arrayIndex++); newOpens(open.modifiers(), open.source(), open.targets()); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "opens", OPENS_ARRAY_SIG, false); + "opens", OPENS_ARRAY_SIG, false); } /* @@ -705,12 +819,12 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitLdcInsn(pn); mv.visitVarInsn(ALOAD, stringSetIndex); mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, - "newOpens", OPENS_MODIFIER_SET_STRING_SET_SIG, false); + "newOpens", OPENS_MODIFIER_SET_STRING_SET_SIG, false); } else { mv.visitVarInsn(ALOAD, modifiersSetIndex); mv.visitLdcInsn(pn); mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, - "newOpens", OPENS_MODIFIER_SET_STRING_SIG, false); + "newOpens", OPENS_MODIFIER_SET_STRING_SIG, false); } } @@ -722,7 +836,7 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitVarInsn(ALOAD, BUILDER_VAR); mv.visitVarInsn(ALOAD, varIndex); mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "uses", SET_SIG, false); + "uses", SET_SIG, false); mv.visitInsn(POP); } @@ -734,17 +848,17 @@ public final class SystemModuleDescriptorPlugin implements Plugin { */ void provides(Collection provides) { mv.visitVarInsn(ALOAD, BUILDER_VAR); - pushInt(provides.size()); + pushInt(mv, provides.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/module/ModuleDescriptor$Provides"); int arrayIndex = 0; for (Provides provide : provides) { mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex++); + pushInt(mv, arrayIndex++); newProvides(provide.service(), provide.providers()); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "provides", PROVIDES_ARRAY_SIG, false); + "provides", PROVIDES_ARRAY_SIG, false); } /* @@ -758,19 +872,19 @@ public final class SystemModuleDescriptorPlugin implements Plugin { */ void newProvides(String service, List providers) { mv.visitLdcInsn(service); - pushInt(providers.size()); + pushInt(mv, providers.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/String"); int arrayIndex = 0; for (String provider : providers) { mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex++); + pushInt(mv, arrayIndex++); mv.visitLdcInsn(provider); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKESTATIC, "java/util/List", - "of", "([Ljava/lang/Object;)Ljava/util/List;", true); + "of", "([Ljava/lang/Object;)Ljava/util/List;", true); mv.visitMethodInsn(INVOKESTATIC, MODULE_DESCRIPTOR_BUILDER, - "newProvides", PROVIDES_STRING_LIST_SIG, false); + "newProvides", PROVIDES_STRING_LIST_SIG, false); } /* @@ -781,7 +895,7 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitVarInsn(ALOAD, BUILDER_VAR); mv.visitVarInsn(ALOAD, varIndex); mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "packages", SET_SIG, false); + "packages", SET_SIG, false); mv.visitInsn(POP); } @@ -792,7 +906,7 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitVarInsn(ALOAD, BUILDER_VAR); mv.visitLdcInsn(cn); mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "mainClass", STRING_SIG, false); + "mainClass", STRING_SIG, false); mv.visitInsn(POP); } @@ -803,48 +917,96 @@ public final class SystemModuleDescriptorPlugin implements Plugin { mv.visitVarInsn(ALOAD, BUILDER_VAR); mv.visitLdcInsn(v.toString()); mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "version", STRING_SIG, false); + "version", STRING_SIG, false); mv.visitInsn(POP); } + } + + class ModuleHashesBuilder { + private static final String MODULE_HASHES_BUILDER = + "jdk/internal/module/ModuleHashes$Builder"; + private static final String MODULE_HASHES_BUILDER_TYPE = + "L" + MODULE_HASHES_BUILDER + ";"; + static final String STRING_BYTE_ARRAY_SIG = + "(Ljava/lang/String;[B)" + MODULE_HASHES_BUILDER_TYPE; + + final ModuleHashes recordedHashes; + final MethodVisitor hmv; + final int index; + + ModuleHashesBuilder(ModuleHashes hashes, int index, MethodVisitor hmv) { + this.recordedHashes = hashes; + this.hmv = hmv; + this.index = index; + } + + /** + * Build ModuleHashes + */ + void build() { + if (recordedHashes == null) + return; + + // new jdk.internal.module.ModuleHashes.Builder + newModuleHashesBuilder(); + + // Invoke ModuleHashes.Builder::hashForModule + recordedHashes + .names() + .forEach(mn -> hashForModule(mn, recordedHashes.hashFor(mn))); + + // Put ModuleHashes into the hashes array + pushModuleHashes(); + } + + + /* + * Create ModuleHashes.Builder instance + */ + void newModuleHashesBuilder() { + hmv.visitTypeInsn(NEW, MODULE_HASHES_BUILDER); + hmv.visitInsn(DUP); + hmv.visitLdcInsn(recordedHashes.algorithm()); + hmv.visitMethodInsn(INVOKESPECIAL, MODULE_HASHES_BUILDER, + "", "(Ljava/lang/String;)V", false); + hmv.visitVarInsn(ASTORE, BUILDER_VAR); + hmv.visitVarInsn(ALOAD, BUILDER_VAR); + } + + + /* + * Invoke ModuleHashes.Builder::build and put the returned + * ModuleHashes to the hashes array + */ + void pushModuleHashes() { + hmv.visitVarInsn(ALOAD, MH_VAR); + pushInt(hmv, index); + hmv.visitVarInsn(ALOAD, BUILDER_VAR); + hmv.visitMethodInsn(INVOKEVIRTUAL, MODULE_HASHES_BUILDER, + "build", "()Ljdk/internal/module/ModuleHashes;", + false); + hmv.visitInsn(AASTORE); + } /* - * Invoke Builder.algorithm(String a); + * Invoke ModuleHashes.Builder.hashForModule(String name, byte[] hash); */ - void algorithm(String alg) { - mv.visitVarInsn(ALOAD, BUILDER_VAR); - mv.visitLdcInsn(alg); - mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "algorithm", STRING_SIG, false); - mv.visitInsn(POP); - } + void hashForModule(String name, byte[] hash) { + hmv.visitVarInsn(ALOAD, BUILDER_VAR); + hmv.visitLdcInsn(name); - /* - * Invoke Builder.moduleHash(String name, byte[] hash); - */ - void moduleHash(String name, byte[] hash) { - mv.visitVarInsn(ALOAD, BUILDER_VAR); - mv.visitLdcInsn(name); - - // must exist - Integer index = modulesToHashIndex.get(name); - if (index != null) { - mv.visitFieldInsn(GETSTATIC, CLASSNAME, MODULES_TO_HASH, "[[B"); - pushInt(index); - mv.visitInsn(AALOAD); - assert(Objects.equals(hash, modulesToHash.get(name))); - } else { - pushInt(hash.length); - mv.visitIntInsn(NEWARRAY, T_BYTE); - for (int i = 0; i < hash.length; i++) { - mv.visitInsn(DUP); // arrayref - pushInt(i); - mv.visitIntInsn(BIPUSH, hash[i]); - mv.visitInsn(BASTORE); - } + pushInt(hmv, hash.length); + hmv.visitIntInsn(NEWARRAY, T_BYTE); + for (int i = 0; i < hash.length; i++) { + hmv.visitInsn(DUP); // arrayref + pushInt(hmv, i); + hmv.visitIntInsn(BIPUSH, hash[i]); + hmv.visitInsn(BASTORE); } - mv.visitMethodInsn(INVOKEVIRTUAL, MODULE_DESCRIPTOR_BUILDER, - "moduleHash", STRING_BYTE_ARRAY_SIG, false); - mv.visitInsn(POP); + + hmv.visitMethodInsn(INVOKEVIRTUAL, MODULE_HASHES_BUILDER, + "hashForModule", STRING_BYTE_ARRAY_SIG, false); + hmv.visitInsn(POP); } } @@ -1039,12 +1201,12 @@ public final class SystemModuleDescriptorPlugin implements Plugin { "of", sb.toString(), true); } else { // call Set.of(E... elements) - pushInt(elements.size()); + pushInt(mv, elements.size()); mv.visitTypeInsn(ANEWARRAY, "java/lang/String"); int arrayIndex = 0; for (T t : elements) { mv.visitInsn(DUP); // arrayref - pushInt(arrayIndex); + pushInt(mv, arrayIndex); visitElement(t, mv); // value mv.visitInsn(AASTORE); arrayIndex++; diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java index 40dad9f52fe..418edd91fa3 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java @@ -67,6 +67,7 @@ import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -100,10 +101,11 @@ import jdk.internal.joptsimple.OptionSet; import jdk.internal.joptsimple.OptionSpec; import jdk.internal.joptsimple.ValueConverter; import jdk.internal.loader.ResourceHelper; -import jdk.internal.misc.JavaLangModuleAccess; -import jdk.internal.misc.SharedSecrets; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleInfo; import jdk.internal.module.ModuleInfoExtender; +import jdk.internal.module.ModulePath; +import jdk.internal.module.ModuleResolution; import jdk.tools.jlink.internal.Utils; import static java.util.stream.Collectors.joining; @@ -165,6 +167,7 @@ public class JmodTask { Mode mode; Path jmodFile; boolean help; + boolean helpExtra; boolean version; List classpath; List cmds; @@ -179,6 +182,7 @@ public class JmodTask { String osArch; String osVersion; Pattern modulesToHash; + ModuleResolution moduleResolution; boolean dryrun; List excludes; Path extractDir; @@ -192,7 +196,7 @@ public class JmodTask { showUsageSummary(); return EXIT_CMDERR; } - if (options.help) { + if (options.help || options.helpExtra) { showHelp(); return EXIT_OK; } @@ -288,8 +292,8 @@ public class JmodTask { private boolean describe() throws IOException { try (JmodFile jf = new JmodFile(options.jmodFile)) { try (InputStream in = jf.getInputStream(Section.CLASSES, MODULE_INFO)) { - ModuleDescriptor md = ModuleDescriptor.read(in); - printModuleDescriptor(md); + ModuleInfo.Attributes attrs = ModuleInfo.read(in, null); + printModuleDescriptor(attrs.descriptor(), attrs.recordedHashes()); return true; } catch (IOException e) { throw new CommandException("err.module.descriptor.not.found"); @@ -303,9 +307,7 @@ public class JmodTask { .collect(joining(" ")); } - private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess(); - - private void printModuleDescriptor(ModuleDescriptor md) + private void printModuleDescriptor(ModuleDescriptor md, ModuleHashes hashes) throws IOException { StringBuilder sb = new StringBuilder(); @@ -351,15 +353,24 @@ public class JmodTask { md.osVersion().ifPresent(v -> sb.append("\n operating-system-version " + v)); - JLMA.hashes(md).ifPresent( - hashes -> hashes.names().stream().sorted().forEach( - mod -> sb.append("\n hashes ").append(mod).append(" ") - .append(hashes.algorithm()).append(" ") - .append(hashes.hashFor(mod)))); + if (hashes != null) { + hashes.names().stream().sorted().forEach( + mod -> sb.append("\n hashes ").append(mod).append(" ") + .append(hashes.algorithm()).append(" ") + .append(toHex(hashes.hashFor(mod)))); + } out.println(sb.toString()); } + private String toHex(byte[] ba) { + StringBuilder sb = new StringBuilder(ba.length); + for (byte b: ba) { + sb.append(String.format("%02x", b & 0xff)); + } + return sb.toString(); + } + private boolean create() throws IOException { JmodFileWriter jmod = new JmodFileWriter(); @@ -400,6 +411,7 @@ public class JmodTask { final String osVersion = options.osVersion; final List excludes = options.excludes; final Hasher hasher = hasher(); + final ModuleResolution moduleResolution = options.moduleResolution; JmodFileWriter() { } @@ -508,6 +520,10 @@ public class JmodTask { } } + if (moduleResolution != null && moduleResolution.value() != 0) { + extender.moduleResolution(moduleResolution); + } + // write the (possibly extended or modified) module-info.class out.writeEntry(extender.toByteArray(), Section.CLASSES, MODULE_INFO); } @@ -536,12 +552,12 @@ public class JmodTask { } URI uri = options.jmodFile.toUri(); - ModuleReference mref = new ModuleReference(descriptor, uri, new Supplier<>() { + ModuleReference mref = new ModuleReference(descriptor, uri) { @Override - public ModuleReader get() { + public ModuleReader open() { throw new UnsupportedOperationException(); } - }); + }; // compose a module finder with the module path and also // a module finder that can find the jmod file being created @@ -1136,6 +1152,28 @@ public class JmodTask { @Override public String valuePattern() { return "module-version"; } } + static class WarnIfResolvedReasonConverter + implements ValueConverter + { + @Override + public ModuleResolution convert(String value) { + if (value.equals("deprecated")) + return ModuleResolution.empty().withDeprecated(); + else if (value.equals("deprecated-for-removal")) + return ModuleResolution.empty().withDeprecatedForRemoval(); + else if (value.equals("incubating")) + return ModuleResolution.empty().withIncubating(); + else + throw new CommandException("err.bad.WarnIfResolvedReason", value); + } + + @Override public Class valueType() { + return ModuleResolution.class; + } + + @Override public String valuePattern() { return "reason"; } + } + static class PatternConverter implements ValueConverter { @Override public Pattern convert(String value) { @@ -1179,12 +1217,24 @@ public class JmodTask { */ private static final class JmodHelpFormatter extends BuiltinHelpFormatter { - private JmodHelpFormatter() { super(80, 2); } + private final Options opts; + + private JmodHelpFormatter(Options opts) { + super(80, 2); + this.opts = opts; + } @Override public String format(Map options) { - Map all = new HashMap<>(); + Map all = new LinkedHashMap<>(); all.putAll(options); + + // extra options + if (!opts.helpExtra) { + all.remove("do-not-resolve-by-default"); + all.remove("warn-if-resolved"); + } + all.put(CMD_FILENAME, new OptionDescriptor() { @Override public Collection options() { @@ -1240,7 +1290,8 @@ public class JmodTask { private final OptionParser parser = new OptionParser("hp"); private void handleOptions(String[] args) { - parser.formatHelpWith(new JmodHelpFormatter()); + options = new Options(); + parser.formatHelpWith(new JmodHelpFormatter(options)); OptionSpec classPath = parser.accepts("class-path", getMessage("main.opt.class-path")) @@ -1282,6 +1333,9 @@ public class JmodTask { = parser.acceptsAll(Set.of("h", "help"), getMessage("main.opt.help")) .forHelp(); + OptionSpec helpExtra + = parser.accepts("help-extra", getMessage("main.opt.help-extra")); + OptionSpec headerFiles = parser.accepts("header-files", getMessage("main.opt.header-files")) .withRequiredArg() @@ -1332,6 +1386,15 @@ public class JmodTask { .withRequiredArg() .describedAs(getMessage("main.opt.os-version.arg")); + OptionSpec doNotResolveByDefault + = parser.accepts("do-not-resolve-by-default", + getMessage("main.opt.do-not-resolve-by-default")); + + OptionSpec warnIfResolved + = parser.accepts("warn-if-resolved", getMessage("main.opt.warn-if-resolved")) + .withRequiredArg() + .withValuesConvertedBy(new WarnIfResolvedReasonConverter()); + OptionSpec version = parser.accepts("version", getMessage("main.opt.version")); @@ -1341,9 +1404,9 @@ public class JmodTask { try { OptionSet opts = parser.parse(args); - if (opts.has(help) || opts.has(version)) { - options = new Options(); + if (opts.has(help) || opts.has(helpExtra) || opts.has(version)) { options.help = opts.has(help); + options.helpExtra = opts.has(helpExtra); options.version = opts.has(version); return; // informational message will be shown } @@ -1352,7 +1415,6 @@ public class JmodTask { if (words.isEmpty()) throw new CommandException("err.missing.mode").showUsage(true); String verb = words.get(0); - options = new Options(); try { options.mode = Enum.valueOf(Mode.class, verb.toUpperCase()); } catch (IllegalArgumentException e) { @@ -1379,7 +1441,7 @@ public class JmodTask { options.manPages = opts.valuesOf(manPages); if (opts.has(modulePath)) { Path[] dirs = opts.valuesOf(modulePath).toArray(new Path[0]); - options.moduleFinder = JLMA.newModulePath(Runtime.version(), true, dirs); + options.moduleFinder = new ModulePath(Runtime.version(), true, dirs); } if (opts.has(moduleVersion)) options.moduleVersion = opts.valueOf(moduleVersion); @@ -1391,6 +1453,13 @@ public class JmodTask { options.osArch = opts.valueOf(osArch); if (opts.has(osVersion)) options.osVersion = opts.valueOf(osVersion); + if (opts.has(warnIfResolved)) + options.moduleResolution = opts.valueOf(warnIfResolved); + if (opts.has(doNotResolveByDefault)) { + if (options.moduleResolution == null) + options.moduleResolution = ModuleResolution.empty(); + options.moduleResolution = options.moduleResolution.withDoNotResolveByDefault(); + } if (opts.has(hashModules)) { options.modulesToHash = opts.valueOf(hashModules); // if storing hashes then the module path is required diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties index bdf56359773..bc5c4b0300d 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties @@ -47,6 +47,7 @@ main.opt.mode.hash=\ \hash - Records hashes of tied modules. main.opt.help=Print this usage message +main.opt.help-extra=Print help on extra options main.opt.version=Version information main.opt.class-path=Application jar files|dir containing classes main.opt.libs=Location of native libraries @@ -73,6 +74,9 @@ main.opt.hash-modules=Compute and record hashes to tie a packaged module\ \ with modules matching the given and depending upon it directly\ \ or indirectly. The hashes are recorded in the JMOD file being created, or\ \ a JMOD file or modular JAR on the module path specified the jmod hash command. +main.opt.do-not-resolve-by-default=Exclude from the default root set of modules +main.opt.warn-if-resolved=Hint for a tool to issue a warning if the module \ +is resolved. One of deprecated, deprecated-for-removal, or incubating main.opt.cmdfile=Read options from the specified file @@ -95,6 +99,8 @@ err.invalid.class.path.entry=invalid class path entry: {0} err.file.already.exists=file already exists: {0} err.jmod.not.found=no jmod file found: {0} err.bad.pattern=bad pattern {0} +err.bad.WarnIfResolvedReason=bad reason: {0}, must be one of deprecated,\ +\ deprecated-for-removal, or incubating err.unknown.option=unknown option(s): {0} err.missing.arg=no value given for {0} err.internal.error=internal error: {0} {1} {2} diff --git a/jdk/src/jdk.jlink/share/classes/module-info.java b/jdk/src/jdk.jlink/share/classes/module-info.java index e20c763b256..b0fd61362e1 100644 --- a/jdk/src/jdk.jlink/share/classes/module-info.java +++ b/jdk/src/jdk.jlink/share/classes/module-info.java @@ -41,7 +41,7 @@ module jdk.jlink { jdk.tools.jlink.internal.plugins.ExcludePlugin, jdk.tools.jlink.internal.plugins.ExcludeFilesPlugin, jdk.tools.jlink.internal.plugins.ExcludeJmodSectionPlugin, - jdk.tools.jlink.internal.plugins.SystemModuleDescriptorPlugin, + jdk.tools.jlink.internal.plugins.SystemModulesPlugin, jdk.tools.jlink.internal.plugins.StripNativeCommandsPlugin, jdk.tools.jlink.internal.plugins.OrderResourcesPlugin, jdk.tools.jlink.internal.plugins.DefaultCompressPlugin, diff --git a/jdk/src/jdk.pack200/share/classes/module-info.java b/jdk/src/jdk.pack200/share/classes/module-info.java index ffca94f972a..da9f12655da 100644 --- a/jdk/src/jdk.pack200/share/classes/module-info.java +++ b/jdk/src/jdk.pack200/share/classes/module-info.java @@ -23,6 +23,7 @@ * questions. */ +@SuppressWarnings("module") module jdk.pack200 { } diff --git a/jdk/test/java/lang/invoke/DropLookupModeTest.java b/jdk/test/java/lang/invoke/DropLookupModeTest.java new file mode 100644 index 00000000000..be7d0a60e54 --- /dev/null +++ b/jdk/test/java/lang/invoke/DropLookupModeTest.java @@ -0,0 +1,152 @@ +/* + * 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 + * @run testng DropLookupModeTest + * @summary Basic unit tests Lookup::dropLookupMode + */ + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; +import static java.lang.invoke.MethodHandles.Lookup.*; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +@Test +public class DropLookupModeTest { + + /** + * Basic test of dropLookupMode + */ + public void testBasic() { + final Lookup fullPowerLookup = MethodHandles.lookup(); + final Class lc = fullPowerLookup.lookupClass(); + assertTrue(fullPowerLookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PROTECTED|PRIVATE)); + + Lookup lookup = fullPowerLookup.dropLookupMode(PRIVATE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE)); + + lookup = fullPowerLookup.dropLookupMode(PROTECTED); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PRIVATE)); + + lookup = fullPowerLookup.dropLookupMode(PACKAGE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE)); + + lookup = fullPowerLookup.dropLookupMode(MODULE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC)); + + lookup = fullPowerLookup.dropLookupMode(PUBLIC); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == 0); + } + + /** + * Starting with a full power Lookup, use dropLookupMode to create new Lookups + * with reduced access. + */ + public void testReducingAccess() { + Lookup lookup = MethodHandles.lookup(); + final Class lc = lookup.lookupClass(); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PROTECTED|PRIVATE)); + + lookup = lookup.dropLookupMode(PROTECTED); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PRIVATE)); + + lookup = lookup.dropLookupMode(PRIVATE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE)); + + lookup = lookup.dropLookupMode(PACKAGE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == (PUBLIC|MODULE)); + + lookup = lookup.dropLookupMode(MODULE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == PUBLIC); + + lookup = lookup.dropLookupMode(PUBLIC); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == 0); + + // repeat with lookup has no access + lookup = lookup.dropLookupMode(PUBLIC); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == 0); + } + + /** + * Test dropLookupMode on the public Lookup. + */ + public void testPublicLookup() { + final Lookup publicLookup = MethodHandles.publicLookup(); + final Class lc = publicLookup.lookupClass(); + assertTrue(publicLookup.lookupModes() == PUBLIC); + + Lookup lookup = publicLookup.dropLookupMode(PRIVATE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == PUBLIC); + + lookup = publicLookup.dropLookupMode(PROTECTED); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == PUBLIC); + + lookup = publicLookup.dropLookupMode(PACKAGE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == PUBLIC); + + lookup = publicLookup.dropLookupMode(MODULE); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == PUBLIC); + + lookup = publicLookup.dropLookupMode(PUBLIC); + assertTrue(lookup.lookupClass() == lc); + assertTrue(lookup.lookupModes() == 0); + } + + @DataProvider(name = "badInput") + public Object[][] badInput() { + return new Object[][] { + { 0, null }, + { (PACKAGE|PRIVATE), null }, // two modes + { Integer.MAX_VALUE, null }, + { Integer.MIN_VALUE, null }, + }; + } + + /** + * Check that IllegalArgumentException is thrown for bad input + */ + @Test(dataProvider = "badInput", expectedExceptions = {IllegalArgumentException.class}) + public void testBadInput(Integer modeToDrop, Object ignore) { + MethodHandles.lookup().dropLookupMode(modeToDrop); + } + +} \ No newline at end of file diff --git a/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java b/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java index 87dfbd7f06e..823ae8797b5 100644 --- a/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java +++ b/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java @@ -84,8 +84,7 @@ public class PrivateLookupInTests { // Invoke MethodHandles.privateLookupIn with a reduced-power caller public void testReducedAccessCallerSameModule() throws Throwable { - // drop access - Lookup caller = MethodHandles.lookup().in(publicType); + Lookup caller = MethodHandles.lookup().dropLookupMode(PACKAGE); assertTrue((caller.lookupModes() & PRIVATE) == 0); assertTrue((caller.lookupModes() & PACKAGE) == 0); assertTrue((caller.lookupModes() & MODULE) != 0); diff --git a/jdk/test/java/lang/module/ModuleDescriptorTest.java b/jdk/test/java/lang/module/ModuleDescriptorTest.java index efaa498d558..276ecf71048 100644 --- a/jdk/test/java/lang/module/ModuleDescriptorTest.java +++ b/jdk/test/java/lang/module/ModuleDescriptorTest.java @@ -23,8 +23,7 @@ /** * @test - * @modules java.base/java.lang.module:open - * java.base/jdk.internal.module + * @modules java.base/jdk.internal.module * @run testng ModuleDescriptorTest * @summary Basic test for java.lang.module.ModuleDescriptor and its builder */ @@ -41,16 +40,13 @@ import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Provides; import java.lang.module.ModuleDescriptor.Requires.Modifier; import java.lang.module.ModuleDescriptor.Version; -import java.lang.reflect.Constructor; import java.lang.reflect.Module; import java.nio.ByteBuffer; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; import static java.lang.module.ModuleDescriptor.Requires.Modifier.*; @@ -66,10 +62,20 @@ public class ModuleDescriptorTest { public Object[][] invalidJavaIdentifiers() { return new Object[][]{ - { null, null }, - { ".foo", null }, - { "foo.", null }, - { "[foo]", null }, + { null, null }, + { "1", null }, + { "1foo", null }, + { ".foo", null }, + { "foo.", null }, + { "[foo]", null }, + { "foo.1", null }, + { "1foo.bar", null }, + { "foo.1bar", null }, + { "foo.[bar]", null }, + { "foo..bar", null }, + { "foo.bar.1", null }, + { "foo.bar.1gus", null }, + { "foo.bar.[gus]", null }, }; } @@ -86,6 +92,15 @@ public class ModuleDescriptorTest { .next(); } + private Requires requires(Set mods, String mn, Version v) { + return ModuleDescriptor.module("m") + .requires(mods, mn, v) + .build() + .requires() + .iterator() + .next(); + } + private Requires requires(String mn) { return requires(Collections.emptySet(), mn); } @@ -103,6 +118,7 @@ public class ModuleDescriptorTest { assertTrue(r.compareTo(r) == 0); assertTrue(r.modifiers().isEmpty()); assertEquals(r.name(), "foo"); + assertFalse(r.compiledVersion().isPresent()); } public void testRequiresWithOneModifier() { @@ -111,6 +127,7 @@ public class ModuleDescriptorTest { assertTrue(r.compareTo(r) == 0); assertEquals(r.modifiers(), EnumSet.of(TRANSITIVE)); assertEquals(r.name(), "foo"); + assertFalse(r.compiledVersion().isPresent()); } public void testRequiresWithTwoModifiers() { @@ -119,6 +136,7 @@ public class ModuleDescriptorTest { assertTrue(r.compareTo(r) == 0); assertEquals(r.modifiers(), EnumSet.of(TRANSITIVE, SYNTHETIC)); assertEquals(r.name(), "foo"); + assertFalse(r.compiledVersion().isPresent()); } public void testRequiresWithAllModifiers() { @@ -127,6 +145,18 @@ public class ModuleDescriptorTest { assertTrue(r.compareTo(r) == 0); assertEquals(r.modifiers(), EnumSet.of(TRANSITIVE, STATIC, SYNTHETIC, MANDATED)); assertEquals(r.name(), "foo"); + assertFalse(r.compiledVersion().isPresent()); + } + + public void testRequiresWithCompiledVersion() { + Version v = Version.parse("1.0"); + Requires r = requires(Set.of(), "foo", v); + assertEquals(r, r); + assertTrue(r.compareTo(r) == 0); + assertEquals(r.modifiers(), Set.of()); + assertEquals(r.name(), "foo"); + assertTrue(r.compiledVersion().isPresent()); + assertEquals(r.compiledVersion().get().toString(), "1.0"); } @Test(expectedExceptions = IllegalStateException.class) @@ -167,6 +197,16 @@ public class ModuleDescriptorTest { ModuleDescriptor.module("m").requires((Requires) null); } + @Test(expectedExceptions = NullPointerException.class) + public void testRequiresWithNullModifiers() { + ModuleDescriptor.module("m").requires(null, "foo"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testRequiresWithNullVersion() { + ModuleDescriptor.module("m").requires(Set.of(), "foo", null); + } + public void testRequiresCompare() { Requires r1 = requires(EnumSet.noneOf(Modifier.class), "foo"); Requires r2 = requires(EnumSet.noneOf(Modifier.class), "bar"); @@ -190,6 +230,20 @@ public class ModuleDescriptorTest { assertTrue(r2.compareTo(r1) == 0); } + public void testRequiresCompareWithSameCompiledVersion() { + Requires r1 = requires(Set.of(), "foo", Version.parse("2.0")); + Requires r2 = requires(Set.of(), "foo", Version.parse("2.0")); + assertTrue(r1.compareTo(r2) == 0); + assertTrue(r2.compareTo(r1) == 0); + } + + public void testRequiresCompareWithDifferentCompiledVersion() { + Requires r1 = requires(Set.of(), "foo", Version.parse("1.0")); + Requires r2 = requires(Set.of(), "foo", Version.parse("2.0")); + assertTrue(r1.compareTo(r2) < 0); + assertTrue(r2.compareTo(r1) > 0); + } + public void testRequiresEqualsAndHashCode() { Requires r1 = requires("foo"); Requires r2 = requires("foo"); @@ -208,6 +262,17 @@ public class ModuleDescriptorTest { r1 = requires(EnumSet.allOf(Requires.Modifier.class), "foo"); r2 = requires(Set.of(), "foo"); assertNotEquals(r1, r2); + + Version v1 = Version.parse("1.0"); + r1 = requires(EnumSet.allOf(Requires.Modifier.class), "foo", v1); + r2 = requires(EnumSet.allOf(Requires.Modifier.class), "foo", v1); + assertEquals(r1, r2); + assertTrue(r1.hashCode() == r2.hashCode()); + + Version v2 = Version.parse("2.0"); + r1 = requires(EnumSet.allOf(Requires.Modifier.class), "foo", v1); + r2 = requires(EnumSet.allOf(Requires.Modifier.class), "foo", v2); + assertNotEquals(r1, r2); } public void testRequiresToString() { @@ -938,7 +1003,7 @@ public class ModuleDescriptorTest { }; // basic test reading module-info.class - public void testRead1() throws Exception { + public void testRead() throws Exception { Module base = Object.class.getModule(); try (InputStream in = base.getResourceAsStream("module-info.class")) { @@ -954,45 +1019,6 @@ public class ModuleDescriptorTest { assertEquals(descriptor.name(), "java.base"); } } - - /** - * Test reading a module-info.class that has a module name, requires, - * and qualified exports with module names that are not supported in the - * Java Language. - */ - public void testRead2() throws Exception { - // use non-public constructor to create a Builder that is not strict - Constructor ctor = Builder.class.getDeclaredConstructor(String.class, boolean.class); - ctor.setAccessible(true); - - Builder builder = (ModuleDescriptor.Builder) ctor.newInstance("m?1", false); - ModuleDescriptor descriptor = builder - .requires("java.base") - .requires("-m1") - .exports("p", Set.of("m2-")) - .build(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ModuleInfoWriter.write(descriptor, baos); - ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray()); - - descriptor = ModuleDescriptor.read(bb); - assertEquals(descriptor.name(), "m?1"); - - Set requires = descriptor.requires() - .stream() - .map(Requires::name) - .collect(Collectors.toSet()); - assertTrue(requires.size() == 2); - assertTrue(requires.contains("java.base")); - assertTrue(requires.contains("-m1")); - - assertTrue(descriptor.exports().size() == 1); - Exports e = descriptor.exports().iterator().next(); - assertTrue(e.targets().size() == 1); - assertTrue(e.targets().contains("m2-")); - } - /** * Test ModuleDescriptor with a packager finder */ diff --git a/jdk/test/java/lang/module/ModuleNamesTest.java b/jdk/test/java/lang/module/ModuleNamesTest.java new file mode 100644 index 00000000000..c0790eab202 --- /dev/null +++ b/jdk/test/java/lang/module/ModuleNamesTest.java @@ -0,0 +1,261 @@ +/* + * 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 + * @modules java.base/jdk.internal.misc + * java.base/jdk.internal.module + * @run testng ModuleNamesTest + * @summary Basic test of reading a module-info.class with module names that + * are legal in class files but not legal in the Java Language + */ + +import java.io.ByteArrayOutputStream; +import java.lang.module.InvalidModuleDescriptorException; +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleDescriptor.Builder; +import java.lang.module.ModuleDescriptor.Exports; +import java.lang.module.ModuleDescriptor.Opens; +import java.lang.module.ModuleDescriptor.Requires; +import java.nio.ByteBuffer; +import java.util.Optional; +import java.util.Set; + +import jdk.internal.misc.SharedSecrets; +import jdk.internal.module.ModuleInfoWriter; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +@Test +public class ModuleNamesTest { + + @DataProvider(name = "legalModuleNames") + public Object[][] legalModuleNames() { + return new Object[][] { + + { ".", "." }, + { ".foo", ".foo" }, + { "foo.", "foo." }, + { "foo.bar", "foo.bar" }, + + { "..", ".." }, + { "..foo", "..foo" }, + { "foo..", "foo.." }, + { "foo..bar", "foo..bar" }, + + { "[", "[" }, + { "[foo", "[foo" }, + { "foo[", "foo[" }, + { "foo[bar", "foo[bar" }, + + { ";", ";" }, + { ";foo", ";foo" }, + { "foo;", "foo;" }, + { "foo;bar", "foo;bar" }, + + { "\\\\", "\\" }, + { "\\\\foo", "\\foo" }, + { "foo\\\\", "foo\\" }, + { "foo\\\\bar", "foo\\bar" }, + + { "\\\\\\\\", "\\\\" }, + { "\\\\\\\\foo", "\\\\foo" }, + { "foo\\\\\\\\", "foo\\\\" }, + { "foo\\\\\\\\bar", "foo\\\\bar" }, + + { "\\:", ":" }, + { "\\:foo", ":foo" }, + { "foo\\:", "foo:" }, + { "foo\\:bar", "foo:bar" }, + + { "\\:\\:", "::" }, + { "\\:\\:foo", "::foo" }, + { "foo\\:\\:", "foo::" }, + { "foo\\:\\:bar", "foo::bar" }, + + { "\\@", "@" }, + { "\\@foo", "@foo" }, + { "foo\\@", "foo@" }, + { "foo\\@bar", "foo@bar" }, + + { "\\@\\@", "@@" }, + { "\\@\\@foo", "@@foo" }, + { "foo\\@\\@", "foo@@" }, + { "foo\\@\\@bar", "foo@@bar" }, + + { makeString("", 0x20, ""), " " }, + { makeString("foo", 0x20, ""), "foo " }, + { makeString("", 0x20, "foo"), " foo" }, + { makeString("foo", 0x20, "bar"), "foo bar" }, + }; + } + + @DataProvider(name = "illegalModuleNames") + public Object[][] illegalModuleNames() { + return new Object[][] { + + { "", null }, + + { ":", null }, + { ":foo", null }, + { "foo:", null }, + { "foo:bar", null }, + + { "@", null }, + { "@foo", null }, + { "foo@", null }, + { "foo@bar", null }, + + { "\\", null }, + { "\\foo", null }, + { "foo\\", null }, + { "foo\\bar", null }, + + { makeString("", 0x00, ""), null }, + { makeString("", 0x00, "foo"), null }, + { makeString("foo", 0x00, ""), null }, + { makeString("foo", 0x00, "bar"), null }, + + { makeString("", 0x1f, ""), null }, + { makeString("", 0x1f, "foo"), null }, + { makeString("foo", 0x1f, ""), null }, + { makeString("foo", 0x1f, "bar"), null }, + + }; + } + + @Test(dataProvider = "legalModuleNames") + public void testLegalModuleName(String mn, String expected) throws Exception { + ModuleDescriptor md = newBuilder(mn).requires("java.base").build(); + ByteBuffer bb = toBuffer(md); + String name = ModuleDescriptor.read(bb).name(); + assertEquals(name, expected); + } + + @Test(dataProvider = "illegalModuleNames", + expectedExceptions = InvalidModuleDescriptorException.class) + public void testIllegalModuleName(String mn, String ignore) throws Exception { + ModuleDescriptor md = newBuilder(mn).requires("java.base").build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException + } + + @Test(dataProvider = "legalModuleNames") + public void testLegalRequires(String mn, String expected) throws Exception { + ModuleDescriptor md = newBuilder("m").requires("java.base").requires(mn).build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor descriptor = ModuleDescriptor.read(bb); + Optional requires = descriptor.requires().stream() + .filter(r -> !r.name().equals("java.base")) + .findAny(); + assertTrue(requires.isPresent()); + assertEquals(requires.get().name(), expected); + } + + @Test(dataProvider = "illegalModuleNames", + expectedExceptions = InvalidModuleDescriptorException.class) + public void testIllegalRequires(String mn, String ignore) throws Exception { + ModuleDescriptor md = newBuilder("m").requires("java.base").requires(mn).build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException + } + + @Test(dataProvider = "legalModuleNames") + public void testLegalExports(String mn, String expected) throws Exception { + ModuleDescriptor md = newBuilder("m") + .requires("java.base") + .exports("p", Set.of(mn)) + .build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor descriptor = ModuleDescriptor.read(bb); + Optional export = descriptor.exports().stream().findAny(); + assertTrue(export.isPresent()); + assertTrue(export.get().targets().contains(expected)); + } + + @Test(dataProvider = "illegalModuleNames", + expectedExceptions = InvalidModuleDescriptorException.class) + public void testIllegalExports(String mn, String ignore) throws Exception { + ModuleDescriptor md = newBuilder("m") + .requires("java.base") + .exports("p", Set.of(mn)) + .build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException + } + + @Test(dataProvider = "legalModuleNames") + public void testLegalOpens(String mn, String expected) throws Exception { + ModuleDescriptor md = newBuilder("m") + .requires("java.base") + .opens("p", Set.of(mn)) + .build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor descriptor = ModuleDescriptor.read(bb); + Optional opens = descriptor.opens().stream().findAny(); + assertTrue(opens.isPresent()); + assertTrue(opens.get().targets().contains(expected)); + } + + @Test(dataProvider = "illegalModuleNames", + expectedExceptions = InvalidModuleDescriptorException.class) + public void testIllegalOpens(String mn, String ignore) throws Exception { + ModuleDescriptor md = newBuilder("m") + .requires("java.base") + .opens("p", Set.of(mn)) + .build(); + ByteBuffer bb = toBuffer(md); + ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException + } + + /** + * Returns a Builder that does not validate module names. + */ + private Builder newBuilder(String mn) { + return SharedSecrets.getJavaLangModuleAccess() + .newModuleBuilder(mn, false, false, false); + } + + /** + * Returns a {@code ByteBuffer} containing the given module descriptor + * in module-info.class format. + */ + private ByteBuffer toBuffer(ModuleDescriptor descriptor) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ModuleInfoWriter.write(descriptor, baos); + return ByteBuffer.wrap(baos.toByteArray()); + } + + /** + * Returns a string containing a given code point. + */ + private String makeString(String prefix, int codePoint, String suffix) { + StringBuilder sb = new StringBuilder(); + sb.append(prefix); + sb.appendCodePoint(codePoint); + sb.append(suffix); + return sb.toString(); + } +} diff --git a/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java b/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java index 63c4c7404e0..d956c249651 100644 --- a/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java +++ b/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java @@ -24,7 +24,7 @@ /** * @test * @library /lib/testlibrary - * @modules java.base/jdk.internal.misc + * @modules java.base/jdk.internal.module * jdk.compiler * @build ModuleReaderTest CompilerUtils JarUtils * @run testng ModuleReaderTest @@ -53,7 +53,7 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.spi.ToolProvider; -import jdk.internal.misc.SharedSecrets; +import jdk.internal.module.ModulePath; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -216,9 +216,7 @@ public class ModuleReaderTest { */ void test(Path mp) throws IOException { - ModuleFinder finder = SharedSecrets.getJavaLangModuleAccess() - .newModulePath(Runtime.version(), true, mp); - + ModuleFinder finder = new ModulePath(Runtime.version(), true, mp); ModuleReference mref = finder.find(TEST_MODULE).get(); ModuleReader reader = mref.open(); diff --git a/jdk/test/java/lang/module/ModuleReferenceTest.java b/jdk/test/java/lang/module/ModuleReferenceTest.java index 6b480bb8b2c..bf2db124de5 100644 --- a/jdk/test/java/lang/module/ModuleReferenceTest.java +++ b/jdk/test/java/lang/module/ModuleReferenceTest.java @@ -31,7 +31,6 @@ import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.net.URI; -import java.util.function.Supplier; import org.testng.annotations.Test; import static org.testng.Assert.*; @@ -39,8 +38,13 @@ import static org.testng.Assert.*; @Test public class ModuleReferenceTest { - private Supplier makeSupplier() { - return () -> { throw new UnsupportedOperationException(); }; + private ModuleReference newModuleReference(ModuleDescriptor descriptor, URI uri) { + return new ModuleReference(descriptor, uri) { + @Override + public ModuleReader open() { + throw new UnsupportedOperationException(); + } + }; } public void testBasic() throws Exception { @@ -53,25 +57,16 @@ public class ModuleReferenceTest { URI uri = URI.create("module:/m"); - Supplier supplier = makeSupplier(); - - ModuleReference mref = new ModuleReference(descriptor, uri, supplier); + ModuleReference mref = newModuleReference(descriptor, uri); assertTrue(mref.descriptor().equals(descriptor)); assertTrue(mref.location().get().equals(uri)); - - // check that the supplier is called - try { - mref.open(); - assertTrue(false); - } catch (UnsupportedOperationException expected) { } } - @Test(expectedExceptions = { NullPointerException.class }) public void testNullDescriptor() throws Exception { URI location = URI.create("module:/m"); - new ModuleReference(null, location, makeSupplier()); + newModuleReference(null, location); } public void testNullLocation() { @@ -79,55 +74,8 @@ public class ModuleReferenceTest { = ModuleDescriptor.module("m") .exports("p") .build(); - Supplier supplier = makeSupplier(); - ModuleReference mref = new ModuleReference(descriptor, null, supplier); + ModuleReference mref = newModuleReference(descriptor, null); assertTrue(!mref.location().isPresent()); } - @Test(expectedExceptions = { NullPointerException.class }) - public void testNullSupplier() throws Exception { - ModuleDescriptor descriptor = ModuleDescriptor.module("m").build(); - URI location = URI.create("module:/m"); - new ModuleReference(descriptor, location, null); - } - - - public void testEqualsAndHashCode() { - ModuleDescriptor descriptor1 - = ModuleDescriptor.module("m1") - .exports("p") - .build(); - ModuleDescriptor descriptor2 - = ModuleDescriptor.module("m1") - .exports("p") - .build(); - - URI uri = URI.create("module:/m1"); - Supplier supplier = makeSupplier(); - - ModuleReference mref1 = new ModuleReference(descriptor1, uri, supplier); - ModuleReference mref2 = new ModuleReference(descriptor2, uri, supplier); - ModuleReference mref3 = new ModuleReference(descriptor1, null, supplier); - - assertTrue(mref1.equals(mref1)); - assertTrue(mref1.equals(mref2)); - assertTrue(mref2.equals(mref1)); - assertTrue(mref1.hashCode() == mref2.hashCode()); - - assertTrue(mref3.equals(mref3)); - assertFalse(mref3.equals(mref1)); - assertFalse(mref1.equals(mref3)); - } - - - public void testToString() { - ModuleDescriptor descriptor = ModuleDescriptor.module("m1").build(); - URI uri = URI.create("module:/m1"); - Supplier supplier = makeSupplier(); - ModuleReference mref = new ModuleReference(descriptor, uri, supplier); - String s = mref.toString(); - assertTrue(s.contains("m1")); - assertTrue(s.contains(uri.toString())); - } - } diff --git a/jdk/test/java/lang/reflect/Module/AnnotationsTest.java b/jdk/test/java/lang/reflect/Module/AnnotationsTest.java index 1746d6d40e9..0390698b282 100644 --- a/jdk/test/java/lang/reflect/Module/AnnotationsTest.java +++ b/jdk/test/java/lang/reflect/Module/AnnotationsTest.java @@ -119,7 +119,6 @@ public class AnnotationsTest { List attrs = new ArrayList<>(); attrs.add(new ClassFileAttributes.ModuleAttribute()); attrs.add(new ClassFileAttributes.ModulePackagesAttribute()); - attrs.add(new ClassFileAttributes.ModuleVersionAttribute()); attrs.add(new ClassFileAttributes.ModuleTargetAttribute()); cr.accept(cv, attrs.toArray(new Attribute[0]), 0); diff --git a/jdk/test/jdk/modules/incubator/DefaultImage.java b/jdk/test/jdk/modules/incubator/DefaultImage.java new file mode 100644 index 00000000000..ff6f5261f14 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/DefaultImage.java @@ -0,0 +1,158 @@ +/* + * 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 8170859 + * @summary Ensure no incubator modules are resolved by default in the image + * @library /lib/testlibrary + * @modules jdk.compiler + * @build CompilerUtils + * @run testng DefaultImage + */ + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.testng.annotations.BeforeTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static jdk.testlibrary.ProcessTools.executeCommand; +import static org.testng.Assert.*; + +public class DefaultImage { + private static final String JAVA_HOME = System.getProperty("java.home"); + private static final Path TEST_SRC = Paths.get(System.getProperty("test.src")); + private static final Path CP_DIR = Paths.get("cp"); + + @BeforeTest + private void setup() throws Throwable { + Path src = TEST_SRC.resolve("src").resolve("cp").resolve("listmods"); + assertTrue(CompilerUtils.compile(src, CP_DIR)); + } + + public void test() throws Throwable { + if (isExplodedBuild()) { + System.out.println("Test cannot run on exploded build"); + return; + } + + java("-cp", CP_DIR.toString(), + "listmods.ListModules") + .assertSuccess() + .resultChecker(r -> r.assertOutputContains("java.base")) + .resultChecker(r -> r.assertOutputDoesNotContain("jdk.incubator")); + } + + @DataProvider(name = "tokens") + public Object[][] singleModuleValues() throws IOException { + return new Object[][]{ { "ALL-DEFAULT" }, { "ALL-SYSTEM"} }; + } + + @Test(dataProvider = "tokens") + public void testAddMods(String addModsToken) throws Throwable { + if (isExplodedBuild()) { + System.out.println("Test cannot run on exploded build"); + return; + } + + java("--add-modules", addModsToken, + "-cp", CP_DIR.toString(), + "listmods.ListModules") + .assertSuccess() + .resultChecker(r -> r.assertOutputContains("java.base")) + .resultChecker(r -> r.assertOutputDoesNotContain("jdk.incubator")); + } + + static ToolResult java(String... opts) throws Throwable { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + String[] options = Stream.concat(Stream.of(getJava()), Stream.of(opts)) + .toArray(String[]::new); + + ProcessBuilder pb = new ProcessBuilder(options); + int exitValue = executeCommand(pb).outputTo(ps) + .errorTo(ps) + .getExitValue(); + + return new ToolResult(exitValue, new String(baos.toByteArray(), UTF_8)); + } + + static class ToolResult { + final int exitCode; + final String output; + + ToolResult(int exitValue, String output) { + this.exitCode = exitValue; + this.output = output; + } + + ToolResult assertSuccess() { + assertEquals(exitCode, 0, + "Expected exit code 0, got " + exitCode + + ", with output[" + output + "]"); + return this; + } + + ToolResult resultChecker(Consumer r) { + r.accept(this); + return this; + } + + ToolResult assertOutputContains(String subString) { + assertTrue(output.contains(subString), + "Expected to find [" + subString + "], in output [" + + output + "]" + "\n"); + return this; + } + + ToolResult assertOutputDoesNotContain(String subString) { + assertFalse(output.contains(subString), + "Expected to NOT find [" + subString + "], in output [" + + output + "]" + "\n"); + return this; + } + } + + static String getJava() { + Path image = Paths.get(JAVA_HOME); + boolean isWindows = System.getProperty("os.name").startsWith("Windows"); + Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java"); + if (Files.notExists(java)) + throw new RuntimeException(java + " not found"); + return java.toAbsolutePath().toString(); + } + + static boolean isExplodedBuild() { + Path modulesPath = Paths.get(JAVA_HOME).resolve("lib").resolve("modules"); + return Files.notExists(modulesPath); + } +} diff --git a/jdk/test/jdk/modules/incubator/ImageModules.java b/jdk/test/jdk/modules/incubator/ImageModules.java new file mode 100644 index 00000000000..347b1d4e221 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/ImageModules.java @@ -0,0 +1,382 @@ +/* + * 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 8170859 + * @summary Basic test for incubator modules in jmods and images + * @library /lib/testlibrary + * @modules jdk.compiler jdk.jartool jdk.jlink + * @build CompilerUtils + * @run testng/othervm ImageModules + */ + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.spi.ToolProvider; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import jdk.testlibrary.FileUtils; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static jdk.testlibrary.ProcessTools.executeCommand; +import static org.testng.Assert.*; + +public class ImageModules { + private static final String JAVA_HOME = System.getProperty("java.home"); + private static final Path JDK_JMODS = Paths.get(JAVA_HOME, "jmods"); + + private static final Path TEST_SRC = Paths.get(System.getProperty("test.src")); + private static final Path MODS_DIR = Paths.get("mods"); + private static final Path CP_DIR = Paths.get("cp"); + private static final Path JARS_DIR = Paths.get("jars"); + private static final Path JMODS_DIR = Paths.get("jmods"); + private static final Path IMAGE = Paths.get("image"); + + private static final String JAVA_BASE = "java.base"; + private final String[] modules = new String[] { "message.writer", + "message.converter" }; + + @BeforeTest + private void setup() throws Throwable { + Path src = TEST_SRC.resolve("src"); + for (String name : modules) { + assertTrue(CompilerUtils.compile(src.resolve(name), + MODS_DIR, + "--module-source-path", src.toString())); + } + + assertTrue(CompilerUtils.compile(src.resolve("cp"), + CP_DIR, + "--module-path", MODS_DIR.toString(), + "--add-modules", "message.writer")); + } + + @DataProvider(name = "singleModule") + public Object[][] singleModuleValues() throws IOException { + Object[][] values = new Object[][]{ + // { Extra args to the build the message.converter jmod + // Tokens to pass to the run time --add-modules option + // SUCCESS or FAILURE expected + // Messages expected in the run time output + // Messages that must not appear in the run time output }, + { "", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_SUCCESS, + List.of("hello world", "message.converter", "java.base"), + List.of("WARNING") }, + { "--do-not-resolve-by-default", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_FAILURE, + List.of("java.base", "java.lang.ClassNotFoundException: converter.MessageConverter"), + List.of("WARNING", "message.converter") }, + { "--warn-if-resolved=incubating", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_SUCCESS, + List.of("hello world", "message.converter", "java.base", + "WARNING: Using incubator modules: message.converter"), + List.of() }, + { "--do-not-resolve-by-default --warn-if-resolved=incubating", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_FAILURE, + List.of("java.base", "java.lang.ClassNotFoundException: converter.MessageConverter"), + List.of("WARNING", "message.converter") }, + { "--do-not-resolve-by-default --warn-if-resolved=incubating", + List.of("message.converter"), + ToolResult.ASSERT_SUCCESS, + List.of("hello world", "message.converter", "java.base", "WARNING"), + List.of() } + }; + return values; + } + + @Test(dataProvider = "singleModule") + public void singleModule(String extraJmodArg, + List addModsTokens, + Consumer assertExitCode, + List expectedOutput, + List unexpectedOutput) + throws Throwable + { + if (Files.notExists(JDK_JMODS)) { + System.out.println("JDK jmods not found test cannot run."); + return; + } + + FileUtils.deleteFileTreeUnchecked(JMODS_DIR); + FileUtils.deleteFileTreeUnchecked(IMAGE); + Files.createDirectories(JMODS_DIR); + Path converterJmod = JMODS_DIR.resolve("converter.jmod"); + + jmod("create", + "--class-path", MODS_DIR.resolve("message.converter").toString(), + extraJmodArg, + converterJmod.toString()) + .assertSuccess(); + + String mpath = JDK_JMODS.toString() + File.pathSeparator + JMODS_DIR.toString(); + jlink("--module-path", mpath, + "--add-modules", JAVA_BASE + ",message.converter", + "--output", IMAGE.toString()) + .assertSuccess(); + + for (String addModsToken : addModsTokens) { + String[] props = new String[] {"", "-Djdk.system.module.finder.disabledFastPath"}; + for (String systemProp : props) + java(IMAGE, + systemProp, + "--add-modules", addModsToken, + "-cp", CP_DIR.toString(), + "test.ConvertToLowerCase", "HEllo WoRlD") + .resultChecker(assertExitCode) + .resultChecker(r -> { + expectedOutput.forEach(e -> r.assertContains(e)); + unexpectedOutput.forEach(e -> r.assertDoesNotContains(e)); + }); + } + } + + @Test + public void singleModularJar() throws Throwable { + FileUtils.deleteFileTreeUnchecked(JARS_DIR); + Files.createDirectories(JARS_DIR); + Path converterJar = JARS_DIR.resolve("converter.jar"); + + jar("--create", + "--file", converterJar.toString(), + "--warn-if-resolved=incubating", + "-C", MODS_DIR.resolve("message.converter").toString() , ".") + .assertSuccess(); + + + java(Paths.get(JAVA_HOME), + "--module-path", JARS_DIR.toString(), + "--add-modules", "message.converter", + "-cp", CP_DIR.toString(), + "test.ConvertToLowerCase", "HEllo WoRlD") + .assertSuccess() + .resultChecker(r -> { + r.assertContains("WARNING: Using incubator modules: message.converter"); + }); + } + + @DataProvider(name = "twoModules") + public Object[][] twoModulesValues() throws IOException { + Object[][] values = new Object[][]{ + // { Extra args to the build the message.writer jmod + // Extra args to the build the message.converter jmod + // Tokens to pass to the run time --add-modules option + // SUCCESS or FAILURE expected + // Messages expected in the run time output + // Messages that must not appear in the run time output }, + { "", + "", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_SUCCESS, + List.of("HELLO CHEGAR !!!", "message.writer", "message.converter", "java.base"), + List.of() }, + { "", + "--do-not-resolve-by-default", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_SUCCESS, + List.of("HELLO CHEGAR !!!", "message.writer", "message.converter", "java.base"), + List.of() }, + { "--do-not-resolve-by-default", + "", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_FAILURE, + List.of("java.lang.ClassNotFoundException: writer.MessageWriter", "java.base"), + List.of("message.writer") }, + { "--do-not-resolve-by-default", + "--do-not-resolve-by-default", + List.of("ALL-DEFAULT", "ALL-SYSTEM"), + ToolResult.ASSERT_FAILURE, + List.of("java.lang.ClassNotFoundException: writer.MessageWriter", "java.base"), + List.of("message.converter", "message.writer") }, + // now add in warnings + { "--do-not-resolve-by-default --warn-if-resolved=incubating", + "", + List.of("message.writer"), + ToolResult.ASSERT_SUCCESS, + List.of("HELLO CHEGAR !!!", "message.writer", "message.converter", "java.base", + "WARNING: Using incubator modules: message.writer"), + List.of() }, + { "", + "--do-not-resolve-by-default --warn-if-resolved=incubating", + List.of("message.writer"), + ToolResult.ASSERT_SUCCESS, + List.of("HELLO CHEGAR !!!", "message.writer", "message.converter", "java.base", + "WARNING: Using incubator modules: message.converter"), + List.of() } }; + return values; + } + + @Test(dataProvider = "twoModules") + public void doNotResolveByDefaultTwoModules(String extraFirstJmodArg, + String extraSecondJmodArg, + List addModsTokens, + Consumer assertExitCode, + List expectedOutput, + List unexpectedOutput) + throws Throwable + { + if (Files.notExists(JDK_JMODS)) { + System.out.println("JDK jmods not found test cannot run."); + return; + } + + FileUtils.deleteFileTreeUnchecked(JMODS_DIR); + FileUtils.deleteFileTreeUnchecked(IMAGE); + Files.createDirectories(JMODS_DIR); + Path writerJmod = JMODS_DIR.resolve("writer.jmod"); + Path converterJmod = JMODS_DIR.resolve("converter.jmod"); + + jmod("create", + extraFirstJmodArg, + "--class-path", MODS_DIR.resolve("message.writer").toString(), + writerJmod.toString()); + + jmod("create", + "--class-path", MODS_DIR.resolve("message.converter").toString(), + extraSecondJmodArg, + converterJmod.toString()) + .assertSuccess(); + + String mpath = JDK_JMODS.toString() + File.pathSeparator + JMODS_DIR.toString(); + jlink("--module-path", mpath, + "--add-modules", JAVA_BASE + ",message.writer,message.converter", + "--output", IMAGE.toString()) + .assertSuccess(); + + for (String addModsToken : addModsTokens) { + String[] props = new String[] {"", "-Djdk.system.module.finder.disabledFastPath"}; + for (String systemProp : props) + java(IMAGE, + systemProp, + "--add-modules", addModsToken, + "-cp", CP_DIR.toString(), + "test.WriteUpperCase", "hello chegar !!!") + .resultChecker(assertExitCode) + .resultChecker(r -> { + expectedOutput.forEach(e -> r.assertContains(e)); + unexpectedOutput.forEach(e -> r.assertDoesNotContains(e)); + }); + } + } + + static final ToolProvider JMOD_TOOL = ToolProvider.findFirst("jmod") + .orElseThrow(() -> new RuntimeException("jmod tool not found")); + static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar") + .orElseThrow(() -> new RuntimeException("jar tool not found")); + static final ToolProvider JLINK_TOOL = ToolProvider.findFirst("jlink") + .orElseThrow(() -> new RuntimeException("jlink tool not found")); + + static ToolResult jmod(String... args) { return execTool(JMOD_TOOL, args); } + + static ToolResult jar(String... args) { return execTool(JAR_TOOL, args); } + + static ToolResult jlink(String... args) { return execTool(JLINK_TOOL, args); } + + static ToolResult java(Path image, String... opts) throws Throwable { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + String[] options = Stream.concat(Stream.of(getJava(image)), + Stream.of(opts).filter(s -> !s.equals(""))) + .toArray(String[]::new); + + ProcessBuilder pb = new ProcessBuilder(options); + int exitValue = executeCommand(pb).outputTo(ps) + .errorTo(ps) + .getExitValue(); + + return new ToolResult(exitValue, new String(baos.toByteArray(), UTF_8)); + } + + static ToolResult execTool(ToolProvider tool, String... args) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + List filteredArgs = Stream.of(args) + .map(s -> s.split(" ")).flatMap(Stream::of) + .filter(s -> !s.equals("")) + .collect(Collectors.toList()); + System.out.println(tool + " " + filteredArgs); + int ec = tool.run(ps, ps, filteredArgs.toArray(new String[] {})); + return new ToolResult(ec, new String(baos.toByteArray(), UTF_8)); + } + + static class ToolResult { + final int exitCode; + final String output; + + ToolResult(int exitValue, String output) { + this.exitCode = exitValue; + this.output = output; + } + + static Consumer ASSERT_SUCCESS = r -> + assertEquals(r.exitCode, 0, + "Expected exit code 0, got " + r.exitCode + + ", with output[" + r.output + "]"); + static Consumer ASSERT_FAILURE = r -> + assertNotEquals(r.exitCode, 0, + "Expected exit code != 0, got " + r.exitCode + + ", with output[" + r.output + "]"); + + ToolResult assertSuccess() { ASSERT_SUCCESS.accept(this); return this; } + ToolResult assertFailure() { ASSERT_FAILURE.accept(this); return this; } + ToolResult resultChecker(Consumer r) { r.accept(this); return this; } + + ToolResult assertContains(String subString) { + assertTrue(output.contains(subString), + "Expected to find [" + subString + "], in output [" + + output + "]" + "\n"); + return this; + } + ToolResult assertDoesNotContains(String subString) { + assertFalse(output.contains(subString), + "Expected to NOT find [" + subString + "], in output [" + + output + "]" + "\n"); + return this; + } + } + + static String getJava(Path image) { + boolean isWindows = System.getProperty("os.name").startsWith("Windows"); + Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java"); + if (Files.notExists(java)) + throw new RuntimeException(java + " not found"); + return java.toAbsolutePath().toString(); + } +} diff --git a/jdk/test/jdk/modules/incubator/src/cp/listmods/ListModules.java b/jdk/test/jdk/modules/incubator/src/cp/listmods/ListModules.java new file mode 100644 index 00000000000..2d80d198ee0 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/cp/listmods/ListModules.java @@ -0,0 +1,39 @@ +/* + * 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 listmods; + +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import static java.util.stream.Collectors.joining; + +public class ListModules { + public static void main(String[] args) throws Exception { + System.out.println(Layer.boot() + .modules() + .stream() + .map(Module::getName) + .sorted() + .collect(joining("\n"))); + } +} diff --git a/jdk/test/jdk/modules/incubator/src/cp/test/ConvertToLowerCase.java b/jdk/test/jdk/modules/incubator/src/cp/test/ConvertToLowerCase.java new file mode 100644 index 00000000000..cf0d1c7cba9 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/cp/test/ConvertToLowerCase.java @@ -0,0 +1,40 @@ +/* + * 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 test; + +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import static java.util.stream.Collectors.joining; + +public class ConvertToLowerCase { + public static void main(String[] args) { + System.out.println(Layer.boot() + .modules() + .stream() + .map(Module::getName) + .sorted() + .collect(joining("\n"))); + System.out.println(converter.MessageConverter.toLowerCase(args[0])); + } +} diff --git a/jdk/test/jdk/modules/incubator/src/cp/test/WriteUpperCase.java b/jdk/test/jdk/modules/incubator/src/cp/test/WriteUpperCase.java new file mode 100644 index 00000000000..844fccb2fcf --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/cp/test/WriteUpperCase.java @@ -0,0 +1,40 @@ +/* + * 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 test; + +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import static java.util.stream.Collectors.joining; + +public class WriteUpperCase { + public static void main(String[] args) { + System.out.println(Layer.boot() + .modules() + .stream() + .map(Module::getName) + .sorted() + .collect(joining("\n"))); + writer.MessageWriter.writeOn(args[0], System.out); + } +} diff --git a/jdk/test/jdk/modules/incubator/src/message.converter/converter/MessageConverter.java b/jdk/test/jdk/modules/incubator/src/message.converter/converter/MessageConverter.java new file mode 100644 index 00000000000..d9604df2ec0 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/message.converter/converter/MessageConverter.java @@ -0,0 +1,34 @@ +/* + * 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 converter; + +public class MessageConverter { + public static String toUpperCase(String message) { + return message.toUpperCase(java.util.Locale.ROOT); + } + + public static String toLowerCase(String message) { + return message.toLowerCase(java.util.Locale.ROOT); + } +} diff --git a/jdk/test/jdk/modules/incubator/src/message.converter/module-info.java b/jdk/test/jdk/modules/incubator/src/message.converter/module-info.java new file mode 100644 index 00000000000..6fbfa700a7b --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/message.converter/module-info.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +module message.converter { + exports converter; +} diff --git a/jdk/test/jdk/modules/incubator/src/message.writer/module-info.java b/jdk/test/jdk/modules/incubator/src/message.writer/module-info.java new file mode 100644 index 00000000000..09370cc283a --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/message.writer/module-info.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +module message.writer { + requires message.converter; + exports writer; +} diff --git a/jdk/test/jdk/modules/incubator/src/message.writer/writer/MessageWriter.java b/jdk/test/jdk/modules/incubator/src/message.writer/writer/MessageWriter.java new file mode 100644 index 00000000000..0c6ba17cf26 --- /dev/null +++ b/jdk/test/jdk/modules/incubator/src/message.writer/writer/MessageWriter.java @@ -0,0 +1,38 @@ +/* + * 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 writer; + +import java.io.PrintStream; +import java.util.Locale; + +public class MessageWriter { + public static void writeOn(String message, PrintStream out) { + String newMesssage = converter.MessageConverter.toUpperCase(message); + if (!newMesssage.equals(message.toUpperCase(Locale.ROOT))) + throw new RuntimeException("Expected " + message.toUpperCase(Locale.ROOT) + + ", got " + newMesssage ); + + out.println(newMesssage); + } +} diff --git a/jdk/test/lib/testlibrary/ModuleUtils.java b/jdk/test/lib/testlibrary/ModuleUtils.java index c227464da1a..b3c9d5e49c8 100644 --- a/jdk/test/lib/testlibrary/ModuleUtils.java +++ b/jdk/test/lib/testlibrary/ModuleUtils.java @@ -32,7 +32,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.function.Supplier; /** @@ -58,12 +57,13 @@ public final class ModuleUtils { URI uri = URI.create("module:/" + name); - Supplier supplier = () -> { - throw new UnsupportedOperationException(); + ModuleReference mref = new ModuleReference(descriptor, uri) { + @Override + public ModuleReader open() { + throw new UnsupportedOperationException(); + } }; - ModuleReference mref = new ModuleReference(descriptor, uri, supplier); - namesToReference.put(name, mref); } diff --git a/jdk/test/tools/jar/compat/CLICompatibility.java b/jdk/test/tools/jar/compat/CLICompatibility.java index 9355f18a66b..c31762eedc3 100644 --- a/jdk/test/tools/jar/compat/CLICompatibility.java +++ b/jdk/test/tools/jar/compat/CLICompatibility.java @@ -43,6 +43,7 @@ import org.testng.annotations.Test; import static java.lang.String.format; import static java.lang.System.out; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /* @@ -428,10 +429,12 @@ public class CLICompatibility { jar("--help") .assertSuccess() - .resultChecker(r -> + .resultChecker(r -> { assertTrue(r.output.startsWith("Usage: jar [OPTION...] [ [--release VERSION] [-C dir] files]"), - "Failed, got [" + r.output + "]") - ); + "Failed, got [" + r.output + "]"); + assertFalse(r.output.contains("--do-not-resolve-by-default")); + assertFalse(r.output.contains("--warn-if-resolved")); + }); jar("--help:compat") .assertSuccess() @@ -439,6 +442,15 @@ public class CLICompatibility { assertTrue(r.output.startsWith("Compatibility Interface:"), "Failed, got [" + r.output + "]") ); + + jar("--help-extra") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.startsWith("Usage: jar [OPTION...] [ [--release VERSION] [-C dir] files]"), + "Failed, got [" + r.output + "]"); + assertTrue(r.output.contains("--do-not-resolve-by-default")); + assertTrue(r.output.contains("--warn-if-resolved")); + }); } // -- Infrastructure diff --git a/jdk/test/tools/jar/modularJar/src/bar/jdk/test/bar/Bar.java b/jdk/test/tools/jar/modularJar/src/bar/jdk/test/bar/Bar.java index 92329265533..2d1d844c818 100644 --- a/jdk/test/tools/jar/modularJar/src/bar/jdk/test/bar/Bar.java +++ b/jdk/test/tools/jar/modularJar/src/bar/jdk/test/bar/Bar.java @@ -25,16 +25,18 @@ package jdk.test.bar; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Exports; -import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Provides; +import java.lang.module.ModuleReference; +import java.lang.module.ResolvedModule; +import java.lang.reflect.Module; import java.util.Optional; import java.util.StringJoiner; import java.util.HashSet; import java.util.Set; - import jdk.internal.misc.SharedSecrets; import jdk.internal.misc.JavaLangModuleAccess; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModuleReferenceImpl; import jdk.test.bar.internal.Message; public class Bar { @@ -71,9 +73,14 @@ public class Bar { if (!sj.toString().equals("")) System.out.println("contains:" + sj.toString()); - ModuleDescriptor foo = jdk.test.foo.Foo.class.getModule().getDescriptor(); - JavaLangModuleAccess jlma = SharedSecrets.getJavaLangModuleAccess(); - Optional oHashes = jlma.hashes(foo); - System.out.println("hashes:" + oHashes.get().hashFor("bar")); + + Module foo = jdk.test.foo.Foo.class.getModule(); + Optional om = foo.getLayer().configuration().findModule(foo.getName()); + assert om.isPresent(); + ModuleReference mref = om.get().reference(); + assert mref instanceof ModuleReferenceImpl; + ModuleHashes hashes = ((ModuleReferenceImpl) mref).recordedHashes(); + assert hashes != null; + System.out.println("hashes:" + hashes.hashFor("bar")); } } diff --git a/jdk/test/tools/jimage/VerifyJimage.java b/jdk/test/tools/jimage/VerifyJimage.java index 30628ad9921..d5415af35b0 100644 --- a/jdk/test/tools/jimage/VerifyJimage.java +++ b/jdk/test/tools/jimage/VerifyJimage.java @@ -49,7 +49,7 @@ import jdk.internal.jimage.ImageLocation; * @test * @summary Verify jimage * @modules java.base/jdk.internal.jimage - * @run main/othervm --add-modules=ALL-SYSTEM VerifyJimage + * @run main/othervm --add-modules=ALL-SYSTEM,jdk.incubator.httpclient VerifyJimage */ /** diff --git a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/CompiledVersionTest.java b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/CompiledVersionTest.java new file mode 100644 index 00000000000..fb7f5569e06 --- /dev/null +++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/CompiledVersionTest.java @@ -0,0 +1,129 @@ +/* + * 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. + */ + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import jdk.testlibrary.FileUtils; +import static jdk.testlibrary.ProcessTools.*; + + +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +/** + * @test + * @library /lib/testlibrary + * @modules jdk.compiler jdk.jlink + * @build CompiledVersionTest CompilerUtils jdk.testlibrary.FileUtils jdk.testlibrary.ProcessTools + * @run testng CompiledVersionTest + */ + +public class CompiledVersionTest { + private static final String JAVA_HOME = System.getProperty("java.home"); + private static final String TEST_SRC = System.getProperty("test.src"); + + private static final Path SRC_DIR = Paths.get(TEST_SRC, "src"); + private static final Path MODS_DIR = Paths.get("mods"); + private static final Path IMAGE = Paths.get("image"); + private static final Path JMODS = Paths.get(JAVA_HOME, "jmods"); + private static final String MAIN_MID = "test/jdk.test.Main"; + + // the names of the modules in this test + private static String[] modules = new String[] { "m1", "m2", "test"}; + private static String[] versions = new String[] { "1.0", "2-ea", "3-internal"}; + + + private static boolean hasJmods() { + if (!Files.exists(JMODS)) { + System.err.println("Test skipped. NO jmods directory"); + return false; + } + return true; + } + + /* + * Compiles all modules used by the test + */ + @BeforeTest + public void compileAll() throws Throwable { + if (!hasJmods()) return; + + for (int i=0; i < modules.length; i++) { + String mn = modules[i]; + String version = versions[i]; + Path msrc = SRC_DIR.resolve(mn); + if (version.equals("0")) { + assertTrue(CompilerUtils.compile(msrc, MODS_DIR, + "--module-source-path", SRC_DIR.toString())); + } else { + assertTrue(CompilerUtils.compile(msrc, MODS_DIR, + "--module-source-path", SRC_DIR.toString(), + "--module-version", version)); + } + } + + if (Files.exists(IMAGE)) { + FileUtils.deleteFileTreeUnchecked(IMAGE); + } + + createImage(IMAGE, modules); + } + + private void createImage(Path outputDir, String... modules) throws Throwable { + Path jlink = Paths.get(JAVA_HOME, "bin", "jlink"); + String mp = JMODS.toString() + File.pathSeparator + MODS_DIR.toString(); + assertTrue(executeProcess(jlink.toString(), "--output", outputDir.toString(), + "--add-modules", Arrays.stream(modules).collect(Collectors.joining(",")), + "--module-path", mp) + .outputTo(System.out) + .errorTo(System.out) + .getExitValue() == 0); + } + + /* + * Test the image created when linking with a module with + * no Packages attribute + */ + @Test + public void testCompiledVersions() throws Throwable { + if (!hasJmods()) return; + + Path java = IMAGE.resolve("bin").resolve("java"); + Stream options = Stream.concat( + Stream.of(java.toString(), "-m", MAIN_MID, String.valueOf(modules.length)), + Stream.concat(Arrays.stream(modules), Arrays.stream(versions)) + ); + + assertTrue(executeProcess(options.toArray(String[]::new)) + .outputTo(System.out) + .errorTo(System.out) + .getExitValue() == 0); + } +} diff --git a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/SystemModulesTest.java b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/SystemModulesTest.java index d74b6b84152..83559fb30b7 100644 --- a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/SystemModulesTest.java +++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/SystemModulesTest.java @@ -59,7 +59,7 @@ public class SystemModulesTest { private void testModuleDescriptor(ModuleDescriptor md) { assertUnmodifiable(md.packages(), "package"); assertUnmodifiable(md.requires(), - jlma.newRequires(Set.of(Requires.Modifier.TRANSITIVE), "require")); + jlma.newRequires(Set.of(Requires.Modifier.TRANSITIVE), "require", null)); for (Requires req : md.requires()) { assertUnmodifiable(req.modifiers(), Requires.Modifier.TRANSITIVE); } diff --git a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java index 0875db2585c..35d1eec67dc 100644 --- a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java +++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java @@ -39,7 +39,7 @@ import static org.testng.Assert.*; /** * @test * @library /lib/testlibrary - * @modules jdk.compiler + * @modules jdk.compiler jdk.jlink * @build UserModuleTest CompilerUtils jdk.testlibrary.FileUtils jdk.testlibrary.ProcessTools * @run testng UserModuleTest */ diff --git a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/jdk/test/Main.java b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/jdk/test/Main.java new file mode 100644 index 00000000000..e5c6fe8e6ca --- /dev/null +++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/jdk/test/Main.java @@ -0,0 +1,104 @@ +/* + * 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.test; + +import java.lang.module.ModuleDescriptor; +import java.lang.reflect.Layer; +import java.lang.reflect.Module; +import java.net.URI; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + + +/* + * Main class to verify if ModuleDescriptor carries the correct version + */ +public class Main { + static final Map nameToVersion = new HashMap<>(); + + // jdk.test.Main $count $module-name... $version... + public static void main(String... args) throws Exception { + int count = args.length > 0 ? Integer.valueOf(args[0]) : 0; + if (count < 1 || args.length != count*2+1) { + throw new IllegalArgumentException(Arrays.toString(args)); + } + + List modules = List.of(Arrays.copyOfRange(args, 1, 1+count)); + List versions = List.of(Arrays.copyOfRange(args, 1+count, args.length)); + for (int i=0; i < modules.size(); i++) { + System.out.format("module %s expects %s version%n", + modules.get(i), versions.get(i)); + nameToVersion.put(modules.get(i), versions.get(i)); + } + + FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), + Collections.emptyMap()); + // check the module descriptor of a system module + for (int i=0; i < modules.size(); i++) { + String mn = modules.get(i); + Module module = Layer.boot().findModule(mn).orElseThrow( + () -> new RuntimeException(mn + " not found") + ); + + // check ModuleDescriptor from the run-time + validate(module.getDescriptor()); + + // check module-info.class in the image + Path path = fs.getPath("/", "modules", modules.get(i), "module-info.class"); + validate(ModuleDescriptor.read(Files.newInputStream(path))); + } + } + + static void validate(ModuleDescriptor descriptor) { + checkVersion(descriptor.name(), descriptor.version()); + descriptor.requires() + .stream() + .filter(r -> !r.name().equals("java.base")) + .forEach(r -> checkVersion(r.name(), r.compiledVersion())); + } + + static void checkVersion(String mn, Optional version) { + boolean matched; + String v = nameToVersion.get(mn); + if (version.isPresent()) { + matched = version.get().toString().equals(v); + } else { + // 0 indicate no version + matched = v.equals("0"); + } + + if (!matched) { + throw new RuntimeException(mn + " mismatched version " + version + + " expected: " + v); + } + } +} diff --git a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/module-info.java b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/module-info.java new file mode 100644 index 00000000000..83e15da97bf --- /dev/null +++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/test/module-info.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +module test { + requires m1; + requires m2; + exports jdk.test; +} diff --git a/jdk/test/tools/jmod/JmodTest.java b/jdk/test/tools/jmod/JmodTest.java index 9e19eef37e1..970320ad9a5 100644 --- a/jdk/test/tools/jmod/JmodTest.java +++ b/jdk/test/tools/jmod/JmodTest.java @@ -470,9 +470,22 @@ public class JmodTest { public void testHelp() { jmod("--help") .assertSuccess() - .resultChecker(r -> - assertTrue(r.output.startsWith("Usage: jmod"), "Help not printed") - ); + .resultChecker(r -> { + assertTrue(r.output.startsWith("Usage: jmod"), "Help not printed"); + assertFalse(r.output.contains("--do-not-resolve-by-default")); + assertFalse(r.output.contains("--warn-if-resolved")); + }); + } + + @Test + public void testHelpExtra() { + jmod("--help-extra") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.startsWith("Usage: jmod"), "Extra help not printed"); + assertContains(r.output, "--do-not-resolve-by-default"); + assertContains(r.output, "--warn-if-resolved"); + }); } @Test diff --git a/jdk/test/tools/jmod/hashes/HashesTest.java b/jdk/test/tools/jmod/hashes/HashesTest.java index 22752e759f1..8d4b2f68300 100644 --- a/jdk/test/tools/jmod/hashes/HashesTest.java +++ b/jdk/test/tools/jmod/hashes/HashesTest.java @@ -50,14 +50,13 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.spi.ToolProvider; import java.util.stream.Collectors; -import jdk.internal.misc.SharedSecrets; -import jdk.internal.misc.JavaLangModuleAccess; +import jdk.internal.module.ModuleInfo; import jdk.internal.module.ModuleHashes; +import jdk.internal.module.ModulePath; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -103,54 +102,53 @@ public class HashesTest { @Test public void test() throws Exception { for (String mn : modules) { - assertFalse(hashes(mn).isPresent()); + assertTrue(hashes(mn) == null); } // hash m1 in m2 jmod("m2", "--module-path", jmods.toString(), "--hash-modules", "m1"); - checkHashes(hashes("m2").get(), "m1"); + checkHashes(hashes("m2"), "m1"); // hash m1 in m2 jmod("m2", "--module-path", jmods.toString(), "--hash-modules", ".*"); - checkHashes(hashes("m2").get(), "m1"); + checkHashes(hashes("m2"), "m1"); // create m2.jmod with no hash jmod("m2"); // run jmod hash command to hash m1 in m2 and m3 runJmod(Arrays.asList("hash", "--module-path", jmods.toString(), "--hash-modules", ".*")); - checkHashes(hashes("m2").get(), "m1"); - checkHashes(hashes("m3").get(), "m1"); + checkHashes(hashes("m2"), "m1"); + checkHashes(hashes("m3"), "m1"); jmod("org.bar"); jmod("org.foo"); jmod("org.bar", "--module-path", jmods.toString(), "--hash-modules", "org.*"); - checkHashes(hashes("org.bar").get(), "org.foo"); + checkHashes(hashes("org.bar"), "org.foo"); jmod("m3", "--module-path", jmods.toString(), "--hash-modules", ".*"); - checkHashes(hashes("m3").get(), "org.foo", "org.bar", "m1"); + checkHashes(hashes("m3"), "org.foo", "org.bar", "m1"); } private void checkHashes(ModuleHashes hashes, String... hashModules) { assertTrue(hashes.names().equals(Set.of(hashModules))); } - private Optional hashes(String name) throws Exception { - ModuleFinder finder = SharedSecrets.getJavaLangModuleAccess() - .newModulePath(Runtime.version(), true, jmods.resolve(name + ".jmod")); + private ModuleHashes hashes(String name) throws Exception { + ModuleFinder finder = new ModulePath(Runtime.version(), + true, + jmods.resolve(name + ".jmod")); ModuleReference mref = finder.find(name).orElseThrow(RuntimeException::new); ModuleReader reader = mref.open(); try (InputStream in = reader.open("module-info.class").get()) { - ModuleDescriptor md = ModuleDescriptor.read(in); - JavaLangModuleAccess jmla = SharedSecrets.getJavaLangModuleAccess(); - Optional hashes = jmla.hashes(md); + ModuleHashes hashes = ModuleInfo.read(in, null).recordedHashes(); System.out.format("hashes in module %s %s%n", name, - hashes.isPresent() ? "present" : "absent"); - if (hashes.isPresent()) { - hashes.get().names().stream() + (hashes != null) ? "present" : "absent"); + if (hashes != null) { + hashes.names().stream() .sorted() - .forEach(n -> System.out.format(" %s %s%n", n, hashes.get().hashFor(n))); + .forEach(n -> System.out.format(" %s %s%n", n, hashes.hashFor(n))); } return hashes; } finally { diff --git a/jdk/test/tools/pack200/pack200-verifier/src/xmlkit/ClassReader.java b/jdk/test/tools/pack200/pack200-verifier/src/xmlkit/ClassReader.java index 144405e5ddf..97e5f767b6e 100644 --- a/jdk/test/tools/pack200/pack200-verifier/src/xmlkit/ClassReader.java +++ b/jdk/test/tools/pack200/pack200-verifier/src/xmlkit/ClassReader.java @@ -41,6 +41,8 @@ import com.sun.tools.classfile.Code_attribute; import com.sun.tools.classfile.CompilationID_attribute; import com.sun.tools.classfile.ConstantPool; import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; +import com.sun.tools.classfile.ConstantPool.CONSTANT_Module_info; +import com.sun.tools.classfile.ConstantPool.CONSTANT_Package_info; import com.sun.tools.classfile.ConstantPool.CONSTANT_Double_info; import com.sun.tools.classfile.ConstantPool.CONSTANT_Fieldref_info; import com.sun.tools.classfile.ConstantPool.CONSTANT_Float_info; @@ -80,9 +82,9 @@ import com.sun.tools.classfile.Module_attribute.RequiresEntry; import com.sun.tools.classfile.ModuleHashes_attribute; import com.sun.tools.classfile.ModuleHashes_attribute.Entry; import com.sun.tools.classfile.ModuleMainClass_attribute; +import com.sun.tools.classfile.ModuleResolution_attribute; import com.sun.tools.classfile.ModuleTarget_attribute; import com.sun.tools.classfile.ModulePackages_attribute; -import com.sun.tools.classfile.ModuleVersion_attribute; import com.sun.tools.classfile.Opcode; import com.sun.tools.classfile.RuntimeInvisibleAnnotations_attribute; import com.sun.tools.classfile.RuntimeInvisibleParameterAnnotations_attribute; @@ -669,6 +671,40 @@ class ConstantPoolVisitor implements ConstantPool.Visitor { return value; } + @Override + public String visitModule(CONSTANT_Module_info info, Integer p) { + String value = slist.get(p); + if (value == null) { + try { + value = visit(cfpool.get(info.name_index), info.name_index); + slist.set(p, value); + xpool.add(new Element("CONSTANT_Module", + new String[]{"id", p.toString()}, + value)); + } catch (ConstantPoolException ex) { + ex.printStackTrace(); + } + } + return value; + } + + @Override + public String visitPackage(CONSTANT_Package_info info, Integer p) { + String value = slist.get(p); + if (value == null) { + try { + value = visit(cfpool.get(info.name_index), info.name_index); + slist.set(p, value); + xpool.add(new Element("CONSTANT_Package", + new String[]{"id", p.toString()}, + value)); + } catch (ConstantPoolException ex) { + ex.printStackTrace(); + } + } + return value; + } + @Override public String visitDouble(CONSTANT_Double_info c, Integer p) { String value = slist.get(p); @@ -1495,20 +1531,20 @@ class AttributeVisitor implements Attribute.Visitor { } @Override - public Element visitModuleTarget(ModuleTarget_attribute attr, Element p) { - Element e = new Element(x.getCpString(attr.attribute_name_index)); - e.add(x.getCpString(attr.os_name_index)); - e.add(x.getCpString(attr.os_arch_index)); - e.add(x.getCpString(attr.os_version_index)); + public Element visitModuleResolution(ModuleResolution_attribute attr, Element p) { + Element e = new Element("ModuleResolution"); + e.setAttr("flags", Integer.toString(attr.resolution_flags)); e.trimToSize(); p.add(e); return null; } @Override - public Element visitModuleVersion(ModuleVersion_attribute attr, Element p) { + public Element visitModuleTarget(ModuleTarget_attribute attr, Element p) { Element e = new Element(x.getCpString(attr.attribute_name_index)); - e.add(x.getCpString(attr.version_index)); + e.add(x.getCpString(attr.os_name_index)); + e.add(x.getCpString(attr.os_arch_index)); + e.add(x.getCpString(attr.os_version_index)); e.trimToSize(); p.add(e); return null; From 98cc34711bbd4276f3e1ee8a05b7494e0247afcb Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Fri, 16 Dec 2016 19:50:35 +0800 Subject: [PATCH 23/45] 8171340: HttpNegotiateServer/java test should not use system proxy on Mac Reviewed-by: chegar --- .../krb5/auto/HttpNegotiateServer.java | 61 +++++++++++-------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java index 96245002874..55f2d1a4d15 100644 --- a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java +++ b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java @@ -23,10 +23,12 @@ /* * @test - * @bug 6578647 6829283 + * @bug 6578647 6829283 8171340 * @run main/othervm HttpNegotiateServer - * @summary Undefined requesting URL in java.net.Authenticator.getPasswordAuthentication() - * @summary HTTP/Negotiate: Authenticator triggered again when user cancels the first one + * @summary Undefined requesting URL in java.net.Authenticator + * .getPasswordAuthentication() + * @summary HTTP/Negotiate: Authenticator triggered again when + * user cancels the first one */ import com.sun.net.httpserver.Headers; @@ -240,16 +242,15 @@ public class HttpNegotiateServer { java.net.Authenticator.setDefault(new KnowAllAuthenticator()); reader = new BufferedReader(new InputStreamReader( - webUrl.openConnection().getInputStream())); + webUrl.openConnection(Proxy.NO_PROXY).getInputStream())); if (!reader.readLine().equals(CONTENT)) { throw new RuntimeException("Bad content"); } reader = new BufferedReader(new InputStreamReader( - proxyUrl.openConnection( - new Proxy(Proxy.Type.HTTP, - new InetSocketAddress(PROXY_HOST, proxyPort))) - .getInputStream())); + proxyUrl.openConnection(new Proxy(Proxy.Type.HTTP, + new InetSocketAddress(PROXY_HOST, proxyPort))) + .getInputStream())); if (!reader.readLine().equals(CONTENT)) { throw new RuntimeException("Bad content"); } @@ -260,7 +261,7 @@ public class HttpNegotiateServer { java.net.Authenticator.setDefault(new KnowNothingAuthenticator()); try { new BufferedReader(new InputStreamReader( - webUrl.openConnection().getInputStream())); + webUrl.openConnection(Proxy.NO_PROXY).getInputStream())); } catch (IOException ioe) { // Will fail since no username and password is provided. } @@ -274,7 +275,7 @@ public class HttpNegotiateServer { try { URL url = webUrl; - URLConnection conn = url.openConnection(); + URLConnection conn = url.openConnection(Proxy.NO_PROXY); conn.connect(); inputStream = conn.getInputStream(); byte[] b = new byte[inputStream.available()]; @@ -285,7 +286,7 @@ public class HttpNegotiateServer { System.out.println("Length: " + s.length()); System.out.println(s); } catch (Exception ex) { - throw new RuntimeException(ex); + throw new RuntimeException(ex); } finally { if (inputStream != null) { try { @@ -307,7 +308,8 @@ public class HttpNegotiateServer { CallbackHandler callback = new CallbackHandler() { @Override - public void handle(Callback[] pCallbacks) throws IOException, UnsupportedCallbackException { + public void handle(Callback[] pCallbacks) + throws IOException, UnsupportedCallbackException { for (Callback cb : pCallbacks) { if (cb instanceof NameCallback) { NameCallback ncb = (NameCallback)cb; @@ -323,7 +325,8 @@ public class HttpNegotiateServer { }; final String jaasConfigName = "oracle.test.kerberos.login"; - final String krb5LoginModule = "com.sun.security.auth.module.Krb5LoginModule"; + final String krb5LoginModule + = "com.sun.security.auth.module.Krb5LoginModule"; Configuration loginConfig = new Configuration() { @Override @@ -347,7 +350,8 @@ public class HttpNegotiateServer { // oracle context/subject/login LoginContext context = null; try { - context = new LoginContext("oracle.test.kerberos.login", null, callback, loginConfig); + context = new LoginContext( + "oracle.test.kerberos.login", null, callback, loginConfig); context.login(); } catch (LoginException ex) { @@ -358,29 +362,35 @@ public class HttpNegotiateServer { Subject subject = context.getSubject(); - final PrivilegedExceptionAction test_action = new PrivilegedExceptionAction() { + final PrivilegedExceptionAction test_action + = new PrivilegedExceptionAction() { public Object run() throws Exception { testConnect(); return null; } }; - System.err.println("\n\nExpecting to succeed when executing with the the logged in subject."); + System.err.println("\n\nExpecting to succeed when executing " + + "with the the logged in subject."); try { Subject.doAs(subject, test_action); - System.err.println("\n\nConnection succeed when executing with the the logged in subject."); + System.err.println("\n\nConnection succeed when executing " + + "with the the logged in subject."); } catch (PrivilegedActionException e) { - System.err.println("\n\nFailure unexpected when executing with the the logged in subject."); + System.err.println("\n\nFailure unexpected when executing " + + "with the the logged in subject."); e.printStackTrace(); throw new RuntimeException("Failed to login as subject"); } try { - System.err.println("\n\nExpecting to fail when running with the current user's login."); + System.err.println("\n\nExpecting to fail when running " + + "with the current user's login."); testConnect(); } catch (Exception ex) { - System.err.println("\nConnect failed when running with the current user's login:\n" + ex.getMessage()); + System.err.println("\nConnect failed when running " + + "with the current user's login:\n" + ex.getMessage()); } } @@ -450,8 +460,9 @@ public class HttpNegotiateServer { return m.createCredential( null, GSSCredential.INDEFINITE_LIFETIME, - MyServerAuthenticator.this.scheme.equalsIgnoreCase("Negotiate")? - GSSUtil.GSS_SPNEGO_MECH_OID: + MyServerAuthenticator.this.scheme + .equalsIgnoreCase("Negotiate") ? + GSSUtil.GSS_SPNEGO_MECH_OID : GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY); } @@ -465,7 +476,8 @@ public class HttpNegotiateServer { GSSContext c = null; String auth = exch.getRequestHeaders().getFirst(respHdr); try { - c = (GSSContext)exch.getHttpContext().getAttributes().get("GSSContext"); + c = (GSSContext)exch.getHttpContext() + .getAttributes().get("GSSContext"); if (auth == null) { // First request Headers map = exch.getResponseHeaders(); map.set (reqHdr, scheme); // Challenge! @@ -478,7 +490,8 @@ public class HttpNegotiateServer { exch.getHttpContext().getAttributes().put("GSSContext", c); return new com.sun.net.httpserver.Authenticator.Retry(err); } else { // Later requests - byte[] token = Base64.getMimeDecoder().decode(auth.split(" ")[1]); + byte[] token = Base64.getMimeDecoder() + .decode(auth.split(" ")[1]); token = c.acceptSecContext(token, 0, token.length); Headers map = exch.getResponseHeaders(); map.set (reqHdr, scheme + " " + Base64.getMimeEncoder() From bd0a13fa2174a951612e7ae428ef3739aee8fa42 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Fri, 16 Dec 2016 14:32:51 +0000 Subject: [PATCH 24/45] 8170282: Enable ALPN parameters to be supplied during the TLS handshake Reviewed-by: wetmore, xuelei --- .../classes/javax/net/ssl/SSLEngine.java | 87 ++++++++++++++ .../classes/javax/net/ssl/SSLSocket.java | 87 ++++++++++++++ .../classes/sun/security/ssl/Handshaker.java | 25 ++++ .../sun/security/ssl/SSLEngineImpl.java | 24 +++- .../sun/security/ssl/SSLSocketImpl.java | 22 ++++ .../sun/security/ssl/ServerHandshaker.java | 81 +++++++++---- .../ssl/ALPN/MyX509ExtendedKeyManager.java | 10 +- .../javax/net/ssl/ALPN/SSLEngineAlpnTest.java | 112 ++++++++++++++---- .../net/ssl/ALPN/SSLServerSocketAlpnTest.java | 107 ++++++++++++++--- .../javax/net/ssl/ALPN/SSLSocketAlpnTest.java | 105 +++++++++++++--- 10 files changed, 579 insertions(+), 81 deletions(-) diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngine.java b/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngine.java index 300265cbcd4..2c724f73a67 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngine.java +++ b/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngine.java @@ -27,6 +27,8 @@ package javax.net.ssl; import java.nio.ByteBuffer; import java.nio.ReadOnlyBufferException; +import java.util.List; +import java.util.function.BiFunction; /** @@ -1332,4 +1334,89 @@ public abstract class SSLEngine { public String getHandshakeApplicationProtocol() { throw new UnsupportedOperationException(); } + + /** + * Registers a callback function that selects an application protocol + * value for a SSL/TLS/DTLS handshake. + * The function overrides any values set using + * {@link SSLParameters#setApplicationProtocols + * SSLParameters.setApplicationProtocols} and it supports the following + * type parameters: + *
    + *
    + *
    {@code SSLEngine} + *
    The function's first argument allows the current {@code SSLEngine} + * to be inspected, including the handshake session and configuration + * settings. + *
    {@code List} + *
    The function's second argument lists the application protocol names + * advertised by the TLS peer. + *
    {@code String} + *
    The function's result is an application protocol name, or null to + * indicate that none of the advertised names are acceptable. + * If the return value is null (no value chosen) or is a value that + * was not advertised by the peer, the underlying protocol will + * determine what action to take. (For example, ALPN will send a + * "no_application_protocol" alert and terminate the connection.) + *
    + *
    + * + * For example, the following call registers a callback function that + * examines the TLS handshake parameters and selects an application protocol + * name: + *
    {@code
    +     *     serverEngine.setHandshakeApplicationProtocolSelector(
    +     *         (serverEngine, clientProtocols) -> {
    +     *             SSLSession session = serverEngine.getHandshakeSession();
    +     *             return chooseApplicationProtocol(
    +     *                 serverEngine,
    +     *                 clientProtocols,
    +     *                 session.getProtocol(),
    +     *                 session.getCipherSuite());
    +     *         });
    +     * }
    + * + * @apiNote + * This method should be called by TLS server applications before the TLS + * handshake begins. Also, this {@code SSLEngine} should be configured with + * parameters that are compatible with the application protocol selected by + * the callback function. For example, enabling a poor choice of cipher + * suites could result in no suitable application protocol. + * See {@link SSLParameters}. + * + * @implSpec + * The implementation in this class throws + * {@code UnsupportedOperationException} and performs no other action. + * + * @param selector the callback function, or null to disable the callback + * functionality. + * @throws UnsupportedOperationException if the underlying provider + * does not implement the operation. + * @since 9 + */ + public void setHandshakeApplicationProtocolSelector( + BiFunction, String> selector) { + throw new UnsupportedOperationException(); + } + + /** + * Retrieves the callback function that selects an application protocol + * value during a SSL/TLS/DTLS handshake. + * See {@link #setHandshakeApplicationProtocolSelector + * setHandshakeApplicationProtocolSelector} + * for the function's type parameters. + * + * @implSpec + * The implementation in this class throws + * {@code UnsupportedOperationException} and performs no other action. + * + * @return the callback function, or null if none has been set. + * @throws UnsupportedOperationException if the underlying provider + * does not implement the operation. + * @since 9 + */ + public BiFunction, String> + getHandshakeApplicationProtocolSelector() { + throw new UnsupportedOperationException(); + } } diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/SSLSocket.java b/jdk/src/java.base/share/classes/javax/net/ssl/SSLSocket.java index daaefe08ec7..ebbc9d9eb8d 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/SSLSocket.java +++ b/jdk/src/java.base/share/classes/javax/net/ssl/SSLSocket.java @@ -28,6 +28,8 @@ package javax.net.ssl; import java.io.IOException; import java.net.*; +import java.util.List; +import java.util.function.BiFunction; /** * This class extends Sockets and provides secure @@ -742,4 +744,89 @@ public abstract class SSLSocket extends Socket public String getHandshakeApplicationProtocol() { throw new UnsupportedOperationException(); } + + + /** + * Registers a callback function that selects an application protocol + * value for a SSL/TLS/DTLS handshake. + * The function overrides any values set using + * {@link SSLParameters#setApplicationProtocols + * SSLParameters.setApplicationProtocols} and it supports the following + * type parameters: + *
    + *
    + *
    {@code SSLSocket} + *
    The function's first argument allows the current {@code SSLSocket} + * to be inspected, including the handshake session and configuration + * settings. + *
    {@code List} + *
    The function's second argument lists the application protocol names + * advertised by the TLS peer. + *
    {@code String} + *
    The function's result is an application protocol name, or null to + * indicate that none of the advertised names are acceptable. + * If the return value is null (no value chosen) or is a value that + * was not advertised by the peer, the underlying protocol will + * determine what action to take. (For example, ALPN will send a + * "no_application_protocol" alert and terminate the connection.) + *
    + *
    + * + * For example, the following call registers a callback function that + * examines the TLS handshake parameters and selects an application protocol + * name: + *
    {@code
    +     *     serverSocket.setHandshakeApplicationProtocolSelector(
    +     *         (serverSocket, clientProtocols) -> {
    +     *             SSLSession session = serverSocket.getHandshakeSession();
    +     *             return chooseApplicationProtocol(
    +     *                 serverSocket,
    +     *                 clientProtocols,
    +     *                 session.getProtocol(),
    +     *                 session.getCipherSuite());
    +     *         });
    +     * }
    + * + * @apiNote + * This method should be called by TLS server applications before the TLS + * handshake begins. Also, this {@code SSLSocket} should be configured with + * parameters that are compatible with the application protocol selected by + * the callback function. For example, enabling a poor choice of cipher + * suites could result in no suitable application protocol. + * See {@link SSLParameters}. + * + * @implSpec + * The implementation in this class throws + * {@code UnsupportedOperationException} and performs no other action. + * + * @param selector the callback function, or null to de-register. + * @throws UnsupportedOperationException if the underlying provider + * does not implement the operation. + * @since 9 + */ + public void setHandshakeApplicationProtocolSelector( + BiFunction, String> selector) { + throw new UnsupportedOperationException(); + } + + /** + * Retrieves the callback function that selects an application protocol + * value during a SSL/TLS/DTLS handshake. + * See {@link #setHandshakeApplicationProtocolSelector + * setHandshakeApplicationProtocolSelector} + * for the function's type parameters. + * + * @implSpec + * The implementation in this class throws + * {@code UnsupportedOperationException} and performs no other action. + * + * @return the callback function, or null if none has been set. + * @throws UnsupportedOperationException if the underlying provider + * does not implement the operation. + * @since 9 + */ + public BiFunction, String> + getHandshakeApplicationProtocolSelector() { + throw new UnsupportedOperationException(); + } } diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java index 2e309dc8bb5..f830bc70ce1 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/Handshaker.java @@ -36,6 +36,7 @@ import java.security.AlgorithmConstraints; import java.security.AccessControlContext; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; +import java.util.function.BiFunction; import javax.crypto.*; import javax.crypto.spec.*; @@ -122,6 +123,14 @@ abstract class Handshaker { // Negotiated ALPN value String applicationProtocol = null; + // Application protocol callback function (for SSLEngine) + BiFunction,String> + appProtocolSelectorSSLEngine = null; + + // Application protocol callback function (for SSLSocket) + BiFunction,String> + appProtocolSelectorSSLSocket = null; + // The maximum expected network packet size for SSL/TLS/DTLS records. int maximumPacketSize = 0; @@ -500,6 +509,22 @@ abstract class Handshaker { return applicationProtocol; } + /** + * Sets the Application Protocol selector function for SSLEngine. + */ + void setApplicationProtocolSelectorSSLEngine( + BiFunction,String> selector) { + this.appProtocolSelectorSSLEngine = selector; + } + + /** + * Sets the Application Protocol selector function for SSLSocket. + */ + void setApplicationProtocolSelectorSSLSocket( + BiFunction,String> selector) { + this.appProtocolSelectorSSLSocket = selector; + } + /** * Sets the cipher suites preference. */ diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java index 6aaaf893d80..f9941165771 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLEngineImpl.java @@ -27,8 +27,9 @@ package sun.security.ssl; import java.io.*; import java.nio.*; -import java.util.*; import java.security.*; +import java.util.*; +import java.util.function.BiFunction; import javax.crypto.BadPaddingException; @@ -206,6 +207,10 @@ public final class SSLEngineImpl extends SSLEngine { // The value under negotiation will be obtained from handshaker. String applicationProtocol = null; + // Callback function that selects the application protocol value during + // the SSL/TLS handshake. + BiFunction, String> applicationProtocolSelector; + // Have we been told whether we're client or server? private boolean serverModeSet = false; private boolean roleIsServer; @@ -442,6 +447,8 @@ public final class SSLEngineImpl extends SSLEngine { handshaker.setEnabledCipherSuites(enabledCipherSuites); handshaker.setEnableSessionCreation(enableSessionCreation); handshaker.setApplicationProtocols(applicationProtocols); + handshaker.setApplicationProtocolSelectorSSLEngine( + applicationProtocolSelector); outputRecord.initHandshaker(); } @@ -2264,6 +2271,21 @@ public final class SSLEngineImpl extends SSLEngine { return null; } + @Override + public synchronized void setHandshakeApplicationProtocolSelector( + BiFunction, String> selector) { + applicationProtocolSelector = selector; + if ((handshaker != null) && !handshaker.activated()) { + handshaker.setApplicationProtocolSelectorSSLEngine(selector); + } + } + + @Override + public synchronized BiFunction, String> + getHandshakeApplicationProtocolSelector() { + return this.applicationProtocolSelector; + } + /** * Returns a printable representation of this end of the connection. */ diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java index 880c98a80a4..2e20d538d6e 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java @@ -37,6 +37,7 @@ import java.security.AlgorithmConstraints; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.BiFunction; import javax.crypto.BadPaddingException; import javax.net.ssl.*; @@ -223,6 +224,10 @@ public final class SSLSocketImpl extends BaseSSLSocketImpl { // The value under negotiation will be obtained from handshaker. String applicationProtocol = null; + // Callback function that selects the application protocol value during + // the SSL/TLS handshake. + BiFunction, String> applicationProtocolSelector; + /* * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME * * IMPORTANT STUFF TO UNDERSTANDING THE SYNCHRONIZATION ISSUES. @@ -1370,6 +1375,8 @@ public final class SSLSocketImpl extends BaseSSLSocketImpl { handshaker.setEnabledCipherSuites(enabledCipherSuites); handshaker.setEnableSessionCreation(enableSessionCreation); handshaker.setApplicationProtocols(applicationProtocols); + handshaker.setApplicationProtocolSelectorSSLSocket( + applicationProtocolSelector); } /** @@ -2658,6 +2665,21 @@ public final class SSLSocketImpl extends BaseSSLSocketImpl { return null; } + @Override + public synchronized void setHandshakeApplicationProtocolSelector( + BiFunction, String> selector) { + applicationProtocolSelector = selector; + if ((handshaker != null) && !handshaker.activated()) { + handshaker.setApplicationProtocolSelectorSSLSocket(selector); + } + } + + @Override + public synchronized BiFunction, String> + getHandshakeApplicationProtocolSelector() { + return this.applicationProtocolSelector; + } + // // We allocate a separate thread to deliver handshake completion // events. This ensures that the notifications don't block the diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java index 17777825f3f..4ad18b163e5 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java @@ -34,6 +34,7 @@ import java.security.cert.*; import java.security.interfaces.*; import java.security.spec.ECParameterSpec; import java.math.BigInteger; +import java.util.function.BiFunction; import javax.crypto.SecretKey; import javax.net.ssl.*; @@ -532,31 +533,39 @@ final class ServerHandshaker extends Handshaker { ALPNExtension clientHelloALPN = (ALPNExtension) mesg.extensions.get(ExtensionType.EXT_ALPN); - if ((clientHelloALPN != null) && (localApl.length > 0)) { + // Use the application protocol callback when provided. + // Otherwise use the local list of application protocols. + boolean hasAPCallback = + ((engine != null && appProtocolSelectorSSLEngine != null) || + (conn != null && appProtocolSelectorSSLSocket != null)); - // Intersect the requested and the locally supported, - // and save for later. - String negotiatedValue = null; - List protocols = clientHelloALPN.getPeerAPs(); + if (!hasAPCallback) { + if ((clientHelloALPN != null) && (localApl.length > 0)) { - // Use server preference order - for (String ap : localApl) { - if (protocols.contains(ap)) { - negotiatedValue = ap; - break; + // Intersect the requested and the locally supported, + // and save for later. + String negotiatedValue = null; + List protocols = clientHelloALPN.getPeerAPs(); + + // Use server preference order + for (String ap : localApl) { + if (protocols.contains(ap)) { + negotiatedValue = ap; + break; + } } - } - if (negotiatedValue == null) { - fatalSE(Alerts.alert_no_application_protocol, - new SSLHandshakeException( - "No matching ALPN values")); - } - applicationProtocol = negotiatedValue; + if (negotiatedValue == null) { + fatalSE(Alerts.alert_no_application_protocol, + new SSLHandshakeException( + "No matching ALPN values")); + } + applicationProtocol = negotiatedValue; - } else { - applicationProtocol = ""; - } + } else { + applicationProtocol = ""; + } + } // Otherwise, applicationProtocol will be set by the callback. session = null; // forget about the current session // @@ -892,8 +901,36 @@ final class ServerHandshaker extends Handshaker { } // Prepare the ALPN response - if (applicationProtocol != null && !applicationProtocol.isEmpty()) { - m1.extensions.add(new ALPNExtension(applicationProtocol)); + if (clientHelloALPN != null) { + List peerAPs = clientHelloALPN.getPeerAPs(); + + // check for a callback function + if (hasAPCallback) { + if (conn != null) { + applicationProtocol = + appProtocolSelectorSSLSocket.apply(conn, peerAPs); + } else { + applicationProtocol = + appProtocolSelectorSSLEngine.apply(engine, peerAPs); + } + } + + // check for no-match and that the selected name was also proposed + // by the TLS peer + if (applicationProtocol == null || + (!applicationProtocol.isEmpty() && + !peerAPs.contains(applicationProtocol))) { + + fatalSE(Alerts.alert_no_application_protocol, + new SSLHandshakeException( + "No matching ALPN values")); + + } else if (!applicationProtocol.isEmpty()) { + m1.extensions.add(new ALPNExtension(applicationProtocol)); + } + } else { + // Nothing was negotiated, returned at end of the handshake + applicationProtocol = ""; } if (debug != null && Debug.isOn("handshake")) { diff --git a/jdk/test/javax/net/ssl/ALPN/MyX509ExtendedKeyManager.java b/jdk/test/javax/net/ssl/ALPN/MyX509ExtendedKeyManager.java index d457766d5d4..ecd7dcfc4eb 100644 --- a/jdk/test/javax/net/ssl/ALPN/MyX509ExtendedKeyManager.java +++ b/jdk/test/javax/net/ssl/ALPN/MyX509ExtendedKeyManager.java @@ -34,15 +34,17 @@ public class MyX509ExtendedKeyManager extends X509ExtendedKeyManager { static final String ERROR = "ERROR"; X509ExtendedKeyManager akm; String expectedAP; + boolean doCheck = true; MyX509ExtendedKeyManager(X509ExtendedKeyManager akm) { this.akm = akm; } public MyX509ExtendedKeyManager( - X509ExtendedKeyManager akm, String expectedAP) { + X509ExtendedKeyManager akm, String expectedAP, boolean doCheck) { this.akm = akm; this.expectedAP = expectedAP; + this.doCheck = doCheck; } @@ -104,6 +106,12 @@ public class MyX509ExtendedKeyManager extends X509ExtendedKeyManager { private void checkALPN(String ap) { + if (!doCheck) { + System.out.println("Skipping KeyManager checks " + + "because a callback has been registered"); + return; + } + if (ERROR.equals(expectedAP)) { throw new RuntimeException("Should not reach here"); } diff --git a/jdk/test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java b/jdk/test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java index de4ea6cc0b6..b17da745841 100644 --- a/jdk/test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java +++ b/jdk/test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java @@ -26,23 +26,53 @@ /* * @test - * @bug 8051498 8145849 + * @bug 8051498 8145849 8170282 * @summary JEP 244: TLS Application-Layer Protocol Negotiation Extension * @compile MyX509ExtendedKeyManager.java - * @run main/othervm SSLEngineAlpnTest h2 h2 h2 - * @run main/othervm SSLEngineAlpnTest h2 h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest http/1.1,h2 h2,http/1.1 http/1.1 - * @run main/othervm SSLEngineAlpnTest h4,h3,h2 h1,h2 h2 - * @run main/othervm SSLEngineAlpnTest EMPTY h2,http/1.1 NONE - * @run main/othervm SSLEngineAlpnTest h2 EMPTY NONE - * @run main/othervm SSLEngineAlpnTest H2 h2 ERROR - * @run main/othervm SSLEngineAlpnTest h2 http/1.1 ERROR + * + * @run main/othervm SSLEngineAlpnTest h2 UNUSED h2 h2 + * @run main/othervm SSLEngineAlpnTest h2 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLEngineAlpnTest h2,http/1.1 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLEngineAlpnTest http/1.1,h2 UNUSED h2,http/1.1 http/1.1 + * @run main/othervm SSLEngineAlpnTest h4,h3,h2 UNUSED h1,h2 h2 + * @run main/othervm SSLEngineAlpnTest EMPTY UNUSED h2,http/1.1 NONE + * @run main/othervm SSLEngineAlpnTest h2 UNUSED EMPTY NONE + * @run main/othervm SSLEngineAlpnTest H2 UNUSED h2 ERROR + * @run main/othervm SSLEngineAlpnTest h2 UNUSED http/1.1 ERROR + * + * @run main/othervm SSLEngineAlpnTest UNUSED h2 h2 h2 + * @run main/othervm SSLEngineAlpnTest UNUSED h2 h2,http/1.1 h2 + * @run main/othervm SSLEngineAlpnTest UNUSED h2 http/1.1,h2 h2 + * @run main/othervm SSLEngineAlpnTest UNUSED http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLEngineAlpnTest UNUSED EMPTY h2,http/1.1 NONE + * @run main/othervm SSLEngineAlpnTest UNUSED h2 EMPTY NONE + * @run main/othervm SSLEngineAlpnTest UNUSED H2 h2 ERROR + * @run main/othervm SSLEngineAlpnTest UNUSED h2 http/1.1 ERROR + * + * @run main/othervm SSLEngineAlpnTest h2 h2 h2 h2 + * @run main/othervm SSLEngineAlpnTest H2 h2 h2,http/1.1 h2 + * @run main/othervm SSLEngineAlpnTest h2,http/1.1 http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLEngineAlpnTest http/1.1,h2 h2 h2,http/1.1 h2 + * @run main/othervm SSLEngineAlpnTest EMPTY h2 h2 h2 + * @run main/othervm SSLEngineAlpnTest h2,http/1.1 EMPTY http/1.1 NONE + * @run main/othervm SSLEngineAlpnTest h2,http/1.1 h2 EMPTY NONE + * @run main/othervm SSLEngineAlpnTest UNUSED UNUSED http/1.1,h2 NONE + * @run main/othervm SSLEngineAlpnTest h2 h2 http/1.1 ERROR + * @run main/othervm SSLEngineAlpnTest h2,http/1.1 H2 http/1.1 ERROR */ /** * A simple SSLEngine-based client/server that demonstrates the proposed API * changes for JEP 244 in support of the TLS ALPN extension (RFC 7301). * + * Usage: + * java SSLEngineAlpnTest + * + * where: + * EMPTY indicates that ALPN is disabled + * UNUSED indicates that no ALPN values are supplied (server-side only) + * ERROR indicates that an exception is expected + * NONE indicates that no ALPN is expected + * * This example is based on our standard SSLEngineTemplate. * * The immediate consumer of ALPN will be HTTP/2 (RFC 7540), aka H2. The H2 IETF @@ -98,6 +128,7 @@ import javax.net.ssl.SSLEngineResult.*; import java.io.*; import java.security.*; import java.nio.*; +import java.util.Arrays; public class SSLEngineAlpnTest { @@ -117,6 +148,9 @@ public class SSLEngineAlpnTest { */ private static final boolean debug = false; + private static boolean hasServerAPs; // whether server APs are present + private static boolean hasCallback; // whether a callback is present + private final SSLContext sslc; private SSLEngine clientEngine; // client Engine @@ -157,17 +191,21 @@ public class SSLEngineAlpnTest { if (debug) { System.setProperty("javax.net.debug", "all"); } + System.out.println("Test args: " + Arrays.toString(args)); // Validate parameters - if (args.length != 3) { + if (args.length != 4) { throw new Exception("Invalid number of test parameters"); } - SSLEngineAlpnTest test = new SSLEngineAlpnTest(args[2]); + hasServerAPs = !args[0].equals("UNUSED"); // are server APs being used? + hasCallback = !args[1].equals("UNUSED"); // is callback being used? + + SSLEngineAlpnTest test = new SSLEngineAlpnTest(args[3]); try { - test.runTest(convert(args[0]), convert(args[1]), args[2]); + test.runTest(convert(args[0]), args[1], convert(args[2]), args[3]); } catch (SSLHandshakeException she) { - if (args[2].equals("ERROR")) { + if (args[3].equals("ERROR")) { System.out.println("Caught the expected exception: " + she); } else { throw she; @@ -199,7 +237,8 @@ public class SSLEngineAlpnTest { } kms = new KeyManager[] { new MyX509ExtendedKeyManager( - (X509ExtendedKeyManager) kms[0], expectedAP) }; + (X509ExtendedKeyManager) kms[0], expectedAP, + !hasCallback && hasServerAPs) }; TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); @@ -215,12 +254,15 @@ public class SSLEngineAlpnTest { * Convert a comma-separated list into an array of strings. */ private static String[] convert(String list) { - String[] strings = null; + if (list.equals("UNUSED")) { + return null; + } if (list.equals("EMPTY")) { return new String[0]; } + String[] strings; if (list.indexOf(',') > 0) { strings = list.split(","); } else { @@ -247,12 +289,12 @@ public class SSLEngineAlpnTest { * One could easily separate these phases into separate * sections of code. */ - private void runTest(String[] serverAPs, String[] clientAPs, - String expectedAP) throws Exception { + private void runTest(String[] serverAPs, String callbackAP, + String[] clientAPs, String expectedAP) throws Exception { boolean dataDone = false; - createSSLEngines(serverAPs, clientAPs); + createSSLEngines(serverAPs, callbackAP, clientAPs); createBuffers(); SSLEngineResult clientResult; // results from client's last operation @@ -364,8 +406,8 @@ public class SSLEngineAlpnTest { * Using the SSLContext created during object creation, * create/configure the SSLEngines we'll use for this test. */ - private void createSSLEngines(String[] serverAPs, String[] clientAPs) - throws Exception { + private void createSSLEngines(String[] serverAPs, String callbackAP, + String[] clientAPs) throws Exception { /* * Configure the serverEngine to act as a server in the SSL/TLS * handshake. Also, require SSL client authentication. @@ -385,18 +427,42 @@ public class SSLEngineAlpnTest { */ String[] suites = sslp.getCipherSuites(); sslp.setCipherSuites(suites); - sslp.setApplicationProtocols(serverAPs); + if (serverAPs != null) { + sslp.setApplicationProtocols(serverAPs); + } sslp.setUseCipherSuitesOrder(true); // Set server side order serverEngine.setSSLParameters(sslp); + // check that no callback has been registered + if (serverEngine.getHandshakeApplicationProtocolSelector() != null) { + throw new Exception("getHandshakeApplicationProtocolSelector() " + + "should return null"); + } + + if (hasCallback) { + serverEngine.setHandshakeApplicationProtocolSelector( + (sslEngine, clientProtocols) -> { + return callbackAP.equals("EMPTY") ? "" : callbackAP; + }); + + // check that the callback can be retrieved + if (serverEngine.getHandshakeApplicationProtocolSelector() + == null) { + throw new Exception("getHandshakeApplicationProtocolSelector()" + + " should return non-null"); + } + } + /* * Similar to above, but using client mode instead. */ clientEngine = sslc.createSSLEngine("client", 80); clientEngine.setUseClientMode(true); sslp = clientEngine.getSSLParameters(); - sslp.setApplicationProtocols(clientAPs); + if (clientAPs != null) { + sslp.setApplicationProtocols(clientAPs); + } clientEngine.setSSLParameters(sslp); if ((clientEngine.getHandshakeApplicationProtocol() != null) || diff --git a/jdk/test/javax/net/ssl/ALPN/SSLServerSocketAlpnTest.java b/jdk/test/javax/net/ssl/ALPN/SSLServerSocketAlpnTest.java index a310cbb0336..a9373ed09f9 100644 --- a/jdk/test/javax/net/ssl/ALPN/SSLServerSocketAlpnTest.java +++ b/jdk/test/javax/net/ssl/ALPN/SSLServerSocketAlpnTest.java @@ -26,22 +26,61 @@ /* * @test - * @bug 8051498 8145849 8158978 + * @bug 8051498 8145849 8158978 8170282 * @summary JEP 244: TLS Application-Layer Protocol Negotiation Extension * @compile MyX509ExtendedKeyManager.java - * @run main/othervm SSLServerSocketAlpnTest h2 h2 h2 - * @run main/othervm SSLServerSocketAlpnTest h2 h2,http/1.1 h2 - * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 h2,http/1.1 h2 - * @run main/othervm SSLServerSocketAlpnTest http/1.1,h2 h2,http/1.1 http/1.1 - * @run main/othervm SSLServerSocketAlpnTest h4,h3,h2 h1,h2 h2 - * @run main/othervm SSLServerSocketAlpnTest EMPTY h2,http/1.1 NONE - * @run main/othervm SSLServerSocketAlpnTest h2 EMPTY NONE - * @run main/othervm SSLServerSocketAlpnTest H2 h2 ERROR - * @run main/othervm SSLServerSocketAlpnTest h2 http/1.1 ERROR + * + * @run main/othervm SSLServerSocketAlpnTest h2 UNUSED h2 h2 + * @run main/othervm SSLServerSocketAlpnTest h2 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLServerSocketAlpnTest http/1.1,h2 UNUSED h2,http/1.1 http/1.1 + * @run main/othervm SSLServerSocketAlpnTest h4,h3,h2 UNUSED h1,h2 h2 + * @run main/othervm SSLServerSocketAlpnTest EMPTY UNUSED h2,http/1.1 NONE + * @run main/othervm SSLServerSocketAlpnTest h2 UNUSED EMPTY NONE + * @run main/othervm SSLServerSocketAlpnTest H2 UNUSED h2 ERROR + * @run main/othervm SSLServerSocketAlpnTest h2 UNUSED http/1.1 ERROR + * + * @run main/othervm SSLServerSocketAlpnTest UNUSED h2 h2 h2 + * @run main/othervm SSLServerSocketAlpnTest UNUSED h2 h2,http/1.1 h2 + * @run main/othervm SSLServerSocketAlpnTest UNUSED h2 http/1.1,h2 h2 + * @run main/othervm SSLServerSocketAlpnTest UNUSED http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLServerSocketAlpnTest UNUSED EMPTY h2,http/1.1 NONE + * @run main/othervm SSLServerSocketAlpnTest UNUSED h2 EMPTY NONE + * @run main/othervm SSLServerSocketAlpnTest UNUSED H2 h2 ERROR + * @run main/othervm SSLServerSocketAlpnTest UNUSED h2 http/1.1 ERROR + * + * @run main/othervm SSLServerSocketAlpnTest h2 h2 h2 h2 + * @run main/othervm SSLServerSocketAlpnTest H2 h2 h2,http/1.1 h2 + * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLServerSocketAlpnTest http/1.1,h2 h2 h2,http/1.1 h2 + * @run main/othervm SSLServerSocketAlpnTest EMPTY h2 h2 h2 + * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 EMPTY http/1.1 NONE + * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 h2 EMPTY NONE + * @run main/othervm SSLServerSocketAlpnTest UNUSED UNUSED http/1.1,h2 NONE + * @run main/othervm SSLServerSocketAlpnTest h2 h2 http/1.1 ERROR + * @run main/othervm SSLServerSocketAlpnTest h2,http/1.1 H2 http/1.1 ERROR + * * @author Brad Wetmore */ +/** + * A simple SSLSocket-based client/server that demonstrates the proposed API + * changes for JEP 244 in support of the TLS ALPN extension (RFC 7301). + * + * Usage: + * java SSLServerSocketAlpnTest + * + * + * where: + * EMPTY indicates that ALPN is disabled + * UNUSED indicates that no ALPN values are supplied (server-side only) + * ERROR indicates that an exception is expected + * NONE indicates that no ALPN is expected + * + * This example is based on our standard SSLSocketTemplate. + */ import java.io.*; import java.security.KeyStore; +import java.util.Arrays; import javax.net.ssl.*; @@ -73,6 +112,9 @@ public class SSLServerSocketAlpnTest { static String trustFilename = System.getProperty("test.src", ".") + "/" + pathToStores + "/" + trustStoreFile; + private static boolean hasServerAPs; // whether server APs are present + private static boolean hasCallback; // whether a callback is present + /* * SSLContext */ @@ -89,6 +131,7 @@ public class SSLServerSocketAlpnTest { static boolean debug = false; static String[] serverAPs; + static String callbackAP; static String[] clientAPs; static String expectedAP; @@ -129,7 +172,9 @@ public class SSLServerSocketAlpnTest { sslp.setUseCipherSuitesOrder(true); // Set server side order // Set the ALPN selection. - sslp.setApplicationProtocols(serverAPs); + if (serverAPs != null) { + sslp.setApplicationProtocols(serverAPs); + } sslServerSocket.setSSLParameters(sslp); serverPort = sslServerSocket.getLocalPort(); @@ -146,6 +191,25 @@ public class SSLServerSocketAlpnTest { + "return null before the handshake starts"); } + // check that no callback has been registered + if (sslSocket.getHandshakeApplicationProtocolSelector() != null) { + throw new Exception("getHandshakeApplicationProtocolSelector() " + + "should return null"); + } + + if (hasCallback) { + sslSocket.setHandshakeApplicationProtocolSelector( + (serverSocket, clientProtocols) -> { + return callbackAP.equals("EMPTY") ? "" : callbackAP; + }); + + // check that the callback can be retrieved + if (sslSocket.getHandshakeApplicationProtocolSelector() == null) { + throw new Exception("getHandshakeApplicationProtocolSelector()" + + " should return non-null"); + } + } + sslSocket.startHandshake(); if (sslSocket.getHandshakeApplicationProtocol() != null) { @@ -276,14 +340,19 @@ public class SSLServerSocketAlpnTest { if (debug) { System.setProperty("javax.net.debug", "all"); } + System.out.println("Test args: " + Arrays.toString(args)); // Validate parameters - if (args.length != 3) { + if (args.length != 4) { throw new Exception("Invalid number of test parameters"); } serverAPs = convert(args[0]); - clientAPs = convert(args[1]); - expectedAP = args[2]; + callbackAP = args[1]; + clientAPs = convert(args[2]); + expectedAP = args[3]; + + hasServerAPs = !args[0].equals("UNUSED"); // are server APs being used? + hasCallback = !callbackAP.equals("UNUSED"); // is callback being used? /* * Start the tests. @@ -291,7 +360,7 @@ public class SSLServerSocketAlpnTest { try { new SSLServerSocketAlpnTest(); } catch (SSLHandshakeException she) { - if (args[2].equals("ERROR")) { + if (args[3].equals("ERROR")) { System.out.println("Caught the expected exception: " + she); } else { throw she; @@ -322,7 +391,8 @@ public class SSLServerSocketAlpnTest { } kms = new KeyManager[] { new MyX509ExtendedKeyManager( - (X509ExtendedKeyManager) kms[0], expectedAP) }; + (X509ExtendedKeyManager) kms[0], expectedAP, + !hasCallback && hasServerAPs) }; TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(trustKS); @@ -338,12 +408,15 @@ public class SSLServerSocketAlpnTest { * Convert a comma-separated list into an array of strings. */ private static String[] convert(String list) { - String[] strings; + if (list.equals("UNUSED")) { + return null; + } if (list.equals("EMPTY")) { return new String[0]; } + String[] strings; if (list.indexOf(',') > 0) { strings = list.split(","); } else { diff --git a/jdk/test/javax/net/ssl/ALPN/SSLSocketAlpnTest.java b/jdk/test/javax/net/ssl/ALPN/SSLSocketAlpnTest.java index fd52f251f9d..ef72474f417 100644 --- a/jdk/test/javax/net/ssl/ALPN/SSLSocketAlpnTest.java +++ b/jdk/test/javax/net/ssl/ALPN/SSLSocketAlpnTest.java @@ -26,22 +26,60 @@ /* * @test - * @bug 8051498 8145849 + * @bug 8051498 8145849 8170282 * @summary JEP 244: TLS Application-Layer Protocol Negotiation Extension * @compile MyX509ExtendedKeyManager.java - * @run main/othervm SSLSocketAlpnTest h2 h2 h2 - * @run main/othervm SSLSocketAlpnTest h2 h2,http/1.1 h2 - * @run main/othervm SSLSocketAlpnTest h2,http/1.1 h2,http/1.1 h2 - * @run main/othervm SSLSocketAlpnTest http/1.1,h2 h2,http/1.1 http/1.1 - * @run main/othervm SSLSocketAlpnTest h4,h3,h2 h1,h2 h2 - * @run main/othervm SSLSocketAlpnTest EMPTY h2,http/1.1 NONE - * @run main/othervm SSLSocketAlpnTest h2 EMPTY NONE - * @run main/othervm SSLSocketAlpnTest H2 h2 ERROR - * @run main/othervm SSLSocketAlpnTest h2 http/1.1 ERROR + * + * @run main/othervm SSLSocketAlpnTest h2 UNUSED h2 h2 + * @run main/othervm SSLSocketAlpnTest h2 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLSocketAlpnTest h2,http/1.1 UNUSED h2,http/1.1 h2 + * @run main/othervm SSLSocketAlpnTest http/1.1,h2 UNUSED h2,http/1.1 http/1.1 + * @run main/othervm SSLSocketAlpnTest h4,h3,h2 UNUSED h1,h2 h2 + * @run main/othervm SSLSocketAlpnTest EMPTY UNUSED h2,http/1.1 NONE + * @run main/othervm SSLSocketAlpnTest h2 UNUSED EMPTY NONE + * @run main/othervm SSLSocketAlpnTest H2 UNUSED h2 ERROR + * @run main/othervm SSLSocketAlpnTest h2 UNUSED http/1.1 ERROR + * + * @run main/othervm SSLSocketAlpnTest UNUSED h2 h2 h2 + * @run main/othervm SSLSocketAlpnTest UNUSED h2 h2,http/1.1 h2 + * @run main/othervm SSLSocketAlpnTest UNUSED h2 http/1.1,h2 h2 + * @run main/othervm SSLSocketAlpnTest UNUSED http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLSocketAlpnTest UNUSED EMPTY h2,http/1.1 NONE + * @run main/othervm SSLSocketAlpnTest UNUSED h2 EMPTY NONE + * @run main/othervm SSLSocketAlpnTest UNUSED H2 h2 ERROR + * @run main/othervm SSLSocketAlpnTest UNUSED h2 http/1.1 ERROR + * + * @run main/othervm SSLSocketAlpnTest h2 h2 h2 h2 + * @run main/othervm SSLSocketAlpnTest H2 h2 h2,http/1.1 h2 + * @run main/othervm SSLSocketAlpnTest h2,http/1.1 http/1.1 h2,http/1.1 http/1.1 + * @run main/othervm SSLSocketAlpnTest http/1.1,h2 h2 h2,http/1.1 h2 + * @run main/othervm SSLSocketAlpnTest EMPTY h2 h2 h2 + * @run main/othervm SSLSocketAlpnTest h2,http/1.1 EMPTY http/1.1 NONE + * @run main/othervm SSLSocketAlpnTest h2,http/1.1 h2 EMPTY NONE + * @run main/othervm SSLSocketAlpnTest UNUSED UNUSED http/1.1,h2 NONE + * @run main/othervm SSLSocketAlpnTest h2 h2 http/1.1 ERROR + * @run main/othervm SSLSocketAlpnTest h2,http/1.1 H2 http/1.1 ERROR + * * @author Brad Wetmore */ +/** + * A simple SSLSocket-based client/server that demonstrates the proposed API + * changes for JEP 244 in support of the TLS ALPN extension (RFC 7301). + * + * Usage: + * java SSLSocketAlpnTest + * + * where: + * EMPTY indicates that ALPN is disabled + * UNUSED indicates that no ALPN values are supplied (server-side only) + * ERROR indicates that an exception is expected + * NONE indicates that no ALPN is expected + * + * This example is based on our standard SSLSocketTemplate. + */ import java.io.*; import java.security.KeyStore; +import java.util.Arrays; import javax.net.ssl.*; @@ -73,6 +111,9 @@ public class SSLSocketAlpnTest { static String trustFilename = System.getProperty("test.src", ".") + "/" + pathToStores + "/" + trustStoreFile; + private static boolean hasServerAPs; // whether server APs are present + private static boolean hasCallback; // whether a callback is present + /* * SSLContext */ @@ -89,6 +130,7 @@ public class SSLSocketAlpnTest { static boolean debug = false; static String[] serverAPs; + static String callbackAP; static String[] clientAPs; static String expectedAP; @@ -136,7 +178,9 @@ public class SSLSocketAlpnTest { sslp.setUseCipherSuitesOrder(true); // Set server side order // Set the ALPN selection. - sslp.setApplicationProtocols(serverAPs); + if (serverAPs != null) { + sslp.setApplicationProtocols(serverAPs); + } sslSocket.setSSLParameters(sslp); if (sslSocket.getHandshakeApplicationProtocol() != null) { @@ -144,6 +188,24 @@ public class SSLSocketAlpnTest { + "return null before the handshake starts"); } + // check that no callback has been registered + if (sslSocket.getHandshakeApplicationProtocolSelector() != null) { + throw new Exception("getHandshakeApplicationProtocolSelector() " + + "should return null"); + } + + if (hasCallback) { + sslSocket.setHandshakeApplicationProtocolSelector( + (serverSocket, clientProtocols) -> { + return callbackAP.equals("EMPTY") ? "" : callbackAP; + }); + + // check that the callback can be retrieved + if (sslSocket.getHandshakeApplicationProtocolSelector() == null) { + throw new Exception("getHandshakeApplicationProtocolSelector()" + " should return non-null"); + } + } + sslSocket.startHandshake(); if (sslSocket.getHandshakeApplicationProtocol() != null) { @@ -274,14 +336,19 @@ public class SSLSocketAlpnTest { if (debug) { System.setProperty("javax.net.debug", "all"); } + System.out.println("Test args: " + Arrays.toString(args)); // Validate parameters - if (args.length != 3) { + if (args.length != 4) { throw new Exception("Invalid number of test parameters"); } serverAPs = convert(args[0]); - clientAPs = convert(args[1]); - expectedAP = args[2]; + callbackAP = args[1]; + clientAPs = convert(args[2]); + expectedAP = args[3]; + + hasServerAPs = !args[0].equals("UNUSED"); // are server APs being used? + hasCallback = !callbackAP.equals("UNUSED"); // is callback being used? /* * Start the tests. @@ -289,7 +356,7 @@ public class SSLSocketAlpnTest { try { new SSLSocketAlpnTest(); } catch (SSLHandshakeException she) { - if (args[2].equals("ERROR")) { + if (args[3].equals("ERROR")) { System.out.println("Caught the expected exception: " + she); } else { throw she; @@ -320,7 +387,8 @@ public class SSLSocketAlpnTest { } kms = new KeyManager[] { new MyX509ExtendedKeyManager( - (X509ExtendedKeyManager) kms[0], expectedAP) }; + (X509ExtendedKeyManager) kms[0], expectedAP, + !hasCallback && hasServerAPs) }; TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(trustKS); @@ -336,12 +404,15 @@ public class SSLSocketAlpnTest { * Convert a comma-separated list into an array of strings. */ private static String[] convert(String list) { - String[] strings; + if (list.equals("UNUSED")) { + return null; + } if (list.equals("EMPTY")) { return new String[0]; } + String[] strings; if (list.indexOf(',') > 0) { strings = list.split(","); } else { From 5028479313983966e38053f4575bd01fb49d7c4e Mon Sep 17 00:00:00 2001 From: Chris Hegarty Date: Fri, 16 Dec 2016 17:20:37 +0000 Subject: [PATCH 25/45] 8171377: Add sun.misc.Unsafe::invokeCleaner Reviewed-by: alanb, plevart --- .../classes/jdk/internal/ref/Cleaner.java | 9 -- .../java.base/share/classes/module-info.java | 6 +- .../share/classes/sun/misc/Unsafe.java | 26 ++++ jdk/test/sun/misc/InvokeCleaner.java | 125 ++++++++++++++++++ 4 files changed, 155 insertions(+), 11 deletions(-) create mode 100644 jdk/test/sun/misc/InvokeCleaner.java diff --git a/jdk/src/java.base/share/classes/jdk/internal/ref/Cleaner.java b/jdk/src/java.base/share/classes/jdk/internal/ref/Cleaner.java index 84c0f618a91..5522c0c1ff0 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/ref/Cleaner.java +++ b/jdk/src/java.base/share/classes/jdk/internal/ref/Cleaner.java @@ -58,7 +58,6 @@ import java.security.PrivilegedAction; public class Cleaner extends PhantomReference - implements Runnable { // Dummy reference queue, needed because the PhantomReference constructor @@ -153,12 +152,4 @@ public class Cleaner }}); } } - - @Override public void run() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPackageAccess("jdk.internal.ref"); - this.clean(); - } - } diff --git a/jdk/src/java.base/share/classes/module-info.java b/jdk/src/java.base/share/classes/module-info.java index 74f0bbf6a9d..0c455f827a7 100644 --- a/jdk/src/java.base/share/classes/module-info.java +++ b/jdk/src/java.base/share/classes/module-info.java @@ -180,7 +180,8 @@ module java.base { java.management, jdk.jvmstat; exports jdk.internal.ref to - java.desktop; + java.desktop, + jdk.unsupported; exports jdk.internal.reflect to java.corba, java.logging, @@ -219,7 +220,8 @@ module java.base { exports sun.nio.ch to java.management, jdk.crypto.token, - jdk.sctp; + jdk.sctp, + jdk.unsupported; exports sun.nio.cs to java.desktop, jdk.charsets; diff --git a/jdk/src/jdk.unsupported/share/classes/sun/misc/Unsafe.java b/jdk/src/jdk.unsupported/share/classes/sun/misc/Unsafe.java index 54971142527..641fa2f06cb 100644 --- a/jdk/src/jdk.unsupported/share/classes/sun/misc/Unsafe.java +++ b/jdk/src/jdk.unsupported/share/classes/sun/misc/Unsafe.java @@ -27,8 +27,10 @@ package sun.misc; import jdk.internal.vm.annotation.ForceInline; import jdk.internal.misc.VM; +import jdk.internal.ref.Cleaner; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; +import sun.nio.ch.DirectBuffer; import java.lang.reflect.Field; import java.security.ProtectionDomain; @@ -1228,4 +1230,28 @@ public final class Unsafe { public void fullFence() { theInternalUnsafe.fullFence(); } + + /** + * Invokes the given direct byte buffer's cleaner, if any. + * + * @param directBuffer a direct byte buffer + * @throws NullPointerException if {@code directBuffer} is null + * @throws IllegalArgumentException if {@code directBuffer} is non-direct, + * or is a {@link java.nio.Buffer#slice slice}, or is a + * {@link java.nio.Buffer#duplicate duplicate} + * @since 9 + */ + public void invokeCleaner(java.nio.ByteBuffer directBuffer) { + if (!directBuffer.isDirect()) + throw new IllegalArgumentException("buffer is non-direct"); + + DirectBuffer db = (DirectBuffer)directBuffer; + if (db.attachment() != null) + throw new IllegalArgumentException("duplicate or slice"); + + Cleaner cleaner = db.cleaner(); + if (cleaner != null) { + cleaner.clean(); + } + } } diff --git a/jdk/test/sun/misc/InvokeCleaner.java b/jdk/test/sun/misc/InvokeCleaner.java new file mode 100644 index 00000000000..3367d1574c6 --- /dev/null +++ b/jdk/test/sun/misc/InvokeCleaner.java @@ -0,0 +1,125 @@ +/* + * 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 8171377 + * @summary Basic test for Unsafe::invokeCleaner + * @modules jdk.unsupported + * @run testng/othervm InvokeCleaner + */ + +import java.io.Closeable; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import sun.misc.Unsafe; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +public class InvokeCleaner { + + static Unsafe UNSAFE; + static Path bob = Paths.get("bob"); + static List closeables = new ArrayList<>(); + + @BeforeClass + static void init() throws Exception { + UNSAFE = getUnsafe(); + + byte[] srcData = new byte[20]; + for (int i=0; i<20; i++) + srcData[i] = (byte)i; + Files.write(bob, srcData); + } + + @DataProvider(name = "badBuffers") + static Object[][] createBadBuffers() throws Exception { + FileChannel fc = FileChannel.open(bob); + closeables.add(fc); + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 10); + + return new Object[][] { + { ByteBuffer.allocate(0) }, + { ByteBuffer.allocate(10) }, + { ByteBuffer.allocate(10).duplicate() }, + { ByteBuffer.allocate(10).slice() }, + { ByteBuffer.allocateDirect(10).duplicate() }, + { ByteBuffer.allocateDirect(10).slice() }, + { ByteBuffer.allocateDirect(0).duplicate() }, + { ByteBuffer.allocateDirect(0).slice() }, + { mbb.duplicate() }, + { mbb.slice() } + }; + } + + @Test(dataProvider="badBuffers", + expectedExceptions = IllegalArgumentException.class) + public void badBuffers(ByteBuffer buffer) throws Exception { + UNSAFE.invokeCleaner(buffer); + } + + @DataProvider(name = "goodBuffers") + static Object[][] createGoodBuffers() throws Exception { + FileChannel fc = FileChannel.open(bob); + closeables.add(fc); + MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 10); + mbb.load(); + + return new Object[][] { + { ByteBuffer.allocateDirect(0) }, + { ByteBuffer.allocateDirect(10) }, + { mbb }, + { fc.map(FileChannel.MapMode.READ_ONLY, 1, 11) } + }; + } + + @Test(dataProvider="goodBuffers") + public void goodBuffers(ByteBuffer buffer) throws Exception { + UNSAFE.invokeCleaner(buffer); + } + + @Test(expectedExceptions = NullPointerException.class) + public void npe() throws Exception { + UNSAFE.invokeCleaner(null); + } + + static Unsafe getUnsafe() throws ReflectiveOperationException { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (Unsafe)f.get(null); + } + + @AfterClass + public void cleanup() throws Exception { + for(Closeable fc : closeables) + fc.close(); + } +} From 4484fde33606a6c92220f1eea543bab026d9dfa6 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Fri, 16 Dec 2016 09:42:33 -0800 Subject: [PATCH 26/45] 8171374: GenGraphs should filter the rank grouping if the group is empty Reviewed-by: alanb, psandoz --- .../src/classes/build/tools/jigsaw/GenGraphs.java | 14 +++++++------- 1 file 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 5fbc5b5f9e2..99f6d0f8bd7 100644 --- a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java +++ b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java @@ -214,13 +214,13 @@ public class GenGraphs { // same ranks ranks.stream() - .forEach(group -> out.format("{rank=same %s}%n", - descriptors.stream() - .map(ModuleDescriptor::name) - .filter(group::contains) - .map(mn -> "\"" + mn + "\"") - .collect(joining(",")) - )); + .map(group -> descriptors.stream() + .map(ModuleDescriptor::name) + .filter(group::contains) + .map(mn -> "\"" + mn + "\"") + .collect(joining(","))) + .filter(group -> group.length() > 0) + .forEach(group -> out.format("{rank=same %s}%n", group)); descriptors.stream() .filter(jdkGroup::contains) From 013944c3f4f98333b9b1f7fd2700ca24a99f6dde Mon Sep 17 00:00:00 2001 From: Rob McKenna Date: Fri, 16 Dec 2016 19:15:37 +0000 Subject: [PATCH 27/45] 8169465: Deadlock in com.sun.jndi.ldap.pool.Connections Reviewed-by: dfuchs, vtewari --- .../com/sun/jndi/ldap/pool/Connections.java | 34 +++++++++++-------- .../classes/com/sun/jndi/ldap/pool/Pool.java | 26 +++++++++----- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Connections.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Connections.java index 0e3e1094d67..510b6885a91 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Connections.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Connections.java @@ -27,7 +27,6 @@ package com.sun.jndi.ldap.pool; import java.util.ArrayList; // JDK 1.2 import java.util.List; -import java.util.Iterator; import java.lang.ref.Reference; import java.lang.ref.SoftReference; @@ -290,23 +289,28 @@ final class Connections implements PoolCallback { * @param threshold an entry idle since this time has expired. * @return true if no more connections in list */ - synchronized boolean expire(long threshold) { - Iterator iter = conns.iterator(); - ConnectionDesc entry; - while (iter.hasNext()) { - entry = iter.next(); + boolean expire(long threshold) { + List clonedConns; + synchronized(this) { + clonedConns = new ArrayList<>(conns); + } + List expired = new ArrayList<>(); + + for (ConnectionDesc entry : clonedConns) { + d("expire(): ", entry); if (entry.expire(threshold)) { - d("expire(): removing ", entry); - td("Expired ", entry); - - iter.remove(); // remove from pool - - // Don't need to call notify() because we're - // removing only idle connections. If there were - // idle connections, then there should be no waiters. + expired.add(entry); + td("expire(): Expired ", entry); } } - return conns.isEmpty(); // whether whole list has 'expired' + + synchronized (this) { + conns.removeAll(expired); + // Don't need to call notify() because we're + // removing only idle connections. If there were + // idle connections, then there should be no waiters. + return conns.isEmpty(); // whether whole list has 'expired' + } } /** diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Pool.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Pool.java index a2813bf9233..504c87ddd43 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Pool.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/pool/Pool.java @@ -25,11 +25,11 @@ package com.sun.jndi.ldap.pool; +import java.util.ArrayList; import java.util.Map; import java.util.WeakHashMap; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.LinkedList; import java.io.PrintStream; @@ -166,17 +166,25 @@ final public class Pool { * and removed. */ public void expire(long threshold) { + Collection copy; synchronized (map) { - Iterator iter = map.values().iterator(); - Connections conns; - while (iter.hasNext()) { - conns = iter.next().getConnections(); - if (conns.expire(threshold)) { - d("expire(): removing ", conns); - iter.remove(); - } + copy = new ArrayList<>(map.values()); + } + + ArrayList removed = new ArrayList<>(); + Connections conns; + for (ConnectionsRef ref : copy) { + conns = ref.getConnections(); + if (conns.expire(threshold)) { + d("expire(): removing ", conns); + removed.add(ref); } } + + synchronized (map) { + map.values().removeAll(removed); + } + expungeStaleConnections(); } From be91309965a532db4cf4fa794987753cfacbadd7 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Fri, 16 Dec 2016 21:43:29 -0800 Subject: [PATCH 28/45] 8139688: Port fdlibm exp to Java Reviewed-by: bpb, nadezhin --- jdk/make/mapfiles/libjava/mapfile-vers | 1 - .../share/classes/java/lang/FdLibm.java | 156 +++++++++++++++++- .../share/classes/java/lang/StrictMath.java | 4 +- .../share/native/libjava/StrictMath.c | 8 +- jdk/test/java/lang/StrictMath/ExpTests.java | 147 +++++++++++++++++ .../java/lang/StrictMath/FdlibmTranslit.java | 140 +++++++++++++++- 6 files changed, 441 insertions(+), 15 deletions(-) create mode 100644 jdk/test/java/lang/StrictMath/ExpTests.java diff --git a/jdk/make/mapfiles/libjava/mapfile-vers b/jdk/make/mapfiles/libjava/mapfile-vers index 5d7cc4a655f..65336defa6d 100644 --- a/jdk/make/mapfiles/libjava/mapfile-vers +++ b/jdk/make/mapfiles/libjava/mapfile-vers @@ -150,7 +150,6 @@ SUNWprivate_1.1 { Java_java_lang_StrictMath_atan; Java_java_lang_StrictMath_atan2; Java_java_lang_StrictMath_cos; - Java_java_lang_StrictMath_exp; Java_java_lang_StrictMath_log; Java_java_lang_StrictMath_log10; Java_java_lang_StrictMath_sin; diff --git a/jdk/src/java.base/share/classes/java/lang/FdLibm.java b/jdk/src/java.base/share/classes/java/lang/FdLibm.java index dfecf79bb18..e1d3085ba70 100644 --- a/jdk/src/java.base/share/classes/java/lang/FdLibm.java +++ b/jdk/src/java.base/share/classes/java/lang/FdLibm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -79,7 +79,8 @@ class FdLibm { */ private static double __LO(double x, int low) { long transX = Double.doubleToRawLongBits(x); - return Double.longBitsToDouble((transX & 0xFFFF_FFFF_0000_0000L)|low ); + return Double.longBitsToDouble((transX & 0xFFFF_FFFF_0000_0000L) | + (low & 0x0000_0000_FFFF_FFFFL)); } /** @@ -96,7 +97,8 @@ class FdLibm { */ private static double __HI(double x, int high) { long transX = Double.doubleToRawLongBits(x); - return Double.longBitsToDouble((transX & 0x0000_0000_FFFF_FFFFL)|( ((long)high)) << 32 ); + return Double.longBitsToDouble((transX & 0x0000_0000_FFFF_FFFFL) | + ( ((long)high)) << 32 ); } /** @@ -580,4 +582,152 @@ class FdLibm { return s * z; } } + + /** + * Returns the exponential of x. + * + * Method + * 1. Argument reduction: + * Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2. + * + * Here r will be represented as r = hi-lo for better + * accuracy. + * + * 2. Approximation of exp(r) by a special rational function on + * the interval [0,0.34658]: + * Write + * R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... + * We use a special Reme algorithm on [0,0.34658] to generate + * a polynomial of degree 5 to approximate R. The maximum error + * of this polynomial approximation is bounded by 2**-59. In + * other words, + * R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 + * (where z=r*r, and the values of P1 to P5 are listed below) + * and + * | 5 | -59 + * | 2.0+P1*z+...+P5*z - R(z) | <= 2 + * | | + * The computation of exp(r) thus becomes + * 2*r + * exp(r) = 1 + ------- + * R - r + * r*R1(r) + * = 1 + r + ----------- (for better accuracy) + * 2 - R1(r) + * where + * 2 4 10 + * R1(r) = r - (P1*r + P2*r + ... + P5*r ). + * + * 3. Scale back to obtain exp(x): + * From step 1, we have + * exp(x) = 2^k * exp(r) + * + * Special cases: + * exp(INF) is INF, exp(NaN) is NaN; + * exp(-INF) is 0, and + * for finite argument, only exp(0)=1 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then exp(x) overflow + * if x < -7.45133219101941108420e+02 then exp(x) underflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + static class Exp { + private static final double one = 1.0; + private static final double[] half = {0.5, -0.5,}; + private static final double huge = 1.0e+300; + private static final double twom1000= 0x1.0p-1000; // 9.33263618503218878990e-302 = 2^-1000 + private static final double o_threshold= 0x1.62e42fefa39efp9; // 7.09782712893383973096e+02 + private static final double u_threshold= -0x1.74910d52d3051p9; // -7.45133219101941108420e+02; + private static final double[] ln2HI ={ 0x1.62e42feep-1, // 6.93147180369123816490e-01 + -0x1.62e42feep-1}; // -6.93147180369123816490e-01 + private static final double[] ln2LO ={ 0x1.a39ef35793c76p-33, // 1.90821492927058770002e-10 + -0x1.a39ef35793c76p-33}; // -1.90821492927058770002e-10 + private static final double invln2 = 0x1.71547652b82fep0; // 1.44269504088896338700e+00 + + private static final double P1 = 0x1.555555555553ep-3; // 1.66666666666666019037e-01 + private static final double P2 = -0x1.6c16c16bebd93p-9; // -2.77777777770155933842e-03 + private static final double P3 = 0x1.1566aaf25de2cp-14; // 6.61375632143793436117e-05 + private static final double P4 = -0x1.bbd41c5d26bf1p-20; // -1.65339022054652515390e-06 + private static final double P5 = 0x1.6376972bea4d0p-25; // 4.13813679705723846039e-08 + + // should be able to forgo strictfp due to controlled over/underflow + public static strictfp double compute(double x) { + double y; + double hi = 0.0; + double lo = 0.0; + double c; + double t; + int k = 0; + int xsb; + /*unsigned*/ int hx; + + hx = __HI(x); /* high word of x */ + xsb = (hx >> 31) & 1; /* sign bit of x */ + hx &= 0x7fffffff; /* high word of |x| */ + + /* filter out non-finite argument */ + if (hx >= 0x40862E42) { /* if |x| >= 709.78... */ + if (hx >= 0x7ff00000) { + if (((hx & 0xfffff) | __LO(x)) != 0) + return x + x; /* NaN */ + else + return (xsb == 0) ? x : 0.0; /* exp(+-inf) = {inf, 0} */ + } + if (x > o_threshold) + return huge * huge; /* overflow */ + if (x < u_threshold) // unsigned compare needed here? + return twom1000 * twom1000; /* underflow */ + } + + /* argument reduction */ + if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */ + if(hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + hi = x - ln2HI[xsb]; + lo=ln2LO[xsb]; + k = 1 - xsb - xsb; + } else { + k = (int)(invln2 * x + half[xsb]); + t = k; + hi = x - t*ln2HI[0]; /* t*ln2HI is exact here */ + lo = t*ln2LO[0]; + } + x = hi - lo; + } else if (hx < 0x3e300000) { /* when |x|<2**-28 */ + if (huge + x > one) + return one + x; /* trigger inexact */ + } else { + k = 0; + } + + /* x is now in primary range */ + t = x * x; + c = x - t*(P1 + t*(P2 + t*(P3 + t*(P4 + t*P5)))); + if (k == 0) + return one - ((x*c)/(c - 2.0) - x); + else + y = one - ((lo - (x*c)/(2.0 - c)) - hi); + + if(k >= -1021) { + y = __HI(y, __HI(y) + (k << 20)); /* add k to y's exponent */ + return y; + } else { + y = __HI(y, __HI(y) + ((k + 1000) << 20)); /* add k to y's exponent */ + return y * twom1000; + } + } + } } diff --git a/jdk/src/java.base/share/classes/java/lang/StrictMath.java b/jdk/src/java.base/share/classes/java/lang/StrictMath.java index 1491a8478bc..63d895fa13c 100644 --- a/jdk/src/java.base/share/classes/java/lang/StrictMath.java +++ b/jdk/src/java.base/share/classes/java/lang/StrictMath.java @@ -227,7 +227,9 @@ public final class StrictMath { * @return the value e{@code a}, * where e is the base of the natural logarithms. */ - public static native double exp(double a); + public static double exp(double a) { + return FdLibm.Exp.compute(a); + } /** * Returns the natural logarithm (base e) of a {@code double} diff --git a/jdk/src/java.base/share/native/libjava/StrictMath.c b/jdk/src/java.base/share/native/libjava/StrictMath.c index 6c5ba3151c4..32d42217c5e 100644 --- a/jdk/src/java.base/share/native/libjava/StrictMath.c +++ b/jdk/src/java.base/share/native/libjava/StrictMath.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 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 @@ -64,12 +64,6 @@ Java_java_lang_StrictMath_atan(JNIEnv *env, jclass unused, jdouble d) return (jdouble) jatan((double)d); } -JNIEXPORT jdouble JNICALL -Java_java_lang_StrictMath_exp(JNIEnv *env, jclass unused, jdouble d) -{ - return (jdouble) jexp((double)d); -} - JNIEXPORT jdouble JNICALL Java_java_lang_StrictMath_log(JNIEnv *env, jclass unused, jdouble d) { diff --git a/jdk/test/java/lang/StrictMath/ExpTests.java b/jdk/test/java/lang/StrictMath/ExpTests.java new file mode 100644 index 00000000000..0a2e1f0304d --- /dev/null +++ b/jdk/test/java/lang/StrictMath/ExpTests.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2015, 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 8139688 + * @key randomness + * @library /lib/testlibrary/ + * @build jdk.testlibrary.RandomFactory + * @build Tests + * @build FdlibmTranslit + * @build ExpTests + * @run main ExpTests + * @summary Tests specifically for StrictMath.exp + */ + +import jdk.testlibrary.RandomFactory; + +/** + * The role of this test is to verify that the FDLIBM exp algorithm is + * being used by running golden file style tests on values that may + * vary from one conforming exponential implementation to another. + */ + +public class ExpTests { + private ExpTests(){} + + public static void main(String [] argv) { + int failures = 0; + + failures += testExp(); + failures += testAgainstTranslit(); + + if (failures > 0) { + System.err.println("Testing the exponential incurred " + + failures + " failures."); + throw new RuntimeException(); + } + } + + // From the fdlibm source, the overflow threshold in hex is: + // 0x4086_2E42_FEFA_39EF. + static final double EXP_OVERFLOW_THRESH = Double.longBitsToDouble(0x4086_2E42_FEFA_39EFL); + + // From the fdlibm source, the underflow threshold in hex is: + // 0xc087_4910_D52D_3051L. + static final double EXP_UNDERFLOW_THRESH = Double.longBitsToDouble(0xc087_4910_D52D_3051L); + + static int testExp() { + int failures = 0; + + double [][] testCases = { + // Some of these could be moved to common Math/StrictMath exp testing. + {Double.NaN, Double.NaN}, + {Double.MAX_VALUE, Double.POSITIVE_INFINITY}, + {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, + {Double.NEGATIVE_INFINITY, +0.0}, + {EXP_OVERFLOW_THRESH, 0x1.ffff_ffff_fff2ap1023}, + {Math.nextUp(EXP_OVERFLOW_THRESH), Double.POSITIVE_INFINITY}, + {Math.nextDown(EXP_UNDERFLOW_THRESH), +0.0}, + {EXP_UNDERFLOW_THRESH, +Double.MIN_VALUE}, + }; + + for(double[] testCase: testCases) + failures+=testExpCase(testCase[0], testCase[1]); + + return failures; + } + + static int testExpCase(double input, double expected) { + int failures = 0; + + failures+=Tests.test("StrictMath.exp(double)", input, + StrictMath.exp(input), expected); + return failures; + } + + // Initialize shared random number generator + private static java.util.Random random = RandomFactory.getRandom(); + + /** + * Test StrictMath.exp against transliteration port of exp. + */ + private static int testAgainstTranslit() { + int failures = 0; + + double[] decisionPoints = { + // Near overflow threshold + EXP_OVERFLOW_THRESH - 512*Math.ulp(EXP_OVERFLOW_THRESH), + + // Near underflow threshold + EXP_UNDERFLOW_THRESH - 512*Math.ulp(EXP_UNDERFLOW_THRESH), + + // Straddle algorithm conditional checks + Double.longBitsToDouble(0x4086_2E42_0000_0000L - 512L), + Double.longBitsToDouble(0x3fd6_2e42_0000_0000L - 512L), + Double.longBitsToDouble(0x3FF0_A2B2_0000_0000L - 512L), + Double.longBitsToDouble(0x3e30_0000_0000_0000L - 512L), + + // Other notable points + Double.MIN_NORMAL - Math.ulp(Double.MIN_NORMAL)*512, + -Double.MIN_VALUE*512, + }; + + for (double decisionPoint : decisionPoints) { + double ulp = Math.ulp(decisionPoint); + failures += testRange(decisionPoint - 1024*ulp, ulp, 1_024); + } + + // Try out some random values + for (int i = 0; i < 100; i++) { + double x = Tests.createRandomDouble(random); + failures += testRange(x, Math.ulp(x), 100); + } + + return failures; + } + + private static int testRange(double start, double increment, int count) { + int failures = 0; + double x = start; + for (int i = 0; i < count; i++, x += increment) { + failures += testExpCase(x, FdlibmTranslit.Exp.compute(x)); + } + return failures; + } +} diff --git a/jdk/test/java/lang/StrictMath/FdlibmTranslit.java b/jdk/test/java/lang/StrictMath/FdlibmTranslit.java index 64d4ca6112a..5ad48cb4b44 100644 --- a/jdk/test/java/lang/StrictMath/FdlibmTranslit.java +++ b/jdk/test/java/lang/StrictMath/FdlibmTranslit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -48,7 +48,8 @@ public class FdlibmTranslit { */ private static double __LO(double x, int low) { long transX = Double.doubleToRawLongBits(x); - return Double.longBitsToDouble((transX & 0xFFFF_FFFF_0000_0000L)|low ); + return Double.longBitsToDouble((transX & 0xFFFF_FFFF_0000_0000L) | + (low & 0x0000_0000_FFFF_FFFFL)); } /** @@ -65,7 +66,8 @@ public class FdlibmTranslit { */ private static double __HI(double x, int high) { long transX = Double.doubleToRawLongBits(x); - return Double.longBitsToDouble((transX & 0x0000_0000_FFFF_FFFFL)|( ((long)high)) << 32 ); + return Double.longBitsToDouble((transX & 0x0000_0000_FFFF_FFFFL) | + ( ((long)high)) << 32 ); } public static double hypot(double x, double y) { @@ -250,4 +252,136 @@ public class FdlibmTranslit { return w; } } + + /** + * Returns the exponential of x. + * + * Method + * 1. Argument reduction: + * Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2. + * + * Here r will be represented as r = hi-lo for better + * accuracy. + * + * 2. Approximation of exp(r) by a special rational function on + * the interval [0,0.34658]: + * Write + * R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... + * We use a special Reme algorithm on [0,0.34658] to generate + * a polynomial of degree 5 to approximate R. The maximum error + * of this polynomial approximation is bounded by 2**-59. In + * other words, + * R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 + * (where z=r*r, and the values of P1 to P5 are listed below) + * and + * | 5 | -59 + * | 2.0+P1*z+...+P5*z - R(z) | <= 2 + * | | + * The computation of exp(r) thus becomes + * 2*r + * exp(r) = 1 + ------- + * R - r + * r*R1(r) + * = 1 + r + ----------- (for better accuracy) + * 2 - R1(r) + * where + * 2 4 10 + * R1(r) = r - (P1*r + P2*r + ... + P5*r ). + * + * 3. Scale back to obtain exp(x): + * From step 1, we have + * exp(x) = 2^k * exp(r) + * + * Special cases: + * exp(INF) is INF, exp(NaN) is NaN; + * exp(-INF) is 0, and + * for finite argument, only exp(0)=1 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then exp(x) overflow + * if x < -7.45133219101941108420e+02 then exp(x) underflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + static class Exp { + private static final double one = 1.0; + private static final double[] halF = {0.5,-0.5,}; + private static final double huge = 1.0e+300; + private static final double twom1000= 9.33263618503218878990e-302; /* 2**-1000=0x01700000,0*/ + private static final double o_threshold= 7.09782712893383973096e+02; /* 0x40862E42, 0xFEFA39EF */ + private static final double u_threshold= -7.45133219101941108420e+02; /* 0xc0874910, 0xD52D3051 */ + private static final double[] ln2HI ={ 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */ + -6.93147180369123816490e-01}; /* 0xbfe62e42, 0xfee00000 */ + private static final double[] ln2LO ={ 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */ + -1.90821492927058770002e-10,}; /* 0xbdea39ef, 0x35793c76 */ + private static final double invln2 = 1.44269504088896338700e+00; /* 0x3ff71547, 0x652b82fe */ + private static final double P1 = 1.66666666666666019037e-01; /* 0x3FC55555, 0x5555553E */ + private static final double P2 = -2.77777777770155933842e-03; /* 0xBF66C16C, 0x16BEBD93 */ + private static final double P3 = 6.61375632143793436117e-05; /* 0x3F11566A, 0xAF25DE2C */ + private static final double P4 = -1.65339022054652515390e-06; /* 0xBEBBBD41, 0xC5D26BF1 */ + private static final double P5 = 4.13813679705723846039e-08; /* 0x3E663769, 0x72BEA4D0 */ + + public static strictfp double compute(double x) { + double y,hi=0,lo=0,c,t; + int k=0,xsb; + /*unsigned*/ int hx; + + hx = __HI(x); /* high word of x */ + xsb = (hx>>31)&1; /* sign bit of x */ + hx &= 0x7fffffff; /* high word of |x| */ + + /* filter out non-finite argument */ + if(hx >= 0x40862E42) { /* if |x|>=709.78... */ + if(hx>=0x7ff00000) { + if(((hx&0xfffff)|__LO(x))!=0) + return x+x; /* NaN */ + else return (xsb==0)? x:0.0; /* exp(+-inf)={inf,0} */ + } + if(x > o_threshold) return huge*huge; /* overflow */ + if(x < u_threshold) return twom1000*twom1000; /* underflow */ + } + + /* argument reduction */ + if(hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */ + if(hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + hi = x-ln2HI[xsb]; lo=ln2LO[xsb]; k = 1-xsb-xsb; + } else { + k = (int)(invln2*x+halF[xsb]); + t = k; + hi = x - t*ln2HI[0]; /* t*ln2HI is exact here */ + lo = t*ln2LO[0]; + } + x = hi - lo; + } + else if(hx < 0x3e300000) { /* when |x|<2**-28 */ + if(huge+x>one) return one+x;/* trigger inexact */ + } + else k = 0; + + /* x is now in primary range */ + t = x*x; + c = x - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); + if(k==0) return one-((x*c)/(c-2.0)-x); + else y = one-((lo-(x*c)/(2.0-c))-hi); + if(k >= -1021) { + y = __HI(y, __HI(y) + (k<<20)); /* add k to y's exponent */ + return y; + } else { + y = __HI(y, __HI(y) + ((k+1000)<<20));/* add k to y's exponent */ + return y*twom1000; + } + } + } } From 1a652df64325acc38783cf8a66cbf53fa706bacb Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Sat, 17 Dec 2016 12:59:15 +0100 Subject: [PATCH 29/45] 8171373: Reduce copying during initialization of ModuleHashes Reviewed-by: alanb, mchung, chegar --- .../jdk/internal/module/ModuleHashes.java | 10 ++++------ .../jdk/internal/module/SystemModuleFinder.java | 16 ++++++++++++++-- .../internal/plugins/SystemModulesPlugin.java | 3 ++- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java index 641127b894f..f4e5fcb9fe1 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleHashes.java @@ -149,9 +149,10 @@ public final class ModuleHashes { */ public static class Builder { final String algorithm; - Map nameToHash; + final Map nameToHash; - Builder(String algorithm) { + Builder(String algorithm, int initialCapacity) { + this.nameToHash = new HashMap<>(initialCapacity); this.algorithm = Objects.requireNonNull(algorithm); } @@ -159,9 +160,6 @@ public final class ModuleHashes { * Sets the module hash for the given module name */ public Builder hashForModule(String mn, byte[] hash) { - if (nameToHash == null) - nameToHash = new HashMap<>(); - nameToHash.put(mn, hash); return this; } @@ -170,7 +168,7 @@ public final class ModuleHashes { * Builds a {@code ModuleHashes}. */ public ModuleHashes build() { - if (nameToHash != null) { + if (!nameToHash.isEmpty()) { return new ModuleHashes(algorithm, nameToHash); } else { return null; diff --git a/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java index cb7fa0a8d13..5ec0a62ca69 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java +++ b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java @@ -124,7 +124,7 @@ public class SystemModuleFinder implements ModuleFinder { private final Map nameToModule; // module name to hashes - private final Map hashes = new HashMap<>(); + private final Map hashes; private SystemModuleFinder() { String[] names = moduleNames(); @@ -162,12 +162,24 @@ public class SystemModuleFinder implements ModuleFinder { } } + Map hashes = null; + boolean secondSeen = false; // record the hashes to build HashSupplier for (ModuleHashes mh : recordedHashes) { if (mh != null) { - hashes.putAll(mh.hashes()); + // if only one module contain ModuleHashes, use it + if (hashes == null) { + hashes = mh.hashes(); + } else { + if (!secondSeen) { + hashes = new HashMap<>(hashes); + secondSeen = true; + } + hashes.putAll(mh.hashes()); + } } } + this.hashes = (hashes == null) ? Map.of() : hashes; ModuleReference[] mods = new ModuleReference[n]; diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java index 6adb3d699b5..d7cd59a398e 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java @@ -967,8 +967,9 @@ public final class SystemModulesPlugin implements Plugin { hmv.visitTypeInsn(NEW, MODULE_HASHES_BUILDER); hmv.visitInsn(DUP); hmv.visitLdcInsn(recordedHashes.algorithm()); + pushInt(hmv, ((4 * recordedHashes.names().size()) / 3) + 1); hmv.visitMethodInsn(INVOKESPECIAL, MODULE_HASHES_BUILDER, - "", "(Ljava/lang/String;)V", false); + "", "(Ljava/lang/String;I)V", false); hmv.visitVarInsn(ASTORE, BUILDER_VAR); hmv.visitVarInsn(ALOAD, BUILDER_VAR); } From 41a216c75b5dc8833276b505303e5606360fc37d Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Sun, 18 Dec 2016 18:01:16 -0800 Subject: [PATCH 30/45] 8171133: java/rmi/registry/reexport/Reexport.java, there is a missing case check in createReg(..) Reviewed-by: rriggs --- jdk/test/java/rmi/registry/reexport/Reexport.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/jdk/test/java/rmi/registry/reexport/Reexport.java b/jdk/test/java/rmi/registry/reexport/Reexport.java index a0c9707a74a..1034cad1903 100644 --- a/jdk/test/java/rmi/registry/reexport/Reexport.java +++ b/jdk/test/java/rmi/registry/reexport/Reexport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -67,10 +67,6 @@ public class Reexport { System.err.println("Creating duplicate registry, this should fail..."); reg = createReg(true, regPort); - if (reg != null) { - TestLibrary.bomb("failed was able to duplicate the registry?!?"); - } - // Kill the first registry. System.err.println("Bringing down the first registry"); try { @@ -105,6 +101,9 @@ public class Reexport { try { reg = LocateRegistry.createRegistry(port); + if (remoteOk) { + TestLibrary.bomb("Remote registry is up, an Exception is expected!"); + } } catch (Throwable e) { if (remoteOk) { System.err.println("EXPECTING PORT IN USE EXCEPTION:"); From 29869a6a87d8795a28c4353169d4a7401288372a Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Sun, 18 Dec 2016 18:09:05 -0800 Subject: [PATCH 31/45] 8171298: ProblemList java/rmi/registry/readTest/readTest.sh due to JDK-7146543 Reviewed-by: rriggs --- jdk/test/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 098deca99d6..5df1d73818d 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -205,6 +205,8 @@ sun/rmi/rmic/newrmic/equivalence/run.sh 8145980 generic- java/rmi/transport/dgcDeadLock/DGCDeadLock.java 8029360 macosx-all +java/rmi/registry/readTest/readTest.sh 7146543 generic-all + ############################################################################ # jdk_security From 5f451fea3fb689db9045538030b7b1bfbf3cd9e0 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 19 Dec 2016 09:48:59 +0530 Subject: [PATCH 32/45] 8170289: Re-examine entry point support in jlink Reviewed-by: mchung --- .../jlink/builder/DefaultImageBuilder.java | 54 +++++++++++++------ .../jdk/tools/jlink/internal/JlinkTask.java | 26 ++++++++- .../jdk/tools/jlink/internal/TaskHelper.java | 10 ++-- .../packager/AppRuntimeImageBuilder.java | 7 ++- .../tools/jlink/resources/jlink.properties | 8 +++ jdk/test/tools/jlink/IntegrationTest.java | 2 +- jdk/test/tools/jlink/basic/BasicTest.java | 42 +++++++++++---- 7 files changed, 114 insertions(+), 35 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java index 5e01cc5f9af..27f79dd74d1 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java @@ -130,6 +130,7 @@ public final class DefaultImageBuilder implements ImageBuilder { } private final Path root; + private final Map launchers; private final Path mdir; private final Set modules = new HashSet<>(); private String targetOsName; @@ -140,10 +141,9 @@ public final class DefaultImageBuilder implements ImageBuilder { * @param root The image root directory. * @throws IOException */ - public DefaultImageBuilder(Path root) throws IOException { - Objects.requireNonNull(root); - - this.root = root; + public DefaultImageBuilder(Path root, Map launchers) throws IOException { + this.root = Objects.requireNonNull(root); + this.launchers = Objects.requireNonNull(launchers); this.mdir = root.resolve("lib"); Files.createDirectories(mdir); } @@ -235,7 +235,7 @@ public final class DefaultImageBuilder implements ImageBuilder { // If native files are stripped completely, /bin dir won't exist! // So, don't bother generating launcher scripts. if (Files.isDirectory(bin)) { - prepareApplicationFiles(files, modules); + prepareApplicationFiles(files); } } catch (IOException ex) { throw new PluginException(ex); @@ -246,22 +246,44 @@ public final class DefaultImageBuilder implements ImageBuilder { * Generates launcher scripts. * * @param imageContent The image content. - * @param modules The set of modules that the runtime image contains. * @throws IOException */ - protected void prepareApplicationFiles(ResourcePool imageContent, Set modules) throws IOException { + protected void prepareApplicationFiles(ResourcePool imageContent) throws IOException { // generate launch scripts for the modules with a main class - for (String module : modules) { + for (Map.Entry entry : launchers.entrySet()) { + String launcherEntry = entry.getValue(); + int slashIdx = launcherEntry.indexOf("/"); + String module, mainClassName; + if (slashIdx == -1) { + module = launcherEntry; + mainClassName = null; + } else { + module = launcherEntry.substring(0, slashIdx); + assert !module.isEmpty(); + mainClassName = launcherEntry.substring(slashIdx + 1); + assert !mainClassName.isEmpty(); + } + String path = "/" + module + "/module-info.class"; Optional res = imageContent.findEntry(path); if (!res.isPresent()) { throw new IOException("module-info.class not found for " + module + " module"); } - Optional mainClass; ByteArrayInputStream stream = new ByteArrayInputStream(res.get().contentBytes()); - mainClass = ModuleDescriptor.read(stream).mainClass(); - if (mainClass.isPresent()) { - Path cmd = root.resolve("bin").resolve(module); + Optional mainClass = ModuleDescriptor.read(stream).mainClass(); + if (mainClassName == null && mainClass.isPresent()) { + mainClassName = mainClass.get(); + } + + if (mainClassName != null) { + // make sure main class exists! + if (!imageContent.findEntry("/" + module + "/" + + mainClassName.replace('.', '/') + ".class").isPresent()) { + throw new IllegalArgumentException(module + " does not have main class: " + mainClassName); + } + + String launcherFile = entry.getKey(); + Path cmd = root.resolve("bin").resolve(launcherFile); // generate shell script for Unix platforms StringBuilder sb = new StringBuilder(); sb.append("#!/bin/sh") @@ -272,7 +294,7 @@ public final class DefaultImageBuilder implements ImageBuilder { .append("\n"); sb.append("$DIR/java $JLINK_VM_OPTIONS -m ") .append(module).append('/') - .append(mainClass.get()) + .append(mainClassName) .append(" $@\n"); try (BufferedWriter writer = Files.newBufferedWriter(cmd, @@ -286,7 +308,7 @@ public final class DefaultImageBuilder implements ImageBuilder { } // generate .bat file for Windows if (isWindows()) { - Path bat = root.resolve(BIN_DIRNAME).resolve(module + ".bat"); + Path bat = root.resolve(BIN_DIRNAME).resolve(launcherFile + ".bat"); sb = new StringBuilder(); sb.append("@echo off") .append("\r\n"); @@ -296,7 +318,7 @@ public final class DefaultImageBuilder implements ImageBuilder { .append("\r\n"); sb.append("\"%DIR%\\java\" %JLINK_VM_OPTIONS% -m ") .append(module).append('/') - .append(mainClass.get()) + .append(mainClassName) .append(" %*\r\n"); try (BufferedWriter writer = Files.newBufferedWriter(bat, @@ -305,6 +327,8 @@ public final class DefaultImageBuilder implements ImageBuilder { writer.write(sb.toString()); } } + } else { + throw new IllegalArgumentException(module + " doesn't contain main class & main not specified in command line"); } } } diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java index f5e429fed43..0eb7ade59fa 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java @@ -110,6 +110,27 @@ public class JlinkTask { Path path = Paths.get(arg); task.options.output = path; }, "--output"), + new Option(true, (task, opt, arg) -> { + String[] values = arg.split("="); + // check values + if (values.length != 2 || values[0].isEmpty() || values[1].isEmpty()) { + throw taskHelper.newBadArgs("err.launcher.value.format", arg); + } else { + String commandName = values[0]; + String moduleAndMain = values[1]; + int idx = moduleAndMain.indexOf("/"); + if (idx != -1) { + if (moduleAndMain.substring(0, idx).isEmpty()) { + throw taskHelper.newBadArgs("err.launcher.module.name.empty", arg); + } + + if (moduleAndMain.substring(idx + 1).isEmpty()) { + throw taskHelper.newBadArgs("err.launcher.main.class.empty", arg); + } + } + task.options.launchers.put(commandName, moduleAndMain); + } + }, "--launcher"), new Option(true, (task, opt, arg) -> { if ("little".equals(arg)) { task.options.endian = ByteOrder.LITTLE_ENDIAN; @@ -170,6 +191,7 @@ public class JlinkTask { final Set limitMods = new HashSet<>(); final Set addMods = new HashSet<>(); Path output; + final Map launchers = new HashMap<>(); Path packagedModulesPath; ByteOrder endian = ByteOrder.nativeOrder(); boolean ignoreSigning = false; @@ -287,7 +309,7 @@ public class JlinkTask { } private void postProcessOnly(Path existingImage) throws Exception { - PluginsConfiguration config = taskHelper.getPluginsConfig(null); + PluginsConfiguration config = taskHelper.getPluginsConfig(null, null); ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage); if (img == null) { throw taskHelper.newBadArgs("err.existing.image.invalid"); @@ -336,7 +358,7 @@ public class JlinkTask { // Then create the Plugin Stack ImagePluginStack stack = ImagePluginConfiguration. - parseConfiguration(taskHelper.getPluginsConfig(options.output)); + parseConfiguration(taskHelper.getPluginsConfig(options.output, options.launchers)); //Ask the stack to proceed stack.operate(imageProvider); diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java index 4ae1af566a0..19044f57e65 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java @@ -403,7 +403,7 @@ public final class TaskHelper { return null; } - private PluginsConfiguration getPluginsConfig(Path output + private PluginsConfiguration getPluginsConfig(Path output, Map launchers ) throws IOException, BadArgs { if (output != null) { if (Files.exists(output)) { @@ -440,9 +440,9 @@ public final class TaskHelper { // recreate or postprocessing don't require an output directory. ImageBuilder builder = null; if (output != null) { - builder = new DefaultImageBuilder(output); - + builder = new DefaultImageBuilder(output, launchers); } + return new Jlink.PluginsConfiguration(pluginsList, builder, lastSorter); } @@ -745,9 +745,9 @@ public final class TaskHelper { + bundleHelper.getMessage(key, args)); } - public PluginsConfiguration getPluginsConfig(Path output) + public PluginsConfiguration getPluginsConfig(Path output, Map launchers) throws IOException, BadArgs { - return pluginOptions.getPluginsConfig(output); + return pluginOptions.getPluginsConfig(output, launchers); } public Path getExistingImage() { diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java index 5b06d8135f2..dd0889d3786 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java @@ -49,6 +49,7 @@ import java.util.Set; */ public final class AppRuntimeImageBuilder { private Path outputDir = null; + private Map launchers = Collections.emptyMap(); private List modulePath = null; private Set addModules = null; private Set limitModules = null; @@ -62,6 +63,10 @@ public final class AppRuntimeImageBuilder { outputDir = value; } + public void setLaunchers(Map value) { + launchers = value; + } + public void setModulePath(List value) { modulePath = value; } @@ -120,7 +125,7 @@ public final class AppRuntimeImageBuilder { // build the image Jlink.PluginsConfiguration pluginConfig = new Jlink.PluginsConfiguration( - plugins, new DefaultImageBuilder(outputDir), null); + plugins, new DefaultImageBuilder(outputDir, launchers), null); Jlink jlink = new Jlink(); jlink.build(jlinkConfig, pluginConfig); } diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties index a56c77be18d..5f88c60a6ee 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties @@ -53,6 +53,11 @@ main.opt.limit-modules=\ main.opt.output=\ \ --output Location of output path +main.opt.launcher=\ +\ --launcher = Launcher command name for the module\n\ +\ --launcher =/
    \n\ +\ Launcher command name for the module and the main class + main.command.files=\ \ @ Read options from file @@ -91,6 +96,9 @@ main.extended.help.footer=\ err.unknown.byte.order:unknown byte order {0} +err.launcher.main.class.empty:launcher main class name cannot be empty: {0} +err.launcher.module.name.empty:launcher module name cannot be empty: {0} +err.launcher.value.format:launcher value should be of form =[/]: {0} err.output.must.be.specified:--output must be specified err.modulepath.must.be.specified:--module-path must be specified err.mods.must.be.specified:no modules specified to {0} diff --git a/jdk/test/tools/jlink/IntegrationTest.java b/jdk/test/tools/jlink/IntegrationTest.java index 8d6bb303bdc..e9666676b25 100644 --- a/jdk/test/tools/jlink/IntegrationTest.java +++ b/jdk/test/tools/jlink/IntegrationTest.java @@ -186,7 +186,7 @@ public class IntegrationTest { lst.add(new MyPostProcessor()); } // Image builder - DefaultImageBuilder builder = new DefaultImageBuilder(output); + DefaultImageBuilder builder = new DefaultImageBuilder(output, Collections.emptyMap()); PluginsConfiguration plugins = new Jlink.PluginsConfiguration(lst, builder, null); diff --git a/jdk/test/tools/jlink/basic/BasicTest.java b/jdk/test/tools/jlink/basic/BasicTest.java index 87b2b0ef69d..ae49a01820c 100644 --- a/jdk/test/tools/jlink/basic/BasicTest.java +++ b/jdk/test/tools/jlink/basic/BasicTest.java @@ -87,20 +87,29 @@ public class BasicTest { JarUtils.createJarFile(jarfile, classes); Path image = Paths.get("mysmallimage"); - runJmod(jarfile.toString(), TEST_MODULE); - runJlink(image, TEST_MODULE, "--compress", "2"); - execute(image, TEST_MODULE); + runJmod(jarfile.toString(), TEST_MODULE, true); + runJlink(image, TEST_MODULE, "--compress", "2", "--launcher", "foo=" + TEST_MODULE); + execute(image, "foo"); Files.delete(jmods.resolve(TEST_MODULE + ".jmod")); image = Paths.get("myimage"); - runJmod(classes.toString(), TEST_MODULE); - runJlink(image, TEST_MODULE); - execute(image, TEST_MODULE); + runJmod(classes.toString(), TEST_MODULE, true); + runJlink(image, TEST_MODULE, "--launcher", "bar=" + TEST_MODULE); + execute(image, "bar"); + + Files.delete(jmods.resolve(TEST_MODULE + ".jmod")); + + image = Paths.get("myimage2"); + runJmod(classes.toString(), TEST_MODULE, false /* no ModuleMainClass! */); + // specify main class in --launcher command line + runJlink(image, TEST_MODULE, "--launcher", "bar2=" + TEST_MODULE + "/jdk.test.Test"); + execute(image, "bar2"); + } - private void execute(Path image, String moduleName) throws Throwable { - String cmd = image.resolve("bin").resolve(moduleName).toString(); + private void execute(Path image, String scriptName) throws Throwable { + String cmd = image.resolve("bin").resolve(scriptName).toString(); OutputAnalyzer analyzer; if (System.getProperty("os.name").startsWith("Windows")) { analyzer = ProcessTools.executeProcess("sh.exe", cmd, "1", "2", "3"); @@ -127,14 +136,25 @@ public class BasicTest { } } - private void runJmod(String cp, String modName) { - int rc = JMOD_TOOL.run(System.out, System.out, new String[] { + private void runJmod(String cp, String modName, boolean main) { + int rc; + if (main) { + rc = JMOD_TOOL.run(System.out, System.out, new String[] { "create", "--class-path", cp, "--module-version", "1.0", "--main-class", "jdk.test.Test", + jmods.resolve(modName + ".jmod").toString() + }); + } else { + rc = JMOD_TOOL.run(System.out, System.out, new String[] { + "create", + "--class-path", cp, + "--module-version", "1.0", jmods.resolve(modName + ".jmod").toString(), - }); + }); + } + if (rc != 0) { throw new AssertionError("Jmod failed: rc = " + rc); } From 117454e97927f3caf84b52b5eac13d7c9a24667f Mon Sep 17 00:00:00 2001 From: Christoph Langer Date: Mon, 19 Dec 2016 09:32:10 +0100 Subject: [PATCH 33/45] 8171075: Inet4AddressImpl: Remove duplicate and (no longer used ?) native coding for BSD Reviewed-by: goetz --- .../unix/native/libnet/Inet4AddressImpl.c | 280 +----------------- 1 file changed, 13 insertions(+), 267 deletions(-) diff --git a/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c b/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c index e2e0f10fad9..385b319391b 100644 --- a/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c +++ b/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c @@ -37,273 +37,10 @@ #include "java_net_Inet4AddressImpl.h" -#if defined(__GLIBC__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 601104)) -#define HAS_GLIBC_GETHOSTBY_R 1 -#endif - - -#if defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R) +#if defined(MACOSX) extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6); - -/* Use getaddrinfo(3), which is thread safe */ -/************************************************************************ - * Inet4AddressImpl - */ - -/* - * Class: java_net_Inet4AddressImpl - * Method: getLocalHostName - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL -Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) { - char hostname[NI_MAXHOST+1]; - - hostname[0] = '\0'; - if (gethostname(hostname, NI_MAXHOST)) { - /* Something went wrong, maybe networking is not setup? */ - strcpy(hostname, "localhost"); - } else { - struct addrinfo hints, *res; - int error; - - memset(&hints, 0, sizeof(hints)); - hints.ai_flags = AI_CANONNAME; - hints.ai_family = AF_UNSPEC; - - error = getaddrinfo(hostname, NULL, &hints, &res); - - if (error == 0) { - /* host is known to name service */ - error = getnameinfo(res->ai_addr, - res->ai_addrlen, - hostname, - NI_MAXHOST, - NULL, - 0, - NI_NAMEREQD); - - /* if getnameinfo fails hostname is still the value - from gethostname */ - - freeaddrinfo(res); - } - } - return (*env)->NewStringUTF(env, hostname); -} - -/* - * Find an internet address for a given hostname. Note that this - * code only works for addresses of type INET. The translation - * of %d.%d.%d.%d to an address (int) occurs in java now, so the - * String "host" shouldn't *ever* be a %d.%d.%d.%d string - * - * Class: java_net_Inet4AddressImpl - * Method: lookupAllHostAddr - * Signature: (Ljava/lang/String;)[[B - */ - -JNIEXPORT jobjectArray JNICALL -Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this, - jstring host) { - const char *hostname; - jobject name; - jobjectArray ret = 0; - int retLen = 0; - - int getaddrinfo_error=0; - struct addrinfo hints, *res, *resNew = NULL; - - initInetAddressIDs(env); - JNU_CHECK_EXCEPTION_RETURN(env, NULL); - - if (IS_NULL(host)) { - JNU_ThrowNullPointerException(env, "host is null"); - return 0; - } - hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE); - CHECK_NULL_RETURN(hostname, NULL); - - memset(&hints, 0, sizeof(hints)); - hints.ai_flags = AI_CANONNAME; - hints.ai_family = AF_INET; - - /* - * Workaround for Solaris bug 4160367 - if a hostname contains a - * white space then 0.0.0.0 is returned - */ - if (isspace((unsigned char)hostname[0])) { - JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", - (char *)hostname); - JNU_ReleaseStringPlatformChars(env, host, hostname); - return NULL; - } - - - getaddrinfo_error = getaddrinfo(hostname, NULL, &hints, &res); - -#ifdef MACOSX - if (getaddrinfo_error) { - // If getaddrinfo fails try getifaddrs. - ret = lookupIfLocalhost(env, hostname, JNI_FALSE); - if (ret != NULL || (*env)->ExceptionCheck(env)) { - JNU_ReleaseStringPlatformChars(env, host, hostname); - return ret; - } - } #endif - if (getaddrinfo_error) { - /* report error */ - NET_ThrowUnknownHostExceptionWithGaiError( - env, hostname, getaddrinfo_error); - JNU_ReleaseStringPlatformChars(env, host, hostname); - return NULL; - } else { - int i = 0; - struct addrinfo *itr, *last = NULL, *iterator = res; - while (iterator != NULL) { - int skip = 0; - itr = resNew; - - while (itr != NULL) { - struct sockaddr_in *addr1, *addr2; - - addr1 = (struct sockaddr_in *)iterator->ai_addr; - addr2 = (struct sockaddr_in *)itr->ai_addr; - if (addr1->sin_addr.s_addr == - addr2->sin_addr.s_addr) { - skip = 1; - break; - } - - itr = itr->ai_next; - } - - if (!skip) { - struct addrinfo *next - = (struct addrinfo*) malloc(sizeof(struct addrinfo)); - if (!next) { - JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); - ret = NULL; - goto cleanupAndReturn; - } - memcpy(next, iterator, sizeof(struct addrinfo)); - next->ai_next = NULL; - if (resNew == NULL) { - resNew = next; - } else { - last->ai_next = next; - } - last = next; - i++; - } - iterator = iterator->ai_next; - } - - retLen = i; - iterator = resNew; - i = 0; - - name = (*env)->NewStringUTF(env, hostname); - if (IS_NULL(name)) { - goto cleanupAndReturn; - } - - ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL); - if (IS_NULL(ret)) { - /* we may have memory to free at the end of this */ - goto cleanupAndReturn; - } - - while (iterator != NULL) { - /* We need 4 bytes to store ipv4 address; */ - int len = 4; - - jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID); - if (IS_NULL(iaObj)) { - /* we may have memory to free at the end of this */ - ret = NULL; - goto cleanupAndReturn; - } - setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)(iterator->ai_addr))->sin_addr.s_addr)); - setInetAddress_hostName(env, iaObj, name); - (*env)->SetObjectArrayElement(env, ret, retLen - i -1, iaObj); - i++; - iterator = iterator->ai_next; - } - } - -cleanupAndReturn: - { - struct addrinfo *iterator, *tmp; - iterator = resNew; - while (iterator != NULL) { - tmp = iterator; - iterator = iterator->ai_next; - free(tmp); - } - JNU_ReleaseStringPlatformChars(env, host, hostname); - } - - freeaddrinfo(res); - - return ret; - -} - -/* - * Class: java_net_Inet4AddressImpl - * Method: getHostByAddr - * Signature: (I)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL -Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this, - jbyteArray addrArray) { - jstring ret = NULL; - - char host[NI_MAXHOST+1]; - jfieldID fid; - int error = 0; - jint family; - struct sockaddr *him ; - int len = 0; - jbyte caddr[4]; - jint addr; - - struct sockaddr_in him4; - struct sockaddr *sa; - - /* - * For IPv4 addresses construct a sockaddr_in structure. - */ - (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr); - addr = ((caddr[0]<<24) & 0xff000000); - addr |= ((caddr[1] <<16) & 0xff0000); - addr |= ((caddr[2] <<8) & 0xff00); - addr |= (caddr[3] & 0xff); - memset((char *) &him4, 0, sizeof(him4)); - him4.sin_addr.s_addr = htonl(addr); - him4.sin_family = AF_INET; - sa = (struct sockaddr *) &him4; - len = sizeof(him4); - - error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD); - - if (!error) { - ret = (*env)->NewStringUTF(env, host); - } - - if (ret == NULL) { - JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL); - } - - return ret; - -} - -#else /* defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R) */ - /* the initial size of our hostent buffers */ #ifndef NI_MAXHOST #define NI_MAXHOST 1025 @@ -405,6 +142,17 @@ Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this, error = getaddrinfo(hostname, NULL, &hints, &res); +#ifdef MACOSX + if (error) { + // If getaddrinfo fails try getifaddrs, see bug 8170910. + ret = lookupIfLocalhost(env, hostname, JNI_FALSE); + if (ret != NULL || (*env)->ExceptionCheck(env)) { + JNU_ReleaseStringPlatformChars(env, host, hostname); + return ret; + } + } +#endif + if (error) { /* report error */ NET_ThrowUnknownHostExceptionWithGaiError(env, hostname, error); @@ -475,7 +223,7 @@ Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this, } } - cleanupAndReturn: +cleanupAndReturn: { struct addrinfo *iterator, *tmp; iterator = resNew; @@ -535,8 +283,6 @@ Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this, return ret; } -#endif /* _ALLBSD_SOURCE */ - #define SET_NONBLOCKING(fd) { \ int flags = fcntl(fd, F_GETFL); \ flags |= O_NONBLOCK; \ From 88d37ce5fd799034a114358a5d687f8cca4c1aa6 Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Tue, 13 Dec 2016 17:02:00 +0300 Subject: [PATCH 34/45] 8170864: java/net/URLClassLoader/closetest/CloseTest.java has undeclared dependencies Reviewed-by: chegar, dfuchs --- .../URLClassLoader/closetest/CloseTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/jdk/test/java/net/URLClassLoader/closetest/CloseTest.java b/jdk/test/java/net/URLClassLoader/closetest/CloseTest.java index 7a4ce531b0b..47feb498c51 100644 --- a/jdk/test/java/net/URLClassLoader/closetest/CloseTest.java +++ b/jdk/test/java/net/URLClassLoader/closetest/CloseTest.java @@ -21,10 +21,11 @@ * questions. */ -/** +/* * @test * @bug 4167874 - * @modules jdk.httpserver + * @modules java.logging + * jdk.httpserver * @library ../../../../com/sun/net/httpserver * @library /lib/testlibrary * @build FileServerHandler jdk.testlibrary.FileUtils @@ -33,10 +34,13 @@ * @summary URL-downloaded jar files can consume all available file descriptors */ -import java.io.*; -import java.net.*; -import java.lang.reflect.*; -import com.sun.net.httpserver.*; +import java.io.File; +import java.lang.reflect.Method; +import java.net.URLClassLoader; +import java.net.InetSocketAddress; +import java.net.URL; +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpServer; public class CloseTest extends Common { @@ -130,7 +134,7 @@ public class CloseTest extends Common { // load tests loadClass ("com.foo.TestClass1", loader, false); loadClass ("com.foo.TestClass", loader, true); - loadClass ("java.sql.Array", loader, true); + loadClass ("java.util.ArrayList", loader, true); // now check we can delete the path rm_minus_rf (new File(name)); From 7b6589033607043e222976a7a94746af781af917 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 14 Dec 2016 19:45:59 +0530 Subject: [PATCH 35/45] 8171070: Test ModuleNamesOrderTest.java fails Reviewed-by: alanb, jlaskey --- jdk/test/ProblemList.txt | 1 - jdk/test/tools/jlink/ModuleNamesOrderTest.java | 6 ++++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 75e81031945..4329ffb0f27 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -261,7 +261,6 @@ tools/jimage/JImageExtractTest.java 8169713 generic- tools/jimage/JImageListTest.java 8169713 generic-all tools/jimage/JImageVerifyTest.java 8169713 generic-all -tools/jlink/ModuleNamesOrderTest.java 8171070 generic-all tools/jlink/multireleasejar/JLinkMultiReleaseJarTest.java 8169971 windows-x64 diff --git a/jdk/test/tools/jlink/ModuleNamesOrderTest.java b/jdk/test/tools/jlink/ModuleNamesOrderTest.java index 09a4dfd9f79..20b642d1ef3 100644 --- a/jdk/test/tools/jlink/ModuleNamesOrderTest.java +++ b/jdk/test/tools/jlink/ModuleNamesOrderTest.java @@ -38,6 +38,12 @@ import tests.JImageGenerator; * @bug 8168925 * @summary MODULES property should be topologically ordered and space-separated list * @library ../lib + * @modules java.base/jdk.internal.jimage + * jdk.jdeps/com.sun.tools.classfile + * jdk.jlink/jdk.tools.jlink.internal + * jdk.jlink/jdk.tools.jmod + * jdk.jlink/jdk.tools.jimage + * jdk.compiler * @build tests.* * @run main ModuleNamesOrderTest */ From ef12502b696efacf0fbd4c2c242ffad6d3d8e87d Mon Sep 17 00:00:00 2001 From: Adam Petcher Date: Wed, 14 Dec 2016 10:22:02 -0500 Subject: [PATCH 36/45] 8165751: NPE hit with java.security.debug=provider Reviewed-by: mullan, weijun --- .../classes/java/security/Signature.java | 12 ++- .../java/security/Signature/NoProvider.java | 99 +++++++++++++++++++ 2 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 jdk/test/java/security/Signature/NoProvider.java diff --git a/jdk/src/java.base/share/classes/java/security/Signature.java b/jdk/src/java.base/share/classes/java/security/Signature.java index df326f4a280..df5350e99f1 100644 --- a/jdk/src/java.base/share/classes/java/security/Signature.java +++ b/jdk/src/java.base/share/classes/java/security/Signature.java @@ -452,6 +452,10 @@ public abstract class Signature extends SignatureSpi { return this.provider; } + private String getProviderName() { + return (provider == null) ? "(no provider)" : provider.getName(); + } + void chooseFirstProvider() { // empty, overridden in Delegate } @@ -473,7 +477,7 @@ public abstract class Signature extends SignatureSpi { if (!skipDebug && pdebug != null) { pdebug.println("Signature." + algorithm + - " verification algorithm from: " + this.provider.getName()); + " verification algorithm from: " + getProviderName()); } } @@ -522,7 +526,7 @@ public abstract class Signature extends SignatureSpi { if (!skipDebug && pdebug != null) { pdebug.println("Signature." + algorithm + - " verification algorithm from: " + this.provider.getName()); + " verification algorithm from: " + getProviderName()); } } @@ -543,7 +547,7 @@ public abstract class Signature extends SignatureSpi { if (!skipDebug && pdebug != null) { pdebug.println("Signature." + algorithm + - " signing algorithm from: " + this.provider.getName()); + " signing algorithm from: " + getProviderName()); } } @@ -566,7 +570,7 @@ public abstract class Signature extends SignatureSpi { if (!skipDebug && pdebug != null) { pdebug.println("Signature." + algorithm + - " signing algorithm from: " + this.provider.getName()); + " signing algorithm from: " + getProviderName()); } } diff --git a/jdk/test/java/security/Signature/NoProvider.java b/jdk/test/java/security/Signature/NoProvider.java new file mode 100644 index 00000000000..4fa4499aaa6 --- /dev/null +++ b/jdk/test/java/security/Signature/NoProvider.java @@ -0,0 +1,99 @@ +/* + * 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 8165751 + * @summary Verify that that a subclass of Signature that does not contain a + * provider can be used verify. + * @run main/othervm -Djava.security.debug=provider NoProvider + */ + +import java.security.*; + +public class NoProvider { + + private static class NoProviderPublicKey implements PublicKey { + + public String getAlgorithm() { + return "NoProvider"; + } + public String getFormat() { + return "none"; + } + public byte[] getEncoded() { + return new byte[1]; + } + } + + private static class NoProviderSignature extends Signature { + + public NoProviderSignature() { + super("NoProvider"); + } + + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException { + // do nothing + } + + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException { + // do nothing + } + + protected void engineUpdate(byte b) throws SignatureException { + // do nothing + } + + protected void engineUpdate(byte[] b, int off, int len) + throws SignatureException { + // do nothing + } + + protected byte[] engineSign() throws SignatureException { + return new byte[1]; + } + + protected boolean engineVerify(byte[] sigBytes) + throws SignatureException { + return false; + } + + @Deprecated + protected void engineSetParameter(String param, Object value) + throws InvalidParameterException { + // do nothing + } + + @Deprecated + protected Object engineGetParameter(String param) + throws InvalidParameterException { + return null; + } + } + + public static void main(String[] args) throws Exception { + new NoProviderSignature().initVerify(new NoProviderPublicKey()); + } +} From 5e0f6d2b0cb8bcb9b9151d0a923dd53a883df92b Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Wed, 14 Dec 2016 19:46:21 +0100 Subject: [PATCH 37/45] 8171245: Solaris builds fails after JDK-8170663 Reviewed-by: naoto --- .../unix/native/libjli/java_md_solinux.c | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c index 538c0a7d249..9099d37af00 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c +++ b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c @@ -515,23 +515,23 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, #endif /* __solaris__ */ /* runpath contains current effective LD_LIBRARY_PATH setting */ - - char *new_jvmpath = JLI_StringDup(jvmpath); - new_runpath_size = ((runpath != NULL) ? JLI_StrLen(runpath) : 0) + - 2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) + + { /* New scope to declare local variable */ + char *new_jvmpath = JLI_StringDup(jvmpath); + new_runpath_size = ((runpath != NULL) ? JLI_StrLen(runpath) : 0) + + 2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) + #ifdef AIX - /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */ - JLI_StrLen(jrepath) + JLI_StrLen(arch) + JLI_StrLen("/lib//jli:") + + /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */ + JLI_StrLen(jrepath) + JLI_StrLen(arch) + JLI_StrLen("/lib//jli:") + #endif - JLI_StrLen(new_jvmpath) + 52; - new_runpath = JLI_MemAlloc(new_runpath_size); - newpath = new_runpath + JLI_StrLen(LD_LIBRARY_PATH "="); + JLI_StrLen(new_jvmpath) + 52; + new_runpath = JLI_MemAlloc(new_runpath_size); + newpath = new_runpath + JLI_StrLen(LD_LIBRARY_PATH "="); - /* - * Create desired LD_LIBRARY_PATH value for target data model. - */ - { + /* + * Create desired LD_LIBRARY_PATH value for target data model. + */ + { /* remove the name of the .so from the JVM path */ lastslash = JLI_StrRChr(new_jvmpath, '/'); if (lastslash) @@ -572,6 +572,7 @@ CreateExecutionEnvironment(int *pargc, char ***pargv, JLI_MemFree(new_runpath); return; } + } } /* From f083b7e6569b630dae453fc46f92047c5c7de1fb Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Wed, 14 Dec 2016 10:51:13 -0800 Subject: [PATCH 38/45] 8171201: Drop java.compact$N aggregator modules 8171202: Rename jdk.crypto.pkcs11 and jdk.pack200 to end with Java letters Reviewed-by: alanb, erikj --- ...o.pkcs11.gmk => Copy-jdk.crypto.token.gmk} | 2 +- ...-jdk.pack200.gmk => Launcher-jdk.pack.gmk} | 8 +-- ...to.pkcs11.gmk => Lib-jdk.crypto.token.gmk} | 6 +- .../{Lib-jdk.pack200.gmk => Lib-jdk.pack.gmk} | 6 +- .../classes/build/tools/jigsaw/GenGraphs.java | 63 ++++++++++++++----- .../java.base/share/classes/module-info.java | 16 ++--- .../share/lib/security/default.policy | 2 +- .../share/classes/module-info.java | 33 ---------- .../share/classes/module-info.java | 35 ----------- .../share/classes/module-info.java | 42 ------------- .../java.se/share/classes/module-info.java | 21 +++++-- .../share/classes/module-info.java | 2 +- .../classes/sun/security/pkcs11/Config.java | 0 .../classes/sun/security/pkcs11/KeyCache.java | 0 .../sun/security/pkcs11/P11Cipher.java | 0 .../sun/security/pkcs11/P11DHKeyFactory.java | 0 .../sun/security/pkcs11/P11DSAKeyFactory.java | 0 .../sun/security/pkcs11/P11Digest.java | 0 .../security/pkcs11/P11ECDHKeyAgreement.java | 0 .../sun/security/pkcs11/P11ECKeyFactory.java | 0 .../classes/sun/security/pkcs11/P11Key.java | 0 .../sun/security/pkcs11/P11KeyAgreement.java | 0 .../sun/security/pkcs11/P11KeyFactory.java | 0 .../sun/security/pkcs11/P11KeyGenerator.java | 0 .../security/pkcs11/P11KeyPairGenerator.java | 0 .../sun/security/pkcs11/P11KeyStore.java | 0 .../classes/sun/security/pkcs11/P11Mac.java | 0 .../sun/security/pkcs11/P11RSACipher.java | 0 .../sun/security/pkcs11/P11RSAKeyFactory.java | 0 .../security/pkcs11/P11SecretKeyFactory.java | 0 .../sun/security/pkcs11/P11SecureRandom.java | 0 .../sun/security/pkcs11/P11Signature.java | 0 .../pkcs11/P11TlsKeyMaterialGenerator.java | 0 .../pkcs11/P11TlsMasterSecretGenerator.java | 0 .../security/pkcs11/P11TlsPrfGenerator.java | 0 .../P11TlsRsaPremasterSecretGenerator.java | 0 .../classes/sun/security/pkcs11/P11Util.java | 0 .../classes/sun/security/pkcs11/Secmod.java | 0 .../classes/sun/security/pkcs11/Session.java | 0 .../sun/security/pkcs11/SessionManager.java | 0 .../sun/security/pkcs11/SunPKCS11.java | 0 .../sun/security/pkcs11/TemplateManager.java | 0 .../classes/sun/security/pkcs11/Token.java | 0 .../pkcs11/wrapper/CK_AES_CTR_PARAMS.java | 0 .../security/pkcs11/wrapper/CK_ATTRIBUTE.java | 0 .../pkcs11/wrapper/CK_CREATEMUTEX.java | 0 .../pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java | 0 .../sun/security/pkcs11/wrapper/CK_DATE.java | 0 .../pkcs11/wrapper/CK_DESTROYMUTEX.java | 0 .../wrapper/CK_ECDH1_DERIVE_PARAMS.java | 0 .../wrapper/CK_ECDH2_DERIVE_PARAMS.java | 0 .../sun/security/pkcs11/wrapper/CK_INFO.java | 0 .../security/pkcs11/wrapper/CK_LOCKMUTEX.java | 0 .../security/pkcs11/wrapper/CK_MECHANISM.java | 0 .../pkcs11/wrapper/CK_MECHANISM_INFO.java | 0 .../security/pkcs11/wrapper/CK_NOTIFY.java | 0 .../pkcs11/wrapper/CK_PBE_PARAMS.java | 0 .../pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java | 0 .../wrapper/CK_RSA_PKCS_OAEP_PARAMS.java | 0 .../wrapper/CK_RSA_PKCS_PSS_PARAMS.java | 0 .../pkcs11/wrapper/CK_SESSION_INFO.java | 0 .../security/pkcs11/wrapper/CK_SLOT_INFO.java | 0 .../pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java | 0 .../wrapper/CK_SSL3_KEY_MAT_PARAMS.java | 0 .../CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java | 0 .../pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java | 0 .../pkcs11/wrapper/CK_TLS_PRF_PARAMS.java | 0 .../pkcs11/wrapper/CK_TOKEN_INFO.java | 0 .../pkcs11/wrapper/CK_UNLOCKMUTEX.java | 0 .../security/pkcs11/wrapper/CK_VERSION.java | 0 .../wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java | 0 .../wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java | 0 .../security/pkcs11/wrapper/Constants.java | 0 .../security/pkcs11/wrapper/Functions.java | 0 .../sun/security/pkcs11/wrapper/PKCS11.java | 0 .../pkcs11/wrapper/PKCS11Constants.java | 0 .../pkcs11/wrapper/PKCS11Exception.java | 0 .../wrapper/PKCS11RuntimeException.java | 0 .../share/legal/pkcs11cryptotoken.md | 0 .../share/legal/pkcs11wrapper.md | 0 .../share/native/libj2pkcs11/j2secmod.c | 0 .../share/native/libj2pkcs11/j2secmod.h | 0 .../share/native/libj2pkcs11/p11_convert.c | 0 .../share/native/libj2pkcs11/p11_crypt.c | 0 .../share/native/libj2pkcs11/p11_digest.c | 0 .../share/native/libj2pkcs11/p11_dual.c | 0 .../share/native/libj2pkcs11/p11_general.c | 0 .../share/native/libj2pkcs11/p11_keymgmt.c | 0 .../share/native/libj2pkcs11/p11_mutex.c | 0 .../share/native/libj2pkcs11/p11_objmgmt.c | 0 .../share/native/libj2pkcs11/p11_sessmgmt.c | 0 .../share/native/libj2pkcs11/p11_sign.c | 0 .../share/native/libj2pkcs11/p11_util.c | 0 .../share/native/libj2pkcs11/pkcs-11v2-20a3.h | 0 .../share/native/libj2pkcs11/pkcs11.h | 0 .../share/native/libj2pkcs11/pkcs11f.h | 0 .../share/native/libj2pkcs11/pkcs11t.h | 0 .../share/native/libj2pkcs11/pkcs11wrapper.h | 0 .../conf/security/sunpkcs11-solaris.cfg | 0 .../unix/native/libj2pkcs11/j2secmod_md.c | 0 .../unix/native/libj2pkcs11/j2secmod_md.h | 0 .../unix/native/libj2pkcs11/p11_md.c | 0 .../unix/native/libj2pkcs11/p11_md.h | 0 .../windows/native/libj2pkcs11/j2secmod_md.c | 0 .../windows/native/libj2pkcs11/j2secmod_md.h | 0 .../windows/native/libj2pkcs11/p11_md.c | 0 .../windows/native/libj2pkcs11/p11_md.h | 0 .../share/classes/module-info.java | 2 +- .../share/native/common-unpack/bands.cpp | 0 .../share/native/common-unpack/bands.h | 0 .../share/native/common-unpack/bytes.cpp | 0 .../share/native/common-unpack/bytes.h | 0 .../share/native/common-unpack/coding.cpp | 0 .../share/native/common-unpack/coding.h | 0 .../share/native/common-unpack/constants.h | 0 .../share/native/common-unpack/defines.h | 0 .../share/native/common-unpack/unpack.cpp | 0 .../share/native/common-unpack/unpack.h | 0 .../share/native/common-unpack/utils.cpp | 0 .../share/native/common-unpack/utils.h | 0 .../share/native/common-unpack/zip.cpp | 0 .../share/native/common-unpack/zip.h | 0 .../share/native/libunpack/jni.cpp | 0 .../share/native/unpack200/main.cpp | 0 .../unpack200/unpack200_proto.exe.manifest | 0 .../CheckSecurityProvider.java | 4 +- .../internal/misc/VM/RuntimeArguments.java | 5 +- .../modules/etc/VerifyModuleDelegation.java | 23 +------ jdk/test/sun/security/ec/TestEC.java | 4 +- .../security/pkcs11/Cipher/ReinitCipher.java | 2 +- .../pkcs11/Cipher/TestPKCS5PaddingError.java | 2 +- .../security/pkcs11/Cipher/TestRSACipher.java | 2 +- .../pkcs11/Cipher/TestRSACipherWrap.java | 2 +- .../pkcs11/Cipher/TestRawRSACipher.java | 2 +- .../pkcs11/Cipher/TestSymmCiphers.java | 2 +- .../pkcs11/Cipher/TestSymmCiphersNoPad.java | 2 +- .../pkcs11/KeyAgreement/SupportedDHKeys.java | 2 +- .../security/pkcs11/KeyAgreement/TestDH.java | 2 +- .../pkcs11/KeyAgreement/TestInterop.java | 2 +- .../pkcs11/KeyAgreement/TestShort.java | 2 +- .../KeyAgreement/UnsupportedDHKeys.java | 2 +- .../pkcs11/KeyGenerator/DESParity.java | 2 +- .../pkcs11/KeyGenerator/TestKeyGenerator.java | 2 +- .../pkcs11/KeyPairGenerator/TestDH2048.java | 2 +- jdk/test/sun/security/pkcs11/Mac/MacKAT.java | 2 +- .../sun/security/pkcs11/Mac/MacSameTest.java | 2 +- .../sun/security/pkcs11/Mac/ReinitMac.java | 2 +- .../pkcs11/MessageDigest/ByteBuffers.java | 2 +- .../pkcs11/MessageDigest/DigestKAT.java | 2 +- .../pkcs11/MessageDigest/ReinitDigest.java | 2 +- .../pkcs11/MessageDigest/TestCloning.java | 2 +- .../security/pkcs11/Provider/Absolute.java | 2 +- jdk/test/sun/security/pkcs11/SampleTest.java | 2 +- .../security/pkcs11/Secmod/AddPrivateKey.java | 2 +- .../pkcs11/Secmod/AddTrustedCert.java | 2 +- .../sun/security/pkcs11/Secmod/Crypto.java | 2 +- .../security/pkcs11/Secmod/GetPrivateKey.java | 2 +- .../pkcs11/Secmod/JksSetPrivateKey.java | 2 +- .../security/pkcs11/Secmod/LoadKeystore.java | 2 +- .../security/pkcs11/Secmod/TrustAnchors.java | 2 +- .../security/pkcs11/SecureRandom/Basic.java | 2 +- .../SecureRandom/TestDeserialization.java | 2 +- .../pkcs11/Serialize/SerializeProvider.java | 2 +- .../pkcs11/Signature/ByteBuffers.java | 2 +- .../pkcs11/Signature/ReinitSignature.java | 2 +- .../security/pkcs11/Signature/TestDSA.java | 2 +- .../pkcs11/Signature/TestDSAKeyLength.java | 2 +- .../pkcs11/Signature/TestRSAKeyLength.java | 2 +- .../security/pkcs11/ec/ReadCertificates.java | 2 +- .../sun/security/pkcs11/ec/ReadPKCS12.java | 2 +- .../sun/security/pkcs11/ec/TestCurves.java | 4 +- jdk/test/sun/security/pkcs11/ec/TestECDH.java | 2 +- .../sun/security/pkcs11/ec/TestECDH2.java | 2 +- .../sun/security/pkcs11/ec/TestECDSA.java | 2 +- .../sun/security/pkcs11/ec/TestECDSA2.java | 2 +- .../sun/security/pkcs11/ec/TestECGenSpec.java | 2 +- .../security/pkcs11/ec/TestKeyFactory.java | 2 +- jdk/test/sun/security/pkcs11/rsa/KeyWrap.java | 2 +- .../sun/security/pkcs11/rsa/TestCACerts.java | 2 +- .../security/pkcs11/rsa/TestKeyFactory.java | 2 +- .../pkcs11/rsa/TestKeyPairGenerator.java | 2 +- .../security/pkcs11/rsa/TestSignatures.java | 2 +- .../pkcs11/sslecc/ClientJSSEServerJSSE.java | 2 +- .../security/pkcs11/tls/TestKeyMaterial.java | 2 +- .../pkcs11/tls/TestLeadingZeroesP11.java | 2 +- .../security/pkcs11/tls/TestMasterSecret.java | 2 +- jdk/test/sun/security/pkcs11/tls/TestPRF.java | 2 +- .../security/pkcs11/tls/TestPremaster.java | 2 +- jdk/test/tools/launcher/MiscTests.java | 4 +- .../modules/limitmods/LimitModsTest.java | 7 +-- .../modules/listmods/ListModsTest.java | 8 +-- 191 files changed, 162 insertions(+), 251 deletions(-) rename jdk/make/copy/{Copy-jdk.crypto.pkcs11.gmk => Copy-jdk.crypto.token.gmk} (95%) rename jdk/make/launcher/{Launcher-jdk.pack200.gmk => Launcher-jdk.pack.gmk} (93%) rename jdk/make/lib/{Lib-jdk.crypto.pkcs11.gmk => Lib-jdk.crypto.token.gmk} (90%) rename jdk/make/lib/{Lib-jdk.pack200.gmk => Lib-jdk.pack.gmk} (92%) delete mode 100644 jdk/src/java.compact1/share/classes/module-info.java delete mode 100644 jdk/src/java.compact2/share/classes/module-info.java delete mode 100644 jdk/src/java.compact3/share/classes/module-info.java rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/module-info.java (98%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/Config.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/KeyCache.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Cipher.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11DHKeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11DSAKeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Digest.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11ECDHKeyAgreement.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11ECKeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Key.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11KeyAgreement.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11KeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11KeyGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11KeyStore.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Mac.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11RSACipher.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11RSAKeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11SecureRandom.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Signature.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11TlsKeyMaterialGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11TlsMasterSecretGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11TlsPrfGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/P11Util.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/Secmod.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/Session.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/SessionManager.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/SunPKCS11.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/TemplateManager.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/Token.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_ATTRIBUTE.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_CREATEMUTEX.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_DATE.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_DESTROYMUTEX.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_INFO.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_LOCKMUTEX.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_NOTIFY.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_PBE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SESSION_INFO.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SLOT_INFO.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_TOKEN_INFO.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_UNLOCKMUTEX.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_VERSION.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/Constants.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/Functions.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/PKCS11.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/classes/sun/security/pkcs11/wrapper/PKCS11RuntimeException.java (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/legal/pkcs11cryptotoken.md (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/legal/pkcs11wrapper.md (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/j2secmod.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/j2secmod.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_convert.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_crypt.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_digest.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_dual.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_general.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_keymgmt.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_mutex.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_objmgmt.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_sessmgmt.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_sign.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/p11_util.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/pkcs-11v2-20a3.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/pkcs11.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/pkcs11f.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/pkcs11t.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/share/native/libj2pkcs11/pkcs11wrapper.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/solaris/conf/security/sunpkcs11-solaris.cfg (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/unix/native/libj2pkcs11/j2secmod_md.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/unix/native/libj2pkcs11/j2secmod_md.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/unix/native/libj2pkcs11/p11_md.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/unix/native/libj2pkcs11/p11_md.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/windows/native/libj2pkcs11/j2secmod_md.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/windows/native/libj2pkcs11/j2secmod_md.h (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/windows/native/libj2pkcs11/p11_md.c (100%) rename jdk/src/{jdk.crypto.pkcs11 => jdk.crypto.token}/windows/native/libj2pkcs11/p11_md.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/classes/module-info.java (98%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/bands.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/bands.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/bytes.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/bytes.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/coding.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/coding.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/constants.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/defines.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/unpack.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/unpack.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/utils.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/utils.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/zip.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/common-unpack/zip.h (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/libunpack/jni.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/share/native/unpack200/main.cpp (100%) rename jdk/src/{jdk.pack200 => jdk.pack}/windows/native/unpack200/unpack200_proto.exe.manifest (100%) diff --git a/jdk/make/copy/Copy-jdk.crypto.pkcs11.gmk b/jdk/make/copy/Copy-jdk.crypto.token.gmk similarity index 95% rename from jdk/make/copy/Copy-jdk.crypto.pkcs11.gmk rename to jdk/make/copy/Copy-jdk.crypto.token.gmk index b9771dee017..d35f655818e 100644 --- a/jdk/make/copy/Copy-jdk.crypto.pkcs11.gmk +++ b/jdk/make/copy/Copy-jdk.crypto.token.gmk @@ -30,7 +30,7 @@ include CopyCommon.gmk ifeq ($(OPENJDK_TARGET_OS), solaris) SUNPKCS11_CFG_SRC := \ - $(JDK_TOPDIR)/src/jdk.crypto.pkcs11/solaris/conf/security/sunpkcs11-solaris.cfg + $(JDK_TOPDIR)/src/jdk.crypto.token/solaris/conf/security/sunpkcs11-solaris.cfg SUNPKCS11_CFG_DST := $(CONF_DST_DIR)/security/sunpkcs11-solaris.cfg $(SUNPKCS11_CFG_DST): $(SUNPKCS11_CFG_SRC) diff --git a/jdk/make/launcher/Launcher-jdk.pack200.gmk b/jdk/make/launcher/Launcher-jdk.pack.gmk similarity index 93% rename from jdk/make/launcher/Launcher-jdk.pack200.gmk rename to jdk/make/launcher/Launcher-jdk.pack.gmk index 32b29b0c598..2ee08c767bf 100644 --- a/jdk/make/launcher/Launcher-jdk.pack200.gmk +++ b/jdk/make/launcher/Launcher-jdk.pack.gmk @@ -34,9 +34,9 @@ $(eval $(call SetupBuildLauncher, pack200, \ # The order of the object files on the link command line affects the size of the resulting # binary (at least on linux) which causes the size to differ between old and new build. -UNPACKEXE_SRC := $(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack \ - $(JDK_TOPDIR)/src/jdk.pack200/share/native/unpack200 -UNPACKEXE_CFLAGS := -I$(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack \ +UNPACKEXE_SRC := $(JDK_TOPDIR)/src/jdk.pack/share/native/common-unpack \ + $(JDK_TOPDIR)/src/jdk.pack/share/native/unpack200 +UNPACKEXE_CFLAGS := -I$(JDK_TOPDIR)/src/jdk.pack/share/native/common-unpack \ -I$(JDK_TOPDIR)/src/java.base/share/native/libjava \ -I$(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS_TYPE)/native/libjava @@ -97,7 +97,7 @@ $(eval $(call SetupNativeCompilation,BUILD_UNPACKEXE, \ -D "JDK_FNAME=unpack200.exe" \ -D "JDK_INTERNAL_NAME=unpack200" \ -D "JDK_FTYPE=0x1L", \ - MANIFEST := $(JDK_TOPDIR)/src/jdk.pack200/windows/native/unpack200/unpack200_proto.exe.manifest, \ + MANIFEST := $(JDK_TOPDIR)/src/jdk.pack/windows/native/unpack200/unpack200_proto.exe.manifest, \ MANIFEST_VERSION := $(VERSION_NUMBER_FOUR_POSITIONS), \ )) diff --git a/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk b/jdk/make/lib/Lib-jdk.crypto.token.gmk similarity index 90% rename from jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk rename to jdk/make/lib/Lib-jdk.crypto.token.gmk index 82618b11fb5..9e015be9f89 100644 --- a/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk +++ b/jdk/make/lib/Lib-jdk.crypto.token.gmk @@ -27,8 +27,8 @@ include LibCommon.gmk ################################################################################ -LIBJ2PKCS11_SRC := $(JDK_TOPDIR)/src/jdk.crypto.pkcs11/share/native/libj2pkcs11 \ - $(JDK_TOPDIR)/src/jdk.crypto.pkcs11/$(OPENJDK_TARGET_OS_TYPE)/native/libj2pkcs11 +LIBJ2PKCS11_SRC := $(JDK_TOPDIR)/src/jdk.crypto.token/share/native/libj2pkcs11 \ + $(JDK_TOPDIR)/src/jdk.crypto.token/$(OPENJDK_TARGET_OS_TYPE)/native/libj2pkcs11 $(eval $(call SetupNativeCompilation,BUILD_LIBJ2PKCS11, \ LIBRARY := j2pkcs11, \ @@ -37,7 +37,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJ2PKCS11, \ OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJ2PKCS11_SRC)) \ $(LIBJAVA_HEADER_FLAGS) \ - -I$(SUPPORT_OUTPUTDIR)/headers/jdk.crypto.pkcs11, \ + -I$(SUPPORT_OUTPUTDIR)/headers/jdk.crypto.token, \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libj2pkcs11/mapfile-vers, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ diff --git a/jdk/make/lib/Lib-jdk.pack200.gmk b/jdk/make/lib/Lib-jdk.pack.gmk similarity index 92% rename from jdk/make/lib/Lib-jdk.pack200.gmk rename to jdk/make/lib/Lib-jdk.pack.gmk index 7f942fcfb41..cc482c9ecd4 100644 --- a/jdk/make/lib/Lib-jdk.pack200.gmk +++ b/jdk/make/lib/Lib-jdk.pack.gmk @@ -30,14 +30,14 @@ include LibCommon.gmk $(eval $(call SetupNativeCompilation,BUILD_LIBUNPACK, \ LIBRARY := unpack, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(JDK_TOPDIR)/src/jdk.pack200/share/native/libunpack \ - $(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack, \ + SRC := $(JDK_TOPDIR)/src/jdk.pack/share/native/libunpack \ + $(JDK_TOPDIR)/src/jdk.pack/share/native/common-unpack, \ TOOLCHAIN := TOOLCHAIN_LINK_CXX, \ OPTIMIZATION := LOW, \ CFLAGS := $(CXXFLAGS_JDKLIB) \ -DNO_ZLIB -DUNPACK_JNI -DFULL \ -I$(SUPPORT_OUTPUTDIR)/headers/java.base \ - -I$(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack \ + -I$(JDK_TOPDIR)/src/jdk.pack/share/native/common-unpack \ $(LIBJAVA_HEADER_FLAGS), \ CFLAGS_release := -DPRODUCT, \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libunpack/mapfile-vers, \ diff --git a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java index bf0f03be6b3..3b81f6b421f 100644 --- a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java +++ b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java @@ -35,9 +35,11 @@ import java.lang.module.ResolvedModule; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; @@ -112,6 +114,7 @@ public class GenGraphs { private static final String REQUIRES_BASE = "color=\"" + GRAY + "\""; private static final Map weights = new HashMap<>(); + private static final List> ranks = new ArrayList<>(); private static void weight(String s, String t, int w) { weights.put(s + ":" + t, w); @@ -128,23 +131,37 @@ public class GenGraphs { static { int h = 1000; - weight("java.se", "java.compact3", h * 10); - weight("jdk.compact3", "java.compact3", h * 10); - weight("java.compact3", "java.compact2", h * 10); - weight("java.compact2", "java.compact1", h * 10); - weight("java.compact1", "java.logging", h * 10); - weight("java.logging", "java.base", h * 10); + weight("java.se", "java.sql.rowset", h * 10); + weight("java.sql.rowset", "java.sql", h * 10); + weight("java.sql", "java.xml", h * 10); + weight("java.xml", "java.base", h * 10); + + ranks.add(Set.of("java.logging", "java.scripting", "java.xml")); + ranks.add(Set.of("java.sql")); + 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")); + } private void genDotFile(Path dir, String name, Configuration cf) throws IOException { try (PrintStream out = new PrintStream(Files.newOutputStream(dir.resolve(name + ".dot")))) { - Map nameToModule = cf.modules().stream() + Map nameToModule; + if (name.equals("java.se.ee")) { + nameToModule = cf.modules().stream() + .map(ResolvedModule::reference) + .map(ModuleReference::descriptor) + .filter(md -> !md.name().startsWith("jdk.")) + .collect(Collectors.toMap(ModuleDescriptor::name, Function.identity())); + } else { + nameToModule = cf.modules().stream() .map(ResolvedModule::reference) .map(ModuleReference::descriptor) .collect(Collectors.toMap(ModuleDescriptor::name, Function.identity())); - + } Set descriptors = new TreeSet<>(nameToModule.values()); out.format("digraph \"%s\" {%n", name); @@ -162,6 +179,17 @@ public class GenGraphs { .forEach(mn -> out.format(" \"%s\" [fontcolor=\"%s\", group=%s];%n", mn, ORANGE, "java")); out.format("}%n"); + + // same ranks + ranks.stream() + .forEach(group -> out.format("{rank=same %s}%n", + descriptors.stream() + .map(ModuleDescriptor::name) + .filter(group::contains) + .map(mn -> "\"" + mn + "\"") + .collect(Collectors.joining(",")) + )); + descriptors.stream() .filter(jdkGroup::contains) .map(ModuleDescriptor::name) @@ -177,14 +205,17 @@ public class GenGraphs { .map(d -> d.name()) .collect(Collectors.toSet()); - graph.adjacentNodes(mn).forEach(dn -> { - String attr = dn.equals("java.base") ? REQUIRES_BASE - : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES); - int w = weightOf(mn, dn); - if (w > 1) - attr += "weight=" + w; - out.format(" \"%s\" -> \"%s\" [%s];%n", mn, dn, attr); - }); + graph.adjacentNodes(mn) + .stream() + .filter(nameToModule::containsKey) + .forEach(dn -> { + String attr = dn.equals("java.base") ? REQUIRES_BASE + : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES); + int w = weightOf(mn, dn); + if (w > 1) + attr += "weight=" + w; + out.format(" \"%s\" -> \"%s\" [%s];%n", mn, dn, attr); + }); }); out.println("}"); diff --git a/jdk/src/java.base/share/classes/module-info.java b/jdk/src/java.base/share/classes/module-info.java index 2d38377f62f..74f0bbf6a9d 100644 --- a/jdk/src/java.base/share/classes/module-info.java +++ b/jdk/src/java.base/share/classes/module-info.java @@ -218,7 +218,7 @@ module java.base { java.security.jgss; exports sun.nio.ch to java.management, - jdk.crypto.pkcs11, + jdk.crypto.token, jdk.sctp; exports sun.nio.cs to java.desktop, @@ -242,14 +242,14 @@ module java.base { java.desktop, java.security.jgss; exports sun.security.internal.interfaces to - jdk.crypto.pkcs11; + jdk.crypto.token; exports sun.security.internal.spec to - jdk.crypto.pkcs11; + jdk.crypto.token; exports sun.security.jca to java.smartcardio, java.xml.crypto, jdk.crypto.ec, - jdk.crypto.pkcs11, + jdk.crypto.token, jdk.naming.dns; exports sun.security.pkcs to jdk.crypto.ec, @@ -257,13 +257,13 @@ module java.base { exports sun.security.provider to java.rmi, java.security.jgss, - jdk.crypto.pkcs11, + jdk.crypto.token, jdk.policytool, jdk.security.auth; exports sun.security.provider.certpath to java.naming; exports sun.security.rsa to - jdk.crypto.pkcs11; + jdk.crypto.token; exports sun.security.ssl to java.security.jgss; exports sun.security.timestamp to @@ -278,14 +278,14 @@ module java.base { java.security.sasl, java.smartcardio, jdk.crypto.ec, - jdk.crypto.pkcs11, + jdk.crypto.token, jdk.jartool, jdk.policytool, jdk.security.auth, jdk.security.jgss; exports sun.security.x509 to jdk.crypto.ec, - jdk.crypto.pkcs11, + jdk.crypto.token, jdk.jartool, jdk.security.auth; exports sun.text.resources to diff --git a/jdk/src/java.base/share/lib/security/default.policy b/jdk/src/java.base/share/lib/security/default.policy index 9014111ce09..0c1798fbe9b 100644 --- a/jdk/src/java.base/share/lib/security/default.policy +++ b/jdk/src/java.base/share/lib/security/default.policy @@ -125,7 +125,7 @@ grant codeBase "jrt:/jdk.crypto.ec" { permission java.security.SecurityPermission "removeProviderProperty.SunEC"; }; -grant codeBase "jrt:/jdk.crypto.pkcs11" { +grant codeBase "jrt:/jdk.crypto.token" { permission java.lang.RuntimePermission "accessClassInPackage.sun.security.*"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; diff --git a/jdk/src/java.compact1/share/classes/module-info.java b/jdk/src/java.compact1/share/classes/module-info.java deleted file mode 100644 index 72d4357759a..00000000000 --- a/jdk/src/java.compact1/share/classes/module-info.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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. - */ - -/** - * Aggregates {@code java.base}, {@code java.logging}, and {@code java.scripting}. - */ -module java.compact1 { - requires transitive java.logging; - requires transitive java.scripting; -} - diff --git a/jdk/src/java.compact2/share/classes/module-info.java b/jdk/src/java.compact2/share/classes/module-info.java deleted file mode 100644 index 0666be8fc10..00000000000 --- a/jdk/src/java.compact2/share/classes/module-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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. - */ - -/** - * Supplements {@code java.compact1} with JDBC, JAXP, and RMI. - */ -module java.compact2 { - requires transitive java.compact1; - requires transitive java.rmi; - requires transitive java.sql; - requires transitive java.xml; -} - diff --git a/jdk/src/java.compact3/share/classes/module-info.java b/jdk/src/java.compact3/share/classes/module-info.java deleted file mode 100644 index 9783a406a54..00000000000 --- a/jdk/src/java.compact3/share/classes/module-info.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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. - */ - -/** - * Supplements {@code java.compact2} with JDBC RowSet, JMX, JNDI, Compiler, - * Instrumentation, Preferences, Security, and XML cryptography APIs. - */ -module java.compact3 { - requires transitive java.compact2; - requires transitive java.compiler; - requires transitive java.instrument; - requires transitive java.management; - requires transitive java.naming; - requires transitive java.prefs; - requires transitive java.security.jgss; - requires transitive java.security.sasl; - requires transitive java.sql.rowset; - requires transitive java.xml.crypto; -} - diff --git a/jdk/src/java.se/share/classes/module-info.java b/jdk/src/java.se/share/classes/module-info.java index cbd67e5b747..2756756588a 100644 --- a/jdk/src/java.se/share/classes/module-info.java +++ b/jdk/src/java.se/share/classes/module-info.java @@ -26,12 +26,25 @@ /** * Defines the core Java SE API. *

    - * The modules defining - * CORBA and Java EE APIs are not required by this module, but they are - * required by {@code java.se.ee}. + * The modules defining CORBA and Java EE APIs are not required by + * this module, but they are required by {@code java.se.ee}. */ module java.se { - requires transitive java.compact3; + requires transitive java.compiler; requires transitive java.datatransfer; requires transitive java.desktop; + requires transitive java.instrument; + requires transitive java.logging; + requires transitive java.management; + requires transitive java.naming; + requires transitive java.prefs; + requires transitive java.rmi; + requires transitive java.scripting; + requires transitive java.security.jgss; + requires transitive java.security.sasl; + requires transitive java.sql; + requires transitive java.sql.rowset; + requires transitive java.xml; + requires transitive java.xml.crypto; } + diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java b/jdk/src/jdk.crypto.token/share/classes/module-info.java similarity index 98% rename from jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java rename to jdk/src/jdk.crypto.token/share/classes/module-info.java index 07f4c1bf3e1..b587d0d4a33 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/module-info.java +++ b/jdk/src/jdk.crypto.token/share/classes/module-info.java @@ -23,7 +23,7 @@ * questions. */ -module jdk.crypto.pkcs11 { +module jdk.crypto.token { // Depends on SunEC provider for EC related functionality requires jdk.crypto.ec; provides java.security.Provider with sun.security.pkcs11.SunPKCS11; diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Config.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Config.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Config.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Config.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/KeyCache.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/KeyCache.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/KeyCache.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/KeyCache.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Cipher.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Cipher.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11DHKeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11DHKeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11DHKeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11DHKeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11DSAKeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11DSAKeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11DSAKeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11DSAKeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Digest.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Digest.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Digest.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Digest.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11ECDHKeyAgreement.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11ECDHKeyAgreement.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11ECDHKeyAgreement.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11ECDHKeyAgreement.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11ECKeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11ECKeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11ECKeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11ECKeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Key.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Key.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Key.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Key.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyAgreement.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyAgreement.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyAgreement.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyAgreement.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyStore.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11KeyStore.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Mac.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Mac.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Mac.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Mac.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSACipher.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11RSACipher.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSACipher.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11RSACipher.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSAKeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11RSAKeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSAKeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11RSAKeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11SecureRandom.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11SecureRandom.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11SecureRandom.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11SecureRandom.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Signature.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Signature.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Signature.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Signature.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsKeyMaterialGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsKeyMaterialGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsKeyMaterialGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsKeyMaterialGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsMasterSecretGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsMasterSecretGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsMasterSecretGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsMasterSecretGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsPrfGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsPrfGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsPrfGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsPrfGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11TlsRsaPremasterSecretGenerator.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Util.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Util.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Util.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/P11Util.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Secmod.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Secmod.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Secmod.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Secmod.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Session.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Session.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Session.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Session.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SessionManager.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/SessionManager.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SessionManager.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/SessionManager.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/SunPKCS11.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/SunPKCS11.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/TemplateManager.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/TemplateManager.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/TemplateManager.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/TemplateManager.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Token.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Token.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/Token.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/Token.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ATTRIBUTE.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ATTRIBUTE.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ATTRIBUTE.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ATTRIBUTE.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_CREATEMUTEX.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_CREATEMUTEX.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_CREATEMUTEX.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_CREATEMUTEX.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_C_INITIALIZE_ARGS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_DATE.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_DATE.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_DATE.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_DATE.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_DESTROYMUTEX.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_DESTROYMUTEX.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_DESTROYMUTEX.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_DESTROYMUTEX.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_INFO.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_INFO.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_INFO.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_INFO.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_LOCKMUTEX.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_LOCKMUTEX.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_LOCKMUTEX.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_LOCKMUTEX.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_NOTIFY.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_NOTIFY.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_NOTIFY.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_NOTIFY.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_PBE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_PBE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_PBE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_PBE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SESSION_INFO.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SESSION_INFO.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SESSION_INFO.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SESSION_INFO.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SLOT_INFO.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SLOT_INFO.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SLOT_INFO.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SLOT_INFO.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_MASTER_KEY_DERIVE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_TOKEN_INFO.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_TOKEN_INFO.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_TOKEN_INFO.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_TOKEN_INFO.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_UNLOCKMUTEX.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_UNLOCKMUTEX.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_UNLOCKMUTEX.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_UNLOCKMUTEX.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_VERSION.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_VERSION.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_VERSION.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_VERSION.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/CK_X9_42_DH2_DERIVE_PARAMS.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/Constants.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/Constants.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/Constants.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/Constants.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/Functions.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/Functions.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/Functions.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/Functions.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11Constants.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11RuntimeException.java b/jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11RuntimeException.java similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/PKCS11RuntimeException.java rename to jdk/src/jdk.crypto.token/share/classes/sun/security/pkcs11/wrapper/PKCS11RuntimeException.java diff --git a/jdk/src/jdk.crypto.pkcs11/share/legal/pkcs11cryptotoken.md b/jdk/src/jdk.crypto.token/share/legal/pkcs11cryptotoken.md similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/legal/pkcs11cryptotoken.md rename to jdk/src/jdk.crypto.token/share/legal/pkcs11cryptotoken.md diff --git a/jdk/src/jdk.crypto.pkcs11/share/legal/pkcs11wrapper.md b/jdk/src/jdk.crypto.token/share/legal/pkcs11wrapper.md similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/legal/pkcs11wrapper.md rename to jdk/src/jdk.crypto.token/share/legal/pkcs11wrapper.md diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/j2secmod.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/j2secmod.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/j2secmod.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/j2secmod.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/j2secmod.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/j2secmod.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/j2secmod.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/j2secmod.h diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_convert.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_convert.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_convert.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_convert.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_crypt.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_crypt.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_crypt.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_crypt.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_digest.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_digest.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_digest.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_digest.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_dual.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_dual.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_dual.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_dual.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_general.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_general.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_general.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_general.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_keymgmt.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_keymgmt.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_keymgmt.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_keymgmt.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_mutex.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_mutex.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_mutex.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_mutex.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_objmgmt.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_objmgmt.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_objmgmt.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_objmgmt.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_sessmgmt.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_sessmgmt.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_sessmgmt.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_sessmgmt.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_sign.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_sign.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_sign.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_sign.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_util.c b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_util.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_util.c rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/p11_util.c diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs-11v2-20a3.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs-11v2-20a3.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs-11v2-20a3.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs-11v2-20a3.h diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11.h diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11f.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11f.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11f.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11f.h diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11t.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11t.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11t.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11t.h diff --git a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11wrapper.h b/jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11wrapper.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/pkcs11wrapper.h rename to jdk/src/jdk.crypto.token/share/native/libj2pkcs11/pkcs11wrapper.h diff --git a/jdk/src/jdk.crypto.pkcs11/solaris/conf/security/sunpkcs11-solaris.cfg b/jdk/src/jdk.crypto.token/solaris/conf/security/sunpkcs11-solaris.cfg similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/solaris/conf/security/sunpkcs11-solaris.cfg rename to jdk/src/jdk.crypto.token/solaris/conf/security/sunpkcs11-solaris.cfg diff --git a/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.c b/jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/j2secmod_md.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.c rename to jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/j2secmod_md.c diff --git a/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.h b/jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/j2secmod_md.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.h rename to jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/j2secmod_md.h diff --git a/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/p11_md.c b/jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/p11_md.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/p11_md.c rename to jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/p11_md.c diff --git a/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/p11_md.h b/jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/p11_md.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/p11_md.h rename to jdk/src/jdk.crypto.token/unix/native/libj2pkcs11/p11_md.h diff --git a/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.c b/jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/j2secmod_md.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.c rename to jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/j2secmod_md.c diff --git a/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.h b/jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/j2secmod_md.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.h rename to jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/j2secmod_md.h diff --git a/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.c b/jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/p11_md.c similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.c rename to jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/p11_md.c diff --git a/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.h b/jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/p11_md.h similarity index 100% rename from jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.h rename to jdk/src/jdk.crypto.token/windows/native/libj2pkcs11/p11_md.h diff --git a/jdk/src/jdk.pack200/share/classes/module-info.java b/jdk/src/jdk.pack/share/classes/module-info.java similarity index 98% rename from jdk/src/jdk.pack200/share/classes/module-info.java rename to jdk/src/jdk.pack/share/classes/module-info.java index ffca94f972a..3cedd0990ec 100644 --- a/jdk/src/jdk.pack200/share/classes/module-info.java +++ b/jdk/src/jdk.pack/share/classes/module-info.java @@ -23,6 +23,6 @@ * questions. */ -module jdk.pack200 { +module jdk.pack { } diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/bands.cpp b/jdk/src/jdk.pack/share/native/common-unpack/bands.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/bands.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/bands.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/bands.h b/jdk/src/jdk.pack/share/native/common-unpack/bands.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/bands.h rename to jdk/src/jdk.pack/share/native/common-unpack/bands.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/bytes.cpp b/jdk/src/jdk.pack/share/native/common-unpack/bytes.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/bytes.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/bytes.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/bytes.h b/jdk/src/jdk.pack/share/native/common-unpack/bytes.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/bytes.h rename to jdk/src/jdk.pack/share/native/common-unpack/bytes.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/coding.cpp b/jdk/src/jdk.pack/share/native/common-unpack/coding.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/coding.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/coding.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/coding.h b/jdk/src/jdk.pack/share/native/common-unpack/coding.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/coding.h rename to jdk/src/jdk.pack/share/native/common-unpack/coding.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/constants.h b/jdk/src/jdk.pack/share/native/common-unpack/constants.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/constants.h rename to jdk/src/jdk.pack/share/native/common-unpack/constants.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/defines.h b/jdk/src/jdk.pack/share/native/common-unpack/defines.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/defines.h rename to jdk/src/jdk.pack/share/native/common-unpack/defines.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp b/jdk/src/jdk.pack/share/native/common-unpack/unpack.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/unpack.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/unpack.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/unpack.h b/jdk/src/jdk.pack/share/native/common-unpack/unpack.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/unpack.h rename to jdk/src/jdk.pack/share/native/common-unpack/unpack.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/utils.cpp b/jdk/src/jdk.pack/share/native/common-unpack/utils.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/utils.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/utils.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/utils.h b/jdk/src/jdk.pack/share/native/common-unpack/utils.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/utils.h rename to jdk/src/jdk.pack/share/native/common-unpack/utils.h diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/zip.cpp b/jdk/src/jdk.pack/share/native/common-unpack/zip.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/zip.cpp rename to jdk/src/jdk.pack/share/native/common-unpack/zip.cpp diff --git a/jdk/src/jdk.pack200/share/native/common-unpack/zip.h b/jdk/src/jdk.pack/share/native/common-unpack/zip.h similarity index 100% rename from jdk/src/jdk.pack200/share/native/common-unpack/zip.h rename to jdk/src/jdk.pack/share/native/common-unpack/zip.h diff --git a/jdk/src/jdk.pack200/share/native/libunpack/jni.cpp b/jdk/src/jdk.pack/share/native/libunpack/jni.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/libunpack/jni.cpp rename to jdk/src/jdk.pack/share/native/libunpack/jni.cpp diff --git a/jdk/src/jdk.pack200/share/native/unpack200/main.cpp b/jdk/src/jdk.pack/share/native/unpack200/main.cpp similarity index 100% rename from jdk/src/jdk.pack200/share/native/unpack200/main.cpp rename to jdk/src/jdk.pack/share/native/unpack200/main.cpp diff --git a/jdk/src/jdk.pack200/windows/native/unpack200/unpack200_proto.exe.manifest b/jdk/src/jdk.pack/windows/native/unpack200/unpack200_proto.exe.manifest similarity index 100% rename from jdk/src/jdk.pack200/windows/native/unpack200/unpack200_proto.exe.manifest rename to jdk/src/jdk.pack/windows/native/unpack200/unpack200_proto.exe.manifest diff --git a/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java b/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java index 1c7f7b42f93..722ccd788d5 100644 --- a/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java +++ b/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java @@ -62,7 +62,7 @@ public class CheckSecurityProvider { if (os.equals("SunOS")) { layer.findModule("jdk.crypto.ucrypto") .ifPresent(m -> expected.add("com.oracle.security.ucrypto.UcryptoProvider")); - layer.findModule("jdk.crypto.pkcs11") + layer.findModule("jdk.crypto.token") .ifPresent(m -> expected.add("sun.security.pkcs11.SunPKCS11")); } expected.add("sun.security.provider.Sun"); @@ -91,7 +91,7 @@ public class CheckSecurityProvider { expected.add("apple.security.AppleProvider"); } if (!os.equals("SunOS")) { - layer.findModule("jdk.crypto.pkcs11") + layer.findModule("jdk.crypto.token") .ifPresent(m -> expected.add("sun.security.pkcs11.SunPKCS11")); } diff --git a/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java b/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java index 754b2ada4ee..f45d9f7dd01 100644 --- a/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java +++ b/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java @@ -26,7 +26,6 @@ * @summary Basic test of VM::getRuntimeArguments * @library /lib/testlibrary * @modules java.base/jdk.internal.misc - * java.compact3 * jdk.zipfs * @run testng RuntimeArguments */ @@ -64,11 +63,11 @@ public class RuntimeArguments { "--add-modules", "jdk.zipfs", "--limit-modules", - "java.compact3"), + "java.logging,java.xml,jdk.charsets,jdk.zipfs"), // expected runtime arguments List.of("--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "--add-modules=jdk.zipfs", - "--limit-modules=java.compact3"), + "--limit-modules=java.logging,java.xml,jdk.charsets,jdk.zipfs"), }, }; }; diff --git a/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java b/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java index cd25a49c31c..72e337066cb 100644 --- a/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java +++ b/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java @@ -24,9 +24,7 @@ /** * @test * @summary Verify the defining class loader of each module never delegates - * to its child class loader. Also sanity check java.compact2 - * requires. - * @modules java.compact2 + * to its child class loader. * @run testng/othervm --add-modules=ALL-SYSTEM VerifyModuleDelegation */ @@ -46,21 +44,10 @@ import static org.testng.Assert.*; public class VerifyModuleDelegation { private static final String JAVA_BASE = "java.base"; - private static final String JAVA_COMPACT1 = "java.compact1"; - private static final String JAVA_COMPACT2 = "java.compact2"; private static final ModuleDescriptor BASE = ModuleDescriptor.module(JAVA_BASE).build(); - private static final ModuleDescriptor COMPACT2 - = ModuleDescriptor.module(JAVA_COMPACT2) - .requires(Set.of(MANDATED), JAVA_BASE) - .requires(Set.of(TRANSITIVE), JAVA_COMPACT1) - .requires(Set.of(TRANSITIVE), "java.rmi") - .requires(Set.of(TRANSITIVE), "java.sql") - .requires(Set.of(TRANSITIVE), "java.xml") - .build(); - private static final Set MREFS = Layer.boot().modules().stream().map(Module::getDescriptor) .collect(toSet()); @@ -79,14 +66,6 @@ public class VerifyModuleDelegation { check(md, BASE); } - @Test - public void checkCompact2() { - ModuleDescriptor md = - MREFS.stream() - .filter(d -> d.name().equals(JAVA_COMPACT2)) - .findFirst().orElseThrow(Error::new); - check(md, COMPACT2); - } @Test public void checkLoaderDelegation() { diff --git a/jdk/test/sun/security/ec/TestEC.java b/jdk/test/sun/security/ec/TestEC.java index c82e1fdac48..93ad04e6618 100644 --- a/jdk/test/sun/security/ec/TestEC.java +++ b/jdk/test/sun/security/ec/TestEC.java @@ -34,8 +34,8 @@ * @library ../pkcs11/ec * @library ../pkcs11/sslecc * @library ../../../java/security/testlibrary - * @modules jdk.crypto.pkcs11/sun.security.pkcs11.wrapper - * @compile --add-modules jdk.crypto.pkcs11 TestEC.java + * @modules jdk.crypto.token/sun.security.pkcs11.wrapper + * @compile --add-modules jdk.crypto.token TestEC.java * @run main/othervm -Djdk.tls.namedGroups="secp256r1,sect193r1" TestEC * @run main/othervm/java.security.policy=TestEC.policy -Djdk.tls.namedGroups="secp256r1,sect193r1" TestEC */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java b/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java index 72dbb728687..643134bf76d 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ReinitCipher * @run main/othervm ReinitCipher sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java b/jdk/test/sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java index 49880d3706e..7804116aea4 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java @@ -27,7 +27,7 @@ * @summary Test internal PKCS5Padding impl with various error conditions. * @author Valerie Peng * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestPKCS5PaddingError * @run main/othervm TestPKCS5PaddingError sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java index 160ce1cb5a1..abf5818ef77 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestRSACipher * @run main/othervm TestRSACipher sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java index 4e4fb600852..d1c5485954c 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipherWrap.java @@ -27,7 +27,7 @@ * @summary basic test for RSA cipher key wrapping functionality * @author Valerie Peng * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestRSACipherWrap * @run main/othervm TestRSACipherWrap sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java index ed85f315a75..7444c7684bf 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java @@ -28,7 +28,7 @@ * @author Valerie Peng * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestRawRSACipher * @run main/othervm TestRawRSACipher sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java index e94c61d2938..3ba5dabdcbc 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java @@ -28,7 +28,7 @@ * @author Valerie Peng * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestSymmCiphers * @run main/othervm TestSymmCiphers sm */ diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java index 4fc7d7b9553..f96c4a08e3f 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java @@ -28,7 +28,7 @@ * @author Valerie Peng * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestSymmCiphersNoPad * @run main/othervm TestSymmCiphersNoPad sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java b/jdk/test/sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java index 52b69892dae..7e3ceae5384 100644 --- a/jdk/test/sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java +++ b/jdk/test/sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java @@ -26,7 +26,7 @@ * @bug 8072452 * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm SupportedDHKeys * @run main/othervm SupportedDHKeys sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyAgreement/TestDH.java b/jdk/test/sun/security/pkcs11/KeyAgreement/TestDH.java index c43dc081878..18a526dbe97 100644 --- a/jdk/test/sun/security/pkcs11/KeyAgreement/TestDH.java +++ b/jdk/test/sun/security/pkcs11/KeyAgreement/TestDH.java @@ -27,7 +27,7 @@ * @summary Verify that DH works properly * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestDH * @run main/othervm TestDH sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyAgreement/TestInterop.java b/jdk/test/sun/security/pkcs11/KeyAgreement/TestInterop.java index 4834b761f89..d231efd95bd 100644 --- a/jdk/test/sun/security/pkcs11/KeyAgreement/TestInterop.java +++ b/jdk/test/sun/security/pkcs11/KeyAgreement/TestInterop.java @@ -26,7 +26,7 @@ * @bug 7146728 * @summary Interop test for DH with secret that has a leading 0x00 byte * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestInterop * @run main/othervm TestInterop sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyAgreement/TestShort.java b/jdk/test/sun/security/pkcs11/KeyAgreement/TestShort.java index f082fee09ac..687daff0147 100644 --- a/jdk/test/sun/security/pkcs11/KeyAgreement/TestShort.java +++ b/jdk/test/sun/security/pkcs11/KeyAgreement/TestShort.java @@ -27,7 +27,7 @@ * @summary KAT test for DH (normal and with secret that has leading a 0x00 byte) * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestShort * @run main/othervm TestShort sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java b/jdk/test/sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java index cdfa887de0a..df0853ce04c 100644 --- a/jdk/test/sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java +++ b/jdk/test/sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java @@ -26,7 +26,7 @@ * @bug 8072452 * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm UnsupportedDHKeys * @run main/othervm UnsupportedDHKeys sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java b/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java index 9e2b6da7b43..3b5d831fcf7 100644 --- a/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java +++ b/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm DESParity * @run main/othervm DESParity sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java b/jdk/test/sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java index f5297390348..ee2ccaa47d1 100644 --- a/jdk/test/sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java +++ b/jdk/test/sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java @@ -27,7 +27,7 @@ * @summary test the KeyGenerator * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestKeyGenerator * @run main/othervm TestKeyGenerator sm */ diff --git a/jdk/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java b/jdk/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java index f5a0a105fe8..4c04226e3ee 100644 --- a/jdk/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java +++ b/jdk/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java @@ -27,7 +27,7 @@ * @summary Ensure that DH key pairs can be generated for 512 - 8192 bits * @author Valerie Peng * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestDH2048 * @run main/othervm TestDH2048 sm */ diff --git a/jdk/test/sun/security/pkcs11/Mac/MacKAT.java b/jdk/test/sun/security/pkcs11/Mac/MacKAT.java index c068ac0e3c1..0894ea96efe 100644 --- a/jdk/test/sun/security/pkcs11/Mac/MacKAT.java +++ b/jdk/test/sun/security/pkcs11/Mac/MacKAT.java @@ -27,7 +27,7 @@ * @summary Basic known-answer-test for Hmac algorithms * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm MacKAT * @run main/othervm MacKAT sm */ diff --git a/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java b/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java index c1ee2ec4a67..818f1737af2 100644 --- a/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java +++ b/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java @@ -27,7 +27,7 @@ * @summary Check if doFinal and update operation result in same Mac * @author Yu-Ching Valerie Peng, Bill Situ, Alexander Fomin * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm MacSameTest * @run main/othervm MacSameTest sm * @key randomness diff --git a/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java b/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java index 97dcb7305b4..9973f46230a 100644 --- a/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java +++ b/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ReinitMac * @run main/othervm ReinitMac sm */ diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java b/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java index 64d7ff5ba65..3226442c71c 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ByteBuffers * @run main/othervm ByteBuffers sm */ diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/DigestKAT.java b/jdk/test/sun/security/pkcs11/MessageDigest/DigestKAT.java index 4a3b71f7deb..42aa231a05f 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/DigestKAT.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/DigestKAT.java @@ -27,7 +27,7 @@ * @summary Basic known-answer-test for all our MessageDigest algorithms * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm DigestKAT * @run main/othervm DigestKAT sm */ diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java b/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java index 3414a579754..04e43bb3fce 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ReinitDigest * @run main/othervm ReinitDigest sm */ diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java b/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java index 4bac0794227..2374e9bda79 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java @@ -28,7 +28,7 @@ * @author Valerie Peng * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestCloning * @run main/othervm TestCloning sm */ diff --git a/jdk/test/sun/security/pkcs11/Provider/Absolute.java b/jdk/test/sun/security/pkcs11/Provider/Absolute.java index 7906ac129c5..05d0e7860aa 100644 --- a/jdk/test/sun/security/pkcs11/Provider/Absolute.java +++ b/jdk/test/sun/security/pkcs11/Provider/Absolute.java @@ -24,7 +24,7 @@ * @test * @bug 7003952 7191662 * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @summary load DLLs and launch executables using fully qualified path */ diff --git a/jdk/test/sun/security/pkcs11/SampleTest.java b/jdk/test/sun/security/pkcs11/SampleTest.java index 5d5c68414f0..f3ee5bdaab6 100644 --- a/jdk/test/sun/security/pkcs11/SampleTest.java +++ b/jdk/test/sun/security/pkcs11/SampleTest.java @@ -27,7 +27,7 @@ * @summary XXX todo * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token */ import java.security.Provider; diff --git a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java index 82fc4ab5f74..b6875a78c1c 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java +++ b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java @@ -27,7 +27,7 @@ * @summary Test that the PKCS#11 KeyStore handles RSA, DSA, and EC keys * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm AddPrivateKey * @run main/othervm AddPrivateKey sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java b/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java index 1e085c33a24..c03cb861497 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java +++ b/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java @@ -27,7 +27,7 @@ * @summary make sure we can add a trusted cert to the NSS KeyStore module * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm AddTrustedCert * @run main/othervm AddTrustedCert sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java index b1b4372a49b..da57418e32b 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java +++ b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java @@ -27,7 +27,7 @@ * @summary verify that NSS no-db mode works correctly * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm Crypto * @run main/othervm Crypto sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java index 9dd1fe0aaba..39db0a3f81f 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java +++ b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java @@ -28,7 +28,7 @@ * and use a private key * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm GetPrivateKey * @run main/othervm GetPrivateKey sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/JksSetPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/JksSetPrivateKey.java index 360e5d1e684..c02a98aea8e 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/JksSetPrivateKey.java +++ b/jdk/test/sun/security/pkcs11/Secmod/JksSetPrivateKey.java @@ -27,7 +27,7 @@ * @summary store a NSS PKCS11 PrivateKeyEntry to JKS KeyStore throws confusing NPE * @author Wang Weijun * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm JksSetPrivateKey * @run main/othervm JksSetPrivateKey sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/LoadKeystore.java b/jdk/test/sun/security/pkcs11/Secmod/LoadKeystore.java index 2e1d85ce58f..e4218834924 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/LoadKeystore.java +++ b/jdk/test/sun/security/pkcs11/Secmod/LoadKeystore.java @@ -26,7 +26,7 @@ * @bug 8048622 8134232 * @summary Checks that PKCS#11 keystore can't be loaded with wrong password * @library ../ - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm LoadKeystore * @run main/othervm LoadKeystore sm policy */ diff --git a/jdk/test/sun/security/pkcs11/Secmod/TrustAnchors.java b/jdk/test/sun/security/pkcs11/Secmod/TrustAnchors.java index a26a5862d59..8735bc6fcb2 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/TrustAnchors.java +++ b/jdk/test/sun/security/pkcs11/Secmod/TrustAnchors.java @@ -27,7 +27,7 @@ * @summary make sure we can access the NSS trust anchor module * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TrustAnchors * @run main/othervm TrustAnchors sm policy */ diff --git a/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java b/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java index 3145431b867..19949777584 100644 --- a/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java +++ b/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm Basic * @run main/othervm Basic sm */ diff --git a/jdk/test/sun/security/pkcs11/SecureRandom/TestDeserialization.java b/jdk/test/sun/security/pkcs11/SecureRandom/TestDeserialization.java index 37985dd96e7..27a3575df3e 100644 --- a/jdk/test/sun/security/pkcs11/SecureRandom/TestDeserialization.java +++ b/jdk/test/sun/security/pkcs11/SecureRandom/TestDeserialization.java @@ -26,7 +26,7 @@ * @bug 6837847 * @summary Ensure a deserialized PKCS#11 SecureRandom is functional. * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token */ import java.io.ByteArrayInputStream; diff --git a/jdk/test/sun/security/pkcs11/Serialize/SerializeProvider.java b/jdk/test/sun/security/pkcs11/Serialize/SerializeProvider.java index a3deb72c974..b22465f0425 100644 --- a/jdk/test/sun/security/pkcs11/Serialize/SerializeProvider.java +++ b/jdk/test/sun/security/pkcs11/Serialize/SerializeProvider.java @@ -27,7 +27,7 @@ * @summary Test that the SunPKCS11 provider can be serialized * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token */ import java.io.ByteArrayInputStream; diff --git a/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java b/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java index 3d1afa3bcb0..854da848f28 100644 --- a/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java +++ b/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ByteBuffers * @run main/othervm ByteBuffers sm */ diff --git a/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java b/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java index 30f1d7f4f17..9a072269f99 100644 --- a/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java +++ b/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main ReinitSignature * @run main ReinitSignature * @run main ReinitSignature diff --git a/jdk/test/sun/security/pkcs11/Signature/TestDSA.java b/jdk/test/sun/security/pkcs11/Signature/TestDSA.java index b707d98ee20..11bfbfde324 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestDSA.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestDSA.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestDSA * @run main/othervm TestDSA sm */ diff --git a/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java b/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java index c1a0dc1bc57..673098e4d21 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java @@ -28,7 +28,7 @@ * with unsupported key sizes * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestDSAKeyLength * @run main/othervm TestDSAKeyLength sm */ diff --git a/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java b/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java index 7618851bc2a..8e70e224bf1 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java @@ -27,7 +27,7 @@ * @summary Make sure initSign/initVerify() check RSA key lengths * @author Yu-Ching Valerie Peng * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestRSAKeyLength * @run main/othervm TestRSAKeyLength sm */ diff --git a/jdk/test/sun/security/pkcs11/ec/ReadCertificates.java b/jdk/test/sun/security/pkcs11/ec/ReadCertificates.java index 3117c983402..46d44f446e2 100644 --- a/jdk/test/sun/security/pkcs11/ec/ReadCertificates.java +++ b/jdk/test/sun/security/pkcs11/ec/ReadCertificates.java @@ -29,7 +29,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ReadCertificates * @run main/othervm ReadCertificates sm policy */ diff --git a/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java b/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java index 57af80441f8..8efbb0a9aea 100644 --- a/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java +++ b/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java @@ -29,7 +29,7 @@ * @library .. * @library ../../../../java/security/testlibrary * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm ReadPKCS12 * @run main/othervm ReadPKCS12 sm policy */ diff --git a/jdk/test/sun/security/pkcs11/ec/TestCurves.java b/jdk/test/sun/security/pkcs11/ec/TestCurves.java index 41e57619643..b07900153ec 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestCurves.java +++ b/jdk/test/sun/security/pkcs11/ec/TestCurves.java @@ -27,8 +27,8 @@ * @summary Basic consistency test for all curves using ECDSA and ECDH * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11/sun.security.pkcs11.wrapper - * @compile --add-modules jdk.crypto.pkcs11 TestCurves.java + * @modules jdk.crypto.token/sun.security.pkcs11.wrapper + * @compile --add-modules jdk.crypto.token TestCurves.java * @run main/othervm TestCurves * @run main/othervm TestCurves sm * @key randomness diff --git a/jdk/test/sun/security/pkcs11/ec/TestECDH.java b/jdk/test/sun/security/pkcs11/ec/TestECDH.java index d5432b03968..a967f8e2eff 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECDH.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECDH.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestECDH * @run main/othervm TestECDH sm policy */ diff --git a/jdk/test/sun/security/pkcs11/ec/TestECDH2.java b/jdk/test/sun/security/pkcs11/ec/TestECDH2.java index d064e5263c3..2da9fbc333b 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECDH2.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECDH2.java @@ -29,7 +29,7 @@ * @library .. * @library ../../../../java/security/testlibrary * @modules java.base/sun.security.util - * jdk.crypto.pkcs11 + * jdk.crypto.token * @compile -XDignore.symbol.file TestECDH2.java * @run main/othervm TestECDH2 * @run main/othervm TestECDH2 sm diff --git a/jdk/test/sun/security/pkcs11/ec/TestECDSA.java b/jdk/test/sun/security/pkcs11/ec/TestECDSA.java index fd5de680064..8b516cc6f27 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECDSA.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECDSA.java @@ -29,7 +29,7 @@ * @library .. * @library ../../../../java/security/testlibrary * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestECDSA * @run main/othervm TestECDSA sm policy */ diff --git a/jdk/test/sun/security/pkcs11/ec/TestECDSA2.java b/jdk/test/sun/security/pkcs11/ec/TestECDSA2.java index fa0c5fc26b8..0a9b9c66b31 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECDSA2.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECDSA2.java @@ -29,7 +29,7 @@ * @library .. * @library ../../../../java/security/testlibrary * @modules java.base/sun.security.util - * jdk.crypto.pkcs11 + * jdk.crypto.token * @compile -XDignore.symbol.file TestECDSA2.java * @run main/othervm TestECDSA2 * @run main/othervm TestECDSA2 sm diff --git a/jdk/test/sun/security/pkcs11/ec/TestECGenSpec.java b/jdk/test/sun/security/pkcs11/ec/TestECGenSpec.java index 4ce105030da..9d50c9522e1 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECGenSpec.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECGenSpec.java @@ -27,7 +27,7 @@ * @summary Verify that we can use ECGenParameterSpec * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestECGenSpec * @run main/othervm TestECGenSpec sm */ diff --git a/jdk/test/sun/security/pkcs11/ec/TestKeyFactory.java b/jdk/test/sun/security/pkcs11/ec/TestKeyFactory.java index 827af91ed9e..524c0485a91 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestKeyFactory.java +++ b/jdk/test/sun/security/pkcs11/ec/TestKeyFactory.java @@ -27,7 +27,7 @@ * @summary Test the P11ECKeyFactory * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestKeyFactory * @run main/othervm TestKeyFactory sm */ diff --git a/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java b/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java index 311a9b7f5aa..00c7199b7e3 100644 --- a/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java +++ b/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm KeyWrap * @run main/othervm KeyWrap sm */ diff --git a/jdk/test/sun/security/pkcs11/rsa/TestCACerts.java b/jdk/test/sun/security/pkcs11/rsa/TestCACerts.java index a79330b8fcb..012142e2776 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestCACerts.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestCACerts.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestCACerts * @run main/othervm TestCACerts sm TestCACerts.policy */ diff --git a/jdk/test/sun/security/pkcs11/rsa/TestKeyFactory.java b/jdk/test/sun/security/pkcs11/rsa/TestKeyFactory.java index d8292bcbad3..f999afae4e6 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestKeyFactory.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestKeyFactory.java @@ -27,7 +27,7 @@ * @summary Test KeyFactory of the new RSA provider * @author Andreas Sterbenz * @library .. - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestKeyFactory * @run main/othervm TestKeyFactory sm rsakeys.ks.policy */ diff --git a/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java b/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java index 84bbb60ab53..6671509b1e1 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java @@ -29,7 +29,7 @@ * @library .. * @library /lib/testlibrary * @build jdk.testlibrary.* - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm -Djava.security.debug=sunpkcs11 TestKeyPairGenerator * @run main/othervm -Djava.security.debug=sunpkcs11 TestKeyPairGenerator * sm TestKeyPairGenerator.policy diff --git a/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java b/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java index 84283b81ef8..e0c61d80901 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @key randomness - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestSignatures * @run main/othervm TestSignatures sm rsakeys.ks.policy */ diff --git a/jdk/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java b/jdk/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java index 11fcaacaf79..a1689656057 100644 --- a/jdk/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java +++ b/jdk/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java @@ -33,7 +33,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm -Djdk.tls.namedGroups="secp256r1,sect193r1" * ClientJSSEServerJSSE * @run main/othervm -Djdk.tls.namedGroups="secp256r1,sect193r1" diff --git a/jdk/test/sun/security/pkcs11/tls/TestKeyMaterial.java b/jdk/test/sun/security/pkcs11/tls/TestKeyMaterial.java index 81a8b4571ba..c0b58d03d0d 100644 --- a/jdk/test/sun/security/pkcs11/tls/TestKeyMaterial.java +++ b/jdk/test/sun/security/pkcs11/tls/TestKeyMaterial.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @modules java.base/sun.security.internal.spec - * jdk.crypto.pkcs11 + * jdk.crypto.token * @run main/othervm TestKeyMaterial * @run main/othervm TestKeyMaterial sm policy */ diff --git a/jdk/test/sun/security/pkcs11/tls/TestLeadingZeroesP11.java b/jdk/test/sun/security/pkcs11/tls/TestLeadingZeroesP11.java index 2d9dc2890aa..e455cce5377 100644 --- a/jdk/test/sun/security/pkcs11/tls/TestLeadingZeroesP11.java +++ b/jdk/test/sun/security/pkcs11/tls/TestLeadingZeroesP11.java @@ -27,7 +27,7 @@ * @summary Need to strip leading zeros in TlsPremasterSecret of DHKeyAgreement * @library .. * @author Pasi Eronen - * @modules jdk.crypto.pkcs11 + * @modules jdk.crypto.token * @run main/othervm TestLeadingZeroesP11 * @run main/othervm TestLeadingZeroesP11 sm */ diff --git a/jdk/test/sun/security/pkcs11/tls/TestMasterSecret.java b/jdk/test/sun/security/pkcs11/tls/TestMasterSecret.java index de6863608d5..abaceb35268 100644 --- a/jdk/test/sun/security/pkcs11/tls/TestMasterSecret.java +++ b/jdk/test/sun/security/pkcs11/tls/TestMasterSecret.java @@ -29,7 +29,7 @@ * @library .. * @modules java.base/sun.security.internal.interfaces * java.base/sun.security.internal.spec - * jdk.crypto.pkcs11 + * jdk.crypto.token * @run main/othervm TestMasterSecret * @run main/othervm TestMasterSecret sm TestMasterSecret.policy */ diff --git a/jdk/test/sun/security/pkcs11/tls/TestPRF.java b/jdk/test/sun/security/pkcs11/tls/TestPRF.java index 47b49e9a634..9efdb0063b3 100644 --- a/jdk/test/sun/security/pkcs11/tls/TestPRF.java +++ b/jdk/test/sun/security/pkcs11/tls/TestPRF.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @modules java.base/sun.security.internal.spec - * jdk.crypto.pkcs11 + * jdk.crypto.token * @run main/othervm TestPRF * @run main/othervm TestPRF sm policy */ diff --git a/jdk/test/sun/security/pkcs11/tls/TestPremaster.java b/jdk/test/sun/security/pkcs11/tls/TestPremaster.java index 67191a7df28..6bdace21519 100644 --- a/jdk/test/sun/security/pkcs11/tls/TestPremaster.java +++ b/jdk/test/sun/security/pkcs11/tls/TestPremaster.java @@ -28,7 +28,7 @@ * @author Andreas Sterbenz * @library .. * @modules java.base/sun.security.internal.spec - * jdk.crypto.pkcs11 + * jdk.crypto.token * @run main/othervm TestPremaster * @run main/othervm TestPremaster sm policy */ diff --git a/jdk/test/tools/launcher/MiscTests.java b/jdk/test/tools/launcher/MiscTests.java index 344730afe28..dbd6255bc3a 100644 --- a/jdk/test/tools/launcher/MiscTests.java +++ b/jdk/test/tools/launcher/MiscTests.java @@ -80,8 +80,8 @@ public class MiscTests extends TestHelper { createFile(new File(mainClass + ".java"), scratch); compile(mainClass + ".java", - "--add-modules=jdk.crypto.pkcs11", - "--add-exports=jdk.crypto.pkcs11/sun.security.pkcs11=ALL-UNNAMED"); + "--add-modules=jdk.crypto.token", + "--add-exports=jdk.crypto.token/sun.security.pkcs11=ALL-UNNAMED"); File testJar = new File("Foo.jar"); testJar.delete(); diff --git a/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java b/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java index 2618fbab45b..208e36f9fa2 100644 --- a/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java +++ b/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java @@ -24,7 +24,7 @@ /** * @test * @library /lib/testlibrary - * @modules java.desktop java.compact1 jdk.compiler + * @modules java.desktop java.logging jdk.compiler * @build LimitModsTest CompilerUtils jdk.testlibrary.* * @run testng LimitModsTest * @summary Basic tests for java --limit-modules @@ -83,13 +83,12 @@ public class LimitModsTest { assertTrue(exitValue == 0); - // java --limit-modules java.compact1 --list-modules - exitValue = executeTestJava("--limit-modules", "java.compact1", "--list-modules") + // java --limit-modules java.logging --list-modules + exitValue = executeTestJava("--limit-modules", "java.logging", "--list-modules") .outputTo(System.out) .errorTo(System.out) .shouldContain("java.base") .shouldContain("java.logging") - .shouldContain("java.compact1") .shouldNotContain("java.xml") .getExitValue(); diff --git a/jdk/test/tools/launcher/modules/listmods/ListModsTest.java b/jdk/test/tools/launcher/modules/listmods/ListModsTest.java index eb21d2d5333..b386f402c47 100644 --- a/jdk/test/tools/launcher/modules/listmods/ListModsTest.java +++ b/jdk/test/tools/launcher/modules/listmods/ListModsTest.java @@ -147,12 +147,12 @@ public class ListModsTest { @Test public void testListWithLimitMods1() throws Exception { OutputAnalyzer output - = executeTestJava("--limit-modules", "java.compact1", "--list-modules") + = executeTestJava("--limit-modules", "java.management", "--list-modules") .outputTo(System.out) .errorTo(System.out); - output.shouldContain("java.compact1"); + output.shouldContain("java.rmi"); output.shouldContain("java.base"); - output.shouldNotContain("java.xml"); + output.shouldNotContain("java.scripting"); assertTrue(output.getExitValue() == 0); } @@ -161,7 +161,7 @@ public class ListModsTest { public void testListWithLimitMods2() throws Exception { OutputAnalyzer output = executeTestJava("--module-path", MODS_DIR.toString(), - "--limit-modules", "java.compact1", + "--limit-modules", "java.management", "--list-modules") .outputTo(System.out) .errorTo(System.out); From 1868b301b8d22b23c80c62f908f07990f258477d Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 14 Dec 2016 20:23:24 +0000 Subject: [PATCH 39/45] Added tag jdk-9+149 for changeset feba4cd7531e --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 8aee88cad73..a491956afa3 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -391,3 +391,4 @@ efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 6e4ff59afb5d0adf21a72c4ff534326594a99e5d jdk-9+146 c41140100bf1e5c10c7b8f3bde91c16eff7485f5 jdk-9+147 9098b2b9d997d65af0026fc2f39cf75234e26bc5 jdk-9+148 +5a846396a24c7aff01d6a8feaa7afc0a6369f04d jdk-9+149 From 1b5542196e38233076c62bc686cfa4610ae97416 Mon Sep 17 00:00:00 2001 From: John Jiang Date: Wed, 14 Dec 2016 19:23:08 -0800 Subject: [PATCH 40/45] 8164595: javax/net/ssl/FixingJavadocs/SSLSessionNulls.java fails intermittently with javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake Takes advantage of new SSLSocketTemplate to resolve this issue Reviewed-by: xuelei --- .../ssl/FixingJavadocs/SSLSessionNulls.java | 228 ++---------------- 1 file changed, 18 insertions(+), 210 deletions(-) diff --git a/jdk/test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java b/jdk/test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java index e9338cc42eb..052731876c9 100644 --- a/jdk/test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java +++ b/jdk/test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -26,6 +26,7 @@ * @bug 4387882 * @summary Need to revisit the javadocs for JSSE, especially the * promoted classes. + * @library /javax/net/ssl/templates * @run main/othervm SSLSessionNulls * * SunJSSE does not support dynamic system properties, no way to re-use @@ -33,109 +34,35 @@ * @author Brad Wetmore */ -import java.io.*; -import java.net.*; -import javax.net.ssl.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; -public class SSLSessionNulls { +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ +public class SSLSessionNulls extends SSLSocketTemplate { - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + @Override + protected void runServerApplication(SSLSocket socket) throws Exception { + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); sslIS.read(); sslOS.write(85); sslOS.flush(); - - sslSocket.close(); } - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + @Override + protected void runClientApplication(SSLSocket socket) throws Exception { + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); sslOS.write(280); sslOS.flush(); sslIS.read(); - SSLSession sslSession = sslSocket.getSession(); + SSLSession sslSession = socket.getSession(); try { sslSession.getValue(null); @@ -163,128 +90,9 @@ public class SSLSessionNulls { throw new IOException( "getValueNames didn't return 0-length arrary"); } - - sslSocket.close(); } - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SSLSessionNulls(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSessionNulls() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } + new SSLSessionNulls().run(); } } From b140a356845c5756831414309f2692e599afcb5b Mon Sep 17 00:00:00 2001 From: Masayoshi Okutsu Date: Thu, 15 Dec 2016 13:08:01 +0900 Subject: [PATCH 41/45] 8054214: JapaneseEra.getDisplayName doesn't return names if it's an additional era Reviewed-by: rriggs, naoto --- .../classes/java/time/chrono/JapaneseEra.java | 40 +++++++++++++++---- .../Calendar/SupplementalJapaneseEraTest.java | 25 +++++++++++- .../Calendar/SupplementalJapaneseEraTest.sh | 4 +- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/time/chrono/JapaneseEra.java b/jdk/src/java.base/share/classes/java/time/chrono/JapaneseEra.java index f289fdb1a93..7ae62944025 100644 --- a/jdk/src/java.base/share/classes/java/time/chrono/JapaneseEra.java +++ b/jdk/src/java.base/share/classes/java/time/chrono/JapaneseEra.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, 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 @@ -73,11 +73,13 @@ import java.io.ObjectStreamException; import java.io.Serializable; import java.time.DateTimeException; import java.time.LocalDate; +import java.time.format.TextStyle; import java.time.temporal.ChronoField; import java.time.temporal.TemporalField; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; import java.util.Arrays; +import java.util.Locale; import java.util.Objects; import sun.util.calendar.CalendarDate; @@ -125,8 +127,8 @@ public final class JapaneseEra */ public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8)); - // the number of defined JapaneseEra constants. - // There could be an extra era defined in its configuration. + // The number of predefined JapaneseEra constants. + // There may be a supplemental era defined by the property. private static final int N_ERA_CONSTANTS = HEISEI.getValue() + ERA_OFFSET; /** @@ -237,6 +239,32 @@ public final class JapaneseEra return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length); } + /** + * Gets the textual representation of this era. + *

    + * This returns the textual name used to identify the era, + * suitable for presentation to the user. + * The parameters control the style of the returned text and the locale. + *

    + * If no textual mapping is found then the {@link #getValue() numeric value} + * is returned. + * + * @param style the style of the text required, not null + * @param locale the locale to use, not null + * @return the text value of the era, not null + * @since 9 + */ + @Override + public String getDisplayName(TextStyle style, Locale locale) { + // If this JapaneseEra is a supplemental one, obtain the name from + // the era definition. + if (getValue() > N_ERA_CONSTANTS - ERA_OFFSET) { + Objects.requireNonNull(locale, "locale"); + return style.asNormal() == TextStyle.NARROW ? getAbbreviation() : getName(); + } + return Era.super.getDisplayName(style, locale); + } + //----------------------------------------------------------------------- /** * Obtains an instance of {@code JapaneseEra} from a date. @@ -338,11 +366,7 @@ public final class JapaneseEra //----------------------------------------------------------------------- String getAbbreviation() { - int index = ordinal(getValue()); - if (index == 0) { - return ""; - } - return ERA_CONFIG[index].getAbbreviation(); + return ERA_CONFIG[ordinal(getValue())].getAbbreviation(); } String getName() { diff --git a/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java index 5cc0bdc67bc..b8071b05753 100644 --- a/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java +++ b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -23,6 +23,8 @@ import java.text.SimpleDateFormat; import java.time.chrono.JapaneseDate; +import java.time.chrono.JapaneseEra; +import java.time.format.TextStyle; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; @@ -140,6 +142,27 @@ public class SupplementalJapaneseEraTest { System.err.printf("JapaneseDate: got=\"%s\", expected=\"%s\"%n", got, expected); errors++; } + JapaneseEra jera = jdate.getEra(); + got = jera.getDisplayName(TextStyle.FULL, Locale.US); + if (!NEW_ERA_NAME.equals(got)) { + System.err.printf("JapaneseEra (FULL): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_NAME); + errors++; + } + got = jera.getDisplayName(TextStyle.SHORT, Locale.US); + if (!NEW_ERA_NAME.equals(got)) { + System.err.printf("JapaneseEra (SHORT): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_NAME); + errors++; + } + got = jera.getDisplayName(TextStyle.NARROW, Locale.US); + if (!NEW_ERA_ABBR.equals(got)) { + System.err.printf("JapaneseEra (NARROW): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_ABBR); + errors++; + } + got = jera.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.US); + if (!NEW_ERA_ABBR.equals(got)) { + System.err.printf("JapaneseEra (NARROW_STANDALONE): got=\"%s\", expected=\"%s\"%n", got, NEW_ERA_ABBR); + errors++; + } } private static void testValidation(String eraName) { diff --git a/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.sh b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.sh index ade093c734b..5feb37d2e36 100644 --- a/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.sh +++ b/jdk/test/java/util/Calendar/SupplementalJapaneseEraTest.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 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 @@ -22,7 +22,7 @@ # # @test -# @bug 8048123 +# @bug 8048123 8054214 # @summary Test for jdk.calendar.japanese.supplemental.era support # @build SupplementalJapaneseEraTest # @run shell SupplementalJapaneseEraTest.sh From 0273a6202dabfb551a5291b0daf6fbf429e19092 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Thu, 15 Dec 2016 10:47:46 +0530 Subject: [PATCH 42/45] 8171138: Remove FileCopierPlugin Reviewed-by: mchung, jlaskey --- .../jlink/builder/DefaultImageBuilder.java | 36 +-- .../ArchiveEntryResourcePoolEntry.java | 2 +- .../internal/plugins/FileCopierPlugin.java | 263 ------------------ .../tools/jlink/plugin/ResourcePoolEntry.java | 4 +- .../tools/jlink/resources/plugins.properties | 6 - .../jdk.jlink/share/classes/module-info.java | 1 - jdk/test/tools/jlink/JLinkTest.java | 13 - .../jlink/plugins/FileCopierPluginTest.java | 163 ----------- 8 files changed, 6 insertions(+), 482 deletions(-) delete mode 100644 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/FileCopierPlugin.java delete mode 100644 jdk/test/tools/jlink/plugins/FileCopierPluginTest.java diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java index c3d18f4dbcb..5e01cc5f9af 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java @@ -58,7 +58,6 @@ import java.util.Set; import static java.util.stream.Collectors.*; import jdk.tools.jlink.internal.BasicImageWriter; -import jdk.tools.jlink.internal.plugins.FileCopierPlugin.SymImageFile; import jdk.tools.jlink.internal.ExecutableImage; import jdk.tools.jlink.plugin.ResourcePool; import jdk.tools.jlink.plugin.ResourcePoolEntry; @@ -149,20 +148,6 @@ public final class DefaultImageBuilder implements ImageBuilder { Files.createDirectories(mdir); } - private void storeRelease(ResourcePool pool) throws IOException { - Properties props = new Properties(); - Optional release = pool.findEntry("/java.base/release"); - if (release.isPresent()) { - try (InputStream is = release.get().content()) { - props.load(is); - } - } - File r = new File(root.toFile(), "release"); - try (FileOutputStream fo = new FileOutputStream(r)) { - props.store(fo, null); - } - } - @Override public void storeFiles(ResourcePool files) { try { @@ -180,9 +165,6 @@ public final class DefaultImageBuilder implements ImageBuilder { throw new PluginException("TargetPlatform attribute is missing for java.base module"); } - // store 'release' file - storeRelease(files); - Path bin = root.resolve(BIN_DIRNAME); // check any duplicated resource files @@ -373,8 +355,6 @@ public final class DefaultImageBuilder implements ImageBuilder { return Paths.get(LEGAL_DIRNAME, entryToFileName(entry)); case TOP: return Paths.get(entryToFileName(entry)); - case OTHER: - return Paths.get("other", entryToFileName(entry)); default: throw new IllegalArgumentException("invalid type: " + entry); } @@ -412,19 +392,11 @@ public final class DefaultImageBuilder implements ImageBuilder { } break; case TOP: - break; - case OTHER: - String filename = entryToFileName(file); - if (file instanceof SymImageFile) { - SymImageFile sym = (SymImageFile) file; - Path target = root.resolve(sym.getTargetPath()); - if (!Files.exists(target)) { - throw new IOException("Sym link target " + target - + " doesn't exist"); - } - writeSymEntry(root.resolve(filename), target); + // Copy TOP files of the "java.base" module (only) + if ("java.base".equals(file.moduleName())) { + writeEntry(in, root.resolve(entryToImagePath(file))); } else { - writeEntry(in, root.resolve(filename)); + throw new InternalError("unexpected TOP entry: " + file.path()); } break; default: diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ArchiveEntryResourcePoolEntry.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ArchiveEntryResourcePoolEntry.java index f82d98981a4..579198152eb 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ArchiveEntryResourcePoolEntry.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ArchiveEntryResourcePoolEntry.java @@ -80,7 +80,7 @@ final class ArchiveEntryResourcePoolEntry extends AbstractResourcePoolEntry { case NATIVE_LIB: return Type.NATIVE_LIB; default: - return ResourcePoolEntry.Type.OTHER; + throw new IllegalArgumentException("Unknown archive entry type: " + entry.type()); } } } diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/FileCopierPlugin.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/FileCopierPlugin.java deleted file mode 100644 index a0384bb7fd7..00000000000 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/FileCopierPlugin.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package jdk.tools.jlink.internal.plugins; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import jdk.tools.jlink.internal.PathResourcePoolEntry; -import jdk.tools.jlink.plugin.PluginException; -import jdk.tools.jlink.plugin.ResourcePool; -import jdk.tools.jlink.plugin.ResourcePoolBuilder; -import jdk.tools.jlink.plugin.ResourcePoolEntry; -import jdk.tools.jlink.plugin.Plugin; -import jdk.tools.jlink.internal.Utils; - -/** - * - * Copy files to image from various locations. - */ -public class FileCopierPlugin implements Plugin { - - public static final String NAME = "copy-files"; - - private static final class CopiedFile { - - Path source; - Path target; - } - private final List files = new ArrayList<>(); - - /** - * Symbolic link to another path. - */ - public static abstract class SymImageFile extends PathResourcePoolEntry { - - private final String targetPath; - - public SymImageFile(String targetPath, String module, String path, - ResourcePoolEntry.Type type, Path file) { - super(module, path, type, file); - this.targetPath = targetPath; - } - - public String getTargetPath() { - return targetPath; - } - } - - private static final class SymImageFileImpl extends SymImageFile { - - public SymImageFileImpl(String targetPath, Path file, String module, - String path, ResourcePoolEntry.Type type) { - super(targetPath, module, path, type, file); - } - } - - private static final class DirectoryCopy implements FileVisitor { - - private final Path source; - private final ResourcePoolBuilder pool; - private final String targetDir; - private final List symlinks = new ArrayList<>(); - - DirectoryCopy(Path source, ResourcePoolBuilder pool, String targetDir) { - this.source = source; - this.pool = pool; - this.targetDir = targetDir; - } - - @Override - public FileVisitResult preVisitDirectory(Path dir, - BasicFileAttributes attrs) throws IOException { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - Objects.requireNonNull(file); - Objects.requireNonNull(attrs); - String path = targetDir + "/" + source.relativize(file); - if (attrs.isSymbolicLink()) { - Path symTarget = Files.readSymbolicLink(file); - if (!Files.exists(symTarget)) { - // relative to file parent? - Path parent = file.getParent(); - if (parent != null) { - symTarget = parent.resolve(symTarget); - } - } - if (!Files.exists(symTarget)) { - System.err.println("WARNING: Skipping sym link, target " - + Files.readSymbolicLink(file) + "not found"); - return FileVisitResult.CONTINUE; - } - SymImageFileImpl impl = new SymImageFileImpl(symTarget.toString(), - file, path, Objects.requireNonNull(file.getFileName()).toString(), - ResourcePoolEntry.Type.OTHER); - symlinks.add(impl); - } else { - addFile(pool, file, path); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) - throws IOException { - if (exc != null) { - throw exc; - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - throw exc; - } - } - - private static void addFile(ResourcePoolBuilder pool, Path file, String path) - throws IOException { - Objects.requireNonNull(pool); - Objects.requireNonNull(file); - Objects.requireNonNull(path); - ResourcePoolEntry impl = ResourcePoolEntry.create( - "/java.base/other/" + path, - ResourcePoolEntry.Type.OTHER, file); - try { - pool.add(impl); - } catch (Exception ex) { - throw new IOException(ex); - } - } - - @Override - public void configure(Map config) { - List arguments = Utils.parseList(config.get(NAME)); - if (arguments.isEmpty()) { - throw new RuntimeException("Invalid argument for " + NAME); - } - - String javahome = System.getProperty("java.home"); - for (String a : arguments) { - int i = a.indexOf("="); - CopiedFile cf = new CopiedFile(); - if (i == -1) { - Path file = Paths.get(a); - if (file.isAbsolute()) { - cf.source = file; - // The target is the image root directory. - cf.target = file.getFileName(); - } else { - file = new File(javahome, a).toPath(); - cf.source = file; - cf.target = Paths.get(a); - } - } else { - String target = a.substring(i + 1); - String f = a.substring(0, i); - Path file = Paths.get(f); - if (file.isAbsolute()) { - cf.source = file; - } else { - cf.source = new File(javahome, - file.toFile().getPath()).toPath(); - } - cf.target = Paths.get(target); - } - if (!Files.exists(cf.source)) { - System.err.println("Skipping file " + cf.source - + ", it doesn't exist"); - } else { - files.add(cf); - } - } - } - - @Override - public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) { - in.transformAndCopy((file) -> { - return file; - }, out); - - // Add new files. - try { - for (CopiedFile file : files) { - if (Files.isRegularFile(file.source)) { - addFile(out, file.source, file.target.toString()); - } else if (Files.isDirectory(file.source)) { - DirectoryCopy dc = new DirectoryCopy(file.source, - out, file.target.toString()); - Files.walkFileTree(file.source, dc); - // Add symlinks after actual content - for (SymImageFile imf : dc.symlinks) { - try { - out.add(imf); - } catch (Exception ex) { - throw new PluginException(ex); - } - } - } - } - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - - return out.build(); - } - - @Override - public String getName() { - return NAME; - } - - @Override - public String getDescription() { - return PluginsResourceBundle.getDescription(NAME); - } - - @Override - public boolean hasArguments() { - return true; - } - - @Override - public String getArgumentsDescription() { - return PluginsResourceBundle.getArgument(NAME); - } -} diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/ResourcePoolEntry.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/ResourcePoolEntry.java index 6bb7d39d69a..cf09709036c 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/ResourcePoolEntry.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/plugin/ResourcePoolEntry.java @@ -58,7 +58,6 @@ public interface ResourcePoolEntry { *

      NATIVE_CMD: A native executable launcher.
    *
      NATIVE_LIB: A native library.
    *
      TOP: A top-level file in the jdk run-time image directory.
    - *
      OTHER: Other kind of file.
    * */ public enum Type { @@ -69,8 +68,7 @@ public interface ResourcePoolEntry { MAN_PAGE, NATIVE_CMD, NATIVE_LIB, - TOP, - OTHER + TOP } /** diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties index 207d1191f5d..3c2983e8d7e 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties @@ -52,12 +52,6 @@ compact-cp.description=Constant Pool strings sharing.\n\ By default, all resources are compressed. You can express the set \n\ of resources to compress or not compress (use ^ for negation). -copy-files.argument== to copy to the image>. - -copy-files.description=\ -If files to copy are not absolute path, JDK home dir is used.\n\ -e.g.: /home/me/myfile.txt=somewhere/conf.txt - dedup-legal-notices.argument=[error-if-not-same-content] dedup-legal-notices.description=\ diff --git a/jdk/src/jdk.jlink/share/classes/module-info.java b/jdk/src/jdk.jlink/share/classes/module-info.java index cb42350e8c2..659e98b5aad 100644 --- a/jdk/src/jdk.jlink/share/classes/module-info.java +++ b/jdk/src/jdk.jlink/share/classes/module-info.java @@ -36,7 +36,6 @@ module jdk.jlink { jdk.tools.jlink.internal.Main.JlinkToolProvider; provides jdk.tools.jlink.plugin.Plugin with - jdk.tools.jlink.internal.plugins.FileCopierPlugin, jdk.tools.jlink.internal.plugins.StripDebugPlugin, jdk.tools.jlink.internal.plugins.ExcludePlugin, jdk.tools.jlink.internal.plugins.ExcludeFilesPlugin, diff --git a/jdk/test/tools/jlink/JLinkTest.java b/jdk/test/tools/jlink/JLinkTest.java index 0e52ac361c9..874c9dfef32 100644 --- a/jdk/test/tools/jlink/JLinkTest.java +++ b/jdk/test/tools/jlink/JLinkTest.java @@ -190,19 +190,6 @@ public class JLinkTest { } } - { - // License files - Path file = Paths.get("LICENSE"); - Files.createFile(file); - String copied = "LICENSE"; - String[] arr = copied.split(","); - String[] copyFiles = new String[2]; - copyFiles[0] = "--copy-files"; - copyFiles[1] = file.toAbsolutePath().toString(); - Path imageDir = helper.generateDefaultImage(copyFiles, "composite2").assertSuccess(); - helper.checkImage(imageDir, "composite2", null, null, arr); - } - { // List plugins StringWriter writer = new StringWriter(); diff --git a/jdk/test/tools/jlink/plugins/FileCopierPluginTest.java b/jdk/test/tools/jlink/plugins/FileCopierPluginTest.java deleted file mode 100644 index 9137ed30e1e..00000000000 --- a/jdk/test/tools/jlink/plugins/FileCopierPluginTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/* - * @test - * @summary Test files copy plugin - * @author Jean-Francois Denise - * @modules jdk.jlink/jdk.tools.jlink.internal - * jdk.jlink/jdk.tools.jlink.builder - * jdk.jlink/jdk.tools.jlink.internal.plugins - * @run main FileCopierPluginTest - */ - -import java.io.File; -import java.net.URI; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import jdk.tools.jlink.internal.ResourcePoolManager; -import jdk.tools.jlink.builder.DefaultImageBuilder; - -import jdk.tools.jlink.internal.plugins.FileCopierPlugin; -import jdk.tools.jlink.plugin.PluginException; -import jdk.tools.jlink.plugin.ResourcePoolEntry; -import jdk.tools.jlink.plugin.ResourcePool; - -public class FileCopierPluginTest { - - public static void main(String[] args) throws Exception { - new FileCopierPluginTest().test(); - } - - /** - * 3 cases - Absolute, no target ==> copy in image root dir - Absolute and - * target ==> copy in image root dir/target - Relative ==> copy from JDK - * home dir. - * - * @throws Exception - */ - public void test() throws Exception { - FileCopierPlugin plug = new FileCopierPlugin(); - String content = "You \n should \n be \bthere.\n"; - String name = "sample.txt"; - File src = new File("src"); - src.mkdir(); - // Need a fake bin - File bin = new File("bin"); - bin.mkdir(); - - File txt = new File(src, name); - txt.createNewFile(); - - String target = "target" + File.separator + name; - Files.write(txt.toPath(), content.getBytes()); - File lic = new File(System.getProperty("java.home"), "LICENSE.txt"); - StringBuilder builder = new StringBuilder(); - int expected = lic.exists() ? 4 : 3; - if (lic.exists()) { - builder.append("LICENSE.txt,"); - } - builder.append(txt.getAbsolutePath()+","); - builder.append(txt.getAbsolutePath() + "=" + target+","); - builder.append(src.getAbsolutePath() + "=src2"); - - Map conf = new HashMap<>(); - conf.put(FileCopierPlugin.NAME, builder.toString()); - plug.configure(conf); - ResourcePoolManager poolMgr = new ResourcePoolManager(); - // java.base/module-info.class is used to add "release" file - // We read it from jrt-fs and add a ResourcePoolEntry - poolMgr.add( - ResourcePoolEntry.create("/java.base/module-info.class", - ResourcePoolEntry.Type.CLASS_OR_RESOURCE, getJavaBaseModuleInfo())); - expected++; - ResourcePool pool = plug.transform( - new ResourcePoolManager().resourcePool(), - poolMgr.resourcePoolBuilder()); - if (pool.entryCount() != expected) { - throw new AssertionError("Wrong number of added files"); - } - pool.entries().forEach(f -> { - if (!f.type().equals(ResourcePoolEntry.Type.OTHER) && - !f.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)) { - throw new AssertionError("Invalid type " + f.type() - + " for file " + f.path()); - } - if (f.content() == null) { - throw new AssertionError("Null stream for file " + f.path()); - } - }); - Path root = new File(".").toPath(); - DefaultImageBuilder imgbuilder = new DefaultImageBuilder(root); - imgbuilder.storeFiles(pool); - - if (lic.exists()) { - File license = new File(root.toFile(), "LICENSE.txt"); - if (!license.exists() || license.length() == 0) { - throw new AssertionError("Invalid license file " - + license.getAbsoluteFile()); - } - } - - File sample1 = new File(root.toFile(), txt.getName()); - if (!sample1.exists() || sample1.length() == 0) { - throw new AssertionError("Invalide sample1 file " - + sample1.getAbsoluteFile()); - } - if (!new String(Files.readAllBytes(sample1.toPath())).equals(content)) { - throw new AssertionError("Invalid Content in sample1"); - } - - File sample2 = new File(root.toFile(), target); - if (!sample2.exists() || sample2.length() == 0) { - throw new AssertionError("Invalide sample2 file " - + sample2.getAbsoluteFile()); - } - if (!new String(Files.readAllBytes(sample2.toPath())).equals(content)) { - throw new AssertionError("Invalid Content in sample2"); - } - - File src2 = new File(root.toFile(), "src2"); - if (!src2.exists() || src2.list().length != 1) { - throw new AssertionError("Invalide src2 dir " - + src2.getAbsoluteFile()); - } - File f = src2.listFiles()[0]; - if (!f.getName().equals(txt.getName())) { - throw new AssertionError("Invalide file name in src2 dir " - + f.getAbsoluteFile()); - } - if (!new String(Files.readAllBytes(f.toPath())).equals(content)) { - throw new AssertionError("Invalid Content in src2 dir"); - } - } - - // read java.base/module-info.class from jrt-fs - private static Path getJavaBaseModuleInfo() { - return Paths.get(URI.create("jrt:/modules/java.base/module-info.class")); - } -} From 91d9ddb0b6be525c12c339ff56bf29475b6705b5 Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Thu, 15 Dec 2016 17:34:59 +0800 Subject: [PATCH 43/45] 8171234: Remove intermittent key from test java/nio/charset/coders/BashStreams.java Reviewed-by: alanb --- jdk/test/java/nio/charset/coders/BashStreams.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/java/nio/charset/coders/BashStreams.java b/jdk/test/java/nio/charset/coders/BashStreams.java index 1658021210b..b8f775d9e8b 100644 --- a/jdk/test/java/nio/charset/coders/BashStreams.java +++ b/jdk/test/java/nio/charset/coders/BashStreams.java @@ -23,7 +23,7 @@ /* @test * @summary Stochastic test of charset-based streams - * @key randomness intermittent + * @key randomness */ import java.io.*; From 5cd134407d5c82b7abd53eb71fab5e9232ec0370 Mon Sep 17 00:00:00 2001 From: Pavel Rappo Date: Mon, 19 Dec 2016 16:00:59 +0000 Subject: [PATCH 44/45] 8164907: Eliminate dependency on java.naming/com.sun.jndi.toolkit.url Reviewed-by: chegar, rriggs --- .../jndi/cosnaming/CNBindingEnumeration.java | 235 ---- .../classes/com/sun/jndi/cosnaming/CNCtx.java | 1158 ----------------- .../com/sun/jndi/cosnaming/CNCtxFactory.java | 51 - .../com/sun/jndi/cosnaming/CNNameParser.java | 500 ------- .../com/sun/jndi/cosnaming/CorbanameUrl.java | 132 -- .../sun/jndi/cosnaming/ExceptionMapper.java | 242 ---- .../com/sun/jndi/cosnaming/IiopUrl.java | 228 ---- .../sun/jndi/cosnaming/OrbReuseTracker.java | 70 - .../com/sun/jndi/cosnaming/RemoteToCorba.java | 81 -- .../jndi/cosnaming/jndiprovider.properties | 4 - .../sun/jndi/toolkit/corba/CorbaUtils.java | 179 --- .../corbaname/corbanameURLContextFactory.java | 38 - .../com/sun/jndi/url/iiop/iiopURLContext.java | 84 -- .../jndi/url/iiop/iiopURLContextFactory.java | 101 -- .../iiopname/iiopnameURLContextFactory.java | 38 - .../share/classes/module-info.java | 1 - 16 files changed, 3142 deletions(-) delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNBindingEnumeration.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtx.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtxFactory.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNNameParser.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CorbanameUrl.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/ExceptionMapper.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/IiopUrl.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/OrbReuseTracker.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/url/corbaname/corbanameURLContextFactory.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContext.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContextFactory.java delete mode 100644 jdk/src/java.corba/share/classes/com/sun/jndi/url/iiopname/iiopnameURLContextFactory.java diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNBindingEnumeration.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNBindingEnumeration.java deleted file mode 100644 index ae5c61d6fe7..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNBindingEnumeration.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.*; -import javax.naming.spi.NamingManager; - -import java.util.NoSuchElementException; -import java.util.Hashtable; - -import org.omg.CosNaming.*; - -/** - * Implements the JNDI NamingEnumeration interface for COS - * Naming. Gets hold of a list of bindings from the COS Naming Server - * and allows the client to iterate through them. - * - * @author Raj Krishnamurthy - * @author Rosanna Lee - */ - -final class CNBindingEnumeration - implements NamingEnumeration { - - private static final int DEFAULT_BATCHSIZE = 100; - private BindingListHolder _bindingList; // list of bindings - private BindingIterator _bindingIter; // iterator for getting list of bindings - private int counter; // pointer in _bindingList - private int batchsize = DEFAULT_BATCHSIZE; // how many to ask for each time - private CNCtx _ctx; // ctx to list - private Hashtable _env; // environment for getObjectInstance - private boolean more = false; // iterator done? - private boolean isLookedUpCtx = false; // iterating on a context beneath this context ? - - /** - * Creates a CNBindingEnumeration object. - * @param ctx Context to enumerate - */ - CNBindingEnumeration(CNCtx ctx, boolean isLookedUpCtx, Hashtable env) { - // Get batch size to use - String batch = (env != null ? - (String)env.get(javax.naming.Context.BATCHSIZE) : null); - if (batch != null) { - try { - batchsize = Integer.parseInt(batch); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Batch size not numeric: " + batch); - } - } - _ctx = ctx; - _ctx.incEnumCount(); - this.isLookedUpCtx = isLookedUpCtx; - _env = env; - _bindingList = new BindingListHolder(); - BindingIteratorHolder _bindingIterH = new BindingIteratorHolder(); - - // Perform listing and request that bindings be returned in _bindingIter - // Upon return,_bindingList returns a zero length list - _ctx._nc.list(0, _bindingList, _bindingIterH); - - _bindingIter = _bindingIterH.value; - - // Get first batch using _bindingIter - if (_bindingIter != null) { - more = _bindingIter.next_n(batchsize, _bindingList); - } else { - more = false; - } - counter = 0; - } - - /** - * Returns the next binding in the list. - * @exception NamingException any naming exception. - */ - - public javax.naming.Binding next() throws NamingException { - if (more && counter >= _bindingList.value.length) { - getMore(); - } - if (more && counter < _bindingList.value.length) { - org.omg.CosNaming.Binding bndg = _bindingList.value[counter]; - counter++; - return mapBinding(bndg); - } else { - throw new NoSuchElementException(); - } - } - - - /** - * Returns true or false depending on whether there are more bindings. - * @return boolean value - */ - - public boolean hasMore() throws NamingException { - // If there's more, check whether current bindingList has been exhausted, - // and if so, try to get more. - // If no more, just say so. - return more ? (counter < _bindingList.value.length || getMore()) : false; - } - - /** - * Returns true or false depending on whether there are more bindings. - * Need to define this to satisfy the Enumeration api requirement. - * @return boolean value - */ - - public boolean hasMoreElements() { - try { - return hasMore(); - } catch (NamingException e) { - return false; - } - } - - /** - * Returns the next binding in the list. - * @exception NoSuchElementException Thrown when the end of the - * list is reached. - */ - - public javax.naming.Binding nextElement() { - try { - return next(); - } catch (NamingException ne) { - throw new NoSuchElementException(); - } - } - - public void close() throws NamingException { - more = false; - if (_bindingIter != null) { - _bindingIter.destroy(); - _bindingIter = null; - } - if (_ctx != null) { - _ctx.decEnumCount(); - - /** - * context was obtained by CNCtx, the user doesn't have a handle to - * it, close it as we are done enumerating through the context - */ - if (isLookedUpCtx) { - _ctx.close(); - } - _ctx = null; - } - } - - protected void finalize() { - try { - close(); - } catch (NamingException e) { - // ignore failures - } - } - - /** - * Get the next batch using _bindingIter. Update the 'more' field. - */ - private boolean getMore() throws NamingException { - try { - more = _bindingIter.next_n(batchsize, _bindingList); - counter = 0; // reset - } catch (Exception e) { - more = false; - NamingException ne = new NamingException( - "Problem getting binding list"); - ne.setRootCause(e); - throw ne; - } - return more; - } - - /** - * Constructs a JNDI Binding object from the COS Naming binding - * object. - * @exception NameNotFound No objects under the name. - * @exception CannotProceed Unable to obtain a continuation context - * @exception InvalidName Name not understood. - * @exception NamingException One of the above. - */ - - private javax.naming.Binding mapBinding(org.omg.CosNaming.Binding bndg) - throws NamingException { - java.lang.Object obj = _ctx.callResolve(bndg.binding_name); - - Name cname = CNNameParser.cosNameToName(bndg.binding_name); - - try { - obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env); - } catch (NamingException e) { - throw e; - } catch (Exception e) { - NamingException ne = new NamingException( - "problem generating object using object factory"); - ne.setRootCause(e); - throw ne; - } - - // Use cname.toString() instead of bindingName because the name - // in the binding should be a composite name - String cnameStr = cname.toString(); - javax.naming.Binding jbndg = new javax.naming.Binding(cnameStr, obj); - - NameComponent[] comps = _ctx.makeFullName(bndg.binding_name); - String fullName = CNNameParser.cosNameToInsString(comps); - jbndg.setNameInNamespace(fullName); - return jbndg; - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtx.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtx.java deleted file mode 100644 index 3d77c3746b7..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtx.java +++ /dev/null @@ -1,1158 +0,0 @@ -/* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.*; -import javax.naming.spi.NamingManager; -import javax.naming.spi.ResolveResult; - -import java.util.Hashtable; -import java.net.MalformedURLException; -import java.net.URL; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.BufferedReader; -import java.io.IOException; - -import org.omg.CosNaming.*; -import org.omg.CosNaming.NamingContextPackage.*; -import org.omg.CORBA.*; - -import com.sun.jndi.toolkit.corba.CorbaUtils; - -// Needed for creating default ORB -import java.applet.Applet; - -/** - * Provides a bridge to the CosNaming server provided by - * JavaIDL. This class provides the InitialContext from CosNaming. - * - * @author Raj Krishnamurthy - * @author Rosanna Lee - */ - -public class CNCtx implements javax.naming.Context { - - private final static boolean debug = false; - - /* - * Implement one shared ORB among all CNCtx. However, there is a public constructor - * accepting an ORB, so we need the option of using a given ORB. - */ - private static ORB _defaultOrb; - ORB _orb; // used by ExceptionMapper and RMI/IIOP factory - public NamingContext _nc; // public for accessing underlying NamingContext - - private synchronized static ORB getDefaultOrb() { - if (_defaultOrb == null) { - _defaultOrb = CorbaUtils.getOrb(null, -1, - new Hashtable()); - } - return _defaultOrb; - } - - private NameComponent[] _name = null; - - Hashtable _env; // used by ExceptionMapper - static final CNNameParser parser = new CNNameParser(); - - private static final String FED_PROP = "com.sun.jndi.cosnaming.federation"; - boolean federation = false; - - // Reference counter for tracking _orb references - OrbReuseTracker orbTracker = null; - int enumCount; - boolean isCloseCalled = false; - - /** - * Create a CNCtx object. Gets the initial naming - * reference for the COS Naming Service from the ORB. - * The ORB can be passed in via the java.naming.corba.orb property - * or be created using properties in the environment properties. - * @param env Environment properties for initializing name service. - * @exception NamingException Cannot initialize ORB or naming context. - */ - @SuppressWarnings("unchecked") - CNCtx(Hashtable env) throws NamingException { - if (env != null) { - env = (Hashtable)env.clone(); - } - _env = (Hashtable)env; - federation = "true".equals(env != null ? env.get(FED_PROP) : null); - initOrbAndRootContext(env); - } - - private CNCtx() { - } - - /** - * This method is used by the iiop and iiopname URL Context factories. - */ - @SuppressWarnings("unchecked") - public static ResolveResult createUsingURL(String url, Hashtable env) - throws NamingException { - CNCtx ctx = new CNCtx(); - if (env != null) { - env = (Hashtable) env.clone(); - } - ctx._env = (Hashtable)env; - String rest = ctx.initUsingUrl( - env != null ? - (org.omg.CORBA.ORB) env.get("java.naming.corba.orb") - : null, - url, env); - - // rest is the INS name - // Return the parsed form to prevent subsequent lookup - // from parsing the string as a composite name - // The caller should be aware that a toString() of the name, - // which came from the environment will yield its INS syntax, - // rather than a composite syntax - return new ResolveResult(ctx, parser.parse(rest)); - } - - /** - * Creates a CNCtx object which supports the javax.naming - * apis given a COS Naming Context object. - * @param orb The ORB used by this context - * @param tracker The ORB reuse tracker for tracking references to the - * orb object - * @param nctx The COS NamingContext object associated with this context - * @param name The name of this context relative to the root - */ - - CNCtx(ORB orb, OrbReuseTracker tracker, NamingContext nctx, - Hashtable env, NameComponent[]name) - throws NamingException { - if (orb == null || nctx == null) - throw new ConfigurationException( - "Must supply ORB or NamingContext"); - if (orb != null) { - _orb = orb; - } else { - _orb = getDefaultOrb(); - } - _nc = nctx; - _env = env; - _name = name; - federation = "true".equals(env != null ? env.get(FED_PROP) : null); - } - - NameComponent[] makeFullName(NameComponent[] child) { - if (_name == null || _name.length == 0) { - return child; - } - NameComponent[] answer = new NameComponent[_name.length+child.length]; - - // parent - System.arraycopy(_name, 0, answer, 0, _name.length); - - // child - System.arraycopy(child, 0, answer, _name.length, child.length); - return answer; - } - - - public String getNameInNamespace() throws NamingException { - if (_name == null || _name.length == 0) { - return ""; - } - return CNNameParser.cosNameToInsString(_name); - } - - /** - * These are the URL schemes that need to be processed. - * IOR and corbaloc URLs can be passed directly to ORB.string_to_object() - */ - private static boolean isCorbaUrl(String url) { - return url.startsWith("iiop://") - || url.startsWith("iiopname://") - || url.startsWith("corbaname:") - ; - } - - /** - * Initializes the COS Naming Service. - * This method initializes the three instance fields: - * _nc : The root naming context. - * _orb: The ORB to use for connecting RMI/IIOP stubs and for - * getting the naming context (_nc) if one was not specified - * explicitly via PROVIDER_URL. - * _name: The name of the root naming context. - *

    - * _orb is obtained from java.naming.corba.orb if it has been set. - * Otherwise, _orb is created using the host/port from PROVIDER_URL - * (if it contains an "iiop" or "iiopname" URL), or from initialization - * properties specified in env. - *

    - * _nc is obtained from the IOR stored in PROVIDER_URL if it has been - * set and does not contain an "iiop" or "iiopname" URL. It can be - * a stringified IOR, "corbaloc" URL, "corbaname" URL, - * or a URL (such as file/http/ftp) to a location - * containing a stringified IOR. If PROVIDER_URL has not been - * set in this way, it is obtained from the result of - * ORB.resolve_initial_reference("NameService"); - *

    - * _name is obtained from the "iiop", "iiopname", or "corbaname" URL. - * It is the empty name by default. - * - * @param env Environment The possibly null environment. - * @exception NamingException When an error occurs while initializing the - * ORB or the naming context. - */ - private void initOrbAndRootContext(Hashtable env) throws NamingException { - org.omg.CORBA.ORB inOrb = null; - String ncIor = null; - - if (inOrb == null && env != null) { - inOrb = (org.omg.CORBA.ORB) env.get("java.naming.corba.orb"); - } - - if (inOrb == null) - inOrb = getDefaultOrb(); // will create a default ORB if none exists - - // Extract PROVIDER_URL from environment - String provUrl = null; - if (env != null) { - provUrl = (String)env.get(javax.naming.Context.PROVIDER_URL); - } - - if (provUrl != null && !isCorbaUrl(provUrl)) { - // Initialize the root naming context by using the IOR supplied - // in the PROVIDER_URL - ncIor = getStringifiedIor(provUrl); - setOrbAndRootContext(inOrb, ncIor); - } else if (provUrl != null) { - // Initialize the root naming context by using the URL supplied - // in the PROVIDER_URL - String insName = initUsingUrl(inOrb, provUrl, env); - - // If name supplied in URL, resolve it to a NamingContext - if (insName.length() > 0) { - _name = CNNameParser.nameToCosName(parser.parse(insName)); - try { - org.omg.CORBA.Object obj = _nc.resolve(_name); - _nc = NamingContextHelper.narrow(obj); - if (_nc == null) { - throw new ConfigurationException(insName + - " does not name a NamingContext"); - } - } catch (org.omg.CORBA.BAD_PARAM e) { - throw new ConfigurationException(insName + - " does not name a NamingContext"); - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, _name); - } - } - } else { - // No PROVIDER_URL supplied; initialize using defaults - if (debug) { - System.err.println("Getting default ORB: " + inOrb + env); - } - setOrbAndRootContext(inOrb, (String)null); - } - } - - - private String initUsingUrl(ORB orb, String url, Hashtable env) - throws NamingException { - if (url.startsWith("iiop://") || url.startsWith("iiopname://")) { - return initUsingIiopUrl(orb, url, env); - } else { - return initUsingCorbanameUrl(orb, url, env); - } - } - - /** - * Handles "iiop" and "iiopname" URLs (INS 98-10-11) - */ - private String initUsingIiopUrl(ORB defOrb, String url, Hashtable env) - throws NamingException { - - if (defOrb == null) - defOrb = getDefaultOrb(); - - try { - IiopUrl parsedUrl = new IiopUrl(url); - - NamingException savedException = null; - - for (IiopUrl.Address addr : parsedUrl.getAddresses()) { - - try { - try { - String tmpUrl = "corbaloc:iiop:" + addr.host - + ":" + addr.port + "/NameService"; - if (debug) { - System.err.println("Using url: " + tmpUrl); - } - org.omg.CORBA.Object rootCtx = - defOrb.string_to_object(tmpUrl); - setOrbAndRootContext(defOrb, rootCtx); - return parsedUrl.getStringName(); - } catch (Exception e) {} // keep going - - // Get ORB - if (debug) { - System.err.println("Getting ORB for " + addr.host - + " and port " + addr.port); - } - - // Assign to fields - setOrbAndRootContext(defOrb, (String)null); - return parsedUrl.getStringName(); - - } catch (NamingException ne) { - savedException = ne; - } - } - if (savedException != null) { - throw savedException; - } else { - throw new ConfigurationException("Problem with URL: " + url); - } - } catch (MalformedURLException e) { - throw new ConfigurationException(e.getMessage()); - } - } - - /** - * Initializes using "corbaname" URL (INS 99-12-03) - */ - private String initUsingCorbanameUrl(ORB orb, String url, Hashtable env) - throws NamingException { - - if (orb == null) - orb = getDefaultOrb(); - - try { - CorbanameUrl parsedUrl = new CorbanameUrl(url); - - String corbaloc = parsedUrl.getLocation(); - String cosName = parsedUrl.getStringName(); - - setOrbAndRootContext(orb, corbaloc); - - return parsedUrl.getStringName(); - } catch (MalformedURLException e) { - throw new ConfigurationException(e.getMessage()); - } - } - - private void setOrbAndRootContext(ORB orb, String ncIor) - throws NamingException { - _orb = orb; - try { - org.omg.CORBA.Object ncRef; - if (ncIor != null) { - if (debug) { - System.err.println("Passing to string_to_object: " + ncIor); - } - ncRef = _orb.string_to_object(ncIor); - } else { - ncRef = _orb.resolve_initial_references("NameService"); - } - if (debug) { - System.err.println("Naming Context Ref: " + ncRef); - } - _nc = NamingContextHelper.narrow(ncRef); - if (_nc == null) { - if (ncIor != null) { - throw new ConfigurationException( - "Cannot convert IOR to a NamingContext: " + ncIor); - } else { - throw new ConfigurationException( -"ORB.resolve_initial_references(\"NameService\") does not return a NamingContext"); - } - } - } catch (org.omg.CORBA.ORBPackage.InvalidName in) { - NamingException ne = - new ConfigurationException( -"COS Name Service not registered with ORB under the name 'NameService'"); - ne.setRootCause(in); - throw ne; - } catch (org.omg.CORBA.COMM_FAILURE e) { - NamingException ne = - new CommunicationException("Cannot connect to ORB"); - ne.setRootCause(e); - throw ne; - } catch (org.omg.CORBA.BAD_PARAM e) { - NamingException ne = new ConfigurationException( - "Invalid URL or IOR: " + ncIor); - ne.setRootCause(e); - throw ne; - } catch (org.omg.CORBA.INV_OBJREF e) { - NamingException ne = new ConfigurationException( - "Invalid object reference: " + ncIor); - ne.setRootCause(e); - throw ne; - } - } - - private void setOrbAndRootContext(ORB orb, org.omg.CORBA.Object ncRef) - throws NamingException { - _orb = orb; - try { - _nc = NamingContextHelper.narrow(ncRef); - if (_nc == null) { - throw new ConfigurationException( - "Cannot convert object reference to NamingContext: " + ncRef); - } - } catch (org.omg.CORBA.COMM_FAILURE e) { - NamingException ne = - new CommunicationException("Cannot connect to ORB"); - ne.setRootCause(e); - throw ne; - } - } - - private String getStringifiedIor(String url) throws NamingException { - if (url.startsWith("IOR:") || url.startsWith("corbaloc:")) { - return url; - } else { - InputStream in = null; - try { - URL u = new URL(url); - in = u.openStream(); - if (in != null) { - BufferedReader bufin = - new BufferedReader(new InputStreamReader(in, "8859_1")); - String str; - while ((str = bufin.readLine()) != null) { - if (str.startsWith("IOR:")) { - return str; - } - } - } - } catch (IOException e) { - NamingException ne = - new ConfigurationException("Invalid URL: " + url); - ne.setRootCause(e); - throw ne; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException e) { - NamingException ne = - new ConfigurationException("Invalid URL: " + url); - ne.setRootCause(e); - throw ne; - } - } - throw new ConfigurationException(url + " does not contain an IOR"); - } - } - - - /** - * Does the job of calling the COS Naming API, - * resolve, and performs the exception mapping. If the resolved - * object is a COS Naming Context (sub-context), then this function - * returns a new JNDI naming context object. - * @param path the NameComponent[] object. - * @exception NotFound No objects under the name. - * @exception CannotProceed Unable to obtain a continuation context - * @exception InvalidName Name not understood. - * @return Resolved object returned by the COS Name Server. - */ - java.lang.Object callResolve(NameComponent[] path) - throws NamingException { - try { - org.omg.CORBA.Object obj = _nc.resolve(path); - try { - NamingContext nc = - NamingContextHelper.narrow(obj); - if (nc != null) { - return new CNCtx(_orb, orbTracker, nc, _env, - makeFullName(path)); - } else { - return obj; - } - } catch (org.omg.CORBA.SystemException e) { - return obj; - } - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, path); - } - } - - /** - * Converts the "String" name into a CompositeName - * returns the object resolved by the COS Naming api, - * resolve. Returns the current context if the name is empty. - * Returns either an org.omg.CORBA.Object or javax.naming.Context object. - * @param name string used to resolve the object. - * @exception NamingException See callResolve. - * @return the resolved object - */ - public java.lang.Object lookup(String name) throws NamingException { - if (debug) { - System.out.println("Looking up: " + name); - } - return lookup(new CompositeName(name)); - } - - /** - * Converts the "Name" name into a NameComponent[] object and - * returns the object resolved by the COS Naming api, - * resolve. Returns the current context if the name is empty. - * Returns either an org.omg.CORBA.Object or javax.naming.Context object. - * @param name JNDI Name used to resolve the object. - * @exception NamingException See callResolve. - * @return the resolved object - */ - public java.lang.Object lookup(Name name) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - if (name.size() == 0 ) - return this; // %%% should clone() so that env can be changed - NameComponent[] path = CNNameParser.nameToCosName(name); - - try { - java.lang.Object answer = callResolve(path); - - try { - return NamingManager.getObjectInstance(answer, name, this, _env); - } catch (NamingException e) { - throw e; - } catch (Exception e) { - NamingException ne = new NamingException( - "problem generating object using object factory"); - ne.setRootCause(e); - throw ne; - } - } catch (CannotProceedException cpe) { - javax.naming.Context cctx = getContinuationContext(cpe); - return cctx.lookup(cpe.getRemainingName()); - } - } - - /** - * Performs bind or rebind in the context depending on whether the - * flag rebind is set. The only objects allowed to be bound are of - * types org.omg.CORBA.Object, org.omg.CosNaming.NamingContext. - * You can use a state factory to turn other objects (such as - * Remote) into these acceptable forms. - * - * Uses the COS Naming apis bind/rebind or - * bind_context/rebind_context. - * @param pth NameComponent[] object - * @param obj Object to be bound. - * @param rebind perform rebind ? if true performs a rebind. - * @exception NotFound No objects under the name. - * @exception CannotProceed Unable to obtain a continuation context - * @exception AlreadyBound An object is already bound to this name. - */ - private void callBindOrRebind(NameComponent[] pth, Name name, - java.lang.Object obj, boolean rebind) throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - try { - // Call state factories to convert - obj = NamingManager.getStateToBind(obj, name, this, _env); - - if (obj instanceof CNCtx) { - // Use naming context object reference - obj = ((CNCtx)obj)._nc; - } - - if ( obj instanceof org.omg.CosNaming.NamingContext) { - NamingContext nobj = - NamingContextHelper.narrow((org.omg.CORBA.Object)obj); - if (rebind) - _nc.rebind_context(pth,nobj); - else - _nc.bind_context(pth,nobj); - - } else if (obj instanceof org.omg.CORBA.Object) { - if (rebind) - _nc.rebind(pth,(org.omg.CORBA.Object)obj); - else - _nc.bind(pth,(org.omg.CORBA.Object)obj); - } - else - throw new IllegalArgumentException( - "Only instances of org.omg.CORBA.Object can be bound"); - } catch (BAD_PARAM e) { - // probably narrow() failed? - NamingException ne = new NotContextException(name.toString()); - ne.setRootCause(e); - throw ne; - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, pth); - } - } - - /** - * Converts the "Name" name into a NameComponent[] object and - * performs the bind operation. Uses callBindOrRebind. Throws an - * invalid name exception if the name is empty. We need a name to - * bind the object even when we work within the current context. - * @param name JNDI Name object - * @param obj Object to be bound. - * @exception NamingException See callBindOrRebind - */ - public void bind(Name name, java.lang.Object obj) - throws NamingException { - if (name.size() == 0 ) { - throw new InvalidNameException("Name is empty"); - } - - if (debug) { - System.out.println("Bind: " + name); - } - NameComponent[] path = CNNameParser.nameToCosName(name); - - try { - callBindOrRebind(path, name, obj, false); - } catch (CannotProceedException e) { - javax.naming.Context cctx = getContinuationContext(e); - cctx.bind(e.getRemainingName(), obj); - } - } - - static private javax.naming.Context - getContinuationContext(CannotProceedException cpe) - throws NamingException { - try { - return NamingManager.getContinuationContext(cpe); - } catch (CannotProceedException e) { - java.lang.Object resObj = e.getResolvedObj(); - if (resObj instanceof Reference) { - Reference ref = (Reference)resObj; - RefAddr addr = ref.get("nns"); - if (addr.getContent() instanceof javax.naming.Context) { - NamingException ne = new NameNotFoundException( - "No object reference bound for specified name"); - ne.setRootCause(cpe.getRootCause()); - ne.setRemainingName(cpe.getRemainingName()); - throw ne; - } - } - throw e; - } - } - - /** - * Converts the "String" name into a CompositeName object and - * performs the bind operation. Uses callBindOrRebind. Throws an - * invalid name exception if the name is empty. - * @param name string - * @param obj Object to be bound. - * @exception NamingException See callBindOrRebind - */ - public void bind(String name, java.lang.Object obj) throws NamingException { - bind(new CompositeName(name), obj); - } - - /** - * Converts the "Name" name into a NameComponent[] object and - * performs the rebind operation. Uses callBindOrRebind. Throws an - * invalid name exception if the name is empty. We must have a name - * to rebind the object to even if we are working within the current - * context. - * @param name string - * @param obj Object to be bound. - * @exception NamingException See callBindOrRebind - */ - public void rebind(Name name, java.lang.Object obj) - throws NamingException { - if (name.size() == 0 ) { - throw new InvalidNameException("Name is empty"); - } - NameComponent[] path = CNNameParser.nameToCosName(name); - try { - callBindOrRebind(path, name, obj, true); - } catch (CannotProceedException e) { - javax.naming.Context cctx = getContinuationContext(e); - cctx.rebind(e.getRemainingName(), obj); - } - } - - /** - * Converts the "String" name into a CompositeName object and - * performs the rebind operation. Uses callBindOrRebind. Throws an - * invalid name exception if the name is an empty string. - * @param name string - * @param obj Object to be bound. - * @exception NamingException See callBindOrRebind - */ - public void rebind(String name, java.lang.Object obj) - throws NamingException { - rebind(new CompositeName(name), obj); - } - - /** - * Calls the unbind api of COS Naming and uses the exception mapper - * class to map the exceptions - * @param path NameComponent[] object - * @exception NotFound No objects under the name. If leaf - * is not found, that's OK according to the JNDI spec - * @exception CannotProceed Unable to obtain a continuation context - * @exception InvalidName Name not understood. - */ - private void callUnbind(NameComponent[] path) throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - try { - _nc.unbind(path); - } catch (NotFound e) { - // If leaf is the one missing, return success - // as per JNDI spec - - if (leafNotFound(e, path[path.length-1])) { - // do nothing - } else { - throw ExceptionMapper.mapException(e, this, path); - } - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, path); - } - } - - private boolean leafNotFound(NotFound e, NameComponent leaf) { - - // This test is not foolproof because some name servers - // always just return one component in rest_of_name - // so you might not be able to tell whether that is - // the leaf (e.g. aa/aa/aa, which one is missing?) - - NameComponent rest; - return e.why.value() == NotFoundReason._missing_node && - e.rest_of_name.length == 1 && - (rest=e.rest_of_name[0]).id.equals(leaf.id) && - (rest.kind == leaf.kind || - (rest.kind != null && rest.kind.equals(leaf.kind))); - } - - /** - * Converts the "String" name into a CompositeName object and - * performs the unbind operation. Uses callUnbind. If the name is - * empty, throws an invalid name exception. Do we unbind the - * current context (JNDI spec says work with the current context if - * the name is empty) ? - * @param name string - * @exception NamingException See callUnbind - */ - public void unbind(String name) throws NamingException { - unbind(new CompositeName(name)); - } - - /** - * Converts the "Name" name into a NameComponent[] object and - * performs the unbind operation. Uses callUnbind. Throws an - * invalid name exception if the name is empty. - * @param name string - * @exception NamingException See callUnbind - */ - public void unbind(Name name) - throws NamingException { - if (name.size() == 0 ) - throw new InvalidNameException("Name is empty"); - NameComponent[] path = CNNameParser.nameToCosName(name); - try { - callUnbind(path); - } catch (CannotProceedException e) { - javax.naming.Context cctx = getContinuationContext(e); - cctx.unbind(e.getRemainingName()); - } - } - - /** - * Renames an object. Since COS Naming does not support a rename - * api, this method unbinds the object with the "oldName" and - * creates a new binding. - * @param oldName string, existing name for the binding. - * @param newName string, name used to replace. - * @exception NamingException See bind - */ - public void rename(String oldName,String newName) - throws NamingException { - rename(new CompositeName(oldName), new CompositeName(newName)); - } - - /** - * Renames an object. Since COS Naming does not support a rename - * api, this method unbinds the object with the "oldName" and - * creates a new binding. - * @param oldName JNDI Name, existing name for the binding. - * @param newName JNDI Name, name used to replace. - * @exception NamingException See bind - */ - public void rename(Name oldName,Name newName) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - if (oldName.size() == 0 || newName.size() == 0) - throw new InvalidNameException("One or both names empty"); - java.lang.Object obj = lookup(oldName); - bind(newName,obj); - unbind(oldName); - } - - /** - * Returns a NameClassEnumeration object which has a list of name - * class pairs. Lists the current context if the name is empty. - * @param name string - * @exception NamingException All exceptions thrown by lookup - * with a non-null argument - * @return a list of name-class objects as a NameClassEnumeration. - */ - public NamingEnumeration list(String name) throws NamingException { - return list(new CompositeName(name)); - } - - /** - * Returns a NameClassEnumeration object which has a list of name - * class pairs. Lists the current context if the name is empty. - * @param name JNDI Name - * @exception NamingException All exceptions thrown by lookup - * @return a list of name-class objects as a NameClassEnumeration. - */ - @SuppressWarnings("unchecked") - public NamingEnumeration list(Name name) - throws NamingException { - return (NamingEnumeration)listBindings(name); - } - - /** - * Returns a BindingEnumeration object which has a list of name - * object pairs. Lists the current context if the name is empty. - * @param name string - * @exception NamingException all exceptions returned by lookup - * @return a list of bindings as a BindingEnumeration. - */ - public NamingEnumeration listBindings(String name) - throws NamingException { - return listBindings(new CompositeName(name)); - } - - /** - * Returns a BindingEnumeration object which has a list of name - * class pairs. Lists the current context if the name is empty. - * @param name JNDI Name - * @exception NamingException all exceptions returned by lookup. - * @return a list of bindings as a BindingEnumeration. - */ - public NamingEnumeration listBindings(Name name) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - if (name.size() > 0) { - try { - java.lang.Object obj = lookup(name); - if (obj instanceof CNCtx) { - return new CNBindingEnumeration( - (CNCtx) obj, true, _env); - } else { - throw new NotContextException(name.toString()); - } - } catch (NamingException ne) { - throw ne; - } catch (BAD_PARAM e) { - NamingException ne = - new NotContextException(name.toString()); - ne.setRootCause(e); - throw ne; - } - } - return new CNBindingEnumeration(this, false, _env); - } - - /** - * Calls the destroy on the COS Naming Server - * @param nc The NamingContext object to use. - * @exception NotEmpty when the context is not empty and cannot be destroyed. - */ - private void callDestroy(NamingContext nc) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - try { - nc.destroy(); - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, null); - } - } - - /** - * Uses the callDestroy function to destroy the context. If name is - * empty destroys the current context. - * @param name string - * @exception OperationNotSupportedException when list is invoked - * with a non-null argument - */ - public void destroySubcontext(String name) throws NamingException { - destroySubcontext(new CompositeName(name)); - } - - /** - * Uses the callDestroy function to destroy the context. Destroys - * the current context if name is empty. - * @param name JNDI Name - * @exception OperationNotSupportedException when list is invoked - * with a non-null argument - */ - public void destroySubcontext(Name name) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - NamingContext the_nc = _nc; - NameComponent[] path = CNNameParser.nameToCosName(name); - if ( name.size() > 0) { - try { - javax.naming.Context ctx = - (javax.naming.Context) callResolve(path); - CNCtx cnc = (CNCtx)ctx; - the_nc = cnc._nc; - cnc.close(); //remove the reference to the context - } catch (ClassCastException e) { - throw new NotContextException(name.toString()); - } catch (CannotProceedException e) { - javax.naming.Context cctx = getContinuationContext(e); - cctx.destroySubcontext(e.getRemainingName()); - return; - } catch (NameNotFoundException e) { - // If leaf is the one missing, return success - // as per JNDI spec - - if (e.getRootCause() instanceof NotFound && - leafNotFound((NotFound)e.getRootCause(), - path[path.length-1])) { - return; // leaf missing OK - } - throw e; - } catch (NamingException e) { - throw e; - } - } - callDestroy(the_nc); - callUnbind(path); - } - - /** - * Calls the bind_new_context COS naming api to create a new subcontext. - * @param path NameComponent[] object - * @exception NotFound No objects under the name. - * @exception CannotProceed Unable to obtain a continuation context - * @exception InvalidName Name not understood. - * @exception AlreadyBound An object is already bound to this name. - * @return the new context object. - */ - private javax.naming.Context callBindNewContext(NameComponent[] path) - throws NamingException { - if (_nc == null) - throw new ConfigurationException( - "Context does not have a corresponding NamingContext"); - try { - NamingContext nctx = _nc.bind_new_context(path); - return new CNCtx(_orb, orbTracker, nctx, _env, - makeFullName(path)); - } catch (Exception e) { - throw ExceptionMapper.mapException(e, this, path); - } - } - - /** - * Uses the callBindNewContext convenience function to create a new - * context. Throws an invalid name exception if the name is empty. - * @param name string - * @exception NamingException See callBindNewContext - * @return the new context object. - */ - public javax.naming.Context createSubcontext(String name) - throws NamingException { - return createSubcontext(new CompositeName(name)); - } - - /** - * Uses the callBindNewContext convenience function to create a new - * context. Throws an invalid name exception if the name is empty. - * @param name string - * @exception NamingException See callBindNewContext - * @return the new context object. - */ - public javax.naming.Context createSubcontext(Name name) - throws NamingException { - if (name.size() == 0 ) - throw new InvalidNameException("Name is empty"); - NameComponent[] path = CNNameParser.nameToCosName(name); - try { - return callBindNewContext(path); - } catch (CannotProceedException e) { - javax.naming.Context cctx = getContinuationContext(e); - return cctx.createSubcontext(e.getRemainingName()); - } - } - - /** - * Is mapped to resolve in the COS Naming api. - * @param name string - * @exception NamingException See lookup. - * @return the resolved object. - */ - public java.lang.Object lookupLink(String name) throws NamingException { - return lookupLink(new CompositeName(name)); - } - - /** - * Is mapped to resolve in the COS Naming api. - * @param name string - * @exception NamingException See lookup. - * @return the resolved object. - */ - public java.lang.Object lookupLink(Name name) throws NamingException { - return lookup(name); - } - - /** - * Allow access to the name parser object. - * @param name JNDI name, is ignored since there is only one Name - * Parser object. - * @exception NamingException -- - * @return NameParser object - */ - public NameParser getNameParser(String name) throws NamingException { - return parser; - } - - /** - * Allow access to the name parser object. - * @param name JNDI name, is ignored since there is only one Name - * Parser object. - * @exception NamingException -- - * @return NameParser object - */ - public NameParser getNameParser(Name name) throws NamingException { - return parser; - } - - /** - * Returns the current environment. - * @return Environment. - */ - @SuppressWarnings("unchecked") - public Hashtable getEnvironment() throws NamingException { - if (_env == null) { - return new Hashtable<>(5, 0.75f); - } else { - return (Hashtable)_env.clone(); - } - } - - public String composeName(String name, String prefix) throws NamingException { - return composeName(new CompositeName(name), - new CompositeName(prefix)).toString(); - } - - public Name composeName(Name name, Name prefix) throws NamingException { - Name result = (Name)prefix.clone(); - return result.addAll(name); - } - - /** - * Adds to the environment for the current context. - * Record change but do not reinitialize ORB. - * - * @param propName The property name. - * @param propValue The ORB. - * @return the previous value of this property if any. - */ - @SuppressWarnings("unchecked") - public java.lang.Object addToEnvironment(String propName, - java.lang.Object propValue) - throws NamingException { - if (_env == null) { - _env = new Hashtable<>(7, 0.75f); - } else { - // copy-on-write - _env = (Hashtable)_env.clone(); - } - - return _env.put(propName, propValue); - } - - // Record change but do not reinitialize ORB - @SuppressWarnings("unchecked") - public java.lang.Object removeFromEnvironment(String propName) - throws NamingException { - if (_env != null && _env.get(propName) != null) { - // copy-on-write - _env = (Hashtable)_env.clone(); - return _env.remove(propName); - } - return null; - } - - synchronized public void incEnumCount() { - enumCount++; - if (debug) { - System.out.println("incEnumCount, new count:" + enumCount); - } - } - - synchronized public void decEnumCount() - throws NamingException { - enumCount--; - if (debug) { - System.out.println("decEnumCount, new count:" + enumCount + - " isCloseCalled:" + isCloseCalled); - } - if ((enumCount == 0) && isCloseCalled) { - close(); - } - } - - synchronized public void close() throws NamingException { - - if (enumCount > 0) { - isCloseCalled = true; - return; - } - - // Never destroy an orb in CNCtx. - // The orb we have is either the shared/default orb, or one passed in to a constructor - // from elsewhere, so that orb is somebody else's responsibility. - } - - protected void finalize() { - try { - close(); - } catch (NamingException e) { - // ignore failures - } - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtxFactory.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtxFactory.java deleted file mode 100644 index 04bcf4d968b..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNCtxFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.spi.InitialContextFactory; -import javax.naming.*; - -import java.util.Hashtable; - -/** - * Implements the JNDI SPI InitialContextFactory interface used to - * create the InitialContext objects. - * - * @author Raj Krishnamurthy - */ - -public class CNCtxFactory implements InitialContextFactory { - - /** - * Creates the InitialContext object. Properties parameter should - * should contain the ORB object for the value jndi.corba.orb. - * @param env Properties object - */ - - public Context getInitialContext(Hashtable env) throws NamingException { - return new CNCtx(env); - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNNameParser.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNNameParser.java deleted file mode 100644 index 2b416941fc6..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CNNameParser.java +++ /dev/null @@ -1,500 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.*; -import java.util.Properties; -import java.util.Vector; -import java.util.Enumeration; - -import org.omg.CosNaming.NameComponent; - -/** - * Parsing routines for NameParser as well as COS Naming stringified names. - * This is used by CNCtx to create a NameComponent[] object and vice versa. - * It follows Section 4.5 of Interoperable Naming Service (INS) 98-10-11. - * In summary, the stringified form is a left-to-right, forward-slash - * separated name. id and kinds are separated by '.'. backslash is the - * escape character. - * - * @author Rosanna Lee - */ - -final public class CNNameParser implements NameParser { - - private static final Properties mySyntax = new Properties(); - private static final char kindSeparator = '.'; - private static final char compSeparator = '/'; - private static final char escapeChar = '\\'; - static { - mySyntax.put("jndi.syntax.direction", "left_to_right"); - mySyntax.put("jndi.syntax.separator", ""+compSeparator); - mySyntax.put("jndi.syntax.escape", ""+escapeChar); - }; - - /** - * Constructs a new name parser for parsing names in INS syntax. - */ - public CNNameParser() { - } - - /** - * Returns a CompoundName given a string in INS syntax. - * @param name The non-null string representation of the name. - * @return a non-null CompoundName - */ - public Name parse(String name) throws NamingException { - Vector comps = insStringToStringifiedComps(name); - return new CNCompoundName(comps.elements()); - } - - /** - * Creates a NameComponent[] from a Name structure. - * Used by CNCtx to convert the input Name arg into a NameComponent[]. - * @param a CompoundName or a CompositeName; - * each component must be the stringified form of a NameComponent. - */ - static NameComponent[] nameToCosName(Name name) - throws InvalidNameException { - int len = name.size(); - if (len == 0) { - return new NameComponent[0]; - } - - NameComponent[] answer = new NameComponent[len]; - for (int i = 0; i < len; i++) { - answer[i] = parseComponent(name.get(i)); - } - return answer; - } - - /** - * Returns the INS stringified form of a NameComponent[]. - * Used by CNCtx.getNameInNamespace(), CNCompoundName.toString(). - */ - static String cosNameToInsString(NameComponent[] cname) { - StringBuilder str = new StringBuilder(); - for ( int i = 0; i < cname.length; i++) { - if ( i > 0) { - str.append(compSeparator); - } - str.append(stringifyComponent(cname[i])); - } - return str.toString(); - } - - /** - * Creates a CompositeName from a NameComponent[]. - * Used by ExceptionMapper and CNBindingEnumeration to convert - * a NameComponent[] into a composite name. - */ - static Name cosNameToName(NameComponent[] cname) { - Name nm = new CompositeName(); - for ( int i = 0; cname != null && i < cname.length; i++) { - try { - nm.add(stringifyComponent(cname[i])); - } catch (InvalidNameException e) { - // ignore - } - } - return nm; - } - - /** - * Converts an INS-syntax string name into a Vector in which - * each element of the vector contains a stringified form of - * a NameComponent. - */ - private static Vector insStringToStringifiedComps(String str) - throws InvalidNameException { - - int len = str.length(); - Vector components = new Vector<>(10); - char[] id = new char[len]; - char[] kind = new char[len]; - int idCount, kindCount; - boolean idMode; - for (int i = 0; i < len; ) { - idCount = kindCount = 0; // reset for new component - idMode = true; // always start off parsing id - while (i < len) { - if (str.charAt(i) == compSeparator) { - break; - - } else if (str.charAt(i) == escapeChar) { - if (i + 1 >= len) { - throw new InvalidNameException(str + - ": unescaped \\ at end of component"); - } else if (isMeta(str.charAt(i+1))) { - ++i; // skip escape and let meta through - if (idMode) { - id[idCount++] = str.charAt(i++); - } else { - kind[kindCount++] = str.charAt(i++); - } - } else { - throw new InvalidNameException(str + - ": invalid character being escaped"); - } - - } else if (idMode && str.charAt(i) == kindSeparator) { - // just look for the first kindSeparator - ++i; // skip kind separator - idMode = false; - - } else { - if (idMode) { - id[idCount++] = str.charAt(i++); - } else { - kind[kindCount++] = str.charAt(i++); - } - } - } - components.addElement(stringifyComponent( - new NameComponent(new String(id, 0, idCount), - new String(kind, 0, kindCount)))); - - if (i < len) { - ++i; // skip separator - } - } - - return components; - } - - /** - * Return a NameComponent given its stringified form. - */ - private static NameComponent parseComponent(String compStr) - throws InvalidNameException { - NameComponent comp = new NameComponent(); - int kindSep = -1; - int len = compStr.length(); - - int j = 0; - char[] newStr = new char[len]; - boolean escaped = false; - - // Find the kind separator - for (int i = 0; i < len && kindSep < 0; i++) { - if (escaped) { - newStr[j++] = compStr.charAt(i); - escaped = false; - } else if (compStr.charAt(i) == escapeChar) { - if (i + 1 >= len) { - throw new InvalidNameException(compStr + - ": unescaped \\ at end of component"); - } else if (isMeta(compStr.charAt(i+1))) { - escaped = true; - } else { - throw new InvalidNameException(compStr + - ": invalid character being escaped"); - } - } else if (compStr.charAt(i) == kindSeparator) { - kindSep = i; - } else { - newStr[j++] = compStr.charAt(i); - } - } - - // Set id - comp.id = new String(newStr, 0, j); - - // Set kind - if (kindSep < 0) { - comp.kind = ""; // no kind separator - } else { - // unescape kind - j = 0; - escaped = false; - for (int i = kindSep+1; i < len; i++) { - if (escaped) { - newStr[j++] = compStr.charAt(i); - escaped = false; - } else if (compStr.charAt(i) == escapeChar) { - if (i + 1 >= len) { - throw new InvalidNameException(compStr + - ": unescaped \\ at end of component"); - } else if (isMeta(compStr.charAt(i+1))) { - escaped = true; - } else { - throw new InvalidNameException(compStr + - ": invalid character being escaped"); - } - } else { - newStr[j++] = compStr.charAt(i); - } - } - comp.kind = new String(newStr, 0, j); - } - return comp; - } - - private static String stringifyComponent(NameComponent comp) { - StringBuilder one = new StringBuilder(escape(comp.id)); - if (comp.kind != null && !comp.kind.equals("")) { - one.append(kindSeparator).append(escape(comp.kind)); - } - if (one.length() == 0) { - return ""+kindSeparator; // if neither id nor kind specified - } else { - return one.toString(); - } - } - - /** - * Returns a string with '.', '\', '/' escaped. Used when - * stringifying the name into its INS stringified form. - */ - private static String escape(String str) { - if (str.indexOf(kindSeparator) < 0 && - str.indexOf(compSeparator) < 0 && - str.indexOf(escapeChar) < 0) { - return str; // no meta characters to escape - } else { - int len = str.length(); - int j = 0; - char[] newStr = new char[len+len]; - for (int i = 0; i < len; i++) { - if (isMeta(str.charAt(i))) { - newStr[j++] = escapeChar; // escape meta character - } - newStr[j++] = str.charAt(i); - } - return new String(newStr, 0, j); - } - } - - /** - * In INS, there are three meta characters: '.', '/' and '\'. - */ - private static boolean isMeta(char ch) { - switch (ch) { - case kindSeparator: - case compSeparator: - case escapeChar: - return true; - } - return false; - } - - /** - * An implementation of CompoundName that bypasses the parsing - * and stringifying code of the default CompoundName. - */ - static final class CNCompoundName extends CompoundName { - CNCompoundName(Enumeration enum_) { - super(enum_, CNNameParser.mySyntax); - } - - public Object clone() { - return new CNCompoundName(getAll()); - } - - public Name getPrefix(int posn) { - Enumeration comps = super.getPrefix(posn).getAll(); - return new CNCompoundName(comps); - } - - public Name getSuffix(int posn) { - Enumeration comps = super.getSuffix(posn).getAll(); - return new CNCompoundName(comps); - } - - public String toString() { - try { - // Convert Name to NameComponent[] then stringify - return cosNameToInsString(nameToCosName(this)); - } catch (InvalidNameException e) { - return super.toString(); - } - } - - private static final long serialVersionUID = -6599252802678482317L; - } - -// for testing only -/* - private static void print(String input) { - try { - System.out.println("\n >>>>>> input: " + input); - - System.out.println("--Compound Name: "); - NameParser parser = new CNNameParser(); - Name name = parser.parse(input); - for (int i = 0; i < name.size(); i++) { - System.out.println("\t" + i + ": " + name.get(i)); - NameComponent cp = parseComponent(name.get(i)); - System.out.println("\t\t" + "id: " + cp.id + ";kind: " + cp.kind); - } - System.out.println("\t" + name.toString()); - - System.out.println("--Composite Name: "); - Name composite = new CompositeName(input); - for (int i = 0; i < composite.size(); i++) { - System.out.println("\t" + i+": " + composite.get(i)); - } - System.out.println("\t" + composite.toString()); - - System.out.println("--Composite To NameComponent"); - NameComponent[] names = nameToCosName(composite); - for (int i = 0; i < composite.size(); i++) { - System.out.println("\t" + i+": id: " + names[i].id + "; kind: " + names[i].kind); - } - System.out.println("\t" + cosNameToInsString(names)); - } catch (NamingException e) { - System.out.println(e); - } - } - - private static void checkName(Name name, String[] comps) throws Exception { - if (name.size() != comps.length) { - throw new Exception( - "test failed; incorrect component count in " + name + "; " + - "expecting " + comps.length + " got " + name.size()); - } - for (int i = 0; i < name.size(); i++) { - if (!comps[i].equals(name.get(i))) { - throw new Exception ( - "test failed; invalid component in " + name + "; " + - "expecting '" + comps[i] + "' got '" + name.get(i) + "'"); - } - } - } - - private static void checkCompound(NameParser parser, - String input, String[] comps) throws Exception { - checkName(parser.parse(input), comps); - } - - private static void checkComposite(String input, String[] comps) - throws Exception { - checkName(new CompositeName(input), comps); - } - - private static String[] compounds = { - "a/b/c", - "a.b/c.d", - "a", - ".", - "a.", - "c.d", - ".e", - "a/x\\/y\\/z/b", - "a\\.b.c\\.d/e.f", - "a/b\\\\/c", - "x\\\\.y", - "x\\.y", - "x.\\\\y", - "x.y\\\\", - "\\\\x.y", - "a.b\\.c/d" - }; - private static String[][] compoundComps = { - {"a", "b", "c"}, - {"a.b", "c.d"}, - {"a"}, - {"."}, - {"a"}, - {"c.d"}, - {".e"}, - {"a", "x\\/y\\/z", "b"}, - {"a\\.b.c\\.d", "e.f"}, - {"a", "b\\\\", "c"}, - {"x\\\\.y"}, - {"x\\.y"}, - {"x.\\\\y"}, - {"x.y\\\\"}, - {"\\\\x.y"}, - {"a.b\\.c", "d"}, - }; - - private static String[] composites = { - "a/b/c", - "a.b/c.d", - "a", - ".", - "a.", - "c.d", - ".e", - "a/x\\\\\\/y\\\\\\/z/b", - "a\\\\.b.c\\\\.d/e.f", - "a/b\\\\\\\\/c", - "x\\\\\\.y", - "x\\\\.y", - "x.\\\\\\\\y", - "x.y\\\\\\\\", - "\\\\\\\\x.y" - }; - - private static String[][] compositeComps = { - {"a", "b", "c"}, - {"a.b", "c.d"}, - {"a"}, - {"."}, - {"a."}, // unlike compound, kind sep is not consumed - {"c.d"}, - {".e"}, - {"a", "x\\/y\\/z", "b"}, - {"a\\.b.c\\.d", "e.f"}, - {"a", "b\\\\", "c"}, - {"x\\\\.y"}, - {"x\\.y"}, - {"x.\\\\y"}, - {"x.y\\\\"}, - {"\\\\x.y"} - }; - - public static void main(String[] args) throws Exception { - if (args.length > 0) { - for (int i = 0; i < args.length; i++) { - print(args[0]); - } - } else { - print("x\\\\.y"); - print("x\\.y"); - print("x.\\\\y"); - print("x.y\\\\"); - print("\\\\x.y"); - } - - NameParser parser = new com.sun.jndi.cosnaming.CNNameParser(); - for (int i = 0; i < compounds.length; i++) { - checkCompound(parser, compounds[i], compoundComps[i]); - } - for (int i = 0; i < composites.length; i++) { - checkComposite(composites[i], compositeComps[i]); - } - - System.out.println("hardwire"); - NameComponent[] foo = new NameComponent[1]; - foo[0] = new NameComponent("foo\\", "bar"); - - System.out.println(cosNameToInsString(foo)); - System.out.println(cosNameToName(foo)); - } -*/ -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CorbanameUrl.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CorbanameUrl.java deleted file mode 100644 index a0cc08034f6..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/CorbanameUrl.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.Name; -import javax.naming.NamingException; - -import java.net.MalformedURLException; -import com.sun.jndi.toolkit.url.UrlUtil; - -/** - * Extract components of a "corbaname" URL. - * - * The format of an corbaname URL is defined in INS 99-12-03 as follows. - *

    {@code
    - * corbaname url = "corbaname:"  ["#" ]
    - * corbaloc_obj  =  ["/" ]
    - * obj_addr_list = as defined in a corbaloc URL
    - * key_string    = as defined in a corbaloc URL
    - * string_name   = stringified COS name | empty_string
    - * }
    - * Characters in {@code } are escaped as follows. - * US-ASCII alphanumeric characters are not escaped. Any characters outside - * of this range are escaped except for the following: - *
    {@code
    - *        ; / : ? @ & = + $ , - _ . ! ~ * ; ( )
    - * }
    - * Escaped characters is escaped by using a % followed by its 2 hexadecimal - * numbers representing the octet. - *

    - * The corbaname URL is parsed into two parts: a corbaloc URL and a COS name. - * The corbaloc URL is constructed by concatenation {@code "corbaloc:"} with - * {@code }. - * The COS name is {@code } with the escaped characters resolved. - *

    - * A corbaname URL is resolved by: - *

      - *
    1. Construct a corbaloc URL by concatenating {@code "corbaloc:"} and {@code }. - *
    2. Resolve the corbaloc URL to a NamingContext by using - *
      {@code
      - *     nctx = ORB.string_to_object(corbalocUrl);
      - * }
      - *
    3. Resolve {@code } in the NamingContext. - *
    - * - * @author Rosanna Lee - */ - -public final class CorbanameUrl { - private String stringName; - private String location; - - /** - * Returns a possibly empty but non-null string that is the "string_name" - * portion of the URL. - */ - public String getStringName() { - return stringName; - } - - public Name getCosName() throws NamingException { - return CNCtx.parser.parse(stringName); - } - - public String getLocation() { - return "corbaloc:" + location; - } - - public CorbanameUrl(String url) throws MalformedURLException { - - if (!url.startsWith("corbaname:")) { - throw new MalformedURLException("Invalid corbaname URL: " + url); - } - - int addrStart = 10; // "corbaname:" - - int addrEnd = url.indexOf('#', addrStart); - if (addrEnd < 0) { - addrEnd = url.length(); - stringName = ""; - } else { - stringName = UrlUtil.decode(url.substring(addrEnd+1)); - } - location = url.substring(addrStart, addrEnd); - - int keyStart = location.indexOf('/'); - if (keyStart >= 0) { - // Has key string - if (keyStart == (location.length() -1)) { - location += "NameService"; - } - } else { - location += "/NameService"; - } - } -/* - // for testing only - public static void main(String[] args) { - try { - CorbanameUrl url = new CorbanameUrl(args[0]); - - System.out.println("location: " + url.getLocation()); - System.out.println("string name: " + url.getStringName()); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } -*/ -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/ExceptionMapper.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/ExceptionMapper.java deleted file mode 100644 index a1e9fd66424..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/ExceptionMapper.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.*; -import javax.naming.directory.*; -import javax.naming.spi.*; - -import org.omg.CosNaming.*; -import org.omg.CosNaming.NamingContextPackage.*; -import org.omg.CORBA.*; - -/** - * A convenience class to map the COS Naming exceptions to the JNDI exceptions. - * @author Raj Krishnamurthy - */ - -public final class ExceptionMapper { - private ExceptionMapper() {} // ensure no instance - private static final boolean debug = false; - - public static final NamingException mapException(Exception e, - CNCtx ctx, NameComponent[] inputName) throws NamingException { - if (e instanceof NamingException) { - return (NamingException)e; - } - - if (e instanceof RuntimeException) { - throw (RuntimeException)e; - } - - NamingException ne; - if (e instanceof NotFound) { - if (ctx.federation) { - return tryFed((NotFound)e, ctx, inputName); - - } else { - ne = new NameNotFoundException(); - } - - } else if (e instanceof CannotProceed) { - - ne = new CannotProceedException(); - NamingContext nc = ((CannotProceed) e).cxt; - NameComponent[] rest = ((CannotProceed) e).rest_of_name; - - // %%% We assume that rest returns *all* unprocessed components. - // Don't' know if that is a good assumption, given - // NotFound doesn't set rest as expected. -RL - if (inputName != null && (inputName.length > rest.length)) { - NameComponent[] resolvedName = - new NameComponent[inputName.length - rest.length]; - System.arraycopy(inputName, 0, resolvedName, 0, resolvedName.length); - // Wrap resolved NamingContext inside a CNCtx - // Guess that its name (which is relative to ctx) - // is the part of inputName minus rest_of_name - ne.setResolvedObj(new CNCtx(ctx._orb, ctx.orbTracker, nc, - ctx._env, - ctx.makeFullName(resolvedName))); - } else { - ne.setResolvedObj(ctx); - } - - ne.setRemainingName(CNNameParser.cosNameToName(rest)); - - } else if (e instanceof InvalidName) { - ne = new InvalidNameException(); - } else if (e instanceof AlreadyBound) { - ne = new NameAlreadyBoundException(); - } else if (e instanceof NotEmpty) { - ne = new ContextNotEmptyException(); - } else { - ne = new NamingException("Unknown reasons"); - } - - ne.setRootCause(e); - return ne; - } - - private static final NamingException tryFed(NotFound e, CNCtx ctx, - NameComponent[] inputName) throws NamingException { - NameComponent[] rest = e.rest_of_name; - - if (debug) { - System.out.println(e.why.value()); - System.out.println(rest.length); - } - - // %%% Using 1.2 & 1.3 Sun's tnameserv, 'rest' contains only the first - // component that failed, not *rest* as advertized. This is useless - // because what if you have something like aa/aa/aa/aa/aa. - // If one of those is not found, you get "aa" as 'rest'. - if (rest.length == 1 && inputName != null) { - // Check that we're not talking to 1.2/1.3 Sun tnameserv - NameComponent lastIn = inputName[inputName.length-1]; - if (rest[0].id.equals(lastIn.id) && - rest[0].kind != null && - rest[0].kind.equals(lastIn.kind)) { - // Might be legit - ; - } else { - // Due to 1.2/1.3 bug that always returns single-item 'rest' - NamingException ne = new NameNotFoundException(); - ne.setRemainingName(CNNameParser.cosNameToName(rest)); - ne.setRootCause(e); - throw ne; - } - } - // Fixed in 1.4; perform calculations based on correct (1.4) behavior - - // Calculate the components of the name that has been resolved - NameComponent[] resolvedName = null; - int len = 0; - if (inputName != null && (inputName.length >= rest.length)) { - - if (e.why == NotFoundReason.not_context) { - // First component of rest is found but not a context; keep it - // as part of resolved name - len = inputName.length - (rest.length - 1); - - // Remove resolved component from rest - if (rest.length == 1) { - // No more remaining - rest = null; - } else { - NameComponent[] tmp = new NameComponent[rest.length-1]; - System.arraycopy(rest, 1, tmp, 0, tmp.length); - rest = tmp; - } - } else { - len = inputName.length - rest.length; - } - - if (len > 0) { - resolvedName = new NameComponent[len]; - System.arraycopy(inputName, 0, resolvedName, 0, len); - } - } - - // Create CPE and set common fields - CannotProceedException cpe = new CannotProceedException(); - cpe.setRootCause(e); - if (rest != null && rest.length > 0) { - cpe.setRemainingName(CNNameParser.cosNameToName(rest)); - } - cpe.setEnvironment(ctx._env); - - if (debug) { - System.out.println("rest of name: " + cpe.getRemainingName()); - } - - // Lookup resolved name to get resolved object - final java.lang.Object resolvedObj = - (resolvedName != null) ? ctx.callResolve(resolvedName) : ctx; - - if (resolvedObj instanceof javax.naming.Context) { - // obj is a context and child is not found - // try getting its nns dynamically by constructing - // a Reference containing obj. - RefAddr addr = new RefAddr("nns") { - public java.lang.Object getContent() { - return resolvedObj; - } - private static final long serialVersionUID = - 669984699392133792L; - }; - Reference ref = new Reference("java.lang.Object", addr); - - // Resolved name has trailing slash to indicate nns - CompositeName cname = new CompositeName(); - cname.add(""); // add trailing slash - - cpe.setResolvedObj(ref); - cpe.setAltName(cname); - cpe.setAltNameCtx((javax.naming.Context)resolvedObj); - - return cpe; - } else { - // Not a context, use object factory to transform object. - - Name cname = CNNameParser.cosNameToName(resolvedName); - java.lang.Object resolvedObj2; - try { - resolvedObj2 = NamingManager.getObjectInstance(resolvedObj, - cname, ctx, ctx._env); - } catch (NamingException ge) { - throw ge; - } catch (Exception ge) { - NamingException ne = new NamingException( - "problem generating object using object factory"); - ne.setRootCause(ge); - throw ne; - } - - // If a context, continue operation with context - if (resolvedObj2 instanceof javax.naming.Context) { - cpe.setResolvedObj(resolvedObj2); - } else { - // Add trailing slash - cname.add(""); - cpe.setAltName(cname); - - // Create nns reference - final java.lang.Object rf2 = resolvedObj2; - RefAddr addr = new RefAddr("nns") { - public java.lang.Object getContent() { - return rf2; - } - private static final long serialVersionUID = - -785132553978269772L; - }; - Reference ref = new Reference("java.lang.Object", addr); - cpe.setResolvedObj(ref); - cpe.setAltNameCtx(ctx); - } - return cpe; - } - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/IiopUrl.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/IiopUrl.java deleted file mode 100644 index a51d6a4880c..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/IiopUrl.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.Name; -import javax.naming.NamingException; - -import java.net.MalformedURLException; -import java.util.Vector; -import java.util.StringTokenizer; -import com.sun.jndi.toolkit.url.UrlUtil; - -/** - * Extract components of an "iiop" or "iiopname" URL. - * - * The format of an iiopname URL is defined in INS 98-10-11 as follows: - * - *
    - * iiopname url = "iiopname://" [addr_list]["/" string_name]
    - * addr_list    = [address ","]* address
    - * address      = [version host [":" port]]
    - * host         = DNS style host name | IP address
    - * version      = major "." minor "@" | empty_string
    - * port         = number
    - * major        = number
    - * minor        = number
    - * string_name  = stringified name | empty_string
    - * 
    - * - * The default port is 9999. The default version is "1.0" - * US-ASCII alphanumeric characters are not escaped. Any characters outside - * of this range are escaped except for the following: - *
    {@code
    - * ; / : ? : @ & = + $ , - _ . ! ~ *  ' ( )
    - * }
    - * Escaped characters is escaped by using a % followed by its 2 hexadecimal - * numbers representing the octet. - * - * For backward compatibility, the "iiop" URL as defined in INS 97-6-6 - * is also supported: - *
    {@code
    - * iiop url     = "iiop://" [host [":" port]] ["/" string_name]
    - * }
    - * The default port is 900. - * - * @author Rosanna Lee - */ - -public final class IiopUrl { - static final private int DEFAULT_IIOPNAME_PORT = 9999; - static final private int DEFAULT_IIOP_PORT = 900; - static final private String DEFAULT_HOST = "localhost"; - private Vector
    addresses; - private String stringName; - - public static class Address { - public int port = -1; - public int major, minor; - public String host; - - public Address(String hostPortVers, boolean oldFormat) - throws MalformedURLException { - // [version host [":" port]] - int start; - - // Parse version - int at; - if (oldFormat || (at = hostPortVers.indexOf('@')) < 0) { - major = 1; - minor = 0; - start = 0; // start at the beginning - } else { - int dot = hostPortVers.indexOf('.'); - if (dot < 0) { - throw new MalformedURLException( - "invalid version: " + hostPortVers); - } - try { - major = Integer.parseInt(hostPortVers.substring(0, dot)); - minor = Integer.parseInt(hostPortVers.substring(dot+1, at)); - } catch (NumberFormatException e) { - throw new MalformedURLException( - "Nonnumeric version: " + hostPortVers); - } - start = at + 1; // skip '@' sign - } - - // Parse host and port - int slash = hostPortVers.indexOf('/', start); - if (slash < 0) { - slash = hostPortVers.length(); - } - if (hostPortVers.startsWith("[", start)) { // at IPv6 literal - int brac = hostPortVers.indexOf(']', start + 1); - if (brac < 0 || brac > slash) { - throw new IllegalArgumentException( - "IiopURL: name is an Invalid URL: " + hostPortVers); - } - - // include brackets - host = hostPortVers.substring(start, brac + 1); - start = brac + 1; - } else { // at hostname or IPv4 - int colon = hostPortVers.indexOf(':', start); - int hostEnd = (colon < 0 || colon > slash) - ? slash - : colon; - if (start < hostEnd) { - host = hostPortVers.substring(start, hostEnd); - } - start = hostEnd; // skip past host - } - if ((start + 1 < slash)) { - if ( hostPortVers.startsWith(":", start)) { // parse port - start++; // skip past ":" - port = Integer.parseInt(hostPortVers. - substring(start, slash)); - } else { - throw new IllegalArgumentException( - "IiopURL: name is an Invalid URL: " + hostPortVers); - } - } - start = slash; - if ("".equals(host) || host == null) { - host = DEFAULT_HOST ; - } - if (port == -1) { - port = (oldFormat ? DEFAULT_IIOP_PORT : - DEFAULT_IIOPNAME_PORT); - } - } - } - - public Vector
    getAddresses() { - return addresses; - } - - /** - * Returns a possibly empty but non-null string that is the "string_name" - * portion of the URL. - */ - public String getStringName() { - return stringName; - } - - public Name getCosName() throws NamingException { - return CNCtx.parser.parse(stringName); - } - - public IiopUrl(String url) throws MalformedURLException { - int addrStart; - boolean oldFormat; - - if (url.startsWith("iiopname://")) { - oldFormat = false; - addrStart = 11; - } else if (url.startsWith("iiop://")) { - oldFormat = true; - addrStart = 7; - } else { - throw new MalformedURLException("Invalid iiop/iiopname URL: " + url); - } - int addrEnd = url.indexOf('/', addrStart); - if (addrEnd < 0) { - addrEnd = url.length(); - stringName = ""; - } else { - stringName = UrlUtil.decode(url.substring(addrEnd+1)); - } - addresses = new Vector<>(3); - if (oldFormat) { - // Only one host:port part, not multiple - addresses.addElement( - new Address(url.substring(addrStart, addrEnd), oldFormat)); - } else { - StringTokenizer tokens = - new StringTokenizer(url.substring(addrStart, addrEnd), ","); - while (tokens.hasMoreTokens()) { - addresses.addElement(new Address(tokens.nextToken(), oldFormat)); - } - if (addresses.size() == 0) { - addresses.addElement(new Address("", oldFormat)); - } - } - } - - // for testing only - /*public static void main(String[] args) { - try { - IiopUrl url = new IiopUrl(args[0]); - Vector addrs = url.getAddresses(); - String name = url.getStringName(); - - for (int i = 0; i < addrs.size(); i++) { - Address addr = (Address)addrs.elementAt(i); - System.out.println("host: " + addr.host); - System.out.println("port: " + addr.port); - System.out.println("version: " + addr.major + " " + addr.minor); - } - System.out.println("name: " + name); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } */ -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/OrbReuseTracker.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/OrbReuseTracker.java deleted file mode 100644 index 25063e73001..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/OrbReuseTracker.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import org.omg.CORBA.ORB; - -/** - * This class keeps track of references to the shared ORB object - * and destroys it when no more references are made to the ORB - * object. This object is created for each ORB object that CNCtx - * creates. - */ -class OrbReuseTracker { - - int referenceCnt; - ORB orb; - - private static final boolean debug = false; - - OrbReuseTracker(ORB orb) { - this.orb = orb; - referenceCnt++; - if (debug) { - System.out.println("New OrbReuseTracker created"); - } - } - - synchronized void incRefCount() { - referenceCnt++; - if (debug) { - System.out.println("Increment orb ref count to:" + referenceCnt); - } - } - - synchronized void decRefCount() { - referenceCnt--; - if (debug) { - System.out.println("Decrement orb ref count to:" + referenceCnt); - } - if ((referenceCnt == 0)) { - if (debug) { - System.out.println("Destroying the ORB"); - } - orb.destroy(); - } - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java deleted file mode 100644 index 9f8414a9573..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/RemoteToCorba.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.cosnaming; - -import javax.naming.*; -import javax.naming.spi.StateFactory; -import java.util.Hashtable; - -import org.omg.CORBA.ORB; - -import java.rmi.Remote; -import java.rmi.server.ExportException; - -import com.sun.jndi.toolkit.corba.CorbaUtils; // for RMI-IIOP - -/** - * StateFactory that turns java.rmi.Remote objects to org.omg.CORBA.Object. - * - * @author Rosanna Lee - */ - -public class RemoteToCorba implements StateFactory { - public RemoteToCorba() { - } - - /** - * Returns the CORBA object for a Remote object. - * If input is not a Remote object, or if Remote object uses JRMP, return null. - * If the RMI-IIOP library is not available, throw ConfigurationException. - * - * @param orig The object to turn into a CORBA object. If not Remote, - * or if is a JRMP stub or impl, return null. - * @param name Ignored - * @param ctx The non-null CNCtx whose ORB to use. - * @param env Ignored - * @return The CORBA object for {@code orig} or null. - * @exception ConfigurationException If the CORBA object cannot be obtained - * due to configuration problems, for instance, if RMI-IIOP not available. - * @exception NamingException If some other problem prevented a CORBA - * object from being obtained from the Remote object. - */ - public Object getStateToBind(Object orig, Name name, Context ctx, - Hashtable env) throws NamingException { - if (orig instanceof org.omg.CORBA.Object) { - // Already a CORBA object, just use it - return null; - } - - if (orig instanceof Remote) { - // Turn remote object into org.omg.CORBA.Object - // Returns null if JRMP; let next factory try - // CNCtx will eventually throw IllegalArgumentException if - // no CORBA object gotten - return CorbaUtils.remoteToCorba((Remote)orig, ((CNCtx)ctx)._orb); - } - return null; // pass and let next state factory try - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties b/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties deleted file mode 100644 index 23ace2d7071..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties +++ /dev/null @@ -1,4 +0,0 @@ -# Provider resource file for the COS Naming service provider. - -# State factory to turn java.rmi.Remote into org.omg.CORBA.Object. -java.naming.factory.state=com.sun.jndi.cosnaming.RemoteToCorba diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java b/jdk/src/java.corba/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java deleted file mode 100644 index 122c9df57f5..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/toolkit/corba/CorbaUtils.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.toolkit.corba; - -// Needed for RMI/IIOP -import java.rmi.Remote; - -import java.rmi.RemoteException; -import java.util.Hashtable; -import java.util.Properties; -import java.util.Enumeration; -import java.applet.Applet; - -import org.omg.CORBA.ORB; - -import javax.naming.Context; -import javax.naming.ConfigurationException; -import javax.rmi.CORBA.Stub; -import javax.rmi.PortableRemoteObject; - -/** - * Contains utilities for performing CORBA-related tasks: - * 1. Get the org.omg.CORBA.Object for a java.rmi.Remote object. - * 2. Create an ORB to use for a given host/port, and environment properties. - * - * @author Simon Nash - * @author Bryan Atsatt - */ - -public class CorbaUtils { - /** - * Returns the CORBA object reference associated with a Remote - * object by using the javax.rmi.CORBA package. - *

    - * This method effective does the following: - *

    -      * java.lang.Object stub;
    -      * try {
    -      *     stub = PortableRemoteObject.toStub(remoteObj);
    -      * } catch (Exception e) {
    -      *     throw new ConfigurationException("Object not exported or not found");
    -      * }
    -      * if (!(stub instanceof javax.rmi.CORBA.Stub)) {
    -      *     return null; // JRMP impl or JRMP stub
    -      * }
    -      * try {
    -      *     ((javax.rmi.CORBA.Stub)stub).connect(orb);  // try to connect IIOP stub
    -      * } catch (RemoteException e) {
    -      *     // ignore 'already connected' error
    -      * }
    -      * return (javax.rmi.CORBA.Stub)stub;
    -      * 
    - * - * @param remoteObj The non-null remote object for - * @param orb The non-null ORB to connect the remote object to - * @return The CORBA Object for remoteObj; null if {@code remoteObj} - * is a JRMP implementation or JRMP stub. - * @exception ConfigurationException The CORBA Object cannot be obtained - * because of configuration problems. - */ - public static org.omg.CORBA.Object remoteToCorba(Remote remoteObj, ORB orb) - throws ConfigurationException { - -// First, get remoteObj's stub - - // javax.rmi.CORBA.Stub stub = PortableRemoteObject.toStub(remoteObj); - - Remote stub; - - try { - stub = PortableRemoteObject.toStub(remoteObj); - } catch (Throwable t) { - ConfigurationException ce = new ConfigurationException( - "Problem with PortableRemoteObject.toStub(); object not exported or stub not found"); - ce.setRootCause(t); - throw ce; - } - -// Next, make sure that the stub is javax.rmi.CORBA.Stub - - if (!(stub instanceof Stub)) { - return null; // JRMP implementation or JRMP stub - } - -// Next, make sure that the stub is connected - try { - ((Stub) stub).connect(orb); - } catch (RemoteException e) { - // ignore RemoteException because stub might have already - // been connected - } catch (Throwable t) { - ConfigurationException ce = new ConfigurationException( - "Problem invoking javax.rmi.CORBA.Stub.connect()"); - ce.setRootCause(t); - throw ce; - } -// Finally, return stub - return (org.omg.CORBA.Object)stub; - } - - /** - * Get ORB using given server and port number, and properties from environment. - * - * @param server Possibly null server; if null means use default; - * For applet, it is the applet host; for app, it is localhost. - * @param port Port number, -1 means default port - * @param env Possibly null environment. Contains environment properties. - * Could contain ORB itself; or applet used for initializing ORB. - * Use all String properties from env for initializing ORB - * @return A non-null ORB. - */ - public static ORB getOrb(String server, int port, Hashtable env) { - // See if we can get info from environment - Properties orbProp; - - // Extract any org.omg.CORBA properties from environment - if (env != null) { - if (env instanceof Properties) { - // Already a Properties, just clone - orbProp = (Properties) env.clone(); - } else { - // Get all String properties - Enumeration envProp; - orbProp = new Properties(); - for (envProp = env.keys(); envProp.hasMoreElements();) { - String key = (String)envProp.nextElement(); - Object val = env.get(key); - if (val instanceof String) { - orbProp.put(key, val); - } - } - } - } else { - orbProp = new Properties(); - } - - if (server != null) { - orbProp.put("org.omg.CORBA.ORBInitialHost", server); - } - if (port >= 0) { - orbProp.put("org.omg.CORBA.ORBInitialPort", ""+port); - } - - // Get Applet from environment - if (env != null) { - @SuppressWarnings("deprecation") - Applet applet = (Applet) env.get(Context.APPLET); - if (applet != null) { - // Create ORBs using applet and orbProp - return ORB.init(applet, orbProp); - } - } - - return ORB.init(new String[0], orbProp); - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/url/corbaname/corbanameURLContextFactory.java b/jdk/src/java.corba/share/classes/com/sun/jndi/url/corbaname/corbanameURLContextFactory.java deleted file mode 100644 index f5df93a13de..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/url/corbaname/corbanameURLContextFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.url.corbaname; - -import com.sun.jndi.url.iiop.iiopURLContextFactory; - -/** - * A corbaname URL context factory. - * It just uses the iiop URL context factory but is needed here - * so that NamingManager.getURLContext() will find it. - * - * @author Rosanna Lee - */ -final public class corbanameURLContextFactory extends iiopURLContextFactory { -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContext.java b/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContext.java deleted file mode 100644 index 445fa490662..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContext.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.url.iiop; - -import javax.naming.spi.ResolveResult; -import javax.naming.*; -import java.util.Hashtable; -import java.net.MalformedURLException; - -import com.sun.jndi.cosnaming.IiopUrl; -import com.sun.jndi.cosnaming.CorbanameUrl; - -/** - * An IIOP URL context. - * - * @author Rosanna Lee - */ - -public class iiopURLContext - extends com.sun.jndi.toolkit.url.GenericURLContext { - - iiopURLContext(Hashtable env) { - super(env); - } - - /** - * Resolves 'name' into a target context with remaining name. - * It only resolves the hostname/port number. The remaining name - * contains the rest of the name found in the URL. - * - * For example, with a iiop URL "iiop://localhost:900/rest/of/name", - * this method resolves "iiop://localhost:900/" to the "NameService" - * context on for the ORB at 'localhost' on port 900, - * and returns as the remaining name "rest/of/name". - */ - protected ResolveResult getRootURLContext(String name, Hashtable env) - throws NamingException { - return iiopURLContextFactory.getUsingURLIgnoreRest(name, env); - } - - /** - * Return the suffix of an "iiop", "iiopname", or "corbaname" url. - * prefix parameter is ignored. - */ - protected Name getURLSuffix(String prefix, String url) - throws NamingException { - try { - if (url.startsWith("iiop://") || url.startsWith("iiopname://")) { - IiopUrl parsedUrl = new IiopUrl(url); - return parsedUrl.getCosName(); - } else if (url.startsWith("corbaname:")) { - CorbanameUrl parsedUrl = new CorbanameUrl(url); - return parsedUrl.getCosName(); - } else { - throw new MalformedURLException("Not a valid URL: " + url); - } - } catch (MalformedURLException e) { - throw new InvalidNameException(e.getMessage()); - } - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContextFactory.java b/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContextFactory.java deleted file mode 100644 index 1371581a728..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiop/iiopURLContextFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.url.iiop; - -import javax.naming.*; -import javax.naming.spi.*; - -import java.util.Hashtable; - -import com.sun.jndi.cosnaming.CNCtx; - -/** - * An IIOP URL context factory. - * - * @author Rosanna Lee - */ - -public class iiopURLContextFactory implements ObjectFactory { - - public Object getObjectInstance(Object urlInfo, Name name, Context nameCtx, - Hashtable env) throws Exception { - -//System.out.println("iiopURLContextFactory " + urlInfo); - if (urlInfo == null) { - return new iiopURLContext(env); - } - if (urlInfo instanceof String) { - return getUsingURL((String)urlInfo, env); - } else if (urlInfo instanceof String[]) { - return getUsingURLs((String[])urlInfo, env); - } else { - throw (new IllegalArgumentException( - "iiopURLContextFactory.getObjectInstance: " + - "argument must be a URL String or array of URLs")); - } - } - - /** - * Resolves 'name' into a target context with remaining name. - * It only resolves the hostname/port number. The remaining name - * contains the rest of the name found in the URL. - * - * For example, with a iiop URL "iiop://localhost:900/rest/of/name", - * this method resolves "iiop://localhost:900/" to the "NameService" - * context on for the ORB at 'localhost' on port 900, - * and returns as the remaining name "rest/of/name". - */ - static ResolveResult getUsingURLIgnoreRest(String url, Hashtable env) - throws NamingException { - return CNCtx.createUsingURL(url, env); - } - - private static Object getUsingURL(String url, Hashtable env) - throws NamingException { - ResolveResult res = getUsingURLIgnoreRest(url, env); - - Context ctx = (Context)res.getResolvedObj(); - try { - return ctx.lookup(res.getRemainingName()); - } finally { - ctx.close(); - } - } - - private static Object getUsingURLs(String[] urls, Hashtable env) { - for (int i = 0; i < urls.length; i++) { - String url = urls[i]; - try { - Object obj = getUsingURL(url, env); - if (obj != null) { - return obj; - } - } catch (NamingException e) { - } - } - return null; // %%% exception?? - } -} diff --git a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiopname/iiopnameURLContextFactory.java b/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiopname/iiopnameURLContextFactory.java deleted file mode 100644 index 76e32cff0a2..00000000000 --- a/jdk/src/java.corba/share/classes/com/sun/jndi/url/iiopname/iiopnameURLContextFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.jndi.url.iiopname; - -import com.sun.jndi.url.iiop.iiopURLContextFactory; - -/** - * An iiopname URL context factory. - * It just uses the iiop URL context factory but is needed here - * so that NamingManager.getURLContext() will find it. - * - * @author Rosanna Lee - */ -final public class iiopnameURLContextFactory extends iiopURLContextFactory { -} diff --git a/jdk/src/java.naming/share/classes/module-info.java b/jdk/src/java.naming/share/classes/module-info.java index b8964699610..f524a4c0bcd 100644 --- a/jdk/src/java.naming/share/classes/module-info.java +++ b/jdk/src/java.naming/share/classes/module-info.java @@ -37,7 +37,6 @@ module java.naming { exports com.sun.jndi.toolkit.ctx to jdk.naming.dns; exports com.sun.jndi.toolkit.url to - java.corba, jdk.naming.dns, jdk.naming.rmi; uses javax.naming.ldap.StartTlsResponse; From 1d6d3d549ab4de336965484fab9c16039c2cd002 Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Mon, 19 Dec 2016 12:13:32 +0100 Subject: [PATCH 45/45] 8171414: tools/launcher/VersionCheck.java failed with AssertionError due to new tool jaotc Reviewed-by: alanb, sla --- jdk/test/tools/launcher/VersionCheck.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jdk/test/tools/launcher/VersionCheck.java b/jdk/test/tools/launcher/VersionCheck.java index afbde0782a3..aa507b6da43 100644 --- a/jdk/test/tools/launcher/VersionCheck.java +++ b/jdk/test/tools/launcher/VersionCheck.java @@ -51,6 +51,7 @@ public class VersionCheck extends TestHelper { "jaccessinspector-32", "jaccesswalker", "jaccesswalker-32", + "jaotc", "javaw", "javaws", "jcontrol", @@ -72,6 +73,7 @@ public class VersionCheck extends TestHelper { "jaccessinspector-32", "jaccesswalker", "jaccesswalker-32", + "jaotc", "jar", "jarsigner", "java-rmi",