From a178ff354673336c6724d0def5957c23a1f4c387 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 30 Apr 2026 17:46:10 +0000 Subject: [PATCH 1/7] 8382471: Improve Resource Resolving Reviewed-by: rhalade, mschoene, jnimeh, mullan --- .../utils/resolver/ResourceResolverSpi.java | 25 +++++++++++++++++++ .../implementations/ResolverDirectHTTP.java | 14 ++++++++--- .../ResolverLocalFilesystem.java | 17 +++++++------ test/lib/jdk/test/lib/security/XMLUtils.java | 11 +++++++- 4 files changed, 55 insertions(+), 12 deletions(-) diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java index 357088262605..1e7bd76413c9 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java @@ -51,4 +51,29 @@ public abstract XMLSignatureInput engineResolveURI(ResourceResolverContext conte */ public abstract boolean engineCanResolveURI(ResourceResolverContext context); + /** + * Returns the scheme for a URI. + * + * @param uri the URI + * @return the scheme, or {@code null} if none + */ + protected static final String scheme(String uri) { + if (uri == null) { + return null; + } + char[] uriChars = uri.toCharArray(); + // Similar to java.net.URI::parse. Find ':' before any of '/', '?', + // or '#', and treat the characters before it as scheme. + for (int i = 0; i < uriChars.length; i++) { + if (uriChars[i] == '/' || uriChars[i] == '?' || uriChars[i] == '#') { + return null; + } + if (uriChars[i] == ':') { + // No validation on the output since we only care if it's + // empty or equal to specific values. + return uri.substring(0, i); + } + } + return null; + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index deda69e98b96..dafa851f3d0c 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -207,6 +207,8 @@ private URLConnection openConnection(URL url, ResourceResolverContext context) t */ @Override public boolean engineCanResolveURI(ResourceResolverContext context) { + LOG.debug("I was asked whether I can resolve {}", context.uriToResolve); + if (context.uriToResolve == null) { LOG.debug("quick fail, uri == null"); return false; @@ -217,11 +219,15 @@ public boolean engineCanResolveURI(ResourceResolverContext context) { return false; } - LOG.debug("I was asked whether I can resolve {}", context.uriToResolve); + String uriToResolveScheme = scheme(context.uriToResolve); - if (context.uriToResolve.startsWith("http:") || - context.uriToResolve.startsWith("https:") || - context.baseUri != null && (context.baseUri.startsWith("http:") || context.baseUri.startsWith("https:"))) { + if (uriToResolveScheme == null) { + String baseUriScheme = scheme(context.baseUri); + if ("http".equals(baseUriScheme) || "https".equals(baseUriScheme)) { + LOG.debug("I state that I can resolve {}", context.uriToResolve); + return true; + } + } else if (uriToResolveScheme.equals("http") || uriToResolveScheme.equals("https")) { LOG.debug("I state that I can resolve {}", context.uriToResolve); return true; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index d3970a3ea694..2a96866cf8be 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -72,20 +72,23 @@ public boolean engineCanResolveURI(ResourceResolverContext context) { return false; } - if (context.uriToResolve.isEmpty() || context.uriToResolve.charAt(0) == '#' || - context.uriToResolve.startsWith("http:") || context.uriToResolve.startsWith("https:")) { + if (context.uriToResolve.isEmpty() || context.uriToResolve.charAt(0) == '#') { return false; } - try { - LOG.debug("I was asked whether I can resolve {}", context.uriToResolve); + LOG.debug("I was asked whether I can resolve {}", context.uriToResolve); + + String uriToResolveScheme = scheme(context.uriToResolve); - if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) { + if (uriToResolveScheme == null) { + String baseUriScheme = scheme(context.baseUri); + if ("file".equals(baseUriScheme)) { LOG.debug("I state that I can resolve {}", context.uriToResolve); return true; } - } catch (Exception e) { - LOG.debug(e.getMessage(), e); + } else if (uriToResolveScheme.equals("file")) { + LOG.debug("I state that I can resolve {}", context.uriToResolve); + return true; } LOG.debug("But I can't"); diff --git a/test/lib/jdk/test/lib/security/XMLUtils.java b/test/lib/jdk/test/lib/security/XMLUtils.java index e70a30d9b3d2..62090c9c8619 100644 --- a/test/lib/jdk/test/lib/security/XMLUtils.java +++ b/test/lib/jdk/test/lib/security/XMLUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -187,6 +187,7 @@ public static Signer signer(PrivateKey privateKey) public static class Signer { + private String baseURI = null; final PrivateKey privateKey; // signer key, never null X509Certificate cert; // certificate, optional @@ -253,6 +254,11 @@ public Signer prop(String name, Object o) { return this; } + public Signer baseURI(String base) { + this.baseURI = base; + return this; + } + // Signs different sources // Signs an XML file in detached mode @@ -341,6 +347,9 @@ private DOMSignContext withProps(DOMSignContext ctxt) { for (var e : props.entrySet()) { ctxt.setProperty(e.getKey(), e.getValue()); } + if (baseURI != null) { + ctxt.setBaseURI(baseURI); + } return ctxt; } From d722a01ac90db0ada927f1e69365dce4d27132ad Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Fri, 12 Jun 2026 12:35:01 +0000 Subject: [PATCH 2/7] 8384708: Enhance HTTP Connections Co-authored-by: Michael McMahon Reviewed-by: rhalade, djelinski, aefimov, michaelm, vyazici --- .../classes/sun/net/www/http/HttpClient.java | 8 + .../www/protocol/http/HttpURLConnection.java | 16 +- .../HTTPSetAuthenticatorTest.java | 6 +- .../SetAuthenticator/HTTPTestServer.java | 487 +++++++++++------- 4 files changed, 315 insertions(+), 202 deletions(-) diff --git a/src/java.base/share/classes/sun/net/www/http/HttpClient.java b/src/java.base/share/classes/sun/net/www/http/HttpClient.java index ffab60e714e3..a67c43d3ce5f 100644 --- a/src/java.base/share/classes/sun/net/www/http/HttpClient.java +++ b/src/java.base/share/classes/sun/net/www/http/HttpClient.java @@ -27,6 +27,7 @@ import java.io.*; import java.net.*; +import java.net.Proxy.Type; import java.util.Locale; import java.util.Objects; import java.util.OptionalInt; @@ -182,6 +183,13 @@ int getKeepAliveTimeout() { return keepAliveTimeout; } + public Proxy getHttpProxy() { + if (proxy != null && proxy.type() == Type.HTTP) { + return proxy; + } + return null; + } + static String normalizeCBT(String s) { if (s == null || s.equals("never")) { return "never"; diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 45e641f11eee..7b7506420f72 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -366,6 +366,9 @@ private static Set schemesListToSet(String list) { private boolean tryTransparentNTLMProxy = true; private boolean useProxyResponseCode = false; + // used when redirecting to compare current and previous proxies + private Proxy lastProxy; + /* Used by Windows specific code */ private Object authObj; @@ -1376,7 +1379,6 @@ private InputStream getInputStream0() throws IOException { // If the user has set either of these headers then do not remove them isUserServerAuth = requests.getKey("Authorization") != -1; isUserProxyAuth = requests.getKey("Proxy-Authorization") != -1; - try { do { if (!checkReuseConnection()) @@ -1386,6 +1388,14 @@ private InputStream getInputStream0() throws IOException { return cachedInputStream; } + // we may need to remove proxy-authorization + Proxy p = http.getHttpProxy(); + // if we're not using a proxy or if the proxy to be used is not + // the same as the originally set one, then remove it + if (p == null || (lastProxy != null && !lastProxy.equals(p))) { + requests.remove("Proxy-Authorization"); + lastProxy = null; + } /* REMIND: This exists to fix the HttpsURLConnection subclass. * Hotjava needs to run on JDK1.1FCS. Do proper fix once a * proper solution for SSL can be found. @@ -1416,7 +1426,7 @@ private InputStream getInputStream0() throws IOException { disconnectInternal(); throw new IOException ("Invalid Http response"); } - if (respCode == HTTP_PROXY_AUTH) { + if (respCode == HTTP_PROXY_AUTH && tunnelState() != TunnelState.TUNNELING) { if (streaming()) { disconnectInternal(); throw new HttpRetryException ( @@ -1999,6 +2009,7 @@ private void doTunneling0() throws IOException { if (respCode == HTTP_OK) { setTunnelState(TunnelState.TUNNELING); + savedRequests.remove("Proxy-Authorization"); break; } // we don't know how to deal with other response code @@ -2552,6 +2563,7 @@ private boolean followRedirect0(String loc, int stat, URL locUrl) { assert isLockHeldByCurrentThread(); + lastProxy = http.getHttpProxy(); disconnectInternal(); if (streaming()) { throw new HttpRetryException (RETRY_MSG3, stat, loc); diff --git a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java index 4d6a74e760b0..723d203c93ad 100644 --- a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java +++ b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * 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,13 +68,11 @@ * @run main/othervm -Dhttp.auth.digest.reEnabledAlgorithms=MD5 HTTPSetAuthenticatorTest DIGEST PROXY305 * @run main/othervm -Dhttp.auth.digest.reEnabledAlgorithms=MD5 HTTPSetAuthenticatorTest DIGEST SERVER307 * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER - * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY + * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes= HTTPSetAuthenticatorTest BASIC PROXY * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY305 * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER307 * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER307 - * - * @author danielfuchs */ public class HTTPSetAuthenticatorTest extends HTTPTest { diff --git a/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java b/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java index aa158c3b6678..6ceb281e364c 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, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * 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,6 +53,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; +import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Random; @@ -60,6 +61,7 @@ import java.util.stream.Collectors; import javax.net.ssl.SSLContext; import sun.net.www.HeaderParser; +import sun.net.www.MessageHeader; /** * A simple HTTP server that supports Digest authentication. @@ -344,10 +346,11 @@ public static HTTPTestServer createServer(HttpProtocolType protocol, Objects.requireNonNull(auth); HttpServer impl = createHttpServer(protocol); + AuthResponder authResponder = createAuthResponder(schemeType, auth, authType, algorithm); final HTTPTestServer server = new HTTPTestServer(impl, null, delegate); final HttpHandler hh = server.createHandler(schemeType, auth, authType); HttpContext ctxt = impl.createContext(path, hh); - server.configureAuthentication(ctxt, schemeType, auth, authType, algorithm); + server.configureAuthentication(ctxt, schemeType, authResponder, authType); impl.start(); return server; } @@ -363,12 +366,19 @@ public static HTTPTestServer createProxy(HttpProtocolType protocol, Objects.requireNonNull(auth); HttpServer impl = createHttpServer(protocol); + AuthResponder authResponder = createAuthResponder(schemeType, auth, authType, null); final HTTPTestServer server = protocol == HttpProtocolType.HTTPS - ? new HttpsProxyTunnel(impl, null, delegate) + ? new HttpsProxyTunnel(impl, null, delegate, authResponder) : new HTTPTestServer(impl, null, delegate); final HttpHandler hh = server.createHandler(schemeType, auth, authType); HttpContext ctxt = impl.createContext(path, hh); - server.configureAuthentication(ctxt, schemeType, auth, authType, null); + if (protocol == HttpProtocolType.HTTPS) { + server.configureAuthentication(ctxt, HttpSchemeType.NONE, + new NoAuthResponder(auth, HttpAuthType.SERVER), + HttpAuthType.SERVER); + } else { + server.configureAuthentication(ctxt, schemeType, authResponder, authType); + } impl.start(); return server; @@ -441,16 +451,16 @@ private HttpHandler createHandler(HttpSchemeType schemeType, private void configureAuthentication(HttpContext ctxt, HttpSchemeType schemeType, - HttpTestAuthenticator auth, - HttpAuthType authType, String algorithm) { + AuthResponder authResponder, + HttpAuthType authType) { switch(schemeType) { case DIGEST: // DIGEST authentication is handled by the handler. - ctxt.getFilters().add(new HttpDigestFilter(auth, authType, algorithm)); + ctxt.getFilters().add(new HttpDigestFilter(authResponder)); break; case BASIC: // BASIC authentication is handled by the filter. - ctxt.getFilters().add(new HttpBasicFilter(auth, authType)); + ctxt.getFilters().add(new HttpBasicFilter(authResponder)); break; case BASICSERVER: switch(authType) { @@ -458,14 +468,14 @@ private void configureAuthentication(HttpContext ctxt, // HttpServer can't support Proxy-type authentication // => we do as if BASIC had been specified, and we will // handle authentication in the handler. - ctxt.getFilters().add(new HttpBasicFilter(auth, authType)); + ctxt.getFilters().add(new HttpBasicFilter(authResponder)); break; case SERVER: case SERVER307: // Basic authentication is handled by HttpServer // directly => the filter should not perform // authentication again. - setContextAuthenticator(ctxt, auth); - ctxt.getFilters().add(new HttpNoAuthFilter(authType)); + setContextAuthenticator(ctxt, authResponder.authenticator); + ctxt.getFilters().add(new HttpNoAuthFilter(authResponder)); break; default: throw new InternalError("Invalid combination scheme=" @@ -473,7 +483,7 @@ private void configureAuthentication(HttpContext ctxt, } case NONE: // No authentication at all. - ctxt.getFilters().add(new HttpNoAuthFilter(authType)); + ctxt.getFilters().add(new HttpNoAuthFilter(authResponder)); break; default: throw new InternalError("No such scheme: " + schemeType); @@ -485,38 +495,230 @@ private HttpHandler create300Handler(URL proxyURL, return new Http3xxHandler(proxyURL, type, code300); } - // Abstract HTTP filter class. - private abstract static class AbstractHttpFilter extends Filter { - + private static abstract class AuthResponder { final HttpAuthType authType; + final HttpTestAuthenticator authenticator; final String type; - public AbstractHttpFilter(HttpAuthType authType, String type) { + + AuthResponder(HttpTestAuthenticator authenticator, + HttpAuthType authType, + String scheme) { + this.authenticator = authenticator; this.authType = authType; - this.type = type; + this.type = authType == HttpAuthType.PROXY + ? scheme + " Proxy" + : scheme + " Server"; } - String getLocation() { - return "Location"; - } - String getAuthenticate() { + final String authenticateHeader() { return authType == HttpAuthType.PROXY - ? "Proxy-Authenticate" : "WWW-Authenticate"; + ? "Proxy-Authenticate" + : "WWW-Authenticate"; } - String getAuthorization() { + final String authorizationHeader() { return authType == HttpAuthType.PROXY - ? "Proxy-Authorization" : "Authorization"; + ? "Proxy-Authorization" + : "Authorization"; } - int getUnauthorizedCode() { + int unauthorizedCode() { return authType == HttpAuthType.PROXY ? HttpURLConnection.HTTP_PROXY_AUTH : HttpURLConnection.HTTP_UNAUTHORIZED; } - String getKeepAlive() { - return "keep-alive"; - } - String getConnection() { + String unauthorizedString() { return authType == HttpAuthType.PROXY - ? "Proxy-Connection" : "Connection"; + ? "Proxy Authentication Required" + : "Unauthorized"; + } + String type() { return type;} + abstract String generateAuthenticateChallenge(); + abstract boolean isAuthentified(String method, Iterator authValues); + } + + private static final class BasicAuthResponder extends AuthResponder { + BasicAuthResponder(HttpTestAuthenticator authenticator, HttpAuthType authType) { + super(authenticator, authType, "Basic"); + } + + @Override + String generateAuthenticateChallenge() { + return "Basic realm=\"" + authenticator.getRealm() + "\""; + } + + @Override + boolean isAuthentified(String method, Iterator authValues) { + while(authValues.hasNext()) { + String a = authValues.next(); + System.out.println(type + ": processing " + a); + int sp = a.indexOf(' '); + if (sp < 0) return false; + String scheme = a.substring(0, sp); + if (!"Basic".equalsIgnoreCase(scheme)) { + System.out.println(type + ": Unsupported scheme '" + + scheme +"'"); + return false; + } + if (a.length() <= sp+1) { + System.out.println(type + ": value too short for '" + + scheme +"'"); + return false; + } + a = a.substring(sp+1); + return validate(a); + } + return false; + } + + boolean validate(String a) { + byte[] b = Base64.getDecoder().decode(a); + String userpass = new String (b); + int colon = userpass.indexOf (':'); + String uname = userpass.substring (0, colon); + String pass = userpass.substring (colon+1); + return authenticator.getUserName().equals(uname) && + new String(authenticator.getPassword(uname)).equals(pass); + } + + } + + private static final class DigestAuthResponder extends AuthResponder { + // This is a very basic DIGEST - used only for the purpose of testing + // the client implementation. Therefore we can get away with never + // updating the server nonce as it makes the implementation of the + // server side digest simpler. + private final byte[] nonce; + private final String ns; + private final String algorithm; + DigestAuthResponder(HttpTestAuthenticator authenticator, HttpAuthType authType, String algorithm) { + super(authenticator, authType, "Digest"); + nonce = new byte[16]; + new Random(Instant.now().toEpochMilli()).nextBytes(nonce); + ns = new BigInteger(1, nonce).toString(16); + this.algorithm = (algorithm == null) ? "MD5" : algorithm; + } + + @Override + String generateAuthenticateChallenge() { + return "Digest realm=\"" + authenticator.getRealm() + "\"," + + "\r\n qop=\"auth\", " + "algorithm=\"" + algorithm + "\", " + + "\r\n nonce=\"" + ns +"\""; + } + + @Override + boolean isAuthentified(String method, Iterator authValues) { + while(authValues.hasNext()) { + String a = authValues.next(); + System.out.println(type + ": processing " + a); + int sp = a.indexOf(' '); + if (sp < 0) return false; + String scheme = a.substring(0, sp); + if (!"Digest".equalsIgnoreCase(scheme)) { + System.out.println(type + ": Unsupported scheme '" + scheme +"'"); + return false; + } + if (a.length() <= sp+1) { + System.out.println(type + ": value too short for '" + scheme +"'"); + return false; + } + a = a.substring(sp+1); + DigestResponse dgr = DigestResponse.create(a); + return validate(method, dgr); + } + return false; + } + + boolean validate(String reqMethod, DigestResponse dg) { + if (!this.algorithm.equalsIgnoreCase(dg.getAlgorithm("MD5"))) { + System.out.println(type + ": Unsupported algorithm " + + dg.algorithm); + return false; + } + if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) { + System.out.println(type + ": Unsupported qop " + + dg.qop); + return false; + } + try { + if (!dg.nonce.equals(ns)) { + System.out.println(type + ": bad nonce returned by client: " + + nonce + " expected " + ns); + return false; + } + if (dg.response == null) { + System.out.println(type + ": missing digest response."); + return false; + } + char[] pa = authenticator.getPassword(dg.username); + return verify(reqMethod, dg, pa); + } catch(IllegalArgumentException | SecurityException + | NoSuchAlgorithmException e) { + System.out.println(type + ": " + e.getMessage()); + return false; + } + } + + boolean verify(String reqMethod, DigestResponse dg, char[] pw) + throws NoSuchAlgorithmException { + String response = DigestResponse.computeDigest(true, reqMethod, pw, algorithm, dg); + if (!dg.response.equals(response)) { + System.out.println(type + ": bad response returned by client: " + + dg.response + " expected " + response); + return false; + } else { + System.out.println(type + ": verified response " + response); + } + return true; + } + + } + + private static final class NoAuthResponder extends AuthResponder { + NoAuthResponder(HttpTestAuthenticator authenticator, HttpAuthType authType) { + super(authenticator, authType, "NoAuth"); + } + + @Override + String generateAuthenticateChallenge() { + throw new InternalError("Should not reach here"); + } + + @Override + boolean isAuthentified(String method, Iterator authValues) { + return true; + } + } + + private static AuthResponder createAuthResponder(HttpSchemeType schemeType, + HttpTestAuthenticator authenticator, + HttpAuthType authType, + String algorithm) { + switch (schemeType) { + case BASIC, BASICSERVER: return new BasicAuthResponder(authenticator, authType); + case DIGEST: return new DigestAuthResponder(authenticator, authType, algorithm); + case NONE: return new NoAuthResponder(authenticator, authType); + default: throw new IllegalArgumentException( + "Unknown authentication scheme: " + schemeType); + } + } + + // Abstract HTTP filter class. + private abstract static class AbstractHttpFilter extends Filter { + + final AuthResponder authResponder; + final String type; + public AbstractHttpFilter(AuthResponder authResponder) { + this.authResponder = authResponder; + this.type = authResponder.type(); + } + + final String getAuthenticate() { + return authResponder.authenticateHeader(); + } + final String getAuthorization() { + return authResponder.authorizationHeader(); + } + final int getUnauthorizedCode() { + return authResponder.unauthorizedCode(); } protected abstract boolean isAuthentified(HttpExchange he) throws IOException; protected abstract void requestAuthentication(HttpExchange he) throws IOException; @@ -694,11 +896,10 @@ public static DigestResponse create(String raw) { } - private class HttpNoAuthFilter extends AbstractHttpFilter { + private static final class HttpNoAuthFilter extends AbstractHttpFilter { - public HttpNoAuthFilter(HttpAuthType authType) { - super(authType, authType == HttpAuthType.SERVER - ? "NoAuth Server" : "NoAuth Proxy"); + public HttpNoAuthFilter(AuthResponder authResponder) { + super(authResponder); } @Override @@ -720,19 +921,15 @@ public String description() { // An HTTP Filter that performs Basic authentication private class HttpBasicFilter extends AbstractHttpFilter { - - private final HttpTestAuthenticator auth; - public HttpBasicFilter(HttpTestAuthenticator auth, HttpAuthType authType) { - super(authType, authType == HttpAuthType.SERVER - ? "Basic Server" : "Basic Proxy"); - this.auth = auth; + public HttpBasicFilter(AuthResponder authResponder) { + super(authResponder); } @Override protected void requestAuthentication(HttpExchange he) throws IOException { - he.getResponseHeaders().add(getAuthenticate(), - "Basic realm=\"" + auth.getRealm() + "\""); + String challenge = authResponder.generateAuthenticateChallenge(); + he.getResponseHeaders().add(getAuthenticate(), challenge); System.out.println(type + ": Requesting Basic Authentication " + he.getResponseHeaders().getFirst(getAuthenticate())); } @@ -742,39 +939,12 @@ protected boolean isAuthentified(HttpExchange he) { if (he.getRequestHeaders().containsKey(getAuthorization())) { List authorization = he.getRequestHeaders().get(getAuthorization()); - for (String a : authorization) { - System.out.println(type + ": processing " + a); - int sp = a.indexOf(' '); - if (sp < 0) return false; - String scheme = a.substring(0, sp); - if (!"Basic".equalsIgnoreCase(scheme)) { - System.out.println(type + ": Unsupported scheme '" - + scheme +"'"); - return false; - } - if (a.length() <= sp+1) { - System.out.println(type + ": value too short for '" - + scheme +"'"); - return false; - } - a = a.substring(sp+1); - return validate(a); - } - return false; + return authResponder.isAuthentified(he.getRequestMethod(), + authorization.iterator()); } return false; } - boolean validate(String a) { - byte[] b = Base64.getDecoder().decode(a); - String userpass = new String (b); - int colon = userpass.indexOf (':'); - String uname = userpass.substring (0, colon); - String pass = userpass.substring (colon+1); - return auth.getUserName().equals(uname) && - new String(auth.getPassword(uname)).equals(pass); - } - @Override public String description() { return "Filter for " + type; @@ -786,31 +956,14 @@ public String description() { // An HTTP Filter that performs Digest authentication private class HttpDigestFilter extends AbstractHttpFilter { - // This is a very basic DIGEST - used only for the purpose of testing - // the client implementation. Therefore we can get away with never - // updating the server nonce as it makes the implementation of the - // server side digest simpler. - private final HttpTestAuthenticator auth; - private final byte[] nonce; - private final String ns; - private final String algorithm; - public HttpDigestFilter(HttpTestAuthenticator auth, HttpAuthType authType, String algorithm) { - super(authType, authType == HttpAuthType.SERVER - ? "Digest Server" : "Digest Proxy"); - this.auth = auth; - nonce = new byte[16]; - new Random(Instant.now().toEpochMilli()).nextBytes(nonce); - ns = new BigInteger(1, nonce).toString(16); - this.algorithm = (algorithm == null) ? "MD5" : algorithm; + public HttpDigestFilter(AuthResponder authResponder) { + super(authResponder); } @Override protected void requestAuthentication(HttpExchange he) throws IOException { - he.getResponseHeaders().add(getAuthenticate(), - "Digest realm=\"" + auth.getRealm() + "\"," - + "\r\n qop=\"auth\", " + "algorithm=\"" + algorithm + "\", " - + "\r\n nonce=\"" + ns +"\""); + he.getResponseHeaders().add(getAuthenticate(), authResponder.generateAuthenticateChallenge()); System.out.println(type + ": Requesting Digest Authentication " + he.getResponseHeaders().getFirst(getAuthenticate())); } @@ -819,71 +972,11 @@ protected void requestAuthentication(HttpExchange he) protected boolean isAuthentified(HttpExchange he) { if (he.getRequestHeaders().containsKey(getAuthorization())) { List authorization = he.getRequestHeaders().get(getAuthorization()); - for (String a : authorization) { - System.out.println(type + ": processing " + a); - int sp = a.indexOf(' '); - if (sp < 0) return false; - String scheme = a.substring(0, sp); - if (!"Digest".equalsIgnoreCase(scheme)) { - System.out.println(type + ": Unsupported scheme '" + scheme +"'"); - return false; - } - if (a.length() <= sp+1) { - System.out.println(type + ": value too short for '" + scheme +"'"); - return false; - } - a = a.substring(sp+1); - DigestResponse dgr = DigestResponse.create(a); - return validate(he.getRequestMethod(), dgr); - } - return false; + return authResponder.isAuthentified(he.getRequestMethod(), authorization.iterator()); } return false; } - boolean validate(String reqMethod, DigestResponse dg) { - if (!this.algorithm.equalsIgnoreCase(dg.getAlgorithm("MD5"))) { - System.out.println(type + ": Unsupported algorithm " - + dg.algorithm); - return false; - } - if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) { - System.out.println(type + ": Unsupported qop " - + dg.qop); - return false; - } - try { - if (!dg.nonce.equals(ns)) { - System.out.println(type + ": bad nonce returned by client: " - + nonce + " expected " + ns); - return false; - } - if (dg.response == null) { - System.out.println(type + ": missing digest response."); - return false; - } - char[] pa = auth.getPassword(dg.username); - return verify(reqMethod, dg, pa); - } catch(IllegalArgumentException | SecurityException - | NoSuchAlgorithmException e) { - System.out.println(type + ": " + e.getMessage()); - return false; - } - } - - boolean verify(String reqMethod, DigestResponse dg, char[] pw) - throws NoSuchAlgorithmException { - String response = DigestResponse.computeDigest(true, reqMethod, pw, algorithm, dg); - if (!dg.response.equals(response)) { - System.out.println(type + ": bad response returned by client: " - + dg.response + " expected " + response); - return false; - } else { - System.out.println(type + ": verified response " + response); - } - return true; - } - @Override public String description() { return "Filter for DIGEST authentication"; @@ -979,22 +1072,23 @@ public void configure (HttpsParameters params) { } } - // This is a bit hacky: HttpsProxyTunnel is an HTTPTestServer hidden - // behind a fake proxy that only understands CONNECT requests. - // The fake proxy is just a server socket that intercept the - // CONNECT and then redirect streams to the real server. + // The HttpsProxyTunnel is a proxy that only understands + // CONNECT requests. It is only used for tunnelling, but + // supports Proxy Authentication with the help of an + // AuthResponder static class HttpsProxyTunnel extends HTTPTestServer implements Runnable { final ServerSocket ss; + final AuthResponder authResponder; private volatile boolean stop; public HttpsProxyTunnel(HttpServer server, HTTPTestServer target, - HttpHandler delegate) + HttpHandler delegate, AuthResponder authResponder) throws IOException { super(server, target, delegate); System.out.flush(); - System.err.println("WARNING: HttpsProxyTunnel is an experimental test class"); + this.authResponder = authResponder; ss = ServerSocketFactory.create(); start(); } @@ -1048,28 +1142,6 @@ public InetSocketAddress getProxyAddress() { return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort()); } - // This is a bit shaky. It doesn't handle continuation - // lines, but our client shouldn't send any. - // Read a line from the input stream, swallowing the final - // \r\n sequence. Stops at the first \n, doesn't complain - // if it wasn't preceded by '\r'. - // - String readLine(InputStream r) throws IOException { - StringBuilder b = new StringBuilder(); - int c; - while ((c = r.read()) != -1) { - if (c == '\n') break; - b.appendCodePoint(c); - } - if (b.length() == 0) { - return ""; - } - if (b.codePointAt(b.length() -1) == '\r') { - b.delete(b.length() -1, b.length()); - } - return b.toString(); - } - @Override public void run() { Socket clientConnection = null; @@ -1137,6 +1209,37 @@ public void run() { } } + private boolean isAuthentified(MessageHeader request) { + String requestLine = request.getValue(0); + String method = requestLine.substring(0, requestLine.indexOf(' ')); + assert "CONNECT".equals(method); + return authResponder.isAuthentified(method, + request.multiValueIterator(authResponder.authorizationHeader())); + } + + private String challengeResponse() { + return "HTTP/1.1 " + authResponder.unauthorizedCode() + " " + + authResponder.unauthorizedString() + + "\r\nContent-Length: 0\r\n" + + authResponder.authenticateHeader() + ": " + + authResponder.generateAuthenticateChallenge() + + "\r\n\r\n"; + } + + private String okResponse() { + return "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; + } + + private String badGatewayResponse() { + return "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n"; + } + + private void sendResponse(PrintWriter pw, String response) { + System.out.println("Tunnel: Sending " + response); + pw.print(response); + pw.flush(); + } + private void processRequestAndWaitToComplete(final Socket clientConnection) throws IOException, InterruptedException { final Socket targetConnection; @@ -1146,32 +1249,24 @@ private void processRequestAndWaitToComplete(final Socket clientConnection) clientConnection.getOutputStream(), "UTF-8"); PrintWriter pw = new PrintWriter(w); System.out.println("Tunnel: Reading request line"); - String requestLine = readLine(ccis); + MessageHeader request = new MessageHeader(ccis); + String requestLine = request.getValue(0); System.out.println("Tunnel: Request line: " + requestLine); - if (requestLine.startsWith("CONNECT ")) { - // We should probably check that the next word following - // CONNECT is the host:port of our HTTPS serverImpl. - // Some improvement for a followup! - - // Read all headers until we find the empty line that - // signals the end of all headers. - while(!requestLine.equals("")) { - System.out.println("Tunnel: Reading header: " - + (requestLine = readLine(ccis))); + if (requestLine != null && requestLine.startsWith("CONNECT ")) { + if (!isAuthentified(request)) { + sendResponse(pw, challengeResponse()); + return; } - targetConnection = new Socket( serverImpl.getAddress().getAddress(), serverImpl.getAddress().getPort()); // Then send the 200 OK response to the client - System.out.println("Tunnel: Sending " - + "HTTP/1.1 200 OK\r\n\r\n"); - pw.print("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); - pw.flush(); + sendResponse(pw, okResponse()); } else { // This should not happen. If it does then consider it a // client error and throw an IOException + sendResponse(pw, badGatewayResponse()); System.out.println("Tunnel: Throwing an IOException due to unexpected" + " request line: " + requestLine); throw new IOException("Client request error - Unexpected request line"); From c9694fa79ac8e15a56e80a372c6a080bdeced1b4 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 17 Jun 2026 17:08:29 +0000 Subject: [PATCH 3/7] 8386298: Improve font loading Reviewed-by: rhalade, kizune, jdv --- src/java.desktop/share/classes/sun/font/HBShaper.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/java.desktop/share/classes/sun/font/HBShaper.java b/src/java.desktop/share/classes/sun/font/HBShaper.java index e7f3e6178fae..8652388edb16 100644 --- a/src/java.desktop/share/classes/sun/font/HBShaper.java +++ b/src/java.desktop/share/classes/sun/font/HBShaper.java @@ -387,7 +387,9 @@ private static int get_glyph_v_advance( */ private static class IntPtr { MemorySegment seg; + @SuppressWarnings("restricted") IntPtr(MemorySegment seg) { + this.seg = seg.reinterpret(4); } void set(int i) { From a490f84d7b5c0e0c4ae47e71ddf0f37ac92d7afa Mon Sep 17 00:00:00 2001 From: Hai-May Chao Date: Wed, 24 Jun 2026 22:30:20 +0000 Subject: [PATCH 4/7] 8386205: Enhance TLS server Reviewed-by: rhalade, ahgross, jnimeh, ascarpino --- .../sun/security/ssl/ServerHandshakeContext.java | 4 ++-- .../share/classes/sun/security/ssl/ServerHello.java | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHandshakeContext.java b/src/java.base/share/classes/sun/security/ssl/ServerHandshakeContext.java index 8bb7def0f575..5d203b5c6ccd 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHandshakeContext.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHandshakeContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. * 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,7 +54,7 @@ class ServerHandshakeContext extends HandshakeContext { private static final long DEFAULT_STATUS_RESP_DELAY = 5000L; final long statusRespTimeout; boolean acceptCliHelloFragments = false; - + boolean sentHRR = false; ServerHandshakeContext(SSLContextImpl sslContext, TransportContext conContext) throws IOException { diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHello.java b/src/java.base/share/classes/sun/security/ssl/ServerHello.java index 4bd2b0a059f5..360699280512 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHello.java @@ -805,6 +805,15 @@ private T13HelloRetryRequestProducer() { public byte[] produce(ConnectionContext context, HandshakeMessage message) throws IOException { ServerHandshakeContext shc = (ServerHandshakeContext) context; + + + if (shc.sentHRR) { + throw shc.conContext.fatal( + Alert.HANDSHAKE_FAILURE, + "TLS 1.3 server MUST NOT send a second HelloRetryRequest " + + "in the same connection"); + } + ClientHelloMessage clientHello = (ClientHelloMessage) message; // negotiate the cipher suite. @@ -840,6 +849,7 @@ public byte[] produce(ConnectionContext context, // Output the handshake message. hhrm.write(shc.handshakeOutput); shc.handshakeOutput.flush(); + shc.sentHRR = true; // In TLS1.3 middlebox compatibility mode the server sends a // dummy change_cipher_spec record immediately after its From 6e6d4c0df2fd0caeeb27896eb039ea1e234dded9 Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Tue, 18 Aug 2026 13:19:08 +0000 Subject: [PATCH 5/7] 8389473: Remove EA from the JDK 27 version string with RC/GAC promotion Reviewed-by: dholmes, iris, erikj --- make/conf/version-numbers.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf index 4f63179ae053..9dbabea0a101 100644 --- a/make/conf/version-numbers.conf +++ b/make/conf/version-numbers.conf @@ -39,4 +39,4 @@ DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 DEFAULT_ACCEPTABLE_BOOT_VERSIONS="26 27" DEFAULT_JDK_SOURCE_TARGET_VERSION=27 -DEFAULT_PROMOTED_VERSION_PRE=ea +DEFAULT_PROMOTED_VERSION_PRE= From c8cfe0ce4794c34866d020f9306e6bbbb7519c7b Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 19 Aug 2026 13:32:43 +0000 Subject: [PATCH 6/7] 8390590: [BACKOUT] C2: Fix the memory around some intrinsics nodes Reviewed-by: thartmann Backport-of: 4b77534a55aa00ea2346a9740660b0c85a1f4374 --- src/hotspot/share/opto/graphKit.cpp | 91 +++----- src/hotspot/share/opto/graphKit.hpp | 3 +- src/hotspot/share/opto/intrinsicnode.cpp | 2 + src/hotspot/share/opto/intrinsicnode.hpp | 200 +++++++----------- src/hotspot/share/opto/library_call.cpp | 14 +- .../intrinsics/string/TestAntiDependency.java | 128 ----------- 6 files changed, 111 insertions(+), 327 deletions(-) delete mode 100644 test/hotspot/jtreg/compiler/intrinsics/string/TestAntiDependency.java diff --git a/src/hotspot/share/opto/graphKit.cpp b/src/hotspot/share/opto/graphKit.cpp index 3112bb6b1690..283510669064 100644 --- a/src/hotspot/share/opto/graphKit.cpp +++ b/src/hotspot/share/opto/graphKit.cpp @@ -39,15 +39,12 @@ #include "opto/intrinsicnode.hpp" #include "opto/locknode.hpp" #include "opto/machnode.hpp" -#include "opto/memnode.hpp" #include "opto/opaquenode.hpp" -#include "opto/opcodes.hpp" #include "opto/parse.hpp" #include "opto/reachability.hpp" #include "opto/rootnode.hpp" #include "opto/runtime.hpp" #include "opto/subtypenode.hpp" -#include "opto/type.hpp" #include "runtime/deoptimization.hpp" #include "runtime/sharedRuntime.hpp" #include "utilities/bitMap.inline.hpp" @@ -4245,81 +4242,51 @@ void GraphKit::store_String_coder(Node* str, Node* value) { value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED); } -// If input and output memory types differ, capture the whole memory to preserve -// the dependency between preceding and subsequent loads/stores. -// For example, the following program: -// StoreB -// compress_string -// LoadB -// has this memory graph (use->def): -// LoadB -> compress_string -> CharMem -// ... -> StoreB -> ByteMem -// The intrinsic hides the dependency between LoadB and StoreB, causing -// the load to read from memory not containing the result of the StoreB. -// The correct memory graph should look like this: -// LoadB -> compress_string -> MergeMem -> StoreB -Node* GraphKit::capture_memory(const TypePtr*& combined_type, const TypePtr* src_type, const TypePtr* dst_type) { +// Capture src and dst memory state with a MergeMemNode +Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) { if (src_type == dst_type) { // Types are equal, we don't need a MergeMemNode - combined_type = src_type; return memory(src_type); } - Node* mem = reset_memory(); - set_all_memory(mem); - combined_type = TypePtr::BOTTOM; - return mem; -} - -// If dst_type and src_type are different, str may have an anti-dependency with another node -// consuming src_type. -// For example: -// compress_string -// StoreC -// has this memory graph (use->def): -// compress_string -> MergeMem -> CharMem -// StoreC -// The scheduler needs to ensure that compress_string is not executed after StoreC, or it will read -// the wrong memory. For normal loads, the scheduler computes its anti-dependencies to ensure the -// memory it reads from is not killed. Since we do not compute anti-dependencies for -// StrCompressedCopyNode, manually insert a MemBar so the anti-dependency becomes use-def -// dependency: -// StoreC -> MemBar -> MergeMem -> compress_string -> MergeMem -> CharMem -// --------------------------------> -void GraphKit::memory_effect(Node* res_mem, const TypePtr* src_type, const TypePtr* dst_type) { - set_memory(res_mem, dst_type); - if (src_type != dst_type) { - Node* all_mem = reset_memory(); - set_all_memory(all_mem); - Node* membar = new MemBarCPUOrderNode(C, C->get_alias_index(src_type), nullptr); - membar->init_req(TypeFunc::Control, control()); - membar->init_req(TypeFunc::Memory, all_mem); - membar = _gvn.transform(membar); - set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control))); - set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)), src_type); - } + MergeMemNode* merge = MergeMemNode::make(map()->memory()); + record_for_igvn(merge); // fold it up later, if possible + int src_idx = C->get_alias_index(src_type); + int dst_idx = C->get_alias_index(dst_type); + merge->set_memory_at(src_idx, memory(src_idx)); + merge->set_memory_at(dst_idx, memory(dst_idx)); + return merge; } Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) { assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported"); assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type"); - const TypePtr* dst_type = TypeAryPtr::BYTES; - const TypePtr* adr_type; - Node* mem = capture_memory(adr_type, src_type, dst_type); - StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, adr_type, src, dst, count); + // If input and output memory types differ, capture both states to preserve + // the dependency between preceding and subsequent loads/stores. + // For example, the following program: + // StoreB + // compress_string + // LoadB + // has this memory graph (use->def): + // LoadB -> compress_string -> CharMem + // ... -> StoreB -> ByteMem + // The intrinsic hides the dependency between LoadB and StoreB, causing + // the load to read from memory not containing the result of the StoreB. + // The correct memory graph should look like this: + // LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem)) + Node* mem = capture_memory(src_type, TypeAryPtr::BYTES); + StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count); Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str))); - memory_effect(res_mem, src_type, dst_type); + set_memory(res_mem, TypeAryPtr::BYTES); return str; } void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) { assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported"); assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type"); - const TypePtr* src_type = TypeAryPtr::BYTES; - const TypePtr* adr_type; - Node* mem = capture_memory(adr_type, src_type, dst_type); - StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, adr_type, src, dst, count); - Node* res_mem = _gvn.transform(str); - memory_effect(res_mem, src_type, dst_type); + // Capture src and dst memory (see comment in 'compress_string'). + Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type); + StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count); + set_memory(_gvn.transform(str), dst_type); } void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) { diff --git a/src/hotspot/share/opto/graphKit.hpp b/src/hotspot/share/opto/graphKit.hpp index d371dfb2e32e..f53f73d09784 100644 --- a/src/hotspot/share/opto/graphKit.hpp +++ b/src/hotspot/share/opto/graphKit.hpp @@ -853,8 +853,7 @@ class GraphKit : public Phase { Node* load_String_coder(Node* str, bool set_ctrl); void store_String_value(Node* str, Node* value); void store_String_coder(Node* str, Node* value); - Node* capture_memory(const TypePtr*& combined_type, const TypePtr* src_type, const TypePtr* dst_type); - void memory_effect(Node* res_mem, const TypePtr* src_type, const TypePtr* dst_type); + Node* capture_memory(const TypePtr* src_type, const TypePtr* dst_type); Node* compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count); void inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count); void inflate_string_slow(Node* src, Node* dst, Node* start, Node* count); diff --git a/src/hotspot/share/opto/intrinsicnode.cpp b/src/hotspot/share/opto/intrinsicnode.cpp index 887681233f16..d3e62dacfe80 100644 --- a/src/hotspot/share/opto/intrinsicnode.cpp +++ b/src/hotspot/share/opto/intrinsicnode.cpp @@ -63,6 +63,8 @@ const Type* StrIntrinsicNode::Value(PhaseGVN* phase) const { return bottom_type(); } +uint StrIntrinsicNode::size_of() const { return sizeof(*this); } + //============================================================================= //------------------------------Ideal------------------------------------------ // Return a node which is more "ideal" than the current node. Strip out diff --git a/src/hotspot/share/opto/intrinsicnode.hpp b/src/hotspot/share/opto/intrinsicnode.hpp index 1fe61cfb1785..d81e7bed7e96 100644 --- a/src/hotspot/share/opto/intrinsicnode.hpp +++ b/src/hotspot/share/opto/intrinsicnode.hpp @@ -48,7 +48,7 @@ class PartialSubtypeCheckNode : public Node { //------------------------------StrIntrinsic------------------------------- // Base class for Ideal nodes used in String intrinsic code. -class StrIntrinsicNode : public Node { +class StrIntrinsicNode: public Node { public: // Possible encodings of the parameters passed to the string intrinsic. // 'L' stands for Latin1 and 'U' stands for UTF16. For example, 'LU' means that @@ -59,11 +59,7 @@ class StrIntrinsicNode : public Node { protected: // Encoding of strings. Used to select the right version of the intrinsic. const ArgEncoding _encoding; - virtual uint size_of() const override { return sizeof(StrIntrinsicNode); } - virtual uint hash() const override { return Node::hash() + _encoding; } - virtual bool cmp(const Node& n) const override { - return Node::cmp(n) && _encoding == static_cast(n)._encoding; - } + virtual uint size_of() const; public: StrIntrinsicNode(Node* control, Node* char_array_mem, @@ -81,189 +77,141 @@ class StrIntrinsicNode : public Node { Node(control, char_array_mem, s1, s2), _encoding(encoding) { } - virtual const TypePtr* adr_type() const override = 0; - virtual uint match_edge(uint idx) const override; - virtual uint ideal_reg() const override { return Op_RegI; } - virtual Node* Ideal(PhaseGVN* phase, bool can_reshape) override; - virtual const Type* Value(PhaseGVN* phase) const override; + virtual const TypePtr* adr_type() const { return TypeAryPtr::BYTES; } + virtual uint match_edge(uint idx) const; + virtual uint ideal_reg() const { return Op_RegI; } + virtual Node* Ideal(PhaseGVN* phase, bool can_reshape); + virtual const Type* Value(PhaseGVN* phase) const; ArgEncoding encoding() const { return _encoding; } private: - virtual bool depends_only_on_test_impl() const override { return false; } + virtual bool depends_only_on_test_impl() const { return false; } }; //------------------------------StrComp------------------------------------- -class StrCompNode final : public StrIntrinsicNode { +class StrCompNode: public StrIntrinsicNode { public: StrCompNode(Node* control, Node* char_array_mem, Node* s1, Node* c1, Node* s2, Node* c2, ArgEncoding encoding): StrIntrinsicNode(control, char_array_mem, s1, c1, s2, c2, encoding) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual const TypePtr* adr_type() const override { return TypeAryPtr::BYTES; } + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } }; //------------------------------StrEquals------------------------------------- -class StrEqualsNode final : public StrIntrinsicNode { +class StrEqualsNode: public StrIntrinsicNode { public: StrEqualsNode(Node* control, Node* char_array_mem, Node* s1, Node* s2, Node* c, ArgEncoding encoding): StrIntrinsicNode(control, char_array_mem, s1, s2, c, encoding) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::BOOL; } - virtual const TypePtr* adr_type() const override { return TypeAryPtr::BYTES; } + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::BOOL; } }; //------------------------------StrIndexOf------------------------------------- -class StrIndexOfNode final : public StrIntrinsicNode { +class StrIndexOfNode: public StrIntrinsicNode { public: StrIndexOfNode(Node* control, Node* char_array_mem, Node* s1, Node* c1, Node* s2, Node* c2, ArgEncoding encoding): StrIntrinsicNode(control, char_array_mem, s1, c1, s2, c2, encoding) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual const TypePtr* adr_type() const override { return TypeAryPtr::BYTES; } + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } }; //------------------------------StrIndexOfChar------------------------------------- -class StrIndexOfCharNode final : public StrIntrinsicNode { +class StrIndexOfCharNode: public StrIntrinsicNode { public: StrIndexOfCharNode(Node* control, Node* char_array_mem, Node* s1, Node* c1, Node* c, ArgEncoding encoding): StrIntrinsicNode(control, char_array_mem, s1, c1, c, encoding) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual const TypePtr* adr_type() const override { return TypeAryPtr::BYTES; } + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } }; //--------------------------StrCompressedCopy------------------------------- -class StrCompressedCopyNode final : public StrIntrinsicNode { -private: - const TypePtr* const _adr_type; - -public: - StrCompressedCopyNode(Node* control, Node* arymem, const TypePtr* adr_type, +class StrCompressedCopyNode: public StrIntrinsicNode { + public: + StrCompressedCopyNode(Node* control, Node* arymem, Node* s1, Node* s2, Node* c): - StrIntrinsicNode(control, arymem, s1, s2, c, none), _adr_type(adr_type) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual Node* Ideal(PhaseGVN* phase, bool can_reshape) override; - -private: - virtual uint size_of() const override { return sizeof(StrCompressedCopyNode); } - virtual uint hash() const override { return StrIntrinsicNode::hash() + (uint)(uintptr_t) _adr_type; } - virtual bool cmp(const Node& n) const override { - return StrIntrinsicNode::cmp(n) && _adr_type == static_cast(n)._adr_type; - } - virtual const TypePtr* adr_type() const override { return _adr_type; } + StrIntrinsicNode(control, arymem, s1, s2, c, none) {}; + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } + virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; } + virtual Node* Ideal(PhaseGVN* phase, bool can_reshape); }; //--------------------------StrInflatedCopy--------------------------------- -class StrInflatedCopyNode final : public StrIntrinsicNode { -private: - const TypePtr* const _adr_type; - -public: - StrInflatedCopyNode(Node* control, Node* arymem, const TypePtr* adr_type, +class StrInflatedCopyNode: public StrIntrinsicNode { + public: + StrInflatedCopyNode(Node* control, Node* arymem, Node* s1, Node* s2, Node* c): - StrIntrinsicNode(control, arymem, s1, s2, c, none), _adr_type(adr_type) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return Type::MEMORY; } - virtual Node* Ideal(PhaseGVN* phase, bool can_reshape) override; - -private: - virtual uint size_of() const override { return sizeof(StrInflatedCopyNode); } - virtual uint hash() const override { return StrIntrinsicNode::hash() + (uint)(uintptr_t) _adr_type; } - virtual bool cmp(const Node& n) const override { - return StrIntrinsicNode::cmp(n) && _adr_type == static_cast(n)._adr_type; - } - virtual const TypePtr* adr_type() const override { return _adr_type; } + StrIntrinsicNode(control, arymem, s1, s2, c, none) {}; + virtual int Opcode() const; + virtual const Type* bottom_type() const { return Type::MEMORY; } + virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; } + virtual Node* Ideal(PhaseGVN* phase, bool can_reshape); }; //------------------------------AryEq--------------------------------------- -class AryEqNode final : public StrIntrinsicNode { -private: - const TypeAryPtr* const _in_adr_type; - -public: - AryEqNode(Node* control, Node* char_array_mem, const TypeAryPtr* in_adr_type, +class AryEqNode: public StrIntrinsicNode { + public: + AryEqNode(Node* control, Node* char_array_mem, Node* s1, Node* s2, ArgEncoding encoding): - StrIntrinsicNode(control, char_array_mem, s1, s2, encoding), _in_adr_type(in_adr_type) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::BOOL; } - -private: - virtual uint size_of() const override { return sizeof(AryEqNode); } - virtual uint hash() const override { return StrIntrinsicNode::hash() + (uint)(uintptr_t) _in_adr_type; } - virtual bool cmp(const Node& n) const override { - return StrIntrinsicNode::cmp(n) && _in_adr_type == static_cast(n)._in_adr_type; - } - virtual const TypePtr* adr_type() const override { return _in_adr_type; } + StrIntrinsicNode(control, char_array_mem, s1, s2, encoding) {}; + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::BOOL; } }; //------------------------------CountPositives------------------------------ -class CountPositivesNode final : public StrIntrinsicNode { +class CountPositivesNode: public StrIntrinsicNode { public: CountPositivesNode(Node* control, Node* char_array_mem, Node* s1, Node* c1): StrIntrinsicNode(control, char_array_mem, s1, c1, none) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::POS; } - virtual const TypePtr* adr_type() const override { return TypeAryPtr::BYTES; } + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::POS; } }; //------------------------------VectorizedHashCodeNode---------------------- -class VectorizedHashCodeNode final : public Node { -private: - const TypeAryPtr* const _in_adr_type; - -public: - VectorizedHashCodeNode(Node* control, Node* ary_mem, const TypeAryPtr* in_adr_type, Node* arg1, Node* cnt1, Node* result, Node* basic_type) - : Node(control, ary_mem, arg1, cnt1, result, basic_type), _in_adr_type(in_adr_type) {}; - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual uint match_edge(uint idx) const override; - virtual uint ideal_reg() const override { return Op_RegI; } - virtual Node* Ideal(PhaseGVN* phase, bool can_reshape) override; - virtual const Type* Value(PhaseGVN* phase) const override; +class VectorizedHashCodeNode: public Node { + public: + VectorizedHashCodeNode(Node* control, Node* ary_mem, Node* arg1, Node* cnt1, Node* result, Node* basic_type) + : Node(control, ary_mem, arg1, cnt1, result, basic_type) {}; + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } + virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; } + virtual uint match_edge(uint idx) const; + virtual uint ideal_reg() const { return Op_RegI; } + virtual Node* Ideal(PhaseGVN* phase, bool can_reshape); + virtual const Type* Value(PhaseGVN* phase) const; private: - virtual uint size_of() const override { return sizeof(VectorizedHashCodeNode); } - virtual uint hash() const override { return Node::hash() + (uint)(uintptr_t) _in_adr_type; } - virtual bool cmp(const Node& n) const override { - return Node::cmp(n) && _in_adr_type == static_cast(n)._in_adr_type; - } - virtual const TypePtr* adr_type() const override { return _in_adr_type; } - virtual bool depends_only_on_test_impl() const override { return false; } + virtual bool depends_only_on_test_impl() const { return false; } }; //------------------------------EncodeISOArray-------------------------------- // encode char[] to byte[] in ISO_8859_1 or ASCII -class EncodeISOArrayNode final : public Node { -private: - const TypePtr* const _adr_type; +class EncodeISOArrayNode: public Node { bool _ascii; - -public: - EncodeISOArrayNode(Node* control, Node* arymem, const TypePtr* adr_type, Node* s1, Node* s2, Node* c, bool ascii) - : Node(control, arymem, s1, s2, c), _adr_type(adr_type), _ascii(ascii) {} + public: + EncodeISOArrayNode(Node* control, Node* arymem, Node* s1, Node* s2, Node* c, bool ascii) + : Node(control, arymem, s1, s2, c), _ascii(ascii) {} bool is_ascii() { return _ascii; } - virtual int Opcode() const override; - virtual const Type* bottom_type() const override { return TypeInt::INT; } - virtual uint match_edge(uint idx) const override; - virtual uint ideal_reg() const override { return Op_RegI; } - virtual Node* Ideal(PhaseGVN* phase, bool can_reshape) override; - virtual const Type* Value(PhaseGVN* phase) const override; + virtual int Opcode() const; + virtual const Type* bottom_type() const { return TypeInt::INT; } + virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; } + virtual uint match_edge(uint idx) const; + virtual uint ideal_reg() const { return Op_RegI; } + virtual Node* Ideal(PhaseGVN* phase, bool can_reshape); + virtual const Type* Value(PhaseGVN* phase) const; + virtual uint size_of() const { return sizeof(EncodeISOArrayNode); } + virtual uint hash() const { return Node::hash() + _ascii; } + virtual bool cmp(const Node& n) const { + return Node::cmp(n) && _ascii == ((EncodeISOArrayNode&)n).is_ascii(); + } private: - virtual uint size_of() const override { return sizeof(EncodeISOArrayNode); } - virtual uint hash() const override { return Node::hash() + (uint)(uintptr_t) _adr_type + _ascii; } - virtual bool cmp(const Node& n) const override { - const EncodeISOArrayNode& e = static_cast(n); - return Node::cmp(n) && _ascii == e._ascii && _adr_type == e._adr_type; - } - virtual const TypePtr* adr_type() const override { return _adr_type; } - virtual bool depends_only_on_test_impl() const override { return false; } + virtual bool depends_only_on_test_impl() const { return false; } }; //-------------------------------DigitNode---------------------------------------- diff --git a/src/hotspot/share/opto/library_call.cpp b/src/hotspot/share/opto/library_call.cpp index 7251783d771a..8ccd1d3c8577 100644 --- a/src/hotspot/share/opto/library_call.cpp +++ b/src/hotspot/share/opto/library_call.cpp @@ -1131,7 +1131,7 @@ bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) { Node* arg2 = argument(1); const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES; - set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae))); + set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae))); clear_upper_avx(); return true; @@ -6255,14 +6255,11 @@ bool LibraryCallKit::inline_encodeISOArray(bool ascii) { // 'src_start' points to src array + scaled offset // 'dst_start' points to dst array + scaled offset - // See GraphKit::compress_string - const TypePtr* adr_type; - Node* mem = capture_memory(adr_type, src_type, dst_type); - Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii); + const TypeAryPtr* mtype = TypeAryPtr::BYTES; + Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii); enc = _gvn.transform(enc); Node* res_mem = _gvn.transform(new SCMemProjNode(enc)); - memory_effect(res_mem, src_type, dst_type); - + set_memory(res_mem, mtype); set_result(enc); clear_upper_avx(); @@ -6741,8 +6738,7 @@ bool LibraryCallKit::inline_vectorizedHashCode() { // Resolve address of first element Node* array_start = array_element_address(array, offset, bt); - const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt); - set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type, + set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)), array_start, length, initialValue, basic_type))); clear_upper_avx(); diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestAntiDependency.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestAntiDependency.java deleted file mode 100644 index c48b24f7c567..000000000000 --- a/test/hotspot/jtreg/compiler/intrinsics/string/TestAntiDependency.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package compiler.intrinsics.string; - -import compiler.lib.ir_framework.DontInline; -import compiler.lib.ir_framework.Run; -import compiler.lib.ir_framework.Test; -import compiler.lib.ir_framework.TestFramework; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; - -import jdk.test.lib.Asserts; - -/* - * @test - * @bug 8373591 - * @summary Verify that StringLatin1::inflate, StringUTF16::compress, and - * StringCoding::implEncodeAsciiArray are scheduled properly - * @library /test/lib / - * @modules java.base/java.lang:+open - * @run driver ${test.main.class} - */ -public class TestAntiDependency { - static final MethodHandle COMPRESS_HANDLE; - static final MethodHandle INFLATE_HANDLE; - static final MethodHandle ENCODE_ISO_HANDLE; - static { - try { - var currentLookup = MethodHandles.lookup(); - var stringLookup = MethodHandles.privateLookupIn(String.class, currentLookup); - Class stringUtf16Class = stringLookup.findClass("java.lang.StringUTF16"); - var stringUtf16Lookup = MethodHandles.privateLookupIn(stringUtf16Class, currentLookup); - COMPRESS_HANDLE = stringUtf16Lookup.findStatic(stringUtf16Class, "compress0", - MethodType.methodType(int.class, char[].class, int.class, byte[].class, int.class, int.class)); - Class stringLatin1Class = stringLookup.findClass("java.lang.StringLatin1"); - var stringLatin1Lookup = MethodHandles.privateLookupIn(stringLatin1Class, currentLookup); - INFLATE_HANDLE = stringLatin1Lookup.findStatic(stringLatin1Class, "inflate0", - MethodType.methodType(void.class, byte[].class, int.class, char[].class, int.class, int.class)); - Class stringCodingClass = stringLookup.findClass("java.lang.StringCoding"); - ENCODE_ISO_HANDLE = stringLookup.findStatic(stringCodingClass, "encodeAsciiArray0", - MethodType.methodType(int.class, char[].class, int.class, byte[].class, int.class, int.class)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] args) { - var testFramework = new TestFramework(); - testFramework.setDefaultWarmup(1); - testFramework.addFlags("--add-opens=java.base/java.lang=ALL-UNNAMED"); - testFramework.start(); - } - - @DontInline - static void consume(Object o1, Object o2) {} - - @Test - static int testStringCompress() throws Throwable { - byte[] dst = new byte[4]; - char[] src = new char[4]; - consume(dst, src); - - // The compiler must not schedule this after the store to src, either by having - // StringCompressedCopyNode kill the whole memory, or by taking into consideration the - // anti-dependency between 2 nodes - int _ = (int) COMPRESS_HANDLE.invokeExact(src, 0, dst, 0, 4); - src[0] = 1; - return dst[0]; - } - - @Test - static int testStringInflate() throws Throwable { - char[] dst = new char[4]; - byte[] src = new byte[4]; - consume(dst, src); - - // The compiler must not schedule this after the store to src, either by having - // StringInflatedCopyNode kill the whole memory, or by taking into consideration the - // anti-dependency between 2 nodes - INFLATE_HANDLE.invokeExact(src, 0, dst, 0, 4); - src[0] = 1; - return dst[0]; - } - - @Test - static int testEncodeISO() throws Throwable { - byte[] dst = new byte[4]; - char[] src = new char[4]; - consume(dst, src); - - // The compiler must not schedule this after the store to src, either by having - // EncodeISOArrayNode kill the whole memory, or by taking into consideration the - // anti-dependency between 2 nodes - int _ = (int) ENCODE_ISO_HANDLE.invokeExact(src, 0, dst, 0, 4); - src[0] = 1; - return dst[0]; - } - - @Run(test = {"testStringCompress", "testStringInflate", "testEncodeISO"}) - public void run() throws Throwable { - Asserts.assertEQ(0, testStringCompress()); - Asserts.assertEQ(0, testStringInflate()); - Asserts.assertEQ(0, testEncodeISO()); - } -} From 815ff4dc327fe17f2433c7d115a5a503af10f3c4 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 19 Aug 2026 14:06:10 +0000 Subject: [PATCH 7/7] 8390591: Add regression test for JDK-8390590 Reviewed-by: thartmann Backport-of: 6994a51e9c3730c68da9f6d46e092b66c37b3186 --- .../intrinsics/string/TestEncodeISOArray.java | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeISOArray.java diff --git a/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeISOArray.java b/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeISOArray.java new file mode 100644 index 000000000000..cb2b37b75bd0 --- /dev/null +++ b/test/hotspot/jtreg/compiler/intrinsics/string/TestEncodeISOArray.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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 8390546 + * @summary Verify that the memory effect of the encodeISOArray intrinsic is correctly wired in. + * @library /test/lib + * @requires vm.compiler2.enabled + * @modules java.base/java.lang:+open java.base/sun.nio.cs:+open + * @run main compiler.intrinsics.string.TestEncodeISOArray + * @run main/othervm -Xbatch -XX:-TieredCompilation -XX:CompileThreshold=100 + * -XX:+IgnoreUnrecognizedVMOptions -XX:UseAVX=0 -XX:-UseSSE42Intrinsics + * compiler.intrinsics.string.TestEncodeISOArray + */ + +package compiler.intrinsics.string; + +import jdk.test.lib.Asserts; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class TestEncodeISOArray { + private static final int ITERATIONS = 20_000; + private static final int FIRST_BYTE = 'C'; + private static final char[] SOURCE = "C2 go brrr".toCharArray(); + private static final byte[] UTF16_SOURCE = toUTF16Bytes(SOURCE); + private static final byte[] EXPECTED = "C2 go brrr".getBytes(StandardCharsets.UTF_8); + private static final MethodType ENCODE_TYPE = MethodType.methodType(int.class, char[].class, int.class, byte[].class, int.class, int.class); + private static final MethodType ENCODE_BYTE_TYPE = MethodType.methodType(int.class, byte[].class, int.class, byte[].class, int.class, int.class); + private static final MethodHandle ENCODE_ASCII_ARRAY = findEncoder("java.lang.StringCoding", "encodeAsciiArray0", ENCODE_TYPE); + private static final MethodHandle ENCODE_ISO_ARRAY = findEncoder("sun.nio.cs.ISO_8859_1$Encoder", "encodeISOArray0", ENCODE_TYPE); + private static final MethodHandle ENCODE_BYTE_ISO_ARRAY = findEncoder("java.lang.StringCoding", "encodeISOArray0", ENCODE_BYTE_TYPE); + + private static byte[] toUTF16Bytes(char[] chars) { + ByteBuffer buffer = ByteBuffer.allocate(chars.length * Character.BYTES).order(ByteOrder.nativeOrder()); + for (char c : chars) { + buffer.putChar(c); + } + return buffer.array(); + } + + private static MethodHandle findEncoder(String className, String methodName, MethodType type) { + try { + Class holder = Class.forName(className); + MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(holder, MethodHandles.lookup()); + return lookup.findStatic(holder, methodName, type); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // Original reproducer from JDK-8390546 + private static byte[] toUtf8Bytes(char[] chars) { + ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(CharBuffer.wrap(chars)); + return Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.limit()); + } + + // Targeted check that does not depend on the UTF-8 encoder and arraycopy both being inlined. + private static int encodeASCIIAndLoadFirstByte() throws Throwable { + byte[] destination = new byte[4]; + int encoded = (int) ENCODE_ASCII_ARRAY.invokeExact(SOURCE, 0, destination, 0, 4); + if (encoded != 4) { + return -1; + } + return destination[0]; + } + + private static int encodeISOAndLoadFirstByte() throws Throwable { + byte[] destination = new byte[4]; + int encoded = (int) ENCODE_ISO_ARRAY.invokeExact(SOURCE, 0, destination, 0, 4); + if (encoded != 4) { + return -1; + } + return destination[0]; + } + + private static int encodeByteISOAndLoadFirstByte() throws Throwable { + byte[] destination = new byte[4]; + int encoded = (int) ENCODE_BYTE_ISO_ARRAY.invokeExact(UTF16_SOURCE, 0, destination, 0, 4); + if (encoded != 4) { + return -1; + } + return destination[0]; + } + + private static boolean runOriginalReproducer() { + for (int i = 0; i < ITERATIONS; i++) { + if (!Arrays.equals(toUtf8Bytes(SOURCE), EXPECTED)) { + return false; + } + } + return true; + } + + private static boolean runASCIITest() throws Throwable { + for (int i = 0; i < ITERATIONS; i++) { + if (encodeASCIIAndLoadFirstByte() != FIRST_BYTE) { + return false; + } + } + return true; + } + + private static boolean runISOTest() throws Throwable { + for (int i = 0; i < ITERATIONS; i++) { + if (encodeISOAndLoadFirstByte() != FIRST_BYTE) { + return false; + } + } + return true; + } + + private static boolean runByteISOTest() throws Throwable { + for (int i = 0; i < ITERATIONS; i++) { + if (encodeByteISOAndLoadFirstByte() != FIRST_BYTE) { + return false; + } + } + return true; + } + + public static void main(String[] args) throws Throwable { + Asserts.assertTrue(runOriginalReproducer(), "Original reproducer failed"); + Asserts.assertTrue(runASCIITest(), "ASCII encoding failed"); + Asserts.assertTrue(runISOTest(), "ISO-8859-1 encoding failed"); + Asserts.assertTrue(runByteISOTest(), "Byte ISO-8859-1 encoding failed"); + } +}