diff --git a/.hgtags b/.hgtags index 964eed62a25..0f601cb1489 100644 --- a/.hgtags +++ b/.hgtags @@ -546,3 +546,6 @@ a535ba736cabc6886acdff36de3a096c46e5ddc5 jdk-13+8 4ce47bc1fb92cf94c6e3d1f49d582f02dcb851ab jdk-12+32 c081f3ea6b9300265a4a34e38f970b1e3ddaae9f jdk-13+9 b67884871b5fff79c5ef3eb8ac74dd48d71ea9b1 jdk-12+33 +8e069f7b4fabfe05d9f500783e6d56cb0196d25c jdk-13+10 +21ea4076a275a0f498afa517e9ee1b94a9cf0255 jdk-13+11 +1d7aec80147a6d92b101a76aef92f3ddc88bedf4 jdk-13+12 diff --git a/doc/building.html b/doc/building.html index 36e9c617203..dc6f097e35c 100644 --- a/doc/building.html +++ b/doc/building.html @@ -237,7 +237,7 @@

For rpm-based distributions (Fedora, Red Hat, etc), try this:

sudo yum groupinstall "Development Tools"

AIX

-

The regular builds by SAP is using AIX version 7.1, but AIX 5.3 is also supported. See the OpenJDK PowerPC Port Status Page for details.

+

Please consult the AIX section of the Supported Build Platforms OpenJDK Build Wiki page for details about which versions of AIX are supported.

Native Compiler (Toolchain) Requirements

Large portions of the JDK consists of native code, that needs to be compiled to be able to run on the target platform. In theory, toolchain and operating system should be independent factors, but in practice there's more or less a one-to-one correlation between target operating system and toolchain.

@@ -373,8 +373,7 @@ CC: Sun C++ 5.13 SunOS_i386 151846-10 2015/10/30

If you have multiple versions of Visual Studio installed, configure will by default pick the latest. You can request a specific version to be used by setting --with-toolchain-version, e.g. --with-toolchain-version=2015.

If you get LINK: fatal error LNK1123: failure during conversion to COFF: file invalid when building using Visual Studio 2010, you have encountered KB2757355, a bug triggered by a specific installation order. However, the solution suggested by the KB article does not always resolve the problem. See this stackoverflow discussion for other suggestions.

IBM XL C/C++

-

The regular builds by SAP is using version 12.1, described as IBM XL C/C++ for AIX, V12.1 (5765-J02, 5725-C72) Version: 12.01.0000.0017.

-

See the OpenJDK PowerPC Port Status Page for details.

+

Please consult the AIX section of the Supported Build Platforms OpenJDK Build Wiki page for details about which versions of XLC are supported.

Boot JDK Requirements

Paradoxically, building the JDK requires a pre-existing JDK. This is called the "boot JDK". The boot JDK does not, however, have to be a JDK built directly from the source code available in the OpenJDK Community. If you are porting the JDK to a new platform, chances are that there already exists another JDK for that platform that is usable as boot JDK.

The rule of thumb is that the boot JDK for building JDK major version N should be a JDK of major version N-1, so for building JDK 9 a JDK 8 would be suitable as boot JDK. However, the JDK should be able to "build itself", so an up-to-date build of the current JDK source is an acceptable alternative. If you are following the N-1 rule, make sure you've got the latest update version, since JDK 8 GA might not be able to build JDK 9 on all platforms.

diff --git a/doc/building.md b/doc/building.md index 1f714a14b6b..2f64c7ee6b1 100644 --- a/doc/building.md +++ b/doc/building.md @@ -295,9 +295,9 @@ sudo yum groupinstall "Development Tools" ### AIX -The regular builds by SAP is using AIX version 7.1, but AIX 5.3 is also -supported. See the [OpenJDK PowerPC Port Status Page]( -http://cr.openjdk.java.net/~simonis/ppc-aix-port) for details. +Please consult the AIX section of the [Supported Build Platforms]( +https://wiki.openjdk.java.net/display/Build/Supported+Build+Platforms) OpenJDK +Build Wiki page for details about which versions of AIX are supported. ## Native Compiler (Toolchain) Requirements @@ -419,11 +419,10 @@ https://stackoverflow.com/questions/10888391) for other suggestions. ### IBM XL C/C++ -The regular builds by SAP is using version 12.1, described as `IBM XL C/C++ for -AIX, V12.1 (5765-J02, 5725-C72) Version: 12.01.0000.0017`. +Please consult the AIX section of the [Supported Build Platforms]( +https://wiki.openjdk.java.net/display/Build/Supported+Build+Platforms) OpenJDK +Build Wiki page for details about which versions of XLC are supported. -See the [OpenJDK PowerPC Port Status Page]( -http://cr.openjdk.java.net/~simonis/ppc-aix-port) for details. ## Boot JDK Requirements diff --git a/doc/testing.html b/doc/testing.html index ef258db25df..c35ee54b849 100644 --- a/doc/testing.html +++ b/doc/testing.html @@ -1,24 +1,19 @@ - + - - - + + + Testing the JDK - - + + -
+

Testing the JDK

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Permission Target NameWhat the Permission AllowsRisks of Allowing this Permission
setHostnameVerifierThe ability to set a callback which can decide whether to - * allow a mismatch between the host being connected to by - * an HttpsURLConnection and the common name field in - * server certificate. - * Malicious - * code can set a verifier that monitors host names visited by - * HttpsURLConnection requests or that allows server certificates - * with invalid common names. - *
getSSLSessionContextThe ability to get the SSLSessionContext of an SSLSession. - * Malicious code may monitor sessions which have been established - * with SSL peers or might invalidate sessions to slow down performance. - *
- * - * @see java.security.BasicPermission - * @see java.security.Permission - * @see java.security.Permissions - * @see java.security.PermissionCollection - * @see java.lang.SecurityManager - * - * - * @author Marianne Mueller - * @author Roland Schemers - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.SSLPermission}. - */ -@Deprecated(since="1.4") -public final class SSLPermission extends BasicPermission { - - private static final long serialVersionUID = -2583684302506167542L; - - /** - * Creates a new SSLPermission with the specified name. - * The name is the symbolic name of the SSLPermission, such as - * "setDefaultAuthenticator", etc. An asterisk - * may appear at the end of the name, following a ".", or by itself, to - * signify a wildcard match. - * - * @param name the name of the SSLPermission. - */ - - public SSLPermission(String name) - { - super(name); - } - - /** - * Creates a new SSLPermission object with the specified name. - * The name is the symbolic name of the SSLPermission, and the - * actions String is currently unused and should be null. This - * constructor exists for use by the Policy object - * to instantiate new Permission objects. - * - * @param name the name of the SSLPermission. - * @param actions should be null. - */ - - public SSLPermission(String name, String actions) - { - super(name, actions); - } -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/SSLSecurity.java b/src/java.base/share/classes/com/sun/net/ssl/SSLSecurity.java deleted file mode 100644 index 664b53e0489..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/SSLSecurity.java +++ /dev/null @@ -1,699 +0,0 @@ -/* - * Copyright (c) 2000, 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.SSLSecurity, - * but was heavily modified to allow com.sun.* users to - * access providers written using the javax.sun.* APIs. - */ - -package com.sun.net.ssl; - -import java.util.*; -import java.io.*; -import java.security.*; -import java.security.Provider.Service; -import java.net.Socket; - -import sun.security.jca.*; - -/** - * This class instantiates implementations of JSSE engine classes from - * providers registered with the java.security.Security object. - * - * @author Jan Luehe - * @author Jeff Nisewanger - * @author Brad Wetmore - */ - -final class SSLSecurity { - - /* - * Don't let anyone instantiate this. - */ - private SSLSecurity() { - } - - - // ProviderList.getService() is not accessible now, implement our own loop - private static Service getService(String type, String alg) { - ProviderList list = Providers.getProviderList(); - for (Provider p : list.providers()) { - Service s = p.getService(type, alg); - if (s != null) { - return s; - } - } - return null; - } - - /** - * The body of the driver for the getImpl method. - */ - private static Object[] getImpl1(String algName, String engineType, - Service service) throws NoSuchAlgorithmException - { - Provider provider = service.getProvider(); - String className = service.getClassName(); - Class implClass; - try { - ClassLoader cl = provider.getClass().getClassLoader(); - if (cl == null) { - // system class - implClass = Class.forName(className); - } else { - implClass = cl.loadClass(className); - } - } catch (ClassNotFoundException e) { - throw new NoSuchAlgorithmException("Class " + className + - " configured for " + - engineType + - " not found: " + - e.getMessage()); - } catch (SecurityException e) { - throw new NoSuchAlgorithmException("Class " + className + - " configured for " + - engineType + - " cannot be accessed: " + - e.getMessage()); - } - - /* - * JSSE 1.0, 1.0.1, and 1.0.2 used the com.sun.net.ssl API as the - * API was being developed. As JSSE was folded into the main - * release, it was decided to promote the com.sun.net.ssl API to - * be javax.net.ssl. It is desired to keep binary compatibility - * with vendors of JSSE implementation written using the - * com.sun.net.sll API, so we do this magic to handle everything. - * - * API used Implementation used Supported? - * ======== =================== ========== - * com.sun javax Yes - * com.sun com.sun Yes - * javax javax Yes - * javax com.sun Not Currently - * - * Make sure the implementation class is a subclass of the - * corresponding engine class. - * - * In wrapping these classes, there's no way to know how to - * wrap all possible classes that extend the TrustManager/KeyManager. - * We only wrap the x509 variants. - */ - - try { // catch instantiation errors - - /* - * (The following Class.forName()s should alway work, because - * this class and all the SPI classes in javax.crypto are - * loaded by the same class loader.) That is, unless they - * give us a SPI class that doesn't exist, say SSLFoo, - * or someone has removed classes from the java.base module. - */ - - Class typeClassJavax; - Class typeClassCom; - Object obj = null; - - /* - * Odds are more likely that we have a javax variant, try this - * first. - */ - if (((typeClassJavax = Class.forName("javax.net.ssl." + - engineType + "Spi")) != null) && - (checkSuperclass(implClass, typeClassJavax))) { - - if (engineType.equals("SSLContext")) { - obj = new SSLContextSpiWrapper(algName, provider); - } else if (engineType.equals("TrustManagerFactory")) { - obj = new TrustManagerFactorySpiWrapper(algName, provider); - } else if (engineType.equals("KeyManagerFactory")) { - obj = new KeyManagerFactorySpiWrapper(algName, provider); - } else { - /* - * We should throw an error if we get - * something totally unexpected. Don't ever - * expect to see this one... - */ - throw new IllegalStateException( - "Class " + implClass.getName() + - " unknown engineType wrapper:" + engineType); - } - - } else if (((typeClassCom = Class.forName("com.sun.net.ssl." + - engineType + "Spi")) != null) && - (checkSuperclass(implClass, typeClassCom))) { - obj = service.newInstance(null); - } - - if (obj != null) { - return new Object[] { obj, provider }; - } else { - throw new NoSuchAlgorithmException( - "Couldn't locate correct object or wrapper: " + - engineType + " " + algName); - } - - } catch (ClassNotFoundException e) { - IllegalStateException exc = new IllegalStateException( - "Engine Class Not Found for " + engineType); - exc.initCause(e); - throw exc; - } - } - - /** - * Returns an array of objects: the first object in the array is - * an instance of an implementation of the requested algorithm - * and type, and the second object in the array identifies the provider - * of that implementation. - * The provName argument can be null, in which case all - * configured providers will be searched in order of preference. - */ - static Object[] getImpl(String algName, String engineType, String provName) - throws NoSuchAlgorithmException, NoSuchProviderException - { - Service service; - if (provName != null) { - ProviderList list = Providers.getProviderList(); - Provider prov = list.getProvider(provName); - if (prov == null) { - throw new NoSuchProviderException("No such provider: " + - provName); - } - service = prov.getService(engineType, algName); - } else { - service = getService(engineType, algName); - } - if (service == null) { - throw new NoSuchAlgorithmException("Algorithm " + algName - + " not available"); - } - return getImpl1(algName, engineType, service); - } - - - /** - * Returns an array of objects: the first object in the array is - * an instance of an implementation of the requested algorithm - * and type, and the second object in the array identifies the provider - * of that implementation. - * The prov argument can be null, in which case all - * configured providers will be searched in order of preference. - */ - static Object[] getImpl(String algName, String engineType, Provider prov) - throws NoSuchAlgorithmException - { - Service service = prov.getService(engineType, algName); - if (service == null) { - throw new NoSuchAlgorithmException("No such algorithm: " + - algName); - } - return getImpl1(algName, engineType, service); - } - - /* - * Checks whether one class is the superclass of another - */ - private static boolean checkSuperclass(Class subclass, Class superclass) { - if ((subclass == null) || (superclass == null)) - return false; - - while (!subclass.equals(superclass)) { - subclass = subclass.getSuperclass(); - if (subclass == null) { - return false; - } - } - return true; - } - - /* - * Return at most the first "resize" elements of an array. - * - * Didn't want to use java.util.Arrays, as PJava may not have it. - */ - static Object[] truncateArray(Object[] oldArray, Object[] newArray) { - - for (int i = 0; i < newArray.length; i++) { - newArray[i] = oldArray[i]; - } - - return newArray; - } - -} - - -/* - * ================================================================= - * The remainder of this file is for the wrapper and wrapper-support - * classes. When SSLSecurity finds something which extends the - * javax.net.ssl.*Spi, we need to go grab a real instance of the - * thing that the Spi supports, and wrap into a com.sun.net.ssl.*Spi - * object. This also mean that anything going down into the SPI - * needs to be wrapped, as well as anything coming back up. - */ -@SuppressWarnings("deprecation") -final class SSLContextSpiWrapper extends SSLContextSpi { - - private javax.net.ssl.SSLContext theSSLContext; - - SSLContextSpiWrapper(String algName, Provider prov) throws - NoSuchAlgorithmException { - theSSLContext = javax.net.ssl.SSLContext.getInstance(algName, prov); - } - - @SuppressWarnings("deprecation") - protected void engineInit(KeyManager[] kma, TrustManager[] tma, - SecureRandom sr) throws KeyManagementException { - - // Keep track of the actual number of array elements copied - int dst; - int src; - javax.net.ssl.KeyManager[] kmaw; - javax.net.ssl.TrustManager[] tmaw; - - // Convert com.sun.net.ssl.kma to a javax.net.ssl.kma - // wrapper if need be. - if (kma != null) { - kmaw = new javax.net.ssl.KeyManager[kma.length]; - for (src = 0, dst = 0; src < kma.length; ) { - /* - * These key managers may implement both javax - * and com.sun interfaces, so if they do - * javax, there's no need to wrap them. - */ - if (!(kma[src] instanceof javax.net.ssl.KeyManager)) { - /* - * Do we know how to convert them? If not, oh well... - * We'll have to drop them on the floor in this - * case, cause we don't know how to handle them. - * This will be pretty rare, but put here for - * completeness. - */ - if (kma[src] instanceof X509KeyManager) { - kmaw[dst] = (javax.net.ssl.KeyManager) - new X509KeyManagerJavaxWrapper( - (X509KeyManager)kma[src]); - dst++; - } - } else { - // We can convert directly, since they implement. - kmaw[dst] = (javax.net.ssl.KeyManager)kma[src]; - dst++; - } - src++; - } - - /* - * If dst != src, there were more items in the original array - * than in the new array. Compress the new elements to avoid - * any problems down the road. - */ - if (dst != src) { - kmaw = (javax.net.ssl.KeyManager []) - SSLSecurity.truncateArray(kmaw, - new javax.net.ssl.KeyManager [dst]); - } - } else { - kmaw = null; - } - - // Now do the same thing with the TrustManagers. - if (tma != null) { - tmaw = new javax.net.ssl.TrustManager[tma.length]; - - for (src = 0, dst = 0; src < tma.length; ) { - /* - * These key managers may implement both...see above... - */ - if (!(tma[src] instanceof javax.net.ssl.TrustManager)) { - // Do we know how to convert them? - if (tma[src] instanceof X509TrustManager) { - tmaw[dst] = (javax.net.ssl.TrustManager) - new X509TrustManagerJavaxWrapper( - (X509TrustManager)tma[src]); - dst++; - } - } else { - tmaw[dst] = (javax.net.ssl.TrustManager)tma[src]; - dst++; - } - src++; - } - - if (dst != src) { - tmaw = (javax.net.ssl.TrustManager []) - SSLSecurity.truncateArray(tmaw, - new javax.net.ssl.TrustManager [dst]); - } - } else { - tmaw = null; - } - - theSSLContext.init(kmaw, tmaw, sr); - } - - protected javax.net.ssl.SSLSocketFactory - engineGetSocketFactory() { - return theSSLContext.getSocketFactory(); - } - - protected javax.net.ssl.SSLServerSocketFactory - engineGetServerSocketFactory() { - return theSSLContext.getServerSocketFactory(); - } - -} - -@SuppressWarnings("deprecation") -final class TrustManagerFactorySpiWrapper extends TrustManagerFactorySpi { - - private javax.net.ssl.TrustManagerFactory theTrustManagerFactory; - - TrustManagerFactorySpiWrapper(String algName, Provider prov) throws - NoSuchAlgorithmException { - theTrustManagerFactory = - javax.net.ssl.TrustManagerFactory.getInstance(algName, prov); - } - - protected void engineInit(KeyStore ks) throws KeyStoreException { - theTrustManagerFactory.init(ks); - } - - protected TrustManager[] engineGetTrustManagers() { - - int dst; - int src; - - javax.net.ssl.TrustManager[] tma = - theTrustManagerFactory.getTrustManagers(); - - TrustManager[] tmaw = new TrustManager[tma.length]; - - for (src = 0, dst = 0; src < tma.length; ) { - if (!(tma[src] instanceof com.sun.net.ssl.TrustManager)) { - // We only know how to wrap X509TrustManagers, as - // TrustManagers don't have any methods to wrap. - if (tma[src] instanceof javax.net.ssl.X509TrustManager) { - tmaw[dst] = (TrustManager) - new X509TrustManagerComSunWrapper( - (javax.net.ssl.X509TrustManager)tma[src]); - dst++; - } - } else { - tmaw[dst] = (TrustManager)tma[src]; - dst++; - } - src++; - } - - if (dst != src) { - tmaw = (TrustManager []) - SSLSecurity.truncateArray(tmaw, new TrustManager [dst]); - } - - return tmaw; - } - -} - -@SuppressWarnings("deprecation") -final class KeyManagerFactorySpiWrapper extends KeyManagerFactorySpi { - - private javax.net.ssl.KeyManagerFactory theKeyManagerFactory; - - KeyManagerFactorySpiWrapper(String algName, Provider prov) throws - NoSuchAlgorithmException { - theKeyManagerFactory = - javax.net.ssl.KeyManagerFactory.getInstance(algName, prov); - } - - protected void engineInit(KeyStore ks, char[] password) - throws KeyStoreException, NoSuchAlgorithmException, - UnrecoverableKeyException { - theKeyManagerFactory.init(ks, password); - } - - protected KeyManager[] engineGetKeyManagers() { - - int dst; - int src; - - javax.net.ssl.KeyManager[] kma = - theKeyManagerFactory.getKeyManagers(); - - KeyManager[] kmaw = new KeyManager[kma.length]; - - for (src = 0, dst = 0; src < kma.length; ) { - if (!(kma[src] instanceof com.sun.net.ssl.KeyManager)) { - // We only know how to wrap X509KeyManagers, as - // KeyManagers don't have any methods to wrap. - if (kma[src] instanceof javax.net.ssl.X509KeyManager) { - kmaw[dst] = (KeyManager) - new X509KeyManagerComSunWrapper( - (javax.net.ssl.X509KeyManager)kma[src]); - dst++; - } - } else { - kmaw[dst] = (KeyManager)kma[src]; - dst++; - } - src++; - } - - if (dst != src) { - kmaw = (KeyManager []) - SSLSecurity.truncateArray(kmaw, new KeyManager [dst]); - } - - return kmaw; - } - -} - -// ================================= - -@SuppressWarnings("deprecation") -final class X509KeyManagerJavaxWrapper implements - javax.net.ssl.X509KeyManager { - - private X509KeyManager theX509KeyManager; - - X509KeyManagerJavaxWrapper(X509KeyManager obj) { - theX509KeyManager = obj; - } - - public String[] getClientAliases(String keyType, Principal[] issuers) { - return theX509KeyManager.getClientAliases(keyType, issuers); - } - - public String chooseClientAlias(String[] keyTypes, Principal[] issuers, - Socket socket) { - String retval; - - if (keyTypes == null) { - return null; - } - - /* - * Scan the list, look for something we can pass back. - */ - for (int i = 0; i < keyTypes.length; i++) { - if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], - issuers)) != null) - return retval; - } - return null; - - } - - /* - * JSSE 1.0.x was only socket based, but it's possible someone might - * want to install a really old provider. We should at least - * try to be nice. - */ - public String chooseEngineClientAlias( - String[] keyTypes, Principal[] issuers, - javax.net.ssl.SSLEngine engine) { - String retval; - - if (keyTypes == null) { - return null; - } - - /* - * Scan the list, look for something we can pass back. - */ - for (int i = 0; i < keyTypes.length; i++) { - if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], - issuers)) != null) - return retval; - } - - return null; - } - - public String[] getServerAliases(String keyType, Principal[] issuers) { - return theX509KeyManager.getServerAliases(keyType, issuers); - } - - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - - if (keyType == null) { - return null; - } - return theX509KeyManager.chooseServerAlias(keyType, issuers); - } - - /* - * JSSE 1.0.x was only socket based, but it's possible someone might - * want to install a really old provider. We should at least - * try to be nice. - */ - public String chooseEngineServerAlias( - String keyType, Principal[] issuers, - javax.net.ssl.SSLEngine engine) { - - if (keyType == null) { - return null; - } - return theX509KeyManager.chooseServerAlias(keyType, issuers); - } - - public java.security.cert.X509Certificate[] - getCertificateChain(String alias) { - return theX509KeyManager.getCertificateChain(alias); - } - - public PrivateKey getPrivateKey(String alias) { - return theX509KeyManager.getPrivateKey(alias); - } -} - -@SuppressWarnings("deprecation") -final class X509TrustManagerJavaxWrapper implements - javax.net.ssl.X509TrustManager { - - private X509TrustManager theX509TrustManager; - - X509TrustManagerJavaxWrapper(X509TrustManager obj) { - theX509TrustManager = obj; - } - - public void checkClientTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws java.security.cert.CertificateException { - if (!theX509TrustManager.isClientTrusted(chain)) { - throw new java.security.cert.CertificateException( - "Untrusted Client Certificate Chain"); - } - } - - public void checkServerTrusted( - java.security.cert.X509Certificate[] chain, String authType) - throws java.security.cert.CertificateException { - if (!theX509TrustManager.isServerTrusted(chain)) { - throw new java.security.cert.CertificateException( - "Untrusted Server Certificate Chain"); - } - } - - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return theX509TrustManager.getAcceptedIssuers(); - } -} - -@SuppressWarnings("deprecation") -final class X509KeyManagerComSunWrapper implements X509KeyManager { - - private javax.net.ssl.X509KeyManager theX509KeyManager; - - X509KeyManagerComSunWrapper(javax.net.ssl.X509KeyManager obj) { - theX509KeyManager = obj; - } - - public String[] getClientAliases(String keyType, Principal[] issuers) { - return theX509KeyManager.getClientAliases(keyType, issuers); - } - - public String chooseClientAlias(String keyType, Principal[] issuers) { - String [] keyTypes = new String [] { keyType }; - return theX509KeyManager.chooseClientAlias(keyTypes, issuers, null); - } - - public String[] getServerAliases(String keyType, Principal[] issuers) { - return theX509KeyManager.getServerAliases(keyType, issuers); - } - - public String chooseServerAlias(String keyType, Principal[] issuers) { - return theX509KeyManager.chooseServerAlias(keyType, issuers, null); - } - - public java.security.cert.X509Certificate[] - getCertificateChain(String alias) { - return theX509KeyManager.getCertificateChain(alias); - } - - public PrivateKey getPrivateKey(String alias) { - return theX509KeyManager.getPrivateKey(alias); - } -} - -@SuppressWarnings("deprecation") -final class X509TrustManagerComSunWrapper implements X509TrustManager { - - private javax.net.ssl.X509TrustManager theX509TrustManager; - - X509TrustManagerComSunWrapper(javax.net.ssl.X509TrustManager obj) { - theX509TrustManager = obj; - } - - public boolean isClientTrusted( - java.security.cert.X509Certificate[] chain) { - try { - theX509TrustManager.checkClientTrusted(chain, "UNKNOWN"); - return true; - } catch (java.security.cert.CertificateException e) { - return false; - } - } - - public boolean isServerTrusted( - java.security.cert.X509Certificate[] chain) { - try { - theX509TrustManager.checkServerTrusted(chain, "UNKNOWN"); - return true; - } catch (java.security.cert.CertificateException e) { - return false; - } - } - - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return theX509TrustManager.getAcceptedIssuers(); - } -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java b/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java deleted file mode 100644 index 376b111fd81..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/TrustManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.TrustManager - */ - -package com.sun.net.ssl; - -/** - * Base interface for JSSE trust managers which manage - * authentication trust decisions for different types of - * authentication material. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.TrustManager}. - */ -@Deprecated(since="1.4") -public interface TrustManager { -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java b/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java deleted file mode 100644 index b580f04af34..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.TrustManagerFactory - */ - -package com.sun.net.ssl; - -import java.security.*; - -/** - * This class acts as a factory for trust managers based on a - * source of trust material. Each trust manager manages a specific - * type of trust material for use by secure sockets. The trust - * material is based on a KeyStore and/or provider specific sources. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.TrustManagerFactory}. - */ -@Deprecated(since="1.4") -public class TrustManagerFactory { - // The provider - private Provider provider; - - // The provider implementation (delegate) - private TrustManagerFactorySpi factorySpi; - - // The name of the trust management algorithm. - private String algorithm; - - /** - *

The default TrustManager can be changed by setting the value of the - * {@code sun.ssl.trustmanager.type} security property to the desired name. - * - * @return the default type as specified by the - * {@code sun.ssl.trustmanager.type} security property, or an - * implementation-specific default if no such property exists. - * - * @see java.security.Security security properties - */ - public static final String getDefaultAlgorithm() { - String type; - type = AccessController.doPrivileged(new PrivilegedAction<>() { - public String run() { - return Security.getProperty("sun.ssl.trustmanager.type"); - } - }); - if (type == null) { - type = "SunX509"; - } - return type; - - } - - /** - * Creates a TrustManagerFactory object. - * - * @param factorySpi the delegate - * @param provider the provider - * @param algorithm the algorithm - */ - protected TrustManagerFactory(TrustManagerFactorySpi factorySpi, - Provider provider, String algorithm) { - this.factorySpi = factorySpi; - this.provider = provider; - this.algorithm = algorithm; - } - - /** - * Returns the algorithm name of this TrustManagerFactory - * object. - * - *

This is the same name that was specified in one of the - * getInstance calls that created this - * TrustManagerFactory object. - * - * @return the algorithm name of this TrustManagerFactory - * object. - */ - public final String getAlgorithm() { - return this.algorithm; - } - - /** - * Generates a TrustManagerFactory object that implements the - * specified trust management algorithm. - * If the default provider package provides an implementation of the - * requested trust management algorithm, an instance of - * TrustManagerFactory containing that implementation is - * returned. If the algorithm is not available in the default provider - * package, other provider packages are searched. - * - * @param algorithm the standard name of the requested trust management - * algorithm. - * - * @return the new TrustManagerFactory object - * - * @exception NoSuchAlgorithmException if the specified algorithm is not - * available in the default provider package or any of the other provider - * packages that were searched. - */ - public static final TrustManagerFactory getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try { - Object[] objs = SSLSecurity.getImpl(algorithm, - "TrustManagerFactory", (String) null); - return new TrustManagerFactory((TrustManagerFactorySpi)objs[0], - (Provider)objs[1], - algorithm); - } catch (NoSuchProviderException e) { - throw new NoSuchAlgorithmException(algorithm + " not found"); - } - } - - /** - * Generates a TrustManagerFactory object for the specified - * trust management algorithm from the specified provider. - * - * @param algorithm the standard name of the requested trust management - * algorithm. - * @param provider the name of the provider - * - * @return the new TrustManagerFactory object - * - * @exception NoSuchAlgorithmException if the specified algorithm is not - * available from the specified provider. - * @exception NoSuchProviderException if the specified provider has not - * been configured. - */ - public static final TrustManagerFactory getInstance(String algorithm, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null || provider.isEmpty()) - throw new IllegalArgumentException("missing provider"); - Object[] objs = SSLSecurity.getImpl(algorithm, "TrustManagerFactory", - provider); - return new TrustManagerFactory((TrustManagerFactorySpi)objs[0], - (Provider)objs[1], algorithm); - } - - /** - * Generates a TrustManagerFactory object for the specified - * trust management algorithm from the specified provider. - * - * @param algorithm the standard name of the requested trust management - * algorithm. - * @param provider an instance of the provider - * - * @return the new TrustManagerFactory object - * - * @exception NoSuchAlgorithmException if the specified algorithm is not - * available from the specified provider. - */ - public static final TrustManagerFactory getInstance(String algorithm, - Provider provider) - throws NoSuchAlgorithmException - { - if (provider == null) - throw new IllegalArgumentException("missing provider"); - Object[] objs = SSLSecurity.getImpl(algorithm, "TrustManagerFactory", - provider); - return new TrustManagerFactory((TrustManagerFactorySpi)objs[0], - (Provider)objs[1], algorithm); - } - - /** - * Returns the provider of this TrustManagerFactory object. - * - * @return the provider of this TrustManagerFactory object - */ - public final Provider getProvider() { - return this.provider; - } - - - /** - * Initializes this factory with a source of certificate - * authorities and related trust material. The - * provider may also include a provider-specific source - * of key material. - * - * @param ks the key store or null - */ - public void init(KeyStore ks) throws KeyStoreException { - factorySpi.engineInit(ks); - } - - /** - * Returns one trust manager for each type of trust material. - * @return the trust managers - */ - public TrustManager[] getTrustManagers() { - return factorySpi.engineGetTrustManagers(); - } -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java b/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java deleted file mode 100644 index 8ab1901c4ea..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactorySpi.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.TrustManagerFactorySpi - */ - -package com.sun.net.ssl; - -import java.security.*; - -/** - * This class defines the Service Provider Interface (SPI) - * for the TrustManagerFactory class. - * - *

All the abstract methods in this class must be implemented by each - * cryptographic service provider who wishes to supply the implementation - * of a particular trust manager factory. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.TrustManagerFactorySpi}. - */ -@Deprecated(since="1.4") -public abstract class TrustManagerFactorySpi { - /** - * Initializes this factory with a source of certificate - * authorities and related trust material. The - * provider may also include a provider-specific source - * of key material. - * - * @param ks the key store or null - */ - protected abstract void engineInit(KeyStore ks) throws KeyStoreException; - - /** - * Returns one trust manager for each type of trust material. - * @return the trust managers - */ - protected abstract TrustManager[] engineGetTrustManagers(); -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java b/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java deleted file mode 100644 index 8d4019c8721..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/X509KeyManager.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.X509KeyManager - */ - -package com.sun.net.ssl; - -import java.security.KeyManagementException; -import java.security.PrivateKey; -import java.security.Principal; -import java.security.cert.X509Certificate; - -/** - * Instances of this interface manage which X509 certificate-based - * key pairs are used to authenticate the local side of a secure - * socket. The individual entries are identified by unique alias names. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.X509KeyManager}. - */ -@Deprecated(since="1.4") -public interface X509KeyManager extends KeyManager { - /** - * Get the matching aliases for authenticating the client side of a secure - * socket given the public key type and the list of - * certificate issuer authorities recognized by the peer (if any). - * - * @param keyType the key algorithm type name - * @param issuers the list of acceptable CA issuer subject names - * @return the matching alias names - */ - public String[] getClientAliases(String keyType, Principal[] issuers); - - /** - * Choose an alias to authenticate the client side of a secure - * socket given the public key type and the list of - * certificate issuer authorities recognized by the peer (if any). - * - * @param keyType the key algorithm type name - * @param issuers the list of acceptable CA issuer subject names - * @return the alias name for the desired key - */ - public String chooseClientAlias(String keyType, Principal[] issuers); - - /** - * Get the matching aliases for authenticating the server side of a secure - * socket given the public key type and the list of - * certificate issuer authorities recognized by the peer (if any). - * - * @param keyType the key algorithm type name - * @param issuers the list of acceptable CA issuer subject names - * @return the matching alias names - */ - public String[] getServerAliases(String keyType, Principal[] issuers); - - /** - * Choose an alias to authenticate the server side of a secure - * socket given the public key type and the list of - * certificate issuer authorities recognized by the peer (if any). - * - * @param keyType the key algorithm type name - * @param issuers the list of acceptable CA issuer subject names - * @return the alias name for the desired key - */ - public String chooseServerAlias(String keyType, Principal[] issuers); - - /** - * Returns the certificate chain associated with the given alias. - * - * @param alias the alias name - * - * @return the certificate chain (ordered with the user's certificate first - * and the root certificate authority last) - */ - public X509Certificate[] getCertificateChain(String alias); - - /* - * Returns the key associated with the given alias. - * - * @param alias the alias name - * - * @return the requested key - */ - public PrivateKey getPrivateKey(String alias); -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java b/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java deleted file mode 100644 index 041c3e6f587..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/X509TrustManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: this file was copied from javax.net.ssl.X509TrustManager - */ - -package com.sun.net.ssl; - -import java.security.cert.X509Certificate; - -/** - * Instance of this interface manage which X509 certificates - * may be used to authenticate the remote side of a secure - * socket. Decisions may be based on trusted certificate - * authorities, certificate revocation lists, online - * status checking or other means. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.X509TrustManager}. - */ -@Deprecated(since="1.4") -public interface X509TrustManager extends TrustManager { - /** - * Given the partial or complete certificate chain - * provided by the peer, build a certificate path - * to a trusted root and return true if it can be - * validated and is trusted for client SSL authentication. - * - * @param chain the peer certificate chain - */ - public boolean isClientTrusted(X509Certificate[] chain); - - /** - * Given the partial or complete certificate chain - * provided by the peer, build a certificate path - * to a trusted root and return true if it can be - * validated and is trusted for server SSL authentication. - * - * @param chain the peer certificate chain - */ - public boolean isServerTrusted(X509Certificate[] chain); - - /** - * Return an array of certificate authority certificates - * which are trusted for authenticating peers. - * - * @return the acceptable CA issuer certificates - */ - public X509Certificate[] getAcceptedIssuers(); -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java b/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java deleted file mode 100644 index 40e3317dd0f..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/Provider.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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.net.ssl.internal.ssl; - -import sun.security.ssl.SunJSSE; - -/** - * Main class for the SunJSSE provider. The actual code was moved to the - * class sun.security.ssl.SunJSSE, but for backward compatibility we - * continue to use this class as the main Provider class. - */ -@Deprecated(since="9") -public final class Provider extends SunJSSE { - - private static final long serialVersionUID = 3231825739635378733L; - - // standard constructor - public Provider() { - super(); - } - - /** - * Installs the JSSE provider. - */ - public static synchronized void install() { - /* nop. Remove this method in the future. */ - } - -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java b/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java deleted file mode 100644 index 2af41b97fe5..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/internal/ssl/X509ExtendedTrustManager.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.net.ssl.internal.ssl; - -import javax.net.ssl.X509TrustManager; - -import java.security.cert.X509Certificate; -import java.security.cert.CertificateException; - -/** - * Instance of this class is an extension of X509TrustManager. - *

- * Note that this class is referenced by the Deploy workspace. Any updates - * must make sure that they do not cause any breakage there. - *

- * It takes the responsiblity of checking the peer identity with its - * principal declared in the cerificate. - *

- * The class provides an alternative to HostnameVerifer. - * If application customizes its HostnameVerifer for - * HttpsURLConnection, the peer identity will be checked - * by the customized HostnameVerifer; otherwise, it will - * be checked by the extended trust manager. - *

- * RFC2830 defines the server identification specification for "LDAP" - * algorithm. RFC2818 defines both the server identification and the - * client identification specification for "HTTPS" algorithm. - * - * @see X509TrustManager - * @see HostnameVerifier - * - * @since 1.6 - * @author Xuelei Fan - */ -@Deprecated(since="9") -public abstract class X509ExtendedTrustManager implements X509TrustManager { - /** - * Constructor used by subclasses only. - */ - protected X509ExtendedTrustManager() { - } - - /** - * Given the partial or complete certificate chain provided by the - * peer, check its identity and build a certificate path to a trusted - * root, return if it can be validated and is trusted for client SSL - * authentication based on the authentication type. - *

- * The authentication type is determined by the actual certificate - * used. For instance, if RSAPublicKey is used, the authType - * should be "RSA". Checking is case-sensitive. - *

- * The algorithm parameter specifies the client identification protocol - * to use. If the algorithm and the peer hostname are available, the - * peer hostname is checked against the peer's identity presented in - * the X509 certificate, in order to prevent masquerade attacks. - * - * @param chain the peer certificate chain - * @param authType the authentication type based on the client certificate - * @param hostname the peer hostname - * @param algorithm the identification algorithm - * @throws IllegalArgumentException if null or zero-length chain - * is passed in for the chain parameter or if null or zero-length - * string is passed in for the authType parameter - * @throws CertificateException if the certificate chain is not trusted - * by this TrustManager. - */ - public abstract void checkClientTrusted(X509Certificate[] chain, - String authType, String hostname, String algorithm) - throws CertificateException; - - /** - * Given the partial or complete certificate chain provided by the - * peer, check its identity and build a certificate path to a trusted - * root, return if it can be validated and is trusted for server SSL - * authentication based on the authentication type. - *

- * The authentication type is the key exchange algorithm portion - * of the cipher suites represented as a String, such as "RSA", - * "DHE_DSS". Checking is case-sensitive. - *

- * The algorithm parameter specifies the server identification protocol - * to use. If the algorithm and the peer hostname are available, the - * peer hostname is checked against the peer's identity presented in - * the X509 certificate, in order to prevent masquerade attacks. - * - * @param chain the peer certificate chain - * @param authType the key exchange algorithm used - * @param hostname the peer hostname - * @param algorithm the identification algorithm - * @throws IllegalArgumentException if null or zero-length chain - * is passed in for the chain parameter or if null or zero-length - * string is passed in for the authType parameter - * @throws CertificateException if the certificate chain is not trusted - * by this TrustManager. - */ - public abstract void checkServerTrusted(X509Certificate[] chain, - String authType, String hostname, String algorithm) - throws CertificateException; -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java b/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java deleted file mode 100644 index 46b8e299911..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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.net.ssl.internal.www.protocol.https; - -import java.net.URL; -import java.net.Proxy; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Iterator; - -import java.security.Principal; -import java.security.cert.*; - -import javax.security.auth.x500.X500Principal; - -import sun.security.util.HostnameChecker; -import sun.security.util.DerValue; -import sun.security.x509.X500Name; - -import sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection; - -/** - * This class was introduced to provide an additional level of - * abstraction between javax.net.ssl.HttpURLConnection and - * com.sun.net.ssl.HttpURLConnection objects.

- * - * javax.net.ssl.HttpURLConnection is used in the new sun.net version - * of protocol implementation (this one) - * com.sun.net.ssl.HttpURLConnection is used in the com.sun version. - * - */ -@Deprecated(since="9") -@SuppressWarnings("deprecation") // HttpsURLConnection is deprecated -public class DelegateHttpsURLConnection extends AbstractDelegateHttpsURLConnection { - - // we need a reference to the HttpsURLConnection to get - // the properties set there - // we also need it to be public so that it can be referenced - // from sun.net.www.protocol.http.HttpURLConnection - // this is for ResponseCache.put(URI, URLConnection) - // second parameter needs to be cast to javax.net.ssl.HttpsURLConnection - // instead of AbstractDelegateHttpsURLConnection - - public com.sun.net.ssl.HttpsURLConnection httpsURLConnection; - - DelegateHttpsURLConnection(URL url, - sun.net.www.protocol.http.Handler handler, - com.sun.net.ssl.HttpsURLConnection httpsURLConnection) - throws IOException { - this(url, null, handler, httpsURLConnection); - } - - DelegateHttpsURLConnection(URL url, Proxy p, - sun.net.www.protocol.http.Handler handler, - com.sun.net.ssl.HttpsURLConnection httpsURLConnection) - throws IOException { - super(url, p, handler); - this.httpsURLConnection = httpsURLConnection; - } - - protected javax.net.ssl.SSLSocketFactory getSSLSocketFactory() { - return httpsURLConnection.getSSLSocketFactory(); - } - - protected javax.net.ssl.HostnameVerifier getHostnameVerifier() { - // note: getHostnameVerifier() never returns null - return new VerifierWrapper(httpsURLConnection.getHostnameVerifier()); - } - - /* - * Called by layered delegator's finalize() method to handle closing - * the underlying object. - */ - protected void dispose() throws Throwable { - super.finalize(); - } -} - -class VerifierWrapper implements javax.net.ssl.HostnameVerifier { - @SuppressWarnings("deprecation") - private com.sun.net.ssl.HostnameVerifier verifier; - - @SuppressWarnings("deprecation") - VerifierWrapper(com.sun.net.ssl.HostnameVerifier verifier) { - this.verifier = verifier; - } - - /* - * In com.sun.net.ssl.HostnameVerifier the method is defined - * as verify(String urlHostname, String certHostname). - * This means we need to extract the hostname from the X.509 certificate - * in this wrapper. - */ - public boolean verify(String hostname, javax.net.ssl.SSLSession session) { - try { - Certificate[] serverChain = session.getPeerCertificates(); - if ((serverChain == null) || (serverChain.length == 0)) { - return false; - } - if (serverChain[0] instanceof X509Certificate == false) { - return false; - } - X509Certificate serverCert = (X509Certificate)serverChain[0]; - String serverName = getServername(serverCert); - if (serverName == null) { - return false; - } - return verifier.verify(hostname, serverName); - } catch (javax.net.ssl.SSLPeerUnverifiedException e) { - return false; - } - } - - /* - * Extract the name of the SSL server from the certificate. - * - * Note this code is essentially a subset of the hostname extraction - * code in HostnameChecker. - */ - private static String getServername(X509Certificate peerCert) { - try { - // compare to subjectAltNames if dnsName is present - Collection> subjAltNames = peerCert.getSubjectAlternativeNames(); - if (subjAltNames != null) { - for (Iterator> itr = subjAltNames.iterator(); itr.hasNext(); ) { - List next = itr.next(); - if (((Integer)next.get(0)).intValue() == 2) { - // compare dNSName with host in url - String dnsName = ((String)next.get(1)); - return dnsName; - } - } - } - - // else check against common name in the subject field - X500Name subject = HostnameChecker.getSubjectX500Name(peerCert); - - DerValue derValue = subject.findMostSpecificAttribute - (X500Name.commonName_oid); - if (derValue != null) { - try { - String name = derValue.getAsString(); - return name; - } catch (IOException e) { - // ignore - } - } - } catch (java.security.cert.CertificateException e) { - // ignore - } - return null; - } - -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java b/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java deleted file mode 100644 index 42874841bfc..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/Handler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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.net.ssl.internal.www.protocol.https; - -import java.io.IOException; -import java.net.URL; -import java.net.Proxy; - -/** - * This class exists for compatibility with previous JSSE releases - * only. The HTTPS implementation can now be found in - * sun.net.www.protocol.https. - * - */ -@Deprecated(since="9") -public class Handler extends sun.net.www.protocol.https.Handler { - - public Handler() { - super(); - } - - public Handler(String proxy, int port) { - super(proxy, port); - } - - protected java.net.URLConnection openConnection(URL u) throws IOException { - return openConnection(u, (Proxy)null); - } - - protected java.net.URLConnection openConnection(URL u, Proxy p) throws IOException { - return new HttpsURLConnectionOldImpl(u, p, this); - } -} diff --git a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java b/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java deleted file mode 100644 index eb7c11b21f9..00000000000 --- a/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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. - */ - -/* - * NOTE: This class lives in the package sun.net.www.protocol.https. - * There is a copy in com.sun.net.ssl.internal.www.protocol.https for JSSE - * 1.0.2 compatibility. It is 100% identical except the package and extends - * lines. Any changes should be made to be class in sun.net.* and then copied - * to com.sun.net.*. - */ - -// For both copies of the file, uncomment one line and comment the other -// package sun.net.www.protocol.https; -package com.sun.net.ssl.internal.www.protocol.https; - -import java.net.URL; -import java.net.Proxy; -import java.net.ProtocolException; -import java.net.MalformedURLException; -import java.io.*; -import java.net.Authenticator; -import javax.net.ssl.*; -import java.security.Permission; -import java.util.Map; -import java.util.List; -import sun.net.www.http.HttpClient; - -/** - * A class to represent an HTTP connection to a remote object. - * - * Ideally, this class should subclass and inherit the http handler - * implementation, but it can't do so because that class have the - * wrong Java Type. Thus it uses the delegate (aka, the - * Adapter/Wrapper design pattern) to reuse code from the http - * handler. - * - * Since it would use a delegate to access - * sun.net.www.protocol.http.HttpURLConnection functionalities, it - * needs to implement all public methods in it's super class and all - * the way to Object. - * - */ - -// For both copies of the file, uncomment one line and comment the other -// public class HttpsURLConnectionImpl -// extends javax.net.ssl.HttpsURLConnection { -@Deprecated(since="9") -@SuppressWarnings("deprecation") // HttpsURLConnection is deprecated -public class HttpsURLConnectionOldImpl - extends com.sun.net.ssl.HttpsURLConnection { - - private DelegateHttpsURLConnection delegate; - -// For both copies of the file, uncomment one line and comment the other -// HttpsURLConnectionImpl(URL u, Handler handler) throws IOException { - HttpsURLConnectionOldImpl(URL u, Handler handler) throws IOException { - this(u, null, handler); - } - - static URL checkURL(URL u) throws IOException { - if (u != null) { - if (u.toExternalForm().indexOf('\n') > -1) { - throw new MalformedURLException("Illegal character in URL"); - } - } - return u; - } -// For both copies of the file, uncomment one line and comment the other -// HttpsURLConnectionImpl(URL u, Handler handler) throws IOException { - HttpsURLConnectionOldImpl(URL u, Proxy p, Handler handler) throws IOException { - super(checkURL(u)); - delegate = new DelegateHttpsURLConnection(url, p, handler, this); - } - - /** - * Create a new HttpClient object, bypassing the cache of - * HTTP client objects/connections. - * - * @param url the URL being accessed - */ - protected void setNewClient(URL url) throws IOException { - delegate.setNewClient(url, false); - } - - /** - * Obtain a HttpClient object. Use the cached copy if specified. - * - * @param url the URL being accessed - * @param useCache whether the cached connection should be used - * if present - */ - protected void setNewClient(URL url, boolean useCache) - throws IOException { - delegate.setNewClient(url, useCache); - } - - /** - * Create a new HttpClient object, set up so that it uses - * per-instance proxying to the given HTTP proxy. This - * bypasses the cache of HTTP client objects/connections. - * - * @param url the URL being accessed - * @param proxyHost the proxy host to use - * @param proxyPort the proxy port to use - */ - protected void setProxiedClient(URL url, String proxyHost, int proxyPort) - throws IOException { - delegate.setProxiedClient(url, proxyHost, proxyPort); - } - - /** - * Obtain a HttpClient object, set up so that it uses per-instance - * proxying to the given HTTP proxy. Use the cached copy of HTTP - * client objects/connections if specified. - * - * @param url the URL being accessed - * @param proxyHost the proxy host to use - * @param proxyPort the proxy port to use - * @param useCache whether the cached connection should be used - * if present - */ - protected void setProxiedClient(URL url, String proxyHost, int proxyPort, - boolean useCache) throws IOException { - delegate.setProxiedClient(url, proxyHost, proxyPort, useCache); - } - - /** - * Implements the HTTP protocol handler's "connect" method, - * establishing an SSL connection to the server as necessary. - */ - public void connect() throws IOException { - delegate.connect(); - } - - /** - * Used by subclass to access "connected" variable. Since we are - * delegating the actual implementation to "delegate", we need to - * delegate the access of "connected" as well. - */ - protected boolean isConnected() { - return delegate.isConnected(); - } - - /** - * Used by subclass to access "connected" variable. Since we are - * delegating the actual implementation to "delegate", we need to - * delegate the access of "connected" as well. - */ - protected void setConnected(boolean conn) { - delegate.setConnected(conn); - } - - /** - * Returns the cipher suite in use on this connection. - */ - public String getCipherSuite() { - return delegate.getCipherSuite(); - } - - /** - * Returns the certificate chain the client sent to the - * server, or null if the client did not authenticate. - */ - public java.security.cert.Certificate [] - getLocalCertificates() { - return delegate.getLocalCertificates(); - } - - /** - * Returns the server's certificate chain, or throws - * SSLPeerUnverified Exception if - * the server did not authenticate. - */ - public java.security.cert.Certificate [] - getServerCertificates() throws SSLPeerUnverifiedException { - return delegate.getServerCertificates(); - } - - /* - * Allowable input/output sequences: - * [interpreted as POST/PUT] - * - get output, [write output,] get input, [read input] - * - get output, [write output] - * [interpreted as GET] - * - get input, [read input] - * Disallowed: - * - get input, [read input,] get output, [write output] - */ - - public synchronized OutputStream getOutputStream() throws IOException { - return delegate.getOutputStream(); - } - - public synchronized InputStream getInputStream() throws IOException { - return delegate.getInputStream(); - } - - public InputStream getErrorStream() { - return delegate.getErrorStream(); - } - - /** - * Disconnect from the server. - */ - public void disconnect() { - delegate.disconnect(); - } - - public boolean usingProxy() { - return delegate.usingProxy(); - } - - /** - * Returns an unmodifiable Map of the header fields. - * The Map keys are Strings that represent the - * response-header field names. Each Map value is an - * unmodifiable List of Strings that represents - * the corresponding field values. - * - * @return a Map of header fields - * @since 1.4 - */ - public Map> getHeaderFields() { - return delegate.getHeaderFields(); - } - - /** - * Gets a header field by name. Returns null if not known. - * @param name the name of the header field - */ - public String getHeaderField(String name) { - return delegate.getHeaderField(name); - } - - /** - * Gets a header field by index. Returns null if not known. - * @param n the index of the header field - */ - public String getHeaderField(int n) { - return delegate.getHeaderField(n); - } - - /** - * Gets a header field by index. Returns null if not known. - * @param n the index of the header field - */ - public String getHeaderFieldKey(int n) { - return delegate.getHeaderFieldKey(n); - } - - /** - * Sets request property. If a property with the key already - * exists, overwrite its value with the new value. - * @param value the value to be set - */ - public void setRequestProperty(String key, String value) { - delegate.setRequestProperty(key, value); - } - - /** - * Adds a general request property specified by a - * key-value pair. This method will not overwrite - * existing values associated with the same key. - * - * @param key the keyword by which the request is known - * (e.g., "accept"). - * @param value the value associated with it. - * @see #getRequestProperties(java.lang.String) - * @since 1.4 - */ - public void addRequestProperty(String key, String value) { - delegate.addRequestProperty(key, value); - } - - /** - * Overwrite super class method - */ - public int getResponseCode() throws IOException { - return delegate.getResponseCode(); - } - - public String getRequestProperty(String key) { - return delegate.getRequestProperty(key); - } - - /** - * Returns an unmodifiable Map of general request - * properties for this connection. The Map keys - * are Strings that represent the request-header - * field names. Each Map value is a unmodifiable List - * of Strings that represents the corresponding - * field values. - * - * @return a Map of the general request properties for this connection. - * @throws IllegalStateException if already connected - * @since 1.4 - */ - public Map> getRequestProperties() { - return delegate.getRequestProperties(); - } - - /* - * We support JDK 1.2.x so we can't count on these from JDK 1.3. - * We override and supply our own version. - */ - public void setInstanceFollowRedirects(boolean shouldFollow) { - delegate.setInstanceFollowRedirects(shouldFollow); - } - - public boolean getInstanceFollowRedirects() { - return delegate.getInstanceFollowRedirects(); - } - - public void setRequestMethod(String method) throws ProtocolException { - delegate.setRequestMethod(method); - } - - public String getRequestMethod() { - return delegate.getRequestMethod(); - } - - public String getResponseMessage() throws IOException { - return delegate.getResponseMessage(); - } - - public long getHeaderFieldDate(String name, long Default) { - return delegate.getHeaderFieldDate(name, Default); - } - - public Permission getPermission() throws IOException { - return delegate.getPermission(); - } - - public URL getURL() { - return delegate.getURL(); - } - - public int getContentLength() { - return delegate.getContentLength(); - } - - public long getContentLengthLong() { - return delegate.getContentLengthLong(); - } - - public String getContentType() { - return delegate.getContentType(); - } - - public String getContentEncoding() { - return delegate.getContentEncoding(); - } - - public long getExpiration() { - return delegate.getExpiration(); - } - - public long getDate() { - return delegate.getDate(); - } - - public long getLastModified() { - return delegate.getLastModified(); - } - - public int getHeaderFieldInt(String name, int Default) { - return delegate.getHeaderFieldInt(name, Default); - } - - public long getHeaderFieldLong(String name, long Default) { - return delegate.getHeaderFieldLong(name, Default); - } - - public Object getContent() throws IOException { - return delegate.getContent(); - } - - @SuppressWarnings("rawtypes") - public Object getContent(Class[] classes) throws IOException { - return delegate.getContent(classes); - } - - public String toString() { - return delegate.toString(); - } - - public void setDoInput(boolean doinput) { - delegate.setDoInput(doinput); - } - - public boolean getDoInput() { - return delegate.getDoInput(); - } - - public void setDoOutput(boolean dooutput) { - delegate.setDoOutput(dooutput); - } - - public boolean getDoOutput() { - return delegate.getDoOutput(); - } - - public void setAllowUserInteraction(boolean allowuserinteraction) { - delegate.setAllowUserInteraction(allowuserinteraction); - } - - public boolean getAllowUserInteraction() { - return delegate.getAllowUserInteraction(); - } - - public void setUseCaches(boolean usecaches) { - delegate.setUseCaches(usecaches); - } - - public boolean getUseCaches() { - return delegate.getUseCaches(); - } - - public void setIfModifiedSince(long ifmodifiedsince) { - delegate.setIfModifiedSince(ifmodifiedsince); - } - - public long getIfModifiedSince() { - return delegate.getIfModifiedSince(); - } - - public boolean getDefaultUseCaches() { - return delegate.getDefaultUseCaches(); - } - - public void setDefaultUseCaches(boolean defaultusecaches) { - delegate.setDefaultUseCaches(defaultusecaches); - } - - /* - * finalize (dispose) the delegated object. Otherwise - * sun.net.www.protocol.http.HttpURLConnection's finalize() - * would have to be made public. - */ - protected void finalize() throws Throwable { - delegate.dispose(); - } - - public boolean equals(Object obj) { - return delegate.equals(obj); - } - - public int hashCode() { - return delegate.hashCode(); - } - - public void setConnectTimeout(int timeout) { - delegate.setConnectTimeout(timeout); - } - - public int getConnectTimeout() { - return delegate.getConnectTimeout(); - } - - public void setReadTimeout(int timeout) { - delegate.setReadTimeout(timeout); - } - - public int getReadTimeout() { - return delegate.getReadTimeout(); - } - - public void setFixedLengthStreamingMode (int contentLength) { - delegate.setFixedLengthStreamingMode(contentLength); - } - - public void setFixedLengthStreamingMode(long contentLength) { - delegate.setFixedLengthStreamingMode(contentLength); - } - - public void setChunkedStreamingMode (int chunklen) { - delegate.setChunkedStreamingMode(chunklen); - } - - @Override - public void setAuthenticator(Authenticator auth) { - delegate.setAuthenticator(auth); - } -} diff --git a/src/java.base/share/classes/com/sun/security/cert/internal/x509/X509V1CertImpl.java b/src/java.base/share/classes/com/sun/security/cert/internal/x509/X509V1CertImpl.java index 0fb1a6c1e88..9e64617eb5f 100644 --- a/src/java.base/share/classes/com/sun/security/cert/internal/x509/X509V1CertImpl.java +++ b/src/java.base/share/classes/com/sun/security/cert/internal/x509/X509V1CertImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,8 @@ import java.util.Vector; * * @author Jeff Nisewanger */ -@Deprecated +@SuppressWarnings("removal") +@Deprecated(since="9", forRemoval=true) public class X509V1CertImpl extends X509Certificate implements Serializable { static final long serialVersionUID = -2048442350420423405L; private java.security.cert.X509Certificate wrappedCert; diff --git a/src/java.base/share/classes/java/lang/AbstractStringBuilder.java b/src/java.base/share/classes/java/lang/AbstractStringBuilder.java index c42ff28eaf9..997fa07645e 100644 --- a/src/java.base/share/classes/java/lang/AbstractStringBuilder.java +++ b/src/java.base/share/classes/java/lang/AbstractStringBuilder.java @@ -93,13 +93,16 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence { /** * Creates an AbstractStringBuilder with the specified coder and with - * the initial capacity equal to the smaller of (capacity + addition) + * the initial capacity equal to the smaller of (length + addition) * and Integer.MAX_VALUE. */ - AbstractStringBuilder(byte coder, int capacity, int addition) { + AbstractStringBuilder(byte coder, int length, int addition) { + if (length < 0) { + throw new NegativeArraySizeException("Negative length: " + length); + } this.coder = coder; - capacity = (capacity < Integer.MAX_VALUE - addition) - ? capacity + addition : Integer.MAX_VALUE; + int capacity = (length < Integer.MAX_VALUE - addition) + ? length + addition : Integer.MAX_VALUE; value = (coder == LATIN1) ? new byte[capacity] : StringUTF16.newBytesFor(capacity); } diff --git a/src/java.base/share/classes/java/lang/Process.java b/src/java.base/share/classes/java/lang/Process.java index 90ca41d0375..247a91847d2 100644 --- a/src/java.base/share/classes/java/lang/Process.java +++ b/src/java.base/share/classes/java/lang/Process.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -206,20 +206,20 @@ public abstract class Process { public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { - long startTime = System.nanoTime(); - long rem = unit.toNanos(timeout); + long remainingNanos = unit.toNanos(timeout); // throw NPE before other conditions + if (hasExited()) + return true; + if (timeout <= 0) + return false; + long deadline = System.nanoTime() + remainingNanos; do { - try { - exitValue(); + Thread.sleep(Math.min(TimeUnit.NANOSECONDS.toMillis(remainingNanos) + 1, 100)); + if (hasExited()) return true; - } catch(IllegalThreadStateException ex) { - if (rem > 0) - Thread.sleep( - Math.min(TimeUnit.NANOSECONDS.toMillis(rem) + 1, 100)); - } - rem = unit.toNanos(timeout) - (System.nanoTime() - startTime); - } while (rem > 0); + remainingNanos = deadline - System.nanoTime(); + } while (remainingNanos > 0); + return false; } @@ -320,11 +320,20 @@ public abstract class Process { * @since 1.8 */ public boolean isAlive() { + return !hasExited(); + } + + /** + * This is called from the default implementation of + * {@code waitFor(long, TimeUnit)}, which is specified to poll + * {@code exitValue()}. + */ + private boolean hasExited() { try { exitValue(); - return false; - } catch(IllegalThreadStateException e) { return true; + } catch (IllegalThreadStateException e) { + return false; } } diff --git a/src/java.base/share/classes/java/lang/ProcessBuilder.java b/src/java.base/share/classes/java/lang/ProcessBuilder.java index d0850cdd401..c360bc4334b 100644 --- a/src/java.base/share/classes/java/lang/ProcessBuilder.java +++ b/src/java.base/share/classes/java/lang/ProcessBuilder.java @@ -89,7 +89,7 @@ import sun.security.action.GetPropertyAction; *

  • a destination for standard output * and standard error. By default, the subprocess writes standard * output and standard error to pipes. Java code can access these pipes - * via the input streams returned by {@link Process#getOutputStream()} and + * via the input streams returned by {@link Process#getInputStream()} and * {@link Process#getErrorStream()}. However, standard output and * standard error may be redirected to other destinations using * {@link #redirectOutput(Redirect) redirectOutput} and diff --git a/src/java.base/share/classes/java/lang/StringBuffer.java b/src/java.base/share/classes/java/lang/StringBuffer.java index bdd6280ca0f..5b8931efa50 100644 --- a/src/java.base/share/classes/java/lang/StringBuffer.java +++ b/src/java.base/share/classes/java/lang/StringBuffer.java @@ -157,10 +157,6 @@ import jdk.internal.HotSpotIntrinsicCandidate; * as the specified {@code CharSequence}. The initial capacity of * the string buffer is {@code 16} plus the length of the * {@code CharSequence} argument. - *

    - * If the length of the specified {@code CharSequence} is - * less than or equal to zero, then an empty buffer of capacity - * {@code 16} is returned. * * @param seq the sequence to copy. * @since 1.5 diff --git a/src/java.base/share/classes/java/lang/ThreadGroup.java b/src/java.base/share/classes/java/lang/ThreadGroup.java index cedb44e73d5..a4a9fd58922 100644 --- a/src/java.base/share/classes/java/lang/ThreadGroup.java +++ b/src/java.base/share/classes/java/lang/ThreadGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ package java.lang; import java.io.PrintStream; import java.util.Arrays; -import jdk.internal.misc.VM; /** * A thread group represents a set of threads. In addition, a thread @@ -425,7 +424,7 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler { ThreadGroup[] groupsSnapshot = null; synchronized (this) { if (destroyed) { - return 0; + return n; } int nt = nthreads; if (nt > list.length - n) { @@ -559,7 +558,7 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler { ThreadGroup[] groupsSnapshot = null; synchronized (this) { if (destroyed) { - return 0; + return n; } int ng = ngroups; if (ng > list.length - n) { diff --git a/src/java.base/share/classes/java/lang/Throwable.java b/src/java.base/share/classes/java/lang/Throwable.java index f2d4d46cb41..8b7718ae8c2 100644 --- a/src/java.base/share/classes/java/lang/Throwable.java +++ b/src/java.base/share/classes/java/lang/Throwable.java @@ -914,8 +914,7 @@ public class Throwable implements Serializable { for (Throwable t : suppressedExceptions) { // Enforce constraints on suppressed exceptions in // case of corrupt or malicious stream. - if (t == null) - throw new NullPointerException(NULL_CAUSE_MESSAGE); + Objects.requireNonNull(t, NULL_CAUSE_MESSAGE); if (t == this) throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); suppressed.add(t); @@ -942,8 +941,7 @@ public class Throwable implements Serializable { stackTrace = null; } else { // Verify stack trace elements are non-null. for(StackTraceElement ste : stackTrace) { - if (ste == null) - throw new NullPointerException("null StackTraceElement in serial stream. "); + Objects.requireNonNull(ste, "null StackTraceElement in serial stream."); } } } else { @@ -1034,8 +1032,7 @@ public class Throwable implements Serializable { if (exception == this) throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception); - if (exception == null) - throw new NullPointerException(NULL_CAUSE_MESSAGE); + Objects.requireNonNull(exception, NULL_CAUSE_MESSAGE); if (suppressedExceptions == null) // Suppressed exceptions not recorded return; diff --git a/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java b/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java index c56601e811d..eda816c3212 100644 --- a/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java +++ b/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,12 +30,16 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.HashSet; import java.util.Set; import sun.net.ConnectionResetException; import sun.net.NetHooks; +import sun.net.PlatformSocketImpl; import sun.net.ResourceManager; import sun.net.util.SocketExceptions; @@ -46,7 +50,7 @@ import sun.net.util.SocketExceptions; * * @author Steven B. Byrne */ -abstract class AbstractPlainSocketImpl extends SocketImpl { +abstract class AbstractPlainSocketImpl extends SocketImpl implements PlatformSocketImpl { /* instance variable for SO_TIMEOUT */ int timeout; // timeout in millisec // traffic class @@ -450,15 +454,17 @@ abstract class AbstractPlainSocketImpl extends SocketImpl { /** * Accepts connections. - * @param s the connection + * @param si the socket impl */ - protected void accept(SocketImpl s) throws IOException { + protected void accept(SocketImpl si) throws IOException { + si.fd = new FileDescriptor(); acquireFD(); try { - socketAccept(s); + socketAccept(si); } finally { releaseFD(); } + SocketCleanable.register(si.fd); } /** @@ -470,8 +476,14 @@ abstract class AbstractPlainSocketImpl extends SocketImpl { throw new IOException("Socket Closed"); if (shut_rd) throw new IOException("Socket input is shutdown"); - if (socketInputStream == null) - socketInputStream = new SocketInputStream(this); + if (socketInputStream == null) { + PrivilegedExceptionAction pa = () -> new SocketInputStream(this); + try { + socketInputStream = AccessController.doPrivileged(pa); + } catch (PrivilegedActionException e) { + throw (IOException) e.getCause(); + } + } } return socketInputStream; } @@ -489,8 +501,14 @@ abstract class AbstractPlainSocketImpl extends SocketImpl { throw new IOException("Socket Closed"); if (shut_wr) throw new IOException("Socket output is shutdown"); - if (socketOutputStream == null) - socketOutputStream = new SocketOutputStream(this); + if (socketOutputStream == null) { + PrivilegedExceptionAction pa = () -> new SocketOutputStream(this); + try { + socketOutputStream = AccessController.doPrivileged(pa); + } catch (PrivilegedActionException e) { + throw (IOException) e.getCause(); + } + } } return socketOutputStream; } @@ -589,15 +607,10 @@ abstract class AbstractPlainSocketImpl extends SocketImpl { } } - void reset() throws IOException { - if (fd != null) { - socketClose(); - } - fd = null; - super.reset(); + void reset() { + throw new InternalError("should not get here"); } - /** * Shutdown read-half of the socket connection; */ diff --git a/src/java.base/share/classes/java/net/ContentHandler.java b/src/java.base/share/classes/java/net/ContentHandler.java index 119af89fed4..8cf7e550aab 100644 --- a/src/java.base/share/classes/java/net/ContentHandler.java +++ b/src/java.base/share/classes/java/net/ContentHandler.java @@ -47,7 +47,7 @@ import java.io.IOException; * If no content handler could be {@linkplain URLConnection#getContent() found}, * URLConnection will look for a content handler in a user-definable set of places. * Users can define a vertical-bar delimited set of class prefixes - * to search through by defining the {@link java.net.URLConnection#contentPathProp} + * to search through by defining the {@value java.net.URLConnection#contentPathProp} * property. The class name must be of the form: *

    * {package-prefix}.{major}.{minor} diff --git a/src/java.base/share/classes/java/net/DelegatingSocketImpl.java b/src/java.base/share/classes/java/net/DelegatingSocketImpl.java new file mode 100644 index 00000000000..f0dc63e5a18 --- /dev/null +++ b/src/java.base/share/classes/java/net/DelegatingSocketImpl.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.net; + +import java.io.FileDescriptor; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Objects; +import java.util.Set; + +import sun.net.PlatformSocketImpl; + +/** + * A SocketImpl that delegates all methods to another SocketImpl. + */ + +class DelegatingSocketImpl extends SocketImpl { + protected final SocketImpl delegate; + + DelegatingSocketImpl(SocketImpl delegate) { + assert delegate instanceof PlatformSocketImpl; + this.delegate = Objects.requireNonNull(delegate); + } + + final SocketImpl delegate() { + return delegate; + } + + @Override + protected FileDescriptor getFileDescriptor() { + return delegate.getFileDescriptor(); + } + + @Override + protected InetAddress getInetAddress() { + return delegate.getInetAddress(); + } + + @Override + protected int getPort() { + return delegate.getPort(); + } + + @Override + protected int getLocalPort() { + return delegate.getLocalPort(); + } + + @Override + protected void create(boolean stream) throws IOException { + delegate.create(stream); + } + + @Override + protected void connect(String host, int port) throws IOException { + delegate.connect(host, port); + } + + @Override + protected void connect(InetAddress address, int port) throws IOException { + delegate.connect(address, port); + } + + @Override + protected void connect(SocketAddress address, int timeout) throws IOException { + delegate.connect(address, timeout); + } + + @Override + protected void bind(InetAddress host, int port) throws IOException { + delegate.bind(host, port); + } + + @Override + protected void listen(int backlog) throws IOException { + delegate.listen(backlog); + } + + @Override + protected void accept(SocketImpl s) throws IOException { + delegate.accept(s); + } + + @Override + protected InputStream getInputStream() throws IOException { + return delegate.getInputStream(); + } + + @Override + protected OutputStream getOutputStream() throws IOException { + return delegate.getOutputStream(); + } + + @Override + protected int available() throws IOException { + return delegate.available(); + } + + @Override + protected void close() throws IOException { + delegate.close(); + } + + @Override + protected boolean supportsUrgentData() { + return delegate.supportsUrgentData(); + } + + @Override + protected void sendUrgentData(int data) throws IOException { + delegate.sendUrgentData(data); + } + + @Override + protected Set> supportedOptions() { + return delegate.supportedOptions(); + } + + @Override + protected void setOption(SocketOption opt, T value) throws IOException { + delegate.setOption(opt, value); + } + + @Override + protected T getOption(SocketOption opt) throws IOException { + return delegate.getOption(opt); + } + + @Override + public void setOption(int optID, Object value) throws SocketException { + delegate.setOption(optID, value); + } + + @Override + public Object getOption(int optID) throws SocketException { + return delegate.getOption(optID); + } + + @Override + protected void shutdownInput() throws IOException { + delegate.shutdownInput(); + } + + @Override + protected void shutdownOutput() throws IOException { + delegate.shutdownOutput(); + } +} diff --git a/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java b/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java index c33532498b6..6bee42f6b63 100644 --- a/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java +++ b/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,14 +34,13 @@ import java.util.Set; /** * Basic SocketImpl that relies on the internal HTTP protocol handler - * implementation to perform the HTTP tunneling and authentication. The - * sockets impl is swapped out and replaced with the socket from the HTTP - * handler after the tunnel is successfully setup. + * implementation to perform the HTTP tunneling and authentication. Once + * connected, all socket operations delegate to a platform SocketImpl. * * @since 1.8 */ -/*package*/ class HttpConnectSocketImpl extends PlainSocketImpl { +/*package*/ class HttpConnectSocketImpl extends DelegatingSocketImpl { private static final String httpURLClazzStr = "sun.net.www.protocol.http.HttpURLConnection"; @@ -76,12 +75,8 @@ import java.util.Set; } } - HttpConnectSocketImpl(String server, int port) { - this.server = server; - this.port = port; - } - - HttpConnectSocketImpl(Proxy proxy) { + HttpConnectSocketImpl(Proxy proxy, SocketImpl delegate) { + super(delegate); SocketAddress a = proxy.address(); if ( !(a instanceof InetSocketAddress) ) throw new IllegalArgumentException("Unsupported address type"); @@ -91,6 +86,27 @@ import java.util.Set; port = ad.getPort(); } + @Override + protected void connect(String host, int port) throws IOException { + connect(new InetSocketAddress(host, port), 0); + } + + @Override + protected void connect(InetAddress address, int port) throws IOException { + connect(new InetSocketAddress(address, port), 0); + } + + @Override + void setSocket(Socket socket) { + delegate.socket = socket; + super.setSocket(socket); + } + + @Override + void setServerSocket(ServerSocket socket) { + throw new InternalError("should not get here"); + } + @Override protected void connect(SocketAddress endpoint, int timeout) throws IOException @@ -98,14 +114,17 @@ import java.util.Set; if (endpoint == null || !(endpoint instanceof InetSocketAddress)) throw new IllegalArgumentException("Unsupported address type"); final InetSocketAddress epoint = (InetSocketAddress)endpoint; - final String destHost = epoint.isUnresolved() ? epoint.getHostName() - : epoint.getAddress().getHostAddress(); + String destHost = epoint.isUnresolved() ? epoint.getHostName() + : epoint.getAddress().getHostAddress(); final int destPort = epoint.getPort(); SecurityManager security = System.getSecurityManager(); if (security != null) security.checkConnect(destHost, destPort); + if (destHost.contains(":")) + destHost = "[" + destHost + "]"; + // Connect to the HTTP proxy server String urlString = "http://" + destHost + ":" + destPort; Socket httpSocket = privilegedDoTunnel(urlString, timeout); @@ -117,21 +136,37 @@ import java.util.Set; close(); // update the Sockets impl to the impl from the http Socket - AbstractPlainSocketImpl psi = (AbstractPlainSocketImpl) httpSocket.impl; - this.getSocket().impl = psi; + SocketImpl si = httpSocket.impl; + getSocket().setImpl(si); // best effort is made to try and reset options previously set Set> options = optionsMap.entrySet(); try { for(Map.Entry entry : options) { - psi.setOption(entry.getKey(), entry.getValue()); + si.setOption(entry.getKey(), entry.getValue()); } } catch (IOException x) { /* gulp! */ } } + + @Override + protected void listen(int backlog) { + throw new InternalError("should not get here"); + } + + @Override + protected void accept(SocketImpl s) { + throw new InternalError("should not get here"); + } + + @Override + void reset() { + throw new InternalError("should not get here"); + } + @Override public void setOption(int opt, Object val) throws SocketException { - super.setOption(opt, val); + delegate.setOption(opt, val); if (external_address != null) return; // we're connected, just return @@ -163,7 +198,10 @@ import java.util.Set; URL destURL = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) destURL.openConnection(proxy); conn.setConnectTimeout(connectTimeout); - conn.setReadTimeout(this.timeout); + int timeout = (int) getOption(SocketOptions.SO_TIMEOUT); + if (timeout > 0) { + conn.setReadTimeout(timeout); + } conn.connect(); doTunneling(conn); try { @@ -174,10 +212,14 @@ import java.util.Set; } } - private void doTunneling(HttpURLConnection conn) { + private void doTunneling(HttpURLConnection conn) throws IOException { try { doTunneling.invoke(conn); } catch (ReflectiveOperationException x) { + Throwable cause = x.getCause(); + if (cause instanceof IOException) { + throw (IOException) cause; + } throw new InternalError("Should not reach here", x); } } @@ -187,7 +229,7 @@ import java.util.Set; if (external_address != null) return external_address.getAddress(); else - return super.getInetAddress(); + return delegate.getInetAddress(); } @Override @@ -195,6 +237,6 @@ import java.util.Set; if (external_address != null) return external_address.getPort(); else - return super.getPort(); + return delegate.getPort(); } } diff --git a/src/java.base/share/classes/java/net/JarURLConnection.java b/src/java.base/share/classes/java/net/JarURLConnection.java index 4c7e0ab6f94..76d24ae0677 100644 --- a/src/java.base/share/classes/java/net/JarURLConnection.java +++ b/src/java.base/share/classes/java/net/JarURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -293,7 +293,7 @@ public abstract class JarURLConnection extends URLConnection { } /** - * Return the Certificate object for this connection if the URL + * Returns the Certificate objects for this connection if the URL * for it points to a JAR file entry, null otherwise. This method * can only be called once * the connection has been completely verified by reading diff --git a/src/java.base/share/classes/java/net/MulticastSocket.java b/src/java.base/share/classes/java/net/MulticastSocket.java index a07bf32edd5..5cb0b1c6a34 100644 --- a/src/java.base/share/classes/java/net/MulticastSocket.java +++ b/src/java.base/share/classes/java/net/MulticastSocket.java @@ -52,8 +52,9 @@ import java.util.Set; * InetAddress group = InetAddress.getByName("228.5.6.7"); * MulticastSocket s = new MulticastSocket(6789); * s.joinGroup(group); - * DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), - * group, 6789); + * byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8); + * DatagramPacket hi = new DatagramPacket(msgBytes, msgBytes.length, + * group, 6789); * s.send(hi); * // get their responses! * byte[] buf = new byte[1000]; diff --git a/src/java.base/share/classes/java/net/NetPermission.java b/src/java.base/share/classes/java/net/NetPermission.java index 0df2c91a299..e100473807c 100644 --- a/src/java.base/share/classes/java/net/NetPermission.java +++ b/src/java.base/share/classes/java/net/NetPermission.java @@ -43,7 +43,7 @@ import java.util.StringTokenizer; * signify a wildcard match. For example: "foo.*" and "*" signify a wildcard * match, while "*foo" and "a*b" do not. *

    - * The following table lists all the possible NetPermission target names, + * The following table lists the standard NetPermission target names, * and for each provides a description of what the permission allows * and a discussion of the risks of granting code the permission. * @@ -158,6 +158,10 @@ import java.util.StringTokenizer; * * + * @implNote + * Implementations may define additional target names, but should use naming + * conventions such as reverse domain name notation to avoid name clashes. + * * @see java.security.BasicPermission * @see java.security.Permission * @see java.security.Permissions diff --git a/src/java.base/share/classes/java/net/ServerSocket.java b/src/java.base/share/classes/java/net/ServerSocket.java index a88b362c894..40f2199476c 100644 --- a/src/java.base/share/classes/java/net/ServerSocket.java +++ b/src/java.base/share/classes/java/net/ServerSocket.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,6 @@ package java.net; -import jdk.internal.access.JavaNetSocketAccess; -import jdk.internal.access.SharedSecrets; - import java.io.FileDescriptor; import java.io.IOException; import java.lang.reflect.Constructor; @@ -38,6 +35,10 @@ import java.security.PrivilegedExceptionAction; import java.util.Set; import java.util.Collections; +import jdk.internal.access.JavaNetSocketAccess; +import jdk.internal.access.SharedSecrets; +import sun.net.PlatformSocketImpl; + /** * This class implements server sockets. A server socket waits for * requests to come in over the network. It performs some operation @@ -290,13 +291,12 @@ class ServerSocket implements java.io.Closeable { } private void setImpl() { + SocketImplFactory factory = ServerSocket.factory; if (factory != null) { impl = factory.createSocketImpl(); checkOldImpl(); } else { - // No need to do a checkOldImpl() here, we know it's an up to date - // SocketImpl! - impl = new SocksSocketImpl(); + impl = SocketImpl.createPlatformSocketImpl(true); } if (impl != null) impl.setServerSocket(this); @@ -542,38 +542,134 @@ class ServerSocket implements java.io.Closeable { * @spec JSR-51 */ protected final void implAccept(Socket s) throws IOException { - SocketImpl si = null; - try { - if (s.impl == null) - s.setImpl(); - else { - s.impl.reset(); - } - si = s.impl; - s.impl = null; - si.address = new InetAddress(); - si.fd = new FileDescriptor(); - getImpl().accept(si); - SocketCleanable.register(si.fd); // raw fd has been set + SocketImpl si = s.impl; - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkAccept(si.getInetAddress().getHostAddress(), - si.getPort()); + // Socket has no SocketImpl + if (si == null) { + si = implAccept(); + s.setImpl(si); + s.postAccept(); + return; + } + + // Socket has a SOCKS or HTTP SocketImpl, need delegate + if (si instanceof DelegatingSocketImpl) { + si = ((DelegatingSocketImpl) si).delegate(); + assert si instanceof PlatformSocketImpl; + } + + // Accept connection with a platform or custom SocketImpl. + // For the platform SocketImpl case: + // - the connection is accepted with a new SocketImpl + // - the SO_TIMEOUT socket option is copied to the new SocketImpl + // - the Socket is connected to the new SocketImpl + // - the existing/old SocketImpl is closed + // For the custom SocketImpl case, the connection is accepted with the + // existing custom SocketImpl. + ensureCompatible(si); + if (impl instanceof PlatformSocketImpl) { + SocketImpl psi = platformImplAccept(); + si.copyOptionsTo(psi); + s.setImpl(psi); + si.closeQuietly(); + } else { + s.impl = null; // temporarily break connection to impl + try { + customImplAccept(si); + } finally { + s.impl = si; // restore connection to impl } - } catch (IOException e) { - if (si != null) - si.reset(); - s.impl = si; - throw e; - } catch (SecurityException e) { - if (si != null) - si.reset(); - s.impl = si; + } + s.postAccept(); + } + + /** + * Accepts a connection with a new SocketImpl. + * @return the new SocketImpl + */ + private SocketImpl implAccept() throws IOException { + if (impl instanceof PlatformSocketImpl) { + return platformImplAccept(); + } else { + // custom server SocketImpl, client SocketImplFactory must be set + SocketImplFactory factory = Socket.socketImplFactory(); + if (factory == null) { + throw new IOException("An instance of " + impl.getClass() + + " cannot accept connection with 'null' SocketImpl:" + + " client socket implementation factory not set"); + } + SocketImpl si = factory.createSocketImpl(); + customImplAccept(si); + return si; + } + } + + /** + * Accepts a connection with a new platform SocketImpl. + * @return the new platform SocketImpl + */ + private SocketImpl platformImplAccept() throws IOException { + assert impl instanceof PlatformSocketImpl; + + // create a new platform SocketImpl and accept the connection + SocketImpl psi = SocketImpl.createPlatformSocketImpl(false); + implAccept(psi); + return psi; + } + + /** + * Accepts a new connection with the given custom SocketImpl. + */ + private void customImplAccept(SocketImpl si) throws IOException { + assert !(impl instanceof PlatformSocketImpl) + && !(si instanceof PlatformSocketImpl); + + si.reset(); + try { + // custom SocketImpl may expect fd/address objects to be created + si.fd = new FileDescriptor(); + si.address = new InetAddress(); + implAccept(si); + } catch (Exception e) { + si.reset(); throw e; } - s.impl = si; - s.postAccept(); + } + + /** + * Accepts a new connection so that the given SocketImpl is connected to + * the peer. The SocketImpl and connection are closed if the connection is + * denied by the security manager. + * @throws IOException if an I/O error occurs + * @throws SecurityException if the security manager's checkAccept method fails + */ + private void implAccept(SocketImpl si) throws IOException { + assert !(si instanceof DelegatingSocketImpl); + + // accept a connection + impl.accept(si); + + // check permission, close SocketImpl/connection if denied + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + try { + sm.checkAccept(si.getInetAddress().getHostAddress(), si.getPort()); + } catch (SecurityException se) { + si.close(); + throw se; + } + } + } + + /** + * Throws IOException if the server SocketImpl and the given client + * SocketImpl are not both platform or custom SocketImpls. + */ + private void ensureCompatible(SocketImpl si) throws IOException { + if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) { + throw new IOException("An instance of " + impl.getClass() + + " cannot accept a connection with an instance of " + si.getClass()); + } } /** @@ -778,7 +874,7 @@ class ServerSocket implements java.io.Closeable { /** * The factory for all server sockets. */ - private static SocketImplFactory factory = null; + private static volatile SocketImplFactory factory; /** * Sets the server socket implementation factory for the diff --git a/src/java.base/share/classes/java/net/Socket.java b/src/java.base/share/classes/java/net/Socket.java index 9dbe5140788..53d9131e8ce 100644 --- a/src/java.base/share/classes/java/net/Socket.java +++ b/src/java.base/share/classes/java/net/Socket.java @@ -28,9 +28,10 @@ package java.net; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; import java.nio.channels.SocketChannel; import java.security.AccessController; -import java.security.PrivilegedExceptionAction; import java.security.PrivilegedAction; import java.util.Set; import java.util.Collections; @@ -75,6 +76,22 @@ class Socket implements java.io.Closeable { */ private boolean oldImpl = false; + /** + * Socket input/output streams + */ + private volatile InputStream in; + private volatile OutputStream out; + private static final VarHandle IN, OUT; + static { + try { + MethodHandles.Lookup l = MethodHandles.lookup(); + IN = l.findVarHandle(Socket.class, "in", InputStream.class); + OUT = l.findVarHandle(Socket.class, "out", OutputStream.class); + } catch (Exception e) { + throw new InternalError(e); + } + } + /** * Creates an unconnected socket, with the * system-default type of SocketImpl. @@ -137,16 +154,22 @@ class Socket implements java.io.Closeable { security.checkConnect(epoint.getAddress().getHostAddress(), epoint.getPort()); } - impl = type == Proxy.Type.SOCKS ? new SocksSocketImpl(p) - : new HttpConnectSocketImpl(p); + + // create a SOCKS or HTTP SocketImpl that delegates to a platform SocketImpl + SocketImpl delegate = SocketImpl.createPlatformSocketImpl(false); + impl = (type == Proxy.Type.SOCKS) ? new SocksSocketImpl(p, delegate) + : new HttpConnectSocketImpl(p, delegate); impl.setSocket(this); } else { if (p == Proxy.NO_PROXY) { + // create a platform or custom SocketImpl for the DIRECT case + SocketImplFactory factory = Socket.factory; if (factory == null) { - impl = new PlainSocketImpl(); - impl.setSocket(this); - } else - setImpl(); + impl = SocketImpl.createPlatformSocketImpl(false); + } else { + impl = factory.createSocketImpl(); + } + impl.setSocket(this); } else throw new IllegalArgumentException("Invalid Proxy"); } @@ -491,24 +514,29 @@ class Socket implements java.io.Closeable { }); } + void setImpl(SocketImpl si) { + impl = si; + impl.setSocket(this); + } + /** * Sets impl to the system-default type of SocketImpl. * @since 1.4 */ void setImpl() { + SocketImplFactory factory = Socket.factory; if (factory != null) { impl = factory.createSocketImpl(); checkOldImpl(); } else { - // No need to do a checkOldImpl() here, we know it's an up to date - // SocketImpl! - impl = new SocksSocketImpl(); + // create a SOCKS SocketImpl that delegates to a platform SocketImpl + SocketImpl delegate = SocketImpl.createPlatformSocketImpl(false); + impl = new SocksSocketImpl(delegate); } if (impl != null) impl.setSocket(this); } - /** * Get the {@code SocketImpl} attached to this socket, creating * it if necessary. @@ -907,18 +935,49 @@ class Socket implements java.io.Closeable { throw new SocketException("Socket is not connected"); if (isInputShutdown()) throw new SocketException("Socket input is shutdown"); - InputStream is = null; - try { - is = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public InputStream run() throws IOException { - return impl.getInputStream(); - } - }); - } catch (java.security.PrivilegedActionException e) { - throw (IOException) e.getException(); + InputStream in = this.in; + if (in == null) { + // wrap the input stream so that the close method closes this socket + in = new SocketInputStream(this, impl.getInputStream()); + if (!IN.compareAndSet(this, null, in)) { + in = this.in; + } + } + return in; + } + + /** + * An InputStream that delegates read/available operations to an underlying + * input stream. The close method is overridden to close the Socket. + * + * This class is instrumented by Java Flight Recorder (JFR) to get socket + * I/O events. + */ + private static class SocketInputStream extends InputStream { + private final Socket parent; + private final InputStream in; + SocketInputStream(Socket parent, InputStream in) { + this.parent = parent; + this.in = in; + } + @Override + public int read() throws IOException { + byte[] a = new byte[1]; + int n = read(a, 0, 1); + return (n > 0) ? (a[0] & 0xff) : -1; + } + @Override + public int read(byte b[], int off, int len) throws IOException { + return in.read(b, off, len); + } + @Override + public int available() throws IOException { + return in.available(); + } + @Override + public void close() throws IOException { + parent.close(); } - return is; } /** @@ -946,18 +1005,44 @@ class Socket implements java.io.Closeable { throw new SocketException("Socket is not connected"); if (isOutputShutdown()) throw new SocketException("Socket output is shutdown"); - OutputStream os = null; - try { - os = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public OutputStream run() throws IOException { - return impl.getOutputStream(); - } - }); - } catch (java.security.PrivilegedActionException e) { - throw (IOException) e.getException(); + OutputStream out = this.out; + if (out == null) { + // wrap the output stream so that the close method closes this socket + out = new SocketOutputStream(this, impl.getOutputStream()); + if (!OUT.compareAndSet(this, null, out)) { + out = this.out; + } + } + return out; + } + + /** + * An OutputStream that delegates write operations to an underlying output + * stream. The close method is overridden to close the Socket. + * + * This class is instrumented by Java Flight Recorder (JFR) to get socket + * I/O events. + */ + private static class SocketOutputStream extends OutputStream { + private final Socket parent; + private final OutputStream out; + SocketOutputStream(Socket parent, OutputStream out) { + this.parent = parent; + this.out = out; + } + @Override + public void write(int b) throws IOException { + byte[] a = new byte[] { (byte) b }; + write(a, 0, 1); + } + @Override + public void write(byte b[], int off, int len) throws IOException { + out.write(b, off, len); + } + @Override + public void close() throws IOException { + parent.close(); } - return os; } /** @@ -1644,7 +1729,11 @@ class Socket implements java.io.Closeable { /** * The factory for all client sockets. */ - private static SocketImplFactory factory = null; + private static volatile SocketImplFactory factory; + + static SocketImplFactory socketImplFactory() { + return factory; + } /** * Sets the client socket implementation factory for the diff --git a/src/java.base/share/classes/java/net/SocketImpl.java b/src/java.base/share/classes/java/net/SocketImpl.java index 1c2060c7f15..a1a0e18e6e3 100644 --- a/src/java.base/share/classes/java/net/SocketImpl.java +++ b/src/java.base/share/classes/java/net/SocketImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,8 @@ import java.io.OutputStream; import java.io.FileDescriptor; import java.util.Set; +import sun.net.PlatformSocketImpl; + /** * The abstract class {@code SocketImpl} is a common superclass * of all classes that actually implement sockets. It is used to @@ -43,6 +45,15 @@ import java.util.Set; * @since 1.0 */ public abstract class SocketImpl implements SocketOptions { + + /** + * Creates an instance of platform's SocketImpl + */ + @SuppressWarnings("unchecked") + static S createPlatformSocketImpl(boolean server) { + return (S) new PlainSocketImpl(); + } + /** * The actual Socket object. */ @@ -177,6 +188,15 @@ public abstract class SocketImpl implements SocketOptions { */ protected abstract void close() throws IOException; + /** + * Closes this socket, ignoring any IOException that is thrown by close. + */ + void closeQuietly() { + try { + close(); + } catch (IOException ignore) { } + } + /** * Places the input stream for this socket at "end of stream". * Any data sent to this socket is acknowledged and then @@ -306,7 +326,8 @@ public abstract class SocketImpl implements SocketOptions { ",port=" + getPort() + ",localport=" + getLocalPort() + "]"; } - void reset() throws IOException { + void reset() { + fd = null; address = null; port = 0; localport = 0; @@ -443,6 +464,19 @@ public abstract class SocketImpl implements SocketOptions { } } + /** + * Attempts to copy socket options from this SocketImpl to a target SocketImpl. + * At this time, only the SO_TIMEOUT make sense to copy. + */ + void copyOptionsTo(SocketImpl target) { + try { + Object timeout = getOption(SocketOptions.SO_TIMEOUT); + if (timeout instanceof Integer) { + target.setOption(SocketOptions.SO_TIMEOUT, timeout); + } + } catch (IOException ignore) { } + } + private static final Set> socketOptions; private static final Set> serverSocketOptions; diff --git a/src/java.base/share/classes/java/net/SocksSocketImpl.java b/src/java.base/share/classes/java/net/SocksSocketImpl.java index 26f282ffb28..7734c5a8234 100644 --- a/src/java.base/share/classes/java/net/SocksSocketImpl.java +++ b/src/java.base/share/classes/java/net/SocksSocketImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ * questions. */ package java.net; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -36,11 +37,9 @@ import sun.net.www.ParseUtil; /** * SOCKS (V4 & V5) TCP socket implementation (RFC 1928). - * This is a subclass of PlainSocketImpl. - * Note this class should NOT be public. */ -class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { +class SocksSocketImpl extends DelegatingSocketImpl implements SocksConsts { private String server = null; private int serverPort = DEFAULT_PORT; private InetSocketAddress external_address; @@ -49,11 +48,12 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { private InputStream cmdIn = null; private OutputStream cmdOut = null; - SocksSocketImpl() { - // Nothing needed + SocksSocketImpl(SocketImpl delegate) { + super(delegate); } - SocksSocketImpl(Proxy proxy) { + SocksSocketImpl(Proxy proxy, SocketImpl delegate) { + super(delegate); SocketAddress a = proxy.address(); if (a instanceof InetSocketAddress) { InetSocketAddress ad = (InetSocketAddress) a; @@ -75,7 +75,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { private synchronized void privilegedConnect(final String host, final int port, final int timeout) - throws IOException + throws IOException { try { AccessController.doPrivileged( @@ -94,7 +94,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { private void superConnectServer(String host, int port, int timeout) throws IOException { - super.connect(new InetSocketAddress(host, port), timeout); + delegate.connect(new InetSocketAddress(host, port), timeout); } private static int remainingMillis(long deadlineMillis) throws IOException { @@ -111,16 +111,23 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { private int readSocksReply(InputStream in, byte[] data, long deadlineMillis) throws IOException { int len = data.length; int received = 0; - while (received < len) { - int count; - try { - count = ((SocketInputStream)in).read(data, received, len - received, remainingMillis(deadlineMillis)); - } catch (SocketTimeoutException e) { - throw new SocketTimeoutException("Connect timed out"); + int originalTimeout = (int) getOption(SocketOptions.SO_TIMEOUT); + try { + while (received < len) { + int count; + int remaining = remainingMillis(deadlineMillis); + setOption(SocketOptions.SO_TIMEOUT, remaining); + try { + count = in.read(data, received, len - received); + } catch (SocketTimeoutException e) { + throw new SocketTimeoutException("Connect timed out"); + } + if (count < 0) + throw new SocketException("Malformed reply from SOCKS server"); + received += count; } - if (count < 0) - throw new SocketException("Malformed reply from SOCKS server"); - received += count; + } finally { + setOption(SocketOptions.SO_TIMEOUT, originalTimeout); } return received; } @@ -239,6 +246,27 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { } } + @Override + protected void connect(String host, int port) throws IOException { + connect(new InetSocketAddress(host, port), 0); + } + + @Override + protected void connect(InetAddress address, int port) throws IOException { + connect(new InetSocketAddress(address, port), 0); + } + + @Override + void setSocket(Socket soc) { + delegate.socket = soc; + super.setSocket(soc); + } + + @Override + void setServerSocket(ServerSocket soc) { + throw new InternalError("should not get here"); + } + /** * Connects the Socks Socket to the specified endpoint. It will first * connect to the SOCKS proxy and negotiate the access. If the proxy @@ -290,7 +318,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { /* * No default proxySelector --> direct connection */ - super.connect(epoint, remainingMillis(deadlineMillis)); + delegate.connect(epoint, remainingMillis(deadlineMillis)); return; } URI uri; @@ -313,13 +341,13 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { java.util.Iterator iProxy = null; iProxy = sel.select(uri).iterator(); if (iProxy == null || !(iProxy.hasNext())) { - super.connect(epoint, remainingMillis(deadlineMillis)); + delegate.connect(epoint, remainingMillis(deadlineMillis)); return; } while (iProxy.hasNext()) { p = iProxy.next(); if (p == null || p.type() != Proxy.Type.SOCKS) { - super.connect(epoint, remainingMillis(deadlineMillis)); + delegate.connect(epoint, remainingMillis(deadlineMillis)); return; } @@ -509,7 +537,15 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { external_address = epoint; } + @Override + protected void listen(int backlog) { + throw new InternalError("should not get here"); + } + @Override + protected void accept(SocketImpl s) { + throw new InternalError("should not get here"); + } /** * Returns the value of this socket's {@code address} field. @@ -522,7 +558,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { if (external_address != null) return external_address.getAddress(); else - return super.getInetAddress(); + return delegate.getInetAddress(); } /** @@ -536,7 +572,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { if (external_address != null) return external_address.getPort(); else - return super.getPort(); + return delegate.getPort(); } @Override @@ -544,10 +580,15 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { if (cmdsock != null) cmdsock.close(); cmdsock = null; - super.close(); + delegate.close(); } private String getUserName() { return StaticProperty.userName(); } + + @Override + void reset() { + throw new InternalError("should not get here"); + } } diff --git a/src/java.base/share/classes/java/net/doc-files/net-properties.html b/src/java.base/share/classes/java/net/doc-files/net-properties.html index 8f18ca5672f..7b5aa27d3ea 100644 --- a/src/java.base/share/classes/java/net/doc-files/net-properties.html +++ b/src/java.base/share/classes/java/net/doc-files/net-properties.html @@ -1,6 +1,6 @@ ")); + tree.add(new RawHtml("")); addJQueryFile(tree, DocPaths.JQUERY_JS_3_3); addJQueryFile(tree, DocPaths.JQUERY_MIGRATE); addJQueryFile(tree, DocPaths.JQUERY_JS); } for (Script script : scripts) { - tree.addContent(script.asContent()); + tree.add(script.asContent()); } } private void addJQueryFile(HtmlTree tree, DocPath filePath) { DocPath jqueryFile = pathToRoot.resolve(DocPaths.JQUERY_FILES.resolve(filePath)); - tree.addContent(HtmlTree.SCRIPT(jqueryFile.getPath())); + tree.add(HtmlTree.SCRIPT(jqueryFile.getPath())); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTag.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTag.java index c80e09954f4..b5ccb16a039 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTag.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,16 +44,13 @@ public enum HtmlTag { BODY(BlockType.OTHER, EndTag.END), BR(BlockType.INLINE, EndTag.NOEND), CAPTION, - CENTER(HtmlVersion.HTML4), CODE(BlockType.INLINE, EndTag.END), DD, - DIR(HtmlVersion.HTML4), DIV, DL, DT, EM(BlockType.INLINE, EndTag.END), - FONT(HtmlVersion.HTML4, BlockType.INLINE, EndTag.END), - FOOTER(HtmlVersion.HTML5), + FOOTER, H1, H2, H3, @@ -61,7 +58,7 @@ public enum HtmlTag { H5, H6, HEAD(BlockType.OTHER, EndTag.END), - HEADER(HtmlVersion.HTML5), + HEADER, HR(BlockType.BLOCK, EndTag.NOEND), HTML(BlockType.OTHER, EndTag.END), I(BlockType.INLINE, EndTag.END), @@ -72,33 +69,32 @@ public enum HtmlTag { LI, LISTING, LINK(BlockType.OTHER, EndTag.NOEND), - MAIN(HtmlVersion.HTML5), + MAIN, MENU, META(BlockType.OTHER, EndTag.NOEND), - NAV(HtmlVersion.HTML5), + NAV, NOSCRIPT(BlockType.OTHER, EndTag.END), OL, P, PRE, SCRIPT(BlockType.OTHER, EndTag.END), - SECTION(HtmlVersion.HTML5), + SECTION, SMALL(BlockType.INLINE, EndTag.END), SPAN(BlockType.INLINE, EndTag.END), STRONG(BlockType.INLINE, EndTag.END), SUB(BlockType.INLINE, EndTag.END), TABLE, TBODY, + THEAD, TD, TH, TITLE(BlockType.OTHER, EndTag.END), TR, - TT(HtmlVersion.HTML4, BlockType.INLINE, EndTag.END), UL; public final BlockType blockType; public final EndTag endTag; public final String value; - public final HtmlVersion htmlVersion; /** * Enum representing the type of HTML element. @@ -118,19 +114,10 @@ public enum HtmlTag { } HtmlTag() { - this(HtmlVersion.ALL, BlockType.BLOCK, EndTag.END); + this(BlockType.BLOCK, EndTag.END); } - HtmlTag(HtmlVersion htmlVersion) { - this(htmlVersion, BlockType.BLOCK, EndTag.END); - } - - HtmlTag(BlockType blockType, EndTag endTag ) { - this(HtmlVersion.ALL, blockType, endTag); - } - - HtmlTag(HtmlVersion htmlVersion, BlockType blockType, EndTag endTag ) { - this.htmlVersion = htmlVersion; + HtmlTag(BlockType blockType, EndTag endTag) { this.blockType = blockType; this.endTag = endTag; this.value = Utils.toLowerCase(name()); @@ -146,16 +133,6 @@ public enum HtmlTag { return (endTag == EndTag.END); } - /** - * Returns true if the tag is allowed in the output HTML version of this javadoc run. - * - * @param htmlVer the output HTML version for this javadoc run - * @return true if the tag is allowed - */ - public boolean allowTag(HtmlVersion htmlVer) { - return (this.htmlVersion == HtmlVersion.ALL || this.htmlVersion == htmlVer); - } - public String toString() { return value; } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java index 3a3375046b0..47ddf05b630 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,7 +75,7 @@ public class HtmlTree extends Content { public HtmlTree(HtmlTag tag, Content... contents) { this(tag); for (Content c: contents) - addContent(c); + add(c); } /** @@ -87,7 +87,7 @@ public class HtmlTree extends Content { public HtmlTree(HtmlTag tag, List contents) { this(tag); for (Content c: contents) - addContent(c); + add(c); } /** @@ -97,7 +97,7 @@ public class HtmlTree extends Content { * @param attrValue value of the attribute * @return this object */ - public HtmlTree addAttr(HtmlAttr attrName, String attrValue) { + public HtmlTree put(HtmlAttr attrName, String attrValue) { if (attrs.isEmpty()) attrs = new LinkedHashMap<>(3); attrs.put(nullCheck(attrName), escapeHtmlChars(attrValue)); @@ -112,7 +112,7 @@ public class HtmlTree extends Content { * @return this object */ public HtmlTree setTitle(Content body) { - addAttr(HtmlAttr.TITLE, stripHtml(body)); + put(HtmlAttr.TITLE, stripHtml(body)); return this; } @@ -123,7 +123,7 @@ public class HtmlTree extends Content { * @return this object */ public HtmlTree setRole(Role role) { - addAttr(HtmlAttr.ROLE, role.toString()); + put(HtmlAttr.ROLE, role.toString()); return this; } @@ -134,7 +134,7 @@ public class HtmlTree extends Content { * @return this object */ public HtmlTree setStyle(HtmlStyle style) { - addAttr(HtmlAttr.CLASS, style.toString()); + put(HtmlAttr.CLASS, style.toString()); return this; } @@ -144,10 +144,10 @@ public class HtmlTree extends Content { * @param tagContent tag content to be added */ @Override - public void addContent(Content tagContent) { + public void add(Content tagContent) { if (tagContent instanceof ContentBuilder) { for (Content c: ((ContentBuilder)tagContent).contents) { - addContent(c); + add(c); } } else if (tagContent == HtmlTree.EMPTY || tagContent.isValid()) { @@ -165,16 +165,16 @@ public class HtmlTree extends Content { * @param stringContent string content that needs to be added */ @Override - public void addContent(CharSequence stringContent) { + public void add(CharSequence stringContent) { if (!content.isEmpty()) { Content lastContent = content.get(content.size() - 1); if (lastContent instanceof StringContent) - lastContent.addContent(stringContent); + lastContent.add(stringContent); else - addContent(new StringContent(stringContent)); + add(new StringContent(stringContent)); } else - addContent(new StringContent(stringContent)); + add(new StringContent(stringContent)); } /** @@ -294,7 +294,7 @@ public class HtmlTree extends Content { */ public static HtmlTree A(String ref, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.A, nullCheck(body)); - htmltree.addAttr(HtmlAttr.HREF, encodeURL(ref)); + htmltree.put(HtmlAttr.HREF, encodeURL(ref)); return htmltree; } @@ -307,8 +307,8 @@ public class HtmlTree extends Content { */ public static HtmlTree A_ID(String id, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.A); - htmltree.addAttr(HtmlAttr.ID, nullCheck(id)); - htmltree.addContent(nullCheck(body)); + htmltree.put(HtmlAttr.ID, nullCheck(id)); + htmltree.add(nullCheck(body)); return htmltree; } @@ -497,7 +497,7 @@ public class HtmlTree extends Content { */ public static HtmlTree HTML(String lang, Content head, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body)); - htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang)); + htmltree.put(HtmlAttr.LANG, nullCheck(lang)); return htmltree; } @@ -511,9 +511,9 @@ public class HtmlTree extends Content { */ public static HtmlTree IFRAME(String src, String name, String title) { HtmlTree htmltree = new HtmlTree(HtmlTag.IFRAME); - htmltree.addAttr(HtmlAttr.SRC, nullCheck(src)); - htmltree.addAttr(HtmlAttr.NAME, nullCheck(name)); - htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title)); + htmltree.put(HtmlAttr.SRC, nullCheck(src)); + htmltree.put(HtmlAttr.NAME, nullCheck(name)); + htmltree.put(HtmlAttr.TITLE, nullCheck(title)); return htmltree; } @@ -527,10 +527,10 @@ public class HtmlTree extends Content { */ public static HtmlTree INPUT(String type, String id, String value) { HtmlTree htmltree = new HtmlTree(HtmlTag.INPUT); - htmltree.addAttr(HtmlAttr.TYPE, nullCheck(type)); - htmltree.addAttr(HtmlAttr.ID, nullCheck(id)); - htmltree.addAttr(HtmlAttr.VALUE, nullCheck(value)); - htmltree.addAttr(HtmlAttr.DISABLED, "disabled"); + htmltree.put(HtmlAttr.TYPE, nullCheck(type)); + htmltree.put(HtmlAttr.ID, nullCheck(id)); + htmltree.put(HtmlAttr.VALUE, nullCheck(value)); + htmltree.put(HtmlAttr.DISABLED, "disabled"); return htmltree; } @@ -543,7 +543,7 @@ public class HtmlTree extends Content { */ public static HtmlTree LABEL(String forLabel, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.LABEL, nullCheck(body)); - htmltree.addAttr(HtmlAttr.FOR, nullCheck(forLabel)); + htmltree.put(HtmlAttr.FOR, nullCheck(forLabel)); return htmltree; } @@ -582,10 +582,10 @@ public class HtmlTree extends Content { */ public static HtmlTree LINK(String rel, String type, String href, String title) { HtmlTree htmltree = new HtmlTree(HtmlTag.LINK); - htmltree.addAttr(HtmlAttr.REL, nullCheck(rel)); - htmltree.addAttr(HtmlAttr.TYPE, nullCheck(type)); - htmltree.addAttr(HtmlAttr.HREF, nullCheck(href)); - htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title)); + htmltree.put(HtmlAttr.REL, nullCheck(rel)); + htmltree.put(HtmlAttr.TYPE, nullCheck(type)); + htmltree.put(HtmlAttr.HREF, nullCheck(href)); + htmltree.put(HtmlAttr.TITLE, nullCheck(title)); return htmltree; } @@ -638,8 +638,8 @@ public class HtmlTree extends Content { public static HtmlTree META(String httpEquiv, String content, String charSet) { HtmlTree htmltree = new HtmlTree(HtmlTag.META); String contentCharset = content + "; charset=" + charSet; - htmltree.addAttr(HtmlAttr.HTTP_EQUIV, nullCheck(httpEquiv)); - htmltree.addAttr(HtmlAttr.CONTENT, contentCharset); + htmltree.put(HtmlAttr.HTTP_EQUIV, nullCheck(httpEquiv)); + htmltree.put(HtmlAttr.CONTENT, contentCharset); return htmltree; } @@ -652,8 +652,8 @@ public class HtmlTree extends Content { */ public static HtmlTree META(String name, String content) { HtmlTree htmltree = new HtmlTree(HtmlTag.META); - htmltree.addAttr(HtmlAttr.NAME, nullCheck(name)); - htmltree.addAttr(HtmlAttr.CONTENT, nullCheck(content)); + htmltree.put(HtmlAttr.NAME, nullCheck(name)); + htmltree.put(HtmlAttr.CONTENT, nullCheck(content)); return htmltree; } @@ -711,8 +711,8 @@ public class HtmlTree extends Content { */ public static HtmlTree SCRIPT(String src) { HtmlTree htmltree = new HtmlTree(HtmlTag.SCRIPT); - htmltree.addAttr(HtmlAttr.TYPE, "text/javascript"); - htmltree.addAttr(HtmlAttr.SRC, nullCheck(src)); + htmltree.put(HtmlAttr.TYPE, "text/javascript"); + htmltree.put(HtmlAttr.SRC, nullCheck(src)); return htmltree; } @@ -785,7 +785,7 @@ public class HtmlTree extends Content { */ public static HtmlTree SPAN(String id, HtmlStyle styleClass, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.SPAN, nullCheck(body)); - htmltree.addAttr(HtmlAttr.ID, nullCheck(id)); + htmltree.put(HtmlAttr.ID, nullCheck(id)); if (styleClass != null) htmltree.setStyle(styleClass); return htmltree; @@ -803,7 +803,7 @@ public class HtmlTree extends Content { HtmlTree htmltree = new HtmlTree(HtmlTag.TABLE, nullCheck(body)); if (styleClass != null) htmltree.setStyle(styleClass); - htmltree.addAttr(HtmlAttr.SUMMARY, nullCheck(summary)); + htmltree.put(HtmlAttr.SUMMARY, nullCheck(summary)); return htmltree; } @@ -858,7 +858,7 @@ public class HtmlTree extends Content { HtmlTree htmltree = new HtmlTree(HtmlTag.TH, nullCheck(body)); if (styleClass != null) htmltree.setStyle(styleClass); - htmltree.addAttr(HtmlAttr.SCOPE, nullCheck(scope)); + htmltree.put(HtmlAttr.SCOPE, nullCheck(scope)); return htmltree; } @@ -916,9 +916,9 @@ public class HtmlTree extends Content { */ public static HtmlTree UL(HtmlStyle styleClass, Content first, Content... more) { HtmlTree htmlTree = new HtmlTree(HtmlTag.UL); - htmlTree.addContent(nullCheck(first)); + htmlTree.add(nullCheck(first)); for (Content c : more) { - htmlTree.addContent(nullCheck(c)); + htmlTree.add(nullCheck(c)); } htmlTree.setStyle(nullCheck(styleClass)); return htmlTree; diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Links.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Links.java index fed52775cbf..cf2876e95c1 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Links.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Links.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,7 +62,6 @@ public class Links { /** * Creates an anchor of the form {@code }. - * In HTML4, a {@code name} attribute will be generated instead of an {@code id} attribute. * * @param name the value for the {@code id} or {@code name} attribute * @return a content tree for the anchor @@ -73,7 +72,6 @@ public class Links { /** * Creates an anchor of the form {@code }. - * In HTML4, a {@code name} attribute will be generated instead of an {@code id} attribute. * * @param sectionName the value for the {@code id} or {@code name} attribute * @return a content tree for the anchor @@ -84,7 +82,6 @@ public class Links { /** * Creates an anchor of the form {@code }. - * In HTML4, a {@code name} attribute will be generated instead of an {@code id} attribute. * * @param sectionName the first part of the value for the {@code id} or {@code name} attribute * @param name the second part of the value for the {@code id} or {@code name} attribute @@ -96,7 +93,6 @@ public class Links { /** * Creates an anchor of the form {@code content}. - * In HTML4, a {@code name} attribute will be generated instead of an {@code id} attribute. * * @param name the value for the {@code id} or {@code name} attribute * @param content the content that should be added to the anchor, @@ -237,10 +233,10 @@ public class Links { public Content createLink(DocLink link, Content label, String title, String target) { HtmlTree anchor = HtmlTree.A(link.relativizeAgainst(file).toString(), label); if (title != null && title.length() != 0) { - anchor.addAttr(HtmlAttr.TITLE, title); + anchor.put(HtmlAttr.TITLE, title); } if (target != null && target.length() != 0) { - anchor.addAttr(HtmlAttr.TARGET, target); + anchor.put(HtmlAttr.TARGET, target); } return anchor; } @@ -283,10 +279,10 @@ public class Links { } HtmlTree l = HtmlTree.A(link.relativizeAgainst(file).toString(), body); if (title != null && title.length() != 0) { - l.addAttr(HtmlAttr.TITLE, title); + l.put(HtmlAttr.TITLE, title); } if (target != null && target.length() != 0) { - l.addAttr(HtmlAttr.TARGET, target); + l.put(HtmlAttr.TARGET, target); } if (isExternal) { l.setStyle(HtmlStyle.externalLink); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Navigation.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Navigation.java index 56a2e16c446..7c7515c7b6c 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Navigation.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Navigation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,7 @@ import javax.lang.model.element.TypeElement; import jdk.javadoc.internal.doclets.formats.html.AbstractMemberWriter; import jdk.javadoc.internal.doclets.formats.html.Contents; import jdk.javadoc.internal.doclets.formats.html.HtmlConfiguration; +import jdk.javadoc.internal.doclets.formats.html.MarkerComments; import jdk.javadoc.internal.doclets.formats.html.SectionName; import jdk.javadoc.internal.doclets.toolkit.Content; import jdk.javadoc.internal.doclets.toolkit.builders.MemberSummaryBuilder; @@ -106,8 +107,8 @@ public class Navigation { } enum Position { - BOTTOM(HtmlConstants.START_OF_BOTTOM_NAVBAR, HtmlConstants.END_OF_BOTTOM_NAVBAR), - TOP(HtmlConstants.START_OF_TOP_NAVBAR, HtmlConstants.END_OF_TOP_NAVBAR); + BOTTOM(MarkerComments.START_OF_BOTTOM_NAVBAR, MarkerComments.END_OF_BOTTOM_NAVBAR), + TOP(MarkerComments.START_OF_TOP_NAVBAR, MarkerComments.END_OF_TOP_NAVBAR); final Content startOfNav; final Content endOfNav; @@ -428,8 +429,8 @@ public class Navigation { } if (!listContents.isEmpty()) { Content li = HtmlTree.LI(contents.summaryLabel); - li.addContent(Contents.SPACE); - tree.addContent(li); + li.add(Contents.SPACE); + tree.add(li); addListToNav(listContents, tree); } break; @@ -460,8 +461,8 @@ public class Navigation { } if (!listContents.isEmpty()) { Content li = HtmlTree.LI(contents.moduleSubNavLabel); - li.addContent(Contents.SPACE); - tree.addContent(li); + li.add(Contents.SPACE); + tree.add(li); addListToNav(listContents, tree); } break; @@ -664,8 +665,8 @@ public class Navigation { } if (!listContents.isEmpty()) { Content li = HtmlTree.LI(contents.detailLabel); - li.addContent(Contents.SPACE); - tree.addContent(li); + li.add(Contents.SPACE); + tree.add(li); addListToNav(listContents, tree); } break; @@ -793,37 +794,37 @@ public class Navigation { } private void addContentToTree(Content tree, Content content) { - tree.addContent(HtmlTree.LI(content)); + tree.add(HtmlTree.LI(content)); } private void addListToNav(List listContents, Content tree) { int count = 0; for (Content liContent : listContents) { if (count < listContents.size() - 1) { - liContent.addContent(Contents.SPACE); - liContent.addContent("|"); - liContent.addContent(Contents.SPACE); + liContent.add(Contents.SPACE); + liContent.add("|"); + liContent.add(Contents.SPACE); } - tree.addContent(liContent); + tree.add(liContent); count++; } } private void addActivePageLink(Content tree, Content label, boolean display) { if (display) { - tree.addContent(HtmlTree.LI(HtmlStyle.navBarCell1Rev, label)); + tree.add(HtmlTree.LI(HtmlStyle.navBarCell1Rev, label)); } } private void addPageLabel(Content tree, Content label, boolean display) { if (display) { - tree.addContent(HtmlTree.LI(label)); + tree.add(HtmlTree.LI(label)); } } private void addOverviewLink(Content tree) { if (configuration.createoverview) { - tree.addContent(HtmlTree.LI(links.createLink(pathToRoot.resolve(DocPaths.overviewSummary(configuration.frames)), + tree.add(HtmlTree.LI(links.createLink(pathToRoot.resolve(DocPaths.overviewSummary(configuration.frames)), contents.overviewLabel, "", ""))); } } @@ -833,7 +834,7 @@ public class Navigation { if (configuration.modules.size() == 1) { ModuleElement mdle = configuration.modules.first(); boolean included = configuration.utils.isIncluded(mdle); - tree.addContent(HtmlTree.LI((included) + tree.add(HtmlTree.LI((included) ? links.createLink(pathToRoot.resolve(configuration.docPaths.moduleSummary(mdle)), contents.moduleLabel, "", "") : contents.moduleLabel)); } else if (!configuration.modules.isEmpty()) { @@ -844,7 +845,7 @@ public class Navigation { private void addModuleOfElementLink(Content tree) { if (configuration.showModules) { - tree.addContent(HtmlTree.LI(navLinkModule)); + tree.add(HtmlTree.LI(navLinkModule)); } } @@ -861,16 +862,16 @@ public class Navigation { } } if (included || packageElement == null) { - tree.addContent(HtmlTree.LI(links.createLink( + tree.add(HtmlTree.LI(links.createLink( pathToRoot.resolve(configuration.docPaths.forPackage(packageElement).resolve(DocPaths.PACKAGE_SUMMARY)), contents.packageLabel))); } else { DocLink crossPkgLink = configuration.extern.getExternalLink( packageElement, pathToRoot, DocPaths.PACKAGE_SUMMARY.getPath()); if (crossPkgLink != null) { - tree.addContent(HtmlTree.LI(links.createLink(crossPkgLink, contents.packageLabel))); + tree.add(HtmlTree.LI(links.createLink(crossPkgLink, contents.packageLabel))); } else { - tree.addContent(HtmlTree.LI(contents.packageLabel)); + tree.add(HtmlTree.LI(contents.packageLabel)); } } } else if (!configuration.packages.isEmpty()) { @@ -879,12 +880,12 @@ public class Navigation { } private void addPackageOfElementLink(Content tree) { - tree.addContent(HtmlTree.LI(links.createLink(DocPath.parent.resolve(DocPaths.PACKAGE_SUMMARY), + tree.add(HtmlTree.LI(links.createLink(DocPath.parent.resolve(DocPaths.PACKAGE_SUMMARY), contents.packageLabel))); } private void addPackageSummaryLink(Content tree) { - tree.addContent(HtmlTree.LI(links.createLink(DocPaths.PACKAGE_SUMMARY, contents.packageLabel))); + tree.add(HtmlTree.LI(links.createLink(DocPaths.PACKAGE_SUMMARY, contents.packageLabel))); } private void addTreeLink(Content tree) { @@ -893,20 +894,20 @@ public class Navigation { DocPath docPath = packages.size() == 1 && configuration.getSpecifiedTypeElements().isEmpty() ? pathToRoot.resolve(configuration.docPaths.forPackage(packages.get(0)).resolve(DocPaths.PACKAGE_TREE)) : pathToRoot.resolve(DocPaths.OVERVIEW_TREE); - tree.addContent(HtmlTree.LI(links.createLink(docPath, contents.treeLabel, "", ""))); + tree.add(HtmlTree.LI(links.createLink(docPath, contents.treeLabel, "", ""))); } } private void addDeprecatedLink(Content tree) { if (!(configuration.nodeprecated || configuration.nodeprecatedlist)) { - tree.addContent(HtmlTree.LI(links.createLink(pathToRoot.resolve(DocPaths.DEPRECATED_LIST), + tree.add(HtmlTree.LI(links.createLink(pathToRoot.resolve(DocPaths.DEPRECATED_LIST), contents.deprecatedLabel, "", ""))); } } private void addIndexLink(Content tree) { if (configuration.createindex) { - tree.addContent(HtmlTree.LI(links.createLink(pathToRoot.resolve( + tree.add(HtmlTree.LI(links.createLink(pathToRoot.resolve( (configuration.splitindex ? DocPaths.INDEX_FILES.resolve(DocPaths.indexN(1)) : DocPaths.INDEX_ALL)), @@ -924,7 +925,7 @@ public class Navigation { DocFile file = DocFile.createFileForInput(configuration, helpfile); helpfilenm = DocPath.create(file.getName()); } - tree.addContent(HtmlTree.LI(links.createLink(pathToRoot.resolve(helpfilenm), + tree.add(HtmlTree.LI(links.createLink(pathToRoot.resolve(helpfilenm), contents.helpLabel, "", ""))); } } @@ -937,7 +938,7 @@ public class Navigation { private void addNavShowLists(Content tree) { DocLink dl = new DocLink(pathToRoot.resolve(DocPaths.INDEX), path.getPath(), null); Content framesContent = links.createLink(dl, contents.framesLabel, "", "_top"); - tree.addContent(HtmlTree.LI(framesContent)); + tree.add(HtmlTree.LI(framesContent)); } /** @@ -947,7 +948,7 @@ public class Navigation { */ private void addNavHideLists(Content tree) { Content noFramesContent = links.createLink(path.basename(), contents.noFramesLabel, "", "_top"); - tree.addContent(HtmlTree.LI(noFramesContent)); + tree.add(HtmlTree.LI(noFramesContent)); } private void addSearch(Content tree) { @@ -956,14 +957,14 @@ public class Navigation { HtmlTree inputText = HtmlTree.INPUT("text", searchValueId, searchValueId); HtmlTree inputReset = HtmlTree.INPUT(reset, reset, reset); HtmlTree liInput = HtmlTree.LI(HtmlTree.LABEL(searchValueId, searchLabel)); - liInput.addContent(inputText); - liInput.addContent(inputReset); + liInput.add(inputText); + liInput.add(inputReset); HtmlTree ulSearch = HtmlTree.UL(HtmlStyle.navListSearch, liInput); - tree.addContent(ulSearch); + tree.add(ulSearch); } private void addFixedNavScript(Content tree) { - tree.addContent(FIXED_NAV_SCRIPT.asContent()); + tree.add(FIXED_NAV_SCRIPT.asContent()); } /** @@ -980,29 +981,29 @@ public class Navigation { HtmlTree navDiv = new HtmlTree(HtmlTag.DIV); if (top) { queue = topBottomNavContents.get(Position.TOP); - fixedNavDiv.addContent(Position.TOP.startOfNav()); + fixedNavDiv.add(Position.TOP.startOfNav()); navDiv.setStyle(HtmlStyle.topNav); } else { queue = topBottomNavContents.get(Position.BOTTOM); - tree.addContent(Position.BOTTOM.startOfNav()); + tree.add(Position.BOTTOM.startOfNav()); navDiv.setStyle(HtmlStyle.bottomNav); } - navDiv.addContent(queue.poll()); + navDiv.add(queue.poll()); HtmlTree skipLinkDiv = HtmlTree.DIV(HtmlStyle.skipNav, queue.poll()); - navDiv.addContent(skipLinkDiv); - navDiv.addContent(queue.poll()); + navDiv.add(skipLinkDiv); + navDiv.add(queue.poll()); HtmlTree navList = new HtmlTree(HtmlTag.UL); navList.setStyle(HtmlStyle.navList); - navList.addAttr(HtmlAttr.TITLE, rowListTitle); + navList.put(HtmlAttr.TITLE, rowListTitle); fixedNavDiv.setStyle(HtmlStyle.fixedNav); addMainNavLinks(navList); - navDiv.addContent(navList); + navDiv.add(navList); Content aboutDiv = HtmlTree.DIV(HtmlStyle.aboutLanguage, top ? userHeader : userFooter); - navDiv.addContent(aboutDiv); + navDiv.add(aboutDiv); if (top) { - fixedNavDiv.addContent(navDiv); + fixedNavDiv.add(navDiv); } else { - tree.addContent(navDiv); + tree.add(navDiv); } HtmlTree subDiv = new HtmlTree(HtmlTag.DIV); subDiv.setStyle(HtmlStyle.subNav); @@ -1011,12 +1012,12 @@ public class Navigation { HtmlTree ulNavSummary = new HtmlTree(HtmlTag.UL); ulNavSummary.setStyle(HtmlStyle.subNavList); addSummaryLinks(ulNavSummary); - div.addContent(ulNavSummary); + div.add(ulNavSummary); // Add the detail links if present. HtmlTree ulNavDetail = new HtmlTree(HtmlTag.UL); ulNavDetail.setStyle(HtmlStyle.subNavList); addDetailLinks(ulNavDetail); - div.addContent(ulNavDetail); + div.add(ulNavDetail); HtmlTree ulFrames = new HtmlTree(HtmlTag.UL); ulFrames.setStyle(HtmlStyle.navList); if (!configuration.nonavbar) { @@ -1025,23 +1026,23 @@ public class Navigation { addNavHideLists(ulFrames); } } - div.addContent(ulFrames); - subDiv.addContent(div); + div.add(ulFrames); + subDiv.add(div); if (top && configuration.createindex) { addSearch(subDiv); } if (top) { - fixedNavDiv.addContent(subDiv); - fixedNavDiv.addContent(queue.poll()); - fixedNavDiv.addContent(Position.TOP.endOfNav()); - tree.addContent(fixedNavDiv); + fixedNavDiv.add(subDiv); + fixedNavDiv.add(queue.poll()); + fixedNavDiv.add(Position.TOP.endOfNav()); + tree.add(fixedNavDiv); HtmlTree paddingDiv = HtmlTree.DIV(HtmlStyle.navPadding, Contents.SPACE); - tree.addContent(paddingDiv); + tree.add(paddingDiv); addFixedNavScript(tree); } else { - tree.addContent(subDiv); - tree.addContent(queue.poll()); - tree.addContent(Position.BOTTOM.endOfNav()); + tree.add(subDiv); + tree.add(queue.poll()); + tree.add(Position.BOTTOM.endOfNav()); } return tree; } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/RawHtml.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/RawHtml.java index a374531f722..afb00f34a6a 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/RawHtml.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/RawHtml.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ public class RawHtml extends Content { * @param content content that needs to be added * @throws UnsupportedOperationException always */ - public void addContent(Content content) { + public void add(Content content) { throw new UnsupportedOperationException(); } @@ -75,7 +75,7 @@ public class RawHtml extends Content { * @throws UnsupportedOperationException always */ @Override - public void addContent(CharSequence stringContent) { + public void add(CharSequence stringContent) { throw new UnsupportedOperationException(); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Script.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Script.java index 2656fa11502..9ac61660cd8 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Script.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Script.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -108,19 +108,19 @@ public class Script { ScriptContent scriptContent = new ScriptContent(sb); HtmlTree tree = new HtmlTree(HtmlTag.SCRIPT) { @Override - public void addContent(CharSequence s) { + public void add(CharSequence s) { throw new UnsupportedOperationException(); } @Override - public void addContent(Content c) { + public void add(Content c) { if (c != scriptContent) { throw new IllegalArgumentException(); } - super.addContent(scriptContent); + super.add(scriptContent); } }; - tree.addAttr(HtmlAttr.TYPE, "text/javascript"); - tree.addContent(scriptContent); + tree.put(HtmlAttr.TYPE, "text/javascript"); + tree.add(scriptContent); return tree; } @@ -200,12 +200,12 @@ public class Script { } @Override - public void addContent(Content content) { + public void add(Content content) { throw new UnsupportedOperationException(); } @Override - public void addContent(CharSequence code) { + public void add(CharSequence code) { sb.append(code); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/StringContent.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/StringContent.java index 912e876bc13..e8c3ed162c5 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/StringContent.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/StringContent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,7 +69,7 @@ public class StringContent extends Content { * @throws UnsupportedOperationException always */ @Override - public void addContent(Content content) { + public void add(Content content) { throw new UnsupportedOperationException(); } @@ -80,7 +80,7 @@ public class StringContent extends Content { * @param strContent string content to be added */ @Override - public void addContent(CharSequence strContent) { + public void add(CharSequence strContent) { appendChars(strContent); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Table.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Table.java index e19007a095f..845d3950365 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Table.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/Table.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,7 +40,6 @@ import javax.lang.model.element.Element; import jdk.javadoc.internal.doclets.formats.html.Contents; import jdk.javadoc.internal.doclets.toolkit.Content; -import jdk.javadoc.internal.doclets.toolkit.util.DocletConstants; /** * A builder for HTML tables, such as the summary tables for various @@ -191,7 +190,6 @@ public class Table { * *

    Notes: *

      - *
    • This currently does not use a {@code } tag, but probably should, eventually *
    • The column styles are not currently applied to the header, but probably should, eventually *
    * @@ -347,7 +345,7 @@ public class Table { if (stripedStyles != null) { int rowIndex = bodyRows.size(); - row.addAttr(HtmlAttr.CLASS, stripedStyles.get(rowIndex % 2).name()); + row.put(HtmlAttr.CLASS, stripedStyles.get(rowIndex % 2).name()); } int colIndex = 0; for (Content c : contents) { @@ -357,14 +355,14 @@ public class Table { HtmlTree cell = (colIndex == rowScopeColumnIndex) ? HtmlTree.TH(cellStyle, "row", c) : HtmlTree.TD(cellStyle, c); - row.addContent(cell); + row.add(cell); colIndex++; } bodyRows.add(row); if (tabMap != null) { int index = bodyRows.size() - 1; - row.addAttr(HtmlAttr.ID, (rowIdPrefix + index)); + row.put(HtmlAttr.ID, (rowIdPrefix + index)); int mask = 0; int maskBit = 1; for (Map.Entry> e : tabMap.entrySet()) { @@ -401,60 +399,62 @@ public class Table { HtmlTree table = new HtmlTree(HtmlTag.TABLE); if (tabMap == null || tabs.size() == 1) { if (tabMap == null) { - table.addContent(caption); + table.add(caption); } else if (tabs.size() == 1) { String tabName = tabs.iterator().next(); - table.addContent(getCaption(new StringContent(tabName))); + table.add(getCaption(new StringContent(tabName))); } - table.addContent(getTableBody()); - mainDiv.addContent(table); + table.add(getTableBody()); + mainDiv.add(table); } else { HtmlTree tablist = new HtmlTree(HtmlTag.DIV) - .addAttr(HtmlAttr.ROLE, "tablist") - .addAttr(HtmlAttr.ARIA_ORIENTATION, "horizontal"); + .put(HtmlAttr.ROLE, "tablist") + .put(HtmlAttr.ARIA_ORIENTATION, "horizontal"); int tabIndex = 0; - tablist.addContent(createTab(tabId.apply(tabIndex), activeTabStyle, true, defaultTab)); - table.addAttr(HtmlAttr.ARIA_LABELLEDBY, tabId.apply(tabIndex)); + tablist.add(createTab(tabId.apply(tabIndex), activeTabStyle, true, defaultTab)); + table.put(HtmlAttr.ARIA_LABELLEDBY, tabId.apply(tabIndex)); for (String tabName : tabMap.keySet()) { tabIndex++; if (tabs.contains(tabName)) { String script = tabScript.apply(1 << (tabIndex - 1)); HtmlTree tab = createTab(tabId.apply(tabIndex), tabStyle, false, tabName); - tab.addAttr(HtmlAttr.ONCLICK, script); - tablist.addContent(tab); + tab.put(HtmlAttr.ONCLICK, script); + tablist.add(tab); } } HtmlTree tabpanel = new HtmlTree(HtmlTag.DIV) - .addAttr(HtmlAttr.ID, tableStyle + "_tabpanel") - .addAttr(HtmlAttr.ROLE, "tabpanel"); - table.addContent(getTableBody()); - tabpanel.addContent(table); - mainDiv.addContent(tablist); - mainDiv.addContent(tabpanel); + .put(HtmlAttr.ID, tableStyle + "_tabpanel") + .put(HtmlAttr.ROLE, "tabpanel"); + table.add(getTableBody()); + tabpanel.add(table); + mainDiv.add(tablist); + mainDiv.add(tabpanel); } return mainDiv; } private HtmlTree createTab(String tabId, HtmlStyle style, boolean defaultTab, String tabName) { HtmlTree tab = new HtmlTree(HtmlTag.BUTTON) - .addAttr(HtmlAttr.ROLE, "tab") - .addAttr(HtmlAttr.ARIA_SELECTED, defaultTab ? "true" : "false") - .addAttr(HtmlAttr.ARIA_CONTROLS, tableStyle + "_tabpanel") - .addAttr(HtmlAttr.TABINDEX, defaultTab ? "0" : "-1") - .addAttr(HtmlAttr.ONKEYDOWN, "switchTab(event)") - .addAttr(HtmlAttr.ID, tabId) + .put(HtmlAttr.ROLE, "tab") + .put(HtmlAttr.ARIA_SELECTED, defaultTab ? "true" : "false") + .put(HtmlAttr.ARIA_CONTROLS, tableStyle + "_tabpanel") + .put(HtmlAttr.TABINDEX, defaultTab ? "0" : "-1") + .put(HtmlAttr.ONKEYDOWN, "switchTab(event)") + .put(HtmlAttr.ID, tabId) .setStyle(style); - tab.addContent(tabName); + tab.add(tabName); return tab; } private Content getTableBody() { ContentBuilder tableContent = new ContentBuilder(); - tableContent.addContent(header.toContent()); + Content thead = new HtmlTree(HtmlTag.THEAD); + thead.add(header.toContent()); + tableContent.add(thead); Content tbody = new HtmlTree(HtmlTag.TBODY); - bodyRows.forEach(row -> tbody.addContent(row)); - tableContent.addContent(tbody); + bodyRows.forEach(row -> tbody.add(row)); + tableContent.add(tbody); return tableContent; } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/TableHeader.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/TableHeader.java index 7ce8f0fd25d..6fb9923604e 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/TableHeader.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/TableHeader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,7 +127,7 @@ public class TableHeader { : (i == 1) ? HtmlStyle.colSecond : null; Content cell = (style == null) ? HtmlTree.TH(scope, cellContent) : HtmlTree.TH(style, scope, cellContent); - tr.addContent(cell); + tr.add(cell); i++; } return tr; diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java index a931becd1d1..4a144ff3dc4 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/BaseConfiguration.java @@ -837,39 +837,47 @@ public abstract class BaseConfiguration { tagletManager = tagletManager == null ? new TagletManager(nosince, showversion, showauthor, javafx, this) : tagletManager; - for (List args : customTagStrs) { - if (args.get(0).equals("-taglet")) { - tagletManager.addCustomTag(args.get(1), getFileManager(), tagletpath); - continue; - } - List tokens = tokenize(args.get(1), TagletManager.SIMPLE_TAGLET_OPT_SEPARATOR, 3); - switch (tokens.size()) { - case 1: - String tagName = args.get(1); - if (tagletManager.isKnownCustomTag(tagName)) { - //reorder a standard tag - tagletManager.addNewSimpleCustomTag(tagName, null, ""); - } else { - //Create a simple tag with the heading that has the same name as the tag. - StringBuilder heading = new StringBuilder(tagName + ":"); - heading.setCharAt(0, Character.toUpperCase(tagName.charAt(0))); - tagletManager.addNewSimpleCustomTag(tagName, heading.toString(), "a"); - } - break; - - case 2: - //Add simple taglet without heading, probably to excluding it in the output. - tagletManager.addNewSimpleCustomTag(tokens.get(0), tokens.get(1), ""); - break; - - case 3: - tagletManager.addNewSimpleCustomTag(tokens.get(0), tokens.get(2), tokens.get(1)); - break; - - default: - Messages messages = getMessages(); - messages.error("doclet.Error_invalid_custom_tag_argument", args.get(1)); + JavaFileManager fileManager = getFileManager(); + Messages messages = getMessages(); + try { + tagletManager.initTagletPath(fileManager, tagletpath); + tagletManager.loadTaglets(fileManager); + + for (List args : customTagStrs) { + if (args.get(0).equals("-taglet")) { + tagletManager.addCustomTag(args.get(1), fileManager); + continue; + } + List tokens = tokenize(args.get(1), TagletManager.SIMPLE_TAGLET_OPT_SEPARATOR, 3); + switch (tokens.size()) { + case 1: + String tagName = args.get(1); + if (tagletManager.isKnownCustomTag(tagName)) { + //reorder a standard tag + tagletManager.addNewSimpleCustomTag(tagName, null, ""); + } else { + //Create a simple tag with the heading that has the same name as the tag. + StringBuilder heading = new StringBuilder(tagName + ":"); + heading.setCharAt(0, Character.toUpperCase(tagName.charAt(0))); + tagletManager.addNewSimpleCustomTag(tagName, heading.toString(), "a"); + } + break; + + case 2: + //Add simple taglet without heading, probably to excluding it in the output. + tagletManager.addNewSimpleCustomTag(tokens.get(0), tokens.get(1), ""); + break; + + case 3: + tagletManager.addNewSimpleCustomTag(tokens.get(0), tokens.get(2), tokens.get(1)); + break; + + default: + messages.error("doclet.Error_invalid_custom_tag_argument", args.get(1)); + } } + } catch (IOException e) { + messages.error("doclet.taglet_could_not_set_location", e.toString()); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Content.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Content.java index 1544076bd7a..d69c82c6cc8 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Content.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Content.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,14 +64,14 @@ public abstract class Content { * * @param content content that needs to be added */ - public abstract void addContent(Content content); + public abstract void add(Content content); /** * Adds a string content to the existing content. * * @param stringContent the string content to be added */ - public abstract void addContent(CharSequence stringContent); + public abstract void add(CharSequence stringContent); /** * Writes content to a writer. diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java index 19a9cc6457d..33f972eb054 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,7 +112,7 @@ public class WorkArounds { } // TODO: fix this up correctly - public void initDocLint(Collection opts, Collection customTagNames, String htmlVersion) { + public void initDocLint(Collection opts, Collection customTagNames) { ArrayList doclintOpts = new ArrayList<>(); boolean msgOptionSeen = false; @@ -137,12 +137,10 @@ public class WorkArounds { sep = DocLint.SEPARATOR; } doclintOpts.add(DocLint.XCUSTOM_TAGS_PREFIX + customTags.toString()); - doclintOpts.add(DocLint.XHTML_VERSION_PREFIX + htmlVersion); + doclintOpts.add(DocLint.XHTML_VERSION_PREFIX + "html5"); JavacTask t = BasicJavacTask.instance(toolEnv.context); doclint = new DocLint(); - // standard doclet normally generates H1, H2 - doclintOpts.add(DocLint.XIMPLICIT_HEADERS + "2"); doclint.init(t, doclintOpts.toArray(new String[doclintOpts.size()]), false); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java index ff49ddaa939..4544b182868 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -156,7 +156,7 @@ public class AnnotationTypeBuilder extends AbstractBuilder { buildAnnotationTypeDescription(annotationInfoTree); buildAnnotationTypeTagInfo(annotationInfoTree); - annotationContentTree.addContent(writer.getAnnotationInfo(annotationInfoTree)); + annotationContentTree.add(writer.getAnnotationInfo(annotationInfoTree)); } /** @@ -205,7 +205,7 @@ public class AnnotationTypeBuilder extends AbstractBuilder { protected void buildMemberSummary(Content annotationContentTree) throws DocletException { Content memberSummaryTree = writer.getMemberTreeHeader(); builderFactory.getMemberSummaryBuilder(writer).build(memberSummaryTree); - annotationContentTree.addContent(writer.getMemberSummaryTree(memberSummaryTree)); + annotationContentTree.add(writer.getMemberSummaryTree(memberSummaryTree)); } /** @@ -223,7 +223,7 @@ public class AnnotationTypeBuilder extends AbstractBuilder { buildAnnotationTypeOptionalMemberDetails(memberDetailsTree); if (memberDetailsTree.isValid()) { - annotationContentTree.addContent(writer.getMemberDetailsTree(memberDetailsTree)); + annotationContentTree.add(writer.getMemberDetailsTree(memberDetailsTree)); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java index 8e69ca00b0c..0c79b37b582 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -153,9 +153,9 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { buildMemberComments(annotationDocTree); buildTagInfo(annotationDocTree); - detailsTree.addContent(writer.getAnnotationDoc( + detailsTree.add(writer.getAnnotationDoc( annotationDocTree, currentMember == lastElement)); - memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree)); + memberDetailsTree.add(writer.getAnnotationDetails(detailsTree)); } } } @@ -166,7 +166,7 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { * @param annotationDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content annotationDocTree) { - annotationDocTree.addContent( + annotationDocTree.add( writer.getSignature(currentMember)); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java index f87090339e1..d64362d6000 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -152,9 +152,9 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { buildAnnotationTypeMemberChildren(annotationDocTree); - detailsTree.addContent(writer.getAnnotationDoc( + detailsTree.add(writer.getAnnotationDoc( annotationDocTree, currentMember == lastMember)); - memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree)); + memberDetailsTree.add(writer.getAnnotationDetails(detailsTree)); } } } @@ -172,7 +172,7 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { * @param annotationDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content annotationDocTree) { - annotationDocTree.addContent(writer.getSignature(currentMember)); + annotationDocTree.add(writer.getSignature(currentMember)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java index bb90678a0b0..c37d1d64a59 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -181,7 +181,7 @@ public class ClassBuilder extends AbstractBuilder { buildClassDescription(classInfoTree); buildClassTagInfo(classInfoTree); - classContentTree.addContent(writer.getClassInfo(classInfoTree)); + classContentTree.add(writer.getClassInfo(classInfoTree)); } /** @@ -322,7 +322,7 @@ public class ClassBuilder extends AbstractBuilder { protected void buildMemberSummary(Content classContentTree) throws DocletException { Content memberSummaryTree = writer.getMemberTreeHeader(); builderFactory.getMemberSummaryBuilder(writer).build(memberSummaryTree); - classContentTree.addContent(writer.getMemberSummaryTree(memberSummaryTree)); + classContentTree.add(writer.getMemberSummaryTree(memberSummaryTree)); } /** @@ -340,7 +340,7 @@ public class ClassBuilder extends AbstractBuilder { buildConstructorDetails(memberDetailsTree); buildMethodDetails(memberDetailsTree); - classContentTree.addContent(writer.getMemberDetailsTree(memberDetailsTree)); + classContentTree.add(writer.getMemberDetailsTree(memberDetailsTree)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java index 73a18e3c54a..ef4f3c66186 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -148,10 +148,10 @@ public class ConstructorBuilder extends AbstractMemberBuilder { buildConstructorComments(constructorDocTree); buildTagInfo(constructorDocTree); - constructorDetailsTree.addContent(writer.getConstructorDoc(constructorDocTree, + constructorDetailsTree.add(writer.getConstructorDoc(constructorDocTree, currentConstructor == lastElement)); } - memberDetailsTree.addContent( + memberDetailsTree.add( writer.getConstructorDetails(constructorDetailsTree)); } } @@ -162,7 +162,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { * @param constructorDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content constructorDocTree) { - constructorDocTree.addContent(writer.getSignature(currentConstructor)); + constructorDocTree.add(writer.getSignature(currentConstructor)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java index 11241855a63..0bc384c40b6 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -136,10 +136,10 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { buildEnumConstantComments(enumConstantsTree); buildTagInfo(enumConstantsTree); - enumConstantsDetailsTree.addContent(writer.getEnumConstants( + enumConstantsDetailsTree.add(writer.getEnumConstants( enumConstantsTree, currentElement == lastElement)); } - memberDetailsTree.addContent( + memberDetailsTree.add( writer.getEnumConstantsDetails(enumConstantsDetailsTree)); } } @@ -150,7 +150,7 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { * @param enumConstantsTree the content tree to which the documentation will be added */ protected void buildSignature(Content enumConstantsTree) { - enumConstantsTree.addContent(writer.getSignature(currentElement)); + enumConstantsTree.add(writer.getSignature(currentElement)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java index 5e98252c001..700f41f3b68 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -137,10 +137,10 @@ public class FieldBuilder extends AbstractMemberBuilder { buildFieldComments(fieldDocTree); buildTagInfo(fieldDocTree); - fieldDetailsTree.addContent(writer.getFieldDoc( + fieldDetailsTree.add(writer.getFieldDoc( fieldDocTree, currentElement == lastElement)); } - memberDetailsTree.addContent( + memberDetailsTree.add( writer.getFieldDetails(fieldDetailsTree)); } } @@ -151,7 +151,7 @@ public class FieldBuilder extends AbstractMemberBuilder { * @param fieldDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content fieldDocTree) { - fieldDocTree.addContent(writer.getSignature(currentElement)); + fieldDocTree.add(writer.getSignature(currentElement)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java index 65c1b2be1a8..790c2576241 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -464,7 +464,7 @@ public abstract class MemberSummaryBuilder extends AbstractMemberBuilder { Content inheritedTree = writer.getInheritedSummaryHeader(inheritedClass); Content linksTree = writer.getInheritedSummaryLinksTree(); addSummaryFootNote(inheritedClass, inheritedMembers, linksTree, writer); - inheritedTree.addContent(linksTree); + inheritedTree.add(linksTree); summaryTreeList.add(writer.getMemberTree(inheritedTree)); } } @@ -497,7 +497,7 @@ public abstract class MemberSummaryBuilder extends AbstractMemberBuilder { buildInheritedSummary(writer, kind, summaryTreeList); if (!summaryTreeList.isEmpty()) { Content memberTree = writer.getMemberSummaryHeader(typeElement, memberSummaryTree); - summaryTreeList.stream().forEach(memberTree::addContent); + summaryTreeList.stream().forEach(memberTree::add); writer.addMemberTree(memberSummaryTree, memberTree); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java index 0f72dd671f7..b774aff6884 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -139,10 +139,10 @@ public class MethodBuilder extends AbstractMemberBuilder { buildMethodComments(methodDocTree); buildTagInfo(methodDocTree); - methodDetailsTree.addContent(writer.getMethodDoc( + methodDetailsTree.add(writer.getMethodDoc( methodDocTree, currentMethod == lastElement)); } - memberDetailsTree.addContent(writer.getMethodDetails(methodDetailsTree)); + memberDetailsTree.add(writer.getMethodDetails(methodDetailsTree)); } } @@ -152,7 +152,7 @@ public class MethodBuilder extends AbstractMemberBuilder { * @param methodDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content methodDocTree) { - methodDocTree.addContent(writer.getSignature(currentMethod)); + methodDocTree.add(writer.getSignature(currentMethod)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java index 97e6d77ca1c..2ff5055d937 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ModuleSummaryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -152,7 +152,7 @@ public class ModuleSummaryBuilder extends AbstractBuilder { buildModulesSummary(summaryContentTree); buildServicesSummary(summaryContentTree); - moduleContentTree.addContent(moduleWriter.getSummaryTree(summaryContentTree)); + moduleContentTree.add(moduleWriter.getSummaryTree(summaryContentTree)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java index 1267b9282df..b48b3c70e00 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -163,7 +163,7 @@ public class PackageSummaryBuilder extends AbstractBuilder { buildErrorSummary(summaryContentTree); buildAnnotationTypeSummary(summaryContentTree); - packageContentTree.addContent(summaryContentTree); + packageContentTree.add(summaryContentTree); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java index 4cc106b9517..7e9b91a5f3f 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,6 @@ import jdk.javadoc.internal.doclets.toolkit.BaseConfiguration; import jdk.javadoc.internal.doclets.toolkit.Content; import jdk.javadoc.internal.doclets.toolkit.DocletException; import jdk.javadoc.internal.doclets.toolkit.PropertyWriter; -import jdk.javadoc.internal.doclets.toolkit.util.VisibleMemberTable; import static jdk.javadoc.internal.doclets.toolkit.util.VisibleMemberTable.Kind.*; @@ -138,10 +137,10 @@ public class PropertyBuilder extends AbstractMemberBuilder { buildPropertyComments(propertyDocTree); buildTagInfo(propertyDocTree); - propertyDetailsTree.addContent(writer.getPropertyDoc( + propertyDetailsTree.add(writer.getPropertyDoc( propertyDocTree, currentProperty == lastElement)); } - memberDetailsTree.addContent( + memberDetailsTree.add( writer.getPropertyDetails(propertyDetailsTree)); } } @@ -152,7 +151,7 @@ public class PropertyBuilder extends AbstractMemberBuilder { * @param propertyDocTree the content tree to which the documentation will be added */ protected void buildSignature(Content propertyDocTree) { - propertyDocTree.addContent(writer.getSignature(currentProperty)); + propertyDocTree.add(writer.getSignature(currentProperty)); } /** diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java index 96f1d1d2aeb..0ceddc9b9d6 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -170,7 +170,7 @@ public class SerializedFormBuilder extends AbstractBuilder { buildPackageSerializedForm(serializedSummariesTree); } - serializedTree.addContent(writer.getSerializedContent( + serializedTree.add(writer.getSerializedContent( serializedSummariesTree)); } @@ -205,7 +205,7 @@ public class SerializedFormBuilder extends AbstractBuilder { * @param packageSerializedTree content tree to which the documentation will be added */ protected void buildPackageHeader(Content packageSerializedTree) { - packageSerializedTree.addContent(writer.getPackageHeader( + packageSerializedTree.add(writer.getPackageHeader( utils.getPackageName(currentPackage))); } @@ -232,10 +232,10 @@ public class SerializedFormBuilder extends AbstractBuilder { buildSerialUIDInfo(classTree); buildClassContent(classTree); - classSerializedTree.addContent(classTree); + classSerializedTree.add(classTree); } } - packageSerializedTree.addContent(classSerializedTree); + packageSerializedTree.add(classSerializedTree); } /** @@ -254,7 +254,7 @@ public class SerializedFormBuilder extends AbstractBuilder { break; } } - classTree.addContent(serialUidTree); + classTree.add(serialUidTree); } /** @@ -270,7 +270,7 @@ public class SerializedFormBuilder extends AbstractBuilder { buildFieldHeader(classContentTree); buildSerializableFields(classContentTree); - classTree.addContent(classContentTree); + classTree.add(classContentTree); } /** @@ -292,20 +292,20 @@ public class SerializedFormBuilder extends AbstractBuilder { buildDeprecatedMethodInfo(methodsContentTree); buildMethodInfo(methodsContentTree); - serializableMethodTree.addContent(methodsContentTree); + serializableMethodTree.add(methodsContentTree); } } if (!utils.serializationMethods(currentTypeElement).isEmpty()) { - classContentTree.addContent(methodWriter.getSerializableMethods( + classContentTree.add(methodWriter.getSerializableMethods( resources.getText("doclet.Serialized_Form_methods"), serializableMethodTree)); if (utils.isSerializable(currentTypeElement) && !utils.isExternalizable(currentTypeElement)) { if (utils.serializationMethods(currentTypeElement).isEmpty()) { Content noCustomizationMsg = methodWriter.getNoCustomizationMsg( resources.getText("doclet.Serializable_no_customization")); - classContentTree.addContent(methodWriter.getSerializableMethods( - resources.getText("doclet.Serialized_Form_methods"), - noCustomizationMsg)); + classContentTree.add(methodWriter.getSerializableMethods( + resources.getText("doclet.Serialized_Form_methods"), + noCustomizationMsg)); } } } @@ -402,8 +402,8 @@ public class SerializedFormBuilder extends AbstractBuilder { fieldWriter.addMemberDescription(ve, fieldsOverviewContentTree); fieldWriter.addMemberTags(ve, fieldsOverviewContentTree); } - serializableFieldsTree.addContent(fieldsOverviewContentTree); - classContentTree.addContent(fieldWriter.getSerializableFields( + serializableFieldsTree.add(fieldsOverviewContentTree); + classContentTree.add(fieldWriter.getSerializableFields( resources.getText("doclet.Serialized_Form_class"), serializableFieldsTree)); } @@ -431,12 +431,12 @@ public class SerializedFormBuilder extends AbstractBuilder { buildFieldDeprecationInfo(fieldsContentTree); buildFieldInfo(fieldsContentTree); - serializableFieldsTree.addContent(fieldsContentTree); + serializableFieldsTree.add(fieldsContentTree); } else { buildSerialFieldTagsInfo(serializableFieldsTree); } } - classContentTree.addContent(fieldWriter.getSerializableFields( + classContentTree.add(fieldWriter.getSerializableFields( resources.getText("doclet.Serialized_Form_fields"), serializableFieldsTree)); } @@ -511,7 +511,7 @@ public class SerializedFormBuilder extends AbstractBuilder { fieldWriter.addMemberHeader(te, fieldType, "", tag.getName().getName().toString(), fieldsContentTree); fieldWriter.addMemberDescription(field, tag, fieldsContentTree); - serializableFieldsTree.addContent(fieldsContentTree); + serializableFieldsTree.add(fieldsContentTree); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties index 146716d9d75..08efb44c0d4 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties @@ -56,6 +56,8 @@ doclet.Notice_taglet_overriden=Note: Custom tags that override standard tags: {0 doclet.Notice_taglet_conflict_warn=Note: Custom tags that could override future standard tags: {0}. To avoid potential overrides, use at least one period character (.) in custom tag names. doclet.Error_taglet_not_registered=Error - Exception {0} thrown while trying to register Taglet {1}... doclet.Error_invalid_custom_tag_argument=Error - {0} is an invalid argument to the -tag option... +doclet.taglet_could_not_set_location = Could not set the taglet path: {0} +doclet.not_standard_file_manager = Cannot set taglet path; the file manager is not a StandardJavaFileManager doclet.Author=Author: doclet.DefaultValue=Default value: doclet.PropertyDescription=Property description: diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css index e46e2825f36..287dde6433d 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css @@ -296,25 +296,32 @@ ul.subNavList li { /* * Styles for headings. */ -div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { +div.details ul.blockList ul.blockList ul.blockList li.blockList h3, +div.details ul.blockList ul.blockList ul.blockListLast li.blockList h3, +div.serializedFormContainer ul.blockList ul.blockList ul.blockList li.blockList h4 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } -ul.blockList ul.blockList ul.blockList li.blockList h3 { +div.details h2, +div.summary h2 { + font-style: italic; +} +div.details h3, +div.summary h3 { + font-style: normal; +} +ul.blockList ul.blockList ul.blockList li.blockList h2 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } -ul.blockList ul.blockList li.blockList h3 { +ul.blockList ul.blockList li.blockList h2 { padding:0; margin:15px 0; } -ul.blockList li.blockList h2 { - padding:0px 0 20px 0; -} /* * Styles for page layout containers. */ @@ -597,7 +604,8 @@ th.colDeprecatedItemName a:link, th.colDeprecatedItemName a:visited, .docSummary { padding:0; } -ul.blockList ul.blockList ul.blockList li.blockList h3 { +ul.blockList ul.blockList ul.blockList li.blockList h3, +ul.blockList ul.blockList ul.blockListLast li.blockList h3 { font-style:normal; } div.block { diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ParamTaglet.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ParamTaglet.java index 4c9c7553dbb..3eea265cf77 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ParamTaglet.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ParamTaglet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -134,7 +134,7 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { ExecutableElement member = (ExecutableElement) holder; Content output = getTagletOutput(false, member, writer, member.getTypeParameters(), utils.getTypeParamTrees(member)); - output.addContent(getTagletOutput(true, member, writer, + output.add(getTagletOutput(true, member, writer, member.getParameters(), utils.getParamTrees(member))); return output; } else { @@ -160,7 +160,7 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { Content result = writer.getOutputInstance(); Set alreadyDocumented = new HashSet<>(); if (!paramTags.isEmpty()) { - result.addContent( + result.add( processParamTags(holder, isParameters, paramTags, getRankMap(writer.configuration().utils, formalParameters), writer, alreadyDocumented) ); @@ -168,7 +168,7 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { if (alreadyDocumented.size() != formalParameters.size()) { //Some parameters are missing corresponding @param tags. //Try to inherit them. - result.addContent(getInheritedTagletOutput(isParameters, holder, + result.add(getInheritedTagletOutput(isParameters, holder, writer, formalParameters, alreadyDocumented)); } return result; @@ -204,7 +204,7 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { inheritedDoc.holderTag, lname, alreadyDocumented.isEmpty()); - result.addContent(content); + result.add(content); } alreadyDocumented.add(String.valueOf(i)); } @@ -256,7 +256,7 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { : "doclet.Type_Parameters_dup_warn", paramName); } - result.addContent(processParamTag(e, isParams, writer, dt, + result.add(processParamTag(e, isParams, writer, dt, ch.getParameterName(dt), alreadyDocumented.isEmpty())); alreadyDocumented.add(rank); } @@ -285,9 +285,9 @@ public class ParamTaglet extends BaseTaglet implements InheritableTaglet { String header = writer.configuration().getResources().getText( isParams ? "doclet.Parameters" : "doclet.TypeParameters"); if (isFirstParam) { - result.addContent(writer.getParamHeader(header)); + result.add(writer.getParamHeader(header)); } - result.addContent(writer.paramTagOutput(e, paramTag, name)); + result.add(writer.paramTagOutput(e, paramTag, name)); return result; } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java index c7b9266bbef..11ebcfc79cf 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java @@ -204,44 +204,77 @@ public class TagletManager { } /** - * Add a new {@code Taglet}. Print a message to indicate whether or not + * Initializes the location TAGLET_PATH which is used to locate the custom taglets. + * @param fileManager the filemanager to load classes and resources. + * @param tagletPath the path to the custom taglet. + * @throws IOException if an error occurs while setting the location. + */ + public void initTagletPath(JavaFileManager fileManager, String tagletPath) throws IOException { + if (fileManager instanceof StandardJavaFileManager) { + StandardJavaFileManager sfm = (StandardJavaFileManager)fileManager; + if (tagletPath != null) { + List paths = new ArrayList<>(); + for (String pathname : tagletPath.split(File.pathSeparator)) { + paths.add(new File(pathname)); + } + sfm.setLocation(TAGLET_PATH, paths); + } else if (!sfm.hasLocation(TAGLET_PATH)) { + sfm.setLocation(TAGLET_PATH, Collections.emptyList()); + } + } else if (tagletPath != null) { + messages.error("doclet.not_standard_file_manager"); + } + } + + /** + * Adds a new {@code Taglet}. Print a message to indicate whether or not * the Taglet was registered properly. * @param classname the name of the class representing the custom tag. * @param fileManager the filemanager to load classes and resources. - * @param tagletPath the path to the class representing the custom tag. */ - public void addCustomTag(String classname, JavaFileManager fileManager, String tagletPath) { + public void addCustomTag(String classname, JavaFileManager fileManager) { try { ClassLoader tagClassLoader; - if (!fileManager.hasLocation(TAGLET_PATH)) { - List paths = new ArrayList<>(); - if (tagletPath != null) { - for (String pathname : tagletPath.split(File.pathSeparator)) { - paths.add(new File(pathname)); - } - } - if (fileManager instanceof StandardJavaFileManager) { - ((StandardJavaFileManager) fileManager).setLocation(TAGLET_PATH, paths); - } - } tagClassLoader = fileManager.getClassLoader(TAGLET_PATH); Class customTagClass = tagClassLoader.loadClass(classname).asSubclass(jdk.javadoc.doclet.Taglet.class); jdk.javadoc.doclet.Taglet instance = customTagClass.getConstructor().newInstance(); - instance.init(docEnv, doclet); - Taglet newLegacy = new UserTaglet(instance); - String tname = newLegacy.getName(); - Taglet t = allTaglets.get(tname); - if (t != null) { - allTaglets.remove(tname); - } - allTaglets.put(tname, newLegacy); - messages.notice("doclet.Notice_taglet_registered", classname); - } catch (Exception exc) { - messages.error("doclet.Error_taglet_not_registered", exc.getClass().getName(), classname); + registerTaglet(instance); + } catch (ReflectiveOperationException exc) { + messages.error("doclet.Error_taglet_not_registered", exc.getClass().getName(), + classname); } } + /** + * Loads taglets from a taglet path using service loader. + * @param fileManager the filemanager to load the taglets. + * @throws IOException if an error occurs while getting the service loader. + */ + public void loadTaglets(JavaFileManager fileManager) throws IOException { + Iterable location = ((StandardJavaFileManager)fileManager).getLocation(TAGLET_PATH); + if (location != null && location.iterator().hasNext()) { + ServiceLoader serviceLoader = + fileManager.getServiceLoader(TAGLET_PATH, jdk.javadoc.doclet.Taglet.class); + Iterator iterator = serviceLoader.iterator(); + while (iterator.hasNext()) { + jdk.javadoc.doclet.Taglet taglet = iterator.next(); + registerTaglet(taglet); + } + } + } + + /** + * Registers the {@code Taglet}. Prints a message if a {@code Taglet} got registered properly. + * @param instance the {@code Taglet} instance. + */ + private void registerTaglet(jdk.javadoc.doclet.Taglet instance) { + instance.init(docEnv, doclet); + Taglet newLegacy = new UserTaglet(instance); + allTaglets.put(newLegacy.getName(), newLegacy); + messages.notice("doclet.Notice_taglet_registered", instance.getClass().getName()); + } + /** * Add a new {@code SimpleTaglet}. If this tag already exists * and the header passed as an argument is null, move tag to the back of the diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletWriter.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletWriter.java index ac555a6cff2..ee1b98d253f 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletWriter.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -259,7 +259,7 @@ public abstract class TagletWriter { } if (currentOutput != null) { tagletManager.seenCustomTag(taglet.getName()); - output.addContent(currentOutput); + output.add(currentOutput); } } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ThrowsTaglet.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ThrowsTaglet.java index 679e9a85881..3b73462283b 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ThrowsTaglet.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/ThrowsTaglet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,9 +104,9 @@ public class ThrowsTaglet extends BaseTaglet !alreadyDocumented.contains(utils.getSimpleName(klass)) && !alreadyDocumented.contains(utils.getFullyQualifiedName(klass))) { if (alreadyDocumented.isEmpty()) { - result.addContent(writer.getThrowsHeader()); + result.add(writer.getThrowsHeader()); } - result.addContent(writer.throwsTagOutput(declaredExceptionType)); + result.add(writer.throwsTagOutput(declaredExceptionType)); alreadyDocumented.add(utils.getSimpleName(klass)); } } @@ -140,7 +140,7 @@ public class ThrowsTaglet extends BaseTaglet declaredExceptionTags.put(inheritedDoc.tagList, (ExecutableElement)inheritedDoc.holder); } } - result.addContent(throwsTagsOutput(declaredExceptionTags, writer, alreadyDocumented, false)); + result.add(throwsTagsOutput(declaredExceptionTags, writer, alreadyDocumented, false)); } return result; } @@ -156,11 +156,11 @@ public class ThrowsTaglet extends BaseTaglet Content result = writer.getOutputInstance(); HashSet alreadyDocumented = new HashSet<>(); if (!tagsMap.isEmpty()) { - result.addContent(throwsTagsOutput(tagsMap, writer, alreadyDocumented, true)); + result.add(throwsTagsOutput(tagsMap, writer, alreadyDocumented, true)); } - result.addContent(inheritThrowsDocumentation(holder, + result.add(inheritThrowsDocumentation(holder, execHolder.getThrownTypes(), alreadyDocumented, writer)); - result.addContent(linkToUndocumentedDeclaredExceptions( + result.add(linkToUndocumentedDeclaredExceptions( execHolder.getThrownTypes(), alreadyDocumented, writer)); return result; } @@ -192,9 +192,9 @@ public class ThrowsTaglet extends BaseTaglet continue; } if (alreadyDocumented.isEmpty()) { - result.addContent(writer.getThrowsHeader()); + result.add(writer.getThrowsHeader()); } - result.addContent(writer.throwsTagOutput(e, dt)); + result.add(writer.throwsTagOutput(e, dt)); alreadyDocumented.add(te != null ? utils.getFullyQualifiedName(te) : excName); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/UserTaglet.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/UserTaglet.java index cb6ebb6edf6..541a29a6187 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/UserTaglet.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/UserTaglet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -132,7 +132,7 @@ public class UserTaglet implements Taglet { */ public Content getTagletOutput(Element element, DocTree tag, TagletWriter writer){ Content output = writer.getOutputInstance(); - output.addContent(new RawHtml(userTaglet.toString(Collections.singletonList(tag), element))); + output.add(new RawHtml(userTaglet.toString(Collections.singletonList(tag), element))); return output; } @@ -146,7 +146,7 @@ public class UserTaglet implements Taglet { if (!tags.isEmpty()) { String tagString = userTaglet.toString(tags, holder); if (tagString != null) { - output.addContent(new RawHtml(tagString)); + output.add(new RawHtml(tagString)); } } return output; diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkFactory.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkFactory.java index 92d0b9a61ac..d1bbbc99b46 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkFactory.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,7 +81,7 @@ public abstract class LinkFactory { // handles primitives, no types and error types @Override protected Content defaultAction(TypeMirror type, LinkInfo linkInfo) { - link.addContent(utils.getTypeName(type, false)); + link.add(utils.getTypeName(type, false)); return link; } @@ -96,14 +96,14 @@ public abstract class LinkFactory { currentDepth--; if (utils.isAnnotated(type)) { linkInfo.type = type; - link.addContent(" "); - link.addContent(getTypeAnnotationLinks(linkInfo)); + link.add(" "); + link.add(getTypeAnnotationLinks(linkInfo)); } // use vararg if required if (linkInfo.isVarArg && currentDepth == 0) { - link.addContent("..."); + link.add("..."); } else { - link.addContent("[]"); + link.add("[]"); } return link; } @@ -111,25 +111,25 @@ public abstract class LinkFactory { @Override public Content visitWildcard(WildcardType type, LinkInfo linkInfo) { linkInfo.isTypeBound = true; - link.addContent("?"); + link.add("?"); TypeMirror extendsBound = type.getExtendsBound(); if (extendsBound != null) { - link.addContent(" extends "); + link.add(" extends "); setBoundsLinkInfo(linkInfo, extendsBound); - link.addContent(getLink(linkInfo)); + link.add(getLink(linkInfo)); } TypeMirror superBound = type.getSuperBound(); if (superBound != null) { - link.addContent(" super "); + link.add(" super "); setBoundsLinkInfo(linkInfo, superBound); - link.addContent(getLink(linkInfo)); + link.add(getLink(linkInfo)); } return link; } @Override public Content visitTypeVariable(TypeVariable type, LinkInfo linkInfo) { - link.addContent(getTypeAnnotationLinks(linkInfo)); + link.add(getTypeAnnotationLinks(linkInfo)); linkInfo.isTypeBound = true; TypeVariable typevariable = (utils.isArrayType(type)) ? (TypeVariable) componentType @@ -138,12 +138,12 @@ public abstract class LinkFactory { if ((!linkInfo.excludeTypeParameterLinks) && utils.isTypeElement(owner)) { linkInfo.typeElement = (TypeElement) owner; Content label = newContent(); - label.addContent(utils.getTypeName(type, false)); + label.add(utils.getTypeName(type, false)); linkInfo.label = label; - link.addContent(getClassLink(linkInfo)); + link.add(getClassLink(linkInfo)); } else { // No need to link method type parameters. - link.addContent(utils.getTypeName(typevariable, false)); + link.add(utils.getTypeName(typevariable, false)); } if (!linkInfo.excludeTypeBounds) { @@ -159,9 +159,9 @@ public abstract class LinkFactory { !utils.isAnnotated(bound)) { continue; } - link.addContent(more ? " & " : " extends "); + link.add(more ? " & " : " extends "); setBoundsLinkInfo(linkInfo, bound); - link.addContent(getLink(linkInfo)); + link.add(getLink(linkInfo)); more = true; } } @@ -173,16 +173,16 @@ public abstract class LinkFactory { if (linkInfo.isTypeBound && linkInfo.excludeTypeBoundsLinks) { // Since we are excluding type parameter links, we should not // be linking to the type bound. - link.addContent(utils.getTypeName(type, false)); - link.addContent(getTypeParameterLinks(linkInfo)); + link.add(utils.getTypeName(type, false)); + link.add(getTypeParameterLinks(linkInfo)); return link; } else { link = newContent(); - link.addContent(getTypeAnnotationLinks(linkInfo)); + link.add(getTypeAnnotationLinks(linkInfo)); linkInfo.typeElement = utils.asTypeElement(type); - link.addContent(getClassLink(linkInfo)); + link.add(getClassLink(linkInfo)); if (linkInfo.includeTypeAsSepLink) { - link.addContent(getTypeParameterLinks(linkInfo, false)); + link.add(getTypeParameterLinks(linkInfo, false)); } } return link; @@ -191,9 +191,9 @@ public abstract class LinkFactory { return linkVisitor.visit(linkInfo.type, linkInfo); } else if (linkInfo.typeElement != null) { Content link = newContent(); - link.addContent(getClassLink(linkInfo)); + link.add(getClassLink(linkInfo)); if (linkInfo.includeTypeAsSepLink) { - link.addContent(getTypeParameterLinks(linkInfo, false)); + link.add(getTypeParameterLinks(linkInfo, false)); } return link; } else { diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkInfo.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkInfo.java index 71a1ad40e2f..c9b9db887f7 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkInfo.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/links/LinkInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -145,11 +145,11 @@ public abstract class LinkInfo { return label; } else if (isLinkable()) { Content tlabel = newContent(); - tlabel.addContent(configuration.utils.getSimpleName(typeElement)); + tlabel.add(configuration.utils.getSimpleName(typeElement)); return tlabel; } else { Content tlabel = newContent(); - tlabel.addContent(configuration.getClassName(typeElement)); + tlabel.add(configuration.getClassName(typeElement)); return tlabel; } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/JavadocTool.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/JavadocTool.java index db41927ba81..883ae92b003 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/JavadocTool.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/JavadocTool.java @@ -197,9 +197,11 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { } // Parse the files in the packages and subpackages to be documented - ListBuffer packageTrees = new ListBuffer<>(); - parse(etable.getFilesToParse(), packageTrees, false); - modules.enter(packageTrees.toList(), null); + ListBuffer allTrees = new ListBuffer<>(); + allTrees.addAll(classTrees); + parse(etable.getFilesToParse(), allTrees, false); + modules.newRound(); + modules.initModules(allTrees.toList()); if (messager.hasErrors()) { return null; @@ -207,7 +209,7 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { // Enter symbols for all files toolEnv.notice("main.Building_tree"); - javadocEnter.main(classTrees.toList().appendList(packageTrees)); + javadocEnter.main(allTrees.toList()); if (messager.hasErrors()) { return null; diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java index cccd66b0da2..54798ddb2d3 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java @@ -756,13 +756,6 @@ public class Start extends ToolOption.Helper { } String text = messager.getText("main.doclet_class_not_found", userDocletName); throw new ToolException(CMDERR, text, cnfe); - } catch (NoClassDefFoundError ncfe) { - if (ncfe.getMessage().contains("com/sun/javadoc/Doclet")) { - String text = messager.getText("main.not_a_doclet", userDocletName); - throw new ToolException(ERROR, text, ncfe); - } else { - throw ncfe; - } } } diff --git a/src/jdk.javadoc/share/legal/jszip.md b/src/jdk.javadoc/share/legal/jszip.md index 29c42666b07..6d4a8e8917a 100644 --- a/src/jdk.javadoc/share/legal/jszip.md +++ b/src/jdk.javadoc/share/legal/jszip.md @@ -23,4 +23,36 @@ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +****************************************** + +The JSZip JavaScript Library v3.1.5 also includes pako + +pako includes the following license: + + +(The MIT License) + +Copyright (C) 2014-2017 by Vitaly Puzrin and Andrei Tuputcyn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +****************************************** + diff --git a/src/jdk.jcmd/share/classes/sun/tools/jmap/JMap.java b/src/jdk.jcmd/share/classes/sun/tools/jmap/JMap.java index 8611a335506..09af1af538e 100644 --- a/src/jdk.jcmd/share/classes/sun/tools/jmap/JMap.java +++ b/src/jdk.jcmd/share/classes/sun/tools/jmap/JMap.java @@ -190,7 +190,7 @@ public class JMap { System.out.flush(); // inspectHeap is not the same as jcmd GC.class_histogram - executeCommandForPid(pid, "inspectheap", filename, liveopt); + executeCommandForPid(pid, "inspectheap", liveopt, filename); } private static void dump(String pid, String options) diff --git a/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c b/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c index 287cebb9bc9..2e273137af0 100644 --- a/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c +++ b/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,12 @@ #define MAXLEN_MESSAGE 256 #define MAXLEN_EXEC (MAXLEN_FILENAME*2+MAXLEN_INTEGER+16) +#define TIMESTAMP_SIZE (MAXLEN_TIMESTAMP+1) +#define MAXLEN_DT 19 // "DD.MM.YYYY HH:MM:SS" +#define MAXLEN_MS 5 // ".mmm " +#define DT_SIZE (MAXLEN_DT+1) +#define TZ_SIZE (TIMESTAMP_SIZE-MAXLEN_DT-MAXLEN_MS) + static MUTEX_T my_mutex = MUTEX_INIT; /* Static variables (should be protected with mutex) */ @@ -52,12 +58,14 @@ static char location_stamp[MAXLEN_LOCATION+1]; static PID_T processPid; static int open_count; -/* Ascii id of current native thread. */ +/* + * "DD.MM.YYYY HH:MM:SS.mmm " + */ static void get_time_stamp(char *tbuf, size_t ltbuf) { - char timestamp_prefix[MAXLEN_TIMESTAMP+1]; - char timestamp_postfix[MAXLEN_TIMESTAMP+1]; + char timestamp_date_time[DT_SIZE]; + char timestamp_timezone[TZ_SIZE]; unsigned millisecs = 0; time_t t = 0; @@ -65,15 +73,14 @@ get_time_stamp(char *tbuf, size_t ltbuf) if ( time(&t) == (time_t)(-1) ) { t = 0; } - /* Break this up so that the format strings are string literals - and we avoid a compiler warning. */ - (void)strftime(timestamp_prefix, sizeof(timestamp_prefix), + + (void)strftime(timestamp_date_time, DT_SIZE, "%d.%m.%Y %T", localtime(&t)); - (void)strftime(timestamp_postfix, sizeof(timestamp_postfix), + (void)strftime(timestamp_timezone, TZ_SIZE, "%Z", localtime(&t)); (void)snprintf(tbuf, ltbuf, - "%s.%.3d %s", timestamp_prefix, - (int)(millisecs), timestamp_postfix); + "%s.%.3d %s", timestamp_date_time, + (int)(millisecs), timestamp_timezone); } /* Get basename of filename */ diff --git a/src/jdk.jdwp.agent/unix/native/libjdwp/linker_md.c b/src/jdk.jdwp.agent/unix/native/libjdwp/linker_md.c index 47b6d74dfa7..35b2814d5a1 100644 --- a/src/jdk.jdwp.agent/unix/native/libjdwp/linker_md.c +++ b/src/jdk.jdwp.agent/unix/native/libjdwp/linker_md.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,17 +23,9 @@ * questions. */ -/* - * Adapted from JDK 1.2 linker_md.c v1.37. Note that we #define - * NATIVE here, whether or not we're running solaris native threads. - * Outside the VM, it's unclear how we can do the locking that is - * done in the green threads version of the code below. - */ -#define NATIVE - /* * Machine Dependent implementation of the dynamic linking support - * for java. This routine is Solaris specific. + * for java. This routine is Unix specific. */ #include @@ -43,10 +35,6 @@ #include #include "path_md.h" -#ifndef NATIVE -#include "iomgr.h" -#include "threads_md.h" -#endif #ifdef __APPLE__ #define LIB_SUFFIX "dylib" @@ -85,7 +73,7 @@ static void dll_build_name(char* buffer, size_t buflen, int dbgsysBuildFunName(char *name, int nameLen, int args_size, int encodingIndex) { - /* On Solaris, there is only one encoding method. */ + // On Unix, there is only one encoding method. if (encodingIndex == 0) return 1; return 0; @@ -96,12 +84,13 @@ dbgsysBuildFunName(char *name, int nameLen, int args_size, int encodingIndex) * appropriate pre and extensions to a filename and the path */ void -dbgsysBuildLibName(char *holder, int holderlen, const char *pname, const char *fname) +dbgsysBuildLibName(char *holder, int holderlen, const char *pname, + const char *fname) { const int pnamelen = pname ? strlen(pname) : 0; *holder = '\0'; - /* Quietly truncate on buffer overflow. Should be an error. */ + // Quietly truncate on buffer overflow. Should be an error. if (pnamelen + (int)strlen(fname) + 10 > holderlen) { return; } @@ -113,30 +102,11 @@ dbgsysBuildLibName(char *holder, int holderlen, const char *pname, const char *f } } -#ifndef NATIVE -extern int thr_main(void); -#endif - void * dbgsysLoadLibrary(const char *name, char *err_buf, int err_buflen) { void * result; -#ifdef NATIVE result = dlopen(name, RTLD_LAZY); -#else - sysMonitorEnter(greenThreadSelf(), &_dl_lock); - result = dlopen(name, RTLD_NOW); - sysMonitorExit(greenThreadSelf(), &_dl_lock); - /* - * This is a bit of bulletproofing to catch the commonly occurring - * problem of people loading a library which depends on libthread into - * the VM. thr_main() should always return -1 which means that libthread - * isn't loaded. - */ - if (thr_main() != -1) { - VM_CALL(panic)("libthread loaded into green threads"); - } -#endif if (result == NULL) { (void)strncpy(err_buf, dlerror(), err_buflen-2); err_buf[err_buflen-1] = '\0'; @@ -146,24 +116,10 @@ dbgsysLoadLibrary(const char *name, char *err_buf, int err_buflen) void dbgsysUnloadLibrary(void *handle) { -#ifndef NATIVE - sysMonitorEnter(greenThreadSelf(), &_dl_lock); -#endif (void)dlclose(handle); -#ifndef NATIVE - sysMonitorExit(greenThreadSelf(), &_dl_lock); -#endif } void * dbgsysFindLibraryEntry(void *handle, const char *name) { - void * sym; -#ifndef NATIVE - sysMonitorEnter(greenThreadSelf(), &_dl_lock); -#endif - sym = dlsym(handle, name); -#ifndef NATIVE - sysMonitorExit(greenThreadSelf(), &_dl_lock); -#endif - return sym; + return dlsym(handle, name); } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketInputStreamInstrumentor.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketInputStreamInstrumentor.java index 618d5567a71..83b4f8afc75 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketInputStreamInstrumentor.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketInputStreamInstrumentor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,15 +27,14 @@ package jdk.jfr.internal.instrument; import java.io.IOException; import java.net.InetAddress; +import java.net.Socket; import jdk.jfr.events.SocketReadEvent; /** * See {@link JITracer} for an explanation of this code. */ -@JIInstrumentationTarget("java.net.SocketInputStream") -@JITypeMapping(from = "jdk.jfr.internal.instrument.SocketInputStreamInstrumentor$AbstractPlainSocketImpl", - to = "java.net.AbstractPlainSocketImpl") +@JIInstrumentationTarget("java.net.Socket$SocketInputStream") final class SocketInputStreamInstrumentor { private SocketInputStreamInstrumentor() { @@ -43,30 +42,28 @@ final class SocketInputStreamInstrumentor { @SuppressWarnings("deprecation") @JIInstrumentationMethod - int read(byte b[], int off, int length, int timeout) throws IOException { + public int read(byte b[], int off, int length) throws IOException { SocketReadEvent event = SocketReadEvent.EVENT.get(); if (!event.isEnabled()) { - return read(b, off, length, timeout); + return read(b, off, length); } int bytesRead = 0; try { event.begin(); - bytesRead = read(b, off, length, timeout); + bytesRead = read(b, off, length); } finally { event.end(); if (event.shouldCommit()) { - String hostString = impl.address.toString(); - int delimiterIndex = hostString.lastIndexOf('/'); - - event.host = hostString.substring(0, delimiterIndex); - event.address = hostString.substring(delimiterIndex + 1); - event.port = impl.port; + InetAddress remote = parent.getInetAddress(); + event.host = remote.getHostName(); + event.address = remote.getHostAddress(); + event.port = parent.getPort(); if (bytesRead < 0) { event.endOfStream = true; } else { event.bytesRead = bytesRead; } - event.timeout = timeout; + event.timeout = parent.getSoTimeout(); event.commit(); event.reset(); @@ -75,14 +72,6 @@ final class SocketInputStreamInstrumentor { return bytesRead; } - private AbstractPlainSocketImpl impl = null; - - void silenceFindBugsUnwrittenField(InetAddress dummy) { - impl.address = dummy; - } - - static class AbstractPlainSocketImpl { - InetAddress address; - int port; - } + // private field in java.net.Socket$SocketInputStream + private Socket parent; } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketOutputStreamInstrumentor.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketOutputStreamInstrumentor.java index a0f62cadc4b..3fdd07138db 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketOutputStreamInstrumentor.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/SocketOutputStreamInstrumentor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,15 +27,14 @@ package jdk.jfr.internal.instrument; import java.io.IOException; import java.net.InetAddress; +import java.net.Socket; import jdk.jfr.events.SocketWriteEvent; /** * See {@link JITracer} for an explanation of this code. */ -@JIInstrumentationTarget("java.net.SocketOutputStream") -@JITypeMapping(from = "jdk.jfr.internal.instrument.SocketOutputStreamInstrumentor$AbstractPlainSocketImpl", - to = "java.net.AbstractPlainSocketImpl") +@JIInstrumentationTarget("java.net.Socket$SocketOutputStream") final class SocketOutputStreamInstrumentor { private SocketOutputStreamInstrumentor() { @@ -43,27 +42,25 @@ final class SocketOutputStreamInstrumentor { @SuppressWarnings("deprecation") @JIInstrumentationMethod - private void socketWrite(byte b[], int off, int len) throws IOException { + public void write(byte b[], int off, int len) throws IOException { SocketWriteEvent event = SocketWriteEvent.EVENT.get(); if (!event.isEnabled()) { - socketWrite(b, off, len); + write(b, off, len); return; } int bytesWritten = 0; try { event.begin(); - socketWrite(b, off, len); + write(b, off, len); bytesWritten = len; } finally { event.end() ; if (event.shouldCommit()) { - String hostString = impl.address.toString(); - int delimiterIndex = hostString.lastIndexOf('/'); - - event.host = hostString.substring(0, delimiterIndex); - event.address = hostString.substring(delimiterIndex + 1); - event.port = impl.port; - event.bytesWritten = bytesWritten < 0 ? 0 : bytesWritten; + InetAddress remote = parent.getInetAddress(); + event.host = remote.getHostName(); + event.address = remote.getHostAddress(); + event.port = parent.getPort(); + event.bytesWritten = bytesWritten; event.commit(); event.reset(); @@ -71,14 +68,6 @@ final class SocketOutputStreamInstrumentor { } } - private AbstractPlainSocketImpl impl = null; - - void silenceFindBugsUnwrittenField(InetAddress dummy) { - impl.address = dummy; - } - - static class AbstractPlainSocketImpl { - InetAddress address; - int port; - } + // private field in java.net.Socket$SocketOutputStream + private Socket parent; } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/Command.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/Command.java index 95ac85be6bc..a7013579938 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/Command.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/tool/Command.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -243,7 +243,7 @@ abstract class Command { } rad.read(); // try to read 1 byte } catch (FileNotFoundException e) { - throw new UserDataException("could not find file '" + path + "'"); + throw new UserDataException("could not open file " + e.getMessage()); } catch (IOException e) { throw new UserDataException("i/o error reading file '" + path + "', " + e.getMessage()); } diff --git a/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java b/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java index e86fb7fa619..d3dc8a9645e 100644 --- a/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java +++ b/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java b/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java index cd5a7021540..f0e392232ed 100644 --- a/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java +++ b/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/jdk.net/macosx/native/libextnet/MacOSXSocketOptions.c b/src/jdk.net/macosx/native/libextnet/MacOSXSocketOptions.c index db676d3c5b1..4844f8dd2e2 100644 --- a/src/jdk.net/macosx/native/libextnet/MacOSXSocketOptions.c +++ b/src/jdk.net/macosx/native/libextnet/MacOSXSocketOptions.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java index 385851acfb0..83b1bcb7d96 100644 --- a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java +++ b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -230,7 +230,7 @@ public class SctpServerChannelImpl extends SctpServerChannel return null; thread = NativeThread.current(); for (;;) { - n = accept0(fd, newfd, isaa); + n = Net.accept(fd, newfd, isaa); if ((n == IOStatus.INTERRUPTED) && isOpen()) continue; break; @@ -412,22 +412,4 @@ public class SctpServerChannelImpl extends SctpServerChannel return SctpNet.getLocalAddresses(fdVal); } } - - /* Native */ - private static native void initIDs(); - - private static native int accept0(FileDescriptor ssfd, - FileDescriptor newfd, InetSocketAddress[] isaa) throws IOException; - - static { - IOUtil.load(); // loads nio & net native libraries - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("sctp"); - return null; - } - }); - initIDs(); - } } diff --git a/src/jdk.sctp/unix/native/libsctp/SctpServerChannelImpl.c b/src/jdk.sctp/unix/native/libsctp/SctpServerChannelImpl.c deleted file mode 100644 index 86309861c67..00000000000 --- a/src/jdk.sctp/unix/native/libsctp/SctpServerChannelImpl.c +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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 "sun_nio_ch_sctp_SctpServerChannelImpl.h" - -extern void Java_sun_nio_ch_ServerSocketChannelImpl_initIDs(JNIEnv* env, - jclass c); - -extern jint Java_sun_nio_ch_ServerSocketChannelImpl_accept0(JNIEnv* env, - jobject this, jobject ssfdo, jobject newfdo, jobjectArray isaa); - -/* - * Class: sun_nio_ch_sctp_SctpServerChannelImpl - * Method: initIDs - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_nio_ch_sctp_SctpServerChannelImpl_initIDs - (JNIEnv* env, jclass c) { - Java_sun_nio_ch_ServerSocketChannelImpl_initIDs(env, c); -} - -/* - * Class: sun_nio_ch_sctp_SctpServerChannelImpl - * Method: accept0 - * Signature: (Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;[Ljava/net/InetSocketAddress;)I - */ -JNIEXPORT jint JNICALL Java_sun_nio_ch_sctp_SctpServerChannelImpl_accept0 - (JNIEnv* env, jobject this, jobject ssfdo, jobject newfdo, jobjectArray isaa) { - return Java_sun_nio_ch_ServerSocketChannelImpl_accept0(env, this, - ssfdo, newfdo, isaa); -} diff --git a/test/hotspot/gtest/gc/z/test_zForwardingTable.cpp b/test/hotspot/gtest/gc/z/test_zForwarding.cpp similarity index 56% rename from test/hotspot/gtest/gc/z/test_zForwardingTable.cpp rename to test/hotspot/gtest/gc/z/test_zForwarding.cpp index e1ae315d2a1..205b2f6d75e 100644 --- a/test/hotspot/gtest/gc/z/test_zForwardingTable.cpp +++ b/test/hotspot/gtest/gc/z/test_zForwarding.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,10 @@ */ #include "precompiled.hpp" -#include "gc/z/zForwardingTable.inline.hpp" +#include "gc/z/zAddress.inline.hpp" +#include "gc/z/zForwarding.inline.hpp" +#include "gc/z/zGlobals.hpp" +#include "gc/z/zPage.inline.hpp" #include "unittest.hpp" using namespace testing; @@ -33,11 +36,11 @@ using namespace testing; #define CAPTURE(expression) CAPTURE1(expression) -class ZForwardingTableTest : public Test { +class ZForwardingTest : public Test { public: // Helper functions - static bool is_power_of_2(size_t value) { + static bool is_power_of_2(uint32_t value) { return ::is_power_of_2((intptr_t)value); } @@ -56,43 +59,43 @@ public: // Test functions - static void setup(ZForwardingTable& table) { - EXPECT_PRED1(is_power_of_2, table._size) << CAPTURE(table._size); + static void setup(ZForwarding* forwarding) { + EXPECT_PRED1(is_power_of_2, forwarding->_entries.length()) << CAPTURE(forwarding->_entries.length()); } - static void find_empty(ZForwardingTable& table) { - size_t size = table._size; - size_t entries_to_check = size * 2; + static void find_empty(ZForwarding* forwarding) { + uint32_t size = forwarding->_entries.length(); + uint32_t entries_to_check = size * 2; for (uint32_t i = 0; i < entries_to_check; i++) { uintptr_t from_index = SequenceToFromIndex::one_to_one(i); - EXPECT_TRUE(table.find(from_index).is_empty()) << CAPTURE2(from_index, size); + EXPECT_TRUE(forwarding->find(from_index).is_empty()) << CAPTURE2(from_index, size); } - EXPECT_TRUE(table.find(uintptr_t(-1)).is_empty()) << CAPTURE(size); + EXPECT_TRUE(forwarding->find(uintptr_t(-1)).is_empty()) << CAPTURE(size); } - static void find_full(ZForwardingTable& table) { - size_t size = table._size; - size_t entries_to_populate = size; + static void find_full(ZForwarding* forwarding) { + uint32_t size = forwarding->_entries.length(); + uint32_t entries_to_populate = size; // Populate for (uint32_t i = 0; i < entries_to_populate; i++) { uintptr_t from_index = SequenceToFromIndex::one_to_one(i); - ZForwardingTableCursor cursor; - ZForwardingTableEntry entry = table.find(from_index, &cursor); + ZForwardingCursor cursor; + ZForwardingEntry entry = forwarding->find(from_index, &cursor); ASSERT_TRUE(entry.is_empty()) << CAPTURE2(from_index, size); - table.insert(from_index, from_index, &cursor); + forwarding->insert(from_index, from_index, &cursor); } // Verify for (uint32_t i = 0; i < entries_to_populate; i++) { uintptr_t from_index = SequenceToFromIndex::one_to_one(i); - ZForwardingTableEntry entry = table.find(from_index); + ZForwardingEntry entry = forwarding->find(from_index); ASSERT_FALSE(entry.is_empty()) << CAPTURE2(from_index, size); ASSERT_EQ(entry.from_index(), from_index) << CAPTURE(size); @@ -100,27 +103,27 @@ public: } } - static void find_every_other(ZForwardingTable& table) { - size_t size = table._size; - size_t entries_to_populate = size / 2; + static void find_every_other(ZForwarding* forwarding) { + uint32_t size = forwarding->_entries.length(); + uint32_t entries_to_populate = size / 2; // Populate even from indices for (uint32_t i = 0; i < entries_to_populate; i++) { uintptr_t from_index = SequenceToFromIndex::even(i); - ZForwardingTableCursor cursor; - ZForwardingTableEntry entry = table.find(from_index, &cursor); + ZForwardingCursor cursor; + ZForwardingEntry entry = forwarding->find(from_index, &cursor); ASSERT_TRUE(entry.is_empty()) << CAPTURE2(from_index, size); - table.insert(from_index, from_index, &cursor); + forwarding->insert(from_index, from_index, &cursor); } // Verify populated even indices for (uint32_t i = 0; i < entries_to_populate; i++) { uintptr_t from_index = SequenceToFromIndex::even(i); - ZForwardingTableCursor cursor; - ZForwardingTableEntry entry = table.find(from_index, &cursor); + ZForwardingCursor cursor; + ZForwardingEntry entry = forwarding->find(from_index, &cursor); ASSERT_FALSE(entry.is_empty()) << CAPTURE2(from_index, size); ASSERT_EQ(entry.from_index(), from_index) << CAPTURE(size); @@ -134,28 +137,47 @@ public: for (uint32_t i = 0; i < entries_to_populate; i++) { uintptr_t from_index = SequenceToFromIndex::odd(i); - ZForwardingTableEntry entry = table.find(from_index); + ZForwardingEntry entry = forwarding->find(from_index); ASSERT_TRUE(entry.is_empty()) << CAPTURE2(from_index, size); } } - static void test(void (*function)(ZForwardingTable&), uint32_t size) { - // Setup - ZForwardingTable table; - table.setup(size); - ASSERT_FALSE(table.is_null()); + static void test(void (*function)(ZForwarding*), uint32_t size) { + // Create page + const ZVirtualMemory vmem(0, ZPageSizeSmall); + const ZPhysicalMemory pmem(ZPhysicalMemorySegment(0, ZPageSizeSmall)); + ZPage page(ZPageTypeSmall, vmem, pmem); + + page.reset(); + + const size_t object_size = 16; + const uintptr_t object = page.alloc_object(object_size); + + ZGlobalSeqNum++; + + bool dummy = false; + page.mark_object(ZAddress::marked(object), dummy, dummy); + + const uint32_t live_objects = size; + const uint32_t live_bytes = live_objects * object_size; + page.inc_live_atomic(live_objects, live_bytes); + + // Setup forwarding + ZForwarding* const forwarding = ZForwarding::create(&page); // Actual test function - (*function)(table); + (*function)(forwarding); - // Teardown - table.reset(); - ASSERT_TRUE(table.is_null()); + // Teardown forwarding + ZForwarding::destroy(forwarding); + + // Teardown page + page.physical_memory().clear(); } // Run the given function with a few different input values. - static void test(void (*function)(ZForwardingTable&)) { + static void test(void (*function)(ZForwarding*)) { test(function, 1); test(function, 2); test(function, 3); @@ -168,18 +190,18 @@ public: } }; -TEST_F(ZForwardingTableTest, setup) { - test(&ZForwardingTableTest::setup); +TEST_F(ZForwardingTest, setup) { + test(&ZForwardingTest::setup); } -TEST_F(ZForwardingTableTest, find_empty) { - test(&ZForwardingTableTest::find_empty); +TEST_F(ZForwardingTest, find_empty) { + test(&ZForwardingTest::find_empty); } -TEST_F(ZForwardingTableTest, find_full) { - test(&ZForwardingTableTest::find_full); +TEST_F(ZForwardingTest, find_full) { + test(&ZForwardingTest::find_full); } -TEST_F(ZForwardingTableTest, find_every_other) { - test(&ZForwardingTableTest::find_every_other); +TEST_F(ZForwardingTest, find_every_other) { + test(&ZForwardingTest::find_every_other); } diff --git a/test/hotspot/gtest/gc/z/test_zPhysicalMemory.cpp b/test/hotspot/gtest/gc/z/test_zPhysicalMemory.cpp index 5b7990c83c7..fec1c48a846 100644 --- a/test/hotspot/gtest/gc/z/test_zPhysicalMemory.cpp +++ b/test/hotspot/gtest/gc/z/test_zPhysicalMemory.cpp @@ -22,6 +22,7 @@ */ #include "precompiled.hpp" +#include "gc/z/zGlobals.hpp" #include "gc/z/zPhysicalMemory.inline.hpp" #include "utilities/debug.hpp" #include "unittest.hpp" @@ -29,55 +30,51 @@ #if defined(AMD64) TEST(ZPhysicalMemorySegmentTest, split) { - const size_t SegmentSize = 2 * M; + ZPhysicalMemorySegment seg(0, 10 * ZGranuleSize); - ZPhysicalMemorySegment seg(0, 10 * SegmentSize); + ZPhysicalMemorySegment seg_split0 = seg.split(0 * ZGranuleSize); + EXPECT_EQ(seg_split0.size(), 0 * ZGranuleSize); + EXPECT_EQ( seg.size(), 10 * ZGranuleSize); - ZPhysicalMemorySegment seg_split0 = seg.split(0 * SegmentSize); - EXPECT_EQ(seg_split0.size(), 0 * SegmentSize); - EXPECT_EQ( seg.size(), 10 * SegmentSize); + ZPhysicalMemorySegment seg_split1 = seg.split(5 * ZGranuleSize); + EXPECT_EQ(seg_split1.size(), 5 * ZGranuleSize); + EXPECT_EQ( seg.size(), 5 * ZGranuleSize); - ZPhysicalMemorySegment seg_split1 = seg.split(5 * SegmentSize); - EXPECT_EQ(seg_split1.size(), 5 * SegmentSize); - EXPECT_EQ( seg.size(), 5 * SegmentSize); + ZPhysicalMemorySegment seg_split2 = seg.split(5 * ZGranuleSize); + EXPECT_EQ(seg_split2.size(), 5 * ZGranuleSize); + EXPECT_EQ( seg.size(), 0 * ZGranuleSize); - ZPhysicalMemorySegment seg_split2 = seg.split(5 * SegmentSize); - EXPECT_EQ(seg_split2.size(), 5 * SegmentSize); - EXPECT_EQ( seg.size(), 0 * SegmentSize); - - ZPhysicalMemorySegment seg_split3 = seg.split(0 * SegmentSize); - EXPECT_EQ(seg_split3.size(), 0 * SegmentSize); - EXPECT_EQ( seg.size(), 0 * SegmentSize); + ZPhysicalMemorySegment seg_split3 = seg.split(0 * ZGranuleSize); + EXPECT_EQ(seg_split3.size(), 0 * ZGranuleSize); + EXPECT_EQ( seg.size(), 0 * ZGranuleSize); } TEST(ZPhysicalMemoryTest, split) { - const size_t SegmentSize = 2 * M; + ZPhysicalMemoryManager pmem_manager(10 * ZGranuleSize); - ZPhysicalMemoryManager pmem_manager(10 * SegmentSize, SegmentSize); + pmem_manager.try_ensure_unused_capacity(10 * ZGranuleSize); + EXPECT_EQ(pmem_manager.unused_capacity(), 10 * ZGranuleSize); - pmem_manager.try_ensure_unused_capacity(10 * SegmentSize); - EXPECT_EQ(pmem_manager.unused_capacity(), 10 * SegmentSize); - - ZPhysicalMemory pmem = pmem_manager.alloc(8 * SegmentSize); + ZPhysicalMemory pmem = pmem_manager.alloc(8 * ZGranuleSize); EXPECT_EQ(pmem.nsegments(), 1u) << "wrong number of segments"; - ZPhysicalMemory split0_pmem = pmem.split(SegmentSize); + ZPhysicalMemory split0_pmem = pmem.split(ZGranuleSize); EXPECT_EQ(split0_pmem.nsegments(), 1u); EXPECT_EQ( pmem.nsegments(), 1u); - EXPECT_EQ(split0_pmem.size(), 1 * SegmentSize); - EXPECT_EQ( pmem.size(), 7 * SegmentSize); + EXPECT_EQ(split0_pmem.size(), 1 * ZGranuleSize); + EXPECT_EQ( pmem.size(), 7 * ZGranuleSize); - ZPhysicalMemory split1_pmem = pmem.split(2 * SegmentSize); + ZPhysicalMemory split1_pmem = pmem.split(2 * ZGranuleSize); EXPECT_EQ(split1_pmem.nsegments(), 1u); EXPECT_EQ( pmem.nsegments(), 1u); - EXPECT_EQ(split1_pmem.size(), 2 * SegmentSize); - EXPECT_EQ( pmem.size(), 5 * SegmentSize); + EXPECT_EQ(split1_pmem.size(), 2 * ZGranuleSize); + EXPECT_EQ( pmem.size(), 5 * ZGranuleSize); - ZPhysicalMemory split2_pmem = pmem.split(5 * SegmentSize); + ZPhysicalMemory split2_pmem = pmem.split(5 * ZGranuleSize); EXPECT_EQ(split2_pmem.nsegments(), 1u); EXPECT_EQ( pmem.nsegments(), 1u); - EXPECT_EQ(split2_pmem.size(), 5 * SegmentSize); - EXPECT_EQ( pmem.size(), 0 * SegmentSize); + EXPECT_EQ(split2_pmem.size(), 5 * ZGranuleSize); + EXPECT_EQ( pmem.size(), 0 * ZGranuleSize); } #endif diff --git a/test/hotspot/gtest/memory/test_virtualSpaceNode.cpp b/test/hotspot/gtest/memory/test_virtualSpaceNode.cpp deleted file mode 100644 index e19581d6ec1..00000000000 --- a/test/hotspot/gtest/memory/test_virtualSpaceNode.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include "precompiled.hpp" -#include "memory/metaspace/virtualSpaceList.hpp" -#include "memory/metaspace/chunkManager.hpp" -#include "runtime/mutexLocker.hpp" -#include "utilities/formatBuffer.hpp" -#include "unittest.hpp" - -// include as last, or otherwise we pull in an incompatible "assert" macro -#include - -using namespace metaspace; - -namespace { - static void chunk_up(size_t words_left, size_t& num_medium_chunks, - size_t& num_small_chunks, - size_t& num_specialized_chunks) { - num_medium_chunks = words_left / MediumChunk; - words_left = words_left % MediumChunk; - - num_small_chunks = words_left / SmallChunk; - words_left = words_left % SmallChunk; - // how many specialized chunks can we get? - num_specialized_chunks = words_left / SpecializedChunk; - ASSERT_EQ(0UL, words_left % SpecializedChunk) << "should be nothing left" - << ", words_left = " << words_left - << ", SpecializedChunk = " << SpecializedChunk; - } - static const size_t vsn_test_size_words = MediumChunk * 4; - static const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord; - class MetachunkRemover { - Metachunk* const _m; - ChunkManager* const _c; - public: - MetachunkRemover(Metachunk* m, ChunkManager* c) : _m(m), _c(c) { } - ~MetachunkRemover() { _c->remove_chunk(_m); } - }; -} - -class ChunkManagerTest { - public: - static size_t sum_free_chunks(ChunkManager* cm) { - return cm->sum_free_chunks(); - } - static size_t sum_free_chunks_count(ChunkManager* cm) { - return cm->sum_free_chunks_count(); - } - static ChunkList* free_chunks(ChunkManager* cm, ChunkIndex i) { - return cm->free_chunks(i); - } -}; - -// removes all the chunks added to the ChunkManager since creation of ChunkManagerRestorer -class ChunkManagerRestorer { - metaspace::ChunkManager* const _cm; - std::vector* _free_chunks[metaspace::NumberOfFreeLists]; - int _count_pre_existing; -public: - ChunkManagerRestorer(metaspace::ChunkManager* cm) : _cm(cm), _count_pre_existing(0) { - _cm->locked_verify(); - for (metaspace::ChunkIndex i = metaspace::ZeroIndex; i < metaspace::NumberOfFreeLists; i = next_chunk_index(i)) { - metaspace::ChunkList* l = ChunkManagerTest::free_chunks(_cm, i); - _count_pre_existing += l->count(); - std::vector *v = new std::vector(l->count()); - metaspace::Metachunk* c = l->head(); - while (c) { - v->push_back(c); - c = c->next(); - } - _free_chunks[i] = v; - } - } - ~ChunkManagerRestorer() { - _cm->locked_verify(); - for (metaspace::ChunkIndex i = metaspace::ZeroIndex; i < metaspace::NumberOfFreeLists; i = next_chunk_index(i)) { - metaspace::ChunkList* l = ChunkManagerTest::free_chunks(_cm, i); - std::vector *v = _free_chunks[i]; - ssize_t count = l->count(); - for (ssize_t j = 0; j < count; j++) { - metaspace::Metachunk* c = l->head(); - while (c) { - bool found = false; - for (size_t k = 0; k < v->size() && !found; k++) { - found = (c == v->at(k)); - } - if (found) { - c = c->next(); - } else { - _cm->remove_chunk(c); - break; - } - } - } - delete _free_chunks[i]; - _free_chunks[i] = NULL; - } - int count_after_cleanup = 0; - for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) { - ChunkList* l = ChunkManagerTest::free_chunks(_cm, i); - count_after_cleanup += l->count(); - } - EXPECT_EQ(_count_pre_existing, count_after_cleanup); - _cm->locked_verify(); - } -}; - -TEST_VM(VirtualSpaceNodeTest, sanity) { - // The chunk sizes must be multiples of eachother, or this will fail - STATIC_ASSERT(MediumChunk % SmallChunk == 0); - STATIC_ASSERT(SmallChunk % SpecializedChunk == 0); - - // just in case STATIC_ASSERT doesn't work - EXPECT_EQ(0, MediumChunk % SmallChunk); - EXPECT_EQ(0, SmallChunk % SpecializedChunk); -} - -TEST_VM(VirtualSpaceNodeTest, four_pages_vsn_is_committed_some_is_used_by_chunks) { - const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord; - if (page_chunks >= MediumChunk) { - SUCCEED() << "SKIP: This doesn't work for systems with vm_page_size >= 16K"; - return; - } - MutexLockerEx ml(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag); - ChunkManager cm(false); - VirtualSpaceNode vsn(false, vsn_test_size_bytes); - ChunkManagerRestorer c(Metaspace::get_chunk_manager(false)); - - vsn.initialize(); - EXPECT_TRUE(vsn.expand_by(page_chunks, page_chunks)); - vsn.get_chunk_vs(SmallChunk); - vsn.get_chunk_vs(SpecializedChunk); - vsn.retire(&cm); - - // committed - used = words left to retire - const size_t words_left = page_chunks - SmallChunk - SpecializedChunk; - size_t num_medium_chunks, num_small_chunks, num_spec_chunks; - chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks); - - EXPECT_EQ(0UL, num_medium_chunks) << "should not get any medium chunks"; - // DISABLED: checks started to fail after 8198423 - // EXPECT_EQ((num_small_chunks + num_spec_chunks), ChunkManagerTest::sum_free_chunks_count(&cm)) << "should be space for 3 chunks"; - // EXPECT_EQ(words_left, ChunkManagerTest::sum_free_chunks(&cm)) << "sizes should add up"; -} - -TEST_VM(VirtualSpaceNodeTest, half_vsn_is_committed_humongous_chunk_is_used) { - MutexLockerEx ml(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag); - ChunkManager cm(false); - VirtualSpaceNode vsn(false, vsn_test_size_bytes); - ChunkManagerRestorer c(Metaspace::get_chunk_manager(false)); - - vsn.initialize(); - EXPECT_TRUE(vsn.expand_by(MediumChunk * 2, MediumChunk * 2)); - // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk - vsn.get_chunk_vs(MediumChunk + SpecializedChunk); - vsn.retire(&cm); - - const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk); - size_t num_medium_chunks, num_small_chunks, num_spec_chunks; - ASSERT_NO_FATAL_FAILURE(chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks)); - - EXPECT_EQ(0UL, num_medium_chunks) << "should not get any medium chunks"; - // DISABLED: checks started to fail after 8198423 - // EXPECT_EQ((num_small_chunks + num_spec_chunks), ChunkManagerTest::sum_free_chunks_count(&cm)) << "should be space for 3 chunks"; - // EXPECT_EQ(words_left, ChunkManagerTest::sum_free_chunks(&cm)) << "sizes should add up"; -} - -TEST_VM(VirtualSpaceNodeTest, all_vsn_is_committed_half_is_used_by_chunks) { - MutexLockerEx ml(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag); - ChunkManager cm(false); - VirtualSpaceNode vsn(false, vsn_test_size_bytes); - ChunkManagerRestorer c(Metaspace::get_chunk_manager(false)); - - vsn.initialize(); - EXPECT_TRUE(vsn.expand_by(vsn_test_size_words, vsn_test_size_words)); - vsn.get_chunk_vs(MediumChunk); - vsn.get_chunk_vs(MediumChunk); - vsn.retire(&cm); - - // DISABLED: checks started to fail after 8198423 - // EXPECT_EQ(2UL, ChunkManagerTest::sum_free_chunks_count(&cm)) << "should have been memory left for 2 chunks"; - // EXPECT_EQ(2UL * MediumChunk, ChunkManagerTest::sum_free_chunks(&cm)) << "sizes should add up"; -} - -TEST_VM(VirtualSpaceNodeTest, no_committed_memory) { - MutexLockerEx ml(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag); - ChunkManager cm(false); - VirtualSpaceNode vsn(false, vsn_test_size_bytes); - ChunkManagerRestorer c(Metaspace::get_chunk_manager(false)); - - vsn.initialize(); - vsn.retire(&cm); - - ASSERT_EQ(0UL, ChunkManagerTest::sum_free_chunks_count(&cm)) << "did not commit any memory in the VSN"; -} - -TEST_VM(VirtualSpaceNodeTest, is_available_positive) { - // Reserve some memory. - VirtualSpaceNode vsn(false, os::vm_allocation_granularity()); - ASSERT_TRUE(vsn.initialize()) << "Failed to setup VirtualSpaceNode"; - - // Commit some memory. - size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord; - ASSERT_TRUE(vsn.expand_by(commit_word_size, commit_word_size)) - << "Failed to commit, commit_word_size = " << commit_word_size; - - SCOPED_TRACE(err_msg("VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", - p2i(vsn.bottom()), p2i(vsn.end())).buffer()); - - // Check that is_available accepts the committed size. - EXPECT_TRUE(vsn.is_available(commit_word_size)) << " commit_word_size = " << commit_word_size; - - // Check that is_available accepts half the committed size. - size_t expand_word_size = commit_word_size / 2; - EXPECT_TRUE(vsn.is_available(expand_word_size)) << " expand_word_size = " << expand_word_size; -} - -TEST_VM(VirtualSpaceNodeTest, is_available_negative) { - // Reserve some memory. - VirtualSpaceNode vsn(false, os::vm_allocation_granularity()); - ASSERT_TRUE(vsn.initialize()) << "Failed to setup VirtualSpaceNode"; - - // Commit some memory. - size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord; - ASSERT_TRUE(vsn.expand_by(commit_word_size, commit_word_size)) - << "Failed to commit, commit_word_size = " << commit_word_size; - - SCOPED_TRACE(err_msg("VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", - p2i(vsn.bottom()), p2i(vsn.end())).buffer()); - - // Check that is_available doesn't accept a too large size. - size_t two_times_commit_word_size = commit_word_size * 2; - EXPECT_FALSE(vsn.is_available(two_times_commit_word_size)) << " two_times_commit_word_size = " << two_times_commit_word_size; -} - -TEST_VM(VirtualSpaceNodeTest, is_available_overflow) { - // Reserve some memory. - VirtualSpaceNode vsn(false, os::vm_allocation_granularity()); - ASSERT_TRUE(vsn.initialize()) << "Failed to setup VirtualSpaceNode"; - - // Commit some memory. - size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord; - ASSERT_TRUE(vsn.expand_by(commit_word_size, commit_word_size)) - << "Failed to commit, commit_word_size = " << commit_word_size; - - SCOPED_TRACE(err_msg("VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", - p2i(vsn.bottom()), p2i(vsn.end())).buffer()); - - // Calculate a size that will overflow the virtual space size. - void* virtual_space_max = (void*)(uintptr_t)-1; - size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1); - size_t overflow_size = bottom_to_max + BytesPerWord; - size_t overflow_word_size = overflow_size / BytesPerWord; - - EXPECT_FALSE(vsn.is_available(overflow_word_size)) << " overflow_word_size = " << overflow_word_size; -} diff --git a/test/hotspot/gtest/metaprogramming/test_isArray.cpp b/test/hotspot/gtest/metaprogramming/test_isArray.cpp new file mode 100644 index 00000000000..59533889fbe --- /dev/null +++ b/test/hotspot/gtest/metaprogramming/test_isArray.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "memory/allocation.hpp" +#include "metaprogramming/isArray.hpp" +#include "utilities/debug.hpp" + +class IsArrayTest: AllStatic { + class A: AllStatic {}; + + static const bool ia_A = IsArray::value; + STATIC_ASSERT(!ia_A); + + static const bool ia_Aptr = IsArray::value; + STATIC_ASSERT(!ia_Aptr); + + static const bool ia_Aarr = IsArray::value; + STATIC_ASSERT(ia_Aarr); + + static const bool ia_Aarr10 = IsArray::value; + STATIC_ASSERT(ia_Aarr10); + + static const bool ia_Aptrarr10 = IsArray::value; + STATIC_ASSERT(ia_Aptrarr10); + + static const bool ia_Aarr10arr10 = IsArray::value; + STATIC_ASSERT(ia_Aarr10arr10); + + static const bool ia_cAarr = IsArray::value; + STATIC_ASSERT(ia_cAarr); + + static const bool ia_vAarr = IsArray::value; + STATIC_ASSERT(ia_vAarr); + + static const bool ia_cAarr10 = IsArray::value; + STATIC_ASSERT(ia_cAarr10); + + static const bool ia_vAarr10 = IsArray::value; + STATIC_ASSERT(ia_vAarr10); + + static const bool ia_voidptr = IsArray::value; + STATIC_ASSERT(!ia_voidptr); + + static const bool ia_intptrt = IsArray::value; + STATIC_ASSERT(!ia_intptrt); + + static const bool ia_char = IsArray::value; + STATIC_ASSERT(!ia_char); +}; diff --git a/test/hotspot/gtest/metaprogramming/test_removeExtent.cpp b/test/hotspot/gtest/metaprogramming/test_removeExtent.cpp new file mode 100644 index 00000000000..1f6d5e9c478 --- /dev/null +++ b/test/hotspot/gtest/metaprogramming/test_removeExtent.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "memory/allocation.hpp" +#include "metaprogramming/removeExtent.hpp" +#include "metaprogramming/isSame.hpp" +#include "utilities/debug.hpp" + +class RemoveExtentTest { + class A: AllStatic {}; + + typedef A* Aptr; + typedef A Aarr[]; + typedef A Aarr10[10]; + typedef const A cA; + typedef const A* cAptr; + typedef const A cAarr[]; + typedef const A cAarr10[10]; + + typedef RemoveExtent::type ra_Aptr; + static const bool ra_Aptr_is_Aptr = IsSame::value; + STATIC_ASSERT(ra_Aptr_is_Aptr); + + typedef RemoveExtent::type ra_Aarr; + static const bool ra_Aarr_is_A = IsSame::value; + STATIC_ASSERT(ra_Aarr_is_A); + + typedef RemoveExtent::type ra_Aarr10; + static const bool ra_Aarr10_is_A = IsSame::value; + STATIC_ASSERT(ra_Aarr10_is_A); + + typedef RemoveExtent::type ra_cAptr; + static const bool ra_cAptr_is_cAptr = IsSame::value; + STATIC_ASSERT(ra_cAptr_is_cAptr); + + typedef RemoveExtent::type ra_cAarr; + static const bool ra_cAarr_is_cA = IsSame::value; + STATIC_ASSERT(ra_cAarr_is_cA); + + typedef RemoveExtent::type ra_cAarr10; + static const bool ra_cAarr10_is_cA = IsSame::value; + STATIC_ASSERT(ra_cAarr10_is_cA); +}; diff --git a/test/hotspot/gtest/runtime/test_os.cpp b/test/hotspot/gtest/runtime/test_os.cpp index d7cbfc20719..6e3c7e6ac8e 100644 --- a/test/hotspot/gtest/runtime/test_os.cpp +++ b/test/hotspot/gtest/runtime/test_os.cpp @@ -153,28 +153,81 @@ TEST_VM_ASSERT_MSG(os, page_size_for_region_with_zero_min_pages, "sanity") { } #endif -TEST(os, test_print_hex_dump) { +static void do_test_print_hex_dump(address addr, size_t len, int unitsize, const char* expected) { + char buf[256]; + buf[0] = '\0'; + stringStream ss(buf, sizeof(buf)); + os::print_hex_dump(&ss, addr, addr + len, unitsize); +// tty->print_cr("expected: %s", expected); +// tty->print_cr("result: %s", buf); + ASSERT_NE(strstr(buf, expected), (char*)NULL); +} + +TEST_VM(os, test_print_hex_dump) { + const char* pattern [4] = { +#ifdef VM_LITTLE_ENDIAN + "00 01 02 03 04 05 06 07", + "0100 0302 0504 0706", + "03020100 07060504", + "0706050403020100" +#else + "00 01 02 03 04 05 06 07", + "0001 0203 0405 0607", + "00010203 04050607", + "0001020304050607" +#endif + }; + + const char* pattern_not_readable [4] = { + "?? ?? ?? ?? ?? ?? ?? ??", + "???? ???? ???? ????", + "???????? ????????", + "????????????????" + }; + + // On AIX, zero page is readable. + address unreadable = +#ifdef AIX + (address) 0xFFFFFFFFFFFF0000ULL; +#else + (address) 0 +#endif + ; + ResourceMark rm; - stringStream ss; + char buf[64]; + stringStream ss(buf, sizeof(buf)); outputStream* out = &ss; // outputStream* out = tty; // enable for printout - // Test dumping unreadable memory does not fail - os::print_hex_dump(out, (address)0, (address)100, 1); - os::print_hex_dump(out, (address)0, (address)100, 2); - os::print_hex_dump(out, (address)0, (address)100, 4); - os::print_hex_dump(out, (address)0, (address)100, 8); + // Test dumping unreadable memory + // Exclude test for Windows for now, since it needs SEH handling to work which cannot be + // guaranteed when we call directly into VM code. (see JDK-8220220) +#ifndef _WIN32 + do_test_print_hex_dump(unreadable, 100, 1, pattern_not_readable[0]); + do_test_print_hex_dump(unreadable, 100, 2, pattern_not_readable[1]); + do_test_print_hex_dump(unreadable, 100, 4, pattern_not_readable[2]); + do_test_print_hex_dump(unreadable, 100, 8, pattern_not_readable[3]); +#endif - // Test dumping readable memory does not fail - char arr[100]; + // Test dumping readable memory + address arr = (address)os::malloc(100, mtInternal); for (int c = 0; c < 100; c++) { arr[c] = c; } - address addr = (address)&arr; - os::print_hex_dump(out, addr, addr + 100, 1); - os::print_hex_dump(out, addr, addr + 100, 2); - os::print_hex_dump(out, addr, addr + 100, 4); - os::print_hex_dump(out, addr, addr + 100, 8); + + // properly aligned + do_test_print_hex_dump(arr, 100, 1, pattern[0]); + do_test_print_hex_dump(arr, 100, 2, pattern[1]); + do_test_print_hex_dump(arr, 100, 4, pattern[2]); + do_test_print_hex_dump(arr, 100, 8, pattern[3]); + + // Not properly aligned. Should automatically down-align by unitsize + do_test_print_hex_dump(arr + 1, 100, 2, pattern[1]); + do_test_print_hex_dump(arr + 1, 100, 4, pattern[2]); + do_test_print_hex_dump(arr + 1, 100, 8, pattern[3]); + + os::free(arr); } ////////////////////////////////////////////////////////////////////////////// diff --git a/test/hotspot/jtreg/ProblemList-graal.txt b/test/hotspot/jtreg/ProblemList-graal.txt index 57ff1c1d6cc..01510a86fa5 100644 --- a/test/hotspot/jtreg/ProblemList-graal.txt +++ b/test/hotspot/jtreg/ProblemList-graal.txt @@ -36,6 +36,7 @@ compiler/compilercontrol/directives/ExcludeTest.java 8181753 generi compiler/compilercontrol/jcmd/AddExcludeTest.java 8181753 generic-all compiler/compilercontrol/jcmd/AddLogTest.java 8181753 generic-all compiler/compilercontrol/mixed/RandomValidCommandsTest.java 8181753 generic-all +compiler/compilercontrol/mixed/RandomCommandsTest.java 8181753 generic-all compiler/graalunit/JttThreadsTest.java 8208066 generic-all @@ -207,8 +208,6 @@ serviceability/jvmti/HeapMonitor/MyPackage/HeapMonitorMultiArrayTest.java 81 runtime/RedefineObject/TestRedefineObject.java 8218399 generic-all -vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/TestDescription.java 8218167 generic-all - vmTestbase/gc/lock/jvmti/alloc/jvmtialloclock02/TestDescription.java 8218700 generic-all vmTestbase/nsk/jdb/unmonitor/unmonitor001/unmonitor001.java 8218701 generic-all @@ -226,4 +225,3 @@ org.graalvm.compiler.core.test.deopt.CompiledMethodTest 8202955 org.graalvm.compiler.hotspot.test.ReservedStackAccessTest 8213567 windows-all -org.graalvm.compiler.hotspot.test.CheckGraalIntrinsics 8218074 diff --git a/test/hotspot/jtreg/ProblemList-zgc.txt b/test/hotspot/jtreg/ProblemList-zgc.txt index 2d4c1c2cdf5..53e7953e470 100644 --- a/test/hotspot/jtreg/ProblemList-zgc.txt +++ b/test/hotspot/jtreg/ProblemList-zgc.txt @@ -27,4 +27,16 @@ # ############################################################################# +serviceability/sa/ClhsdbInspect.java 8220624 generic-all +serviceability/sa/ClhsdbJdis.java 8220624 generic-all +serviceability/sa/ClhsdbJhisto.java 8220624 generic-all +serviceability/sa/ClhsdbJstack.java 8220624 generic-all +serviceability/sa/ClhsdbPrintAs.java 8220624 generic-all +serviceability/sa/ClhsdbPstack.java 8220624 generic-all +serviceability/sa/ClhsdbSource.java 8220624 generic-all +serviceability/sa/TestClhsdbJstackLock.java 8220624 generic-all +serviceability/sa/TestHeapDumpForInvokeDynamic.java 8220624 generic-all +serviceability/sa/TestHeapDumpForLargeArray.java 8220624 generic-all +serviceability/sa/TestUniverse.java 8220624 generic-all +serviceability/sa/TestJmapCore.java 8220624 generic-all serviceability/sa/TestJmapCoreMetaspace.java 8219443 generic-all diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index 7b8083a46ca..7721d9b0280 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -83,6 +83,7 @@ gc/metaspace/CompressedClassSpaceSizeInJmapHeap.java 8193639 solaris-all runtime/handshake/HandshakeWalkSuspendExitTest.java 8214174 generic-all runtime/NMT/CheckForProperDetailStackTrace.java 8218458 generic-all runtime/SharedArchiveFile/SASymbolTableTest.java 8193639 solaris-all +runtime/containers/docker/TestCPUSets.java 8220672 generic-all ############################################################################# @@ -157,11 +158,7 @@ vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded004 vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded005/TestDescription.java 8153598 generic-all vmTestbase/nsk/monitoring/ThreadMXBean/ThreadInfo/Deadlock/JavaDeadlock001/TestDescription.java 8060733 generic-all -vmTestbase/nsk/jdi/ThreadReference/isSuspended/issuspended002/TestDescription.java 4903717 generic-all -vmTestbase/nsk/jdi/ThreadReference/resume/resume001/TestDescription.java 8072701 generic-all vmTestbase/nsk/jdi/ThreadReference/stop/stop001/TestDescription.java 7034630 generic-all -vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001/TestDescription.java 8013728 generic-all -vmTestbase/nsk/jdi/EventRequest/setEnabled/setenabled003/TestDescription.java 8066993 generic-all vmTestbase/nsk/jdi/VirtualMachine/redefineClasses/redefineclasses021/TestDescription.java 8065773 generic-all vmTestbase/nsk/jdi/VirtualMachine/redefineClasses/redefineclasses023/TestDescription.java 8065773 generic-all diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups index aa82fb17b88..accc6c4d737 100644 --- a/test/hotspot/jtreg/TEST.groups +++ b/test/hotspot/jtreg/TEST.groups @@ -1,5 +1,5 @@ # -# Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -265,6 +265,7 @@ tier1_runtime = \ -runtime/7158988/FieldMonitor.java \ -runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java \ -runtime/CommandLine/PrintGCApplicationConcurrentTime.java \ + -runtime/CompressedOops/UseCompressedOops.java \ -runtime/ConstantPool/IntfMethod.java \ -runtime/ErrorHandling/CreateCoredumpOnCrash.java \ -runtime/ErrorHandling/ErrorHandler.java \ @@ -280,11 +281,6 @@ tier1_runtime = \ -runtime/modules/ModuleStress/ExportModuleStressTest.java \ -runtime/modules/ModuleStress/ModuleStressGC.java \ -runtime/NMT \ - -runtime/RedefineObject/TestRedefineObject.java \ - -runtime/RedefineTests/RedefineLeak.java \ - -runtime/RedefineTests/RedefinePreviousVersions.java \ - -runtime/RedefineTests/RedefineRunningMethods.java \ - -runtime/RedefineTests/RedefineRunningMethodsWithBacktrace.java \ -runtime/ReservedStack \ -runtime/SelectionResolution/AbstractMethodErrorTest.java \ -runtime/SelectionResolution/IllegalAccessErrorTest.java \ @@ -328,6 +324,12 @@ tier1_runtime_appcds_exclude = \ tier1_serviceability = \ serviceability/dcmd/compiler \ -serviceability/dcmd/compiler/CompilerQueueTest.java \ + serviceability/jvmti/RedefineClasses \ + -serviceability/jvmti/RedefineClasses/RedefineLeak.java \ + -serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java \ + -serviceability/jvmti/RedefineClasses/RedefineRunningMethods.java \ + -serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithBacktrace.java \ + -serviceability/jvmti/RedefineClasses/TestRedefineObject.java \ serviceability/logging \ serviceability/sa \ -serviceability/sa/ClhsdbScanOops.java \ @@ -346,6 +348,7 @@ hotspot_tier2_runtime = \ runtime/ \ serviceability/ \ -runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java \ + -runtime/CompressedOops/UseCompressedOops.java \ -runtime/Thread/TestThreadDumpMonitorContention.java \ -runtime/containers/ \ -:tier1_runtime \ diff --git a/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileAbsoluteDirectoryTest.java b/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileAbsoluteDirectoryTest.java new file mode 100644 index 00000000000..c53793fd3ab --- /dev/null +++ b/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileAbsoluteDirectoryTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @requires vm.aot + * @library / /test/lib /testlibrary + * @modules java.base/jdk.internal.misc + * @build compiler.aot.cli.jaotc.CompileAbsoluteDirectoryTest + * @run driver ClassFileInstaller compiler.aot.cli.jaotc.data.HelloWorldOne + * compiler.aot.cli.jaotc.data.HelloWorldTwo + * @run driver compiler.aot.cli.jaotc.CompileAbsoluteDirectoryTest + * @summary check jaotc can compile directory with classes where directory is specified by absolute path + * @bug 8218859 + */ +package compiler.aot.cli.jaotc; + +import compiler.aot.cli.jaotc.data.HelloWorldOne; +import compiler.aot.cli.jaotc.data.HelloWorldTwo; +import java.io.File; +import jdk.test.lib.Asserts; +import jdk.test.lib.process.OutputAnalyzer; + +public class CompileAbsoluteDirectoryTest { + public static void main(String[] args) { + try { + String dir = new java.io.File(".").getAbsolutePath(); + System.out.println("Do test --directory " + dir); + OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--directory", dir); + oa.shouldHaveExitValue(0); + File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH); + Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing"); + Asserts.assertGT(compiledLibrary.length(), 0L, "Unexpected compiled library size"); + JaotcTestHelper.checkLibraryUsage(HelloWorldOne.class.getName()); + JaotcTestHelper.checkLibraryUsage(HelloWorldTwo.class.getName()); + } catch (Exception e) { + throw new Error("Can't get full path name for '.', got exception " + e, e); + } + } +} diff --git a/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileDirectoryTest.java b/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileDirectoryTest.java index aa54e675d22..57972524d10 100644 --- a/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileDirectoryTest.java +++ b/test/hotspot/jtreg/compiler/aot/cli/jaotc/CompileDirectoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ * @run driver ClassFileInstaller compiler.aot.cli.jaotc.data.HelloWorldOne * compiler.aot.cli.jaotc.data.HelloWorldTwo * @run driver compiler.aot.cli.jaotc.CompileDirectoryTest - * @summary check jaotc can compile directory with classes + * @summary check jaotc can compile directory with classes where directory is specified by relative path */ package compiler.aot.cli.jaotc; diff --git a/test/hotspot/jtreg/compiler/c1/Test8211100.java b/test/hotspot/jtreg/compiler/c1/Test8211100.java new file mode 100644 index 00000000000..1934233f038 --- /dev/null +++ b/test/hotspot/jtreg/compiler/c1/Test8211100.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8211100 + * @summary hotspot C1 issue with comparing long numbers on x86 32-bit + * + * @run main/othervm -XX:+PrintCompilation -XX:CompileOnly=compiler.c1.Test8211100::test + * -XX:CompileCommand=quiet compiler.c1.Test8211100 + */ + +package compiler.c1; + +public class Test8211100 { + private static final int ITERATIONS = 100_000; + + public static void main(String[] args) { + for (int i = 0; i < ITERATIONS; i++) { + test(4558828911L, + 4294967296L); + } + } + + private static void test(long one, long two) { + while (true) { + if (one >= two) { + break; + } + } + } +} diff --git a/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java b/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java index ace02f62254..a1339cdad30 100644 --- a/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java +++ b/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java @@ -294,7 +294,7 @@ public abstract class CiReplayBase { try { String cmd = ProcessTools.getCommandLine(ProcessTools.createJavaProcessBuilder(true, args)); return new String[]{"sh", "-c", prefix - + (Platform.isWindows() ? cmd.replace('\\', '/').replace(";", "\\;") : cmd)}; + + (Platform.isWindows() ? cmd.replace('\\', '/').replace(";", "\\;").replace("|", "\\|") : cmd)}; } catch(Throwable t) { throw new Error("Can't create process builder: " + t, t); } diff --git a/test/hotspot/jtreg/compiler/classUnloading/methodUnloading/TestOverloadCompileQueues.java b/test/hotspot/jtreg/compiler/classUnloading/methodUnloading/TestOverloadCompileQueues.java new file mode 100644 index 00000000000..32933fdb94b --- /dev/null +++ b/test/hotspot/jtreg/compiler/classUnloading/methodUnloading/TestOverloadCompileQueues.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test TestOverloadCompileQueues + * @bug 8163511 + * @summary Test overloading the C1 and C2 compile queues with tasks. + * @requires !vm.graal.enabled + * @run main/othervm -XX:-TieredCompilation -XX:CompileThreshold=2 -XX:CICompilerCount=1 + * compiler.classUnloading.methodUnloading.TestOverloadCompileQueues + * @run main/othervm -XX:TieredCompileTaskTimeout=1000 -XX:CompileThresholdScaling=0.001 -XX:CICompilerCount=2 + * compiler.classUnloading.methodUnloading.TestOverloadCompileQueues + */ + +package compiler.classUnloading.methodUnloading; + +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; + +public class TestOverloadCompileQueues { + public static final int ITERS = 500; // Increase for longer stress testing + + // Some methods to fill up the compile queue + public static void test0() { } + public static void test1() { } + public static void test2() { } + public static void test3() { } + public static void test4() { } + public static void test5() { } + public static void test6() { } + public static void test7() { } + public static void test8() { } + public static void test9() { } + public static void test10() { } + public static void test11() { } + public static void test12() { } + public static void test13() { } + public static void test14() { } + public static void test15() { } + public static void test16() { } + public static void test17() { } + public static void test18() { } + public static void test19() { } + + public static void main(String[] args) throws Throwable { + Class thisClass = TestOverloadCompileQueues.class; + ClassLoader defaultLoader = thisClass.getClassLoader(); + URL classesDir = thisClass.getProtectionDomain().getCodeSource().getLocation(); + + for (int i = 0; i < ITERS; ++i) { + // Load test class with own class loader + URLClassLoader myLoader = URLClassLoader.newInstance(new URL[] {classesDir}, defaultLoader.getParent()); + Class testClass = Class.forName(thisClass.getCanonicalName(), true, myLoader); + + // Execute all test methods to trigger compilation and fill up compile queue + for (int j = 1; j < 20; ++j) { + Method method = testClass.getDeclaredMethod("test" + j); + method.invoke(null); + method.invoke(null); + } + + // Unload dead classes from ealier iterations + System.gc(); + } + } +} diff --git a/test/jdk/vm/jit/BadLogicCode.java b/test/hotspot/jtreg/compiler/codegen/BadLogicCode.java similarity index 93% rename from test/jdk/vm/jit/BadLogicCode.java rename to test/hotspot/jtreg/compiler/codegen/BadLogicCode.java index 6de4ad5c112..70e01ab64b3 100644 --- a/test/jdk/vm/jit/BadLogicCode.java +++ b/test/hotspot/jtreg/compiler/codegen/BadLogicCode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,8 +26,11 @@ * @bug 4157675 * @summary Solaris JIT generates bad code for logic expression * @author Tom Rodriguez + * @run main compiler.codegen.BadLogicCode */ +package compiler.codegen; + public class BadLogicCode { static int values[] = {Integer.MIN_VALUE, -1, 0, 1, 4, 16, 31, 32, 33, Integer.MAX_VALUE}; diff --git a/test/jdk/vm/runtime/ShiftTest.java b/test/hotspot/jtreg/compiler/codegen/ShiftTest.java similarity index 93% rename from test/jdk/vm/runtime/ShiftTest.java rename to test/hotspot/jtreg/compiler/codegen/ShiftTest.java index 1d42b2c338f..739d2ce8c52 100644 --- a/test/jdk/vm/runtime/ShiftTest.java +++ b/test/hotspot/jtreg/compiler/codegen/ShiftTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,11 @@ * @test * @bug 4093292 * @summary Test for correct code generation by the JIT + * @run main compiler.codegen.ShiftTest */ + +package compiler.codegen; + public class ShiftTest { static final int w = 32; diff --git a/test/hotspot/jtreg/compiler/codegen/aes/TestCipherBlockChainingEncrypt.java b/test/hotspot/jtreg/compiler/codegen/aes/TestCipherBlockChainingEncrypt.java index 649135eea59..7eb2533ff7d 100644 --- a/test/hotspot/jtreg/compiler/codegen/aes/TestCipherBlockChainingEncrypt.java +++ b/test/hotspot/jtreg/compiler/codegen/aes/TestCipherBlockChainingEncrypt.java @@ -25,7 +25,12 @@ * @test * @bug 8209951 * @summary SIGBUS in com.sun.crypto.provider.CipherBlockChaining - * @run main/othervm/timeout=300 -Xbatch + * @library /test/lib / + * @build sun.hotspot.WhiteBox + * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission + * + * @run main/othervm -Xbatch + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. * compiler.codegen.aes.TestCipherBlockChainingEncrypt */ @@ -40,6 +45,10 @@ import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; +import compiler.whitebox.CompilerWhiteBoxTest; +import sun.hotspot.code.Compiler; +import jtreg.SkippedException; + public class TestCipherBlockChainingEncrypt { private static String algorithm = "PBEWithHmacSHA1AndAES_256"; private static final String PBEPASS = "Hush, it's supposed to be a secret!"; @@ -53,8 +62,11 @@ public class TestCipherBlockChainingEncrypt { private static Cipher ci; public static void main(String[] args) throws Exception { - for(int i=0; i<5_000; i++) { - if (!(new TestCipherBlockChainingEncrypt().test(args))) { + if (!Compiler.isIntrinsicAvailable(CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION, "com.sun.crypto.provider.CipherBlockChaining", "implEncrypt", byte[].class, int.class, int.class, byte[].class, int.class)) { + throw new SkippedException("Base64 intrinsic is not available"); + } + for(int i=0; i<2_000; i++) { + if (!(new TestCipherBlockChainingEncrypt().test(args))) { throw new RuntimeException("TestCipherBlockChainingEncrypt test failed"); } } diff --git a/test/jdk/com/sun/net/ssl/SSLSecurity/ComSSLContextImpl.java b/test/hotspot/jtreg/compiler/escapeAnalysis/TestGetClass.java similarity index 52% rename from test/jdk/com/sun/net/ssl/SSLSecurity/ComSSLContextImpl.java rename to test/hotspot/jtreg/compiler/escapeAnalysis/TestGetClass.java index ee5403a345c..7b2b587b2cf 100644 --- a/test/jdk/com/sun/net/ssl/SSLSecurity/ComSSLContextImpl.java +++ b/test/hotspot/jtreg/compiler/escapeAnalysis/TestGetClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,27 +21,32 @@ * questions. */ -import java.security.*; -import com.sun.net.ssl.*; +/* + * @test + * @bug 8218201 + * @summary BCEscapeAnalyzer assigns wrong escape state to getClass return value. + * @run main/othervm -XX:-TieredCompilation -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:DisableIntrinsic=_getClass + * -XX:CompileCommand=quiet -XX:CompileCommand=compileonly,compiler.escapeAnalysis.TestGetClass::test + * -XX:+PrintCompilation compiler.escapeAnalysis.TestGetClass + */ -public class ComSSLContextImpl extends SSLContextSpi { +package compiler.escapeAnalysis; - public ComSSLContextImpl() { - System.out.println("ComSSLContextImpl initialized"); +public class TestGetClass { + static Object obj = new Object(); + + public static boolean test() { + if (obj.getClass() == Object.class) { + synchronized (obj) { + return true; + } + } + return false; } - protected void engineInit(KeyManager[] km, - TrustManager[] tm, SecureRandom sr) throws KeyManagementException { - System.out.println("ComSSLContextImpl init'd"); + public static void main(String[] args) { + if (!test()) { + throw new RuntimeException("Test failed"); + } } - - protected javax.net.ssl.SSLSocketFactory engineGetSocketFactory() { - return null; - } - - protected javax.net.ssl.SSLServerSocketFactory - engineGetServerSocketFactory() { - return null; - } - } diff --git a/test/jdk/vm/jit/ExceptionInInit.java b/test/hotspot/jtreg/compiler/exceptions/ExceptionInInit.java similarity index 95% rename from test/jdk/vm/jit/ExceptionInInit.java rename to test/hotspot/jtreg/compiler/exceptions/ExceptionInInit.java index 5b5e6836cf8..55389130054 100644 --- a/test/jdk/vm/jit/ExceptionInInit.java +++ b/test/hotspot/jtreg/compiler/exceptions/ExceptionInInit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,8 +29,11 @@ * @author Tom Rodriguez * * @modules java.rmi + * @run main compiler.exceptions.ExceptionInInit */ +package compiler.exceptions; + import java.security.AccessController; import java.security.PrivilegedAction; diff --git a/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java b/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java index 5de98975fa7..4afe0c0fe56 100644 --- a/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java +++ b/test/hotspot/jtreg/compiler/gcbarriers/UnsafeIntrinsicsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ * @modules java.base/jdk.internal.misc:+open * @summary Validate barriers after Unsafe getReference, CAS and swap (GetAndSet) * @requires vm.gc.Z & !vm.graal.enabled - * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -XX:+UnlockDiagnosticVMOptions -XX:+ZUnmapBadViews -XX:ZCollectionInterval=1 -XX:-CreateCoredumpOnCrash -XX:CompileCommand=dontinline,*::mergeImpl* compiler.gcbarriers.UnsafeIntrinsicsTest + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -XX:+UnlockDiagnosticVMOptions -XX:+ZVerifyViews -XX:ZCollectionInterval=1 -XX:-CreateCoredumpOnCrash -XX:CompileCommand=dontinline,*::mergeImpl* compiler.gcbarriers.UnsafeIntrinsicsTest */ package compiler.gcbarriers; diff --git a/src/hotspot/share/classfile/dictionary.inline.hpp b/test/hotspot/jtreg/compiler/graalunit/EA9Test.java similarity index 64% rename from src/hotspot/share/classfile/dictionary.inline.hpp rename to test/hotspot/jtreg/compiler/graalunit/EA9Test.java index fa04e0a2f51..03b4a73dcaa 100644 --- a/src/hotspot/share/classfile/dictionary.inline.hpp +++ b/test/hotspot/jtreg/compiler/graalunit/EA9Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -19,21 +19,20 @@ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. - * */ -#ifndef SHARE_CLASSFILE_DICTIONARY_INLINE_HPP -#define SHARE_CLASSFILE_DICTIONARY_INLINE_HPP - -#include "classfile/dictionary.hpp" -#include "runtime/orderAccess.hpp" - -inline ProtectionDomainEntry* DictionaryEntry::pd_set_acquire() const { - return OrderAccess::load_acquire(&_pd_set); -} - -inline void DictionaryEntry::release_set_pd_set(ProtectionDomainEntry* new_head) { - OrderAccess::release_store(&_pd_set, new_head); -} - -#endif // SHARE_CLASSFILE_DICTIONARY_INLINE_HPP +/* + * @test + * @summary + * @requires vm.opt.final.EnableJVMCI == true + * + * @modules jdk.internal.vm.compiler + * + * @library /test/lib /compiler/graalunit / + * + * @build compiler.graalunit.common.GraalUnitTestLauncher + * + * @run driver jdk.test.lib.FileInstaller ../../ProblemList-graal.txt ExcludeList.txt + * + * @run main/othervm compiler.graalunit.common.GraalUnitTestLauncher -prefix org.graalvm.compiler.core.jdk9.test.ea -exclude ExcludeList.txt + */ diff --git a/test/hotspot/jtreg/compiler/graalunit/HotspotJdk9Test.java b/test/hotspot/jtreg/compiler/graalunit/HotspotJdk9Test.java new file mode 100644 index 00000000000..19e2861eae7 --- /dev/null +++ b/test/hotspot/jtreg/compiler/graalunit/HotspotJdk9Test.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary + * @requires vm.opt.final.EnableJVMCI == true + * + * @modules jdk.internal.vm.compiler + * + * @library /test/lib /compiler/graalunit / + * + * @build compiler.graalunit.common.GraalUnitTestLauncher + * + * @run driver jdk.test.lib.FileInstaller ../../ProblemList-graal.txt ExcludeList.txt + * + * @run main/othervm compiler.graalunit.common.GraalUnitTestLauncher -prefix org.graalvm.compiler.hotspot.jdk9.test -exclude ExcludeList.txt + */ diff --git a/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt b/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt index d4e99587faa..c39c36148f1 100644 --- a/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt +++ b/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt @@ -11,6 +11,7 @@ EA9 org.graalvm.compiler.core.jdk9.test.ea Debug org.graalvm.compiler.debug.test Graph org.graalvm.compiler.graph.test @requires vm.graal.enabled HotspotAmd64 org.graalvm.compiler.hotspot.amd64.test +HotspotJdk9 org.graalvm.compiler.hotspot.jdk9.test HotspotSparc org.graalvm.compiler.hotspot.sparc.test @requires vm.simpleArch == "sparcv9" HotspotLir org.graalvm.compiler.hotspot.lir.test Hotspot org.graalvm.compiler.hotspot.test diff --git a/test/hotspot/jtreg/compiler/intrinsics/math/TestFpMinMaxIntrinsics.java b/test/hotspot/jtreg/compiler/intrinsics/math/TestFpMinMaxIntrinsics.java index 9fe71a2d772..0beff7b7893 100644 --- a/test/hotspot/jtreg/compiler/intrinsics/math/TestFpMinMaxIntrinsics.java +++ b/test/hotspot/jtreg/compiler/intrinsics/math/TestFpMinMaxIntrinsics.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2018, Arm Limited. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Arm Limited. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,20 +27,31 @@ * @bug 8212043 * @summary Test compiler intrinsics of floating-point Math.min/max * - * @run main/othervm -Xint compiler.intrinsics.math.TestFpMinMaxIntrinsics + * @run main/othervm -Xint compiler.intrinsics.math.TestFpMinMaxIntrinsics sanityTests 1 * @run main/othervm -XX:+UnlockDiagnosticVMOptions * -Xcomp -XX:TieredStopAtLevel=1 * -XX:CompileOnly=java/lang/Math - * compiler.intrinsics.math.TestFpMinMaxIntrinsics + * compiler.intrinsics.math.TestFpMinMaxIntrinsics sanityTests 1 * @run main/othervm -XX:+UnlockDiagnosticVMOptions * -Xcomp -XX:-TieredCompilation * -XX:CompileOnly=java/lang/Math - * compiler.intrinsics.math.TestFpMinMaxIntrinsics + * compiler.intrinsics.math.TestFpMinMaxIntrinsics sanityTests 1 + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions + * -XX:-TieredCompilation -XX:CompileThresholdScaling=0.1 + * -XX:CompileCommand=print,compiler/intrinsics/math/TestFpMinMaxIntrinsics.*Test* + * compiler.intrinsics.math.TestFpMinMaxIntrinsics sanityTests 10000 + * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions + * -XX:-TieredCompilation -Xcomp + * -XX:CompileCommand=print,compiler/intrinsics/math/TestFpMinMaxIntrinsics.*Test* + * -XX:CompileCommand=compileonly,compiler/intrinsics/math/TestFpMinMaxIntrinsics.*Test* + * compiler.intrinsics.math.TestFpMinMaxIntrinsics reductionTests 100 */ package compiler.intrinsics.math; import java.util.Arrays; +import java.util.Random; +import java.lang.reflect.Method; public class TestFpMinMaxIntrinsics { @@ -63,63 +74,220 @@ public class TestFpMinMaxIntrinsics { private static final float[][] f_cases = { // a b min max { fPos, fPos, fPos, fPos }, + { fNeg, fNeg, fNeg, fNeg }, { fPos, fNeg, fNeg, fPos }, + { fNeg, fPos, fNeg, fPos }, + { fPosZero, fNegZero, fNegZero, fPosZero }, + { fNegZero, fPosZero, fNegZero, fPosZero }, { fNegZero, fNegZero, fNegZero, fNegZero }, + { fPos, fPosInf, fPos, fPosInf }, { fNeg, fNegInf, fNegInf, fNeg }, + { fPos, fNaN, fNaN, fNaN }, + { fNaN, fPos, fNaN, fNaN }, + { fNeg, fNaN, fNaN, fNaN }, + { fNaN, fNeg, fNaN, fNaN }, + + { fPosInf, fNaN, fNaN, fNaN }, + { fNaN, fPosInf, fNaN, fNaN }, { fNegInf, fNaN, fNaN, fNaN }, + { fNaN, fNegInf, fNaN, fNaN } }; private static final double[][] d_cases = { // a b min max { dPos, dPos, dPos, dPos }, + { dNeg, dNeg, dNeg, dNeg }, { dPos, dNeg, dNeg, dPos }, + { dNeg, dPos, dNeg, dPos }, + { dPosZero, dNegZero, dNegZero, dPosZero }, + { dNegZero, dPosZero, dNegZero, dPosZero }, { dNegZero, dNegZero, dNegZero, dNegZero }, + { dPos, dPosInf, dPos, dPosInf }, { dNeg, dNegInf, dNegInf, dNeg }, + { dPos, dNaN, dNaN, dNaN }, + { dNaN, dPos, dNaN, dNaN }, + { dNeg, dNaN, dNaN, dNaN }, + { dNaN, dNeg, dNaN, dNaN }, + + { dPosInf, dNaN, dNaN, dNaN }, + { dNaN, dPosInf, dNaN, dNaN }, { dNegInf, dNaN, dNaN, dNaN }, + { dNaN, dNegInf, dNaN, dNaN } }; private static void fTest(float[] row) { - float min = Math.min(row[0], row[1]); - float max = Math.max(row[0], row[1]); - if (Float.isNaN(min) && Float.isNaN(max) - && Float.isNaN(row[2]) && Float.isNaN(row[3])) { - // Return if all of them are NaN - return; + fCheck(row[0], row[1], Math.min(row[0], row[1]), Math.max(row[0], row[1]), row[2], row[3]); + } + + private static void fReductionTest(float[] row) { + float fmin = row[0], fmax = row[0]; + + for (int i=0; i<100; i++) { + fmin = Math.min(fmin, row[1]); + fmax = Math.max(fmax, row[1]); } - if (min != row[2] || max != row[3]) { + + fCheck(row[0], row[1], fmin, fmax, row[2], row[3]); + } + + private static void fCheck(float a, float b, float fmin, float fmax, float efmin, float efmax) { + int min = Float.floatToRawIntBits(fmin); + int max = Float.floatToRawIntBits(fmax); + int emin = Float.floatToRawIntBits(efmin); + int emax = Float.floatToRawIntBits(efmax); + + if (min != emin || max != emax) { throw new AssertionError("Unexpected result of float min/max: " + - "a = " + row[0] + ", b = " + row[1] + ", " + - "result = (" + min + ", " + max + "), " + - "expected = (" + row[2] + ", " + row[3] + ")"); + "a = " + a + ", b = " + b + ", " + + "result = (" + fmin + ", " + fmax + "), " + + "expected = (" + efmin + ", " + efmax + ")"); } } private static void dTest(double[] row) { - double min = Math.min(row[0], row[1]); - double max = Math.max(row[0], row[1]); - if (Double.isNaN(min) && Double.isNaN(max) - && Double.isNaN(row[2]) && Double.isNaN(row[3])) { - // Return if all of them are NaN - return; + dCheck(row[0], row[1], Math.min(row[0], row[1]), Math.max(row[0], row[1]), row[2], row[3]); + } + + private static void dReductionTest(double[] row) { + double dmin = row[0], dmax = row[0]; + + for (int i=0; i<100; i++) { + dmin = Math.min(dmin, row[1]); + dmax = Math.max(dmax, row[1]); } - if (min != row[2] || max != row[3]) { - throw new AssertionError("Unexpected result of double min/max" + - "a = " + row[0] + ", b = " + row[1] + ", " + - "result = (" + min + ", " + max + "), " + - "expected = (" + row[2] + ", " + row[3] + ")"); + + dCheck(row[0], row[1], dmin, dmax, row[2], row[3]); + } + + private static void dCheck(double a, double b, double dmin, double dmax, double edmin, double edmax) { + double min = Double.doubleToRawLongBits(dmin); + double max = Double.doubleToRawLongBits(dmax); + double emin = Double.doubleToRawLongBits(edmin); + double emax = Double.doubleToRawLongBits(edmax); + + if (min != emin || max != emax) { + throw new AssertionError("Unexpected result of double min/max: " + + "a = " + a + ", b = " + b + ", " + + "result = (" + dmin + ", " + dmax + "), " + + "expected = (" + edmin + ", " + edmax + ")"); } } - public static void main(String[] args) { + public static void sanityTests() { Arrays.stream(f_cases).forEach(TestFpMinMaxIntrinsics::fTest); Arrays.stream(d_cases).forEach(TestFpMinMaxIntrinsics::dTest); - System.out.println("PASS"); + } + + public static void reductionTests() { + Arrays.stream(f_cases).forEach(TestFpMinMaxIntrinsics::fReductionTest); + Arrays.stream(d_cases).forEach(TestFpMinMaxIntrinsics::dReductionTest); + } + + public static void main(String[] args) throws Exception { + Method m = TestFpMinMaxIntrinsics.class.getDeclaredMethod(args[0]); + for (int i = 0 ; i < Integer.parseInt(args[1]) ; i++) + m.invoke(null); + } + + private static final int COUNT = 1000; + private static final int LOOPS = 100; + + private static Random r = new Random(); + + private static Node[] pool = new Node[COUNT]; + + private static long time = 0; + private static long times = 0; + + public static void init() { + for (int i=0; i +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +static volatile int release_critical = 0; + +JNIEXPORT jboolean JNICALL +Java_gc_g1_TestPeriodicCollectionJNI_blockInNative(JNIEnv* env, jobject obj, jintArray dummy) { + void* native_array = (*env)->GetPrimitiveArrayCritical(env, dummy, 0); + + if (native_array == NULL) { + return JNI_FALSE; } - protected void engineInit(KeyStore ks, char[] passwd) - throws KeyStoreException { - System.out.println("JavaxKeyManagerFactoryImpl init'd"); + while (!release_critical) { +#ifdef WINDOWS + Sleep(1); +#else + usleep(1000); +#endif } - protected void engineInit(ManagerFactoryParameters spec) - throws InvalidAlgorithmParameterException { - } + (*env)->ReleasePrimitiveArrayCritical(env, dummy, native_array, 0); - protected KeyManager[] engineGetKeyManagers() { - return null; - } + return JNI_TRUE; } + +JNIEXPORT void JNICALL Java_gc_g1_TestPeriodicCollectionJNI_unblock(JNIEnv *env, jobject obj) +{ + release_critical = 1; +} + +#ifdef __cplusplus +} +#endif diff --git a/test/hotspot/jtreg/gc/shenandoah/compiler/TestMaybeNullUnsafeAccess.java b/test/hotspot/jtreg/gc/shenandoah/compiler/TestMaybeNullUnsafeAccess.java index 566f7e25989..514140f4b5e 100644 --- a/test/hotspot/jtreg/gc/shenandoah/compiler/TestMaybeNullUnsafeAccess.java +++ b/test/hotspot/jtreg/gc/shenandoah/compiler/TestMaybeNullUnsafeAccess.java @@ -28,7 +28,12 @@ * @requires vm.gc.Shenandoah * @modules java.base/jdk.internal.misc:+open * - * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:-TieredCompilation TestMaybeNullUnsafeAccess + * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:-TieredCompilation + * TestMaybeNullUnsafeAccess + * + * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:-TieredCompilation + * -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC + * TestMaybeNullUnsafeAccess * */ diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java b/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java index cb9f536db05..5315bd9078c 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Red Hat, Inc. All rights reserved. + * Copyright (c) 2017, 2019, Red Hat, Inc. All rights reserved. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as @@ -53,50 +53,6 @@ public class TestLoopMiningArguments { } public static void main(String[] args) throws Exception { - testDefaultGC(); - testShenandoah(); - } - - public static void testDefaultGC() throws Exception { - testWith("Default GC should have CLS enabled, LSM = 1000", - true, 1000); - - testWith("Default GC with +CLS should set LSM = 1", - true, 1, - "-XX:+UseCountedLoopSafepoints" - ); - - testWith("Default GC with +CLS should not override LSM>1", - true, 10, - "-XX:LoopStripMiningIter=10", - "-XX:+UseCountedLoopSafepoints" - ); - - testWith("Default GC with +CLS should not override LSM=1", - true, 1, - "-XX:LoopStripMiningIter=1", - "-XX:+UseCountedLoopSafepoints" - ); - - testWith("Default GC with +CLS should override LSM=0 to 1", - true, 1, - "-XX:LoopStripMiningIter=0", - "-XX:+UseCountedLoopSafepoints" - ); - - testWith("Default GC with -CLS should set LSM = 0", - false, 0, - "-XX:-UseCountedLoopSafepoints" - ); - - testWith("Default GC with -CLS should override LSM to 0", - false, 0, - "-XX:LoopStripMiningIter=10", - "-XX:-UseCountedLoopSafepoints" - ); - } - - public static void testShenandoah() throws Exception { testWith("Shenandoah should have CLS and LSM enabled", true, 1000, "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java index db206f81546..b7ff19dc054 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -203,7 +203,13 @@ public class TestOptionsWithRanges { allOptionsAsMap = JVMOptionsUtils.getOptionsWithRangeAsMap(origin -> (!(origin.contains("develop") || origin.contains("notproduct")))); /* - * Remove CICompilerCount from testing because currently it can hang system + * Exclude VMThreadStackSize from max range testing, because it will always exit with code 1, + * which technically passes, but really it fails, and worse yet, it produces hs_err_pid file. + */ + excludeTestMaxRange("VMThreadStackSize"); + + /* + * Exclude CICompilerCount from testing because currently it can hang system */ excludeTestMaxRange("CICompilerCount"); diff --git a/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java b/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java index 2562e669052..3a48fb09552 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java +++ b/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java @@ -45,6 +45,7 @@ public class VMDeprecatedOptions { {"MinRAMFraction", "2"}, {"InitialRAMFraction", "64"}, {"TLABStats", "false"}, + {"ThreadLocalHandshakes", "true"}, // deprecated alias flags (see also aliased_jvm_flags): {"DefaultMaxRAMFraction", "4"}, diff --git a/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java b/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java index b47674fa13b..af3e501d1ad 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java @@ -30,7 +30,7 @@ * java.management * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission - * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. UseCompressedOops + * @run main/othervm/timeout=480 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. UseCompressedOops */ import java.util.ArrayList; import java.util.Collections; diff --git a/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java b/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java index 5044708feaf..b4408b9d68c 100644 --- a/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java +++ b/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,14 +23,15 @@ /* * @test - * @bug 8151486 + * @bug 8151486 8218266 * @summary Call Class.forName() on the system classloader from a class loaded * from a custom classloader, using the current class's protection domain. * @library /test/lib + * @modules java.base/jdk.internal.misc * @build jdk.test.lib.Utils * jdk.test.lib.util.JarUtils * @build ClassForName ProtectionDomainCacheTest - * @run main/othervm/policy=test.policy -XX:+UnlockDiagnosticVMOptions -XX:VerifySubSet=dictionary -XX:+VerifyAfterGC -Xlog:gc+verify=debug,protectiondomain=trace,class+unload:gc.log -Djava.security.manager ProtectionDomainCacheTest + * @run main/othervm/policy=test.policy -Djava.security.manager ProtectionDomainCacheTest */ import java.net.URL; @@ -42,48 +43,69 @@ import java.nio.file.Paths; import java.util.List; import jdk.test.lib.Utils; import jdk.test.lib.util.JarUtils; +import java.io.File; + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; /* * Create .jar, load ClassForName from .jar using a URLClassLoader */ public class ProtectionDomainCacheTest { - private static final long TIMEOUT = (long)(5000.0 * Utils.TIMEOUT_FACTOR); - private static final String TESTCLASSES = System.getProperty("test.classes", "."); - private static final String CLASSFILENAME = "ClassForName.class"; + static class Test { + private static final long TIMEOUT = (long)(5000.0 * Utils.TIMEOUT_FACTOR); + private static final String TESTCLASSES = System.getProperty("test.classes", "."); + private static final String CLASSFILENAME = "ClassForName.class"; - // Use a new classloader to load the ClassForName class. - public static void loadAndRun(Path jarFilePath) - throws Exception { - ClassLoader classLoader = new URLClassLoader( - new URL[]{jarFilePath.toUri().toURL()}) { - @Override public String toString() { return "LeakedClassLoader"; } - }; + // Use a new classloader to load the ClassForName class. + public static void loadAndRun(Path jarFilePath) + throws Exception { + ClassLoader classLoader = new URLClassLoader( + new URL[]{jarFilePath.toUri().toURL()}) { + @Override public String toString() { return "LeakedClassLoader"; } + }; - Class loadClass = Class.forName("ClassForName", true, classLoader); - loadClass.newInstance(); + Class loadClass = Class.forName("ClassForName", true, classLoader); + loadClass.newInstance(); - System.out.println("returning : " + classLoader); + System.out.println("returning : " + classLoader); + } + + public static void main(final String[] args) throws Exception { + // Create a temporary .jar file containing ClassForName.class + Path testClassesDir = Paths.get(TESTCLASSES); + Path jarFilePath = Files.createTempFile("cfn", ".jar"); + JarUtils.createJarFile(jarFilePath, testClassesDir, CLASSFILENAME); + jarFilePath.toFile().deleteOnExit(); + + // Remove the ClassForName.class file that jtreg built, to make sure + // we're loading from the tmp .jar + Path classFile = FileSystems.getDefault().getPath(TESTCLASSES, + CLASSFILENAME); + Files.delete(classFile); + + loadAndRun(jarFilePath); + + // Give the GC a chance to unload protection domains + for (int i = 0; i < 100; i++) { + System.gc(); + } + System.out.println("All Classloaders and protection domain cache entries successfully unloaded"); + } } - public static void main(final String[] args) throws Exception { - // Create a temporary .jar file containing ClassForName.class - Path testClassesDir = Paths.get(TESTCLASSES); - Path jarFilePath = Files.createTempFile("cfn", ".jar"); - JarUtils.createJarFile(jarFilePath, testClassesDir, CLASSFILENAME); - jarFilePath.toFile().deleteOnExit(); - - // Remove the ClassForName.class file that jtreg built, to make sure - // we're loading from the tmp .jar - Path classFile = FileSystems.getDefault().getPath(TESTCLASSES, - CLASSFILENAME); - Files.delete(classFile); - - loadAndRun(jarFilePath); - - // Give the GC a chance to unload protection domains - for (int i = 0; i < 100; i++) { - System.gc(); - } - System.out.println("All Classloaders and protection domain cache entries successfully unloaded"); + public static void main(String args[]) throws Exception { + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-Djava.security.policy==" + System.getProperty("test.src") + File.separator + "test.policy", + "-Dtest.classes=" + System.getProperty("test.classes", "."), + "-XX:+UnlockDiagnosticVMOptions", + "-XX:VerifySubSet=dictionary", + "-XX:+VerifyAfterGC", + "-Xlog:gc+verify,protectiondomain=debug", + "-Djava.security.manager", + Test.class.getName()); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldContain("PD in set is not alive"); + output.shouldHaveExitValue(0); } } diff --git a/test/hotspot/jtreg/runtime/Dictionary/test.policy b/test/hotspot/jtreg/runtime/Dictionary/test.policy index 46145b9fa41..06998b8bcae 100644 --- a/test/hotspot/jtreg/runtime/Dictionary/test.policy +++ b/test/hotspot/jtreg/runtime/Dictionary/test.policy @@ -1,5 +1,5 @@ grant { - permission java.io.FilePermission "<>", "read, write, delete"; + permission java.io.FilePermission "<>", "read, write, delete, execute"; permission java.lang.RuntimePermission "createClassLoader"; permission java.lang.RuntimePermission "getClassLoader"; permission java.util.PropertyPermission "*", "read"; /* for Utils */ diff --git a/test/jdk/vm/runtime/ExplicitArithmeticCheck.java b/test/hotspot/jtreg/runtime/ErrorHandling/ExplicitArithmeticCheck.java similarity index 96% rename from test/jdk/vm/runtime/ExplicitArithmeticCheck.java rename to test/hotspot/jtreg/runtime/ErrorHandling/ExplicitArithmeticCheck.java index 970c5377094..839d8379f40 100644 --- a/test/jdk/vm/runtime/ExplicitArithmeticCheck.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ExplicitArithmeticCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java b/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java new file mode 100644 index 00000000000..dc204f564a3 --- /dev/null +++ b/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2019, SAP SE. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.*; +import jdk.test.lib.process.*; + +/* + * @test TestAbortVMOnSafepointTimeout + * @summary Check if VM can kill thread which doesn't reach safepoint. + * @bug 8219584 + * @requires vm.compiler2.enabled + * @library /test/lib + * @modules java.base/jdk.internal.misc + * java.management + */ + +public class TestAbortVMOnSafepointTimeout { + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + int result = test_loop(3); + System.out.println("This message would occur after some time with result " + result); + return; + } + + testWith(500, 500); + } + + static int test_loop(int x) { + int sum = 0; + if (x != 0) { + // Long running loop without safepoint. + for (int y = 1; y < Integer.MAX_VALUE; ++y) { + if (y % x == 0) ++sum; + } + } + return sum; + } + + public static void testWith(int sfpt_interval, int timeout_delay) throws Exception { + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+SafepointTimeout", + "-XX:+SafepointALot", + "-XX:+AbortVMOnSafepointTimeout", + "-XX:SafepointTimeoutDelay=" + timeout_delay, + "-XX:GuaranteedSafepointInterval=" + sfpt_interval, + "-XX:-TieredCompilation", + "-XX:-UseCountedLoopSafepoints", + "-XX:LoopStripMiningIter=0", + "-XX:LoopUnrollLimit=0", + "-XX:CompileCommand=compileonly,TestAbortVMOnSafepointTimeout::test_loop", + "-Xcomp", + "-XX:-CreateCoredumpOnCrash", + "-Xms64m", + "TestAbortVMOnSafepointTimeout", + "runTestLoop" + ); + + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + if (Platform.isWindows()) { + output.shouldMatch("Safepoint sync time longer than"); + } else { + output.shouldMatch("SIGILL"); + if (Platform.isLinux()) { + output.shouldMatch("(sent by kill)"); + } + output.shouldMatch("TestAbortVMOnSafepointTimeout.test_loop"); + } + output.shouldNotHaveExitValue(0); + } +} diff --git a/test/jdk/vm/runtime/MonitorCacheMaybeExpand_DeadLock.java b/test/hotspot/jtreg/runtime/Thread/MonitorCacheMaybeExpand_DeadLock.java similarity index 98% rename from test/jdk/vm/runtime/MonitorCacheMaybeExpand_DeadLock.java rename to test/hotspot/jtreg/runtime/Thread/MonitorCacheMaybeExpand_DeadLock.java index 48c7b30853d..c037dd037e5 100644 --- a/test/jdk/vm/runtime/MonitorCacheMaybeExpand_DeadLock.java +++ b/test/hotspot/jtreg/runtime/Thread/MonitorCacheMaybeExpand_DeadLock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineBasicTest.java b/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineBasicTest.java index ba1b7a258b8..b5c3c97b0df 100644 --- a/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineBasicTest.java +++ b/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineBasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,10 +24,10 @@ /* * @test - * @summary Run /runtime/RedefineTests/RedefineRunningMethods in AppCDS mode to + * @summary Run /serviceability/jvmti/RedefineClasses/RedefineRunningMethods in AppCDS mode to * make sure class redefinition works with CDS. * @requires vm.cds - * @library /test/lib /test/hotspot/jtreg/runtime/RedefineTests /test/hotspot/jtreg/runtime/appcds + * @library /test/lib /test/hotspot/jtreg/serviceability/jvmti/RedefineClasses /test/hotspot/jtreg/runtime/appcds * @modules java.compiler * java.instrument * jdk.jartool/sun.tools.jar diff --git a/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineRunningMethods_Shared.java b/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineRunningMethods_Shared.java index 7e0d81c05b4..9677a06c655 100644 --- a/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineRunningMethods_Shared.java +++ b/test/hotspot/jtreg/runtime/appcds/redefineClass/RedefineRunningMethods_Shared.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,10 +24,10 @@ /* * @test - * @summary Run /runtime/RedefineTests/RedefineRunningMethods in AppCDS mode to + * @summary Run /serviceability/jvmti/RedefineClasses/RedefineRunningMethods in AppCDS mode to * make sure class redefinition works with CDS. * @requires vm.cds - * @library /test/lib /test/hotspot/jtreg/runtime/RedefineTests /test/hotspot/jtreg/runtime/appcds + * @library /test/lib /test/hotspot/jtreg/serviceability/jvmti/RedefineClasses /test/hotspot/jtreg/runtime/appcds * @modules java.base/jdk.internal.misc * @modules java.compiler * java.instrument diff --git a/test/hotspot/jtreg/runtime/containers/docker/Dockerfile-BasicTest b/test/hotspot/jtreg/runtime/containers/docker/Dockerfile-BasicTest index 166c969289e..c275cb74595 100644 --- a/test/hotspot/jtreg/runtime/containers/docker/Dockerfile-BasicTest +++ b/test/hotspot/jtreg/runtime/containers/docker/Dockerfile-BasicTest @@ -1,4 +1,4 @@ -FROM oraclelinux:7.2 +FROM oraclelinux:7.6 MAINTAINER mikhailo.seledtsov@oracle.com COPY /jdk /jdk diff --git a/test/hotspot/jtreg/runtime/containers/docker/JfrReporter.java b/test/hotspot/jtreg/runtime/containers/docker/JfrReporter.java new file mode 100644 index 00000000000..983fb50ba0a --- /dev/null +++ b/test/hotspot/jtreg/runtime/containers/docker/JfrReporter.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.nio.file.Paths; +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingFile; + + +// This class is intended to run inside a container +public class JfrReporter { + public static final String TEST_REPORTED_CORES="TEST_REPORTED_CORES"; + public static final String TEST_REPORTED_MEMORY="TEST_REPORTED_MEMORY"; + public static final String TEST_REPORTED_PID="TEST_REPORTED_PID"; + public static final String TESTCASE_CPU="cpu"; + public static final String TESTCASE_MEMORY="memory"; + public static final String TESTCASE_PROCESS="process"; + + public static void main(String[] args) throws Exception { + String testCase = args[0]; + System.out.println("Testcase: " + testCase); + switch (testCase) { + case TESTCASE_CPU: + RecordedEvent event = testEvent("jdk.CPUInformation", "cpu.jfr"); + System.out.println(TEST_REPORTED_CORES + "=" + event.getInt("cores")); + break; + case TESTCASE_MEMORY: + event = testEvent("jdk.PhysicalMemory", "memory.jfr"); + System.out.println(TEST_REPORTED_MEMORY + "=" + event.getLong("totalSize")); + break; + case TESTCASE_PROCESS: + event = testEvent("jdk.SystemProcess", "process.jfr"); + System.out.println(TEST_REPORTED_PID + "=" + event.getString("pid")); + break; + default: + throw new IllegalArgumentException("Invalid test case"); + } + } + + private static RecordedEvent testEvent(String event, String recordingPath) throws Exception { + System.out.println("========= Testing event: " + event); + Recording r = new Recording(); + r.enable(event); + r.setDestination(Paths.get("tmp", recordingPath)); + r.start(); + r.stop(); + + RecordedEvent recordedEvent = RecordingFile.readAllEvents(r.getDestination()).get(0); + System.out.println("RecordedEvent: " + recordedEvent); + return recordedEvent; + } +} diff --git a/test/hotspot/jtreg/runtime/containers/docker/TestJFREvents.java b/test/hotspot/jtreg/runtime/containers/docker/TestJFREvents.java new file mode 100644 index 00000000000..73e6ac178fa --- /dev/null +++ b/test/hotspot/jtreg/runtime/containers/docker/TestJFREvents.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +/* + * @test + * @summary Ensure that certain JFR events return correct results for resource values + * when run inside Docker container, such as available CPU and memory. + * Also make sure that PIDs are based on value provided by container, + * not by the host system. + * @requires (docker.support & os.maxMemory >= 2g) + * @library /test/lib + * @modules java.base/jdk.internal.misc + * java.management + * jdk.jartool/sun.tools.jar + * @build JfrReporter + * @run driver TestJFREvents + */ +import jdk.test.lib.containers.docker.Common; +import jdk.test.lib.containers.docker.DockerRunOptions; +import jdk.test.lib.containers.docker.DockerTestUtils; +import jdk.test.lib.Utils; + + +public class TestJFREvents { + private static final String imageName = Common.imageName("jfr-events"); + private static final int availableCPUs = Runtime.getRuntime().availableProcessors(); + + public static void main(String[] args) throws Exception { + System.out.println("Test Environment: detected availableCPUs = " + availableCPUs); + if (!DockerTestUtils.canTestDocker()) { + return; + } + + DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker"); + + try { + // leave one CPU for system and tools, otherwise this test may be unstable + int maxNrOfAvailableCpus = availableCPUs - 1; + for (int i=1; i < maxNrOfAvailableCpus; i = i * 2) { + testCPUInfo(i, i); + } + + long MB = 1024*1024; + testMemory("200m", "" + 200*MB); + testMemory("500m", "" + 500*MB); + testMemory("1g", "" + 1024*MB); + + testProcessInfo(); + + } finally { + DockerTestUtils.removeDockerImage(imageName); + } + } + + + private static void testCPUInfo(int valueToSet, int expectedValue) throws Exception { + Common.logNewTestCase("CPUInfo: --cpus = " + valueToSet); + DockerTestUtils.dockerRunJava( + commonDockerOpts() + .addDockerOpts("--cpus=" + valueToSet) + .addClassOptions(JfrReporter.TESTCASE_CPU)) + .shouldHaveExitValue(0) + .shouldContain(JfrReporter.TEST_REPORTED_CORES); + + // The following assertion is currently disabled due to JFR reporting incorrect values. + // JFR reports values for the host system as opposed to values for the container. + // @ignore 8219999 + // .shouldContain(JfrReporter.TEST_REPORTED_CORES + "=" + expectedValue); + } + + + private static void testMemory(String valueToSet, String expectedValue) throws Exception { + Common.logNewTestCase("Memory: --memory = " + valueToSet); + DockerTestUtils.dockerRunJava( + commonDockerOpts() + .addDockerOpts("--memory=" + valueToSet) + .addClassOptions(JfrReporter.TESTCASE_MEMORY)) + .shouldHaveExitValue(0) + .shouldContain(JfrReporter.TEST_REPORTED_MEMORY + "=" + expectedValue); + } + + + private static void testProcessInfo() throws Exception { + Common.logNewTestCase("ProcessInfo"); + DockerTestUtils.dockerRunJava( + commonDockerOpts() + .addClassOptions(JfrReporter.TESTCASE_PROCESS)) + .shouldHaveExitValue(0) + .shouldContain(JfrReporter.TEST_REPORTED_PID + "=1"); + + } + + + private static DockerRunOptions commonDockerOpts() { + return new DockerRunOptions(imageName, "/jdk/bin/java", "JfrReporter") + .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/") + .addJavaOpts("-cp", "/test-classes/"); + } +} diff --git a/test/jdk/vm/runtime/WideStrictInline.java b/test/hotspot/jtreg/runtime/interpreter/WideStrictInline.java similarity index 98% rename from test/jdk/vm/runtime/WideStrictInline.java rename to test/hotspot/jtreg/runtime/interpreter/WideStrictInline.java index ae3141de109..c6fc9947380 100644 --- a/test/jdk/vm/runtime/WideStrictInline.java +++ b/test/hotspot/jtreg/runtime/interpreter/WideStrictInline.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/logging/RedefineClasses.java b/test/hotspot/jtreg/runtime/logging/RedefineClasses.java index 2bdc24df7a4..7cb2d48569d 100644 --- a/test/hotspot/jtreg/runtime/logging/RedefineClasses.java +++ b/test/hotspot/jtreg/runtime/logging/RedefineClasses.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ * @test * @bug 8197901 8209758 * @summary Redefine classes with enabling logging to verify Klass:external_name() during GC. - * @comment This test is simplified version of runtime/RedefineTests/RedefineRunningMethods.java. + * @comment This test is simplified version of serviceability/jvmti/RedefineClasses/RedefineRunningMethods.java. * @library /test/lib * @modules java.compiler * java.instrument diff --git a/test/jdk/vm/runtime/ReflectStackOverflow.java b/test/hotspot/jtreg/runtime/reflect/ReflectStackOverflow.java similarity index 96% rename from test/jdk/vm/runtime/ReflectStackOverflow.java rename to test/hotspot/jtreg/runtime/reflect/ReflectStackOverflow.java index 348f1e743ae..b1bed32eaa2 100644 --- a/test/jdk/vm/runtime/ReflectStackOverflow.java +++ b/test/hotspot/jtreg/runtime/reflect/ReflectStackOverflow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/verifier/BadSignatures.jcod b/test/hotspot/jtreg/runtime/verifier/BadSignatures.jcod new file mode 100644 index 00000000000..219689fd004 --- /dev/null +++ b/test/hotspot/jtreg/runtime/verifier/BadSignatures.jcod @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * In this case, the signature for the fieldRef for str is missing its closing ';'. + * public class BadFieldRef { + * static String str = new String("Hi"); + * public static void m(String argv[]) { + * System.out.println(str); + * } + * } +*/ +class BadFieldRef { + 0xCAFEBABE; + 0; // minor version + 57; // version + [38] { // Constant Pool + ; // first element is empty + Method #9 #21; // #1 at 0x0A + Field #22 #23; // #2 at 0x0F + Field #8 #24; // #3 at 0x14 + Method #25 #26; // #4 at 0x19 + class #27; // #5 at 0x1E + String #28; // #6 at 0x21 + Method #5 #29; // #7 at 0x24 + class #30; // #8 at 0x29 + class #31; // #9 at 0x2C + Utf8 "str"; // #10 at 0x2F + Utf8 "Ljava/lang/String"; // #11 at 0x35 // Missing closing ';' !! + Utf8 ""; // #12 at 0x4A + Utf8 "()V"; // #13 at 0x53 + Utf8 "Code"; // #14 at 0x59 + Utf8 "LineNumberTable"; // #15 at 0x60 + Utf8 "m"; // #16 at 0x72 + Utf8 "([Ljava/lang/String;)V"; // #17 at 0x76 + Utf8 ""; // #18 at 0x8F + Utf8 "SourceFile"; // #19 at 0x9A + Utf8 "BadFieldRef.java"; // #20 at 0xA7 + NameAndType #12 #13; // #21 at 0xBA + class #32; // #22 at 0xBF + NameAndType #33 #34; // #23 at 0xC2 + NameAndType #10 #11; // #24 at 0xC7 + class #35; // #25 at 0xCC + NameAndType #36 #37; // #26 at 0xCF + Utf8 "java/lang/String"; // #27 at 0xD4 + Utf8 "Hi"; // #28 at 0xE7 + NameAndType #12 #37; // #29 at 0xEC + Utf8 "BadFieldRef"; // #30 at 0xF1 + Utf8 "java/lang/Object"; // #31 at 0xFF + Utf8 "java/lang/System"; // #32 at 0x0112 + Utf8 "out"; // #33 at 0x0125 + Utf8 "Ljava/io/PrintStream;"; // #34 at 0x012B + Utf8 "java/io/PrintStream"; // #35 at 0x0143 + Utf8 "println"; // #36 at 0x0159 + Utf8 "(Ljava/lang/String;)V"; // #37 at 0x0163 + } // Constant Pool + + 0x0021; // access [ ACC_PUBLIC ACC_SUPER ] + #8;// this_cpx + #9;// super_cpx + + [0] { // Interfaces + } // Interfaces + + [1] { // fields + { // Member at 0x0185 + 0x0008; // access + #10; // name_cpx + #11; // sig_cpx + [0] { // Attributes + } // Attributes + } // Member + } // fields + + [3] { // methods + { // Member at 0x018F + 0x0001; // access + #12; // name_cpx + #13; // sig_cpx + [1] { // Attributes + Attr(#14, 29) { // Code at 0x0197 + 1; // max_stack + 1; // max_locals + Bytes[5]{ + 0x2AB70001B1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#15, 6) { // LineNumberTable at 0x01AE + [1] { // LineNumberTable + 0 1; // at 0x01BA + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member at 0x01BA + 0x0009; // access + #16; // name_cpx + #17; // sig_cpx + [1] { // Attributes + Attr(#14, 38) { // Code at 0x01C2 + 2; // max_stack + 1; // max_locals + Bytes[10]{ + 0xB20002B20003B600; + 0x04B1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#15, 10) { // LineNumberTable at 0x01DE + [2] { // LineNumberTable + 0 6; // at 0x01EA + 9 7; // at 0x01EE + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member at 0x01EE + 0x0008; // access + #18; // name_cpx + #13; // sig_cpx + [1] { // Attributes + Attr(#14, 37) { // Code at 0x01F6 + 3; // max_stack + 0; // max_locals + Bytes[13]{ + 0xBB0005591206B700; + 0x07B30003B1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#15, 6) { // LineNumberTable at 0x0215 + [1] { // LineNumberTable + 0 3; // at 0x0221 + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [1] { // Attributes + Attr(#19, 2) { // SourceFile at 0x0223 + #20; + } // end SourceFile + } // Attributes +} // end class BadFieldRef + + + +/* + * In this case, the signature for the methodRef has an illegal embedded ';'. + * public class BadMethodRef { + * public static void main(java.la;ng.String argv[]) throws Throwable { + * System.out.println(" World"); + * } + * } +*/ +class BadMethodRef { + 0xCAFEBABE; + 0; // minor version + 57; // version + [32] { // Constant Pool + ; // first element is empty + Method #6 #17; // #1 at 0x0A + Field #18 #19; // #2 at 0x0F + String #20; // #3 at 0x14 + Method #21 #22; // #4 at 0x17 + class #23; // #5 at 0x1C + class #24; // #6 at 0x1F + Utf8 ""; // #7 at 0x22 + Utf8 "()V"; // #8 at 0x2B + Utf8 "Code"; // #9 at 0x31 + Utf8 "LineNumberTable"; // #10 at 0x38 + Utf8 "main"; // #11 at 0x4A + Utf8 "([Ljava/lang/String;)V"; // #12 at 0x51 + Utf8 "Exceptions"; // #13 at 0x6A + class #25; // #14 at 0x77 + Utf8 "SourceFile"; // #15 at 0x7A + Utf8 "BadMethodRef.java"; // #16 at 0x87 + NameAndType #7 #8; // #17 at 0x9B + class #26; // #18 at 0xA0 + NameAndType #27 #28; // #19 at 0xA3 + Utf8 " World"; // #20 at 0xA8 + class #29; // #21 at 0xB1 + NameAndType #30 #31; // #22 at 0xB4 + Utf8 "BadMethodRef"; // #23 at 0xB9 + Utf8 "java/lang/Object"; // #24 at 0xC8 + Utf8 "java/lang/Throwable"; // #25 at 0xDB + Utf8 "java/lang/System"; // #26 at 0xF1 + Utf8 "out"; // #27 at 0x0104 + Utf8 "Ljava/io/PrintStream;"; // #28 at 0x010A + Utf8 "java/io/PrintStream"; // #29 at 0x0122 + Utf8 "println"; // #30 at 0x0138 + Utf8 "(Ljava/la;ng/String;)V"; // #31 at 0x0142 // Illegal "la;ng" + } // Constant Pool + + 0x0021; // access [ ACC_PUBLIC ACC_SUPER ] + #5;// this_cpx + #6;// super_cpx + + [0] { // Interfaces + } // Interfaces + + [0] { // fields + } // fields + + [2] { // methods + { // Member at 0x0166 + 0x0001; // access + #7; // name_cpx + #8; // sig_cpx + [1] { // Attributes + Attr(#9, 29) { // Code at 0x016E + 1; // max_stack + 1; // max_locals + Bytes[5]{ + 0x2AB70001B1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#10, 6) { // LineNumberTable at 0x0185 + [1] { // LineNumberTable + 0 1; // at 0x0191 + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member at 0x0191 + 0x0009; // access + #11; // name_cpx + #12; // sig_cpx + [2] { // Attributes + Attr(#9, 37) { // Code at 0x0199 + 2; // max_stack + 1; // max_locals + Bytes[9]{ + 0xB200021203B60004; + 0xB1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#10, 10) { // LineNumberTable at 0x01B4 + [2] { // LineNumberTable + 0 4; // at 0x01C0 + 8 5; // at 0x01C4 + } + } // end LineNumberTable + } // Attributes + } // end Code + ; + Attr(#13, 4) { // Exceptions at 0x01C4 + [1] { // Exceptions + #14; // at 0x01CE + } + } // end Exceptions + } // Attributes + } // Member + } // methods + + [1] { // Attributes + Attr(#15, 2) { // SourceFile at 0x01D0 + #16; + } // end SourceFile + } // Attributes +} // end class BadMethodRef + + +/* + * In this case, the signature for myMethod has an illegal embedded '['. + * public class BadMethodSig { + * public static void myMethod(Str[ing argv[]) throws Throwable { + * System.out.println(" World"); + * } + * } +*/ +class BadMethodSig { + 0xCAFEBABE; + 0; // minor version + 57; // version + [32] { // Constant Pool + ; // first element is empty + Method #6 #17; // #1 at 0x0A + Field #18 #19; // #2 at 0x0F + String #20; // #3 at 0x14 + Method #21 #22; // #4 at 0x17 + class #23; // #5 at 0x1C + class #24; // #6 at 0x1F + Utf8 ""; // #7 at 0x22 + Utf8 "()V"; // #8 at 0x2B + Utf8 "Code"; // #9 at 0x31 + Utf8 "LineNumberTable"; // #10 at 0x38 + Utf8 "myMethod"; // #11 at 0x4A + Utf8 "([Ljava/lang/Str[ing;)V"; // #12 at 0x55 // Illegal "Str[ing" + Utf8 "Exceptions"; // #13 at 0x6E + class #25; // #14 at 0x7B + Utf8 "SourceFile"; // #15 at 0x7E + Utf8 "BadMethodSig.java"; // #16 at 0x8B + NameAndType #7 #8; // #17 at 0x9F + class #26; // #18 at 0xA4 + NameAndType #27 #28; // #19 at 0xA7 + Utf8 " World"; // #20 at 0xAC + class #29; // #21 at 0xB5 + NameAndType #30 #31; // #22 at 0xB8 + Utf8 "BadMethodSig"; // #23 at 0xBD + Utf8 "java/lang/Object"; // #24 at 0xCC + Utf8 "java/lang/Throwable"; // #25 at 0xDF + Utf8 "java/lang/System"; // #26 at 0xF5 + Utf8 "out"; // #27 at 0x0108 + Utf8 "Ljava/io/PrintStream;"; // #28 at 0x010E + Utf8 "java/io/PrintStream"; // #29 at 0x0126 + Utf8 "println"; // #30 at 0x013C + Utf8 "(Ljava/lang/String;)V"; // #31 at 0x0146 + } // Constant Pool + + 0x0021; // access [ ACC_PUBLIC ACC_SUPER ] + #5;// this_cpx + #6;// super_cpx + + [0] { // Interfaces + } // Interfaces + + [0] { // fields + } // fields + + [2] { // methods + { // Member at 0x016A + 0x0001; // access + #7; // name_cpx + #8; // sig_cpx + [1] { // Attributes + Attr(#9, 29) { // Code at 0x0172 + 1; // max_stack + 1; // max_locals + Bytes[5]{ + 0x2AB70001B1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#10, 6) { // LineNumberTable at 0x0189 + [1] { // LineNumberTable + 0 1; // at 0x0195 + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member at 0x0195 + 0x0009; // access + #11; // name_cpx + #12; // sig_cpx + [2] { // Attributes + Attr(#9, 37) { // Code at 0x019D + 2; // max_stack + 1; // max_locals + Bytes[9]{ + 0xB200021203B60004; + 0xB1; + }; + [0] { // Traps + } // end Traps + [1] { // Attributes + Attr(#10, 10) { // LineNumberTable at 0x01B8 + [2] { // LineNumberTable + 0 4; // at 0x01C4 + 8 5; // at 0x01C8 + } + } // end LineNumberTable + } // Attributes + } // end Code + ; + Attr(#13, 4) { // Exceptions at 0x01C8 + [1] { // Exceptions + #14; // at 0x01D2 + } + } // end Exceptions + } // Attributes + } // Member + } // methods + + [1] { // Attributes + Attr(#15, 2) { // SourceFile at 0x01D4 + #16; + } // end SourceFile + } // Attributes +} // end class BadMethodSig diff --git a/test/hotspot/jtreg/runtime/verifier/TestSigParse.java b/test/hotspot/jtreg/runtime/verifier/TestSigParse.java new file mode 100644 index 00000000000..a570905f5b0 --- /dev/null +++ b/test/hotspot/jtreg/runtime/verifier/TestSigParse.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8129579 + * @summary Test that signatures are properly parsed when verification of local + * classes is requested but verification of remote classes is not. + * @compile BadSignatures.jcod + * @run main/othervm -XX:+BytecodeVerificationLocal -XX:-BytecodeVerificationRemote TestSigParse + */ + +public class TestSigParse { + + public static void main(String args[]) throws Throwable { + System.out.println("Regression test for bug 819579"); + + // Test a FieldRef with a bad signature. + try { + Class newClass = Class.forName("BadFieldRef"); + throw new RuntimeException("Expected ClasFormatError exception not thrown"); + } catch (java.lang.ClassFormatError e) { + String eMsg = e.getMessage(); + if (!eMsg.contains("Field") || !eMsg.contains("has illegal signature")) { + throw new RuntimeException("Unexpected exception: " + eMsg); + } + } + + // Test a MethodRef with a bad signature. + try { + Class newClass = Class.forName("BadMethodRef"); + throw new RuntimeException("Expected ClasFormatError exception not thrown"); + } catch (java.lang.ClassFormatError e) { + String eMsg = e.getMessage(); + if (!eMsg.contains("Method") || !eMsg.contains("has illegal signature")) { + throw new RuntimeException("Unexpected exception: " + eMsg); + } + } + + // Test a method in a class with a bad signature. + try { + Class newClass = Class.forName("BadMethodSig"); + throw new RuntimeException("Expected ClasFormatError exception not thrown"); + } catch (java.lang.ClassFormatError e) { + String eMsg = e.getMessage(); + if (!eMsg.contains("Class name contains illegal character")) { + throw new RuntimeException("Unexpected exception: " + eMsg); + } + } + } + +} diff --git a/test/jdk/vm/verifier/TestStaticIF.java b/test/hotspot/jtreg/runtime/verifier/TestStaticIF.java similarity index 94% rename from test/jdk/vm/verifier/TestStaticIF.java rename to test/hotspot/jtreg/runtime/verifier/TestStaticIF.java index d3c3239e816..f58b659f859 100644 --- a/test/jdk/vm/verifier/TestStaticIF.java +++ b/test/hotspot/jtreg/runtime/verifier/TestStaticIF.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/jdk/vm/verifier/VerifyProtectedConstructor.java b/test/hotspot/jtreg/runtime/verifier/VerifyProtectedConstructor.java similarity index 98% rename from test/jdk/vm/verifier/VerifyProtectedConstructor.java rename to test/hotspot/jtreg/runtime/verifier/VerifyProtectedConstructor.java index c47057581e9..9385d6fac6c 100644 --- a/test/jdk/vm/verifier/VerifyProtectedConstructor.java +++ b/test/hotspot/jtreg/runtime/verifier/VerifyProtectedConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/jdk/vm/verifier/VerifyStackForExceptionHandlers.java b/test/hotspot/jtreg/runtime/verifier/VerifyStackForExceptionHandlers.java similarity index 98% rename from test/jdk/vm/verifier/VerifyStackForExceptionHandlers.java rename to test/hotspot/jtreg/runtime/verifier/VerifyStackForExceptionHandlers.java index d3188cb9afd..f79b0fb29e2 100644 --- a/test/jdk/vm/verifier/VerifyStackForExceptionHandlers.java +++ b/test/hotspot/jtreg/runtime/verifier/VerifyStackForExceptionHandlers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTests.java b/test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTests.java similarity index 98% rename from test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTests.java rename to test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTests.java index 544f5d47a40..5037b025aa9 100644 --- a/test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTests.java +++ b/test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java b/test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java similarity index 97% rename from test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java rename to test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java index 791a1345d46..59971413eea 100644 --- a/test/jdk/vm/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java +++ b/test/hotspot/jtreg/runtime/verifier/defaultMethods/DefaultMethodRegressionTestsRun.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.cpp similarity index 77% rename from test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c rename to test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.cpp index e41e322233d..f672a143144 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.c +++ b/test/hotspot/jtreg/serviceability/jvmti/HeapMonitor/libHeapMonitorTest.cpp @@ -28,27 +28,7 @@ #include #include "jvmti.h" -#ifdef __cplusplus extern "C" { -#endif - -#ifndef JNI_ENV_ARG - -#ifdef __cplusplus -#define JNI_ENV_ARG(x) -#define JNI_ENV_ARG2(x, y) y -#define JNI_ENV_ARG3(x, y, z) y, z -#define JNI_ENV_ARG4(x, y, z, w) y, z, w -#define JNI_ENV_PTR(x) x -#else -#define JNI_ENV_ARG(x) x -#define JNI_ENV_ARG2(x, y) x, y -#define JNI_ENV_ARG3(x, y, z) x, y, z -#define JNI_ENV_ARG4(x, y, z, w) x, y, z, w -#define JNI_ENV_PTR(x) (*x) -#endif - -#endif #define TRUE 1 #define FALSE 0 @@ -92,36 +72,35 @@ typedef struct _ExpectedContentFrame { static void event_storage_lock(EventStorage* storage) { - (*jvmti)->RawMonitorEnter(jvmti, storage->storage_monitor); + jvmti->RawMonitorEnter(storage->storage_monitor); } static void event_storage_unlock(EventStorage* storage) { - (*jvmti)->RawMonitorExit(jvmti, storage->storage_monitor); + jvmti->RawMonitorExit(storage->storage_monitor); } static void event_storage_lock_compaction(EventStorage* storage) { - (*jvmti)->RawMonitorEnter(jvmti, storage->compaction_monitor); + jvmti->RawMonitorEnter(storage->compaction_monitor); } static void event_storage_unlock_compaction(EventStorage* storage) { - (*jvmti)->RawMonitorExit(jvmti, storage->compaction_monitor); + jvmti->RawMonitorExit(storage->compaction_monitor); } // Given a method and a location, this method gets the line number. static -jint get_line_number(jvmtiEnv* jvmti, jmethodID method, - jlocation location) { +jint get_line_number(jmethodID method, jlocation location) { // Read the line number table. jvmtiLineNumberEntry *table_ptr = 0; jint line_number_table_entries; int l; jlocation last_location; - int jvmti_error = (*jvmti)->GetLineNumberTable(jvmti, method, - &line_number_table_entries, - &table_ptr); + int jvmti_error = jvmti->GetLineNumberTable(method, + &line_number_table_entries, + &table_ptr); if (JVMTI_ERROR_NONE != jvmti_error) { return -1; @@ -170,21 +149,18 @@ static void print_out_frames(JNIEnv* env, ObjectTrace* trace) { } // Transform into usable information. - line_number = get_line_number(jvmti, methodid, bci); - if (JVMTI_ERROR_NONE != - (*jvmti)->GetMethodName(jvmti, methodid, &name, &signature, 0)) { + line_number = get_line_number(methodid, bci); + if (JVMTI_ERROR_NONE != jvmti->GetMethodName(methodid, &name, &signature, 0)) { fprintf(stderr, "\tUnknown method name\n"); continue; } - if (JVMTI_ERROR_NONE != - (*jvmti)->GetMethodDeclaringClass(jvmti, methodid, &declaring_class)) { + if (JVMTI_ERROR_NONE != jvmti->GetMethodDeclaringClass(methodid, &declaring_class)) { fprintf(stderr, "\tUnknown class\n"); continue; } - err = (*jvmti)->GetSourceFileName(jvmti, declaring_class, - &file_name); + err = jvmti->GetSourceFileName(declaring_class, &file_name); if (err != JVMTI_ERROR_NONE) { fprintf(stderr, "\tUnknown file\n"); continue; @@ -206,8 +182,7 @@ static void print_out_frames(JNIEnv* env, ObjectTrace* trace) { continue; } - fprintf(stderr, "\t%s%s (%s: %d)\n", - name, signature, file_name, line_number); + fprintf(stderr, "\t%s%s (%s: %d)\n", name, signature, file_name, line_number); } } @@ -240,16 +215,14 @@ static jboolean check_sample_content(JNIEnv* env, } // Transform into usable information. - line_number = get_line_number(jvmti, methodid, bci); - (*jvmti)->GetMethodName(jvmti, methodid, &name, &signature, 0); + line_number = get_line_number(methodid, bci); + jvmti->GetMethodName(methodid, &name, &signature, 0); - if (JVMTI_ERROR_NONE != - (*jvmti)->GetMethodDeclaringClass(jvmti, methodid, &declaring_class)) { + if (JVMTI_ERROR_NONE != jvmti->GetMethodDeclaringClass(methodid, &declaring_class)) { return FALSE; } - err = (*jvmti)->GetSourceFileName(jvmti, declaring_class, - &file_name); + err = jvmti->GetSourceFileName(declaring_class, &file_name); if (err != JVMTI_ERROR_NONE) { return FALSE; } @@ -303,105 +276,93 @@ static int fill_native_frames(JNIEnv* env, jobjectArray frames, const char* file_name = NULL; const char* signature = NULL; - jobject obj = JNI_ENV_PTR(env)->GetObjectArrayElement( - JNI_ENV_ARG3(env, frames, (jsize) i)); + jobject obj = env->GetObjectArrayElement(frames, (jsize) i); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetObjectArrayElement\n"); return -1; } - frame_class = JNI_ENV_PTR(env)->GetObjectClass(JNI_ENV_ARG2(env, obj)); + frame_class = env->GetObjectClass(obj); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetObjectClass\n"); return -1; } - line_number_field_id = - JNI_ENV_PTR(env)->GetFieldID(JNI_ENV_ARG4(env, frame_class, "lineNumber", "I")); + line_number_field_id = env->GetFieldID(frame_class, "lineNumber", "I"); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetFieldID\n"); return -1; } - line_number = JNI_ENV_PTR(env)->GetIntField(JNI_ENV_ARG3(env, obj, line_number_field_id)); + line_number = env->GetIntField(obj, line_number_field_id); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetIntField\n"); return -1; } - string_id = JNI_ENV_PTR(env)->GetFieldID( - JNI_ENV_ARG4(env, frame_class, "method", "Ljava/lang/String;")); + string_id = env->GetFieldID(frame_class, "method", "Ljava/lang/String;"); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetFieldID\n"); return -1; } - string_object = (jstring) JNI_ENV_PTR(env)->GetObjectField( - JNI_ENV_ARG3(env, obj, string_id)); + string_object = (jstring) env->GetObjectField(obj, string_id); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetObjectField\n"); return -1; } - method = JNI_ENV_PTR(env)->GetStringUTFChars(JNI_ENV_ARG3(env, string_object, 0)); + method = env->GetStringUTFChars(string_object, 0); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "Exception in jni GetStringUTFChars\n"); return -1; } - string_id = JNI_ENV_PTR(env)->GetFieldID( - JNI_ENV_ARG4(env, frame_class, "fileName", "Ljava/lang/String;")); + string_id = env->GetFieldID(frame_class, "fileName", "Ljava/lang/String;"); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "Exception in jni GetFieldID\n"); return -1; } - string_object = - (jstring) (JNI_ENV_PTR(env)->GetObjectField( - JNI_ENV_ARG3(env, obj, string_id))); + string_object = (jstring) (env->GetObjectField(obj, string_id)); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in second jni GetObjectField\n"); return -1; } - file_name = JNI_ENV_PTR(env)->GetStringUTFChars( - JNI_ENV_ARG3(env, string_object, 0)); + file_name = env->GetStringUTFChars(string_object, 0); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetStringUTFChars\n"); return -1; } - string_id = JNI_ENV_PTR(env)->GetFieldID( - JNI_ENV_ARG4(env, frame_class, "signature", "Ljava/lang/String;")); + string_id = env->GetFieldID(frame_class, "signature", "Ljava/lang/String;"); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in second jni GetFieldID\n"); return -1; } - string_object = - (jstring) (JNI_ENV_PTR(env)->GetObjectField( - JNI_ENV_ARG3(env, obj, string_id))); + string_object = (jstring) (env->GetObjectField(obj, string_id)); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in third jni GetObjectField\n"); return -1; } - signature = JNI_ENV_PTR(env)->GetStringUTFChars( - JNI_ENV_ARG3(env, string_object, 0)); + signature = env->GetStringUTFChars(string_object, 0); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { + if (env->ExceptionOccurred()) { fprintf(stderr, "fill_native_frames: Exception in jni GetStringUTFChars\n"); return -1; } @@ -439,7 +400,7 @@ static void event_storage_set_garbage_history(EventStorage* storage, int value) global_event_storage.garbage_history_size = value; free(global_event_storage.garbage_collected_objects); size = sizeof(*global_event_storage.garbage_collected_objects) * value; - global_event_storage.garbage_collected_objects = malloc(size); + global_event_storage.garbage_collected_objects = reinterpret_cast(malloc(size)); memset(global_event_storage.garbage_collected_objects, 0, size); event_storage_unlock(storage); } @@ -551,7 +512,7 @@ static jboolean event_storage_garbage_contains(JNIEnv* env, // No mutex here, handled by the caller. static void event_storage_augment_storage(EventStorage* storage) { int new_max = (storage->live_object_size * 2) + 1; - ObjectTrace** new_objects = malloc(new_max * sizeof(*new_objects)); + ObjectTrace** new_objects = reinterpret_cast(malloc(new_max * sizeof(*new_objects))); int current_count = storage->live_object_count; memcpy(new_objects, storage->live_objects, current_count * sizeof(*new_objects)); @@ -570,7 +531,7 @@ static void event_storage_add(EventStorage* storage, jint count; jvmtiError err; - err = (*jvmti)->GetStackTrace(jvmti, thread, 0, 64, frames, &count); + err = jvmti->GetStackTrace(thread, 0, 64, frames, &count); if (err == JVMTI_ERROR_NONE && count >= 1) { ObjectTrace* live_object; jvmtiFrameInfo* allocated_frames = (jvmtiFrameInfo*) malloc(count * sizeof(*allocated_frames)); @@ -581,11 +542,10 @@ static void event_storage_add(EventStorage* storage, live_object->frame_count = count; live_object->size = size; live_object->thread = thread; - live_object->object = (*jni)->NewWeakGlobalRef(jni, object); + live_object->object = jni->NewWeakGlobalRef(object); - if (JNI_ENV_PTR(jni)->ExceptionOccurred(JNI_ENV_ARG(jni))) { - JNI_ENV_PTR(jni)->FatalError( - JNI_ENV_ARG2(jni, "Error in event_storage_add: Exception in jni NewWeakGlobalRef")); + if (jni->ExceptionOccurred()) { + jni->FatalError("Error in event_storage_add: Exception in jni NewWeakGlobalRef"); } // Only now lock and get things done quickly. @@ -627,13 +587,13 @@ static void event_storage_compact(EventStorage* storage, JNIEnv* jni) { ObjectTrace* live_object = live_objects[i]; jweak object = live_object->object; - if (!(*jni)->IsSameObject(jni, object, NULL)) { + if (!jni->IsSameObject(object, NULL)) { if (dest != i) { live_objects[dest] = live_object; dest++; } } else { - (*jni)->DeleteWeakGlobalRef(jni, object); + jni->DeleteWeakGlobalRef(object); live_object->object = NULL; event_storage_add_garbage_collected_object(storage, live_object); @@ -735,7 +695,7 @@ Java_MyPackage_HeapMonitorThreadDisabledTest_checkThreadSamplesOnlyFrom( char* expected_name; int found_thread = FALSE; - err = (*jvmti)->GetThreadInfo(jvmti, thread, &info); + err = jvmti->GetThreadInfo(thread, &info); expected_name = info.name; if (err != JVMTI_ERROR_NONE) { @@ -763,7 +723,7 @@ static void add_thread_count(jthread thread) { jvmtiThreadInfo info; jvmtiError err; - err = (*jvmti)->GetThreadInfo(jvmti, thread, &info); + err = jvmti->GetThreadInfo(thread, &info); if (err != JVMTI_ERROR_NONE) { fprintf(stderr, "Thread info for %p failed, ignoring thread count\n", thread); @@ -789,8 +749,8 @@ JNIEXPORT void JNICALL Java_MyPackage_HeapMonitorThreadDisabledTest_enableSamplingEvents( JNIEnv* env, jclass cls, jthread thread) { fprintf(stderr, "Enabling for %p\n", thread); - check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, thread), + check_error(jvmti->SetEventNotificationMode( + JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, thread), "Set event notifications for a single thread"); } @@ -838,14 +798,14 @@ void JNICALL GarbageCollectionFinish(jvmtiEnv *jvmti_env) { } static int enable_notifications() { - if (check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL), + if (check_error(jvmti->SetEventNotificationMode( + JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL), "Set event notifications")) { return 1; } - return check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, NULL), + return check_error(jvmti->SetEventNotificationMode( + JVMTI_ENABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, NULL), "Set event notifications"); } @@ -855,16 +815,14 @@ jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { jvmtiEventCallbacks callbacks; jvmtiCapabilities caps; - res = JNI_ENV_PTR(jvm)->GetEnv(JNI_ENV_ARG3(jvm, (void **) &jvmti, - JVMTI_VERSION_9)); + res = jvm->GetEnv((void **) &jvmti, JVMTI_VERSION); if (res != JNI_OK || jvmti == NULL) { fprintf(stderr, "Error: wrong result of a valid call to GetEnv!\n"); return JNI_ERR; } // Get second jvmti environment. - res = JNI_ENV_PTR(jvm)->GetEnv(JNI_ENV_ARG3(jvm, (void **) &second_jvmti, - JVMTI_VERSION_9)); + res = jvm->GetEnv((void **) &second_jvmti, JVMTI_VERSION); if (res != JNI_OK || second_jvmti == NULL) { fprintf(stderr, "Error: wrong result of a valid second call to GetEnv!\n"); return JNI_ERR; @@ -875,14 +833,14 @@ jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { &global_event_storage, &second_global_event_storage); } - (*jvmti)->CreateRawMonitor(jvmti, "storage_monitor", + jvmti->CreateRawMonitor("storage_monitor", &global_event_storage.storage_monitor); - (*jvmti)->CreateRawMonitor(jvmti, "second_storage_monitor", + jvmti->CreateRawMonitor("second_storage_monitor", &second_global_event_storage.storage_monitor); - (*jvmti)->CreateRawMonitor(jvmti, "compaction_monitor", + jvmti->CreateRawMonitor("compaction_monitor", &global_event_storage.compaction_monitor); - (*jvmti)->CreateRawMonitor(jvmti, "second_compaction_monitor", + jvmti->CreateRawMonitor("second_compaction_monitor", &second_global_event_storage.compaction_monitor); event_storage_set_garbage_history(&global_event_storage, 200); @@ -900,12 +858,12 @@ jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { caps.can_generate_garbage_collection_events = 1; caps.can_generate_sampled_object_alloc_events = 1; caps.can_generate_vm_object_alloc_events = 1; - if (check_error((*jvmti)->AddCapabilities(jvmti, &caps), "Add capabilities")) { + if (check_error(jvmti->AddCapabilities(&caps), "Add capabilities")) { return JNI_ERR; } - if (check_error((*jvmti)->SetEventCallbacks(jvmti, &callbacks, - sizeof(jvmtiEventCallbacks)), + if (check_error(jvmti->SetEventCallbacks(&callbacks, + sizeof(jvmtiEventCallbacks)), " Set Event Callbacks")) { return JNI_ERR; } @@ -914,7 +872,7 @@ jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) { JNIEXPORT void JNICALL Java_MyPackage_HeapMonitor_setSamplingInterval(JNIEnv* env, jclass cls, jint value) { - (*jvmti)->SetHeapSamplingInterval(jvmti, value); + jvmti->SetHeapSamplingInterval(value); } JNIEXPORT jboolean JNICALL @@ -934,37 +892,32 @@ Java_MyPackage_HeapMonitor_enableSamplingEvents(JNIEnv* env, jclass cls) { JNIEXPORT void JNICALL Java_MyPackage_HeapMonitor_disableSamplingEvents(JNIEnv* env, jclass cls) { - check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_DISABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, NULL), + check_error(jvmti->SetEventNotificationMode( + JVMTI_DISABLE, JVMTI_EVENT_SAMPLED_OBJECT_ALLOC, NULL), "Set event notifications"); - check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_DISABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL), + check_error(jvmti->SetEventNotificationMode( + JVMTI_DISABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL), "Garbage Collection Finish"); } static ExpectedContentFrame *get_native_frames(JNIEnv* env, jclass cls, jobjectArray frames) { ExpectedContentFrame *native_frames; - jsize size = JNI_ENV_PTR(env)->GetArrayLength(JNI_ENV_ARG2(env, frames)); + jsize size = env->GetArrayLength(frames); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env))) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, "get_native_frames failed with the GetArrayLength call")); + if (env->ExceptionOccurred()) { + env->FatalError("get_native_frames failed with the GetArrayLength call"); } - native_frames = malloc(size * sizeof(*native_frames)); + native_frames = reinterpret_cast (malloc(size * sizeof(*native_frames))); if (native_frames == NULL) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, - "Error in get_native_frames: malloc returned NULL\n")); + env->FatalError("Error in get_native_frames: malloc returned NULL\n"); } if (fill_native_frames(env, frames, native_frames, size) != 0) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, - "Error in get_native_frames: fill_native_frames returned failed status\n")); + env->FatalError("Error in get_native_frames: fill_native_frames returned failed status\n"); } return native_frames; @@ -975,7 +928,7 @@ Java_MyPackage_HeapMonitor_obtainedEvents(JNIEnv* env, jclass cls, jobjectArray frames, jboolean check_lines) { jboolean result; - jsize size = JNI_ENV_PTR(env)->GetArrayLength(JNI_ENV_ARG2(env, frames)); + jsize size = env->GetArrayLength(frames); ExpectedContentFrame *native_frames = get_native_frames(env, cls, frames); result = event_storage_contains(env, &global_event_storage, native_frames, @@ -990,7 +943,7 @@ Java_MyPackage_HeapMonitor_garbageContains(JNIEnv* env, jclass cls, jobjectArray frames, jboolean check_lines) { jboolean result; - jsize size = JNI_ENV_PTR(env)->GetArrayLength(JNI_ENV_ARG2(env, frames)); + jsize size = env->GetArrayLength(frames); ExpectedContentFrame *native_frames = get_native_frames(env, cls, frames); result = event_storage_garbage_contains(env, &global_event_storage, @@ -1005,7 +958,7 @@ Java_MyPackage_HeapMonitor_getSize(JNIEnv* env, jclass cls, jobjectArray frames, jboolean check_lines) { jlong result = 0; - jsize size = JNI_ENV_PTR(env)->GetArrayLength(JNI_ENV_ARG2(env, frames)); + jsize size = env->GetArrayLength(frames); ExpectedContentFrame *native_frames = get_native_frames(env, cls, frames); result = event_storage_get_size(env, &global_event_storage, @@ -1017,7 +970,7 @@ Java_MyPackage_HeapMonitor_getSize(JNIEnv* env, jclass cls, JNIEXPORT void JNICALL Java_MyPackage_HeapMonitor_forceGarbageCollection(JNIEnv* env, jclass cls) { - check_error((*jvmti)->ForceGarbageCollection(jvmti), + check_error(jvmti->ForceGarbageCollection(), "Forced Garbage Collection"); } @@ -1033,12 +986,12 @@ Java_MyPackage_HeapMonitorNoCapabilityTest_allSamplingMethodsFail(JNIEnv *env, jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_generate_sampled_object_alloc_events = 1; - if (check_error((*jvmti)->RelinquishCapabilities(jvmti, &caps), + if (check_error(jvmti->RelinquishCapabilities(&caps), "Add capabilities\n")){ return FALSE; } - if (check_capability_error((*jvmti)->SetHeapSamplingInterval(jvmti, 1<<19), + if (check_capability_error(jvmti->SetHeapSamplingInterval(1<<19), "Set Heap Sampling Interval")) { return FALSE; } @@ -1048,22 +1001,22 @@ Java_MyPackage_HeapMonitorNoCapabilityTest_allSamplingMethodsFail(JNIEnv *env, JNIEXPORT jboolean JNICALL Java_MyPackage_HeapMonitorIllegalArgumentTest_testIllegalArgument(JNIEnv *env, jclass cls) { - if (check_error((*jvmti)->SetHeapSamplingInterval(jvmti, 0), + if (check_error(jvmti->SetHeapSamplingInterval(0), "Sampling interval 0 failed\n")){ return FALSE; } - if (check_error((*jvmti)->SetHeapSamplingInterval(jvmti, 1024), + if (check_error(jvmti->SetHeapSamplingInterval(1024), "Sampling interval 1024 failed\n")){ return FALSE; } - if (!check_error((*jvmti)->SetHeapSamplingInterval(jvmti, -1), + if (!check_error(jvmti->SetHeapSamplingInterval(-1), "Sampling interval -1 passed\n")){ return FALSE; } - if (!check_error((*jvmti)->SetHeapSamplingInterval(jvmti, -1024), + if (!check_error(jvmti->SetHeapSamplingInterval(-1024), "Sampling interval -1024 passed\n")){ return FALSE; } @@ -1110,7 +1063,7 @@ Java_MyPackage_HeapMonitorTwoAgentsTest_enablingSamplingInSecondaryAgent( memset(&caps, 0, sizeof(caps)); caps.can_generate_sampled_object_alloc_events = 1; - if (check_error((*second_jvmti)->AddCapabilities(second_jvmti, &caps), + if (check_error(second_jvmti->AddCapabilities(&caps), "Set the capability for second agent")) { return FALSE; } @@ -1118,8 +1071,8 @@ Java_MyPackage_HeapMonitorTwoAgentsTest_enablingSamplingInSecondaryAgent( memset(&callbacks, 0, sizeof(callbacks)); callbacks.SampledObjectAlloc = &SampledObjectAlloc2; - if (check_error((*second_jvmti)->SetEventCallbacks(second_jvmti, &callbacks, - sizeof(jvmtiEventCallbacks)), + if (check_error(second_jvmti->SetEventCallbacks(&callbacks, + sizeof(jvmtiEventCallbacks)), " Set Event Callbacks for second agent")) { return FALSE; } @@ -1129,8 +1082,8 @@ Java_MyPackage_HeapMonitorTwoAgentsTest_enablingSamplingInSecondaryAgent( JNIEXPORT void JNICALL Java_MyPackage_HeapMonitor_enableVMEvents(JNIEnv* env, jclass cls) { - check_error((*jvmti)->SetEventNotificationMode( - jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_OBJECT_ALLOC, NULL), + check_error(jvmti->SetEventNotificationMode( + JVMTI_ENABLE, JVMTI_EVENT_VM_OBJECT_ALLOC, NULL), "Set vm event notifications"); } @@ -1146,27 +1099,24 @@ Java_MyPackage_HeapMonitor_sampledEvents(JNIEnv* env, jclass cls) { static jobject allocate_object(JNIEnv* env) { // Construct an Object. - jclass cls = JNI_ENV_PTR(env)->FindClass(JNI_ENV_ARG2(env, "java/lang/Object")); + jclass cls = env->FindClass("java/lang/Object"); jmethodID constructor; jobject result; - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env)) || cls == NULL) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, "Error in jni FindClass: Cannot find Object class\n")); + if (env->ExceptionOccurred() || cls == NULL) { + env->FatalError("Error in jni FindClass: Cannot find Object class\n"); } - constructor = JNI_ENV_PTR(env)->GetMethodID(JNI_ENV_ARG4(env, cls, "", "()V")); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env)) || constructor == NULL) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, "Error in jni GetMethodID: Cannot find Object class constructor\n")); + constructor = env->GetMethodID(cls, "", "()V"); + if (env->ExceptionOccurred() || constructor == NULL) { + env->FatalError("Error in jni GetMethodID: Cannot find Object class constructor\n"); } // Call back constructor to allocate a new instance, with an int argument - result = JNI_ENV_PTR(env)->NewObject(JNI_ENV_ARG3(env, cls, constructor)); + result = env->NewObject(cls, constructor); - if (JNI_ENV_PTR(env)->ExceptionOccurred(JNI_ENV_ARG(env)) || result == NULL) { - JNI_ENV_PTR(env)->FatalError( - JNI_ENV_ARG2(env, "Error in jni NewObject: Cannot allocate an object\n")); + if (env->ExceptionOccurred() || result == NULL) { + env->FatalError("Error in jni NewObject: Cannot allocate an object\n"); } return result; } @@ -1186,7 +1136,7 @@ void JNICALL RecursiveSampledObjectAlloc(jvmtiEnv *jvmti_env, int i; for (i = 0; i < 1000; i++) { if (allocate_object(jni_env) == NULL) { - JNI_ENV_PTR(jni_env)->FatalError(JNI_ENV_ARG2(jni_env, "allocate_object returned NULL\n")); + jni_env->FatalError("allocate_object returned NULL\n"); } } @@ -1205,13 +1155,11 @@ Java_MyPackage_HeapMonitorRecursiveTest_setCallbackToCallAllocateSomeMore(JNIEnv memset(&callbacks, 0, sizeof(callbacks)); callbacks.SampledObjectAlloc = &RecursiveSampledObjectAlloc; - if (check_error((*jvmti)->SetEventCallbacks(jvmti, &callbacks, - sizeof(jvmtiEventCallbacks)), - " Set Event Callbacks")) { - JNI_ENV_PTR(env)->FatalError(JNI_ENV_ARG2(env, "Cannot reset the callback.")); + if (check_error(jvmti->SetEventCallbacks(&callbacks, + sizeof(jvmtiEventCallbacks)), + "Set Event Callbacks")) { + env->FatalError("Cannot reset the callback."); } } -#ifdef __cplusplus } -#endif diff --git a/test/hotspot/jtreg/runtime/RedefineObject/Agent.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/Agent.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineObject/Agent.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/Agent.java index b1c025da3cf..8710f718166 100644 --- a/test/hotspot/jtreg/runtime/RedefineObject/Agent.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/Agent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/ModifyAnonymous.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/ModifyAnonymous.java similarity index 99% rename from test/hotspot/jtreg/runtime/RedefineTests/ModifyAnonymous.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/ModifyAnonymous.java index a54158afc9f..496c741edb4 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/ModifyAnonymous.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/ModifyAnonymous.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineAddLambdaExpression.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAddLambdaExpression.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineAddLambdaExpression.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAddLambdaExpression.java index 62d63fc5f20..482a0c7ed1c 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineAddLambdaExpression.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAddLambdaExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineAnnotations.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAnnotations.java similarity index 99% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineAnnotations.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAnnotations.java index 0340e69d480..4516518a0c8 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineAnnotations.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineAnnotations.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineDeleteJmethod.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineDeleteJmethod.java similarity index 100% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineDeleteJmethod.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineDeleteJmethod.java diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineDoubleDelete.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineDoubleDelete.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineDoubleDelete.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineDoubleDelete.java index 64883401a40..a7cacc7f4d5 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineDoubleDelete.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineDoubleDelete.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineFinalizer.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineFinalizer.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineFinalizer.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineFinalizer.java index 6106b5a20c8..c1cc7dd820c 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineFinalizer.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineFinalizer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceCall.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceCall.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceCall.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceCall.java index d23d3abbc99..909843971bd 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceCall.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceCall.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceMethods.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceMethods.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceMethods.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceMethods.java index 8f6af6c8eea..080fe5ca02f 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceMethods.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineInterfaceMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineLeak.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineLeak.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java index cc69b203cc3..5458e058b28 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineLeak.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefinePreviousVersions.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefinePreviousVersions.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java index 1042f6b3fcd..05623dd70a1 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefinePreviousVersions.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethods.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethods.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethods.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethods.java index 4ac307ad2d7..fe66fd2de52 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethods.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithBacktrace.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithBacktrace.java similarity index 99% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithBacktrace.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithBacktrace.java index 95da49666ee..01278ffc368 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithBacktrace.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithBacktrace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithResolutionErrors.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithResolutionErrors.java similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithResolutionErrors.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithResolutionErrors.java index 3560e9472c0..ff2592eebdb 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineRunningMethodsWithResolutionErrors.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineRunningMethodsWithResolutionErrors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/RedefineSubtractLambdaExpression.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSubtractLambdaExpression.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineTests/RedefineSubtractLambdaExpression.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSubtractLambdaExpression.java index 841a54ce437..1adaa156f44 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/RedefineSubtractLambdaExpression.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSubtractLambdaExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/RetransformClassesZeroLength.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java similarity index 97% rename from test/hotspot/jtreg/serviceability/jvmti/RetransformClassesZeroLength.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java index 3d546556f1b..873c8fa5acf 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RetransformClassesZeroLength.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/TestLambdaFormRetransformation.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestLambdaFormRetransformation.java similarity index 98% rename from test/hotspot/jtreg/serviceability/jvmti/TestLambdaFormRetransformation.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestLambdaFormRetransformation.java index 5f66938b65d..7570c0cf527 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/TestLambdaFormRetransformation.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestLambdaFormRetransformation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/TestMultipleClasses.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestMultipleClasses.java similarity index 100% rename from test/hotspot/jtreg/runtime/RedefineTests/TestMultipleClasses.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestMultipleClasses.java diff --git a/test/hotspot/jtreg/runtime/RedefineObject/TestRedefineObject.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineObject.java similarity index 97% rename from test/hotspot/jtreg/runtime/RedefineObject/TestRedefineObject.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineObject.java index 7d77c1b7139..97822543883 100644 --- a/test/hotspot/jtreg/runtime/RedefineObject/TestRedefineObject.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineObject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/TestRedefineWithUnresolvedClass.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineWithUnresolvedClass.java similarity index 98% rename from test/hotspot/jtreg/serviceability/jvmti/TestRedefineWithUnresolvedClass.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineWithUnresolvedClass.java index c6a203e86bc..1f486e3ab1c 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/TestRedefineWithUnresolvedClass.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TestRedefineWithUnresolvedClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/UnresolvedClassAgent.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/UnresolvedClassAgent.java similarity index 96% rename from test/hotspot/jtreg/serviceability/jvmti/UnresolvedClassAgent.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/UnresolvedClassAgent.java index efe7b25a1aa..74c134815e1 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/UnresolvedClassAgent.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/UnresolvedClassAgent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/jvmti/UnresolvedClassAgent.mf b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/UnresolvedClassAgent.mf similarity index 100% rename from test/hotspot/jtreg/serviceability/jvmti/UnresolvedClassAgent.mf rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/UnresolvedClassAgent.mf diff --git a/test/hotspot/jtreg/runtime/RedefineObject/WalkThroughInvoke.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/WalkThroughInvoke.java similarity index 96% rename from test/hotspot/jtreg/runtime/RedefineObject/WalkThroughInvoke.java rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/WalkThroughInvoke.java index 3738dfd3c99..3dd5e832c3c 100644 --- a/test/hotspot/jtreg/runtime/RedefineObject/WalkThroughInvoke.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/WalkThroughInvoke.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/runtime/RedefineTests/libRedefineDeleteJmethod.c b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/libRedefineDeleteJmethod.c similarity index 100% rename from test/hotspot/jtreg/runtime/RedefineTests/libRedefineDeleteJmethod.c rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/libRedefineDeleteJmethod.c diff --git a/test/hotspot/jtreg/runtime/RedefineTests/libRedefineDoubleDelete.c b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/libRedefineDoubleDelete.c similarity index 98% rename from test/hotspot/jtreg/runtime/RedefineTests/libRedefineDoubleDelete.c rename to test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/libRedefineDoubleDelete.c index b5d0dc0afe6..3e9e0d25a57 100644 --- a/test/hotspot/jtreg/runtime/RedefineTests/libRedefineDoubleDelete.c +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/libRedefineDoubleDelete.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/hotspot/jtreg/serviceability/sa/ClhsdbPrintStatics.java b/test/hotspot/jtreg/serviceability/sa/ClhsdbPrintStatics.java index f7e0bf92b82..49787a1afff 100644 --- a/test/hotspot/jtreg/serviceability/sa/ClhsdbPrintStatics.java +++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbPrintStatics.java @@ -60,8 +60,7 @@ public class ClhsdbPrintStatics { "ClassLoaderDataGraph::_head", "JNIHandles::_weak_global_handles", "PerfMemory::_top", "ObjectSynchronizer::gBlockList", - "java_lang_Class::_oop_size_offset", - "CodeCache::_scavenge_root_nmethods")); + "java_lang_Class::_oop_size_offset")); expStrMap.put("printstatics SystemDictionary", List.of( "Static fields of SystemDictionary", "SystemDictionary::Class_klass_knum", diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001.java index 43f4b07719d..5bb46c42153 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,6 +62,7 @@ import java.io.*; */ public class tc10x001 { + public final static String SGL_QUIT = "quit"; public final static String UNEXPECTED_STRING = "***Unexpected exception "; @@ -299,6 +300,8 @@ public class tc10x001 { } catch (Throwable e) { complain(UNEXPECTED_STRING + e); exitStatus = Consts.TEST_FAILED; + } finally { + debugee.sendSignal(tc10x001.SGL_QUIT); // Acknowledge debugee result received. } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001/newclass/tc10x001a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001/newclass/tc10x001a.java index ad2dabd468a..86e06d03c30 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001/newclass/tc10x001a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001/newclass/tc10x001a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,6 +54,7 @@ public class tc10x001a { // brkpLineNumber // checkLastLine System.err.println("i = " + i); pipe.println("@" + i); + String instr = pipe.readln(); // Wait for debugger "quit" System.exit(Consts.TEST_PASSED + Consts.JCK_STATUS_BASE); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001a.java index e5fe3e4e571..d29f1e37d68 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/BScenarios/hotswap/tc10x001a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,6 +54,7 @@ public class tc10x001a { System.err.println("i = " + i); // brkpLineNumber // checkLastLine pipe.println("@" + i); + String instr = pipe.readln(); // Wait for debugger "quit" System.exit(Consts.TEST_PASSED + Consts.JCK_STATUS_BASE); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassExclusionFilter/exclfilter001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassExclusionFilter/exclfilter001.java index 71e1878e3b9..f591d38bbb0 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassExclusionFilter/exclfilter001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassExclusionFilter/exclfilter001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,14 +23,15 @@ package nsk.jdi.ClassUnloadRequest.addClassExclusionFilter; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jdi.*; import com.sun.jdi.*; import com.sun.jdi.event.*; import com.sun.jdi.request.*; + import java.io.*; -import java.util.*; /** * Debugger requests ClassUnloadEvent and sets class filter by calling @@ -64,7 +65,7 @@ public class exclfilter001 { private static int exitStatus; private static Log log; private static Debugee debugee; - private static int eventWaitTime; + private static long waitTime; String[] patterns = { prefix + "Sub*", @@ -88,7 +89,7 @@ public class exclfilter001 { exclfilter001 tstObj = new exclfilter001(); ArgumentHandler argHandler = new ArgumentHandler(argv); - eventWaitTime = argHandler.getWaitTime() * 60000; + waitTime = argHandler.getWaitTime(); log = new Log(out, argHandler); debugee = Debugee.prepareDebugee(argHandler, log, debugeeName); @@ -121,7 +122,7 @@ public class exclfilter001 { debugee.sendSignal(SGNL_UNLOAD); debugee.receiveExpectedSignal(SGNL_READY); - receiveEvents(eventWaitTime, patterns[i]); + receiveEvents(patterns[i]); display(""); debugee.getEventRequestManager().deleteEventRequest(request); @@ -146,19 +147,20 @@ public class exclfilter001 { return request; } - private void receiveEvents(int waitTime, String pattern) { + private void receiveEvents(String pattern) { EventSet eventSet = null; Event event; - int totalTime = waitTime; + long totalWaitTime = Utils.adjustTimeout(waitTime * 10000); + long waitTimeout = Utils.adjustTimeout(waitTime * 1000); long begin, delta; int count = 0; boolean exit = false; try { begin = System.currentTimeMillis(); - eventSet = debugee.VM().eventQueue().remove(totalTime); + eventSet = debugee.VM().eventQueue().remove(waitTimeout); delta = System.currentTimeMillis() - begin; - totalTime -= delta; + totalWaitTime -= delta; while (eventSet != null) { EventIterator eventIterator = eventSet.eventIterator(); while (eventIterator.hasNext()) { @@ -174,14 +176,14 @@ public class exclfilter001 { throw new Failure("Unexpected VMDisconnectEvent received"); } } - if (totalTime <= 0 || exit) { + if (totalWaitTime <= 0 || exit) { break; } debugee.resume(); - begin = System.currentTimeMillis(); - eventSet = debugee.VM().eventQueue().remove(totalTime); + begin = System.currentTimeMillis(); + eventSet = debugee.VM().eventQueue().remove(waitTimeout); delta = System.currentTimeMillis() - begin; - totalTime -= delta; + totalWaitTime -= delta; } } catch(InterruptedException e) { throw new Failure(e); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassFilter/filter001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassFilter/filter001.java index 8da9a0ecb14..c7ed2cbd11b 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassFilter/filter001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ClassUnloadRequest/addClassFilter/filter001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.jdi.ClassUnloadRequest.addClassFilter; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jdi.*; @@ -63,7 +64,7 @@ public class filter001 { private static int exitStatus; private static Log log; private static Debugee debugee; - private static int eventWaitTime; + private static long waitTime; String[] patterns = { prefix + "Sub*", @@ -87,7 +88,8 @@ public class filter001 { filter001 tstObj = new filter001(); ArgumentHandler argHandler = new ArgumentHandler(argv); - eventWaitTime = argHandler.getWaitTime() * 60000; + waitTime = argHandler.getWaitTime(); + log = new Log(out, argHandler); debugee = Debugee.prepareDebugee(argHandler, log, debugeeName); @@ -120,7 +122,7 @@ public class filter001 { debugee.sendSignal(SGNL_UNLOAD); debugee.receiveExpectedSignal(SGNL_READY); - receiveEvents(eventWaitTime, patterns[i]); + receiveEvents(patterns[i]); display(""); debugee.getEventRequestManager().deleteEventRequest(request); @@ -145,19 +147,20 @@ public class filter001 { return request; } - private void receiveEvents(int waitTime, String pattern) { + private void receiveEvents(String pattern) { EventSet eventSet = null; Event event; - int totalTime = waitTime; + long totalWaitTime = Utils.adjustTimeout(waitTime * 10000); + long waitTimeout = Utils.adjustTimeout(waitTime * 1000); long begin, delta; int count = 0; boolean exit = false; try { begin = System.currentTimeMillis(); - eventSet = debugee.VM().eventQueue().remove(totalTime); + eventSet = debugee.VM().eventQueue().remove(waitTimeout); delta = System.currentTimeMillis() - begin; - totalTime -= delta; + totalWaitTime -= delta; while (eventSet != null) { EventIterator eventIterator = eventSet.eventIterator(); while (eventIterator.hasNext()) { @@ -173,14 +176,14 @@ public class filter001 { throw new Failure("Unexpected VMDisconnectEvent received"); } } - if (totalTime <= 0 || exit) { + if (totalWaitTime <= 0 || exit) { break; } debugee.resume(); - begin = System.currentTimeMillis(); - eventSet = debugee.VM().eventQueue().remove(totalTime); + begin = System.currentTimeMillis(); + eventSet = debugee.VM().eventQueue().remove(waitTimeout); delta = System.currentTimeMillis() - begin; - totalTime -= delta; + totalWaitTime -= delta; } } catch(InterruptedException e) { throw new Failure(e); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/_itself_/event001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/_itself_/event001.java index 836bf01e988..4453127ed96 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/_itself_/event001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Event/_itself_/event001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,7 @@ import java.util.Iterator; import java.util.List; import java.io.*; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -234,7 +235,7 @@ public class event001 { // wait for a requested event try { - gotEvent.wait(argHandler.getWaitTime()*60000); + gotEvent.wait(Utils.adjustTimeout(argHandler.getWaitTime()*1000)); } catch (InterruptedException e) { log.complain("TEST FAILURE: waiting for a requested AccessWatchpointEvent #" + i + ": caught " + e); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004.java index 7f58fde7e14..ecea5e29b6e 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.jdi.EventQueue.remove; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -67,7 +68,7 @@ import java.io.*; *
    * The check includes two steps.
    * In first one, second thread waits for any incoming event from the
    - * debugger which is sleeping for "WAITTIME*90 seconds"; hence,
    + * debugger which is sleeping for some time; hence,
    * no events are expected to be received at the debugger end.
    * In second, second thread is interrupted, and the debugger waits for
    * a breakpoint event after the debuggee finishes sleeping.
    @@ -130,7 +131,7 @@ public class remove004 { static Debugee debuggee; static ArgumentHandler argsHandler; - static int waitTime; + static long waitTime; static VirtualMachine vm = null; static EventRequestManager eventRManager = null; @@ -140,6 +141,8 @@ public class remove004 { static ReferenceType debuggeeClass = null; + static Value trueValue; + static int testExitCode = PASSED; class JDITestRuntimeException extends RuntimeException { @@ -156,7 +159,7 @@ public class remove004 { logHandler = new Log(out, argsHandler); Binder binder = new Binder(argsHandler, logHandler); - waitTime = argsHandler.getWaitTime() * 60000; + waitTime = Utils.adjustTimeout(argsHandler.getWaitTime() * 1000); try { log2("launching a debuggee :"); @@ -285,6 +288,8 @@ public class remove004 { if (!debuggeeClass.name().equals(debuggeeName)) throw new JDITestRuntimeException("** Unexpected ClassName for ClassPrepareEvent **"); + trueValue = debuggeeClass.getValue(debuggeeClass.fieldByName("BOOLEAN_TRUE_VALUE")); + log2(" received: ClassPrepareEvent for debuggeeClass"); String bPointMethod = "methodForCommunication"; @@ -356,11 +361,11 @@ public class remove004 { thread2.interrupt(); for (int i2 = 0; i2 < waitTime; ) { - waitObj.wait(10000); + waitObj.wait(1000); if (!thread2.isAlive()) { break; } - i2 += 10000; + i2 += 1000; } if (thread2.isAlive()) { log3("ERROR: thread2 is still alive"); @@ -508,9 +513,17 @@ public class remove004 { log2("-----t2: eventSet = eventQueue.remove(); expects: InterruptedException"); eventSet = eventQueue.remove(); throw new JDITestRuntimeException("** return from eventQueue.remove(); **"); - } catch ( InterruptedException e1) { + } catch (InterruptedException e1) { log2("-----t2: InterruptedException"); - } catch ( Exception e ) { + // Signal to debuggee to stop sleeping + try { + ((ClassType) debuggeeClass).setValue(debuggeeClass.fieldByName("stopSleeping"), + trueValue); + } catch (InvalidTypeException | ClassNotLoadedException e) { + log3("ERROR: -----t2: Exception : " + e); + testExitCode = FAILED; + } + } catch (Exception e) { log3("ERROR: -----t2: Exception : " + e); testExitCode = FAILED; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004a.java index 1d5c3d2f1c9..f630835348e 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove/remove004a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.jdi.EventQueue.remove; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -63,6 +64,12 @@ public class remove004a { static int lineForComm = 2; + // Used for communication between debugger and debuggee + static volatile boolean stopSleeping = false; + + // Used by debugger to set stopSleeping flag to true + static final boolean BOOLEAN_TRUE_VALUE = true; + private static void methodForCommunication() { int i1 = instruction; int i2 = i1; @@ -97,10 +104,12 @@ public class remove004a { log1("before: methodForCommunication();"); methodForCommunication(); log1("before: Thread.sleep"); - try { - Thread.sleep(argHandler.getWaitTime()*90000); - } catch (InterruptedException e) { - } + Utils.waitForCondition( + () -> { + return stopSleeping; + }, + Utils.adjustTimeout(argHandler.getWaitTime() * 10000), + 100); log1("after: Thread.sleep"); break ; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004.java index d924cfe5cb7..64fad54af18 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.jdi.EventQueue.remove_l; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -30,7 +31,6 @@ import nsk.share.jdi.*; import com.sun.jdi.*; import com.sun.jdi.event.*; import com.sun.jdi.request.*; - import java.util.*; import java.io.*; @@ -63,8 +63,8 @@ import java.io.*; * to be suspended and to inform the debugger with the event.
    * The case for testing consists of of two steps.
    * In the first one the first assertion is checked up on as follows:
    - * the debugger sleeps for "WAITTIME * 90 sec";
    - * hence, no event is expected in the debugger within WAITTINE, and
    + * the debugger sleeps for some time;
    + * hence, no event is expected in the debugger within WAITTIME, and
    * debugger's method breakpointForCommunication() should get null.
    * After WAITTIME, the debugger just expects to get normal breakpoint event.
    */ @@ -126,7 +126,7 @@ public class remove_l004 { static Debugee debuggee; static ArgumentHandler argsHandler; - static int waitTime; + static long waitTime; static VirtualMachine vm = null; static EventRequestManager eventRManager = null; @@ -136,6 +136,8 @@ public class remove_l004 { static ReferenceType debuggeeClass = null; + static Value trueValue; + static int testExitCode = PASSED; class JDITestRuntimeException extends RuntimeException { @@ -152,7 +154,7 @@ public class remove_l004 { logHandler = new Log(out, argsHandler); Binder binder = new Binder(argsHandler, logHandler); - waitTime = argsHandler.getWaitTime() * 60000; + waitTime = Utils.adjustTimeout(argsHandler.getWaitTime() * 1000); try { log2("launching a debuggee :"); @@ -281,6 +283,8 @@ public class remove_l004 { if (!debuggeeClass.name().equals(debuggeeName)) throw new JDITestRuntimeException("** Unexpected ClassName for ClassPrepareEvent **"); + trueValue = debuggeeClass.getValue(debuggeeClass.fieldByName("BOOLEAN_TRUE_VALUE")); + log2(" received: ClassPrepareEvent for debuggeeClass"); String bPointMethod = "methodForCommunication"; @@ -326,6 +330,11 @@ public class remove_l004 { testExitCode = FAILED; throw new JDITestRuntimeException("** unexpected Exception **"); } + + // Signal to debuggee to stop sleeping + ((ClassType) debuggeeClass).setValue(debuggeeClass.fieldByName("stopSleeping"), + trueValue); + } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004a.java index 8c0e2c3f032..2d940208128 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/EventQueue/remove_l/remove_l004a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.jdi.EventQueue.remove_l; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -63,6 +64,12 @@ public class remove_l004a { static int lineForComm = 2; + // Used for communication between debugger and debuggee + static volatile boolean stopSleeping = false; + + // Used by debugger to set stopSleeping flag to true + static final boolean BOOLEAN_TRUE_VALUE = true; + private static void methodForCommunication() { int i1 = instruction; int i2 = i1; @@ -97,10 +104,12 @@ public class remove_l004a { log1("before: methodForCommunication();"); methodForCommunication(); log1("before: Thread.sleep"); - try { - Thread.sleep(argHandler.getWaitTime()*90000); - } catch (InterruptedException e) { - } + Utils.waitForCondition( + () -> { + return stopSleeping; + }, + Utils.adjustTimeout(argHandler.getWaitTime() * 10000), + 100); log1("after: Thread.sleep"); break ; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/isSuspended/issuspended002a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/isSuspended/issuspended002a.java index 25a50e0ed2a..fbcc366caa5 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/isSuspended/issuspended002a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/isSuspended/issuspended002a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,8 +63,8 @@ public class issuspended002a { public static void main (String argv[]) { - for (int i=0; icom.sun.jdi.VirtualMachine.allThreads()
    * complies with the its spec.
    *
    - * The test checks up the reasults of the method when
    + * The test checks up the results of the method when
    * it is invoked two times in raw immediately after
    * new thread has been started in the debuggee VM.
    *
    @@ -192,11 +192,15 @@ public class allthreads001 { String threadName = "testedThread"; + // Suspend VM to ensure no new background thread (e.g. JVMCI + // compiler thread) is started between two allThreads() calls. + vm.suspend(); List allThreads1 = vm.allThreads(); log2("allThreads1.size() = " + allThreads1.size()); List allThreads2 = vm.allThreads(); log2("allThreads2.size() = " + allThreads2.size()); + vm.resume(); if ( allThreads1.size() != allThreads2.size() ) { log3("ERROR: allThreads1.size() != allThreads2.size()"); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002.java index 90f9651c999..7f745cad44f 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002.java @@ -23,6 +23,7 @@ package nsk.jdi.VirtualMachine.dispose; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -272,29 +273,29 @@ public class dispose002 { if (expresult != returnCode0) break label1; - log2(" Thread.sleep(waitTime*60000);"); - try { - Thread.sleep(waitTime*60000); - } catch ( InterruptedException e ) { - log3("ERROR: InterruptedException"); - expresult = returnCode1; - break label1; - } + log2(" Waiting for thread2 is not alive"); - log2("......sending to the debuggee: 'check_alive'"); - log2(" expected reply: 'not_alive'"); - pipe.println("check_alive"); - line = pipe.readln(); - if (line.equals("alive")) { - log3("ERROR: thread2 is alive"); - expresult = returnCode1; - } else if (line.equals("not_alive")) { - log2(" thread2 is not alive"); - } else { - log3("ERROR: unexpected reply: " + line); - expresult = returnCode4; - } + Utils.waitForCondition( + () -> { + log2("......sending to the debuggee: 'check_alive'"); + log2(" expected reply: 'not_alive'"); + pipe.println("check_alive"); + String reply = pipe.readln(); + if (reply.equals("alive")) { + log3("ERROR: thread2 is alive"); + return false; + } else if (reply.equals("not_alive")) { + log2(" thread2 is not alive"); + return true; + } else { + log3("ERROR: unexpected reply: " + reply); + throw new RuntimeException("ERROR: unexpected reply: " + reply); + } + }, + Utils.adjustTimeout(waitTime * 60000), + 1000); + pipe.println("check_done"); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002a.java index 52469ccc636..00f441770ee 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose002a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -125,18 +125,26 @@ public class dispose002a { } } log1("mainThread is out of: synchronized (lockingObject)"); - - instruction = pipe.readln(); - if (!instruction.equals("check_alive")) { - logErr("ERROR: unexpected instruction: " + instruction); - exitCode = FAILED; - } else { - log1("checking on: thread2.isAlive"); - if (test_thread.isAlive()) { - pipe.println("alive"); - test_thread.interrupt(); + while (true) { + instruction = pipe.readln(); + if (instruction.equals("check_done")) { + if (test_thread.isAlive()) { + logErr("ERROR: thread thread2 is still alive"); + exitCode = FAILED; + } + break; + } else if (instruction.equals("check_alive")) { + log1("checking on: thread2.isAlive"); + if (test_thread.isAlive()) { + pipe.println("alive"); + test_thread.interrupt(); + } else { + pipe.println("not_alive"); + } } else { - pipe.println("not_alive"); + logErr("ERROR: unexpected instruction: " + instruction); + exitCode = FAILED; + break; } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003.java index 855ea9634e1..06a06961877 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003.java @@ -23,6 +23,7 @@ package nsk.jdi.VirtualMachine.dispose; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -179,6 +180,7 @@ public class dispose003 { int expresult = returnCode0; + String threadName = "testedThread"; List allThreads = null; @@ -236,28 +238,28 @@ public class dispose003 { if (expresult != returnCode0) break label1; - log2(" Thread.sleep(waitTime*60000);"); - try { - Thread.sleep(waitTime*60000); - } catch ( InterruptedException e ) { - log3("ERROR: InterruptedException"); - expresult = returnCode1; - break label1; - } + log2(" Waiting for thread2 is not alive"); - log2("......sending to the debuggee: 'check_alive'"); - log2(" expected reply: 'not_alive'"); - pipe.println("check_alive"); - line = pipe.readln(); - if (line.equals("alive")) { - log3("ERROR: thread2 is alive"); - expresult = returnCode1; - } else if (line.equals("not_alive")) { - log2(" thread2 is not alive"); - } else { - log3("ERROR: unexpected reply: " + line); - expresult = returnCode4; - } + Utils.waitForCondition( + () -> { + log2("......sending to the debuggee: 'check_alive'"); + log2(" expected reply: 'not_alive'"); + pipe.println("check_alive"); + String reply = pipe.readln(); + if (reply.equals("alive")) { + log3("ERROR: thread2 is alive"); + return false; + } else if (reply.equals("not_alive")) { + log2(" thread2 is not alive"); + return true; + } else { + log3("ERROR: unexpected reply: " + reply); + throw new RuntimeException("ERROR: unexpected reply: " + reply); + } + }, + Utils.adjustTimeout(waitTime * 60000), + 1000); + pipe.println("check_done"); } @@ -287,4 +289,6 @@ public class dispose003 { } return testExitCode; } + + } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003a.java index 39c491b6fbc..71fcd3ee435 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose003a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -126,17 +126,26 @@ public class dispose003a { } log1("mainThread is out of: synchronized (lockingObject)"); - instruction = pipe.readln(); - if (!instruction.equals("check_alive")) { - logErr("ERROR: unexpected instruction: " + instruction); - exitCode = FAILED; - } else { - log1("checking on: thread2.isAlive"); - if (test_thread.isAlive()) { - test_thread.resume(); - pipe.println("alive"); + while (true) { + instruction = pipe.readln(); + if (instruction.equals("check_done")) { + if (test_thread.isAlive()) { + logErr("ERROR: thread2 thread is still alive"); + exitCode = FAILED; + } + break; + } else if (instruction.equals("check_alive")) { + log1("checking on: thread2.isAlive"); + if (test_thread.isAlive()) { + test_thread.resume(); + pipe.println("alive"); + } else { + pipe.println("not_alive"); + } } else { - pipe.println("not_alive"); + logErr("ERROR: unexpected instruction: " + instruction); + exitCode = FAILED; + break; } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004.java index 3604a0ee822..ed9716fed03 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004.java @@ -23,6 +23,7 @@ package nsk.jdi.VirtualMachine.dispose; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -261,29 +262,30 @@ public class dispose004 { if (expresult != returnCode0) break label1; - log2(" Thread.sleep(waitTime*60000);"); - try { - Thread.sleep(waitTime*60000); - } catch ( InterruptedException e ) { - log3("ERROR: InterruptedException"); - expresult = returnCode1; - break label1; - } + log2(" Waiting for thread2 is not alive"); - log2("......sending to the debuggee: 'check_alive'"); - log2(" expected reply: 'not_alive'"); - pipe.println("check_alive"); - line = pipe.readln(); - if (line.equals("alive")) { - log3("ERROR: thread2 is alive"); - expresult = returnCode1; - } else if (line.equals("not_alive")) { - log2(" thread2 is not alive"); - } else { - log3("ERROR: unexpected reply: " + line); - expresult = returnCode4; - } + Utils.waitForCondition( + () -> { + log2("......sending to the debuggee: 'check_alive'"); + log2(" expected reply: 'not_alive'"); + pipe.println("check_alive"); + String reply = pipe.readln(); + if (reply.equals("alive")) { + log3("ERROR: thread2 is alive"); + return false; + } else if (reply.equals("not_alive")) { + log2(" thread2 is not alive"); + return true; + } else { + log3("ERROR: unexpected reply: " + reply); + throw new RuntimeException("ERROR: unexpected reply: " + reply); + } + }, + Utils.adjustTimeout(waitTime * 60000), + 1000); + + pipe.println("check_done"); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004a.java index 46aa79d58d4..6bd5fa04dec 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004a.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/dispose/dispose004a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,18 +127,26 @@ public class dispose004a { } } log1("mainThread is out of: synchronized (lockingObject)"); - - instruction = pipe.readln(); - if (!instruction.equals("check_alive")) { - logErr("ERROR: unexpected instruction: " + instruction); - exitCode = FAILED; - } else { - log1("checking on: thread2.isAlive"); - if (test_thread.isAlive()) { - test_thread.resume(); - pipe.println("alive"); + while (true) { + instruction = pipe.readln(); + if (instruction.equals("check_done")) { + if (test_thread.isAlive()) { + logErr("thread thread2 is still alive"); + exitCode = FAILED; + } + break; + } else if (instruction.equals("check_alive")) { + log1("checking on: thread2.isAlive"); + if (test_thread.isAlive()) { + test_thread.resume(); + pipe.println("alive"); + } else { + pipe.println("not_alive"); + } } else { - pipe.println("not_alive"); + logErr("ERROR: unexpected instruction: " + instruction); + exitCode = FAILED; + break; } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/suspend/suspend001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/suspend/suspend001.java index b03b8b89fb5..b68fb3db190 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/suspend/suspend001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/suspend/suspend001.java @@ -23,6 +23,7 @@ package nsk.jdi.VirtualMachine.suspend; +import jdk.test.lib.Utils; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; @@ -318,9 +319,10 @@ public class suspend001 { eventSet1.resume(); eventSet.resume(); - log2(" before: Thread.sleep(waitTime*60000);"); + log2(" before: Thread.sleep(waitTime*1000);"); + try { - Thread.sleep(waitTime*60000); + Thread.sleep(Utils.adjustTimeout(waitTime*1000)); } catch ( InterruptedException e ) { log3("ERROR: InterruptedException"); expresult = returnCode1; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWait/monitorwait001/monitorwait001.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWait/monitorwait001/monitorwait001.cpp index 0313ca59319..958c3afbd57 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWait/monitorwait001/monitorwait001.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWait/monitorwait001/monitorwait001.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -147,10 +147,6 @@ static int clean() { jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_MONITOR_WAIT, NULL))) nsk_jvmti_setFailStatus(); - /* dispose global references */ - jni->DeleteGlobalRef(object); - jni->DeleteGlobalRef(thread); - return NSK_TRUE; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWaited/monitorwaited001/monitorwaited001.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWaited/monitorwaited001/monitorwaited001.cpp index c7237f43961..704b8382540 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWaited/monitorwaited001/monitorwaited001.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/MonitorWaited/monitorwaited001/monitorwaited001.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -148,10 +148,6 @@ static int clean() { jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_MONITOR_WAITED, NULL))) nsk_jvmti_setFailStatus(); - /* dispose global references */ - jni->DeleteGlobalRef(object); - jni->DeleteGlobalRef(thread); - return NSK_TRUE; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp index 84978a09f47..4f6a01a7009 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP02/sp02t003/sp02t003.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -275,7 +275,6 @@ static int checkThreads(int suspended, const char* kind) { jint frameCount = 0; jint frameStackSize = 0; jvmtiFrameInfo frameStack[MAX_STACK_SIZE]; - int commonDepth = 0; int found = 0; int j; @@ -296,12 +295,8 @@ static int checkThreads(int suspended, const char* kind) { } NSK_DISPLAY1(" stack depth: %d\n", (int)frameStackSize); - commonDepth = (frameCount < frameStackSize ? frameCount : frameStackSize); - NSK_DISPLAY1(" common: %d\n", (int)commonDepth); - - /* check first commonDepth frames and find expected method there */ found = 0; - for (j = 0; j < commonDepth; j++) { + for (j = 0; j < frameStackSize; j++) { jmethodID qMethod = (jmethodID)NULL; jlocation qLocation = NSK_JVMTI_INVALID_JLOCATION; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp index 1e6768ed89d..a578f8e9ce8 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/sampling/SP06/sp06t003/sp06t003.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -295,7 +295,6 @@ static int checkThreads(int suspended, const char* kind0) { jint frameCount = 0; jint frameStackSize = 0; jvmtiFrameInfo frameStack[MAX_STACK_SIZE]; - int commonDepth = 0; int found = 0; int j; @@ -319,12 +318,8 @@ static int checkThreads(int suspended, const char* kind0) { } NSK_DISPLAY1(" stack depth: %d\n", (int)frameStackSize); - commonDepth = (frameCount < frameStackSize ? frameCount : frameStackSize); - NSK_DISPLAY1(" common: %d\n", (int)commonDepth); - - /* check first commonDepth frames and find expected method there */ found = 0; - for (j = 0; j < commonDepth; j++) { + for (j = 0; j < frameStackSize; j++) { jmethodID qMethod = (jmethodID)NULL; jlocation qLocation = NSK_JVMTI_INVALID_JLOCATION; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/jvmti_tools.cpp b/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/jvmti_tools.cpp index a643e05f826..404b1001956 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/jvmti_tools.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/jvmti_tools.cpp @@ -584,6 +584,10 @@ void nsk_jvmti_agentFailed() { int isThreadExpected(jvmtiEnv *jvmti, jthread thread) { static const char *vm_jfr_buffer_thread_name = "VM JFR Buffer Thread"; static const char *jfr_request_timer_thread_name = "JFR request timer"; + static const char *graal_management_bean_registration_thread_name = + "HotSpotGraalManagement Bean Registration"; + static const char *graal_compiler_thread_name_prefix = "JVMCI CompilerThread"; + static const size_t prefixLength = strlen(graal_compiler_thread_name_prefix); jvmtiThreadInfo threadinfo; NSK_JVMTI_VERIFY(jvmti->GetThreadInfo(thread, &threadinfo)); @@ -594,6 +598,13 @@ int isThreadExpected(jvmtiEnv *jvmti, jthread thread) { if (strcmp(threadinfo.name, jfr_request_timer_thread_name) == 0) return 0; + if (strcmp(threadinfo.name, graal_management_bean_registration_thread_name) == 0) + return 0; + + if ((strlen(threadinfo.name) > prefixLength) && + strncmp(threadinfo.name, graal_compiler_thread_name_prefix, prefixLength) == 0) + return 0; + return 1; } diff --git a/test/jaxp/TEST.ROOT b/test/jaxp/TEST.ROOT index f5754d7b155..e9525b912b3 100644 --- a/test/jaxp/TEST.ROOT +++ b/test/jaxp/TEST.ROOT @@ -23,7 +23,7 @@ modules=java.xml groups=TEST.groups # Minimum jtreg version -requiredVersion=4.2 b14 +requiredVersion=4.2 b13 # Path to libraries in the topmost test directory. This is needed so @library # does not need ../../ notation to reach them diff --git a/test/jaxp/javax/xml/jaxp/unittest/transform/OutputPropertiesTest.java b/test/jaxp/javax/xml/jaxp/unittest/transform/OutputPropertiesTest.java new file mode 100644 index 00000000000..1361dec2525 --- /dev/null +++ b/test/jaxp/javax/xml/jaxp/unittest/transform/OutputPropertiesTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package transform; + +import java.io.StringReader; +import java.util.Properties; +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamSource; +import org.testng.Assert; +import org.testng.annotations.Test; + +/* + * @test + * @bug 8219705 + * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest + * @run testng transform.OutputPropertiesTest + * @summary Verifies the output properties are set correctly + */ +public class OutputPropertiesTest { + @Test + public void testOutputProperties() throws Exception { + String xslData = "" + + "\n" + + " \n" + + " \n" + + " Hello World! \n" + + " \n" + + ""; + + System.out.println(xslData); + + Templates templates = TransformerFactory.newInstance() + .newTemplates(new StreamSource(new StringReader(xslData))); + + Properties properties = templates.getOutputProperties(); + String[] prNames = new String[]{"method", "version", "indent", "media-type"}; + String[] prValues = new String[]{"html", "4.0", "yes", "text/html"}; + + for (int i = 0; i < prNames.length; i++) { + String value = properties.getProperty(prNames[i]); + String msg = "The value of the property '" + prNames[i] + "' should be '" + + prValues[i] + "' when the method is '" + prValues[0] + "'. \n"; + Assert.assertEquals(value, prValues[i], msg); + System.out.println( + prNames[i] + ": actual: " + value + ", expected: " + prValues[i]); + } + } +} diff --git a/test/jdk/TEST.ROOT b/test/jdk/TEST.ROOT index 642eb5e4f64..f83470ce28a 100644 --- a/test/jdk/TEST.ROOT +++ b/test/jdk/TEST.ROOT @@ -22,7 +22,9 @@ com/apple/laf com/sun/java/accessibility com/sun/java/swing sanity/client demo/j javax/management sun/awt sun/java2d javax/xml/jaxp/testng/validation java/lang/ProcessHandle # Tests that cannot run concurrently -exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi java/util/stream java/util/Arrays/largeMemory java/util/BitSet/stream javax/rmi sanity/client +exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd \ +sun/security/mscapi java/util/stream java/util/Arrays/largeMemory java/util/BitSet/stream javax/rmi + # Group definitions groups=TEST.groups @@ -42,6 +44,7 @@ requires.properties= \ vm.compiler1.enabled \ vm.compiler2.enabled \ vm.cds \ + vm.debug \ vm.hasSA \ vm.hasSAandCanAttach \ vm.hasJFR \ diff --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups index 9bb5f7b6fb5..cfbcd19f492 100644 --- a/test/jdk/TEST.groups +++ b/test/jdk/TEST.groups @@ -1,4 +1,4 @@ -# Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -103,8 +103,7 @@ jdk_lang = \ jdk/internal/ref \ jdk/internal/jimage \ jdk/internal/math \ - jdk/modules \ - vm + jdk/modules # All of the java.util package jdk_util = \ @@ -214,8 +213,7 @@ jdk_security3 = \ sun/security \ -sun/security/krb5 \ -sun/security/jgss \ - javax/net \ - com/sun/net/ssl + javax/net jdk_security4 = \ com/sun/security/jgss \ diff --git a/test/jdk/com/sun/crypto/provider/Cipher/AEAD/GCMLargeDataKAT.java b/test/jdk/com/sun/crypto/provider/Cipher/AEAD/GCMLargeDataKAT.java new file mode 100644 index 00000000000..11efb2d0611 --- /dev/null +++ b/test/jdk/com/sun/crypto/provider/Cipher/AEAD/GCMLargeDataKAT.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.MessageDigest; +import java.util.HashMap; + +/* + * @test + * @bug 8220165 + * @summary Verify correctness of large data sizes for GCM. + */ + +/** + * This test stores the MD5 hash of correctly encrypted AES/GCM data for + * particular data lengths. Those lengths are run on SunJCE to verify returns + * the same MD5 hash of the encrypted data. These are not NIST data sets or + * provided by any other organization. The data sets are known good values, + * verified with two different JCE providers (solaris-sparcv9 ucrypto and + * linux SunJCE). + * + * Lengths around 64k are chosen because 64k is the point where + * com.sun.crypto.provider.GaloisCounterMode#doLastBlock() starts it's + * intrinsic warmup + * + * Plaintext is all zeros. Preset key and IV. + * + * The choice of MD5 is for speed. Shortcoming of the algorithm are + * not relevant for this test. + */ + +public class GCMLargeDataKAT { + + // Hash of encrypted results of AES/GCM for particular lengths. + // + static final HashMap results = new HashMap<>() {{ + put(65534, "1397b91c31ce793895edace4e175bfee"); //64k-2 + put(65535, "4ad101c9f450e686668b3f8f05db96f0"); //64k-1 + put(65536, "fbfaee3451acd3f603200d6be0f39b24"); //64k + put(65537, "e7dfca4a71495c65d20982c3c9b9813f"); //64k+1 + put(67583, "c8ebdcb3532ec6c165de961341af7635"); //66k-1 + put(67584, "36559d108dfd25dd29da3fec3455b9e5"); //66k + put(67585, "1d21b42d80ea179810744fc23dc228b6"); //66k+1 + put(102400, "0d1544fcab20bbd4c8103b9d273f2c82"); //100k + put(102401, "f2d53ef65fd12d0a861368659b23ea2e"); //100k+1 + put(102402, "97f0f524cf63d2d9d23d81e64d416ee0"); //100k+2 + put(102403, "4a6b4af55b7d9016b64114d6813d639c"); //100k+3 + put(102404, "ba63cc131fcde2f12ddf2ac634201be8"); //100k+4 + put(102405, "673d05c7fe5e283e42e5c0d049fdcea6"); //100k+5 + put(102406, "76cc99a7850ce857eb3cb43049cf9877"); //100k+6 + put(102407, "65863f99072cf2eb7fce18bd78b33f4e"); //100k+7 + put(102408, "b9184f0f272682cc1f791fa7070eddd4"); //100k+8 + put(102409, "45fe36afef43cc665bf22a9ca200c3c2"); //100k+9 + put(102410, "67249e41646edcb37a78a61b0743cf11"); //100k+0 + put(102411, "ffdc611e29c8849842e81ec78f32c415"); //100k+11 + put(102412, "b7fde7fd52221057dccc1c181a140125"); //100k+12 + put(102413, "4b1d6c64d56448105e5613157e69c0ae"); //100k+13 + put(102414, "6d2c0b26c0c8785c8eec3298a5f0080c"); //100k+14 + put(102415, "1df2061b114fbe56bdf3717e3ee61ef9"); //100k+15 + put(102416, "a691742692c683ac9d1254df5fc5f768"); //100k+16 + }}; + static final int HIGHLEN = 102416; + + static final int GCM_TAG_LENGTH = 16; + static final byte[] iv = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + static final byte[] key_code = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 + }; + static final GCMParameterSpec spec = + new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); + static final SecretKey key = new SecretKeySpec(key_code, "AES"); + static boolean testresult = true; + static byte[] plaintext = new byte[HIGHLEN]; + static MessageDigest md5; + Cipher cipher; + + GCMLargeDataKAT() { + } + + byte[] encrypt(int inLen) { + try { + cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); + cipher.init(Cipher.ENCRYPT_MODE, key, spec); + return cipher.doFinal(plaintext, 0, inLen); + } catch (Exception e) { + System.err.println("Encrypt Failure (length = " + inLen + ") : " + + e.getMessage()); + e.printStackTrace(); + } + return new byte[0]; + } + + static byte[] hash(byte[] data) { + return md5.digest(data); + } + + // Decrypt the data and return a boolean if the plaintext is all 0's. + boolean decrypt(byte[] data) { + byte[] result = null; + int len = data.length - GCM_TAG_LENGTH; + if (data.length == 0) { + return false; + } + try { + cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); + cipher.init(Cipher.DECRYPT_MODE, key, spec); + result = cipher.doFinal(data); + } catch (Exception e) { + System.err.println("Decrypt Failure (length = " + len + ") : " + + e.getMessage()); + e.printStackTrace(); + return false; + } + + if (result.length != len) { + System.err.println("Decrypt Failure (length = " + len + + ") : plaintext length invalid = " + result.length); + } + // Return false if we find a non zero. + int i = 0; + while (result.length > i) { + if (result[i++] != 0) { + System.err.println("Decrypt Failure (length = " + len + + ") : plaintext invalid, char index " + i); + return false; + } + } + return true; + } + + void test() throws Exception { + + // results order is not important + for (int l : results.keySet()) { + byte[] enc = new GCMLargeDataKAT().encrypt(l); + + // verify hash with stored hash of that length + String hashstr = toHex(hash(enc)); + boolean r = (hashstr.compareTo(results.get(l)) == 0); + + System.out.println("---------------------------------------------"); + + // Encrypted test & results + System.out.println("Encrypt data size " + l + " \tResult: " + + (r ? "Pass" : "Fail")); + if (!r) { + if (enc.length != 0) { + System.out.println("\tExpected: " + results.get(l)); + System.out.println("\tReturned: " + hashstr); + } + testresult = false; + continue; + } + + // Decrypted test & results + r = decrypt(enc); + System.out.println("Decrypt data size " + l + " \tResult: " + + (r ? "Pass" : "Fail")); + if (!r) { + testresult = false; + } + } + + // After test complete, throw an error if there was a failure + if (!testresult) { + throw new Exception("Tests failed"); + } + } + + /** + * With no argument, the test will run the predefined data lengths + * + * With an integer argument, this test will print the hash of the encrypted + * data of that integer length. + * + */ + public static void main(String args[]) throws Exception { + md5 = MessageDigest.getInstance("MD5"); + + if (args.length > 0) { + int len = Integer.parseInt(args[0]); + byte[] e = new GCMLargeDataKAT().encrypt(len); + System.out.println(toHex(hash(e))); + return; + } + + new GCMLargeDataKAT().test(); + } + + // bytes to hex string + static String toHex(byte[] bytes) { + StringBuffer hexStringBuffer = new StringBuffer(32); + for (int i = 0; i < bytes.length; i++) { + hexStringBuffer.append(byteToHex(bytes[i])); + } + return hexStringBuffer.toString(); + } + // byte to hex + static String byteToHex(byte num) { + char[] hexDigits = new char[2]; + hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); + hexDigits[1] = Character.forDigit((num & 0xF), 16); + return new String(hexDigits); + } +} diff --git a/test/jdk/com/sun/jdi/JdbStopThreadidTest.java b/test/jdk/com/sun/jdi/JdbStopThreadidTest.java index 9a32463799f..26752159d43 100644 --- a/test/jdk/com/sun/jdi/JdbStopThreadidTest.java +++ b/test/jdk/com/sun/jdi/JdbStopThreadidTest.java @@ -32,6 +32,7 @@ * @run main/othervm JdbStopThreadidTest */ +import jdk.test.lib.process.OutputAnalyzer; import lib.jdb.Jdb; import lib.jdb.JdbCommand; import lib.jdb.JdbTest; @@ -138,6 +139,7 @@ public class JdbStopThreadidTest extends JdbTest { jdb.command(JdbCommand.cont().waitForPrompt("Breakpoint hit: \"thread=MYTHREAD-2\", \\S+MyThread.brkMethod", true)); // Continue until the application exits. Once again, hitting a breakpoint will cause // a failure because we are not suppose to hit one. - jdb.command(JdbCommand.cont().waitForPrompt(Jdb.APPLICATION_EXIT, true)); + jdb.contToExit(1); + new OutputAnalyzer(getJdbOutput()).shouldContain(Jdb.APPLICATION_EXIT); } } diff --git a/test/jdk/com/sun/jdi/RedefineNestmateAttr/TestNestmateAttr.java b/test/jdk/com/sun/jdi/RedefineNestmateAttr/TestNestmateAttr.java index b78414d27d6..d89a4a0e5df 100644 --- a/test/jdk/com/sun/jdi/RedefineNestmateAttr/TestNestmateAttr.java +++ b/test/jdk/com/sun/jdi/RedefineNestmateAttr/TestNestmateAttr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -212,6 +212,8 @@ public class TestNestmateAttr extends TestScaffold { protected void startUp(String targetName) { List argList = new ArrayList<>(Arrays.asList(args)); argList.add(0, targetName); // pre-pend so it becomes the first "app" arg + // We need the class path that contains the path to jdk.test.lib.Asserts. + argList.add(0, " -cp " + System.getProperty("test.class.path")); println("run args: " + argList); connect((String[]) argList.toArray(args)); waitForVMStart(); diff --git a/test/jdk/com/sun/jdi/SimulResumerTest.java b/test/jdk/com/sun/jdi/SimulResumerTest.java index e27fa353087..669eb37df92 100644 --- a/test/jdk/com/sun/jdi/SimulResumerTest.java +++ b/test/jdk/com/sun/jdi/SimulResumerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -210,7 +210,9 @@ public class SimulResumerTest extends TestScaffold { } } catch (IncompatibleThreadStateException ee) { - // ignore + // ignore checks if thread was not suspended + } catch (ObjectCollectedException ee) { + // ignore ownedMonitors failure } catch (VMDisconnectedException ee) { // This is how we stop. The debuggee runs to completion // and we get this exception. @@ -249,7 +251,7 @@ public class SimulResumerTest extends TestScaffold { public void run() { while (true) { iters++; - System.out.println("bkpts = " + bkpts + ", iters = " + iters); + // System.out.println("bkpts = " + bkpts + ", iters = " + iters); try { Thread.sleep(waitTime); check(debuggeeThread1); diff --git a/test/jdk/com/sun/net/httpserver/TestLogging.java b/test/jdk/com/sun/net/httpserver/TestLogging.java index 225375fdf30..14e6aa3b657 100644 --- a/test/jdk/com/sun/net/httpserver/TestLogging.java +++ b/test/jdk/com/sun/net/httpserver/TestLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,7 +79,7 @@ public class TestLogging extends Test { System.out.println ("caught expected exception"); } - Socket s = new Socket ("127.0.0.1", p1); + Socket s = new Socket (InetAddress.getLoopbackAddress(), p1); OutputStream os = s.getOutputStream(); //os.write ("GET xxx HTTP/1.1\r\n".getBytes()); os.write ("HELLO WORLD\r\n".getBytes()); diff --git a/test/jdk/com/sun/net/httpserver/bugs/6725892/Test.java b/test/jdk/com/sun/net/httpserver/bugs/6725892/Test.java index e09a33f653f..14404598131 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/6725892/Test.java +++ b/test/jdk/com/sun/net/httpserver/bugs/6725892/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -96,7 +96,7 @@ public class Test { static void test1() throws IOException { failed = false; - Socket s = new Socket ("127.0.0.1", port); + Socket s = new Socket (InetAddress.getLoopbackAddress(), port); InputStream is = s.getInputStream(); // server should close connection after 2 seconds. We wait up to 10 s.setSoTimeout (10000); diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6361557.java b/test/jdk/com/sun/net/httpserver/bugs/B6361557.java index d854c772503..a1306f3895e 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6361557.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6361557.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,7 +78,7 @@ public class B6361557 { server.start (); InetSocketAddress destaddr = new InetSocketAddress ( - "127.0.0.1", server.getAddress().getPort() + InetAddress.getLoopbackAddress(), server.getAddress().getPort() ); System.out.println ("destaddr " + destaddr); diff --git a/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java b/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java index 84fbf1fd4e2..f72c828e437 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java +++ b/test/jdk/com/sun/net/httpserver/bugs/TruncatedRequestBody.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,7 @@ import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; @@ -100,7 +101,7 @@ public class TruncatedRequestBody { // Test 1: fixed length - Socket sock = new Socket("127.0.0.1", port); + Socket sock = new Socket(InetAddress.getLoopbackAddress(), port); String s1 = "POST /foo HTTP/1.1\r\nContent-length: 200000\r\n" + "\r\nfoo bar99"; @@ -114,7 +115,7 @@ public class TruncatedRequestBody { String s2 = "POST /foo HTTP/1.1\r\nTransfer-encoding: chunked\r\n\r\n" + "100\r\nFoo bar"; - sock = new Socket("127.0.0.1", port); + sock = new Socket(InetAddress.getLoopbackAddress(), port); os = sock.getOutputStream(); os.write(s2.getBytes(StandardCharsets.ISO_8859_1)); Thread.sleep(500); diff --git a/test/jdk/com/sun/net/ssl/SSLSecurity/JavaxSSLContextImpl.java b/test/jdk/com/sun/net/ssl/SSLSecurity/JavaxSSLContextImpl.java deleted file mode 100644 index 2b39bb8fd79..00000000000 --- a/test/jdk/com/sun/net/ssl/SSLSecurity/JavaxSSLContextImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.security.*; -import javax.net.ssl.*; - -public class JavaxSSLContextImpl extends SSLContextSpi { - - public JavaxSSLContextImpl() { - System.out.println("JavaxSSLContextImpl initialized"); - } - - protected void engineInit(KeyManager[] km, - TrustManager[] tm, SecureRandom sr) throws KeyManagementException { - System.out.println("JavaxSSLContextImpl init'd"); - } - - protected SSLEngine engineCreateSSLEngine() { - return null; - } - - protected SSLEngine engineCreateSSLEngine(String host, int port) { - return null; - } - - protected SSLSocketFactory engineGetSocketFactory() { - return null; - } - - protected SSLServerSocketFactory engineGetServerSocketFactory() { - return null; - } - - protected SSLSessionContext engineGetServerSessionContext() { - return null; - } - - protected SSLSessionContext engineGetClientSessionContext() { - return null; - } -} diff --git a/test/jdk/com/sun/net/ssl/SSLSecurity/ProviderTest.java b/test/jdk/com/sun/net/ssl/SSLSecurity/ProviderTest.java deleted file mode 100644 index e4d46d873a7..00000000000 --- a/test/jdk/com/sun/net/ssl/SSLSecurity/ProviderTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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 - * 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 4667976 8130181 - * @modules java.base/com.sun.net.ssl - * @compile JavaxSSLContextImpl.java ComSSLContextImpl.java - * JavaxTrustManagerFactoryImpl.java ComTrustManagerFactoryImpl.java - * JavaxKeyManagerFactoryImpl.java ComKeyManagerFactoryImpl.java - * @run main/othervm ProviderTest - * @summary brokenness in the com.sun.net.ssl.SSLSecurity wrappers - */ - -import java.security.*; -import com.sun.net.ssl.*; - -public class ProviderTest { - - public static void main(String args[]) throws Exception { - SSLContext sslc; - TrustManagerFactory tmf; - KeyManagerFactory kmf; - - Provider extraProvider = new MyProvider(); - Security.addProvider(extraProvider); - try { - System.out.println("getting a javax SSLContext"); - sslc = SSLContext.getInstance("javax"); - sslc.init(null, null, null); - System.out.println("\ngetting a com SSLContext"); - sslc = SSLContext.getInstance("com"); - sslc.init(null, null, null); - - System.out.println("\ngetting a javax TrustManagerFactory"); - tmf = TrustManagerFactory.getInstance("javax"); - tmf.init((KeyStore) null); - System.out.println("\ngetting a com TrustManagerFactory"); - tmf = TrustManagerFactory.getInstance("com"); - tmf.init((KeyStore) null); - - System.out.println("\ngetting a javax KeyManagerFactory"); - kmf = KeyManagerFactory.getInstance("javax"); - kmf.init((KeyStore) null, null); - System.out.println("\ngetting a com KeyManagerFactory"); - kmf = KeyManagerFactory.getInstance("com"); - kmf.init((KeyStore) null, null); - } finally { - Security.removeProvider(extraProvider.getName()); - } - } -} - -class MyProvider extends Provider { - - private static String info = "Brad's provider"; - - /** - * Installs the JSSE provider. - */ - public static synchronized void install() - { - /* nop. Remove this method in the future. */ - } - - public MyProvider() - { - super("BRAD", "1.0", info); - - AccessController.doPrivileged(new java.security.PrivilegedAction() { - public Object run() { - - put("SSLContext.javax", "JavaxSSLContextImpl"); - put("SSLContext.com", "ComSSLContextImpl"); - put("TrustManagerFactory.javax", - "JavaxTrustManagerFactoryImpl"); - put("TrustManagerFactory.com", - "ComTrustManagerFactoryImpl"); - put("KeyManagerFactory.javax", - "JavaxKeyManagerFactoryImpl"); - put("KeyManagerFactory.com", - "ComKeyManagerFactoryImpl"); - - return null; - } - }); - - } -} diff --git a/test/jdk/com/sun/net/ssl/SSLSecurity/TruncateArray.java b/test/jdk/com/sun/net/ssl/SSLSecurity/TruncateArray.java deleted file mode 100644 index cc25449b5a3..00000000000 --- a/test/jdk/com/sun/net/ssl/SSLSecurity/TruncateArray.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute 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 4665824 - * @summary JSSE - ClassCastException with 1.4 - * @modules java.base/com.sun.net.ssl - */ - -import com.sun.net.ssl.*; - -public class TruncateArray { - - public static void main(String args[]) throws Exception { - try { - - TrustManager tms [] = new TrustManager [] { - new MyTM(), new MyTM(), new MyTM() }; - - KeyManager kms [] = new KeyManager [] { - new MyKM(), new MyKM(), new MyKM() }; - - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(kms, tms, null); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SUNX509"); - KeyManager[] km = kmf.getKeyManagers(); - - TrustManagerFactory tmf = - TrustManagerFactory.getInstance("SUNX509"); - TrustManager[] tm = tmf.getTrustManagers(); - - } catch (ClassCastException e) { - throw e; - } catch (Throwable e) { - /* - * swallow anything else, we only are interested - * in class casting errors here. For example, we soon - * may be catching methods called on uninitialized factories. - */ - System.out.println("Caught something else"); - e.printStackTrace(); - } - } - - static class MyTM implements TrustManager { - } - - static class MyKM implements KeyManager { - } -} diff --git a/test/jdk/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java b/test/jdk/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java index be50b4efb2f..b015ae84633 100644 --- a/test/jdk/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java +++ b/test/jdk/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import com.sun.nio.sctp.*; import java.io.IOException; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; @@ -36,7 +37,7 @@ import static java.nio.ByteBuffer.*; public class SendFailed { - static final SocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 3000); + static final SocketAddress remoteAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 3000); static final int[] bufferSizes = { 20, 49, 50, 51, 100, 101, 1024, 1025, 4095, 4096, 4097, 8191, 8192, 8193}; diff --git a/test/jdk/java/lang/Process/WaitFor.java b/test/jdk/java/lang/Process/WaitFor.java new file mode 100644 index 00000000000..db15f89f8ce --- /dev/null +++ b/test/jdk/java/lang/Process/WaitFor.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8220684 + * @summary Process.waitFor(long, TimeUnit) can return false for a process + * that exited within the timeout + * @run main/othervm WaitFor + */ + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.concurrent.TimeUnit; + +public class WaitFor { + public static void main(String[] args) throws Throwable { + int failCnt = 0; + for (int i = 0; i < 30; ++i) { + Process proc = new MyProcess(new ProcessBuilder("true").start()); + boolean exited = proc.waitFor(100, TimeUnit.MILLISECONDS); + if (!exited && !proc.isAlive()) failCnt++; + } + if (failCnt > 10) { + throw new RuntimeException(failCnt + " processes were still alive" + + " after timeout"); + } + } +} + +/** + * This class uses the default implementation of java.lang.Process#waitFor(long, + * TimeUnit), and delegates all other calls to the actual implementation of + * Process. + */ +class MyProcess extends Process { + Process impl; + public MyProcess(Process impl) { this.impl = impl; } + public OutputStream getOutputStream() { return impl.getOutputStream(); } + public InputStream getInputStream() { return impl.getInputStream(); } + public InputStream getErrorStream() { return impl.getErrorStream(); } + public int waitFor() throws InterruptedException { return impl.waitFor(); } + public int exitValue() { return impl.exitValue(); } + public void destroy() { impl.destroy(); } + public ProcessHandle toHandle() { return impl.toHandle(); } +} diff --git a/test/jdk/java/lang/SecurityManager/CheckSecurityProvider.java b/test/jdk/java/lang/SecurityManager/CheckSecurityProvider.java index 7034f114aa3..4f5ad8db17e 100644 --- a/test/jdk/java/lang/SecurityManager/CheckSecurityProvider.java +++ b/test/jdk/java/lang/SecurityManager/CheckSecurityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,7 @@ public class CheckSecurityProvider { expected.add("sun.security.rsa.SunRsaSign"); layer.findModule("jdk.crypto.ec") .ifPresent(m -> expected.add("sun.security.ec.SunEC")); - expected.add("com.sun.net.ssl.internal.ssl.Provider"); + expected.add("sun.security.ssl.SunJSSE"); expected.add("com.sun.crypto.provider.SunJCE"); layer.findModule("jdk.security.jgss") .ifPresent(m -> expected.add("sun.security.jgss.SunProvider")); diff --git a/test/jdk/java/lang/StringBuffer/AppendCharSequence.java b/test/jdk/java/lang/StringBuffer/AppendCharSequence.java index e6012ca2718..4b516aa2582 100644 --- a/test/jdk/java/lang/StringBuffer/AppendCharSequence.java +++ b/test/jdk/java/lang/StringBuffer/AppendCharSequence.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* @test - * @bug 4812591 4705328 5019111 + * @bug 4812591 4705328 5019111 8218228 * @summary Test append and insert methods with CharSequence params * @key randomness */ @@ -230,6 +230,35 @@ public class AppendCharSequence { throw new RuntimeException("CharSequence constructor failure"); } } + checkNegativeLenCharSeq(-1); + checkNegativeLenCharSeq(-16); + checkNegativeLenCharSeq(-17); + checkNegativeLenCharSeq(Integer.MIN_VALUE); } + // Test constructing from CharSequence of negative length + private static void checkNegativeLenCharSeq(int len) { + try { + CharSequence seq = new MyNegativeLenCharSeq(len); + StringBuffer sb = new StringBuffer(seq); + } catch (NegativeArraySizeException expected) { + } catch (Throwable exc) { + throw new RuntimeException("Unexpected: " + exc, exc); + } + } + + private static class MyNegativeLenCharSeq implements CharSequence { + int length; + MyNegativeLenCharSeq(int length) { + this.length = length; + } + public char charAt(int i) { + throw new UnsupportedOperationException(); + } + public int length() { return length; } + public CharSequence subSequence(int st, int e) { + throw new UnsupportedOperationException(); + } + public String toString() { return ""; } + } } diff --git a/test/jdk/java/lang/ThreadGroup/Destroy.java b/test/jdk/java/lang/ThreadGroup/Destroy.java new file mode 100644 index 00000000000..a93940ba9bb --- /dev/null +++ b/test/jdk/java/lang/ThreadGroup/Destroy.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @summary enumerate(list,n,recurse) may return 0 if the group is being destroyed, + * whereas it should never return a value < n. This lead to inconsistent + * results if ThreadGroup::enumerate is called concurrently at the same + * time that a child group is being destroyed. This is a race condition, + * and this test will not always fail without the fix, but it does fail + * often enough. + * @bug 8219197 + * + */ +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; + +public class Destroy { + + static final class Task implements Runnable { + final Semaphore sem; + final CountDownLatch count; + + public Task(Semaphore sem, CountDownLatch count) { + this.sem = sem; + this.count = count; + } + + @Override + public void run() { + try { + count.countDown(); + sem.acquire(); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + System.out.println(Thread.currentThread().getName() + + " exiting"); + } + } + } + + public static void main(String[] args) throws Exception { + testDestroyChild(); + } + + public static void testDestroyChild() throws Exception { + ThreadGroup root = new ThreadGroup("root"); + ThreadGroup parent = new ThreadGroup(root,"parent"); + ThreadGroup child1 = new ThreadGroup(parent, "child1"); + CountDownLatch count = new CountDownLatch(2); + Semaphore sem1 = new Semaphore(1); + Semaphore sem2 = new Semaphore(1); + Thread t1 = new Thread(parent, new Task(sem1, count), "PT1"); + Thread t2 = new Thread(parent, new Task(sem2, count), "PT2"); + sem1.acquire(); + sem2.acquire(); + try { + + t1.start(); + t2.start(); + + System.out.println("\nAwaiting parent threads..."); + count.await(); + Thread[] threads = new Thread[2]; + int nb = root.enumerate(threads, true); + if (nb != 2) { + throw new AssertionError("wrong number of threads: " + nb); + } + + Thread t3 = new Thread(child1::destroy, "destroy"); + AtomicInteger nbr = new AtomicInteger(); + Thread t4 = new Thread("enumerate") { + public void run() { + Thread[] threads = new Thread[42]; + nbr.addAndGet(root.enumerate(threads, true)); + } + }; + t4.start(); + t3.start(); + t4.join(); + t3.join(); + if (nbr.get() != nb) { + throw new AssertionError("wrong number of threads: " + nbr.get()); + } + + } finally { + sem1.release(); + sem2.release(); + } + t1.join(); + t2.join(); + } +} diff --git a/test/jdk/java/net/Authenticator/B6870935.java b/test/jdk/java/net/Authenticator/B6870935.java index 4985e7df752..279ef63a865 100644 --- a/test/jdk/java/net/Authenticator/B6870935.java +++ b/test/jdk/java/net/Authenticator/B6870935.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -240,7 +240,7 @@ public class B6870935 { try { Authenticator.setDefault (new MyAuthenticator ()); - SocketAddress addr = new InetSocketAddress ("127.0.0.1", port); + SocketAddress addr = new InetSocketAddress (InetAddress.getLoopbackAddress(), port); Proxy proxy = new Proxy (Proxy.Type.HTTP, addr); String s = "http://www.ibm.com"; URL url = new URL(s); diff --git a/test/jdk/java/net/DatagramSocket/SendDatagramToBadAddress.java b/test/jdk/java/net/DatagramSocket/SendDatagramToBadAddress.java index b0cb10a6e92..f859ff4ee03 100644 --- a/test/jdk/java/net/DatagramSocket/SendDatagramToBadAddress.java +++ b/test/jdk/java/net/DatagramSocket/SendDatagramToBadAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -114,8 +114,7 @@ public class SendDatagramToBadAddress { if (OSsupportsFeature()) { print ("running on OS that supports ICMP port unreachable"); } - String host = "127.0.0.1"; - InetAddress addr = InetAddress.getByName(host); + InetAddress addr = InetAddress.getLoopbackAddress(); DatagramSocket sock = new DatagramSocket(); DatagramSocket serversock = new DatagramSocket(0); DatagramPacket p; diff --git a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java index 528dd11ffbc..1c48b502003 100644 --- a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java +++ b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -208,7 +208,8 @@ public class HTTPTestServer extends HTTPTest { @Override protected ServerSocket createBindable() throws IOException { - return new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1")); + InetAddress address = InetAddress.getLoopbackAddress(); + return new ServerSocket(0, 0, address); } @Override @@ -230,7 +231,8 @@ public class HTTPTestServer extends HTTPTest { @Override protected S createBindable() throws IOException { S server = newHttpServer(); - server.bind(new InetSocketAddress("127.0.0.1", 0), 0); + InetAddress address = InetAddress.getLoopbackAddress(); + server.bind(new InetSocketAddress(address, 0), 0); return server; } diff --git a/test/jdk/java/net/Socket/HttpProxy.java b/test/jdk/java/net/Socket/HttpProxy.java index 00a2cc2edb4..44c778f0614 100644 --- a/test/jdk/java/net/Socket/HttpProxy.java +++ b/test/jdk/java/net/Socket/HttpProxy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,11 +23,12 @@ /* * @test - * @bug 6370908 + * @bug 6370908 8220663 * @summary Add support for HTTP_CONNECT proxy in Socket class * @modules java.base/sun.net.www * @run main HttpProxy * @run main/othervm -Djava.net.preferIPv4Stack=true HttpProxy + * @run main/othervm -Djava.net.preferIPv6Addresses=true HttpProxy */ import java.io.IOException; @@ -40,6 +41,9 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ServerSocket; import java.net.Socket; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.List; import sun.net.www.MessageHeader; public class HttpProxy { @@ -50,9 +54,10 @@ public class HttpProxy { public static void main(String[] args) throws Exception { String host; int port; + ConnectProxyTunnelServer proxy = null; if (args.length == 0) { // Start internal proxy - ConnectProxyTunnelServer proxy = new ConnectProxyTunnelServer(); + proxy = new ConnectProxyTunnelServer(); proxy.start(); host = "localhost"; port = proxy.getLocalPort(); @@ -66,8 +71,13 @@ public class HttpProxy { return; } - HttpProxy p = new HttpProxy(host, port); - p.test(); + try { + HttpProxy p = new HttpProxy(host, port); + p.test(); + } finally { + if (proxy != null) + proxy.close(); + } } public HttpProxy(String proxyHost, int proxyPort) { @@ -79,26 +89,37 @@ public class HttpProxy { InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort); Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress); - try (ServerSocket ss = new ServerSocket(0); - Socket sock = new Socket(httpProxy)) { - sock.setSoTimeout(SO_TIMEOUT); - sock.setTcpNoDelay(false); + try (ServerSocket ss = new ServerSocket(0)) { + List externalAddresses = new ArrayList<>(); + externalAddresses.add( + new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort())); - InetSocketAddress externalAddress = - new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort()); + if (!"true".equals(System.getProperty("java.net.preferIPv4Stack"))) { + byte[] bytes = new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; + var address = InetAddress.getByAddress(bytes); + externalAddresses.add( + new InetSocketAddress(address, ss.getLocalPort())); + } - out.println("Trying to connect to server socket on " + externalAddress); - sock.connect(externalAddress); - try (Socket externalSock = ss.accept()) { - // perform some simple checks - check(sock.isBound(), "Socket is not bound"); - check(sock.isConnected(), "Socket is not connected"); - check(!sock.isClosed(), "Socket should not be closed"); - check(sock.getSoTimeout() == SO_TIMEOUT, - "Socket should have a previously set timeout"); - check(sock.getTcpNoDelay() == false, "NODELAY should be false"); + for (SocketAddress externalAddress : externalAddresses) { + try (Socket sock = new Socket(httpProxy)) { + sock.setSoTimeout(SO_TIMEOUT); + sock.setTcpNoDelay(false); - simpleDataExchange(sock, externalSock); + out.println("Trying to connect to server socket on " + externalAddress); + sock.connect(externalAddress); + try (Socket externalSock = ss.accept()) { + // perform some simple checks + check(sock.isBound(), "Socket is not bound"); + check(sock.isConnected(), "Socket is not connected"); + check(!sock.isClosed(), "Socket should not be closed"); + check(sock.getSoTimeout() == SO_TIMEOUT, + "Socket should have a previously set timeout"); + check(sock.getTcpNoDelay() == false, "NODELAY should be false"); + + simpleDataExchange(sock, externalSock); + } + } } } } @@ -108,7 +129,7 @@ public class HttpProxy { } static Exception unexpected(Exception e) { - out.println("Unexcepted Exception: " + e); + out.println("Unexpected Exception: " + e); e.printStackTrace(); return e; } @@ -164,9 +185,10 @@ public class HttpProxy { return i1 * 256 + i2; } - static class ConnectProxyTunnelServer extends Thread { + static class ConnectProxyTunnelServer extends Thread implements AutoCloseable { private final ServerSocket ss; + private volatile boolean closed; public ConnectProxyTunnelServer() throws IOException { ss = new ServerSocket(0); @@ -174,13 +196,20 @@ public class HttpProxy { @Override public void run() { - try (Socket clientSocket = ss.accept()) { - processRequest(clientSocket); + try { + while (!closed) { + try (Socket clientSocket = ss.accept()) { + processRequest(clientSocket); + } + } } catch (Exception e) { - out.println("Proxy Failed: " + e); - e.printStackTrace(); + if (!closed) { + out.println("Proxy Failed: " + e); + e.printStackTrace(); + } } finally { - try { ss.close(); } catch (IOException x) { unexpected(x); } + if (!closed) + try { ss.close(); } catch (IOException x) { unexpected(x); } } } @@ -191,6 +220,12 @@ public class HttpProxy { return ss.getLocalPort(); } + @Override + public void close() throws Exception { + closed = true; + ss.close(); + } + /* * Processes the CONNECT request */ @@ -200,7 +235,7 @@ public class HttpProxy { if (!statusLine.startsWith("CONNECT")) { out.println("proxy server: processes only " - + "CONNECT method requests, recieved: " + + "CONNECT method requests, received: " + statusLine); return; } @@ -246,12 +281,19 @@ public class HttpProxy { int endi = connectStr.lastIndexOf(' '); String connectInfo = connectStr.substring(starti+1, endi).trim(); // retrieve server name and port - endi = connectInfo.indexOf(':'); + endi = connectInfo.lastIndexOf(':'); String name = connectInfo.substring(0, endi); + + if (name.contains(":")) { + if (!(name.startsWith("[") && name.endsWith("]"))) { + throw new IOException("Invalid host:" + name); + } + name = name.substring(1, name.length() - 1); + } int port = Integer.parseInt(connectInfo.substring(endi+1)); return new InetSocketAddress(name, port); } catch (Exception e) { - out.println("Proxy recieved a request: " + connectStr); + out.println("Proxy received a request: " + connectStr); throw unexpected(e); } } diff --git a/test/jdk/java/net/Socket/UrgentDataTest.java b/test/jdk/java/net/Socket/UrgentDataTest.java index ed1ba15450b..a0db6924fc8 100644 --- a/test/jdk/java/net/Socket/UrgentDataTest.java +++ b/test/jdk/java/net/Socket/UrgentDataTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,7 +57,7 @@ public class UrgentDataTest { test.listener = new ServerSocket (0); test.isClient = true; test.isServer = true; - test.clHost = "127.0.0.1"; + test.clHost = InetAddress.getLoopbackAddress().getHostAddress(); test.clPort = test.listener.getLocalPort(); test.run(); } else if (args[0].equals ("-server")) { diff --git a/test/jdk/java/net/SocketImpl/SocketImplCombinations.java b/test/jdk/java/net/SocketImpl/SocketImplCombinations.java new file mode 100644 index 00000000000..5fa2a960977 --- /dev/null +++ b/test/jdk/java/net/SocketImpl/SocketImplCombinations.java @@ -0,0 +1,844 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8220493 + * @modules java.base/java.net:+open java.base/sun.nio.ch:+open + * @run testng/othervm SocketImplCombinations + * @summary Test Socket and ServerSocket with combinations of SocketImpls + */ + +import java.io.FileDescriptor; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketImpl; +import java.net.SocketImplFactory; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.function.BiConsumer; + +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +@Test +public class SocketImplCombinations { + + /** + * Test creating an unconnected Socket, it should be created with a platform SocketImpl. + */ + public void testNewSocket1() throws IOException { + try (Socket s = new Socket()) { + SocketImpl si = getSocketImpl(s); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } + } + + /** + * Test creating a connected Socket, it should be created with a platform SocketImpl. + */ + public void testNewSocket2() throws IOException { + try (ServerSocket ss = new ServerSocket(0)) { + try (Socket s = new Socket(ss.getInetAddress(), ss.getLocalPort())) { + SocketImpl si = getSocketImpl(s); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } + } + } + + /** + * Test creating a Socket for a DIRECT connection, it should be created with a + * platform SocketImpl. + */ + public void testNewSocket3() throws IOException { + try (Socket s = new Socket(Proxy.NO_PROXY)) { + SocketImpl si = getSocketImpl(s); + assertTrue(isPlatformSocketImpl(si)); + } + } + + /** + * Test creating a Socket for a SOCKS connection, it should be created with a + * SOCKS SocketImpl. + */ + public void testNewSocket4() throws IOException { + var address = new InetSocketAddress("127.0.0.1", 1080); + var socksProxy = new Proxy(Proxy.Type.SOCKS, address); + try (Socket s = new Socket(socksProxy)) { + SocketImpl si = getSocketImpl(s); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } + } + + /** + * Test creating a Socket for a HTTP proxy connection, it should be created with + * a HTTP proxy SocketImpl. + */ + public void testNewSocket5() throws IOException { + var address = new InetSocketAddress("127.0.0.1", 8080); + var httpProxy = new Proxy(Proxy.Type.HTTP, address); + try (Socket s = new Socket(httpProxy)) { + SocketImpl si = getSocketImpl(s); + assertTrue(isHttpConnectSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } + } + + /** + * Test creating a Socket no SocketImpl. A platform SocketImpl should be + * created lazily. + */ + public void testNewSocket6() throws IOException { + Socket s = new Socket((SocketImpl) null) { }; + try (s) { + assertTrue(getSocketImpl(s) == null); + s.bind(new InetSocketAddress(0)); // force SocketImpl to be created + SocketImpl si = getSocketImpl(s); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } + } + + /** + * Test creating a Socket with a custom SocketImpl. + */ + public void testNewSocket7() throws IOException { + Socket s = new Socket(new CustomSocketImpl(false)) { }; + try (s) { + SocketImpl si = getSocketImpl(s); + assertTrue(si instanceof CustomSocketImpl); + } + } + + /** + * Test creating a Socket when there is a SocketImplFactory set. + */ + public void testNewSocket8() throws IOException { + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try (Socket s = new Socket()) { + SocketImpl si = getSocketImpl(s); + assertTrue(si instanceof CustomSocketImpl); + } finally { + setSocketSocketImplFactory(null); + } + } + + /** + * Test creating a Socket for a DIRECT connection when there is a + * SocketImplFactory set. + */ + public void testNewSocket9() throws IOException { + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try (Socket s = new Socket(Proxy.NO_PROXY)) { + SocketImpl si = getSocketImpl(s); + assertTrue(si instanceof CustomSocketImpl); + } finally { + setSocketSocketImplFactory(null); + } + } + + /** + * Test creating a Socket for a SOCKS connection when there is a + * SocketImplFactory set. + */ + public void testNewSocket10() throws IOException { + var address = new InetSocketAddress("127.0.0.1", 1080); + var socksProxy = new Proxy(Proxy.Type.SOCKS, address); + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try (Socket s = new Socket(socksProxy)) { + SocketImpl si = getSocketImpl(s); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } finally { + setSocketSocketImplFactory(null); + } + } + + /** + * Test creating a Socket for a HTTP proxy connection when there is a + * SocketImplFactory set. + */ + public void testNewSocket11() throws IOException { + var address = new InetSocketAddress("127.0.0.1", 8080); + var httpProxy = new Proxy(Proxy.Type.HTTP, address); + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try (Socket s = new Socket(httpProxy)) { + SocketImpl si = getSocketImpl(s); + assertTrue(isHttpConnectSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + } finally { + setSocketSocketImplFactory(null); + } + } + + /** + * Test creating a Socket no SocketImpl when there is a SocketImplFactory set. + */ + public void testNewSocket12() throws IOException { + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try { + Socket s = new Socket((SocketImpl) null) { }; + try (s) { + assertTrue(getSocketImpl(s) == null); + s.bind(new InetSocketAddress(0)); // force SocketImpl to be created + assertTrue(getSocketImpl(s) instanceof CustomSocketImpl); + } + } finally { + setSocketSocketImplFactory(null); + } + } + + /** + * Test creating an unbound ServerSocket, it should be created with a platform + * SocketImpl. + */ + public void testNewServerSocket1() throws IOException { + try (ServerSocket ss = new ServerSocket()) { + SocketImpl si = getSocketImpl(ss); + assertTrue(isPlatformSocketImpl(si)); + } + } + + /** + * Test creating a bound ServerSocket, it should be created with a platform + * SocketImpl. + */ + public void testNewServerSocket2() throws IOException { + try (ServerSocket ss = new ServerSocket(0)) { + SocketImpl si = getSocketImpl(ss); + assertTrue(isPlatformSocketImpl(si)); + } + } + + /** + * Test creating a ServerSocket with a custom SocketImpl. + */ + public void testNewServerSocket3() throws IOException { + ServerSocket ss = new ServerSocket(new CustomSocketImpl(true)) { }; + try (ss) { + SocketImpl si = getSocketImpl(ss); + assertTrue(si instanceof CustomSocketImpl); + } + } + + /** + * Test creating an unbound ServerSocket when there is a SocketImplFactory set. + */ + public void testNewServerSocket4() throws IOException { + setServerSocketImplFactory(() -> new CustomSocketImpl(true)); + try (ServerSocket ss = new ServerSocket()) { + SocketImpl si = getSocketImpl(ss); + assertTrue(si instanceof CustomSocketImpl); + } finally { + setServerSocketImplFactory(null); + } + } + + /** + * Test creating a bound ServerSocket when there is a SocketImplFactory set. + */ + public void testNewServerSocket5() throws IOException { + setServerSocketImplFactory(() -> new CustomSocketImpl(true)); + try (ServerSocket ss = new ServerSocket(0)) { + SocketImpl si = getSocketImpl(ss); + assertTrue(si instanceof CustomSocketImpl); + } finally { + setServerSocketImplFactory(null); + } + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl, + * the Socket to accept is created with no SocketImpl. + */ + public void testServerSocketAccept1() throws IOException { + var socket = new Socket((SocketImpl) null) { }; + assertTrue(getSocketImpl(socket) == null); + + serverSocketAccept(socket, (ss, s) -> { + assertTrue(isPlatformSocketImpl(getSocketImpl(ss))); + assertTrue(s == socket); + SocketImpl si = getSocketImpl(s); + assertTrue(isPlatformSocketImpl(si)); + checkFields(si); + }); + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl, + * the Socket to accept is created with no SocketImpl, and there is a custom + * client SocketImplFactory set. + */ + public void testServerSocketAccept2() throws IOException { + var socket = new Socket((SocketImpl) null) { }; + assertTrue(getSocketImpl(socket) == null); + + serverSocketAccept(socket, () -> new CustomSocketImpl(false), (ss, s) -> { + assertTrue(isPlatformSocketImpl(getSocketImpl(ss))); + assertTrue(s == socket); + SocketImpl si = getSocketImpl(s); + assertTrue(isPlatformSocketImpl(si)); + checkFields(si); + }); + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl, + * the Socket to accept is created with a SocketImpl that delegates to a + * platform SocketImpl. + */ + public void testServerSocketAccept3() throws IOException { + var socket = new Socket(); + SocketImpl si = getSocketImpl(socket); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + + serverSocketAccept(socket, (ss, s) -> { + assertTrue(isPlatformSocketImpl(getSocketImpl(ss))); + assertTrue(s == socket); + SocketImpl psi = getSocketImpl(socket); + assertTrue(isPlatformSocketImpl(psi)); + checkFields(psi); + }); + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a platform SocketImpl, + * the Socket to accept is created with a custom SocketImpl. + */ + public void testServerSocketAccept4a() throws IOException { + SocketImpl clientImpl = new CustomSocketImpl(false); + Socket socket = new Socket(clientImpl) { }; + assertTrue(getSocketImpl(socket) == clientImpl); + + try (ServerSocket ss = serverSocketToAccept(socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + socket.close(); + } + } + + public void testServerSocketAccept4b() throws IOException { + SocketImpl clientImpl = new CustomSocketImpl(false); + Socket socket = new Socket(clientImpl) { }; + assertTrue(getSocketImpl(socket) == clientImpl); + + setSocketSocketImplFactory(() -> new CustomSocketImpl(false)); + try (ServerSocket ss = serverSocketToAccept(socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + setSocketSocketImplFactory(null); + socket.close(); + } + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl, + * the Socket to accept is created no SocketImpl. + */ + public void testServerSocketAccept5a() throws IOException { + SocketImpl serverImpl = new CustomSocketImpl(true); + try (ServerSocket ss = new ServerSocket(serverImpl) { }) { + ss.bind(new InetSocketAddress(0)); + expectThrows(IOException.class, ss::accept); + } + } + + public void testServerSocketAccept5b() throws IOException { + var socket = new Socket((SocketImpl) null) { }; + assertTrue(getSocketImpl(socket) == null); + + SocketImpl serverImpl = new CustomSocketImpl(true); + try (ServerSocket ss = serverSocketToAccept(serverImpl, socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + socket.close(); + } + } + + public void testServerSocketAccept5c() throws IOException { + setServerSocketImplFactory(() -> new CustomSocketImpl(true)); + try (ServerSocket ss = new ServerSocket(0)) { + expectThrows(IOException.class, ss::accept); + } finally { + setServerSocketImplFactory(null); + } + } + + public void testServerSocketAccept5d() throws IOException { + var socket = new Socket((SocketImpl) null) { }; + assertTrue(getSocketImpl(socket) == null); + + setServerSocketImplFactory(() -> new CustomSocketImpl(true)); + try (ServerSocket ss = serverSocketToAccept(socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + setServerSocketImplFactory(null); + socket.close(); + } + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl, + * the Socket to accept is created with no SocketImpl, and there is a custom + * client SocketImplFactory set. + */ + public void testServerSocketAccept6() throws Exception { + var socket = new Socket((SocketImpl) null) { }; + assertTrue(getSocketImpl(socket) == null); + + SocketImpl serverImpl = new CustomSocketImpl(true); + SocketImplFactory clientFactory = () -> new CustomSocketImpl(false); + serverSocketAccept(serverImpl, socket, clientFactory, (ss, s) -> { + assertTrue(getSocketImpl(ss) == serverImpl); + SocketImpl si = getSocketImpl(s); + assertTrue(si instanceof CustomSocketImpl); + checkFields(si); + }); + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl, + * the Socket to accept is created with a SocketImpl that delegates to a + * platform SocketImpl. + */ + public void testServerSocketAccept7a() throws IOException { + var socket = new Socket(); + SocketImpl si = getSocketImpl(socket); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + + SocketImpl serverImpl = new CustomSocketImpl(true); + try (ServerSocket ss = serverSocketToAccept(serverImpl, socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + socket.close(); + } + } + + public void testServerSocketAccept7b() throws IOException { + var socket = new Socket(); + SocketImpl si = getSocketImpl(socket); + assertTrue(isSocksSocketImpl(si)); + SocketImpl delegate = getDelegate(si); + assertTrue(isPlatformSocketImpl(delegate)); + + setServerSocketImplFactory(() -> new CustomSocketImpl(true)); + try (ServerSocket ss = serverSocketToAccept(socket)) { + expectThrows(IOException.class, ss::accept); + } finally { + setServerSocketImplFactory(null); + socket.close(); + } + } + + /** + * Test ServerSocket.accept. The ServerSocket uses a custom SocketImpl, + * the Socket to accept is created with a custom SocketImpl. + */ + public void testServerSocketAccept8() throws Exception { + SocketImpl clientImpl = new CustomSocketImpl(false); + Socket socket = new Socket(clientImpl) { }; + assertTrue(getSocketImpl(socket) == clientImpl); + + SocketImpl serverImpl = new CustomSocketImpl(true); + SocketImplFactory clientFactory = () -> new CustomSocketImpl(false); + serverSocketAccept(serverImpl, socket, clientFactory, (ss, s) -> { + assertTrue(getSocketImpl(ss) == serverImpl); + assertTrue(getSocketImpl(s) == clientImpl); + checkFields(clientImpl); + }); + } + + /** + * Creates a ServerSocket that returns the given Socket from accept. + * The consumer is invoked with the server socket and the accepted socket. + */ + static void serverSocketAccept(Socket socket, + BiConsumer consumer) + throws IOException + { + Socket s1 = null; + Socket s2 = null; + try (ServerSocket ss = serverSocketToAccept(socket)) { + s1 = new Socket(ss.getInetAddress(), ss.getLocalPort()); + s2 = ss.accept(); + consumer.accept(ss, s2); + } finally { + if (s1 != null) s1.close(); + if (s2 != null) s2.close(); + } + } + + /** + * Creates a ServerSocket that returns the given Socket from accept. The + * given SocketImplFactory is set during the accept and the consumer is + * invoked when the server socket and the accepted socket. + */ + static void serverSocketAccept(Socket socket, + SocketImplFactory factory, + BiConsumer consumer) + throws IOException + { + Socket s1 = null; + Socket s2 = null; + try (ServerSocket ss = serverSocketToAccept(socket)) { + s1 = new Socket(ss.getInetAddress(), ss.getLocalPort()); + setSocketSocketImplFactory(factory); + try { + s2 = ss.accept(); + } finally { + setSocketSocketImplFactory(null); + } + consumer.accept(ss, s2); + } finally { + if (s1 != null) s1.close(); + if (s2 != null) s2.close(); + } + } + + /** + * Creates a ServerSocket with a SocketImpl returns the given Socket from + * accept. The given SocketImplFactory is set during the accept and the + * consumer is invoked when the server socket and the accepted socket. + */ + static void serverSocketAccept(SocketImpl impl, + Socket socket, + SocketImplFactory factory, + BiConsumer consumer) + throws IOException + { + Socket s1 = null; + Socket s2 = null; + try (ServerSocket ss = serverSocketToAccept(impl, socket)) { + s1 = new Socket(ss.getInetAddress(), ss.getLocalPort()); + setSocketSocketImplFactory(factory); + try { + s2 = ss.accept(); + } finally { + setSocketSocketImplFactory(null); + } + consumer.accept(ss, s2); + } finally { + if (s1 != null) s1.close(); + if (s2 != null) s2.close(); + } + } + + /** + * Creates a ServerSocket that returns the given Socket from accept. + */ + static ServerSocket serverSocketToAccept(Socket s) throws IOException { + return new ServerSocket(0) { + @Override + public Socket accept() throws IOException { + implAccept(s); + return s; + } + }; + } + + /** + * Creates a ServerSocket with a SocketImpl that returns the given Socket + * from accept. + */ + static ServerSocket serverSocketToAccept(SocketImpl impl, Socket s) throws IOException { + ServerSocket ss = new ServerSocket(impl) { + @Override + public Socket accept() throws IOException { + implAccept(s); + return s; + } + }; + ss.bind(new InetSocketAddress(0)); + return ss; + } + + /** + * Returns the socket's SocketImpl + */ + static SocketImpl getSocketImpl(Socket s) { + try { + Field f = Socket.class.getDeclaredField("impl"); + f.setAccessible(true); + return (SocketImpl) f.get(s); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the server socket's SocketImpl + */ + static SocketImpl getSocketImpl(ServerSocket ss) { + try { + Field f = ServerSocket.class.getDeclaredField("impl"); + f.setAccessible(true); + return (SocketImpl) f.get(ss); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the SocketImpl that the given SocketImpl delegates to + */ + static SocketImpl getDelegate(SocketImpl si) { + try { + Class clazz = Class.forName("java.net.DelegatingSocketImpl"); + Field f = clazz.getDeclaredField("delegate"); + f.setAccessible(true); + return (SocketImpl) f.get(si); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the value of a SocketImpl field + */ + static T get(SocketImpl si, String name) { + try { + Field f = SocketImpl.class.getDeclaredField(name); + f.setAccessible(true); + return (T) f.get(si); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Sets the value of SocketImpl field + */ + static void set(SocketImpl si, String name, Object value) { + try { + Field f = SocketImpl.class.getDeclaredField(name); + f.setAccessible(true); + f.set(si, value); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns true if the SocketImpl is a PlatformSocketImpl + */ + static boolean isPlatformSocketImpl(SocketImpl si) { + try { + Class clazz = Class.forName("sun.net.PlatformSocketImpl"); + return clazz.isInstance(si); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns true if the SocketImpl is a SocksSocketImpl + */ + static boolean isSocksSocketImpl(SocketImpl si) { + try { + Class clazz = Class.forName("java.net.SocksSocketImpl"); + return clazz.isInstance(si); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Returns true if the SocketImpl is a HttpConnectSocketImpl + */ + static boolean isHttpConnectSocketImpl(SocketImpl si) { + try { + Class clazz = Class.forName("java.net.HttpConnectSocketImpl"); + return clazz.isInstance(si); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Socket.setSocketImplFactory(SocketImplFactory) + */ + static void setSocketSocketImplFactory(SocketImplFactory factory) { + try { + Field f = Socket.class.getDeclaredField("factory"); + f.setAccessible(true); + f.set(null, factory); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * ServerSocket.setSocketFactory(SocketImplFactory) + */ + static void setServerSocketImplFactory(SocketImplFactory factory) { + try { + Field f = ServerSocket.class.getDeclaredField("factory"); + f.setAccessible(true); + f.set(null, factory); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Checks the 4 protected fields of a SocketImpl to make sure that they + * have been initialized. + */ + static void checkFields(SocketImpl si) { + FileDescriptor fd = get(si, "fd"); + InetAddress address = get(si, "address"); + int port = get(si, "port"); + int localport = get(si, "localport"); + assertTrue(fd.valid() && address != null && port != 0 && localport != 0); + } + + /** + * Custom SocketImpl that is layed on a SocketChannel or ServerSocketChannel + */ + static class CustomSocketImpl extends SocketImpl { + private final boolean server; + private ServerSocketChannel ssc; + private SocketChannel sc; + + CustomSocketImpl(boolean server) { + this.server = server; + } + + @Override + protected void create(boolean stream) throws IOException { + if (server) { + ssc = ServerSocketChannel.open(); + } else { + sc = SocketChannel.open(); + } + } + + @Override + protected void connect(String host, int port) throws IOException { + connect(new InetSocketAddress(host, port), 0); + } + + @Override + protected void connect(InetAddress address, int port) throws IOException { + connect(new InetSocketAddress(address, port), 0); + } + + @Override + protected void connect(SocketAddress remote, int timeout) throws IOException { + sc.connect(remote); + super.address = ((InetSocketAddress) remote).getAddress(); + super.port = ((InetSocketAddress) remote).getPort(); + } + + @Override + protected void bind(InetAddress address, int port) throws IOException { + if (server) { + ssc.bind(new InetSocketAddress(address, port)); + super.localport = ssc.socket().getLocalPort(); + } else { + sc.bind(new InetSocketAddress(address, port)); + super.localport = sc.socket().getLocalPort(); + } + super.address = address; + } + + @Override + protected void listen(int backlog) { + // do nothing + } + + @Override + protected void accept(SocketImpl si) throws IOException { + SocketChannel peer = ssc.accept(); + FileDescriptor fd; + try { + Class clazz = Class.forName("sun.nio.ch.SocketChannelImpl"); + Field f = clazz.getDeclaredField("fd"); + f.setAccessible(true); + fd = (FileDescriptor) f.get(peer); + } catch (Exception e) { + throw new RuntimeException(e); + } + set(si, "fd", fd); + set(si, "address", peer.socket().getInetAddress()); + set(si, "port", peer.socket().getPort()); + set(si, "localport", peer.socket().getLocalPort()); + } + + @Override + protected InputStream getInputStream() { + throw new RuntimeException(); + } + + @Override + protected OutputStream getOutputStream() { + throw new RuntimeException(); + } + + @Override + protected int available() { + return 0; + } + + @Override + protected void close() { + } + + @Override + protected void sendUrgentData(int data) { + throw new RuntimeException(); + } + + @Override + public void setOption(int option, Object value) { + throw new RuntimeException(); + } + + @Override + public Object getOption(int option) { + throw new RuntimeException(); + } + } +} diff --git a/test/jdk/java/net/SocketOption/OptionsTest.java b/test/jdk/java/net/SocketOption/OptionsTest.java index 214c2d920f1..f0a24427f51 100644 --- a/test/jdk/java/net/SocketOption/OptionsTest.java +++ b/test/jdk/java/net/SocketOption/OptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -100,7 +100,7 @@ public class OptionsTest { static void doSocketTests() throws Exception { try ( ServerSocket srv = new ServerSocket(0); - Socket c = new Socket("127.0.0.1", srv.getLocalPort()); + Socket c = new Socket(InetAddress.getLoopbackAddress(), srv.getLocalPort()); Socket s = srv.accept(); ) { Set> options = c.supportedOptions(); diff --git a/test/jdk/java/net/SocketOption/TcpKeepAliveTest.java b/test/jdk/java/net/SocketOption/TcpKeepAliveTest.java index 6ee8b78b9a3..d5ad3327c7e 100644 --- a/test/jdk/java/net/SocketOption/TcpKeepAliveTest.java +++ b/test/jdk/java/net/SocketOption/TcpKeepAliveTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ */ import java.io.IOException; import java.net.DatagramSocket; +import java.net.InetAddress; import java.net.MulticastSocket; import java.net.ServerSocket; import java.net.Socket; @@ -37,7 +38,6 @@ import jdk.net.ExtendedSocketOptions; public class TcpKeepAliveTest { - private static final String LOCAL_HOST = "127.0.0.1"; private static final int DEFAULT_KEEP_ALIVE_PROBES = 7; private static final int DEFAULT_KEEP_ALIVE_TIME = 1973; private static final int DEFAULT_KEEP_ALIVE_INTVL = 53; @@ -45,7 +45,7 @@ public class TcpKeepAliveTest { public static void main(String args[]) throws IOException { try (ServerSocket ss = new ServerSocket(0); - Socket s = new Socket(LOCAL_HOST, ss.getLocalPort()); + Socket s = new Socket(InetAddress.getLoopbackAddress(), ss.getLocalPort()); DatagramSocket ds = new DatagramSocket(0); MulticastSocket mc = new MulticastSocket(0)) { if (ss.supportedOptions().contains(ExtendedSocketOptions.TCP_KEEPIDLE)) { diff --git a/test/jdk/java/net/URL/HandlerLoop.java b/test/jdk/java/net/URL/HandlerLoop.java index 3249e24712f..26adcf0bec4 100644 --- a/test/jdk/java/net/URL/HandlerLoop.java +++ b/test/jdk/java/net/URL/HandlerLoop.java @@ -32,7 +32,7 @@ import java.net.URLStreamHandlerFactory; * @summary Test bootstrap problem when a URLStreamHandlerFactory is loaded * by the application class loader. * @modules java.base/sun.net.www.protocol.file - * @run main HandlerLoop + * @run main/othervm HandlerLoop */ public class HandlerLoop { diff --git a/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java b/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java index dbf6d9985ac..cb3d083669b 100644 --- a/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java +++ b/test/jdk/java/net/httpclient/UnknownBodyLengthTest.java @@ -22,6 +22,7 @@ */ import java.io.InputStream; import java.io.OutputStream; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; @@ -72,7 +73,7 @@ public class UnknownBodyLengthTest { : ServerSocketFactory.getDefault(); ss = factory.createServerSocket(); ss.setReuseAddress(true); - ss.bind(new InetSocketAddress("127.0.0.1", 0)); + ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); System.out.println("ServerSocket = " + ss.getClass() + " " + ss); port = ss.getLocalPort(); clientURL = (useSSL ? "https" : "http") + "://localhost:" diff --git a/test/jdk/java/nio/Buffer/Basic-X.java.template b/test/jdk/java/nio/Buffer/Basic-X.java.template index bfbb8dda097..d8f2ef94e13 100644 --- a/test/jdk/java/nio/Buffer/Basic-X.java.template +++ b/test/jdk/java/nio/Buffer/Basic-X.java.template @@ -648,7 +648,7 @@ public class Basic$Type$ } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, ($type$[])null, 0, 42)); @@ -668,6 +668,11 @@ public class Basic$Type$ catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class Basic$Type$ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + $Type$Buffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + $Type$Buffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + #if[byte] // Views diff --git a/test/jdk/java/nio/Buffer/Basic.java b/test/jdk/java/nio/Buffer/Basic.java index 92d8a6042d3..9a181838e90 100644 --- a/test/jdk/java/nio/Buffer/Basic.java +++ b/test/jdk/java/nio/Buffer/Basic.java @@ -25,8 +25,8 @@ * @summary Unit test for buffers * @bug 4413135 4414911 4416536 4416562 4418782 4471053 4472779 4490253 4523725 * 4526177 4463011 4660660 4661219 4663521 4782970 4804304 4938424 5029431 - * 6231529 6221101 6234263 6535542 6591971 6593946 6795561 7190219 7199551 - * 8065556 8149469 + * 5071718 6231529 6221101 6234263 6535542 6591971 6593946 6795561 7190219 + * 7199551 8065556 8149469 * @modules java.base/java.nio:open * java.base/jdk.internal.misc * @author Mark Reinhold diff --git a/test/jdk/java/nio/Buffer/BasicByte.java b/test/jdk/java/nio/Buffer/BasicByte.java index a2ea7d02cb4..3e8ba12b812 100644 --- a/test/jdk/java/nio/Buffer/BasicByte.java +++ b/test/jdk/java/nio/Buffer/BasicByte.java @@ -648,7 +648,7 @@ public class BasicByte } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (byte[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicByte catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicByte + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + ByteBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + ByteBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + // Views diff --git a/test/jdk/java/nio/Buffer/BasicChar.java b/test/jdk/java/nio/Buffer/BasicChar.java index 91d43ce8881..6b927c8d782 100644 --- a/test/jdk/java/nio/Buffer/BasicChar.java +++ b/test/jdk/java/nio/Buffer/BasicChar.java @@ -648,7 +648,7 @@ public class BasicChar } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (char[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicChar catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicChar + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + CharBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + CharBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/BasicDouble.java b/test/jdk/java/nio/Buffer/BasicDouble.java index 570130902ed..8811cff7d13 100644 --- a/test/jdk/java/nio/Buffer/BasicDouble.java +++ b/test/jdk/java/nio/Buffer/BasicDouble.java @@ -648,7 +648,7 @@ public class BasicDouble } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (double[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicDouble catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicDouble + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + DoubleBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + DoubleBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/BasicFloat.java b/test/jdk/java/nio/Buffer/BasicFloat.java index 4abe3381884..f11b79225d6 100644 --- a/test/jdk/java/nio/Buffer/BasicFloat.java +++ b/test/jdk/java/nio/Buffer/BasicFloat.java @@ -648,7 +648,7 @@ public class BasicFloat } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (float[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicFloat catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicFloat + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + FloatBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + FloatBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/BasicInt.java b/test/jdk/java/nio/Buffer/BasicInt.java index fc53901b5a0..ca0d040998b 100644 --- a/test/jdk/java/nio/Buffer/BasicInt.java +++ b/test/jdk/java/nio/Buffer/BasicInt.java @@ -648,7 +648,7 @@ public class BasicInt } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (int[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicInt catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicInt + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + IntBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + IntBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/BasicLong.java b/test/jdk/java/nio/Buffer/BasicLong.java index 5feb0d3cfce..ab28e859b15 100644 --- a/test/jdk/java/nio/Buffer/BasicLong.java +++ b/test/jdk/java/nio/Buffer/BasicLong.java @@ -648,7 +648,7 @@ public class BasicLong } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (long[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicLong catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicLong + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + LongBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + LongBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/BasicShort.java b/test/jdk/java/nio/Buffer/BasicShort.java index 846bcb97a4d..e9458dde906 100644 --- a/test/jdk/java/nio/Buffer/BasicShort.java +++ b/test/jdk/java/nio/Buffer/BasicShort.java @@ -648,7 +648,7 @@ public class BasicShort } } - // Exceptions in absolute bulk operations + // Exceptions in absolute bulk and slice operations catchNullArgument(b, () -> b.get(7, null, 0, 42)); catchNullArgument(b, () -> b.put(7, (short[])null, 0, 42)); @@ -668,6 +668,11 @@ public class BasicShort catchIndexOutOfBounds(b, () -> b.put(b.limit(), tmpa, 0, 1)); catchIndexOutOfBounds(b, () -> b.put(b.limit() - 41, tmpa, 0, 42)); + catchIndexOutOfBounds(b, () -> b.slice(-1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(b.limit() + 1, 7)); + catchIndexOutOfBounds(b, () -> b.slice(0, -1)); + catchIndexOutOfBounds(b, () -> b.slice(7, b.limit() - 7 + 1)); + // Values b.clear(); @@ -832,6 +837,20 @@ public class BasicShort + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); } + int bPos = b.position(); + int bLim = b.limit(); + + b.position(7); + b.limit(42); + ShortBuffer rsb = b.slice(); + b.position(0); + b.limit(b.capacity()); + ShortBuffer asb = b.slice(7, 35); + checkSlice(rsb, asb); + + b.position(bPos); + b.limit(bLim); + diff --git a/test/jdk/java/nio/Buffer/ByteBufferViews.java b/test/jdk/java/nio/Buffer/ByteBufferViews.java index dfa3f55c0ff..18a3ac55c86 100644 --- a/test/jdk/java/nio/Buffer/ByteBufferViews.java +++ b/test/jdk/java/nio/Buffer/ByteBufferViews.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,6 +64,8 @@ public class ByteBufferViews { size -> ByteBuffer.allocate(size).position(8).slice()), Map.entry("ByteBuffer.allocate(size).position(8).slice().duplicate()", size -> ByteBuffer.allocate(size).position(8).slice().duplicate()), + Map.entry("ByteBuffer.allocate(size).slice(8,size-8)", + size -> ByteBuffer.allocate(size).slice(8,size-8)), // Unaligned Map.entry("ByteBuffer.allocate(size).position(1)", size -> ByteBuffer.allocate(size).position(1)), @@ -71,6 +73,8 @@ public class ByteBufferViews { size -> ByteBuffer.allocate(size).position(1).slice()), Map.entry("ByteBuffer.allocate(size).position(1).slice().duplicate()", size -> ByteBuffer.allocate(size).position(1).slice().duplicate()), + Map.entry("ByteBuffer.allocate(size).slice(1,size-1)", + size -> ByteBuffer.allocate(size).slice(1,size-1)), // Off-heap Map.entry("ByteBuffer.allocateDirect(size)", @@ -82,13 +86,17 @@ public class ByteBufferViews { size -> ByteBuffer.allocateDirect(size).position(8).slice()), Map.entry("ByteBuffer.allocateDirect(size).position(8).slice().duplicate()", size -> ByteBuffer.allocateDirect(size).position(8).slice().duplicate()), + Map.entry("ByteBuffer.allocateDirect(size).slice(8,size-8)", + size -> ByteBuffer.allocateDirect(size).slice(8,size-8)), // Unaligned Map.entry("ByteBuffer.allocateDirect(size).position(1)", size -> ByteBuffer.allocateDirect(size).position(1)), Map.entry("ByteBuffer.allocateDirect(size).position(1).slice()", size -> ByteBuffer.allocateDirect(size).position(1).slice()), Map.entry("ByteBuffer.allocateDirect(size).position(1).slice().duplicate()", - size -> ByteBuffer.allocateDirect(size).position(1).slice().duplicate()) + size -> ByteBuffer.allocateDirect(size).position(1).slice().duplicate()), + Map.entry("ByteBuffer.allocateDirect(size).slice(1,size-1)", + size -> ByteBuffer.allocateDirect(size).slice(1,size-1)) ); // List of buffer byte order functions diff --git a/test/jdk/java/nio/Buffer/StringCharBufferSliceTest.java b/test/jdk/java/nio/Buffer/StringCharBufferSliceTest.java index e730b224788..f66612e3cbc 100644 --- a/test/jdk/java/nio/Buffer/StringCharBufferSliceTest.java +++ b/test/jdk/java/nio/Buffer/StringCharBufferSliceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,11 +22,14 @@ */ /* @test - * @bug 4997655 7000913 + * @bug 4997655 5071718 7000913 * @summary (bf) CharBuffer.slice() on wrapped CharSequence results in wrong position */ -import java.nio.*; +import java.nio.CharBuffer; +import java.nio.InvalidMarkException; +import java.util.function.BiConsumer; +import java.util.function.Consumer; public class StringCharBufferSliceTest { public static void main( String[] args) throws Exception { @@ -40,85 +43,114 @@ public class StringCharBufferSliceTest { CharBuffer buff = CharBuffer.wrap(in); test(buff, buff.slice()); + test(buff, buff.slice(0, buff.remaining())); System.out.println( ">>> StringCharBufferSliceTest-main: testing with new position."); buff.position(2); test(buff, buff.slice()); + test(buff, buff.slice(2, buff.remaining())); System.out.println( ">>> StringCharBufferSliceTest-main: testing with non zero initial position."); buff = CharBuffer.wrap(in, 3, in.length()); test(buff, buff.slice()); + test(buff, buff.slice(0, buff.remaining())); System.out.println( ">>> StringCharBufferSliceTest-main: testing slice result with get()"); buff.position(4); buff.limit(7); - CharBuffer slice = buff.slice(); - for (int i = 0; i < 3; i++) { - if (slice.get() != buff.get()) { - throw new RuntimeException("Wrong characters in slice result."); + BiConsumer bitest = (b, s) -> { + for (int i = 0; i < 3; i++) { + if (s.get() != b.get()) { + throw new RuntimeException + ("Wrong characters in slice result."); + } } - } + }; + bitest.accept(buff, buff.slice()); + buff.position(4); + bitest.accept(buff, buff.slice(4, 3)); System.out.println( ">>> StringCharBufferSliceTest-main: testing slice result with get(int)"); buff.position(4); buff.limit(7); - slice = buff.slice(); - for (int i = 0; i < 3; i++) { - if (slice.get(i) != buff.get(4 + i)) { - throw new RuntimeException("Wrong characters in slice result."); + bitest = (b, s) -> { + for (int i = 0; i < 3; i++) { + if (s.get(i) != b.get(4 + i)) { + throw new RuntimeException + ("Wrong characters in slice result."); + } } - } + }; + bitest.accept(buff, buff.slice()); + buff.position(4); + bitest.accept(buff, buff.slice(4, 3)); System.out.println( ">>> StringCharBufferSliceTest-main: testing slice with result of slice"); buff.position(0); buff.limit(buff.capacity()); - slice = buff.slice(); - for (int i=0; i<4; i++) { - slice.position(i); - CharBuffer nextSlice = slice.slice(); - if (nextSlice.position() != 0) - throw new RuntimeException("New buffer's position should be zero"); - if (!nextSlice.equals(slice)) - throw new RuntimeException("New buffer should be equal"); - slice = nextSlice; - } + Consumer test = (s) -> { + for (int i=0; i<4; i++) { + s.position(i); + CharBuffer nextSlice = s.slice(); + if (nextSlice.position() != 0) + throw new RuntimeException + ("New buffer's position should be zero"); + if (!nextSlice.equals(s)) + throw new RuntimeException("New buffer should be equal"); + s = nextSlice; + } + }; + test.accept(buff.slice()); + test.accept(buff.slice(0, buff.capacity())); System.out.println( ">>> StringCharBufferSliceTest-main: testing toString."); buff.position(4); buff.limit(7); - slice = buff.slice(); - if (!slice.toString().equals("tes")) { - throw new RuntimeException("bad toString() after slice(): " + slice.toString()); - } + test = (s) -> { + if (!s.toString().equals("tes")) { + throw new RuntimeException + ("bad toString() after slice(): " + s.toString()); + } + }; + test.accept(buff.slice()); + test.accept(buff.slice(4, 3)); System.out.println( ">>> StringCharBufferSliceTest-main: testing subSequence."); buff.position(4); buff.limit(8); - slice = buff.slice(); - CharSequence subSeq = slice.subSequence(1, 3); - if (subSeq.charAt(0) != 'e' || subSeq.charAt(1) != 's') { - throw new RuntimeException("bad subSequence() after slice(): '" + subSeq + "'"); - } + test = (s) -> { + CharSequence subSeq = s.subSequence(1, 3); + if (subSeq.charAt(0) != 'e' || subSeq.charAt(1) != 's') { + throw new RuntimeException + ("bad subSequence() after slice(): '" + subSeq + "'"); + } + }; + test.accept(buff.slice()); + test.accept(buff.slice(4, 4)); System.out.println( ">>> StringCharBufferSliceTest-main: testing duplicate."); buff.position(4); buff.limit(8); - slice = buff.slice(); - CharBuffer dupe = slice.duplicate(); - if (dupe.charAt(0) != 't' || dupe.charAt(1) != 'e' - || dupe.charAt(2) != 's' || dupe.charAt(3) != 't') { - throw new RuntimeException("bad duplicate() after slice(): '" + dupe + "'"); - } + test = (s) -> { + CharBuffer dupe = s.duplicate(); + if (dupe.charAt(0) != 't' || dupe.charAt(1) != 'e' + || dupe.charAt(2) != 's' || dupe.charAt(3) != 't') { + throw new RuntimeException + ("bad duplicate() after slice(): '" + dupe + "'"); + } + }; + test.accept(buff.slice()); + test.accept(buff.slice(4, 4)); System.out.println(">>> StringCharBufferSliceTest-main: done!"); } diff --git a/test/jdk/java/nio/channels/AsyncCloseAndInterrupt.java b/test/jdk/java/nio/channels/AsyncCloseAndInterrupt.java index cbb28aa2ba8..31f87137838 100644 --- a/test/jdk/java/nio/channels/AsyncCloseAndInterrupt.java +++ b/test/jdk/java/nio/channels/AsyncCloseAndInterrupt.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -182,7 +182,7 @@ public class AsyncCloseAndInterrupt { = new ChannelFactory("DatagramChannel") { InterruptibleChannel create() throws IOException { DatagramChannel dc = DatagramChannel.open(); - InetAddress lb = InetAddress.getByName("127.0.0.1"); + InetAddress lb = InetAddress.getLoopbackAddress(); dc.bind(new InetSocketAddress(lb, 0)); dc.connect(new InetSocketAddress(lb, 80)); return dc; diff --git a/test/jdk/java/nio/channels/AsynchronousChannelGroup/bootlib/Attack.java b/test/jdk/java/nio/channels/AsynchronousChannelGroup/bootlib/Attack.java index c0317632443..ae0bf64d037 100644 --- a/test/jdk/java/nio/channels/AsynchronousChannelGroup/bootlib/Attack.java +++ b/test/jdk/java/nio/channels/AsynchronousChannelGroup/bootlib/Attack.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,7 @@ */ import java.io.IOException; +import java.net.InetAddress; import java.net.Socket; import java.util.concurrent.CountDownLatch; @@ -42,7 +43,7 @@ public class Attack implements Runnable { @Override public void run() { try { - new Socket("127.0.0.1", 9999).close(); + new Socket(InetAddress.getLoopbackAddress(), 9999).close(); throw new RuntimeException("Connected (not expected)"); } catch (IOException e) { throw new RuntimeException("IOException (not expected)"); diff --git a/test/jdk/java/nio/channels/Selector/LotsOfCancels.java b/test/jdk/java/nio/channels/Selector/LotsOfCancels.java index 79df4b83625..8c22d3dfdcc 100644 --- a/test/jdk/java/nio/channels/Selector/LotsOfCancels.java +++ b/test/jdk/java/nio/channels/Selector/LotsOfCancels.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 Google Inc. All Rights Reserved. + * Copyright 2009, 2019, Google Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,7 @@ * questions. */ +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SelectionKey; @@ -87,7 +88,7 @@ public class LotsOfCancels { throws Exception { testStartTime = System.nanoTime(); - InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359); + InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 7359); // Create server channel, add it to selector and run epoll_ctl. log("Setting up server"); diff --git a/test/jdk/java/nio/channels/SocketChannel/AsyncCloseChannel.java b/test/jdk/java/nio/channels/SocketChannel/AsyncCloseChannel.java index eb33b840e0d..2561c5b9b06 100644 --- a/test/jdk/java/nio/channels/SocketChannel/AsyncCloseChannel.java +++ b/test/jdk/java/nio/channels/SocketChannel/AsyncCloseChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ */ import java.io.IOException; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; @@ -39,7 +40,6 @@ public class AsyncCloseChannel { static volatile boolean keepGoing = true; static int maxAcceptCount = 100; static volatile int acceptCount = 0; - static String host = "127.0.0.1"; static int sensorPort; static int targetPort; @@ -149,7 +149,7 @@ public class AsyncCloseChannel { } wake = false; } - s.connect(new InetSocketAddress(host, sensorPort)); + s.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), sensorPort)); try { Thread.sleep(10); } catch (InterruptedException ex) { } @@ -183,7 +183,7 @@ public class AsyncCloseChannel { while(keepGoing) { try { final SocketChannel s = SocketChannel.open( - new InetSocketAddress(host, targetPort)); + new InetSocketAddress(InetAddress.getLoopbackAddress(), targetPort)); s.finishConnect(); s.socket().setSoLinger(false, 0); ready = false; diff --git a/test/jdk/java/nio/channels/SocketChannel/CloseRegisteredChannel.java b/test/jdk/java/nio/channels/SocketChannel/CloseRegisteredChannel.java index 216d6be160b..04b752fd79d 100644 --- a/test/jdk/java/nio/channels/SocketChannel/CloseRegisteredChannel.java +++ b/test/jdk/java/nio/channels/SocketChannel/CloseRegisteredChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,7 +41,7 @@ public class CloseRegisteredChannel { //System.out.println ("listening on port " + port); SocketChannel client = SocketChannel.open (); - client.connect (new InetSocketAddress ("127.0.0.1", port)); + client.connect (new InetSocketAddress (InetAddress.getLoopbackAddress(), port)); SocketChannel slave = server.accept (); slave.configureBlocking (true); diff --git a/test/jdk/java/nio/channels/SocketChannel/CloseTimeoutChannel.java b/test/jdk/java/nio/channels/SocketChannel/CloseTimeoutChannel.java index a09c4bef452..10fdcaaaea6 100644 --- a/test/jdk/java/nio/channels/SocketChannel/CloseTimeoutChannel.java +++ b/test/jdk/java/nio/channels/SocketChannel/CloseTimeoutChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public class CloseTimeoutChannel { try { System.out.println("Establishing connection"); Socket socket=SocketChannel.open( - new InetSocketAddress("127.0.0.1", port)).socket(); + new InetSocketAddress(InetAddress.getLoopbackAddress(), port)).socket(); OutputStream out=socket.getOutputStream(); InputStream in=socket.getInputStream(); diff --git a/test/jdk/java/nio/channels/SocketChannel/SocketInheritance.java b/test/jdk/java/nio/channels/SocketChannel/SocketInheritance.java index 1df065d2724..18e26b38c55 100644 --- a/test/jdk/java/nio/channels/SocketChannel/SocketInheritance.java +++ b/test/jdk/java/nio/channels/SocketChannel/SocketInheritance.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -65,7 +65,7 @@ public class SocketInheritance { // connect to the given port static SocketChannel connect(int port) throws IOException { - InetAddress lh = InetAddress.getByName("127.0.0.1"); + InetAddress lh = InetAddress.getLoopbackAddress(); InetSocketAddress isa = new InetSocketAddress(lh, port); return SocketChannel.open(isa); } diff --git a/test/jdk/java/nio/channels/etc/AdaptorCloseAndInterrupt.java b/test/jdk/java/nio/channels/etc/AdaptorCloseAndInterrupt.java index 368437a3803..5da7ed90db5 100644 --- a/test/jdk/java/nio/channels/etc/AdaptorCloseAndInterrupt.java +++ b/test/jdk/java/nio/channels/etc/AdaptorCloseAndInterrupt.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,7 +93,7 @@ public class AdaptorCloseAndInterrupt { void scReadAsyncClose() throws IOException { try { SocketChannel sc = SocketChannel.open(new InetSocketAddress( - "127.0.0.1", port)); + InetAddress.getLoopbackAddress(), port)); sc.socket().setSoTimeout(30*1000); doAsyncClose(sc); @@ -115,7 +115,7 @@ public class AdaptorCloseAndInterrupt { void scReadAsyncInterrupt() throws IOException { try { final SocketChannel sc = SocketChannel.open(new InetSocketAddress( - "127.0.0.1", port)); + InetAddress.getLoopbackAddress(), port)); sc.socket().setSoTimeout(30*1000); doAsyncInterrupt(); @@ -141,7 +141,7 @@ public class AdaptorCloseAndInterrupt { void dcReceiveAsyncClose() throws IOException { DatagramChannel dc = DatagramChannel.open(); dc.connect(new InetSocketAddress( - "127.0.0.1", port)); + InetAddress.getLoopbackAddress(), port)); dc.socket().setSoTimeout(30*1000); doAsyncClose(dc); @@ -159,7 +159,7 @@ public class AdaptorCloseAndInterrupt { void dcReceiveAsyncInterrupt() throws IOException { DatagramChannel dc = DatagramChannel.open(); dc.connect(new InetSocketAddress( - "127.0.0.1", port)); + InetAddress.getLoopbackAddress(), port)); dc.socket().setSoTimeout(30*1000); doAsyncInterrupt(); diff --git a/test/jdk/java/nio/channels/etc/Shadow.java b/test/jdk/java/nio/channels/etc/Shadow.java index fe75d9953dc..5ee3ebdb86e 100644 --- a/test/jdk/java/nio/channels/etc/Shadow.java +++ b/test/jdk/java/nio/channels/etc/Shadow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -107,7 +107,7 @@ public class Shadow { // connect client socket to port SocketAddress connectAddr = - new InetSocketAddress("127.0.0.1", + new InetSocketAddress(InetAddress.getLoopbackAddress(), serverSocket.getLocalPort()); socket.connect(connectAddr); log.println("connected Socket: " + socket); diff --git a/test/jdk/java/nio/charset/coders/StreamTimeout.java b/test/jdk/java/nio/charset/coders/StreamTimeout.java index 1d8f1175c32..7f570cb5a2f 100644 --- a/test/jdk/java/nio/charset/coders/StreamTimeout.java +++ b/test/jdk/java/nio/charset/coders/StreamTimeout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,7 @@ import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; +import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; @@ -47,7 +48,7 @@ public class StreamTimeout { private final Socket so; Client(int port) throws IOException { - so = new Socket("127.0.0.1", port); + so = new Socket(InetAddress.getLoopbackAddress(), port); } @Override diff --git a/test/jdk/java/rmi/transport/readTimeout/ReadTimeoutTest.java b/test/jdk/java/rmi/transport/readTimeout/ReadTimeoutTest.java index 702b8796e7c..d10ca072f10 100644 --- a/test/jdk/java/rmi/transport/readTimeout/ReadTimeoutTest.java +++ b/test/jdk/java/rmi/transport/readTimeout/ReadTimeoutTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,9 +82,9 @@ public class ReadTimeoutTest // Now, connect to that port //Thread.sleep(2000); - System.err.println("(connecting to listening port on 127.0.0.1:" + + System.err.println("(connecting to listening port on localhost:" + port + ")"); - DoS = new Socket("127.0.0.1", port); + DoS = new Socket(InetAddress.getLoopbackAddress(), port); InputStream stream = DoS.getInputStream(); // Read on the socket in the background diff --git a/test/jdk/java/security/BasicPermission/Wildcard.java b/test/jdk/java/security/BasicPermission/Wildcard.java index 9a7441defb2..08023956c25 100644 --- a/test/jdk/java/security/BasicPermission/Wildcard.java +++ b/test/jdk/java/security/BasicPermission/Wildcard.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,8 +33,7 @@ import javax.net.ssl.SSLPermission; * @summary Check that BasicPermission subclasses don't throw exception if name * contains wildcard character ("*") but does not signify a * wildcard match - * @modules java.base/com.sun.net.ssl - * java.sql + * @modules java.sql */ public class Wildcard { @@ -51,6 +50,5 @@ public class Wildcard { new SQLPermission(wildcard); new PropertyPermission(wildcard, "read"); new SSLPermission(wildcard); - new com.sun.net.ssl.SSLPermission(wildcard); } } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java index 55e95daddba..45f5de44af9 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* * @test - * @bug 8177552 + * @bug 8177552 8217721 * @summary Checks the functioning of compact number format * @modules jdk.localedata * @run testng/othervm TestCompactNumber @@ -528,6 +528,11 @@ public class TestCompactNumber { .getCompactNumberInstance(l, NumberFormat.Style.LONG).format(10000)); } + @Test(expectedExceptions = IllegalArgumentException.class) + public void testFormatWithNullParam() { + FORMAT_EN_US_SHORT.format(null); + } + @Test(dataProvider = "format") public void testFormat(NumberFormat cnf, Object number, String expected) { diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java index 962393eaff3..8fb0d645fec 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* * @test - * @bug 8177552 + * @bug 8177552 8217254 * @summary Checks the validity of compact number patterns specified through * CompactNumberFormat constructor * @run testng/othervm TestCompactPatternsValidity @@ -80,7 +80,9 @@ public class TestCompactPatternsValidity { // A non empty pattern containing no 0s (min integer digits) {new String[]{"K", "0K", "00K"}}, // 0s (min integer digits) exceeding for the range at index 3 - {new String[]{"", "", "0K", "00000K"}},}; + {new String[]{"", "", "0K", "00000K"}}, + // null as a compact pattern + {new String[]{"", "", null, "00K"}},}; } @DataProvider(name = "validPatternsFormat") @@ -124,7 +126,7 @@ public class TestCompactPatternsValidity { } @Test(dataProvider = "invalidPatterns", - expectedExceptions = RuntimeException.class) + expectedExceptions = IllegalArgumentException.class) public void testInvalidCompactPatterns(String[] compactPatterns) { new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols .getInstance(Locale.US), compactPatterns); diff --git a/test/jdk/java/text/Format/DateFormat/SDFTCKZoneNamesTest.java b/test/jdk/java/text/Format/DateFormat/SDFTCKZoneNamesTest.java new file mode 100644 index 00000000000..a9f2e30a4d0 --- /dev/null +++ b/test/jdk/java/text/Format/DateFormat/SDFTCKZoneNamesTest.java @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8218948 + * @summary TCK tests that check the time zone names between DFS.getZoneStrings() + * and SDF.format("z*") + * @run main SDFTCKZoneNamesTest + */ +import java.text.*; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; + +public class SDFTCKZoneNamesTest { + + StringBuffer myFormat(Date date, SimpleDateFormat sdf) { + String pattern = sdf.toPattern(); + StringBuffer toAppendTo = new StringBuffer(""); + boolean inQuote = false; + char prevCh = 0; + char ch; + int count = 0; + for (int i = 0; i < pattern.length(); i++) { + ch = pattern.charAt(i); + if (inQuote) { + if (ch == '\'') { + inQuote = false; + if (count == 0) toAppendTo.append(ch); + else count = 0; + } else { + toAppendTo.append(ch); + count++; + } + } else { // not inQuote + if (ch == '\'') { + inQuote = true; + if (count > 0) { + toAppendTo.append(subFormat(prevCh, count, date, sdf)); + count = 0; + prevCh = 0; + } + } else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') { + if (ch != prevCh && count > 0) { + toAppendTo.append(subFormat(prevCh, count, date, sdf)); + prevCh = ch; + count = 1; + } else { + if (ch != prevCh) prevCh = ch; + count++; + } + } else if (count > 0) { + toAppendTo.append(subFormat(prevCh, count, date, sdf)); + toAppendTo.append(ch); + prevCh = 0; + count = 0; + } else toAppendTo.append(ch); + } + } + if (count > 0) { + toAppendTo.append(subFormat(prevCh, count, date, sdf)); + } + return toAppendTo; + } + + private String subFormat(char ch, int count, Date date, SimpleDateFormat sdf) + throws IllegalArgumentException { + int value = 0; + int patternCharIndex = -1; + int maxIntCount = 10; + String current = ""; + DateFormatSymbols formatData = sdf.getDateFormatSymbols(); + Calendar calendar = sdf.getCalendar(); + calendar.setTime(date); + NumberFormat nf = sdf.getNumberFormat(); + nf.setGroupingUsed(false); + + if ((patternCharIndex = "GyMdkHmsSEDFwWahKz".indexOf(ch)) == -1) + throw new IllegalArgumentException("Illegal pattern character " + + "'" + ch + "'"); + switch (patternCharIndex) { + case 0: // 'G' - ERA + value = calendar.get(Calendar.ERA); + current = formatData.getEras()[value]; + break; + case 1: // 'y' - YEAR + value = calendar.get(Calendar.YEAR); + + if (count == 2) { + // For formatting, if the number of pattern letters is 2, + // the year is truncated to 2 digits; + current = zeroPaddingNumber(value, 2, 2, nf); + } else { + // otherwise it is interpreted as a number. + current = zeroPaddingNumber(value, count, maxIntCount, nf); + } + + break; + case 2: // 'M' - MONTH + value = calendar.get(Calendar.MONTH); + if (count >= 4) + // DateFormatSymbols::getMonths spec: "If the language requires different forms for formatting + // and stand-alone usages, this method returns month names in the formatting form." + // Because of that only formatting cases patterns may be tested. Like, "MMMM yyyy". Wrong + // pattern: "MMMM". + current = formatData.getMonths()[value]; + else if (count == 3) + // DateFormatSymbols::getShortMonths spec: "If the language requires different forms for formatting + // and stand-alone usages, This method returns short month names in the formatting form." + // Because of that only formatting cases patterns may be tested. Like, "MMM yyyy". Wrong pattern: + // "MMM". + current = formatData.getShortMonths()[value]; + else + current = zeroPaddingNumber(value + 1, count, maxIntCount, nf); + break; + case 3: // 'd' - DATE + value = calendar.get(Calendar.DATE); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 4: // 'k' - HOUR_OF_DAY: 1-based. eg, 23:59 + 1 hour =>> 24:59 + if ((value = calendar.get(Calendar.HOUR_OF_DAY)) == 0) + current = zeroPaddingNumber( + calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1, + count, maxIntCount, nf); + else + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 5: // 'H' - HOUR_OF_DAY:0-based. eg, 23:59 + 1 hour =>> 00:59 + value = calendar.get(Calendar.HOUR_OF_DAY); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 6: // 'm' - MINUTE + value = calendar.get(Calendar.MINUTE); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 7: // 's' - SECOND + value = calendar.get(Calendar.SECOND); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 8: // 'S' - MILLISECOND + value = calendar.get(Calendar.MILLISECOND); + /* + if (count > 3) + value = value * (int) Math.pow(10, count - 3); + else if (count == 2) + value = (value + 5) / 10; + else if (count == 1) + value = (value + 50) / 100; + */ + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 9: // 'E' - DAY_OF_WEEK + value = calendar.get(Calendar.DAY_OF_WEEK); + if (count >= 4) + current = formatData.getWeekdays()[value]; + else // count < 4, use abbreviated form if exists + current = formatData.getShortWeekdays()[value]; + break; + case 10: // 'D' - DAY_OF_YEAR + value = calendar.get(Calendar.DAY_OF_YEAR); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 11: // 'F' - DAY_OF_WEEK_IN_MONTH + value = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 12: // 'w' - WEEK_OF_YEAR + value = calendar.get(Calendar.WEEK_OF_YEAR); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 13: // 'W' - WEEK_OF_MONTH + value = calendar.get(Calendar.WEEK_OF_MONTH); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 14: // 'a' - AM_PM + value = calendar.get(Calendar.AM_PM); + current = formatData.getAmPmStrings()[value]; + break; + case 15: // 'h' - HOUR:1-based. eg, 11PM + 1 hour =>> 12 AM + if ((value = calendar.get(Calendar.HOUR)) == 0) + current = zeroPaddingNumber( + calendar.getLeastMaximum(Calendar.HOUR) + 1, + count, maxIntCount, nf); + else + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 16: // 'K' - HOUR: 0-based. eg, 11PM + 1 hour =>> 0 AM + value = calendar.get(Calendar.HOUR); + current = zeroPaddingNumber(value, count, maxIntCount, nf); + break; + case 17: // 'z' - ZONE_OFFSET + int zoneIndex = getZoneIndex(calendar.getTimeZone().getID(), formatData); + if (zoneIndex == -1) { + StringBuffer zoneString = new StringBuffer(); + value = calendar.get(Calendar.ZONE_OFFSET) + + calendar.get(Calendar.DST_OFFSET); + if (value < 0) { + zoneString.append("GMT-"); + value = -value; // suppress the '-' sign for text display. + } else + zoneString.append("GMT+"); + zoneString.append( + zeroPaddingNumber((int) (value / (60 * 60 * 1000)), 2, 2, nf)); + zoneString.append(':'); + zoneString.append( + zeroPaddingNumber( + (int) ((value % (60 * 60 * 1000)) / (60 * 1000)), 2, 2, nf)); + current = zoneString.toString(); + } else if (calendar.get(Calendar.DST_OFFSET) != 0) { + if (count >= 4) + current = formatData.getZoneStrings()[zoneIndex][3]; + else + // count < 4, use abbreviated form if exists + current = formatData.getZoneStrings()[zoneIndex][4]; + } else { + if (count >= 4) + current = formatData.getZoneStrings()[zoneIndex][1]; + else + current = formatData.getZoneStrings()[zoneIndex][2]; + } + break; + } + + return current; + } + + + String zeroPaddingNumber(long value, int minDigits, int maxDigits, + NumberFormat nf) { + nf.setMinimumIntegerDigits(minDigits); + nf.setMaximumIntegerDigits(maxDigits); + return nf.format(value); + } + + + int getZoneIndex(String ID, DateFormatSymbols dfs) { + String[][] zoneStrings = dfs.getZoneStrings(); + + for (int index = 0; index < zoneStrings.length; index++) { + if (ID.equalsIgnoreCase(zoneStrings[index][0])) return index; + } + return -1; + } + + + final int second = 1000; + final int minute = 60 * second; + final int hour = 60 * minute; + final int day = 24 * hour; + final int month = 30 * day; + final int year = 365 * day; + final int someday = 30 * year + 3 * month + 19 * day + 5 * hour; + + + /* standalone interface */ + public static void main(String argv[]) { + Locale defaultLocale = Locale.getDefault(); + SDFTCKZoneNamesTest test = new SDFTCKZoneNamesTest(); + + try { + List.of(Locale.ROOT, + Locale.CHINA, + Locale.forLanguageTag("es-419"), + Locale.GERMANY, + Locale.forLanguageTag("hi-IN"), + Locale.JAPAN, + Locale.TAIWAN, + Locale.UK, + Locale.US, + Locale.forLanguageTag("uz-Cyrl-UZ"), + Locale.forLanguageTag("zh-SG"), + Locale.forLanguageTag("zh-HK"), + Locale.forLanguageTag("zh-MO")).stream() + .forEach(l -> { + System.out.printf("Testing locale: %s%n", l); + Locale.setDefault(l); + test.SimpleDateFormat0062(); + }); + } finally { + Locale.setDefault(defaultLocale); + } + } + + + /** + * Equivalence class partitioning + * with state, input and output values orientation + * for public StringBuffer format(Date date, StringBuffer result, FieldPosition fp), + *
    pre-conditions: patterns: { "'s0mething'z mm::hh,yyyy zz", + * "zzzz", + * "z"} (each pattern contains letter for TIMEZONE_FIELD), + *
    date: a Date object + *
    result: a string + *
    fp: a FieldPosition object with TIMEZONE_FIELD field + *
    output: formatted date as expected. + */ + public void SimpleDateFormat0062() { + boolean passed = true; + String patterns[] = {"'s0mething'z mm::hh,yyyy zz", + "zzzz", + "z"}; + SimpleDateFormat sdf = new SimpleDateFormat(); + Date date = new Date(1234567890); + for (String[] tz : sdf.getDateFormatSymbols().getZoneStrings()) { + sdf.setTimeZone(TimeZone.getTimeZone(tz[0])); + for (int i = 0; i < patterns.length && passed; i++) { + StringBuffer result = new StringBuffer("qwerty"); + FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD); + sdf.applyPattern(patterns[i]); + String expected = new + StringBuffer("qwerty").append(myFormat(date, + sdf)).toString(); + String formatted = sdf.format(date, result, fp).toString(); + + if (!expected.equals(formatted)) { + System.out.println( + "method format(date, StringBuffer, FieldPosition) formats wrong"); + System.out.println(" pattern: " + patterns[i]); + System.out.println(" time zone ID: " + tz[0]); + System.out.println(" expected result: " + expected); + System.out.println(" formatted result: " + formatted); + passed = false; + } + + if (passed && !expected.equals(result.toString())) { + System.out.println( + "method format(Date date, StringBuffer toAppendTo, FieldPosition fp) toAppendTo is not " + + "equal to output"); + System.out.println(" pattern: " + patterns[i]); + System.out.println(" time zone ID: " + tz[0]); + System.out.println(" toAppendTo : " + result); + System.out.println(" formatted date: " + formatted); + passed = false; + } + } + } + if(passed) + { + System.out.println("PASSED : OKAY"); + }else + { + throw new RuntimeException("FAILED"); + } + } +} diff --git a/test/jdk/java/util/Arrays/TimSortStackSize2.java b/test/jdk/java/util/Arrays/TimSortStackSize2.java index 85eeaad109f..2d028f4a4b4 100644 --- a/test/jdk/java/util/Arrays/TimSortStackSize2.java +++ b/test/jdk/java/util/Arrays/TimSortStackSize2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * @library /test/lib * @modules java.management * java.base/jdk.internal + * @requires (vm.debug == false) * @build TimSortStackSize2 * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission diff --git a/test/jdk/java/util/Calendar/JapaneseEraNameTest.java b/test/jdk/java/util/Calendar/JapaneseEraNameTest.java index 7760a939de0..430bd86a871 100644 --- a/test/jdk/java/util/Calendar/JapaneseEraNameTest.java +++ b/test/jdk/java/util/Calendar/JapaneseEraNameTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8202088 8207152 8217609 + * @bug 8202088 8207152 8217609 8219890 * @summary Test the localized Japanese new era name (May 1st. 2019-) * is retrieved no matter CLDR provider contains the name or not. * @modules jdk.localedata @@ -53,8 +53,10 @@ public class JapaneseEraNameTest { // type, locale, name { LONG, JAPAN, "\u5143\u53f7" }, // NewEra { LONG, US, "NewEra" }, + { LONG, CHINA, "NewEra" }, { SHORT, JAPAN, "\u5143\u53f7" }, { SHORT, US, "NewEra" }, + { SHORT, CHINA, "N" }, }; } diff --git a/test/jdk/java/util/Locale/LocaleProviders.java b/test/jdk/java/util/Locale/LocaleProviders.java index f256677b504..342ea91fd1d 100644 --- a/test/jdk/java/util/Locale/LocaleProviders.java +++ b/test/jdk/java/util/Locale/LocaleProviders.java @@ -72,6 +72,10 @@ public class LocaleProviders { bug8027289Test(args[1]); break; + case "bug8220227Test": + bug8220227Test(); + break; + default: throw new RuntimeException("Test method '"+methodName+"' not found."); } @@ -249,4 +253,15 @@ public class LocaleProviders { } } } + + static void bug8220227Test() { + if (System.getProperty("os.name").startsWith("Windows")) { + Locale l = new Locale("xx","XX"); + String country = l.getDisplayCountry(); + if (country.endsWith("(XX)")) { + throw new RuntimeException( + "Unexpected Region name: " + country); + } + } + } } diff --git a/test/jdk/java/util/Locale/LocaleProvidersRun.java b/test/jdk/java/util/Locale/LocaleProvidersRun.java index 958642c6dfe..6770cf281ad 100644 --- a/test/jdk/java/util/Locale/LocaleProvidersRun.java +++ b/test/jdk/java/util/Locale/LocaleProvidersRun.java @@ -25,7 +25,7 @@ * @test * @bug 6336885 7196799 7197573 7198834 8000245 8000615 8001440 8008577 * 8010666 8013086 8013233 8013903 8015960 8028771 8054482 8062006 - * 8150432 8215913 + * 8150432 8215913 8220227 * @summary tests for "java.locale.providers" system property * @library /test/lib * @build LocaleProviders @@ -148,6 +148,12 @@ public class LocaleProvidersRun { testRun("COMPAT,HOST", "bug8027289Test", "FFE5", "", ""); testRun("HOST", "bug8027289Test", "00A5", "", ""); } + + //testing 8220227 fix. (Windows only) + if (!defLang.equals("en")) { + testRun("HOST", "bug8220227Test", "", "", ""); + } + } private static void testRun(String prefList, String methodName, diff --git a/test/jdk/java/util/logging/TestLoggerWeakRefLeak.java b/test/jdk/java/util/logging/TestLoggerWeakRefLeak.java index 0929b5341ff..f9d05af6cd2 100644 --- a/test/jdk/java/util/logging/TestLoggerWeakRefLeak.java +++ b/test/jdk/java/util/logging/TestLoggerWeakRefLeak.java @@ -123,7 +123,7 @@ public class TestLoggerWeakRefLeak { } /** - * 'vm.heapHisto("", "-live")' will request a full GC + * 'vm.heapHisto("-live")' will request a full GC */ private static int getInstanceCountFromHeapHisto() throws AttachNotSupportedException, Exception { int instanceCount = 0; @@ -131,7 +131,7 @@ public class TestLoggerWeakRefLeak { HotSpotVirtualMachine vm = (HotSpotVirtualMachine) VirtualMachine .attach(Long.toString(ProcessTools.getProcessId())); try { - try (InputStream heapHistoStream = vm.heapHisto("", "-live"); + try (InputStream heapHistoStream = vm.heapHisto("-live"); BufferedReader in = new BufferedReader(new InputStreamReader(heapHistoStream))) { String inputLine; while ((inputLine = in.readLine()) != null) { diff --git a/test/jdk/javax/crypto/SecretKeyFactory/SecKeyFacSunJCEPrf.java b/test/jdk/javax/crypto/SecretKeyFactory/SecKeyFacSunJCEPrf.java new file mode 100644 index 00000000000..356beb31a53 --- /dev/null +++ b/test/jdk/javax/crypto/SecretKeyFactory/SecKeyFacSunJCEPrf.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8218723 + * @summary Use SunJCE Mac in SecretKeyFactory PBKDF2 implementation + * @library evilprov.jar + * @library /test/lib + * @build jdk.test.lib.Convert + * @run main/othervm SecKeyFacSunJCEPrf + */ + +import java.util.Arrays; +import javax.crypto.SecretKeyFactory; +import javax.crypto.SecretKey; +import javax.crypto.spec.PBEKeySpec; +import java.security.Provider; +import java.security.Security; +import com.evilprovider.*; +import jdk.test.lib.Convert; + +public class SecKeyFacSunJCEPrf { + + // One of the PBKDF2 HMAC-SHA1 test vectors from RFC 6070 + private static final byte[] SALT = "salt".getBytes(); + private static final char[] PASS = "password".toCharArray(); + private static final int ITER = 4096; + private static final byte[] EXP_OUT = Convert.hexStringToByteArray( + "4B007901B765489ABEAD49D926F721D065A429C1"); + + public static void main(String[] args) throws Exception { + // Instantiate the Evil Provider and insert it in the + // most-preferred position. + Provider evilProv = new EvilProvider(); + System.out.println("3rd Party Provider: " + evilProv); + Security.insertProviderAt(evilProv, 1); + + SecretKeyFactory pbkdf2 = + SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1", "SunJCE"); + PBEKeySpec pbks = new PBEKeySpec(PASS, SALT, ITER, 160); + + SecretKey secKey1 = pbkdf2.generateSecret(pbks); + System.out.println("PBKDF2WithHmacSHA1:\n" + + Convert.byteArrayToHexString(secKey1.getEncoded())); + if (Arrays.equals(secKey1.getEncoded(), EXP_OUT)) { + System.out.println("Test Vector Passed"); + } else { + System.out.println("Test Vector Failed"); + System.out.println("Expected Output:\n" + + Convert.byteArrayToHexString(EXP_OUT)); + throw new RuntimeException(); + } + } +} + diff --git a/test/jdk/javax/crypto/SecretKeyFactory/evilprov.jar b/test/jdk/javax/crypto/SecretKeyFactory/evilprov.jar new file mode 100644 index 00000000000..5d73de23ee3 Binary files /dev/null and b/test/jdk/javax/crypto/SecretKeyFactory/evilprov.jar differ diff --git a/test/jdk/javax/crypto/SecretKeyFactory/evilprov/Makefile b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/Makefile new file mode 100644 index 00000000000..918c31f0947 --- /dev/null +++ b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/Makefile @@ -0,0 +1,55 @@ +# +# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Java paths +#JAVA_BASE=PATH_TO_JAVA_IMG_DIR +JAVABIN=$(JAVA_BASE)/bin +JAVAC=$(JAVABIN)/javac +JAVA=$(JAVABIN)/java +JAR=$(JAVABIN)/jar +JARSIGNER=$(JAVABIN)/jarsigner + +# Compile-time flags and paths +JFLAGS=-Xlint:all +SRCPATH=com/evilprovider +CLASSDST=classes + +PROVJAR=evilprov.jar +KSTORE=PATH_TO_KEYSTORE +KALIAS=PLACE_SIGNING_ALIAS_HERE +MODVER=1.0 + +all: $(PROVJAR) + +%.class: %.java + mkdir -p $(CLASSDST) + $(JAVAC) -d $(CLASSDST) $(JFLAGS) $< + +$(PROVJAR): $(SRCPATH)/EvilHmacSHA1.class $(SRCPATH)/EvilProvider.class module-info.class + $(JAR) --create --file $(PROVJAR) --module-version $(MODVER) -C $(CLASSDST) . + +signed: $(PROVJAR) + jarsigner -keystore $(KSTORE) $(PROVJAR).jar $(KALIAS) + +clean: + rm -rf $(CLASSDST) $(PROVJAR) diff --git a/test/jdk/javax/crypto/SecretKeyFactory/evilprov/README b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/README new file mode 100644 index 00000000000..3bc33a4529e --- /dev/null +++ b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/README @@ -0,0 +1,15 @@ +Everything in this directory is dedicated to building the EvilProvider +used with the SecKeyFacSunJCEPRF test (JDK-8218723). + +The makefile does require a JDK image path to be provided through the +JAVA_BASE makefile variable. As an example: + +make JAVA_BASE=/usr/java/jdk-11.0.1 evilprov + +Since the EvilProvider is a modular jar, JDK 9 or later should be used. + +For OpenJDK, no signing is required. If signing is required (for use +with Oracle JDK, for instance), you must obtain a JCE signing certificate +and place it in a keystore, then run the "signed" makefile target (it will +build the jar file if it does not already exist). + diff --git a/test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilHmacSHA1.java b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilHmacSHA1.java new file mode 100644 index 00000000000..017535a8bc4 --- /dev/null +++ b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilHmacSHA1.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.evilprovider; + +import java.security.*; +import java.security.spec.*; +import java.nio.ByteBuffer; + +import javax.crypto.*; + +public final class EvilHmacSHA1 extends MacSpi { + private final Mac internalMac; + + public EvilHmacSHA1() throws GeneralSecurityException { + internalMac = Mac.getInstance("HmacSHA1", "SunJCE"); + } + + @Override + protected byte[] engineDoFinal() { + return internalMac.doFinal(); + } + + @Override + protected int engineGetMacLength() { + return internalMac.getMacLength(); + } + + @Override + protected void engineInit(Key key, AlgorithmParameterSpec spec) + throws InvalidKeyException, InvalidAlgorithmParameterException { + SecretKey sKey; + if (key instanceof SecretKey) { + sKey = (SecretKey)key; + } else { + throw new IllegalArgumentException("Key must be a SecretKey"); + } + + byte[] sKeyEnc = sKey.getEncoded(); + int keyBits = sKeyEnc.length * 8; + if (keyBits < 160) { + throw new IllegalArgumentException("Key must be at least 160 bits"); + } + + // Pass through to init + internalMac.init(key, spec); + } + + @Override + protected void engineReset() { + internalMac.reset(); + } + + @Override + protected void engineUpdate(byte input) { + internalMac.update(input); + } + + @Override + protected void engineUpdate(byte[] input, int offset, int len) { + internalMac.update(input, offset, len); + } + + @Override + protected void engineUpdate(ByteBuffer input) { + internalMac.update(input); + } +} diff --git a/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilProvider.java similarity index 69% rename from src/java.base/share/classes/com/sun/net/ssl/KeyManager.java rename to test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilProvider.java index 903e2578e79..2976e8db206 100644 --- a/src/java.base/share/classes/com/sun/net/ssl/KeyManager.java +++ b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/com/evilprovider/EvilProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,20 +23,18 @@ * questions. */ -/* - * NOTE: this file was copied from javax.net.ssl.KeyManager - */ +package com.evilprovider; -package com.sun.net.ssl; +import java.security.*; -/** - * Base interface for JSSE key managers. These manage the - * key material which is used to authenticate to the peer - * of a secure socket. - * - * @deprecated As of JDK 1.4, this implementation-specific class was - * replaced by {@link javax.net.ssl.KeyManager}. - */ -@Deprecated(since="1.4") -public interface KeyManager { +public final class EvilProvider extends Provider { + + private static final long serialVersionUID = 11223344550000L; + + public EvilProvider() { + super("EvilProvider", "1.0", "Evil Provider"); + putService(new Provider.Service(this, "Mac", "HmacSHA1", + "com.evilprovider.EvilHmacSHA1", null, null)); + } } + diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlVersion.java b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/module-info.java similarity index 81% rename from src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlVersion.java rename to test/jdk/javax/crypto/SecretKeyFactory/evilprov/module-info.java index c3b3e6ded5e..d971726946c 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlVersion.java +++ b/test/jdk/javax/crypto/SecretKeyFactory/evilprov/module-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,15 +23,13 @@ * questions. */ -package jdk.javadoc.internal.doclets.formats.html.markup; - /** - * Enum representing the version of HTML generated by javadoc. + * Provides the evil provider * - * @author Bhavesh Patel + * @provides java.security.Provider + * + * @moduleGraph */ -public enum HtmlVersion { - HTML4, - HTML5, - ALL +module jdk.evilprovider { + provides java.security.Provider with com.evilprovider.EvilProvider; } diff --git a/test/jdk/javax/net/ssl/FixingJavadocs/ComURLNulls.java b/test/jdk/javax/net/ssl/FixingJavadocs/ComURLNulls.java deleted file mode 100644 index 9ede06d1f49..00000000000 --- a/test/jdk/javax/net/ssl/FixingJavadocs/ComURLNulls.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2001, 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 - * @bug 4387882 4451038 - * @summary Need to revisit the javadocs for JSSE, especially the - * promoted classes, and HttpsURLConnection.getCipherSuite throws - * NullPointerException - * @modules java.base/com.sun.net.ssl - * java.base/com.sun.net.ssl.internal.www.protocol.https - * @run main/othervm ComURLNulls - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.net.*; -import java.io.*; -import javax.net.ssl.*; -import com.sun.net.ssl.HttpsURLConnection; -import com.sun.net.ssl.HostnameVerifier; - -/* - * Tests that the com null argument changes made it in ok. - */ - -public class ComURLNulls { - - private static class ComSunHTTPSHandlerFactory implements URLStreamHandlerFactory { - private static String SUPPORTED_PROTOCOL = "https"; - - public URLStreamHandler createURLStreamHandler(String protocol) { - if (!protocol.equalsIgnoreCase(SUPPORTED_PROTOCOL)) - return null; - - return new com.sun.net.ssl.internal.www.protocol.https.Handler(); - } - } - - public static void main(String[] args) throws Exception { - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - URL.setURLStreamHandlerFactory(new ComSunHTTPSHandlerFactory()); - - /** - * This test does not establish any connection to the specified - * URL, hence a dummy URL is used. - */ - URL foobar = new URL("https://example.com/"); - - HttpsURLConnection urlc = - (HttpsURLConnection) foobar.openConnection(); - - try { - urlc.getCipherSuite(); - } catch (IllegalStateException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.getServerCertificates(); - } catch (IllegalStateException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setDefaultHostnameVerifier(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setHostnameVerifier(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setDefaultSSLSocketFactory(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setSSLSocketFactory(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception"); - System.out.println(e.getMessage()); - } - System.out.println("TESTS PASSED"); - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } -} diff --git a/test/jdk/javax/net/ssl/GetInstance.java b/test/jdk/javax/net/ssl/GetInstance.java index 6aec679c127..dd14f946de7 100644 --- a/test/jdk/javax/net/ssl/GetInstance.java +++ b/test/jdk/javax/net/ssl/GetInstance.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ * @summary verify getInstance() works using Provider.getService() * Export "PKIX" as the standard algorithm name of KeyManagerFactory * @author Andreas Sterbenz - * @modules java.base/com.sun.net.ssl */ import java.security.*; @@ -113,38 +112,7 @@ public class GetInstance { tmf = TrustManagerFactory.getInstance("X.509", p); same(p, tmf.getProvider()); - testComSun(); - long stop = System.currentTimeMillis(); System.out.println("Done (" + (stop - start) + " ms)."); } - - private static void testComSun() throws Exception { - Provider p = Security.getProvider("SunJSSE"); - - com.sun.net.ssl.SSLContext context; - context = com.sun.net.ssl.SSLContext.getInstance("SSL"); - same(p, context.getProvider()); - context = com.sun.net.ssl.SSLContext.getInstance("SSL", "SunJSSE"); - same(p, context.getProvider()); - context = com.sun.net.ssl.SSLContext.getInstance("SSL", p); - same(p, context.getProvider()); - - com.sun.net.ssl.KeyManagerFactory kmf; - kmf = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); - same(p, kmf.getProvider()); - kmf = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509", "SunJSSE"); - same(p, kmf.getProvider()); - kmf = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509", p); - same(p, kmf.getProvider()); - - com.sun.net.ssl.TrustManagerFactory tmf; - tmf = com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509"); - same(p, tmf.getProvider()); - tmf = com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509", "SunJSSE"); - same(p, tmf.getProvider()); - tmf = com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509", p); - same(p, tmf.getProvider()); - } - } diff --git a/test/jdk/javax/net/ssl/SSLSession/CheckMyTrustedKeystore.java b/test/jdk/javax/net/ssl/SSLSession/CheckMyTrustedKeystore.java deleted file mode 100644 index 9d7b8172a1e..00000000000 --- a/test/jdk/javax/net/ssl/SSLSession/CheckMyTrustedKeystore.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright (c) 2001, 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. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 4329114 - * @summary Need better way of reflecting the reason when a chain is - * rejected as untrusted. - * @modules java.base/com.sun.net.ssl - * @ignore JSSE supports algorithm constraints with CR 6916074, - * need to update this test case in JDK 7 soon - * @run main/othervm CheckMyTrustedKeystore - * - * @author Brad Wetmore - */ - -// This is a serious hack job! - -import java.io.*; -import java.net.*; -import java.security.*; -import javax.net.ssl.*; -import java.security.cert.*; - -public class CheckMyTrustedKeystore { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * 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? - */ - final static String pathToStores = "../etc"; - final static String keyStoreFile = "keystore"; - final static String trustStoreFile = "truststore"; - final static String unknownStoreFile = "unknown_keystore"; - final static String passwd = "passphrase"; - final static char[] cpasswd = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - final 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 { - KeyStore ks = KeyStore.getInstance("JKS"); - com.sun.net.ssl.SSLContext ctx = - com.sun.net.ssl.SSLContext.getInstance("TLS"); - com.sun.net.ssl.KeyManagerFactory kmf = - com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); - - ks.load(new FileInputStream(keyFilename), cpasswd); - kmf.init(ks, cpasswd); - - com.sun.net.ssl.TrustManager [] tms = - new com.sun.net.ssl.TrustManager [] - { new MyComX509TrustManager() }; - - ctx.init(kmf.getKeyManagers(), tms, null); - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) ctx.getServerSocketFactory(); - - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - sslServerSocket.setNeedClientAuth(true); - - /* - * Create using the other type. - */ - SSLContext ctx1 = - SSLContext.getInstance("TLS"); - KeyManagerFactory kmf1 = - KeyManagerFactory.getInstance("SunX509"); - - TrustManager [] tms1 = - new TrustManager [] - { new MyJavaxX509TrustManager() }; - - kmf1.init(ks, cpasswd); - - ctx1.init(kmf1.getKeyManagers(), tms1, null); - - sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory(); - - SSLServerSocket sslServerSocket1 = - (SSLServerSocket) sslssf.createServerSocket(serverPort1); - serverPort1 = sslServerSocket1.getLocalPort(); - sslServerSocket1.setNeedClientAuth(true); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslServerSocket.close(); - serverReady = false; - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - sslSocket.close(); - - sslSocket = (SSLSocket) sslServerSocket1.accept(); - sslIS = sslSocket.getInputStream(); - sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - sslSocket.close(); - - System.out.println("Server exiting!"); - System.out.flush(); - } - - void doTest(SSLSocket sslSocket) throws Exception { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - System.out.println(" Writing"); - sslOS.write(280); - sslOS.flush(); - System.out.println(" Reading"); - sslIS.read(); - - 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); - } - - /* - * See if an unknown keystore actually gets checked ok. - */ - System.out.println("=============="); - System.out.println("Starting test0"); - KeyStore uks = KeyStore.getInstance("JKS"); - SSLContext ctx = - SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = - KeyManagerFactory.getInstance("SunX509"); - - uks.load(new FileInputStream(unknownFilename), cpasswd); - kmf.init(uks, cpasswd); - - TrustManager [] tms = new TrustManager [] - { new MyJavaxX509TrustManager() }; - - ctx.init(kmf.getKeyManagers(), tms, null); - - SSLSocketFactory sslsf = - (SSLSocketFactory) ctx.getSocketFactory(); - - System.out.println("Trying first socket " + serverPort); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - doTest(sslSocket); - - /* - * Now try the other way. - */ - com.sun.net.ssl.SSLContext ctx1 = - com.sun.net.ssl.SSLContext.getInstance("TLS"); - com.sun.net.ssl.KeyManagerFactory kmf1 = - com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); - kmf1.init(uks, cpasswd); - - com.sun.net.ssl.TrustManager [] tms1 = - new com.sun.net.ssl.TrustManager [] - { new MyComX509TrustManager() }; - - ctx1.init(kmf1.getKeyManagers(), tms1, null); - - sslsf = (SSLSocketFactory) ctx1.getSocketFactory(); - - System.out.println("Trying second socket " + serverPort1); - sslSocket = (SSLSocket) sslsf.createSocket("localhost", - serverPort1); - - doTest(sslSocket); - System.out.println("Completed test1"); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - int serverPort = 0; - int serverPort1 = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - final static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - final static String unknownFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + unknownStoreFile; - - public static void main(String[] args) throws Exception { - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new CheckMyTrustedKeystore(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - CheckMyTrustedKeystore() 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(); - } - } -} - -class MyComX509TrustManager implements com.sun.net.ssl.X509TrustManager { - - public X509Certificate[] getAcceptedIssuers() { - return (new X509Certificate[0]); - } - - public boolean isClientTrusted(X509Certificate[] chain) { - System.out.println(" IsClientTrusted?"); - return true; - } - - public boolean isServerTrusted(X509Certificate[] chain) { - System.out.println(" IsServerTrusted?"); - return true; - } -} - -class MyJavaxX509TrustManager implements X509TrustManager { - - public X509Certificate[] getAcceptedIssuers() { - return (new X509Certificate[0]); - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - System.out.println(" CheckClientTrusted(" + authType + ")?"); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - System.out.println(" CheckServerTrusted(" + authType + ")?"); - } -} diff --git a/test/jdk/javax/net/ssl/compatibility/Cert.java b/test/jdk/javax/net/ssl/compatibility/Cert.java index 8d2e7992ecd..b72d0b32b5f 100644 --- a/test/jdk/javax/net/ssl/compatibility/Cert.java +++ b/test/jdk/javax/net/ssl/compatibility/Cert.java @@ -33,134 +33,134 @@ public enum Cert { // This certificate is generated by the below command: // openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 \ // -pkeyopt rsa_keygen_pubexp:65537 -out key.pem - // openssl req -x509 -new -key key.pem \ + // openssl req -x509 -new -days 7300 -key key.pem \ // -subj "/CN=RSA-2048-SHA256" -sha256 -out cer.pem RSA_2048_SHA256( KeyAlgorithm.RSA, "-----BEGIN CERTIFICATE-----\n" + - "MIIDFTCCAf2gAwIBAgIUcCwtPduMIU144++G82mUEVNNK9kwDQYJKoZIhvcNAQEL\n" + - "BQAwGjEYMBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MB4XDTE5MDExNjA2MDgzNVoX\n" + - "DTE5MDIxNTA2MDgzNVowGjEYMBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MIIBIjAN\n" + - "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAycT4Kd742lTlULVh5BcsZIG/AvVl\n" + - "4IVnCoKoE8EyAf+YB2f+pYTDtyPzxnIUUqJ1/1dRY1EyHKQWRv1/J6H9qrKl48Sx\n" + - "zgctOMN6zrCjPGx85MWRW7jOTi9/FNjCfmmGDzo7jjfhEeSzU56zyOMMka2UvKYa\n" + - "P7YSTfC6nT79uaQNj/fqSK98FDLypDcrMiwzJZ7UX4M4Yo33EtqT0wFJfHl/LHJT\n" + - "lmpQdn7dDCqZGviP59tfuGPO7/la18OiN8hU8cttEkAcW3k19kYNhhtfxqs1MtAZ\n" + - "xGlN3eeW4IfjitMerEUd5wHrACyC4TKuj5NO6Wk1vl8pINsdkUttv5pHbQIDAQAB\n" + - "o1MwUTAdBgNVHQ4EFgQUT6UTyQ2i4qOkx3AAPwWS6wdmgncwHwYDVR0jBBgwFoAU\n" + - "T6UTyQ2i4qOkx3AAPwWS6wdmgncwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B\n" + - "AQsFAAOCAQEAPa4ib8oo7vgOh1c/HBvynkzoZ/ci3hqQCArqHkTKQEFSpHeUz46j\n" + - "u+GBRV/bFvZWc+GR9BPedKZUyRzCy3lmWclsxXEnv1uz/PTGBRMtZpjaaveTHzXm\n" + - "VVIkMH+wTZsZ/EQiz2pHgPuAJdPTHlwIYOYo5jk/eZoTKGupBuce+gsn0ctSZQc/\n" + - "TyayRCvnbQQ9Q6VbcfbrWGAmnCa4VANGuk3uZFj2Hc87udJ+2R8WkyfgXtwypNtb\n" + - "1SrRuCqthfCFa4s+P0LlddVqp18gSvsiB+yA1RVZSlSD4GfJfrgtSsJu/ovqThr7\n" + - "+YTfrHCVl4gliXaVujl6tQHaFk23WbAMwg==\n" + + "MIIDFTCCAf2gAwIBAgIUe8nlNUPJa9Iy57Cy5JM49bCzWdkwDQYJKoZIhvcNAQEL\n" + + "BQAwGjEYMBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MB4XDTE5MDIyNzA3NDkwMVoX\n" + + "DTM5MDIyMjA3NDkwMVowGjEYMBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MIIBIjAN\n" + + "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1Clo5Prh1AdHSdM7G85B6K20bjSn\n" + + "bydcWxa7vQDEgFid1Ne8XRbugv5i8I7kGv2sTl99fopHeJcXHJvQGg7KVPgZqH0Z\n" + + "S7ZImlT5f4FYFj8sKnM5wx2P2AxcbO8ktSox0qIgtsHsCd7SusczylqEvSUrcqEe\n" + + "V58LtoWH+trsWoSBDlHRew2eD6ZGyQTM8VFqbt9oF2XXW22JiuP+cSvb+p5qSCy5\n" + + "dGpdPCJpPB/9HpChZl/r+VsqpbHwUPEVu9/FG0SVjpcqvJojYrgglb1PvJxLqceN\n" + + "DPOirwxnnEdiu5j0xC6RhOkbcxTGtS0VgEEC1+HyY+KeauZJOrw2x1ZmxQIDAQAB\n" + + "o1MwUTAdBgNVHQ4EFgQUSSj0EFZWTSFr91nTUE2MrJdrJGowHwYDVR0jBBgwFoAU\n" + + "SSj0EFZWTSFr91nTUE2MrJdrJGowDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B\n" + + "AQsFAAOCAQEAW9uuS2ZpG1ytpNA0g20m29R/DVSnygdfp8r/xeaWgdol4H2syPzg\n" + + "xok3PLkxkSpBv6CgIPXBzy/iXSMlkX0mUKEO3aQnJ8MoZ5Tzu3Bkp2fTugRQuTRi\n" + + "iNWQjsMoupsrTXIZhJ64jkDCnlFADPAdvVqQV01yZcKW98sj3TyaT7TJuYX9mU+V\n" + + "OuICkS1LE5NssuyLodxpfqpjBMtVovSKZ57JvO36G6riftnjr3FBf8ukWFK2/UfP\n" + + "DaHyFQ+NewbjPy7N+taFlLHS7ELwZVQQ42t8JeHRuF5IVvlp1UjTgXC5NuhOBwQY\n" + + "2dXFFroT0vXetn7Fr51zENPP3/TGeaoQnw==\n" + "-----END CERTIFICATE-----", "308204be020100300d06092a864886f70d0101010500048204a8308204a40201" + - "000282010100c9c4f829def8da54e550b561e4172c6481bf02f565e085670a82" + - "a813c13201ff980767fea584c3b723f3c6721452a275ff57516351321ca41646" + - "fd7f27a1fdaab2a5e3c4b1ce072d38c37aceb0a33c6c7ce4c5915bb8ce4e2f7f" + - "14d8c27e69860f3a3b8e37e111e4b3539eb3c8e30c91ad94bca61a3fb6124df0" + - "ba9d3efdb9a40d8ff7ea48af7c1432f2a4372b322c33259ed45f8338628df712" + - "da93d301497c797f2c7253966a50767edd0c2a991af88fe7db5fb863ceeff95a" + - "d7c3a237c854f1cb6d12401c5b7935f6460d861b5fc6ab3532d019c4694ddde7" + - "96e087e38ad31eac451de701eb002c82e132ae8f934ee96935be5f2920db1d91" + - "4b6dbf9a476d0203010001028201006dba71df8b8438707cf9647b2529391a3b" + - "b95e69888b0ee197c4b09575b6b58183f35b2a1067e06c23e03a26e6487e53bf" + - "96840b8827c18db713ca5eb176165713aac5f0bd65b75f6f8457b03a3dbbe9a0" + - "0e662784034027230b7091e54c0c253cf8c554b5acf02739231ba6d87429ecbb" + - "c2acc98472eb988ecc81206d165d33147e03279e60f7fbf73d8f199895f627a3" + - "3cf0c2ef2bcbd096f2e08b2684ea675956da0d95e941afe081e8c79ddb003b50" + - "0f3b340978bce6821438ef25ddbf4fc9dba3f421dbf576f3099dbd4463dbcd2f" + - "da5a987067d00c5af85faa7aea6427f12a1c03c9b5155fc5b5d4da51b4e9f5bf" + - "34087e582728bcaf40b39b0938163d02818100e379b3e110ca339eb1491b95ca" + - "0e73359a167722250f161ff78fef35e22282af28e02da454d0dca6af65b9118b" + - "6e3efe9cabae5d85746b0c336e3d9002c0575afe370ae7a0294c01988d6fa098" + - "9c4a6fc0816addcef3e891f2e56289da5b1b7a1c743664bb8b30ed6028942f72" + - "74f25c075b0646b47fae6c3fc31b4bfd05b02302818100e31210ff848f5a73c6" + - "1a508be415845bb18dcf09688ad543e8b040d9399850801a322e631dc605ec3e" + - "d25695b4f66cb6a728a4e11ff211122c7d0de7de356337b344fca03176c2c370" + - "7fbcdec2433a6c75d7a7d57b761ad6a8c1c8faaf316e0f410643f667958fcfac" + - "c9960d860c73cec45d118517fe72c5939730d8482bdb2f0281807e1a5ab0bb29" + - "0ce2bd6f44de8debe2cc65466cf6bdca963e5474336d10968711e93c15b152df" + - "9262c93b40144cd26a13a5f0bab1d7a8c92b335bbabf19f75cb5f1d5bbb2da23" + - "eaa1bbdb3475b80474736d29917fb3199de542dd0cfa54d54aef2fd4f0ce78f5" + - "59c34e1a50c3d8d4a20288855a7e59d3aa731209ec18fd04693702818100c384" + - "54da8edb9878c384f901db1ca3e1081b20bfeb224fcbaf59c41cc6b8dde7cfa6" + - "91c68a666dc723b89d113ec6488965995b8ef4a0cc0e27fc6db2cee48d4ff2ae" + - "5e0fd94777202d87efaaa6fe9819b7c63f1f54b5371aca2841d3887239602d0f" + - "2609cedb3aff08ba72d7a62aa6b4cce38e2859a6a0507b6add85fd6eb5c50281" + - "8100c07809a53e9ec6769bf2d31ed767766078ff7020199869473c26a211a4b2" + - "9828618b69e6e29ed0f1d8d8cac2c61490c3f20d19c1ff067c5d291080c8e15b" + - "2ce267cd37f8b0c1afe9c070418b310b5641640805d3a75890ccf6d2bf0bea11" + - "d327323db5452cadc1a3bd17c20ab92b6f09d4216a03c7a03c6ffc72e51f51eb" + - "dfa4"), + "000282010100d42968e4fae1d4074749d33b1bce41e8adb46e34a76f275c5b16" + + "bbbd00c480589dd4d7bc5d16ee82fe62f08ee41afdac4e5f7d7e8a477897171c" + + "9bd01a0eca54f819a87d194bb6489a54f97f8158163f2c2a7339c31d8fd80c5c" + + "6cef24b52a31d2a220b6c1ec09ded2bac733ca5a84bd252b72a11e579f0bb685" + + "87fadaec5a84810e51d17b0d9e0fa646c904ccf1516a6edf681765d75b6d898a" + + "e3fe712bdbfa9e6a482cb9746a5d3c22693c1ffd1e90a1665febf95b2aa5b1f0" + + "50f115bbdfc51b44958e972abc9a2362b82095bd4fbc9c4ba9c78d0cf3a2af0c" + + "679c4762bb98f4c42e9184e91b7314c6b52d15804102d7e1f263e29e6ae6493a" + + "bc36c75666c502030100010282010028f1f4f47c16a93cde5d390ee746df2170" + + "a4a9c02fb01c008ef3cc37a5b646aed387083baa1b8adc6d0bdb3138849d006b" + + "ffb1d0820f590e8fbf4db2d3d496e7df19d4929017348ebe7a37cc8bc1dc4944" + + "d4cc781157db32eeefc7763fb756f55699438701d5f3f1b4e9a7182fad5880c8" + + "73a223c61f52ea87c72d7f14511906af61d7fa190b02854471d4bdb77dac34ef" + + "46a3af3f39dff1c8844cad7f74f9936fbcc22bed6b139f47dc215048ddf02f60" + + "a24703b292be106ea4f01ec0839466666d9c3dc8488b353dccdd5f90bd4b5bb9" + + "4493b7da219ec4962fe6a427f6d69e2764065212c5accdbed3aa36a18d540e55" + + "192e63db9f6bdfc90ec52b89714d0102818100f7c35a70ee7d6aabd7feb590f6" + + "30ce9c28299f3431ebcd3c89ec9424cf68c626ee4f6ff0748ffc0ad810a9f6dd" + + "2b203c8fa7f516483545822e6c963b9f6a1687aca663be061aadcca920b09699" + + "bd7d2e8973bafe9ef11e19a27c10befe3e8919c141d04e5aab2990cc061c6798" + + "5d3da742a3c8c62b68a8ccb4af21c1c935bdcd02818100db37101251d805b8d6" + + "12749d8780cce9e4ff8fc58313e4192fbf9018dc2a8875beff70ea2ebaa24058" + + "d3de6eab4be66b0bb81c04f0fa29bad0f787776ed2e6ab7b7d9814ce7721cadd" + + "cc3f500ddfd73ae9def4d92a79e4a1662da16dbfc52d60507308286cf592ed8b" + + "9911089c4ec7dba3fcd64926b55d137d41f6de454694d902818100af6b582077" + + "2ac318d2401bcb7c13886555a64a7b09115be98df9bbd5e827d58c00d4ab7bc2" + + "fba2c706bd9da9146491596f98ca553160ce4ae295ad349fa4dc38c94bb178fc" + + "176d9066faa72ca9c358db572462741e92b6ee0d75ebe15e5f66709ebcfb404e" + + "bfbb1932eaecb7885013f3d5a1e2e83419d0d1c6e7ec6da9096ccd0281810099" + + "81fc922797f3a1d4dec5a4ce8fc66effba6aae7034cca54a8785dbb2c96217ba" + + "315c9bd12f469172e2a2bfb2da8ab769547ae286f157a987cddea2270c2f15e4" + + "7b35b554439e79564a4207c83f7893bbd43277a4c408f370ff012d3e7e506142" + + "d4dae09c3477b83aea6c40305d069d6b3f91bb560ce8e9cdec1478dfe0263902" + + "818002b66c71380142c3e606bfc598b4060f6833ac80e16d08aea40f4837191d" + + "34a3c85b91c3043c6ebb2c651a7fbb89539f5621820f792a5279a947c51f47b7" + + "1b6051c5a81d2d1c30dfa1f93cb57af1d7ee7862e8d90e33bd5c80f14aa9471b" + + "a2ea7aacddbb44d1a5e60f5fac437ca50cd56e237936fd3e9d034efc3e3c6710" + + "4c08"), // This certificate is generated by the below command: // openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 \ // -pkeyopt rsa_keygen_pubexp:65537 -out key.pem - // openssl req -x509 -new -key key.pem \ + // openssl req -x509 -new -days 7300 -key key.pem \ // -subj "/CN=EXAMPLE" -sha256 -out cer.pem EXAMPLE_RSA_2048_SHA256( KeyAlgorithm.RSA, "-----BEGIN CERTIFICATE-----\n" + - "MIIDBTCCAe2gAwIBAgIUfmLJ5eIbVUGXAzlZXtw08GQ6ppMwDQYJKoZIhvcNAQEL\n" + - "BQAwEjEQMA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAxMTYwNjA4MzVaFw0xOTAyMTUw\n" + - "NjA4MzVaMBIxEDAOBgNVBAMMB0VYQU1QTEUwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" + - "DwAwggEKAoIBAQCp7IDXT8J9iDMVAuLMTZS9oDD83BDkL5INGdXk1esTzyqXFmV2\n" + - "d5zNTr4A8w+YstkR081zL4MyEvHyQF1IlWoniRMXTZNMYYtU8dI8h2Fl5etSIEsc\n" + - "ArsAp3QMcoqEu4F4T68KPU7z1M5kYKevGqPsO4GJwjoydSZMLZMrq09yEyXlnE9l\n" + - "pNhyfFbQIp86mtXkY9nP3hn7JX6KMZSwAHbp7FtFkGfMx+usMnsMan+Z7UyWJE3o\n" + - "2cf29Fr9lBdV24gWAymyJA3BAW60wEI2JPYzIZVNn4zxmlkWk5sr+m5rUCXMzsyp\n" + - "G+rPk7YSpPutmczPe1BEiFwkgk+E5gZsNESbAgMBAAGjUzBRMB0GA1UdDgQWBBRm\n" + - "mZ3V6rNvJyG5DdYt1yo/Eiz+AjAfBgNVHSMEGDAWgBRmmZ3V6rNvJyG5DdYt1yo/\n" + - "Eiz+AjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBNHOWMa7f8\n" + - "iXwhET/6Rpu0JILusRrJVGXl3JOHxDsibUPAeZ4KI7VEEBw6ln0bKAFaYg+Nh9Xh\n" + - "dMuPC6e5wrX2Z912ncexa7BXDQDS4VyuvEGpp7rWFNtKRfc75hKmcRz+blgdhw9m\n" + - "gF1VcW3vBIjAUjMllRuyPlyXThgOPwcBXGEIewvyLXWbkNDFIeqycwsQsw5JJcbA\n" + - "Fh4alzjapSvSM84VS79u/MxaNZAtKpaymMaM05A8vIp8iHDm4N4AhIwHLT1mrtFt\n" + - "8y+3p4W6vtA+SlFGz8fQw5ppoxvPeJyHZmSmGeorcBv9XXWHhJ0rGz8UbE76xE0B\n" + - "EwC7yAE/SiA7\n" + + "MIIDBTCCAe2gAwIBAgIUD+8I14TmOfEfxtD6hgnhhK8ARCAwDQYJKoZIhvcNAQEL\n" + + "BQAwEjEQMA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAyMjcwODAzNDhaFw0zOTAyMjIw\n" + + "ODAzNDhaMBIxEDAOBgNVBAMMB0VYQU1QTEUwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" + + "DwAwggEKAoIBAQChKYq85df7kUnf35qAfxW/OnqCgn/5FNwlWAwHLlEiHpK+k7jD\n" + + "8S6LVbw55I/4J3lehIHcIapGdmqh9ijUc2aNxTJ33z+/TTu2n+KlWmGj0G7ovTXk\n" + + "TbWptdgk5ro8DCr8I8YcvwdLekwH4AkRL6jSyiqsqlGZYLIxDd4l0CwSt5orbu/y\n" + + "+2UtM4DEOEswrxdP9UAd+W0On4AWaFIEbfuFaLZXHadvKxidnaCmudOJry6NjFWn\n" + + "+3PmIWNhZJitD0gq8FG3pvY502fLqHX95pigWCkDtrDNiqReXgVvZFWPaSMs065y\n" + + "n2ClShbzTs8pqJp8oBde9Iwi3RKwkew8I2iJAgMBAAGjUzBRMB0GA1UdDgQWBBTL\n" + + "3w5XucuEre5nQiaKnqi4s7ldBjAfBgNVHSMEGDAWgBTL3w5XucuEre5nQiaKnqi4\n" + + "s7ldBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBo51E5U5H7\n" + + "kXkI1LaGDs35dOOtrPQQQ7DzhQACUDfyYB8/BBUlYHPegS2ca/l1mkD2P/GNyZbN\n" + + "r4eRoOujfU59gOwH4+MEs/4zUKicajTGUPCbJ56heipHunHzj+2nj3ok5PI0MoI1\n" + + "soQfRV1FshfWAni7E49L1QI/PQrQ2cPR/1dvkB06JCIn0GoTxd8E76VCJz576xnd\n" + + "XgjiadVbjMYDH9XJEy6eQT6vY5WeGOQC2XwSE3mS6G+Z9jlwIswa8RrKGtKqFGK1\n" + + "6yse9zfJv64X8tQwnrkatCx4shJwDUet6wJQzm0/NMPfquoxz7QHF2NsLlNky+fY\n" + + "fZjMnoO3J1nV\n" + "-----END CERTIFICATE-----", - "308204be020100300d06092a864886f70d0101010500048204a8308204a40201" + - "000282010100a9ec80d74fc27d88331502e2cc4d94bda030fcdc10e42f920d19" + - "d5e4d5eb13cf2a97166576779ccd4ebe00f30f98b2d911d3cd732f833212f1f2" + - "405d48956a278913174d934c618b54f1d23c876165e5eb52204b1c02bb00a774" + - "0c728a84bb81784faf0a3d4ef3d4ce6460a7af1aa3ec3b8189c23a3275264c2d" + - "932bab4f721325e59c4f65a4d8727c56d0229f3a9ad5e463d9cfde19fb257e8a" + - "3194b00076e9ec5b459067ccc7ebac327b0c6a7f99ed4c96244de8d9c7f6f45a" + - "fd941755db88160329b2240dc1016eb4c0423624f63321954d9f8cf19a591693" + - "9b2bfa6e6b5025cccecca91beacf93b612a4fbad99cccf7b5044885c24824f84" + - "e6066c34449b0203010001028201005842e1357557678eec4198ab274590e1e2" + - "282fdf3ae2db96b8395831b1af962d8048d438458da1a3bea7d0a46fd077ed6a" + - "66228c16fcc570b3bd8a132a1579fb2927026ea7f8ff9db8b496e81bc5ca80df" + - "775c10c76edfa55a555bf5cedf5ce9c60d55b532dd24a7bfc0c1b7b7ab55c3e9" + - "b0c25661963de573a22494853a11dce95ea31417d3c87c806ef74cb6c8b7190c" + - "cfcdc2d21e8a756061c9e6cf40bca95d5aa43fb990b9492250ec9a752151320c" + - "b30a64beb0e17d83ad9ea702afcd5d8d6b7bfe11031aa27d83652e8db864bdbc" + - "447aee6e973018f77155aa24e05d3b7f9e232096ff93e8e2b1361b6cdbd4edf8" + - "dd88b46b178b38c34fe0ea5fc40f9102818100db14d91a4e8a89cc95a7cc687f" + - "2f2f295bc8a945826b3da840f871161ce2062f980d45b50172e744a308c0972e" + - "6f3f028465e6a59b75c0687bc3db4b69f5a931b73e9dedc6b05d41f4c1dd0575" + - "8e0460efba9bbb98f1c6ae3f018e2fb967a085dc5290ba8487703e1aee05fd90" + - "3c17867130c5676b7b9567a6fd61e9be6d660902818100c68f0053c621d52d65" + - "4ec381775e1b8fbf15ad391a0ad478d5b46374ad3f7c417a2f425f285999b4e6" + - "1672614ec6b4bad54400ecbc9e92f35cdab590a8cff4c029146a9b101d53950f" + - "7dddaa45946bfcf2a4e86bcddfc141a2cc49969519a326c7e5b001912e151d86" + - "b17f5789f39513c3f660c3e41f169a7668b22c17241e8302818100b86d0a7e4c" + - "d3ef40dc530f8e8052b63ef8d729382c9c1ea17f6025c2d9b9a43f789ee3a986" + - "78b61b5fabc485004002291a4fb6247f8456df1e21388079c8a61006149e5a46" + - "42bd9f026e18a3b9dc3def64a010ed91c926da148c38a8104a1e25d1dd679cbc" + - "684fa2d884bb62438372c2689307fb11ce4d6d9e73fb730c2d8811028181008d" + - "fda14c4739d68a9a11d3397835321c7f976ec290df01c64f7caa4abbc1d487b6" + - "6aa95a072edbfe4333f623a403f1265270490102799bb8b0c42e66fe7188230a" + - "bd70e6e685324a3c43d40a79ab83f5e5470c765b49119870650a92c69908d528" + - "ca162d68b6bd9ed9bd80c506ffcbb1d0c715b7c02083377e49ac705f34132502" + - "8180100e20febd1a5af92fdfc36aaf47d1a771cb1484d79e2389d5e6f47dc773" + - "512edef82676f9f9d5a77aac2f01d66fe864d85abcce47e3d22491421f959c1e" + - "5545c16fc5c5f5550ced81485dc237d9df8753cd6031e431bd34425e81b1e193" + - "c51a6d2c8a7cc01028f47b7fb7d79b481facb76c4775ff997f2e63acb3ff429c" + - "47b3"), + "308204bd020100300d06092a864886f70d0101010500048204a7308204a30201" + + "000282010100a1298abce5d7fb9149dfdf9a807f15bf3a7a82827ff914dc2558" + + "0c072e51221e92be93b8c3f12e8b55bc39e48ff827795e8481dc21aa46766aa1" + + "f628d473668dc53277df3fbf4d3bb69fe2a55a61a3d06ee8bd35e44db5a9b5d8" + + "24e6ba3c0c2afc23c61cbf074b7a4c07e009112fa8d2ca2aacaa519960b2310d" + + "de25d02c12b79a2b6eeff2fb652d3380c4384b30af174ff5401df96d0e9f8016" + + "6852046dfb8568b6571da76f2b189d9da0a6b9d389af2e8d8c55a7fb73e62163" + + "616498ad0f482af051b7a6f639d367cba875fde698a0582903b6b0cd8aa45e5e" + + "056f64558f69232cd3ae729f60a54a16f34ecf29a89a7ca0175ef48c22dd12b0" + + "91ec3c236889020301000102820100655c9e60ce62b85b99ce0f71ba2db3fcd1" + + "07ea7baf8776823b8e940a142c7d3c23696fb97eab7b6db11fb07dbbbb0500c5" + + "dcab5c4b642feb1c87ff2d90e97fefdcbe303c9e7870580535ac33f9937d9783" + + "9a281ef41798114448cc74bd5f34fbf8177bebea8de8ffe33ff4bd5f2ccd8ebe" + + "0e7708ac47be54749bd7438b199d2f134b71efc513827f260c0f74f1fc32f45b" + + "e5d510844777fcd2a486bc02c080d120d1c32336000ece743ea755f79f60a44a" + + "5e619ceb1caa873d847715616874d13c2ff1fe9f9f81d8fc83e83fb035bce8d9" + + "ed8f5caa41626d323551311b1d8d8f06785e3700d45e4d771157b22826efe553" + + "7a5892ad3bf3f915ec25342a8c7a3d02818100d19c03d857442bbaedb41b741e" + + "8e93d295940fdfc455898463ad96b0089ee68d90b787848b7aed6bb735c7e4b9" + + "7b22e867000d8e4b4ede4b155c34fd88c10244917912c048d023757bd758a117" + + "764aa80434c5c9636ec125574667ffe01af856f4517d06b6831ad50f16b26bba" + + "67a7125e158988c98b817dbb0928efa00c3ed702818100c4d49f7f3bf36586aa" + + "519bf2841c459c1863e71c08a9111344e51fcf5ff4267420fd9ffc9f72288e44" + + "b56bdae4eaa669e5e350afe4b4402be4af54d5dbc8b5dc5f5b6bb79df4fd17a5" + + "225287947783b5327b5dedf02733fb534514cc05fde1dcfceb8b537ad3c163a8" + + "8f36a60e2fb17fa6d9a0f3fca444f349eed9f07823879f02818100a5e9eb753c" + + "261ec338d23e84dc8718e53036e195cacfb6294fc920a4b83e26da59799c5043" + + "238b789ead784b48b1fa40a0fefebbea4a44548454d730f4256a8921e906f9a2" + + "e8f59851ed741f16f63043ec0865a2720d41df2fc4f01f2ea1ca7ef1a6eae2fc" + + "66ac3f8750fceb9ec1db1203dce25f9ec0c93fdf6371beb31dde430281807852" + + "be59ea4d25504847f13c34948fdd176fe2f4d93a790cbd7e0f8f16ca4ac38cf3" + + "5e5cf11fb93917398c805896353ae164af8b8714c571cfaf7afded086a5c1812" + + "ebeb686d3e56b9051d4c726f091db8897fe7177aefa500c7672a3db370e245de" + + "bbe24160b784f3a2f0b65c4fbd831a7d498e3d70321243acf69fb0e18f630281" + + "8065f0a2f257f8bf1d57e3f1b72c9a664ca92630985ee5ba35438e57a1df67a6" + + "f6b380907f5b7f9bdd2ddc63385615c5ca3c0dcbedfdc3f18433160855824712" + + "eaaeb318774478427dfb58135715cf82730a743dd8448984450905c28a6a97a0" + + "5f4aaad616978c07c5957c4f1945073f333df4337557bd6b754953f71df7a03c" + + "ec"), // This certificate is generated by the below commands: // openssl genpkey -genparam -algorithm dsa -pkeyopt dsa_paramgen_bits:2048 \ @@ -275,106 +275,106 @@ public enum Cert { // This certificate is generated by the below commands: // openssl genpkey -algorithm ec -pkeyopt ec_paramgen_curve:P-256 \ // -pkeyopt ec_param_enc:named_curve -out key.pem - // openssl req -x509 -new -key key.pem \ + // openssl req -x509 -new -days 7300 -key key.pem \ // -subj "/CN=ECDSA-SECP256-SHA256" -sha256 -out cer.pem ECDSA_PRIME256V1_SHA256( KeyAlgorithm.EC, "-----BEGIN CERTIFICATE-----\n" + - "MIIBkzCCATmgAwIBAgIUXebzNfSMvdkNrc5175FM6dE/gxwwCgYIKoZIzj0EAwIw\n" + - "HzEdMBsGA1UEAwwURUNEU0EtU0VDUDI1Ni1TSEEyNTYwHhcNMTkwMTE2MDYwODQx\n" + - "WhcNMTkwMjE1MDYwODQxWjAfMR0wGwYDVQQDDBRFQ0RTQS1TRUNQMjU2LVNIQTI1\n" + - "NjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOp7VcLfpVc5ghO0HlYjwH+YSAf7\n" + - "zTShLeoY35PwqcoUgg9DBR4g7rM3xovOKxGZ5uORD8vo5l9L0+53f2+7YH+jUzBR\n" + - "MB0GA1UdDgQWBBSmW8/6KP8EJKBVlfmFkBSbVWTEWzAfBgNVHSMEGDAWgBSmW8/6\n" + - "KP8EJKBVlfmFkBSbVWTEWzAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0gA\n" + - "MEUCIQCtGdW3Xl5OzX7QiwtiT6pbIrm6eCUwN/vVoMfs3Yn5rgIgCbLidpdMpFrd\n" + - "HWB2/mVxQegLBCOIGMVPXrTat4A76As=\n" + + "MIIBkzCCATmgAwIBAgIUVW+Rj8muf1DO8yUB9NSEDkD8oYowCgYIKoZIzj0EAwIw\n" + + "HzEdMBsGA1UEAwwURUNEU0EtU0VDUDI1Ni1TSEEyNTYwHhcNMTkwMjI3MTEwNzA0\n" + + "WhcNMzkwMjIyMTEwNzA0WjAfMR0wGwYDVQQDDBRFQ0RTQS1TRUNQMjU2LVNIQTI1\n" + + "NjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJPHqflVA59hR/sBM64OOY2/PTTx\n" + + "kZZhKcVV8vEkWRWvDV2u2F+lbRQoEoe8bwfGgQgGJIdc+dz9/TVAaYlitaKjUzBR\n" + + "MB0GA1UdDgQWBBRS9gbMeeA7j7QdipPufKn3jI3hKTAfBgNVHSMEGDAWgBRS9gbM\n" + + "eeA7j7QdipPufKn3jI3hKTAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0gA\n" + + "MEUCIDH0b3EewcoZUeSo0c2pNSWGCeRlZI49dASDbZ3A0jdTAiEAy/dM9LwYvyLl\n" + + "yuWq4yTouCdzfQwR9QXg3ohRMhnASlg=\n" + "-----END CERTIFICATE-----", "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02" + - "01010420aa9602d20de7ebfc2787a6e5ae20166d1e8d8bd29b4e5f046414bae8" + - "9a8e7eb9a14403420004ea7b55c2dfa557398213b41e5623c07f984807fbcd34" + - "a12dea18df93f0a9ca14820f43051e20eeb337c68bce2b1199e6e3910fcbe8e6" + - "5f4bd3ee777f6fbb607f"), + "01010420ae670b91bae99a9752f2b7e26ab9c0e98636f0b0040d78f2ea4081f8" + + "e57c72e0a1440342000493c7a9f955039f6147fb0133ae0e398dbf3d34f19196" + + "6129c555f2f1245915af0d5daed85fa56d14281287bc6f07c681080624875cf9" + + "dcfdfd3540698962b5a2"), // This certificate is generated by the below commands: // openssl genpkey -algorithm ec -pkeyopt ec_paramgen_curve:P-256 \ // -pkeyopt ec_param_enc:named_curve -out key.pem - // openssl req -x509 -new -key key.pem \ + // openssl req -x509 -new -days 7300 -key key.pem \ // -subj "/CN=EXAMPLE" -sha256 -out cer.pem EXAMPLE_ECDSA_PRIME256V1_SHA256( KeyAlgorithm.EC, "-----BEGIN CERTIFICATE-----\n" + - "MIIBeTCCAR+gAwIBAgIUWZkzN4WOoj7HUYLoWtgy+ad/zjswCgYIKoZIzj0EAwIw\n" + - "EjEQMA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAxMTYwNjA4NDFaFw0xOTAyMTUwNjA4\n" + - "NDFaMBIxEDAOBgNVBAMMB0VYQU1QTEUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC\n" + - "AAQMzWjRuN9r2/kcVYyHFpKduuYj2VFRXo81qd+EcyjnLZab5m9RqIYy6iDUvZk5\n" + - "w8wHeHGpMybPzNSEQ2mVY5Yvo1MwUTAdBgNVHQ4EFgQUUhVK37nQDP6OEW5w7XEb\n" + - "p8/sCxMwHwYDVR0jBBgwFoAUUhVK37nQDP6OEW5w7XEbp8/sCxMwDwYDVR0TAQH/\n" + - "BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiEA9B2e4TWZKMxS8/uyVjl6D+cyqsPU\n" + - "7/qATL5cTK1AIUACID8BPfcPE46ARCretiGWywVuQzAVKz1fkjwEwLmAo+2x\n" + + "MIIBeTCCAR+gAwIBAgIUH6kQ0NfopvszxUwZ58KhMicqgCwwCgYIKoZIzj0EAwIw\n" + + "EjEQMA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAyMjcxMTA5MTJaFw0zOTAyMjIxMTA5\n" + + "MTJaMBIxEDAOBgNVBAMMB0VYQU1QTEUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC\n" + + "AASbW2bDwNxTHAzN7aW/OD/ywfa0A4bPKF3Qw4U4nLFBHhbbEmDrIkRWqU56UUDt\n" + + "fnTZnBCJtm4sH8o9D1D9UZVFo1MwUTAdBgNVHQ4EFgQUEEpzWKgPritmUQNEcQhz\n" + + "bB+5KuUwHwYDVR0jBBgwFoAUEEpzWKgPritmUQNEcQhzbB+5KuUwDwYDVR0TAQH/\n" + + "BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBjeGB0oc6t2fWOaviIMfqRqta64nl6\n" + + "Gj8I/JfDH97P1wIhAJ5IC9cxVTiPL/QTxUxRRlTYUboL/+ck1XR9JbZjd/ar\n" + "-----END CERTIFICATE-----", "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02" + - "01010420ed3600c6b62b351b48b4c61f37c46c45460ff599aa7f9c2d79635d0e" + - "147c23a3a144034200040ccd68d1b8df6bdbf91c558c8716929dbae623d95151" + - "5e8f35a9df847328e72d969be66f51a88632ea20d4bd9939c3cc077871a93326" + - "cfccd48443699563962f"), + "010104205dfd6695d259d4047433c0b4520bedcf95130c5c08ba149caddad70d" + + "b3b66c1ba144034200049b5b66c3c0dc531c0ccdeda5bf383ff2c1f6b40386cf" + + "285dd0c385389cb1411e16db1260eb224456a94e7a5140ed7e74d99c1089b66e" + + "2c1fca3d0f50fd519545"), // This certificate is generated by the below commands: // openssl genpkey -algorithm ec -pkeyopt ec_paramgen_curve:P-256 \ // -pkeyopt ec_param_enc:named_curve -out key.pem // openssl req -new -key key.pem \ // -subj "/CN=EC-RSA-SECP256-SHA256" -sha256 -out csr.pem - // openssl x509 -req -CAcreateserial -in csr.pem -sha256 \ + // openssl x509 -req -CAcreateserial -days 7300 -in csr.pem -sha256 \ // -CA CA.cer -CAkey CA.key -out cer.pem // Actually the CA is RSA_2048_SHA256 EC_RSA_PRIME256V1_SHA256( KeyAlgorithm.EC, "-----BEGIN CERTIFICATE-----\n" + - "MIIB9TCB3gIUIpSnxoBfFOKeRdx52FvEKuk1uvYwDQYJKoZIhvcNAQELBQAwGjEY\n" + - "MBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MB4XDTE5MDExNjA2MDg0NloXDTE5MDIx\n" + - "NTA2MDg0NlowIDEeMBwGA1UEAwwVRUMtUlNBLVNFQ1AyNTYtU0hBMjU2MFkwEwYH\n" + - "KoZIzj0CAQYIKoZIzj0DAQcDQgAETcLM10u7ehsxJQbX3ypbSRMz7ZDkFS/QsmPF\n" + - "04NSwiBncQPjtpaPSshVDJzigEDfACcwIdO0BH4Eh2oHcB6hDzANBgkqhkiG9w0B\n" + - "AQsFAAOCAQEAHg06hhIec3ctUh7pao53ZF3SVJ/Pty4rgQ3Hb5gNhZHrmYWldj6J\n" + - "UagMRtfX0fJwzIdY0kNTol38es+6XDTCdYsaDDw4Ix1yF/xoExu6PqJ49npMVxqB\n" + - "yeXwg8aDB9sbmeczZp0kWa1DiN3HgJGoA8HbPOUZbuetCVl2ME82ZPdKdLaHgjO/\n" + - "Af3/gjYGVR27YB5sVIXkq3wJ5wEF+EvePKQZqnHFLhjz0xIIyp7mU6NFr26TsNh0\n" + - "JYecs5S0ydhf41x9GS4p8KpqRcfAOX4z5DEBe+BjgSuprGZabflFCbZ/PQrtBmdp\n" + - "5+cg/cNcA3zEXnsAzLu2R/+73/h9v75g/Q==\n" + + "MIIB9TCB3gIUWuMp26pvpTFO08C+ev6W8ZRDwqAwDQYJKoZIhvcNAQELBQAwGjEY\n" + + "MBYGA1UEAwwPUlNBLTIwNDgtU0hBMjU2MB4XDTE5MDIyNzA3NTUwMFoXDTM5MDIy\n" + + "MjA3NTUwMFowIDEeMBwGA1UEAwwVRUMtUlNBLVNFQ1AyNTYtU0hBMjU2MFkwEwYH\n" + + "KoZIzj0CAQYIKoZIzj0DAQcDQgAEgCoIan3yAA4KVwAO4qrMFF1alcYFzywPHerI\n" + + "eje3eQVhFaTecnbm0rTJE66JF8HeNuefd61+v1FqWo95aJ1l9zANBgkqhkiG9w0B\n" + + "AQsFAAOCAQEAJIgHTHyPJ5X44JR5ee3N2sYA8C9KGf2YFq/yPQ+pYYIk2gNKqMTH\n" + + "IgHzEqpeb1KC8i+F57xD8qL76QZ7YGVueKoU0o2XYO8Fj4Kug9B48uYvw4J025Bf\n" + + "emxVzuDwgPNAeQwzfoR4NpMKV6TjA7c1VVNUwnse7jHyzqkQLlNors62U+O2MI/t\n" + + "4RM6PDLWuGm9eDZAtifxdjjME9efEXOVi2y/9YAr7hOJKn3r1ie1Txo1N3LXTsLg\n" + + "Y0GlCcOiDGD5So6jSn4hY2CyeeEtTOZkloT/2Slpz9MbLzlav8hqnNQDbuSCFnyn\n" + + "fQh6yysvdeRm6Yx8bNkA/pxz/Y21fXVWMg==\n" + "-----END CERTIFICATE-----", "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02" + - "010104200ab17f2b70ba744b08564635ebfc535c60d43139e1c722cfb9c7152e" + - "9faad5b3a144034200044dc2ccd74bbb7a1b312506d7df2a5b491333ed90e415" + - "2fd0b263c5d38352c220677103e3b6968f4ac8550c9ce28040df00273021d3b4" + - "047e04876a07701ea10f"), + "0101042079433b715d94d8de6b423f55ef05c911613dc708339391339bef6ca3" + + "c14b419ca14403420004802a086a7df2000e0a57000ee2aacc145d5a95c605cf" + + "2c0f1deac87a37b779056115a4de7276e6d2b4c913ae8917c1de36e79f77ad7e" + + "bf516a5a8f79689d65"), // This certificate is generated by the below commands: // openssl genpkey -algorithm ec -pkeyopt ec_paramgen_curve:P-256 \ // -pkeyopt ec_param_enc:named_curve -out key.pem // openssl req -new -key key.pem -subj "/CN=EXAMPLE" -sha256 -out csr.pem - // openssl x509 -req -CAcreateserial -in csr.pem -sha256 \ + // openssl x509 -req -CAcreateserial -days 7300 -in csr.pem -sha256 \ // -CA CA.cer -CAkey CA.key -out cer.pem // Actually the CA is EXAMPLE_RSA_2048_SHA256 EXAMPLE_EC_RSA_PRIME256V1_SHA256( KeyAlgorithm.EC, "-----BEGIN CERTIFICATE-----\n" + - "MIIB3zCByAIUbogHun+2LFxbX9B5fImITzFQVfIwDQYJKoZIhvcNAQELBQAwEjEQ\n" + - "MA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAxMTYwNjA4NDZaFw0xOTAyMTUwNjA4NDZa\n" + - "MBIxEDAOBgNVBAMMB0VYQU1QTEUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASA\n" + - "pPapPXO0qJO7mDm9dTuSKdsxWatAaloJZnwenBFIY8krulHd8VPSGbERmxRBY/z2\n" + - "+MH8dwaC1t9DAFb+1qdWMA0GCSqGSIb3DQEBCwUAA4IBAQA3SfXMUFj7xCl7nR8L\n" + - "/6mf0La/q4O1pGKmVpy55aP7dZmY3xzaPtDFevdnMqb7tBTiLl0Y8OehMQW/8usb\n" + - "qtcYPekZJV5g1ezMhyB/AHecotfsrBS7l9r+IWYf/GUoQ8izC1srNXVrqDCt0cbB\n" + - "o7bc0lQFhI+rcMt1AzQtrNkVhX0dcBbLyhNJzgyAXatSB5R0/R3kTddUZfrOtOoC\n" + - "IXUZJRQ7hZKx7qi/U4+q246IuKSSp2SjFTU1QpeO4/Q06eJ3sbtx5Nd1Rfzlo2Jq\n" + - "uYi8szOupFC8xKCB+odMndHvh1QO/8E4e4r0mShkrnK3M/lKiwi67yl3Jk9uY9ls\n" + - "X5Q6\n" + + "MIIB3zCByAIUWm9wgVB1TgdT5lpGNNkWBzuclKQwDQYJKoZIhvcNAQELBQAwEjEQ\n" + + "MA4GA1UEAwwHRVhBTVBMRTAeFw0xOTAyMjcwODA0MTNaFw0zOTAyMjIwODA0MTNa\n" + + "MBIxEDAOBgNVBAMMB0VYQU1QTEUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASp\n" + + "6YAqTEEjuMlG+vKl8XPo2T2wgqY6t+j1R5ySC0YiGesfrwVLTM4V+Ey9PKHoEIVK\n" + + "kWNUF5Sb2JdrYIuzb5WdMA0GCSqGSIb3DQEBCwUAA4IBAQBPrIScxw5Nx4DhT5GL\n" + + "ngyNBOun0yAwqrxQ3LPheMuN7CH4qehFPDx8MHhmFFjEIDKVRbEEgxiCJAgca7qD\n" + + "uLCfESM8KU4bkV4Pjx7/OEQZ3AkQ0UwDvDr/DypPg7TLLyF979OQo+fEaqWKH8Q4\n" + + "8Ot8+VUFuwpYhHQlkoPnwFKIuCfDGwYmmHP2btlZ5qBuDDzdo1JVGF8pJ943cfA8\n" + + "zRBJGKw8MMJXlfk3yiDSKMji0106SFuGwFJfkrdUnZ+hpeJ7rrrqW7jwLIil8PKf\n" + + "Z41UjYM4Ut/6O5SFqueBsC6yxfzrJbd8UZ7ZkfagWMr/AXLK1Sm3ICSPHsQW30mH\n" + + "uX+T\n" + "-----END CERTIFICATE-----", "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02" + - "01010420618ff6a884185b97322aaeab5f9fdf8a14ab18d0478565317b483db0" + - "0f3b5bf6a1440342000480a4f6a93d73b4a893bb9839bd753b9229db3159ab40" + - "6a5a09667c1e9c114863c92bba51ddf153d219b1119b144163fcf6f8c1fc7706" + - "82d6df430056fed6a756"); + "01010420f1f944e1fc4bd7013b157db5fed23b84a4a1cd3d1a22f40746353185" + + "c0d8684da14403420004a9e9802a4c4123b8c946faf2a5f173e8d93db082a63a" + + "b7e8f5479c920b462219eb1faf054b4cce15f84cbd3ca1e810854a9163541794" + + "9bd8976b608bb36f959d"); public final KeyAlgorithm keyAlgorithm; public final String certMaterials; diff --git a/test/jdk/javax/xml/crypto/dsig/GenerationTests.java b/test/jdk/javax/xml/crypto/dsig/GenerationTests.java index 560179a8c0e..8ccb522b5f6 100644 --- a/test/jdk/javax/xml/crypto/dsig/GenerationTests.java +++ b/test/jdk/javax/xml/crypto/dsig/GenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,7 @@ /** * @test * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8046949 - * 8046724 8079693 8177334 8205507 8210736 + * 8046724 8079693 8177334 8205507 8210736 8217878 * @summary Basic unit tests for generating XML Signatures with JSR 105 * @modules java.base/sun.security.util * java.base/sun.security.x509 @@ -126,8 +126,12 @@ public class GenerationTests { private final static String CRL = DATA_DIR + System.getProperty("file.separator") + "certs" + System.getProperty("file.separator") + "crl"; + // XML Document with a DOCTYPE declaration private final static String ENVELOPE = DATA_DIR + System.getProperty("file.separator") + "envelope.xml"; + // XML Document without a DOCTYPE declaration + private final static String ENVELOPE2 = + DATA_DIR + System.getProperty("file.separator") + "envelope2.xml"; private static URIDereferencer httpUd = null; private final static String STYLESHEET = "http://www.w3.org/TR/xml-stylesheet"; @@ -328,6 +332,10 @@ public class GenerationTests { test_create_signature_reference_dependency(); test_create_signature_with_attr_in_no_namespace(); test_create_signature_with_empty_id(); + test_create_signature_enveloping_over_doc(ENVELOPE, true); + test_create_signature_enveloping_over_doc(ENVELOPE2, true); + test_create_signature_enveloping_over_doc(ENVELOPE, false); + test_create_signature_enveloping_dom_level1(); // run tests for detached signatures with local http server try (Http server = Http.startServer()) { @@ -1038,6 +1046,109 @@ public class GenerationTests { "signature", null); DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc); sig.sign(dsc); + + System.out.println(); + } + + static void test_create_signature_enveloping_over_doc(String filename, + boolean pass) throws Exception + { + System.out.println("* Generating signature-enveloping-over-doc.xml"); + + // create reference + Reference ref = fac.newReference("#object", sha256); + + // create SignedInfo + SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256, + Collections.singletonList(ref)); + + // create object + Document doc = null; + try (FileInputStream fis = new FileInputStream(filename)) { + doc = db.parse(fis); + } + DOMStructure ds = pass ? new DOMStructure(doc.getDocumentElement()) + : new DOMStructure(doc); + XMLObject obj = fac.newXMLObject(Collections.singletonList(ds), + "object", null, "UTF-8"); + + // This creates an enveloping signature over the entire XML Document + XMLSignature sig = fac.newXMLSignature(si, rsa, + Collections.singletonList(obj), + "signature", null); + DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc); + try { + sig.sign(dsc); + if (!pass) { + // A Document node can only exist at the root of the doc so this + // should fail + throw new Exception("Test unexpectedly passed"); + } + } catch (Exception e) { + if (!pass) { + System.out.println("Test failed as expected: " + e); + } else { + throw e; + } + } + + if (pass) { + DOMValidateContext dvc = new DOMValidateContext + (getPublicKey("RSA", 1024), doc.getDocumentElement()); + XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); + + if (sig.equals(sig2) == false) { + throw new Exception + ("Unmarshalled signature is not equal to generated signature"); + } + if (sig2.validate(dvc) == false) { + throw new Exception("Validation of generated signature failed"); + } + } + + System.out.println(); + } + + static void test_create_signature_enveloping_dom_level1() throws Exception { + System.out.println("* Generating signature-enveloping-dom-level1.xml"); + + // create reference + Reference ref = fac.newReference("#object", sha256); + + // create SignedInfo + SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha256, + Collections.singletonList(ref)); + + // create object using DOM Level 1 methods + Document doc = db.newDocument(); + Element child = doc.createElement("Child"); + child.setAttribute("Version", "1.0"); + child.setAttribute("Id", "child"); + child.setIdAttribute("Id", true); + child.appendChild(doc.createComment("Comment")); + XMLObject obj = fac.newXMLObject( + Collections.singletonList(new DOMStructure(child)), + "object", null, "UTF-8"); + + XMLSignature sig = fac.newXMLSignature(si, rsa, + Collections.singletonList(obj), + "signature", null); + DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 1024), doc); + sig.sign(dsc); + + DOMValidateContext dvc = new DOMValidateContext + (getPublicKey("RSA", 1024), doc.getDocumentElement()); + XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); + + if (sig.equals(sig2) == false) { + throw new Exception + ("Unmarshalled signature is not equal to generated signature"); + } + if (sig2.validate(dvc) == false) { + throw new Exception("Validation of generated signature failed"); + } + + System.out.println(); } static void test_create_signature() throws Exception { diff --git a/test/jdk/javax/xml/crypto/dsig/data/envelope2.xml b/test/jdk/javax/xml/crypto/dsig/data/envelope2.xml new file mode 100644 index 00000000000..d1b56709a57 --- /dev/null +++ b/test/jdk/javax/xml/crypto/dsig/data/envelope2.xml @@ -0,0 +1,15 @@ + + + + foo + bar + + + bar + + + + + + + diff --git a/test/jdk/jdk/internal/platform/docker/Dockerfile-BasicTest b/test/jdk/jdk/internal/platform/docker/Dockerfile-BasicTest index 166c969289e..c275cb74595 100644 --- a/test/jdk/jdk/internal/platform/docker/Dockerfile-BasicTest +++ b/test/jdk/jdk/internal/platform/docker/Dockerfile-BasicTest @@ -1,4 +1,4 @@ -FROM oraclelinux:7.2 +FROM oraclelinux:7.6 MAINTAINER mikhailo.seledtsov@oracle.com COPY /jdk /jdk diff --git a/test/jdk/jdk/jfr/event/io/TestInstrumentation.java b/test/jdk/jdk/jfr/event/io/TestInstrumentation.java index 75e7cb386cd..fe75a350194 100644 --- a/test/jdk/jdk/jfr/event/io/TestInstrumentation.java +++ b/test/jdk/jdk/jfr/event/io/TestInstrumentation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -105,14 +105,14 @@ public class TestInstrumentation implements ClassFileTransformer { "java/io/FileOutputStream::write::(I)V", "java/io/FileOutputStream::write::([B)V", "java/io/FileOutputStream::write::([BII)V", - "java/net/SocketInputStream::read::()I", - "java/net/SocketInputStream::read::([B)I", - "java/net/SocketInputStream::read::([BII)I", - "java/net/SocketInputStream::close::()V", - "java/net/SocketOutputStream::write::(I)V", - "java/net/SocketOutputStream::write::([B)V", - "java/net/SocketOutputStream::write::([BII)V", - "java/net/SocketOutputStream::close::()V", + "java/net/Socket$SocketInputStream::read::()I", + "java/net/Socket$SocketInputStream::read::([B)I", + "java/net/Socket$SocketInputStream::read::([BII)I", + "java/net/Socket$SocketInputStream::close::()V", + "java/net/Socket$SocketOutputStream::write::(I)V", + "java/net/Socket$SocketOutputStream::write::([B)V", + "java/net/Socket$SocketOutputStream::write::([BII)V", + "java/net/Socket$SocketOutputStream::close::()V", "java/nio/channels/FileChannel::read::([Ljava/nio/ByteBuffer;)J", "java/nio/channels/FileChannel::write::([Ljava/nio/ByteBuffer;)J", "java/nio/channels/SocketChannel::open::()Ljava/nio/channels/SocketChannel;", diff --git a/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java b/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java index e998e9aa345..5509c9b500d 100644 --- a/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java +++ b/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ */ package jdk.jfr.jvm; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -54,48 +55,66 @@ public class TestDumpOnCrash { private static final CharSequence LOG_FILE_EXTENSION = ".log"; private static final CharSequence JFR_FILE_EXTENSION = ".jfr"; - static class Crasher { + static class CrasherIllegalAccess { public static void main(String[] args) { Unsafe.getUnsafe().putInt(0L, 0); } } - public static void main(String[] args) throws Exception { - processOutput(runProcess()); + static class CrasherHalt { + public static void main(String[] args) { + System.out.println("Running Runtime.getRuntime.halt"); + Runtime.getRuntime().halt(17); + } } - private static OutputAnalyzer runProcess() throws Exception { - return new OutputAnalyzer( - ProcessTools.createJavaProcessBuilder(true, + static class CrasherSig { + public static void main(String[] args) throws Exception { + String signalName = args[0]; + System.out.println("Sending SIG" + signalName + " to process " + ProcessHandle.current().pid()); + Runtime.getRuntime().exec("kill -" + signalName + " " + ProcessHandle.current().pid()).waitFor(); + } + } + + public static void main(String[] args) throws Exception { + verify(runProcess(CrasherIllegalAccess.class.getName(), "")); + verify(runProcess(CrasherHalt.class.getName(), "")); + + // Verification is excluded for the test case below until 8219680 is fixed + long pid = runProcess(CrasherSig.class.getName(), "FPE"); + // @ignore 8219680 + // verify(pid); + } + + private static long runProcess(String crasher, String signal) throws Exception { + System.out.println("Test case for crasher " + crasher); + Process p = ProcessTools.createJavaProcessBuilder(true, "-Xmx64m", - "-Xint", "-XX:-CreateCoredumpOnCrash", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", - "-XX:StartFlightRecording=dumponexit=true", - Crasher.class.getName()).start()); + "-XX:StartFlightRecording", + crasher, + signal) + .start(); + + OutputAnalyzer output = new OutputAnalyzer(p); + System.out.println("========== Crasher process output:"); + System.out.println(output.getOutput()); + System.out.println("=================================="); + + return p.pid(); } - private static void processOutput(OutputAnalyzer output) throws Exception { - output.shouldContain("CreateCoredumpOnCrash turned off, no core file dumped"); + private static void verify(long pid) throws IOException { + String fileName = "hs_err_pid" + pid + ".jfr"; + Path file = Paths.get(fileName).toAbsolutePath().normalize(); - final Path jfrEmergencyFilePath = getHsErrJfrPath(output); - Asserts.assertTrue(Files.exists(jfrEmergencyFilePath), "No emergency jfr recording file " + jfrEmergencyFilePath + " exists"); - Asserts.assertNotEquals(Files.size(jfrEmergencyFilePath), 0L, "File length 0. Should at least be some bytes"); - System.out.printf("File size=%d%n", Files.size(jfrEmergencyFilePath)); + Asserts.assertTrue(Files.exists(file), "No emergency jfr recording file " + file + " exists"); + Asserts.assertNotEquals(Files.size(file), 0L, "File length 0. Should at least be some bytes"); + System.out.printf("File size=%d%n", Files.size(file)); - List events = RecordingFile.readAllEvents(jfrEmergencyFilePath); + List events = RecordingFile.readAllEvents(file); Asserts.assertFalse(events.isEmpty(), "No event found"); System.out.printf("Found event %s%n", events.get(0).getEventType().getName()); } - - private static Path getHsErrJfrPath(OutputAnalyzer output) throws Exception { - // extract to find hs-err_pid log file location - final String hs_err_pid_log_file = output.firstMatch("# *(\\S*hs_err_pid\\d+\\.log)", 1); - if (hs_err_pid_log_file == null) { - throw new RuntimeException("Did not find hs_err_pid.log file in output.\n"); - } - // the dumped out jfr file should have the same name and location but with a .jfr extension - final String hs_err_pid_jfr_file = hs_err_pid_log_file.replace(LOG_FILE_EXTENSION, JFR_FILE_EXTENSION); - return Paths.get(hs_err_pid_jfr_file); - } } diff --git a/test/jdk/jdk/jfr/tool/TestPrint.java b/test/jdk/jdk/jfr/tool/TestPrint.java index f6b01e71893..88c5ac0840a 100644 --- a/test/jdk/jdk/jfr/tool/TestPrint.java +++ b/test/jdk/jdk/jfr/tool/TestPrint.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ public class TestPrint { output.shouldContain("missing file"); output = ExecuteHelper.jfr("print", "missing.jfr"); - output.shouldContain("could not find file "); + output.shouldContain("could not open file "); Path file = Utils.createTempFile("faked-print-file", ".jfr"); FileWriter fw = new FileWriter(file.toFile()); diff --git a/test/jdk/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java b/test/jdk/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java index bf820b09d78..6b3f9294154 100644 --- a/test/jdk/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java +++ b/test/jdk/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,12 +37,13 @@ import java.nio.file.Paths; import java.util.Arrays; import java.util.List; -import jdk.test.lib.compiler.CompilerUtils; -import static jdk.test.lib.process.ProcessTools.*; - import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import static org.testng.Assert.*; + +import jdk.test.lib.compiler.CompilerUtils; + +import static jdk.test.lib.process.ProcessTools.executeTestJava; +import static org.testng.Assert.assertTrue; @Test public class OverlappingPackagesTest { @@ -93,7 +94,7 @@ public class OverlappingPackagesTest { public void testOverlapWithBaseModule() throws Exception { int exitValue = executeTestJava("--module-path", MODS_DIR.toString(), - "-add-modules", "misc", + "--add-modules", "misc", "-m", "test/test.Main") .outputTo(System.out) .errorTo(System.err) diff --git a/test/jdk/jdk/net/Sockets/QuickAckTest.java b/test/jdk/jdk/net/Sockets/QuickAckTest.java index b1d9f899c24..5561e02ffb7 100644 --- a/test/jdk/jdk/net/Sockets/QuickAckTest.java +++ b/test/jdk/jdk/net/Sockets/QuickAckTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ */ import java.io.IOException; import java.net.DatagramSocket; +import java.net.InetAddress; import java.net.MulticastSocket; import java.net.ServerSocket; import java.net.Socket; @@ -38,12 +39,10 @@ import jdk.net.Sockets; public class QuickAckTest { - private static final String LOCAL_HOST = "127.0.0.1"; - public static void main(String args[]) throws IOException { try (ServerSocket ss = new ServerSocket(0); - Socket s = new Socket(LOCAL_HOST, ss.getLocalPort()); + Socket s = new Socket(InetAddress.getLoopbackAddress(), ss.getLocalPort()); DatagramSocket ds = new DatagramSocket(0); MulticastSocket mc = new MulticastSocket(0)) { diff --git a/test/jdk/jdk/net/Sockets/Test.java b/test/jdk/jdk/net/Sockets/Test.java index 639a7a1bcc3..bc1b92333cb 100644 --- a/test/jdk/jdk/net/Sockets/Test.java +++ b/test/jdk/jdk/net/Sockets/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,14 +79,14 @@ public class Test { DatagramSocket dg = new DatagramSocket(0)) { int tcp_port = ss.getLocalPort(); - final InetAddress loop = InetAddress.getByName("127.0.0.1"); + final InetAddress loop = InetAddress.getLoopbackAddress(); final InetSocketAddress loopad = new InetSocketAddress(loop, tcp_port); final int udp_port = dg.getLocalPort(); - final Socket s = new Socket("127.0.0.1", tcp_port); + final Socket s = new Socket(loop, tcp_port); final SocketChannel sc = SocketChannel.open(); - sc.connect(new InetSocketAddress("127.0.0.1", tcp_port)); + sc.connect(new InetSocketAddress(loop, tcp_port)); doTest("Sockets.setOption Socket", () -> { out.println(flowIn); diff --git a/test/jdk/sun/management/jmxremote/bootstrap/JMXAgentInterfaceBinding.java b/test/jdk/sun/management/jmxremote/bootstrap/JMXAgentInterfaceBinding.java index 4647f280fef..93200bd6341 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/JMXAgentInterfaceBinding.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/JMXAgentInterfaceBinding.java @@ -28,10 +28,13 @@ import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; @@ -135,9 +138,9 @@ public class JMXAgentInterfaceBinding { private final int rmiPort; private final boolean useSSL; private final CountDownLatch latch; - private boolean failed; - private boolean jmxConnectWorked; - private boolean rmiConnectWorked; + private volatile boolean failed; + private volatile boolean jmxConnectWorked; + private volatile boolean rmiConnectWorked; private JMXConnectorThread(String addr, int jmxPort, @@ -156,6 +159,7 @@ public class JMXAgentInterfaceBinding { try { connect(); } catch (IOException e) { + e.printStackTrace(); failed = true; } } @@ -223,14 +227,16 @@ public class JMXAgentInterfaceBinding { private static class MainThread extends Thread { - private static final int WAIT_FOR_JMX_AGENT_TIMEOUT_MS = 500; + private static final String EXP_TERM_MSG_REG = "Exit: ([0-9]+)"; + private static final Pattern EXIT_PATTERN = Pattern.compile(EXP_TERM_MSG_REG); + private static final String COOP_EXIT = "MainThread: Cooperative Exit"; + private static final int WAIT_FOR_JMX_AGENT_TIMEOUT_MS = 20_000; private final String addr; private final int jmxPort; private final int rmiPort; private final boolean useSSL; - private boolean terminated = false; private boolean jmxAgentStarted = false; - private Exception excptn; + private volatile Exception excptn; private MainThread(InetAddress bindAddress, int jmxPort, int rmiPort, boolean useSSL) { this.addr = wrapAddress(bindAddress.getHostAddress()); @@ -243,14 +249,16 @@ public class JMXAgentInterfaceBinding { public void run() { try { waitUntilReadyForConnections(); - // Do nothing, but wait for termination. - try { - while (!terminated) { - Thread.sleep(100); - } - } catch (InterruptedException e) { // ignore + + // Wait for termination message + String actualTerm = new String(System.in.readAllBytes(), StandardCharsets.UTF_8).trim(); + System.err.println("DEBUG: MainThread: actualTerm: '" + actualTerm + "'"); + Matcher matcher = EXIT_PATTERN.matcher(actualTerm); + if (matcher.matches()) { + int expExitCode = Integer.parseInt(matcher.group(1)); + System.out.println(COOP_EXIT); + System.exit(expExitCode); // The main test expects this exit value } - System.out.println("MainThread: Thread stopped."); } catch (Exception e) { this.excptn = e; } diff --git a/test/jdk/sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java b/test/jdk/sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java index 6899c014b9f..3d6f25052ec 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java @@ -24,6 +24,7 @@ import java.io.File; import java.net.InetAddress; import java.net.NetworkInterface; +import java.net.UnknownHostException; import java.net.SocketException; import java.util.ArrayList; import java.util.List; @@ -33,33 +34,32 @@ import jdk.test.lib.thread.ProcessThread; import jdk.test.lib.process.ProcessTools; /** - * NOTE: - * This test requires at least a setup similar to the following in - * /etc/hosts file (or the windows equivalent). I.e. it expects it to - * be multi-homed and not both being the loop-back interface. - * For example: - * ----->8-------- /etc/hosts ----------->8--- - * 127.0.0.1 localhost - * 192.168.0.1 localhost - * ----->8-------- /etc/hosts ----------->8--- - * * @test * @bug 6425769 * @summary Test JMX agent host address binding. Same ports but different - * interfaces to bind to (using plain sockets and SSL sockets). + * interfaces to bind to (selecting plain or SSL sockets at random + * @key intermittent * * @library /test/lib * @modules java.management.rmi * * @build JMXAgentInterfaceBinding - * @run main/timeout=5 JMXInterfaceBindingTest + * @run main/timeout=60 JMXInterfaceBindingTest */ public class JMXInterfaceBindingTest { public static final int COMMUNICATION_ERROR_EXIT_VAL = 1; - public static final int STOP_PROCESS_EXIT_VAL = 143; - public static final int JMX_PORT = 9111; - public static final int RMI_PORT = 9112; + public static final int STOP_PROCESS_EXIT_VAL = 10; + public static final int JMX_PORT_RANGE_LOWER = 9100; + public static final int JMX_PORT_RANGE_UPPER = 9200; + public static final int JMX_PORT = getRandomPortInRange(JMX_PORT_RANGE_LOWER, + JMX_PORT_RANGE_UPPER); + public static final int JMX_PORT_RANGE_LOWER_SSL = 9201; // 9200 might be RMI Port + public static final int JMX_PORT_RANGE_UPPER_SSL = 9300; + public static final int JMX_PORT_SSL = getRandomPortInRange(JMX_PORT_RANGE_LOWER_SSL, + JMX_PORT_RANGE_UPPER_SSL); + public static final int RMI_PORT = JMX_PORT + 1; + public static final int RMI_PORT_SSL = JMX_PORT_SSL + 1; public static final String READY_MSG = "MainThread: Ready for connections"; public static final String TEST_CLASS = JMXAgentInterfaceBinding.class.getSimpleName(); public static final String KEYSTORE_LOC = System.getProperty("test.src", ".") + @@ -89,8 +89,8 @@ public class JMXInterfaceBindingTest { System.out.println(); String msg = String.format("DEBUG: Launching java tester for triplet (HOSTNAME,JMX_PORT,RMI_PORT) == (%s,%d,%d)", address, - JMX_PORT, - RMI_PORT); + useSSL ? JMX_PORT_SSL : JMX_PORT, + useSSL ? RMI_PORT_SSL : RMI_PORT); System.out.println(msg); ProcessThread jvm = runJMXBindingTest(address, useSSL); jvms.add(jvm); @@ -100,9 +100,9 @@ public class JMXInterfaceBindingTest { int failedProcesses = 0; for (ProcessThread pt: jvms) { try { - pt.stopProcess(); + pt.sendMessage("Exit: " + STOP_PROCESS_EXIT_VAL); pt.join(); - } catch (InterruptedException e) { + } catch (Throwable e) { System.err.println("Failed to stop process: " + pt.getName()); throw new RuntimeException("Test failed", e); } @@ -131,10 +131,12 @@ public class JMXInterfaceBindingTest { args.add("-classpath"); args.add(TEST_CLASSPATH); args.add("-Dcom.sun.management.jmxremote.host=" + address); - args.add("-Dcom.sun.management.jmxremote.port=" + JMX_PORT); - args.add("-Dcom.sun.management.jmxremote.rmi.port=" + RMI_PORT); + args.add("-Dcom.sun.management.jmxremote.port=" + (useSSL ? JMX_PORT_SSL : JMX_PORT)); + args.add("-Dcom.sun.management.jmxremote.rmi.port=" + (useSSL ? RMI_PORT_SSL : RMI_PORT)); args.add("-Dcom.sun.management.jmxremote.authenticate=false"); args.add("-Dcom.sun.management.jmxremote.ssl=" + Boolean.toString(useSSL)); + // This is needed for testing on loopback + args.add("-Djava.rmi.server.hostname=" + address); if (useSSL) { args.add("-Dcom.sun.management.jmxremote.registry.ssl=true"); args.add("-Djavax.net.ssl.keyStore=" + KEYSTORE_LOC); @@ -144,8 +146,8 @@ public class JMXInterfaceBindingTest { } args.add(TEST_CLASS); args.add(address); - args.add(Integer.toString(JMX_PORT)); - args.add(Integer.toString(RMI_PORT)); + args.add(Integer.toString(useSSL ? JMX_PORT_SSL : JMX_PORT)); + args.add(Integer.toString(useSSL ? RMI_PORT_SSL : RMI_PORT)); args.add(Boolean.toString(useSSL)); try { ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(args.toArray(new String[] {})); @@ -175,35 +177,42 @@ public class JMXInterfaceBindingTest { } } + private static int getRandomPortInRange(int lower, int upper) { + if (upper <= lower) { + throw new IllegalArgumentException("upper <= lower"); + } + int range = upper - lower; + int randPort = lower + (int)(Math.random() * range); + return randPort; + } + public static void main(String[] args) { - List addrs = getAddressesForLocalHost(); - if (addrs.size() < 2) { - System.out.println("Ignoring manual test since no more than one IPs are configured for 'localhost'"); + List addrs = getNonLoopbackAddressesForLocalHost(); + if (addrs.isEmpty()) { + System.out.println("Ignoring test since no non-loopback IPs are available to bind to " + + "in addition to the loopback interface."); return; } JMXInterfaceBindingTest test = new JMXInterfaceBindingTest(); + // Add loopback interface too as we'd like to verify whether it's + // possible to bind to multiple addresses on the same host. This + // wasn't possible prior JDK-6425769. It used to bind to *all* local + // interfaces. We add loopback here, since that eases test setup. + addrs.add(InetAddress.getLoopbackAddress()); test.run(addrs); System.out.println("All tests PASSED."); } - private static List getAddressesForLocalHost() { - + private static List getNonLoopbackAddressesForLocalHost() { + List addrs = new ArrayList<>(); try { - return NetworkInterface.networkInterfaces() - .flatMap(NetworkInterface::inetAddresses) - .filter(JMXInterfaceBindingTest::isNonloopbackLocalhost) - .collect(Collectors.toList()); - } catch (SocketException e) { + InetAddress localHost = InetAddress.getLocalHost(); + if (!localHost.isLoopbackAddress()) { + addrs.add(localHost); + } + return addrs; + } catch (UnknownHostException e) { throw new RuntimeException("Test failed", e); } } - - // we need 'real' localhost addresses only (eg. not loopback ones) - // so we can bind the remote JMX connector to them - private static boolean isNonloopbackLocalhost(InetAddress i) { - if (!i.isLoopbackAddress()) { - return i.getHostName().toLowerCase().equals("localhost"); - } - return false; - } } diff --git a/test/jdk/sun/net/www/protocol/http/StackTraceTest.java b/test/jdk/sun/net/www/protocol/http/StackTraceTest.java index 3a12c3c4eef..0b710269570 100644 --- a/test/jdk/sun/net/www/protocol/http/StackTraceTest.java +++ b/test/jdk/sun/net/www/protocol/http/StackTraceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,22 +21,30 @@ * questions. */ -/** +/* * @test * @bug 4773417 5003746 + * @library /test/lib + * @build jdk.test.lib.Utils + * @run main StackTraceTest * @summary HttpURLConnection.getInputStream() produces IOException with * bad stack trace; HttpURLConnection.getInputStream loses * exception message, exception class */ import java.net.*; import java.io.IOException; +import jdk.test.lib.Utils; public class StackTraceTest { public static void main(String[] args) throws Exception { - URL url; - try (ServerSocket ss = new ServerSocket(0)) { // refusing socket - url = new URL("http://localhost:" + ss.getLocalPort() + "/"); - } + InetSocketAddress refusing = Utils.refusingEndpoint(); + int port = refusing.getPort(); + String host = refusing.getAddress().getHostAddress(); + if (host.contains(":")) + host = "[" + host + "]"; + URL url = URI.create("http://" + host + ":" + port + "/").toURL(); + System.out.println("URL: " + url); + URLConnection uc = url.openConnection(); // Trigger implicit connection by trying to retrieve bogus diff --git a/test/jdk/sun/net/www/protocol/http/TunnelThroughProxy.java b/test/jdk/sun/net/www/protocol/http/TunnelThroughProxy.java index 4d4260f6bb4..78e98609362 100644 --- a/test/jdk/sun/net/www/protocol/http/TunnelThroughProxy.java +++ b/test/jdk/sun/net/www/protocol/http/TunnelThroughProxy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,8 +64,9 @@ public class TunnelThroughProxy { int serverPort = server.getLocalPort(); Socket sock; - sock = new Socket(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", proxyPort))); - InetSocketAddress dest = new InetSocketAddress("127.0.0.1", serverPort); + sock = new Socket(new Proxy(Proxy.Type.HTTP, + new InetSocketAddress(InetAddress.getLoopbackAddress(), proxyPort))); + InetSocketAddress dest = new InetSocketAddress(InetAddress.getLoopbackAddress(), serverPort); sock.connect(dest); int localPort = sock.getLocalPort(); if (localPort == proxyPort) diff --git a/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/CheckMethods.java b/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/CheckMethods.java index 9ca30a19855..fc1de1261d9 100644 --- a/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/CheckMethods.java +++ b/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/CheckMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,13 +26,12 @@ * @bug 4423074 * @summary Need to rebase all the duplicated classes from Merlin. * This test will check out http POST - * @modules java.base/sun.net.www.protocol.https java.base/com.sun.net.ssl.internal.www.protocol.https + * @modules java.base/sun.net.www.protocol.https */ import java.net.*; import java.util.*; import java.lang.reflect.*; import sun.net.www.protocol.https.HttpsURLConnectionImpl; -import com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl; public class CheckMethods { static boolean debug = false; @@ -85,9 +84,8 @@ public class CheckMethods { } } - // check HttpsURLConnectionImpl and HttpsURLConnectionOldImpl - // contain all public and protected methods defined in - // HttpURLConnection and URLConnection + // check HttpsURLConnectionImpl contain all public and protected methods + // defined in HttpURLConnection and URLConnection public static void main(String[] args) { ArrayList allMethods = new ArrayList( Arrays.asList(HttpURLConnection.class.getDeclaredMethods())); @@ -121,24 +119,6 @@ public class CheckMethods { throw new RuntimeException("Method definition test failed on HttpsURLConnectionImpl"); } - // testing HttpsURLConnectionOldImpl - List httpsOldMethods = - Arrays.asList(HttpsURLConnectionOldImpl.class.getDeclaredMethods()); - - ArrayList httpsOldMethodSignatures = new ArrayList(); - for (Iterator itr = httpsOldMethods.iterator(); itr.hasNext(); ) { - Method m = (Method)itr.next(); - if (!Modifier.isStatic(m.getModifiers())) { - httpsOldMethodSignatures.add( - new MethodSignature(m.getName(), m.getParameterTypes())); - } - } - - if (!httpsOldMethodSignatures.containsAll(allMethodSignatures)) { - throw new RuntimeException("Method definition test failed" + - " on HttpsURLConnectionOldImpl"); - } - // testing for non static public field ArrayList allFields = new ArrayList( Arrays.asList(URLConnection.class.getFields())); diff --git a/test/jdk/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java b/test/jdk/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java deleted file mode 100644 index 7b301270c6d..00000000000 --- a/test/jdk/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright (c) 2001, 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 - * @bug 4474255 - * @summary Can no longer obtain a com.sun.net.ssl.HttpsURLConnection - * @modules java.base/com.sun.net.ssl - * java.base/com.sun.net.ssl.internal.www.protocol.https - * @run main/othervm ComHTTPSConnection - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import java.security.cert.Certificate; -import javax.net.ssl.*; -import com.sun.net.ssl.HostnameVerifier; -import com.sun.net.ssl.HttpsURLConnection; - -/** - * See if we can obtain a com.sun.net.ssl.HttpsURLConnection, - * and then play with it a bit. - */ -public class ComHTTPSConnection { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * 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 = "../../../../../../javax/net/ssl/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.... - */ - - /** - * Returns the path to the file obtained from - * parsing the HTML header. - */ - private static String getPath(DataInputStream in) - throws IOException - { - String line = in.readLine(); - String path = ""; - // extract class from GET line - if (line.startsWith("GET /")) { - line = line.substring(5, line.length()-1).trim(); - int index = line.indexOf(' '); - if (index != -1) { - path = line.substring(0, index); - } - } - - // eat the rest of header - do { - line = in.readLine(); - } while ((line.length() != 0) && - (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); - - if (path.length() != 0) { - return path; - } else { - throw new IOException("Malformed Header"); - } - } - - /** - * Returns an array of bytes containing the bytes for - * the file represented by the argument path. - * - * In our case, we just pretend to send something back. - * - * @return the bytes for the file - * @exception FileNotFoundException if the file corresponding - * to path could not be loaded. - */ - private byte[] getBytes(String path) - throws IOException - { - return "Hello world, I am here".getBytes(); - } - - /* - * 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(); - DataOutputStream out = - new DataOutputStream(sslSocket.getOutputStream()); - - try { - // get path to class file from header - DataInputStream in = - new DataInputStream(sslSocket.getInputStream()); - String path = getPath(in); - // retrieve bytecodes - byte[] bytecodes = getBytes(path); - // send bytecodes in response (assumes HTTP/1.0 or later) - try { - out.writeBytes("HTTP/1.0 200 OK\r\n"); - out.writeBytes("Content-Length: " + bytecodes.length + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.write(bytecodes); - out.flush(); - } catch (IOException ie) { - ie.printStackTrace(); - return; - } - - } catch (Exception e) { - e.printStackTrace(); - // write out error response - out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.flush(); - } finally { - // close the socket - System.out.println("Server closing socket"); - sslSocket.close(); - serverReady = false; - } - } - - private static class ComSunHTTPSHandlerFactory implements URLStreamHandlerFactory { - private static String SUPPORTED_PROTOCOL = "https"; - - public URLStreamHandler createURLStreamHandler(String protocol) { - if (!protocol.equalsIgnoreCase(SUPPORTED_PROTOCOL)) - return null; - - return new com.sun.net.ssl.internal.www.protocol.https.Handler(); - } - } - - /* - * 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); - } - - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - URL.setURLStreamHandlerFactory(new ComSunHTTPSHandlerFactory()); - HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier()); - - URL url = new URL("https://" + "localhost:" + serverPort + - "/etc/hosts"); - URLConnection urlc = url.openConnection(); - - if (!(urlc instanceof com.sun.net.ssl.HttpsURLConnection)) { - throw new Exception( - "URLConnection ! instanceof " + - "com.sun.net.ssl.HttpsURLConnection"); - } - - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - urlc.getInputStream())); - String inputLine; - System.out.print("Client reading... "); - while ((inputLine = in.readLine()) != null) - System.out.println(inputLine); - - System.out.println("Cipher Suite: " + - ((HttpsURLConnection)urlc).getCipherSuite()); - Certificate[] certs = - ((HttpsURLConnection)urlc).getServerCertificates(); - for (int i = 0; i < certs.length; i++) { - System.out.println(certs[0]); - } - - in.close(); - } catch (SSLException e) { - if (in != null) - in.close(); - throw e; - } - System.out.println("Client reports: SUCCESS"); - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } - - static class NameVerifier implements HostnameVerifier { - public boolean verify(String urlHostname, - String certHostname) { - System.out.println( - "CertificateHostnameVerifier: " + urlHostname + " == " - + certHostname + " returning true"); - return true; - } - } - - /* - * ============================================================= - * 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 ComHTTPSConnection(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ComHTTPSConnection() 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(); - } - } -} diff --git a/test/jdk/sun/net/www/protocol/https/NewImpl/ComHostnameVerifier.java b/test/jdk/sun/net/www/protocol/https/NewImpl/ComHostnameVerifier.java deleted file mode 100644 index 2a1f80a4cac..00000000000 --- a/test/jdk/sun/net/www/protocol/https/NewImpl/ComHostnameVerifier.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 4474255 4484246 - * @summary When an application enables anonymous SSL cipher suite, - * Hostname verification is not required - * @modules java.base/com.sun.net.ssl - * java.base/com.sun.net.ssl.internal.www.protocol.https - * @run main/othervm ComHostnameVerifier - */ - -import java.io.*; -import java.net.*; -import java.security.Security; -import javax.net.ssl.*; -import javax.security.cert.*; -import com.sun.net.ssl.HostnameVerifier; -import com.sun.net.ssl.HttpsURLConnection; - -/** - * Use com.net.net.ssl.HostnameVerifier - */ -public class ComHostnameVerifier { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * 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; - - /* - * 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.... - */ - - /** - * Returns the path to the file obtained from - * parsing the HTML header. - */ - private static String getPath(DataInputStream in) - throws IOException - { - String line = in.readLine(); - if (line == null) - return null; - String path = ""; - // extract class from GET line - if (line.startsWith("GET /")) { - line = line.substring(5, line.length()-1).trim(); - int index = line.indexOf(' '); - if (index != -1) { - path = line.substring(0, index); - } - } - - // eat the rest of header - do { - line = in.readLine(); - } while ((line.length() != 0) && - (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); - - if (path.length() != 0) { - return path; - } else { - throw new IOException("Malformed Header"); - } - } - - /** - * Returns an array of bytes containing the bytes for - * the file represented by the argument path. - * - * In our case, we just pretend to send something back. - * - * @return the bytes for the file - * @exception FileNotFoundException if the file corresponding - * to path could not be loaded. - */ - private byte[] getBytes(String path) - throws IOException - { - return "Hello world, I am here".getBytes(); - } - - /* - * 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(); - - String ciphers[]= { "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" }; - sslServerSocket.setEnabledCipherSuites(ciphers); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - DataOutputStream out = - new DataOutputStream(sslSocket.getOutputStream()); - - try { - // get path to class file from header - DataInputStream in = - new DataInputStream(sslSocket.getInputStream()); - String path = getPath(in); - // retrieve bytecodes - byte[] bytecodes = getBytes(path); - // send bytecodes in response (assumes HTTP/1.0 or later) - try { - out.writeBytes("HTTP/1.0 200 OK\r\n"); - out.writeBytes("Content-Length: " + bytecodes.length + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.write(bytecodes); - out.flush(); - } catch (IOException ie) { - ie.printStackTrace(); - return; - } - - } catch (Exception e) { - e.printStackTrace(); - // write out error response - out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.flush(); - } finally { - // close the socket - System.out.println("Server closing socket"); - sslSocket.close(); - serverReady = false; - } - } - - private static class ComSunHTTPSHandlerFactory implements URLStreamHandlerFactory { - private static String SUPPORTED_PROTOCOL = "https"; - - public URLStreamHandler createURLStreamHandler(String protocol) { - if (!protocol.equalsIgnoreCase(SUPPORTED_PROTOCOL)) - return null; - - return new com.sun.net.ssl.internal.www.protocol.https.Handler(); - } - } - - /* - * 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); - } - - URL.setURLStreamHandlerFactory(new ComSunHTTPSHandlerFactory()); - - System.setProperty("https.cipherSuites", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); - - // use the default hostname verifier - - URL url = new URL("https://" + "localhost:" + serverPort + - "/etc/hosts"); - URLConnection urlc = url.openConnection(); - - if (!(urlc instanceof com.sun.net.ssl.HttpsURLConnection)) { - throw new Exception( - "URLConnection ! instanceof " + - "com.sun.net.ssl.HttpsURLConnection"); - } - - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - urlc.getInputStream())); - String inputLine; - System.out.print("Client reading... "); - while ((inputLine = in.readLine()) != null) - System.out.println(inputLine); - System.out.println("Cipher Suite: " + - ((HttpsURLConnection)urlc).getCipherSuite()); - in.close(); - } catch (SSLException e) { - if (in != null) - in.close(); - throw e; - } - System.out.println("Client reports: SUCCESS"); - } - - /* - * ============================================================= - * 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 { - // re-enable 3DES - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ComHostnameVerifier(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ComHostnameVerifier() 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(); - } - } -} diff --git a/test/jdk/sun/nio/cs/TestIBMBugs.java b/test/jdk/sun/nio/cs/TestIBMBugs.java index ab03e6cd5ce..387fe9ac1bd 100644 --- a/test/jdk/sun/nio/cs/TestIBMBugs.java +++ b/test/jdk/sun/nio/cs/TestIBMBugs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* @test - * @bug 6371437 6371422 6371416 6371619 5058184 6371431 6639450 6569191 6577466 8212794 + * @bug 6371437 6371422 6371416 6371619 5058184 6371431 6639450 6569191 6577466 8212794 8220281 * @summary Check if the problems reported in above bugs have been fixed * @modules jdk.charsets */ @@ -31,6 +31,8 @@ import java.io.*; import java.nio.*; import java.nio.charset.*; import java.util.Arrays; +import java.util.Locale; +import java.util.HashSet; public class TestIBMBugs { @@ -250,6 +252,77 @@ public class TestIBMBugs { } } + private static void bug8220281 () throws Exception { + if (System.getProperty("os.name").contains("AIX")) { + /* Following AIX codesets are used for Java default charset. */ + /* They should be in sun.nio.cs package on AIX platform. */ + String[] codesets = new String[] { + "IBM-950", "BIG5-HKSCS", "GB18030", "IBM-1046", + "IBM-1124", "IBM-1129", "IBM-1252", "IBM-856", + "IBM-858", "IBM-921", "IBM-922", "IBM-932", "IBM-943C", + "IBM-eucCN", "IBM-eucJP", "IBM-eucKR", "IBM-eucTW", + "ISO8859-1", "ISO8859-15", "ISO8859-2", "ISO8859-4", + "ISO8859-5", "ISO8859-6", "ISO8859-7", "ISO8859-8", + "ISO8859-9", "TIS-620", "UTF-8", }; + String[] charsets = new String[] { + "x-IBM950", "Big5-HKSCS", "GB18030", "x-IBM1046", + "x-IBM1124", "x-IBM1129", "windows-1252", "x-IBM856", + "IBM00858", "x-IBM921", "x-IBM922", "x-IBM942C", + "x-IBM943C", "x-IBM1383", "x-IBM29626C", "x-IBM970", + "x-IBM964", "ISO-8859-1", "ISO-8859-15", "ISO-8859-2", + "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", + "ISO-8859-8", "ISO-8859-9", "TIS-620", "UTF-8", }; + for(int i = 0; i < codesets.length; i++) { + Charset cs0 = Charset.forName(codesets[i]); + if (!"sun.nio.cs".equals(cs0.getClass().getPackage().getName())) { + throw new Exception(cs0.getClass().getCanonicalName()+" faild"); + } + Charset cs1 = Charset.forName(charsets[i]); + if (!cs0.equals(cs1)) { + throw new Exception(codesets[i]+"("+cs0.name()+") failed"); + } + } + } + for(Charset cs : Charset.availableCharsets().values()) { + String csName = cs.name().toLowerCase(Locale.ROOT); + String suffix = null; + HashSet aliases = new HashSet(); + for(String s : cs.aliases()) { + aliases.add(s.toLowerCase(Locale.ROOT)); + } + aliases.add(csName); + if (csName.startsWith("x-ibm-")) { + suffix = csName.replaceAll("x-ibm-0*", ""); + } else if (csName.startsWith("x-ibm")) { + suffix = csName.replaceAll("x-ibm0*", ""); + } else if (csName.startsWith("ibm-")) { + suffix = csName.replaceAll("ibm-0*", ""); + } else if (csName.startsWith("ibm")) { + suffix = csName.replaceAll("ibm0*", ""); + } + if ("ibm-thai".equals(csName)) { + suffix = "838"; + } + if (null != suffix) { + while (suffix.length() < 3) { + suffix = "0"+suffix; + } + if (!aliases.contains("cp"+suffix)) { + throw new Exception(cs.name()+"\t"+"cp"+suffix); + } + if (!aliases.contains("ibm"+suffix)) { + throw new Exception(cs.name()+"\t"+"ibm"+suffix); + } + if (!aliases.contains("ibm-"+suffix)) { + throw new Exception(cs.name()+"\t"+"ibm-"+suffix); + } + if (!aliases.contains(suffix)) { + throw new Exception(cs.name()+"\t"+suffix); + } + } + } + } + public static void main (String[] args) throws Exception { bug6577466(); // need to be tested before any other IBM949C test case @@ -263,5 +336,6 @@ public class TestIBMBugs { bug8202329(); bug8212794(); bug8213618(); + bug8220281(); } } diff --git a/test/jdk/sun/security/ec/SignatureDigestTruncate.java b/test/jdk/sun/security/ec/SignatureDigestTruncate.java new file mode 100644 index 00000000000..aa58a9b7169 --- /dev/null +++ b/test/jdk/sun/security/ec/SignatureDigestTruncate.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.Convert; + +import java.security.*; +import java.security.spec.*; +import java.math.*; +import java.util.*; + +/* + * @test + * @bug 8147502 + * @summary Test that digests are properly truncated before the signature + * is applied. The digest should be truncated to the bit length of the + * group order. + * @library /test/lib + * @build jdk.test.lib.Convert + * @run main SignatureDigestTruncate + */ +public class SignatureDigestTruncate { + + /* + * A SecureRandom that produces nextBytes in a way that causes the nonce + * to be set to the value supplied to the constructor. This class + * is specific to the way that the native ECDSA implementation in + * SunEC produces nonces from random input. It may not work for all + * test cases, and it will need to be updated when the behavior of + * SunEC changes. + */ + private static class FixedRandom extends SecureRandom { + + private final byte[] val; + + public FixedRandom(byte[] val) { + // SunEC adds one to the value returned, so subtract one here in + // order to get back to the correct value. + BigInteger biVal = new BigInteger(1, val); + biVal = biVal.subtract(BigInteger.ONE); + byte[] temp = biVal.toByteArray(); + this.val = new byte[val.length]; + int inStartPos = Math.max(0, temp.length - val.length); + int outStartPos = Math.max(0, val.length - temp.length); + System.arraycopy(temp, inStartPos, this.val, outStartPos, + temp.length - inStartPos); + } + + @Override + public void nextBytes(byte[] bytes) { + // SunEC samples (n + 1) * 2 bytes, but only n*2 bytes are used by + // the native implementation. So the value must be offset slightly. + Arrays.fill(bytes, (byte) 0); + int copyLength = Math.min(val.length, bytes.length - 2); + System.arraycopy(val, 0, bytes, bytes.length - copyLength - 2, + copyLength); + } + } + + private static void assertEquals(byte[] expected, byte[] actual, + String name) { + if (!Arrays.equals(actual, expected)) { + System.out.println("expect: " + + Convert.byteArrayToHexString(expected)); + System.out.println("actual: " + + Convert.byteArrayToHexString(actual)); + throw new RuntimeException("Incorrect " + name + " value"); + } + } + + private static void runTest(String alg, String curveName, + String privateKeyStr, String msgStr, String kStr, String sigStr) + throws Exception { + + byte[] privateKey = Convert.hexStringToByteArray(privateKeyStr); + byte[] msg = Convert.hexStringToByteArray(msgStr); + byte[] k = Convert.hexStringToByteArray(kStr); + byte[] expectedSig = Convert.hexStringToByteArray(sigStr); + + AlgorithmParameters params = AlgorithmParameters.getInstance("EC"); + params.init(new ECGenParameterSpec(curveName)); + ECParameterSpec ecParams = + params.getParameterSpec(ECParameterSpec.class); + + KeyFactory kf = KeyFactory.getInstance("EC"); + BigInteger s = new BigInteger(1, privateKey); + ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(s, ecParams); + PrivateKey privKey = kf.generatePrivate(privKeySpec); + + Signature sig = Signature.getInstance(alg); + sig.initSign(privKey, new FixedRandom(k)); + sig.update(msg); + byte[] computedSig = sig.sign(); + assertEquals(expectedSig, computedSig, "signature"); + } + + public static void main(String[] args) throws Exception { + runTest("SHA384withECDSAinP1363Format", "sect283r1", + "abcdef10234567", "010203040506070809", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d" + + "1e1f20212223", + "01d7544b5d3935216bd45e2f8042537e1e0296a11e0eb96666199281b409" + + "42abccd5358a035de8a314d3e6c2a97614daebf5fb1313540eec3f9a3272" + + "068aa10922ccae87d255c84c"); + } +} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/CheckNullEntity.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/CheckNullEntity.java index ad00042c01f..452fe1b4570 100644 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/CheckNullEntity.java +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/CheckNullEntity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ * @summary unspecified exceptions in X509TrustManager.checkClient[Server]Truste d * @author Xuelei Fan - * @modules java.base/com.sun.net.ssl.internal.ssl */ import java.io.*; @@ -37,8 +36,6 @@ import java.security.cert.X509Certificate; import java.security.*; import java.util.Enumeration; -import com.sun.net.ssl.internal.ssl.X509ExtendedTrustManager; - public class CheckNullEntity { /* @@ -157,7 +154,7 @@ public class CheckNullEntity { if (trustManager instanceof X509ExtendedTrustManager) { try { ((X509ExtendedTrustManager)trustManager).checkClientTrusted( - certChain, (String)null, "localhost", null); + certChain, (String)null, (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; @@ -165,7 +162,7 @@ public class CheckNullEntity { try { ((X509ExtendedTrustManager)trustManager).checkServerTrusted( - certChain, (String)null, "localhost", null); + certChain, (String)null, (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; @@ -173,7 +170,7 @@ public class CheckNullEntity { try { ((X509ExtendedTrustManager)trustManager).checkClientTrusted( - certChain, "", "localhost", null); + certChain, "", (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; @@ -181,7 +178,7 @@ public class CheckNullEntity { try { ((X509ExtendedTrustManager)trustManager).checkServerTrusted( - certChain, "", "localhost", null); + certChain, "", (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; @@ -189,7 +186,7 @@ public class CheckNullEntity { try { ((X509ExtendedTrustManager)trustManager).checkClientTrusted( - null, authType, "localhost", null); + null, authType, (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; @@ -197,7 +194,7 @@ public class CheckNullEntity { try { ((X509ExtendedTrustManager)trustManager).checkServerTrusted( - null, authType, "localhost", null); + null, authType, (Socket)null); } catch (IllegalArgumentException iae) { // get the right exception extFailed >>= 1; diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/ClientServer.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/ClientServer.java deleted file mode 100644 index 54c6c538437..00000000000 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/ClientServer.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4717766 - * @author Brad Wetmore - * @summary 1.0.3 JsseX509TrustManager erroneously calls isClientTrusted() - * @modules java.base/com.sun.net.ssl - * @run main/manual ClientServer - */ - -/* - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * - * JSSE supports algorithm constraints with CR 6916074, need to update - * this test case in JDK 7 soon. - * - * This problem didn't exist in JSSE 1.4, only JSSE 1.0.3. However, - * this is a useful test, so I decided to include it in 1.4.2. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.security.cert.*; -import java.security.*; -import com.sun.net.ssl.*; - -public class ClientServer { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * 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 = "../../../../javax/net/ssl/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 = getDefaultServer(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.setNeedClientAuth(true); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - - if (!serverTM.wasServerChecked() && serverTM.wasClientChecked()) { - System.out.println("SERVER TEST PASSED!"); - } else { - throw new Exception("SERVER TEST FAILED! " + - !serverTM.wasServerChecked() + " " + - serverTM.wasClientChecked()); - } - } - - /* - * 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 = getDefaultClient(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - - if (clientTM.wasServerChecked() && !clientTM.wasClientChecked()) { - System.out.println("CLIENT TEST PASSED!"); - } else { - throw new Exception("CLIENT TEST FAILED! " + - clientTM.wasServerChecked() + " " + - !clientTM.wasClientChecked()); - } - } - - private com.sun.net.ssl.SSLContext getDefault(MyX509TM tm) - throws Exception { - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - char[] passphrase = "passphrase".toCharArray(); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(keyFilename), passphrase); - - com.sun.net.ssl.KeyManagerFactory kmf = - com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(trustFilename), passphrase); - - com.sun.net.ssl.TrustManagerFactory tmf = - com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); - - com.sun.net.ssl.TrustManager [] tms = tmf.getTrustManagers(); - - int i; - for (i = 0; i < tms.length; i++) { - if (tms[i] instanceof com.sun.net.ssl.X509TrustManager) { - break; - } - } - - if (i >= tms.length) { - throw new Exception("Couldn't find X509TM"); - } - - tm.init((com.sun.net.ssl.X509TrustManager)tms[i]); - tms = new MyX509TM [] { tm }; - - com.sun.net.ssl.SSLContext ctx = - com.sun.net.ssl.SSLContext.getInstance("TLS"); - ctx.init(kmf.getKeyManagers(), tms, null); - return ctx; - } - - MyX509TM serverTM; - MyX509TM clientTM; - - private SSLServerSocketFactory getDefaultServer() throws Exception { - serverTM = new MyX509TM(); - return getDefault(serverTM).getServerSocketFactory(); - } - - private SSLSocketFactory getDefaultClient() throws Exception { - clientTM = new MyX509TM(); - return getDefault(clientTM).getSocketFactory(); - } - - static class MyX509TM implements com.sun.net.ssl.X509TrustManager { - - com.sun.net.ssl.X509TrustManager tm; - boolean clientChecked; - boolean serverChecked; - - void init(com.sun.net.ssl.X509TrustManager x509TM) { - tm = x509TM; - } - - public boolean wasClientChecked() { - return clientChecked; - } - - public boolean wasServerChecked() { - return serverChecked; - } - - public boolean isClientTrusted(X509Certificate[] chain) { - clientChecked = true; - return true; - } - - public boolean isServerTrusted(X509Certificate[] chain) { - serverChecked = true; - return true; - } - - public X509Certificate[] getAcceptedIssuers() { - return tm.getAcceptedIssuers(); - } - } - - /* - * ============================================================= - * 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 { - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ClientServer(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ClientServer() 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) - throw serverException; - if (clientException != null) - 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(); - } - } -} diff --git a/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java b/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java index b2ccd6e5f9b..8922668b613 100644 --- a/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java +++ b/test/jdk/sun/security/tools/jarsigner/warnings/NoTimestampTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.Date; import java.util.Locale; +import java.util.TimeZone; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.util.JarUtils; @@ -46,6 +47,7 @@ public class NoTimestampTest extends Test { * and checks that proper warnings are shown. */ public static void main(String[] args) throws Throwable { + Locale reservedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -61,6 +63,9 @@ public class NoTimestampTest extends Test { private void start() throws Throwable { String timezone = System.getProperty("user.timezone"); System.out.println(String.format("Timezone = %s", timezone)); + if (timezone != null) { + TimeZone.setDefault(TimeZone.getTimeZone(timezone)); + } // create a jar file that contains one class file Utils.createFiles(FIRST_FILE); @@ -73,10 +78,11 @@ public class NoTimestampTest extends Test { "-validity", Integer.toString(VALIDITY)); Date expirationDate = getCertExpirationDate(); + System.out.println("Cert expiration: " + expirationDate); // sign jar file OutputAnalyzer analyzer = jarsigner( - "-J-Duser.timezone=" + timezone, + userTimezoneOpt(timezone), "-keystore", KEYSTORE, "-storepass", PASSWORD, "-keypass", PASSWORD, @@ -90,7 +96,7 @@ public class NoTimestampTest extends Test { // verify signed jar analyzer = jarsigner( - "-J-Duser.timezone=" + timezone, + userTimezoneOpt(timezone), "-verify", "-keystore", KEYSTORE, "-storepass", PASSWORD, @@ -103,7 +109,7 @@ public class NoTimestampTest extends Test { // verify signed jar in strict mode analyzer = jarsigner( - "-J-Duser.timezone=" + timezone, + userTimezoneOpt(timezone), "-verify", "-strict", "-keystore", KEYSTORE, @@ -117,6 +123,10 @@ public class NoTimestampTest extends Test { System.out.println("Test passed"); } + private static String userTimezoneOpt(String timezone) { + return timezone == null ? null : "-J-Duser.timezone=" + timezone; + } + private static Date getCertExpirationDate() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream in = new FileInputStream(KEYSTORE)) { diff --git a/test/jdk/sun/security/tools/jarsigner/warnings/Test.java b/test/jdk/sun/security/tools/jarsigner/warnings/Test.java index ed2eec105c2..fcd49f812e3 100644 --- a/test/jdk/sun/security/tools/jarsigner/warnings/Test.java +++ b/test/jdk/sun/security/tools/jarsigner/warnings/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,12 +21,13 @@ * questions. */ -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; /** * Base class. @@ -259,7 +260,9 @@ public abstract class Test { cmd.add(tool); cmd.add("-J-Duser.language=en"); cmd.add("-J-Duser.country=US"); - cmd.addAll(Arrays.asList(args)); + cmd.addAll(Arrays.asList(args).stream().filter(arg -> { + return arg != null && !arg.isEmpty(); + }).collect(Collectors.toList())); return ProcessTools.executeCommand(cmd.toArray(new String[cmd.size()])); } } diff --git a/test/jdk/vm/JniInvocationTest.java b/test/jdk/tools/launcher/JniInvocationTest.java similarity index 100% rename from test/jdk/vm/JniInvocationTest.java rename to test/jdk/tools/launcher/JniInvocationTest.java diff --git a/test/jdk/tools/launcher/Test7029048.java b/test/jdk/tools/launcher/Test7029048.java index c87d9d00b24..5cccebf5a4a 100644 --- a/test/jdk/tools/launcher/Test7029048.java +++ b/test/jdk/tools/launcher/Test7029048.java @@ -23,7 +23,7 @@ /** * @test - * @bug 7029048 8217340 + * @bug 7029048 8217340 8217216 * @summary Ensure that the launcher defends against user settings of the * LD_LIBRARY_PATH environment variable on Unixes * @library /test/lib @@ -89,6 +89,29 @@ public class Test7029048 extends TestHelper { } static void analyze(TestResult tr, int nLLPComponents, String caseID) { + if (isSolaris) { + String envValue = getValue("LD_LIBRARY_PATH_64", tr.testOutput); + /* + * the envValue can never be null, since the test code should always + * print a "null" string. + */ + if (envValue == null) { + throw new RuntimeException("NPE, likely a program crash ??"); + } + boolean noLLP64 = envValue.equals("null"); + if (nLLPComponents == 0 && noLLP64) { + System.out.println("FAIL: test7029048, " + caseID); + System.out.println(" Missing LD_LIBRARY_PATH_64"); + errors++; + return; + } else if (nLLPComponents > 3 && !noLLP64) { + System.out.println("FAIL: test7029048, " + caseID); + System.out.println(" Unexpected LD_LIBRARY_PATH_64: " + envValue); + errors++; + return; + } + } + String envValue = getValue(LD_LIBRARY_PATH, tr.testOutput); /* * the envValue can never be null, since the test code should always @@ -202,8 +225,8 @@ public class Test7029048 extends TestHelper { env.clear(); env.put(LD_LIBRARY_PATH_64, dstServerDir.getAbsolutePath()); run(env, - v.value, // Do not add one, since we didn't set - // LD_LIBRARY_PATH here + // LD_LIBRARY_PATH_64 is copied into LD_LIBRARY_PATH for LIBJVM case + v.value == 0 ? 0 : v.value + 1, "Case 3: " + desc); } } diff --git a/test/jdk/vm/exeJniInvocationTest.c b/test/jdk/tools/launcher/exeJniInvocationTest.c similarity index 95% rename from test/jdk/vm/exeJniInvocationTest.c rename to test/jdk/tools/launcher/exeJniInvocationTest.c index 9ae1a092ca3..d49a7e054c2 100644 --- a/test/jdk/vm/exeJniInvocationTest.c +++ b/test/jdk/tools/launcher/exeJniInvocationTest.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java b/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java index 31bb1d75631..03d98f757cc 100644 --- a/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java +++ b/test/langtools/jdk/javadoc/doclet/InheritDocForUserTags/DocTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,8 @@ * @run main DocTest */ +import javadoc.tester.JavadocTester; + /** * DocTest documentation. * @@ -39,8 +41,6 @@ * @implSpec DocTest implementation spec. * @implNote DocTest implementation note. */ -import javadoc.tester.JavadocTester; - public class DocTest extends JavadocTester { public static void main(String... args) throws Exception { DocTest tester = new DocTest(); @@ -51,6 +51,7 @@ public class DocTest extends JavadocTester { public void test() { javadoc("-verbose", "-d", "DocTest", + "-sourcepath", System.getProperty("test.src.path"), "-tag", "apiNote:optcm:API Note", "-tag", "implSpec:optcm:Implementation Requirements:", "-tag", "implNote:optcm:Implementation Note:", diff --git a/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java b/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java index c08b6489f59..ae749bd8589 100644 --- a/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java +++ b/test/langtools/jdk/javadoc/doclet/JavascriptWinTitle/JavascriptWinTitle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,13 +56,13 @@ public class JavascriptWinTitle extends JavadocTester { checkExit(Exit.OK); checkOutput("overview-summary.html", true, ""); checkOutput("index.html", true, - " allBodyClassesFound = new HashSet<>(); final Set allGeneratorsFound = new HashSet<>(); public void runTests() throws Exception { @@ -93,6 +94,7 @@ public class TestMetadata extends JavadocTester { } javadoc(args.toArray(new String[args.size()])); checkExit(Exit.OK); + checkBodyClasses(); checkMetadata(); // spot check the descriptions for declarations @@ -126,10 +128,91 @@ public class TestMetadata extends JavadocTester { failed("not found: " + notFound); } + checking ("all body classes"); + if (allBodyClassesFound.equals(allBodyClasses)) { + passed("all gbody classes found"); + } else { + Set notFound = new TreeSet<>(allBodyClasses); + notFound.removeAll(allBodyClassesFound); + failed("not found: " + notFound); + } + printSummary(); } final Pattern nl = Pattern.compile("[\\r\\n]+"); + final Pattern bodyPattern = Pattern.compile("]*class=\"([^\"]+)\""); + final Set allBodyClasses = Set.of( + "all-classes-frame", + "all-classes-index", + "all-packages-index", + "class-declaration", + "class-use", + "constants-summary", + "deprecated-list", + "doc-file", + "frames", + "help", + "index-redirect", + "module-declaration", + "module-frame", + "module-index", + "module-index-frame", + "module-package-index-frame", + "package-declaration", + "package-frame", + "package-index", + "package-index-frame", + "package-tree", + "package-use", + "serialized-form", + "single-index", + "source", + "split-index", + "tree" + ); + + void checkBodyClasses() throws IOException { + Path outputDirPath = outputDir.toPath(); + for (Path p : tb.findFiles(".html", outputDirPath)) { + checkBodyClass(outputDirPath.relativize(p)); + } + } + + void checkBodyClass(Path p) { + checking("Check body: " + p); + + List bodyLines = nl.splitAsStream(readOutputFile(p.toString())) + .filter(s -> s.contains(""); final Pattern generatorPattern = Pattern.compile("content=\"javadoc/([^\"]+)\">"); final Set allGenerators = Set.of( diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java b/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java index 864fbf5251f..f00b48f880b 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestIndirectExportsOpens.java @@ -193,10 +193,12 @@ public class TestIndirectExportsOpens extends JavadocTester { "
    \n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java index 264df25715b..d024487a6ce 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModuleServices.java @@ -173,7 +173,7 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", false, - "

    Services

    "); + "

    Services

    "); } @Test @@ -194,15 +194,17 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", true, - "

    Services

    "); + "

    Services

    "); checkOutput("m/module-summary.html", true, "
    \n
    " + typeString + " 
    FromPackages
    m
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -235,15 +237,17 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", true, - "

    Services

    "); + "

    Services

    "); checkOutput("m/module-summary.html", true, "
    \n
    Uses 
    TypeDescription
    A
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -276,7 +280,7 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", false, - "

    Services

    "); + "

    Services

    "); } @Test @@ -302,15 +306,17 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", true, - "

    Services

    "); + "

    Services

    "); checkOutput("m/module-summary.html", true, "
    \n
    Uses 
    TypeDescription
    A
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -346,15 +352,17 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", true, - "

    Services

    "); + "

    Services

    "); checkOutput("m/module-summary.html", true, "
    \n
    Provides 
    TypeDescription
    A
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -389,15 +397,17 @@ public class TestModuleServices extends JavadocTester { checkExit(Exit.OK); checkOutput("m/module-summary.html", true, - "

    Services

    "); + "

    Services

    "); checkOutput("m/module-summary.html", true, "
    \n
    Provides 
    TypeDescription
    A
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -408,10 +418,12 @@ public class TestModuleServices extends JavadocTester { "
    Provides 
    TypeDescription
    A
    ", "
    \n\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" + diff --git a/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java b/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java index e46f1c18401..97aaa563aa7 100644 --- a/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java +++ b/test/langtools/jdk/javadoc/doclet/testModules/TestModules.java @@ -623,18 +623,22 @@ public class TestModules extends JavadocTester { "
    \n" + "
    Uses 
    TypeDescription
    B
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); checkOutput("overview-summary.html", false, "
    \n" + "
    Modules 
    ModuleDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); } void checkOverviewSummaryPackages() { @@ -642,10 +646,12 @@ public class TestModules extends JavadocTester { "
    \n" + "
    Packages 
    PackageDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "", "
    Modules 
    ModuleDescription
    \n" + "
    \n" + "
    \n" @@ -659,10 +665,12 @@ public class TestModules extends JavadocTester { "
    \n" + "\n" + "\n" + + "n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "\n", "\n" + "
    \n" + "
    The overview summary page header.
    \n" @@ -678,18 +686,22 @@ public class TestModules extends JavadocTester { "
    \n" + "
    Packages 
    PackageDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); checkOutput("overview-summary.html", false, "
    \n" + "
    Modules 
    ModuleDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); } void checkHtml5OverviewSummaryPackages() { @@ -697,10 +709,12 @@ public class TestModules extends JavadocTester { "
    \n" + "
    Packages 
    PackageDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "", "
    Modules 
    ModuleDescription
    \n" + "
    \n" + "\n" @@ -717,10 +731,12 @@ public class TestModules extends JavadocTester { checkOutput("overview-summary.html", true, "
    \n\n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "", "\n" + "\n" + "\n" @@ -788,20 +804,26 @@ public class TestModules extends JavadocTester { + "
    With a test description for uses.
    \n\n" + "", "\n" + + "\n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "", "\n" + + "\n" + "\n" + "\n" + "\n" - + "", + + "\n" + + "", "\n" + + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); } void checkAggregatorModuleSummary() { @@ -978,18 +1000,21 @@ public class TestModules extends JavadocTester { + "", "
    \n
    Packages 
    PackageDescription
    Opens 
    PackageDescription
    Uses 
    TypeDescription
    Provides 
    TypeDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "", "
    \n
    Requires 
    ModifierModuleDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "", "
    \n
    Indirect Requires 
    ModifierModuleDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" @@ -1011,10 +1036,12 @@ public class TestModules extends JavadocTester { + "", "
    \n
    Indirect Opens 
    FromPackages 
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" @@ -1081,11 +1108,13 @@ public class TestModules extends JavadocTester { + " class=\"tableTab\" onclick=\"show(2);\">Opens"); checkOutput("moduleC/module-summary.html", found, "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" - + ""); + + "\n" + + ""); checkOutput("moduletags/module-summary.html", true, "\n" + ""); @@ -1261,7 +1290,7 @@ public class TestModules extends JavadocTester { + "
    This is a test description for the test.moduleFullName.
    \n" + ""); checkOutput("module-overview-frame.html", found, - "

    Modules

    \n" + "

    Modules

    \n" + "
      \n" + "
    • moduleB
    • \n" + "
    • test.moduleFullName
    • \n" @@ -1301,16 +1330,20 @@ public class TestModules extends JavadocTester { + " onclick=\"show(2);\">Class Summary\n", - "
    \n" + "\n" + + "\n" + "\n" + "\n" - + ""); + + "\n" + + "\n"); checkOutput("allpackages-index.html", true, "\n" + + "\n" + "\n" + "\n" + "\n" - + "\n"); + + "\n" + + ""); checkOutput("allclasses-index.html", found, "
    Opens 
    PackageDescription
    testpkgmdlB
    Exports 
    PackageExported To ModulesDescription
    testpkgmdltags 
    ClassDescription
    Package Summary 
    PackageDescription
    \n"); checkOutput("allpackages-index.html", found, diff --git a/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java b/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java index 737d5bfd1a1..2d931ef24c5 100644 --- a/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java +++ b/test/langtools/jdk/javadoc/doclet/testNavigation/TestNavigation.java @@ -144,7 +144,7 @@ public class TestNavigation extends JavadocTester { + ""); } - // Test to make sure that no extra padding for nav bar gets generated if -nonavbar is specified for HTML4. + // Test to make sure that no extra padding for nav bar gets generated if -nonavbar is specified. @Test public void test2(Path ignore) { javadoc("-d", "out-2", @@ -155,39 +155,6 @@ public class TestNavigation extends JavadocTester { checkExit(Exit.OK); checkSubNav(); - checkOutput("pkg/A.html", false, - "\n" - + "\n" - + "
     
    \n" - + "\n" - + ""); - - checkOutput("pkg/package-summary.html", false, - "\n" - + "\n" - + "
     
    \n" - + "\n" - + "
    "); - } - - // Test to make sure that no extra padding for nav bar gets generated if -nonavbar is specified for HTML5. - @Test - public void test3(Path ignore) { - javadoc("-d", "out-3", - "-html5", - "-nonavbar", - "--frames", - "-sourcepath", testSrc, - "pkg"); - checkExit(Exit.OK); - checkSubNav(); - checkOutput("pkg/A.html", false, "\n" + "
    \n" @@ -212,7 +179,7 @@ public class TestNavigation extends JavadocTester { } @Test - public void test4(Path base) throws IOException { + public void test3(Path base) throws IOException { Path src = base.resolve("src"); tb.writeJavaFiles(src, "package pkg1; public class A {\n" @@ -255,7 +222,7 @@ public class TestNavigation extends JavadocTester { "package pkg1; public interface InterfaceWithNoMembers {\n" + "}"); - javadoc("-d", "out-4", + javadoc("-d", "out-3", "-sourcepath", src.toString(), "pkg1"); checkExit(Exit.OK); diff --git a/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java b/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java index aaa9ee3e0dc..e3afa631541 100644 --- a/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java +++ b/test/langtools/jdk/javadoc/doclet/testNewLanguageFeatures/TestNewLanguageFeatures.java @@ -24,7 +24,7 @@ /* * @test * @bug 4789689 4905985 4927164 4827184 4993906 5004549 7025314 7010344 8025633 8026567 8162363 - * 8175200 8186332 8182765 8196202 8187288 8173730 + * 8175200 8186332 8182765 8196202 8187288 8173730 8215307 * @summary Run Javadoc on a set of source files that demonstrate new * language features. Check the output to ensure that the new * language features are properly documented. @@ -66,7 +66,7 @@ public class TestNewLanguageFeatures extends JavadocTester { void checkEnums() { checkOutput("pkg/Coin.html", true, // Make sure enum header is correct. - "Enum Coin", + "Enum Coin", // Make sure enum signature is correct. "
    public enum "
                     + "Coin\n"
    @@ -110,7 +110,7 @@ public class TestNewLanguageFeatures extends JavadocTester {
         void checkTypeParameters() {
             checkOutput("pkg/TypeParameters.html", true,
                     // Make sure the header is correct.
    -                "Class TypeParameters<E>",
    +                "Class TypeParameters<E>",
                     // Check class type parameters section.
                     "
    Type Parameters:
    \n" + "
    E - " @@ -426,11 +426,13 @@ public class TestNewLanguageFeatures extends JavadocTester { + "type Foo4 " + "\n" + + "
    \n" + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" diff --git a/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java b/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java index 572929f3f15..93b0e21fb7e 100644 --- a/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java +++ b/test/langtools/jdk/javadoc/doclet/testOptions/TestOptions.java @@ -193,10 +193,10 @@ public class TestOptions extends JavadocTester { "
    @Documented\npublic @interface "
                     + "AnnotationTypeField
    ", - "

    DEFAULT_NAME

    \n
    static final java.lang.String "
    +                "

    DEFAULT_NAME

    \n
    static final java.lang.String "
                     + ""
                     + "DEFAULT_NAME
    ", - "

    name

    \n
    java.lang.String name\n
    java.lang.String name
    "); checkOutput("src-html/linksource/AnnotationTypeField.html", true, diff --git a/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java b/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java index f9038e72bb2..4e73dfdca84 100644 --- a/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java +++ b/test/langtools/jdk/javadoc/doclet/testOrdering/TestOrdering.java @@ -551,107 +551,107 @@ public class TestOrdering extends JavadocTester { checkExit(Exit.OK); checkOrder("pkg5/AnnoFieldTest.html", - "

    Field Detail

    ", + "

    Field Detail

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

    Optional Element Summary

    ", + "

    Optional Element Summary

    ", "four", "one", "three", "two", - "

    Element Detail

    ", - "

    one

    ", - "

    two

    ", - "

    three

    ", - "

    four

    "); + "

    Element Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

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

    Required Element Summary

    ", + "

    Required Element Summary

    ", "four", "one", "three", "two", - "

    Element Detail

    ", - "

    one

    ", - "

    two

    ", - "

    three

    ", - "

    four

    "); + "

    Element Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

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

    Constructor Summary

    ", + "

    Constructor Summary

    ", "Constructor Detail", + "

    Constructor Detail

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

    Enum Constant Summary

    ", + "

    Enum Constant Summary

    ", "
    FOUR", "ONE", "THREE", "TWO", - "

    Enum Constant Detail

    ", - "

    ONE

    ", - "

    TWO

    ", - "

    THREE

    ", - "

    FOUR

    "); + "

    Enum Constant Detail

    ", + "

    ONE

    ", + "

    TWO

    ", + "

    THREE

    ", + "

    FOUR

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

    Field Summary

    ", + "

    Field Summary

    ", "four", "one", "three", "two", - "

    Field Detail

    ", - "

    one

    ", - "

    two

    ", - "

    three

    ", - "

    four

    "); + "

    Field Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

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

    Method Summary

    ", + "

    Method Summary

    ", "four", "one", "three", "two", - "

    Method Detail

    ", - "

    one

    ", - "

    two

    ", - "

    three

    ", - "

    four

    "); + "

    Method Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

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

    Method Summary

    ", + "

    Method Summary

    ", "four", "one", "three", "two", - "

    Method Detail

    ", - "

    one

    ", - "

    two

    ", - "

    three

    ", - "

    four

    "); + "

    Method Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

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

    Property Summary

    ", + "

    Property Summary

    ", "four", "one", "three", "two", - "

    Property Detail

    ", - "

    oneProperty

    ", - "

    twoProperty

    ", - "

    threeProperty

    ", - "

    fourProperty

    "); + "

    Property Detail

    ", + "

    oneProperty

    ", + "

    twoProperty

    ", + "

    threeProperty

    ", + "

    fourProperty

    "); } } diff --git a/test/langtools/jdk/javadoc/doclet/testOverriddenMethods/TestBadOverride.java b/test/langtools/jdk/javadoc/doclet/testOverriddenMethods/TestBadOverride.java index b46c2c3342b..d7c346bfa77 100644 --- a/test/langtools/jdk/javadoc/doclet/testOverriddenMethods/TestBadOverride.java +++ b/test/langtools/jdk/javadoc/doclet/testOverriddenMethods/TestBadOverride.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public class TestBadOverride extends JavadocTester { checkOutput("pkg4/Foo.html", true, "
  • \n" - + "

    toString

    \n" + + "

    toString

    \n" + "
    public void toString()
    \n" + "
    Why can't I do this ?
    \n" + "
  • "); diff --git a/test/langtools/jdk/javadoc/doclet/testPackagePage/TestPackagePage.java b/test/langtools/jdk/javadoc/doclet/testPackagePage/TestPackagePage.java index 9610d48b1d5..273e0b2e594 100644 --- a/test/langtools/jdk/javadoc/doclet/testPackagePage/TestPackagePage.java +++ b/test/langtools/jdk/javadoc/doclet/testPackagePage/TestPackagePage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -87,17 +87,21 @@ public class TestPackagePage extends JavadocTester { checkOutput("allclasses-index.html", true, "
    \n
    Modifier and TypeMethodDescription
    void
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + "\n"); + + "\n" + + "\n"); checkOutput("allpackages-index.html", true, "
    \n
    Class Summary 
    ClassDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" - + "\n"); + + "\n" + + "\n"); checkOutput("type-search-index.js", true, "{\"l\":\"All Classes\",\"url\":\"allclasses-index.html\"}"); checkOutput("package-search-index.js", true, diff --git a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java index aa39c9e8e0f..8a1a0f8bf64 100644 --- a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java +++ b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java @@ -717,6 +717,7 @@ public class TestSearch extends JavadocTester { + " id=\"t6\" class=\"tableTab\" onclick=\"show(32);\">Annotation Types Summary\n" + "
    \n" + "
    Package Summary 
    PackageDescription
    \n" + + "\n" + "\n" + "\n" + "\n" @@ -726,6 +727,7 @@ public class TestSearch extends JavadocTester { checkOutput("allpackages-index.html", true, "
    \n
    ClassDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" diff --git a/test/langtools/jdk/javadoc/doclet/testSerializedForm/TestSerializedForm.java b/test/langtools/jdk/javadoc/doclet/testSerializedForm/TestSerializedForm.java index 6ffbe096119..46499236cf7 100644 --- a/test/langtools/jdk/javadoc/doclet/testSerializedForm/TestSerializedForm.java +++ b/test/langtools/jdk/javadoc/doclet/testSerializedForm/TestSerializedForm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 4341304 4485668 4966728 8032066 8071982 8192933 + * @bug 4341304 4485668 4966728 8032066 8071982 8192933 8215307 * @summary Test that methods readResolve and writeReplace show * up in serialized-form.html the same way that readObject and writeObject do. * If the doclet includes readResolve and writeReplace in the serialized-form @@ -109,6 +109,8 @@ public class TestSerializedForm extends JavadocTester { testSrc("SerializedForm.java"), testSrc("ExternalizedForm.java"), "pkg1"); checkExit(Exit.OK); + showHeadings("serialized-form.html"); + checkOutput("serialized-form.html", true, "

    Class pkg1.NestedInnerClass.InnerClass.ProNestedInnerClass " @@ -130,15 +132,15 @@ public class TestSerializedForm extends JavadocTester { + "extends java.lang.Object implements Serializable

    "); checkOutput("serialized-form.html", true, - "

    Serialized Fields

    \n" + + "

    Serialized Fields

    \n" + "
      \n" + "
    • \n" + - "

      longs

      \n" + + "
      longs
      \n" + "
      Long[] longs
      \n" + "
      the longs
      \n" + "
    • \n" + "
    • \n" + - "

      name

      \n" + + "
      name
      \n" + "
      java.lang.String name
      \n" + "
      a test
      "); } diff --git a/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java b/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java index 828bff1ad51..4a03c499b5a 100644 --- a/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java +++ b/test/langtools/jdk/javadoc/doclet/testSummaryHeading/TestSummaryHeading.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,6 +51,6 @@ public class TestSummaryHeading extends JavadocTester { checkExit(Exit.OK); checkOutput("C.html", true, - "

      Method Summary

      "); + "

      Method Summary

      "); } } diff --git a/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java b/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java index 7c1f5da9a13..76d99202311 100644 --- a/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java +++ b/test/langtools/jdk/javadoc/doclet/testSummaryTag/TestSummaryTag.java @@ -86,7 +86,7 @@ public class TestSummaryTag extends JavadocTester { // make sure the second @summary's content is displayed correctly checkOutput("p1/A.html", true, "
    • \n" - + "

      m3

      \n" + + "

      m3

      \n" + "
      public void m3()
      \n" + "
      First sentence some text maybe second sentence.
      \n" + "
    • \n" diff --git a/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java b/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java index 551ea5c61f6..e14c348a679 100644 --- a/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java +++ b/test/langtools/jdk/javadoc/doclet/testSystemPropertyTaglet/TestSystemPropertyTaglet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,9 +76,9 @@ public class TestSystemPropertyTaglet extends JavadocTester { checkExit(Exit.OK); checkOrder("pkg/A.html", - "

      Class A

      ", + "

      Class A

      ", "test with user.name", - "

      Method Detail

      ", + "

      Method Detail

      ", "test with java.version"); checkOrder("index-all.html", diff --git a/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java b/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java index f0599ff5b23..ab8d839e7e9 100644 --- a/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java +++ b/test/langtools/jdk/javadoc/doclet/testUnnamedPackage/TestUnnamedPackage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,10 +69,12 @@ public class TestUnnamedPackage extends JavadocTester { checkOutput("allclasses-index.html", true, "
      \n
    Package Summary 
    PackageDescription
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" @@ -86,10 +88,12 @@ public class TestUnnamedPackage extends JavadocTester { checkOutput("allpackages-index.html", true, "
    \n
    Class Summary 
    ClassDescription
    C
    \n" + "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + + "\n" + "\n" + "\n" + "\n" diff --git a/test/langtools/jdk/javadoc/lib/javadoc/tester/A11yChecker.java b/test/langtools/jdk/javadoc/lib/javadoc/tester/A11yChecker.java index b505f233778..f0f936d14bc 100644 --- a/test/langtools/jdk/javadoc/lib/javadoc/tester/A11yChecker.java +++ b/test/langtools/jdk/javadoc/lib/javadoc/tester/A11yChecker.java @@ -36,7 +36,7 @@ public class A11yChecker extends HtmlChecker { private boolean html5; - private int currLevel; + private int currRank; private int headingErrors; private boolean inBody; @@ -86,6 +86,7 @@ public class A11yChecker extends HtmlChecker { switch (name) { case "body": inBody = true; + currRank = 0; break; case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": @@ -126,18 +127,18 @@ public class A11yChecker extends HtmlChecker { } private void checkHeading(String h) { - int level = Character.digit(h.charAt(1), 10); - if (level > currLevel + 1) { + int rank = Character.digit(h.charAt(1), 10); + if (rank > currRank + 1) { headingErrors++; StringBuilder sb = new StringBuilder(); String sep = ""; - for (int i = currLevel + 1; i < level; i++) { + for (int i = currRank + 1; i < rank; i++) { sb.append(sep).append("h").append(i); sep = ", "; } error(currFile, getLineNumber(), "missing headings: " + sb); } - currLevel = level; + currRank = rank; } @Override diff --git a/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java b/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java index c1b2868376d..0d5cf244def 100644 --- a/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java +++ b/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java @@ -96,7 +96,7 @@ import java.util.function.Function; * } * * // test methods... - * @Test + * {@literal @}Test * void test() { * javadoc(args); * checkExit(Exit.OK); @@ -232,7 +232,7 @@ public abstract class JavadocTester { private DirectoryCheck outputDirectoryCheck = DirectoryCheck.EMPTY; - private boolean automaticCheckAccessibility = false; + private boolean automaticCheckAccessibility = true; private boolean automaticCheckLinks = true; /** The current subtest number. Incremented when checking(...) is called. */ @@ -261,7 +261,7 @@ public abstract class JavadocTester { } /** - * Run all methods annotated with @Test, followed by printSummary. + * Runs all methods annotated with @Test, followed by printSummary. * Typically called on a tester object in main() * @param f a function which will be used to provide arguments to each * invoked method @@ -285,7 +285,7 @@ public abstract class JavadocTester { } /** - * Run javadoc. + * Runs javadoc. * The output directory used by this call and the final exit code * will be saved for later use. * To aid the reader, it is recommended that calls to this method @@ -391,7 +391,7 @@ public abstract class JavadocTester { } /** - * Set the kind of check for the initial contents of the output directory + * Sets the kind of check for the initial contents of the output directory * before javadoc is run. * The filter should return true for files that should not appear. * @param c the kind of check to perform @@ -401,7 +401,14 @@ public abstract class JavadocTester { } /** - * Set whether or not to perform an automatic call of checkLinks. + * Sets whether or not to perform an automatic call of checkAccessibility. + */ + public void setAutomaticCheckAccessibility(boolean b) { + automaticCheckAccessibility = b; + } + + /** + * Sets whether or not to perform an automatic call of checkLinks. */ public void setAutomaticCheckLinks(boolean b) { automaticCheckLinks = b; @@ -431,7 +438,7 @@ public abstract class JavadocTester { } /** - * Check the exit code of the most recent call of javadoc. + * Checks the exit code of the most recent call of javadoc. * * @param expected the exit code that is required for the test * to pass. @@ -446,7 +453,7 @@ public abstract class JavadocTester { } /** - * Check for content in (or not in) the generated output. + * Checks for content in (or not in) the generated output. * Within the search strings, the newline character \n * will be translated to the platform newline character sequence. * @param path a path within the most recent output directory @@ -465,7 +472,7 @@ public abstract class JavadocTester { } /** - * Check for content in (or not in) the generated output. + * Checks for content in (or not in) the generated output. * Within the search strings, the newline character \n * will be translated to the platform newline character sequence. * @param path a path within the most recent output directory, identifying @@ -487,7 +494,7 @@ public abstract class JavadocTester { } /** - * Check for content in (or not in) the one of the output streams written by + * Checks for content in (or not in) the one of the output streams written by * javadoc. Within the search strings, the newline character \n * will be translated to the platform newline character sequence. * @param output the output stream to check @@ -519,6 +526,11 @@ public abstract class JavadocTester { } } + /** + * Performs some structural accessibility checks on the files generated by the most + * recent run of javadoc. + * The checks can be run automatically by calling {@link #setAutomaticCheckAccessibility}. + */ public void checkAccessibility() { checking("Check accessibility"); A11yChecker c = new A11yChecker(out, this::readFile); @@ -536,6 +548,11 @@ public abstract class JavadocTester { } } + /** + * Checks all the links within the files generated by the most + * recent run of javadoc. + * The checks can be run automatically by calling {@link #setAutomaticCheckLinks}. + */ public void checkLinks() { checking("Check links"); LinkChecker c = new LinkChecker(out, this::readFile); @@ -554,7 +571,27 @@ public abstract class JavadocTester { } /** - * Get the content of the one of the output streams written by javadoc. + * Shows the heading structure for each of the specified files. + * The structure is is printed in plain text to the main output stream. + * No errors are reported (unless there is a problem reading a file) + * but missing headings are noted within the output. + * @params the files + */ + public void showHeadings(String... paths) { + ShowHeadings s = new ShowHeadings(out, this::readFile); + for (String p : paths) { + try { + File f = new File(outputDir, p); + s.checkFiles(List.of(f.toPath()), false, Collections.emptySet()); + } catch (IOException e) { + checking("Read file"); + failed("Error reading file: " + e); + } + } + } + + /** + * Gets the content of the one of the output streams written by javadoc. * @param output the name of the output stream * @return the content of the output stream */ @@ -563,7 +600,7 @@ public abstract class JavadocTester { } /** - * Get the content of the one of the output streams written by javadoc. + * Gets the content of the one of the output streams written by javadoc. * @param output the name of the output stream * @return the content of the output stream, as a line of lines */ @@ -573,7 +610,7 @@ public abstract class JavadocTester { } /** - * Check for files in (or not in) the generated output. + * Checks for files in (or not in) the generated output. * @param expectedFound true if all of the files are expected * to be found, or false if all of the files are expected to be * not found @@ -584,7 +621,7 @@ public abstract class JavadocTester { } /** - * Check for files in (or not in) the generated output. + * Checks for files in (or not in) the generated output. * @param expectedFound true if all of the files are expected * to be found, or false if all of the files are expected to be * not found @@ -605,7 +642,7 @@ public abstract class JavadocTester { } /** - * Check that a series of strings are found in order in a file in + * Checks that a series of strings are found in order in a file in * the generated output. * @param path the file to check * @param strings the strings whose order to check @@ -658,7 +695,7 @@ public abstract class JavadocTester { } /** - * Compare a set of files in each of two directories. + * Compares a set of files in each of two directories. * * @param baseDir1 the directory containing the first set of files * @param baseDir2 the directory containing the second set of files @@ -673,7 +710,7 @@ public abstract class JavadocTester { } /** - * A utility to copy a directory from one place to another. + * Copies a directory from one place to another. * * @param targetDir the directory to copy. * @param destDir the destination to copy the directory to. @@ -707,7 +744,7 @@ public abstract class JavadocTester { } /** - * Copy source file to destination file. + * Copies a file. * * @param destfile the destination file * @param srcfile the source file @@ -749,7 +786,7 @@ public abstract class JavadocTester { } /** - * Read the file and return it as a string. + * Reads the file and return it as a string. * * @param baseDir the directory in which to locate the file * @param fileName the name of the file to read @@ -825,7 +862,7 @@ public abstract class JavadocTester { } /** - * Print a summary of the test results. + * Prints a summary of the test results. */ protected void printSummary() { String javadocRuns = (javadocRunNum <= 1) ? "" @@ -845,7 +882,7 @@ public abstract class JavadocTester { } /** - * Search for the string in the given file and return true + * Searches for the string in the given file and return true * if the string was found. * * @param fileString the contents of the file to search through @@ -861,7 +898,7 @@ public abstract class JavadocTester { } /** - * Compare the two given files. + * Compares the two given files. * * @param baseDir1 the directory in which to locate the first file * @param baseDir2 the directory in which to locate the second file diff --git a/test/langtools/jdk/javadoc/lib/javadoc/tester/ShowHeadings.java b/test/langtools/jdk/javadoc/lib/javadoc/tester/ShowHeadings.java new file mode 100644 index 00000000000..c18186d06d3 --- /dev/null +++ b/test/langtools/jdk/javadoc/lib/javadoc/tester/ShowHeadings.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javadoc.tester; + +import java.io.PrintStream; +import java.nio.file.Path; +import java.util.Map; +import java.util.function.Function; + +public class ShowHeadings extends HtmlChecker { + + private int currLevel; + + private boolean copyContent; + + ShowHeadings(PrintStream out, Function fileReader) { + super(out, fileReader); + } + + @Override + public void report() { + } + + @Override + public void startFile(Path path) { + out.println("Headings: " + path); + currLevel = 0; + } + + @Override + public void endFile() { + } + + @Override + public void docType(String doctype) { + } + + @Override + public void startElement(String name, Map attrs, boolean selfClosing) { + switch (name) { + case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": + startHeading(name); + break; + } + } + + @Override + public void endElement(String name) { + switch (name) { + case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": + out.println(); + copyContent = false; + break; + } + + } + + private void startHeading(String h) { + int level = Character.digit(h.charAt(1), 10); + while (level > currLevel + 1) { + currLevel++; + out.println("* ".repeat(currLevel - 1) + "H" + currLevel + ": *** MISSING ***"); + } + currLevel = level; + out.print("* ".repeat(currLevel - 1) + "H" + currLevel + ": "); + copyContent = true; + } + + @Override + public void content(String s) { + if (copyContent) { + out.print(s.replace(" ", " ") + .replace("<", "<") + .replace(">", ">") + .replace("&", "&") + .replaceAll("\\s+", " ") + ); + } + } +} + diff --git a/test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadersTest.java b/test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadingsTest.java similarity index 78% rename from test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadersTest.java rename to test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadingsTest.java index a68ea01afa8..142a376a3a0 100644 --- a/test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadersTest.java +++ b/test/langtools/jdk/javadoc/tool/doclint/ImplicitHeadingsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,19 +24,23 @@ /* * @test * @bug 8006346 - * @summary doclint should make allowance for headers generated by standard doclet + * @summary doclint should make allowance for headings generated by standard doclet * @modules jdk.javadoc/jdk.javadoc.internal.tool */ import java.io.File; /** - *

    Header

    + *

    Class heading

    */ -public class ImplicitHeadersTest { +public class ImplicitHeadingsTest { + /** + *

    Method heading

    + * @param args command-line args + */ public static void main(String... args) { File testSrc = new File(System.getProperty("test.src")); - File testFile = new File(testSrc, ImplicitHeadersTest.class.getSimpleName() + ".java"); + File testFile = new File(testSrc, ImplicitHeadingsTest.class.getSimpleName() + ".java"); String[] javadocArgs = { "-d", "out", testFile.getPath() }; int rc = jdk.javadoc.internal.tool.Main.execute(javadocArgs); if (rc != 0) diff --git a/test/langtools/jdk/javadoc/tool/removeOldDoclet/OldDoclet.jasm b/test/langtools/jdk/javadoc/tool/removeOldDoclet/OldDoclet.jasm deleted file mode 100644 index 6f0f23ee922..00000000000 --- a/test/langtools/jdk/javadoc/tool/removeOldDoclet/OldDoclet.jasm +++ /dev/null @@ -1,28 +0,0 @@ - -super public class OldDoclet - extends com/sun/javadoc/Doclet - version 55:0 -{ - - -public Method "":"()V" - stack 1 locals 1 -{ - aload_0; - invokespecial Method com/sun/javadoc/Doclet."":"()V"; - return; - -} - -public static Method start:"(Lcom/sun/javadoc/RootDoc;)Z" - stack 2 locals 1 -{ - getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; - ldc String "OLD_DOCLET_MARKER"; - invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; - iconst_1; - ireturn; - -} - -} // end Class OldDoclet diff --git a/test/langtools/jdk/javadoc/tool/removeOldDoclet/RemoveOldDoclet.java b/test/langtools/jdk/javadoc/tool/removeOldDoclet/RemoveOldDoclet.java index 1d0da6886cc..c0ff69c528c 100644 --- a/test/langtools/jdk/javadoc/tool/removeOldDoclet/RemoveOldDoclet.java +++ b/test/langtools/jdk/javadoc/tool/removeOldDoclet/RemoveOldDoclet.java @@ -28,7 +28,6 @@ * @library /tools/lib ../../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool * @build javadoc.tester.* toolbox.ToolBox builder.ClassBuilder - * @compile OldDoclet.jasm * @run main RemoveOldDoclet */ @@ -44,6 +43,7 @@ import javadoc.tester.JavadocTester; public class RemoveOldDoclet extends JavadocTester { final ToolBox tb; + static final String Doclet_CLASS_NAME = TestDoclet.class.getName(); public static void main(String... args) throws Exception { RemoveOldDoclet tester = new RemoveOldDoclet(); @@ -55,7 +55,7 @@ public class RemoveOldDoclet extends JavadocTester { } @Test - public void testInvokeOldDoclet(Path base) throws Exception { + public void testInvalidDoclet(Path base) throws Exception { Path srcDir = base.resolve("src"); Path outDir = base.resolve("out"); @@ -64,14 +64,21 @@ public class RemoveOldDoclet extends JavadocTester { .write(srcDir); javadoc("-d", outDir.toString(), - "-doclet", "OldDoclet", + "-doclet", Doclet_CLASS_NAME, "-docletpath", System.getProperty("test.classes", "."), "-sourcepath", srcDir.toString(), "pkg"); checkExit(Exit.ERROR); checkOutput(Output.OUT, true, - "javadoc: error - Class OldDoclet is not a valid doclet.\n" - + "Note: As of JDK 13, the com.sun.javadoc API is no longer supported."); + "javadoc: error - Class " + Doclet_CLASS_NAME + " is not a valid doclet.\n" + + "Note: As of JDK 13, the com.sun.javadoc API is no longer supported."); + } + + static class TestDoclet { + public static boolean start() { + System.out.println("OLD_DOCLET_MARKER"); + return true; + } } } diff --git a/test/langtools/tools/doclint/AccessibilityTest.java b/test/langtools/tools/doclint/AccessibilityTest.java index 305c1543766..50bfabcd9b0 100644 --- a/test/langtools/tools/doclint/AccessibilityTest.java +++ b/test/langtools/tools/doclint/AccessibilityTest.java @@ -10,17 +10,37 @@ /** */ public class AccessibilityTest { + /** + *

    ...

    + */ + public class Bad_H1 { } + + /** + *

    ...

    + */ + public class Missing_H2 { } + + /** + *

    ...

    + *

    ...

    + */ + public class Missing_H3 { } /** *

    ...

    */ - public void missing_h1() { } + public void bad_h2() { } /** - *

    ...

    - *

    ...

    + *

    ...

    */ - public void missing_h2() { } + public void missing_h3() { } + + /** + *

    ...

    + *
    ...
    + */ + public void missing_h4() { } /** * diff --git a/test/langtools/tools/doclint/AccessibilityTest.out b/test/langtools/tools/doclint/AccessibilityTest.out index 20354af7982..94c7611232a 100644 --- a/test/langtools/tools/doclint/AccessibilityTest.out +++ b/test/langtools/tools/doclint/AccessibilityTest.out @@ -1,13 +1,25 @@ -AccessibilityTest.java:15: error: header used out of sequence:

    - *

    ...

    +AccessibilityTest.java:14: error: unexpected heading used:

    , compared to implicit preceding heading:

    + *

    ...

    ^ -AccessibilityTest.java:21: error: header used out of sequence:

    +AccessibilityTest.java:19: error: heading used out of sequence:

    , compared to implicit preceding heading:

    *

    ...

    ^ -AccessibilityTest.java:26: error: no "alt" attribute for image +AccessibilityTest.java:25: error: heading used out of sequence:

    , compared to previous heading:

    + *

    ...

    + ^ +AccessibilityTest.java:30: error: unexpected heading used:

    , compared to implicit preceding heading:

    + *

    ...

    + ^ +AccessibilityTest.java:40: error: unexpected heading used:

    , compared to implicit preceding heading:

    + *

    ...

    + ^ +AccessibilityTest.java:41: error: heading used out of sequence:
    , compared to previous heading:

    + *

    ...
    + ^ +AccessibilityTest.java:46: error: no "alt" attribute for image * ^ -AccessibilityTest.java:41: error: no summary or caption for table +AccessibilityTest.java:61: error: no summary or caption for table *
    Package Summary 
    PackageDescription
    <Unnamed>
    head
    data
    ^ -4 errors +8 errors diff --git a/test/langtools/tools/doclint/html/BlockTagsTest.java b/test/langtools/tools/doclint/html/BlockTagsTest.java index 66406673c38..4042dc49e00 100644 --- a/test/langtools/tools/doclint/html/BlockTagsTest.java +++ b/test/langtools/tools/doclint/html/BlockTagsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,7 @@ * @library .. * @modules jdk.compiler/com.sun.tools.doclint * @build DocLintTester - * @run main DocLintTester -Xmsgs BlockTagsTest.java + * @run main DocLintTester -Xmsgs:-accessibility BlockTagsTest.java */ /** */ diff --git a/test/langtools/tools/doclint/html/HtmlVersionTagsAttrsTest.java b/test/langtools/tools/doclint/html/HtmlVersionTagsAttrsTest.java index 2ae4ca91478..f65431cd81b 100644 --- a/test/langtools/tools/doclint/html/HtmlVersionTagsAttrsTest.java +++ b/test/langtools/tools/doclint/html/HtmlVersionTagsAttrsTest.java @@ -83,7 +83,7 @@ public class HtmlVersionTagsAttrsTest { * * imgTest *
    - *

    Topics

    + *

    Topics

    *

    Aria attribute test

    *

    Label test

    *
    @@ -98,8 +98,8 @@ public class HtmlVersionTagsAttrsTest { *

    Teletype text

    *
    *
    - *

    Section

    - *

    Another heading

    + *

    Section

    + *
    Another heading
    *
    * hgroup no longer supported in HTML5. *
    @@ -113,12 +113,12 @@ public class HtmlVersionTagsAttrsTest { /** *
    *

    Testing section tag

    - *

    Section

    + *

    Section

    * Section text. *
    *
    *

    Testing article tag

    - *

    Article

    + *
    Article
    * Article text. *
    *
    @@ -133,7 +133,7 @@ public class HtmlVersionTagsAttrsTest { * Main content * * *
      diff --git a/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.java b/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.java index 5ed12822649..efcc4eef11c 100644 --- a/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.java +++ b/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.java @@ -13,6 +13,6 @@ /** * valid * duplicate - *

      duplicate

      + *

      duplicate

      */ public class AnchorAlreadyDefined { } diff --git a/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.out b/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.out index 89075016b52..ec745ab16e6 100644 --- a/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.out +++ b/test/langtools/tools/doclint/tidy/AnchorAlreadyDefined.out @@ -2,6 +2,6 @@ AnchorAlreadyDefined.java:15: error: anchor already defined: "here" * duplicate ^ AnchorAlreadyDefined.java:16: error: anchor already defined: "here" - *

      duplicate

      + *

      duplicate

      ^ 2 errors diff --git a/test/langtools/tools/doclint/tidy/MissingTag.java b/test/langtools/tools/doclint/tidy/MissingTag.java index 48f3008093a..973de870900 100644 --- a/test/langtools/tools/doclint/tidy/MissingTag.java +++ b/test/langtools/tools/doclint/tidy/MissingTag.java @@ -13,6 +13,6 @@ /** *

      - *

      text

      + *

      text

      */ public class MissingTag { } diff --git a/test/langtools/tools/doclint/tidy/MissingTag.out b/test/langtools/tools/doclint/tidy/MissingTag.out index 8703fd1f347..2dc621836c5 100644 --- a/test/langtools/tools/doclint/tidy/MissingTag.out +++ b/test/langtools/tools/doclint/tidy/MissingTag.out @@ -2,6 +2,6 @@ MissingTag.java:15: error: unexpected end tag:

      *

      ^ MissingTag.java:16: error: end tag missing:
      - *

      text

      + *

      text

      ^ 2 errors diff --git a/test/langtools/tools/javac/doclint/ImplicitHeadersTest.java b/test/langtools/tools/javac/doclint/ImplicitHeadingsTest.java similarity index 73% rename from test/langtools/tools/javac/doclint/ImplicitHeadersTest.java rename to test/langtools/tools/javac/doclint/ImplicitHeadingsTest.java index e80b88c6195..4b4ce556b0b 100644 --- a/test/langtools/tools/javac/doclint/ImplicitHeadersTest.java +++ b/test/langtools/tools/javac/doclint/ImplicitHeadingsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,12 +24,17 @@ /* * @test * @bug 8006346 - * @summary doclint should make allowance for headers generated by standard doclet - * @compile -Xdoclint:all/public ImplicitHeadersTest.java + * @summary doclint should make allowance for headings generated by standard doclet + * @compile -Xdoclint:all/public ImplicitHeadingsTest.java */ /** - *

      Header

      + *

      Class heading

      */ -public class ImplicitHeadersTest { } +public class ImplicitHeadingsTest { + /** + *

      Method heading

      + */ + public void m() { } +} diff --git a/test/langtools/tools/javac/file/SymLinkArchiveTest.java b/test/langtools/tools/javac/file/SymLinkArchiveTest.java index 827ae8a22ee..2cd8d0381a4 100644 --- a/test/langtools/tools/javac/file/SymLinkArchiveTest.java +++ b/test/langtools/tools/javac/file/SymLinkArchiveTest.java @@ -33,6 +33,7 @@ * @run main SymLinkArchiveTest */ +import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -69,7 +70,13 @@ public class SymLinkArchiveTest extends TestRunner { tb.writeFile(javaFile, "class T extends p.B {}"); Path jar = base.resolve("lib.jar"); - Files.createSymbolicLink(jar, classpath.getFileName()); + try { + Files.createSymbolicLink(jar, classpath.getFileName()); + } catch (FileSystemException fse) { + System.err.println("warning: test passes vacuously, sym-link could not be created"); + System.err.println(fse.getMessage()); + return; + } Result result = new JavacTask(tb).files(javaFile).classpath(jar).run(Expect.FAIL); String output = result.getOutput(OutputKind.DIRECT); diff --git a/test/langtools/tools/javac/file/SymLinkShortNameTest.java b/test/langtools/tools/javac/file/SymLinkShortNameTest.java new file mode 100644 index 00000000000..9aa9b562d51 --- /dev/null +++ b/test/langtools/tools/javac/file/SymLinkShortNameTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2019, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8193277 + * @summary SimpleFileObject inconsistency between getName and getShortName + * @library /tools/lib + * @modules jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.jdeps/com.sun.tools.classfile + * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox + * @run main SymLinkShortNameTest + */ + +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import toolbox.JavacTask; +import toolbox.Task.Expect; +import toolbox.Task.OutputKind; +import toolbox.Task.Result; +import toolbox.TestRunner; +import toolbox.TestRunner.Test; +import toolbox.ToolBox; + +public class SymLinkShortNameTest extends TestRunner { + public static void main(String... args) throws Exception { + new SymLinkShortNameTest().runTests(m -> new Object[] {Paths.get(m.getName())}); + } + + private final ToolBox tb = new ToolBox(); + + public SymLinkShortNameTest() { + super(System.err); + } + + @Test + public void testJarSymlink(Path base) throws Exception { + Files.createDirectories(base); + Path b = base.resolve("B.java"); + tb.writeFile(b, "class B { int f() {} }"); + + Path a = base.resolve("A.java"); + try { + Files.createSymbolicLink(a, b.getFileName()); + } catch (FileSystemException fse) { + System.err.println("warning: test passes vacuously, sym-link could not be created"); + System.err.println(fse.getMessage()); + return; + } + + { + Result result = + new JavacTask(tb).options("-XDrawDiagnostics").files(a).run(Expect.FAIL); + String output = result.getOutput(OutputKind.DIRECT); + + String expected = "A.java:1:20: compiler.err.missing.ret.stmt"; + if (!output.contains(expected)) { + throw new AssertionError( + "expected output to contain: " + expected + "\nwas:\n" + output); + } + } + { + Result result = new JavacTask(tb).files(a).run(Expect.FAIL); + String output = result.getOutput(OutputKind.DIRECT); + + String expected = "A.java:1: error: missing return statement"; + if (!output.contains(expected)) { + throw new AssertionError( + "expected output to contain: " + expected + "\nwas:\n" + output); + } + } + } +} diff --git a/test/langtools/tools/javac/modules/PatchModulesTest.java b/test/langtools/tools/javac/modules/PatchModulesTest.java index 2640a881c96..61421602adc 100644 --- a/test/langtools/tools/javac/modules/PatchModulesTest.java +++ b/test/langtools/tools/javac/modules/PatchModulesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 8160489 + * @bug 8160489 8217868 * @summary tests for --patch-modules * @library /tools/lib * @modules @@ -192,5 +192,23 @@ public class PatchModulesTest extends ModuleTestBase { throw new AssertionError(); } } + + @Test + public void testPatchModuleSourcePathClash(Path base) throws Exception { + Path src = base.resolve("src"); + tb.writeJavaFiles(src, + "module m { uses test.Test; }", + "package test; public class Test { }"); + Path classes = base.resolve("classes"); + tb.createDirectories(classes); + + new toolbox.JavacTask(tb) + .options("--patch-module", "other=" + src.toString(), + "-sourcepath", src.toString()) + .outdir(classes) + .files(findJavaFiles(src.resolve("module-info.java"))) + .run() + .writeAll(); + } } diff --git a/test/langtools/tools/javac/processing/model/completionfailure/SymbolsDontCumulate.java b/test/langtools/tools/javac/processing/model/completionfailure/SymbolsDontCumulate.java index 8f2b91fc8e8..b6857f71a07 100644 --- a/test/langtools/tools/javac/processing/model/completionfailure/SymbolsDontCumulate.java +++ b/test/langtools/tools/javac/processing/model/completionfailure/SymbolsDontCumulate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,25 +24,31 @@ /* * @test * @bug 8209055 - * @summary Verify that speculative symbols are not unnecesarily retained in + * @summary Verify that speculative symbols are not unnecessarily retained in * the DeferredCompletionFailureHandler * @library /tools/javac/lib /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code:+open + * jdk.compiler/com.sun.tools.javac.main * @run main SymbolsDontCumulate */ import java.lang.reflect.Field; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; import javax.tools.JavaCompiler; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; -import toolbox.*; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.DeferredCompletionFailureHandler; +import toolbox.ToolBox; + public class SymbolsDontCumulate { ToolBox tb = new ToolBox(); @@ -65,7 +71,7 @@ public class SymbolsDontCumulate { DeferredCompletionFailureHandler h = DeferredCompletionFailureHandler.instance(((JavacTaskImpl) task).getContext()); Field class2Flip = h.userCodeHandler.getClass().getDeclaredField("class2Flip"); class2Flip.setAccessible(true); - int size = ((Map) class2Flip.get(h.userCodeHandler)).size(); + int size = ((Map) class2Flip.get(h.userCodeHandler)).size(); assertEquals(0, size); } } diff --git a/test/micro/org/openjdk/bench/java/lang/StringIndexOf.java b/test/micro/org/openjdk/bench/java/lang/StringIndexOf.java index 572484319db..57ced6d8e13 100644 --- a/test/micro/org/openjdk/bench/java/lang/StringIndexOf.java +++ b/test/micro/org/openjdk/bench/java/lang/StringIndexOf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,6 +46,12 @@ public class StringIndexOf { private String shortSub1; private String data2; private String shortSub2; + private String string16Short; + private String string16Medium; + private String string16Long; + private char searchChar; + private char searchChar16; + private String searchString16; @Setup public void setup() { @@ -58,9 +64,122 @@ public class StringIndexOf { shortSub1 = "1"; data2 = "00001001010100a10110101010010101110101001110110101010010101010010000010111010101010101010a100010010101110111010101101010100010010a100a0010101111111000010101010010101000010101010010101010101110a10010101010101010101010101010"; shortSub2 = "a"; + searchChar = 's'; + + string16Short = "scar\u01fe1"; + string16Medium = "capaapapapasdkajdlkajskldjaslkjdlkasjdsalksca1r\u01fescar"; + string16Long = "2937489745890797905764956790452976742965790437698498409583479067ngdcapaapapapasdkajdlkajskldjaslkjdlkasjdsalkja1sscar\u01fescar"; + searchChar16 = 0x1fe; + searchString16 = "\u01fe"; + } + + + /** IndexOf Micros Chars */ + @Benchmark + public int searchCharLongSuccess() { + return dataStringBig.indexOf(searchChar); + } + + @Benchmark + public int searchCharMediumSuccess() { + return searchStringBig.indexOf(searchChar); + } + + @Benchmark + public int searchCharShortSuccess() { + return searchString.indexOf(searchChar); + } + + @Benchmark + public int searchChar16LongSuccess() { + return string16Long.indexOf(searchChar16); + } + + @Benchmark + public int searchChar16MediumSuccess() { + return string16Medium.indexOf(searchChar16); + } + + @Benchmark + public int searchChar16ShortSuccess() { + return string16Short.indexOf(searchChar16); + } + + @Benchmark + public int searchChar16LongWithOffsetSuccess() { + return string16Long.indexOf(searchChar16, 3); + } + + @Benchmark + public int searchChar16MediumWithOffsetSuccess() { + return string16Medium.indexOf(searchChar16, 3); + } + + @Benchmark + public int searchChar16ShortWithOffsetSuccess() { + return string16Short.indexOf(searchChar16, 2); } /** IndexOf Micros Strings */ + @Benchmark + public int searchString16LongLatinSuccess() { + return string16Long.indexOf(shortSub1); + } + + @Benchmark + public int searchString16MediumLatinSuccess() { + return string16Medium.indexOf(shortSub1); + } + + @Benchmark + public int searchString16ShortLatinSuccess() { + return string16Long.indexOf(shortSub2); + } + + @Benchmark + public int searchString16LongWithOffsetLatinSuccess() { + return string16Long.indexOf(shortSub1, 3); + } + + @Benchmark + public int searchString16MediumWithOffsetLatinSuccess() { + return string16Medium.indexOf(shortSub1, 3); + } + + @Benchmark + public int searchString16ShortWithOffsetLatinSuccess() { + return string16Short.indexOf(shortSub2, 1); + } + + @Benchmark + public int searchString16LongWithOffsetSuccess() { + return string16Long.indexOf(searchString16, 3); + } + + @Benchmark + public int searchString16MediumWithOffsetSuccess() { + return string16Medium.indexOf(searchString16, 3); + } + + @Benchmark + public int searchString16ShortWithOffsetSuccess() { + return string16Short.indexOf(searchString16, 2); + } + + @Benchmark + public int searchString16LongSuccess() { + return string16Long.indexOf(searchString16); + } + + @Benchmark + public int searchString16MediumSuccess() { + return string16Medium.indexOf(searchString16); + } + + @Benchmark + public int searchString16ShortSuccess() { + return string16Short.indexOf(searchString16); + } /** * Benchmarks String.indexOf with a rather small String to search and a rather small String to search for. The diff --git a/test/micro/org/openjdk/bench/vm/compiler/FpMinMaxIntrinsics.java b/test/micro/org/openjdk/bench/vm/compiler/FpMinMaxIntrinsics.java new file mode 100644 index 00000000000..b1f8cc0fc03 --- /dev/null +++ b/test/micro/org/openjdk/bench/vm/compiler/FpMinMaxIntrinsics.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.vm.compiler; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.*; + +import java.util.concurrent.TimeUnit; +import java.util.Random; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +public class FpMinMaxIntrinsics { + private static final int COUNT = 1000; + + private double[] doubles = new double[COUNT]; + private float[] floats = new float[COUNT]; + + private int c1, c2, s1, s2; + + private Random r = new Random(); + + @Setup + public void init() { + c1 = s1 = step(); + c2 = COUNT - (s2 = step()); + + for (int i=0; i 0 ? c2 - s2 : COUNT - (s2 = step()); + } + + @Benchmark + public float fMinReduce() { + float result = Float.MAX_VALUE; + + for (int i=0; i