From 0ab8a85e87cb607c48a45900550998f0d36cf761 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 25 Feb 2026 17:37:09 +0000 Subject: [PATCH 01/54] 8376152: Test javax/sound/sampled/Clip/bug5070081.java timed out then completed Reviewed-by: syan, aivanov, azvegint --- test/jdk/javax/sound/sampled/Clip/bug5070081.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/jdk/javax/sound/sampled/Clip/bug5070081.java b/test/jdk/javax/sound/sampled/Clip/bug5070081.java index e7bf7e30de2..89e9d591d28 100644 --- a/test/jdk/javax/sound/sampled/Clip/bug5070081.java +++ b/test/jdk/javax/sound/sampled/Clip/bug5070081.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -31,7 +31,8 @@ import javax.sound.sampled.LineUnavailableException; /* * @test - * @bug 5070081 + * @key sound + * @bug 5070081 8376152 * @summary Tests that javax.sound.sampled.Clip does not loses position through * stop/start */ From 9d4fbbe36d85d71ce850bb83bbfb1ce1d3e8dd23 Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Wed, 25 Feb 2026 17:43:05 +0000 Subject: [PATCH 02/54] 8374222: jpackage will exit with error if it fails to clean the temp directory Reviewed-by: almatvee --- .../internal/DefaultBundlingEnvironment.java | 4 +- .../jdk/jpackage/internal/TempDirectory.java | 145 ++++- .../resources/MainResources.properties | 3 + .../jpackage/test/PathDeletionPreventer.java | 173 ++++++ .../jpackage/internal/TempDirectoryTest.java | 570 ++++++++++++++++++ 5 files changed, 877 insertions(+), 18 deletions(-) create mode 100644 test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PathDeletionPreventer.java create mode 100644 test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/TempDirectoryTest.java diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java index 3a58180aa35..fc51f60aa66 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/DefaultBundlingEnvironment.java @@ -195,11 +195,11 @@ class DefaultBundlingEnvironment implements CliBundlingEnvironment { public void createBundle(BundlingOperationDescriptor op, Options cmdline) { final var bundler = getBundlerSupplier(op).get().orElseThrow(); Optional permanentWorkDirectory = Optional.empty(); - try (var tempDir = new TempDirectory(cmdline)) { + try (var tempDir = new TempDirectory(cmdline, Globals.instance().objectFactory())) { if (!tempDir.deleteOnClose()) { permanentWorkDirectory = Optional.of(tempDir.path()); } - bundler.accept(tempDir.options()); + bundler.accept(tempDir.map(cmdline)); } catch (IOException ex) { throw new UncheckedIOException(ex); } finally { diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/TempDirectory.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/TempDirectory.java index 50d1701bf0d..345a42c5051 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/TempDirectory.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/TempDirectory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -26,29 +26,46 @@ package jdk.jpackage.internal; import java.io.Closeable; import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import jdk.jpackage.internal.cli.Options; import jdk.jpackage.internal.cli.StandardOption; import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.Slot; final class TempDirectory implements Closeable { - TempDirectory(Options options) throws IOException { - final var tempDir = StandardOption.TEMP_ROOT.findIn(options); - if (tempDir.isPresent()) { - this.path = tempDir.orElseThrow(); - this.options = options; - } else { - this.path = Files.createTempDirectory("jdk.jpackage"); - this.options = options.copyWithDefaultValue(StandardOption.TEMP_ROOT, path); - } - - deleteOnClose = tempDir.isEmpty(); + TempDirectory(Options options, RetryExecutorFactory retryExecutorFactory) throws IOException { + this(StandardOption.TEMP_ROOT.findIn(options), retryExecutorFactory); } - Options options() { - return options; + TempDirectory(Optional tempDir, RetryExecutorFactory retryExecutorFactory) throws IOException { + this(tempDir.isEmpty() ? Files.createTempDirectory("jdk.jpackage") : tempDir.get(), + tempDir.isEmpty(), + retryExecutorFactory); + } + + TempDirectory(Path tempDir, boolean deleteOnClose, RetryExecutorFactory retryExecutorFactory) throws IOException { + this.path = Objects.requireNonNull(tempDir); + this.deleteOnClose = deleteOnClose; + this.retryExecutorFactory = Objects.requireNonNull(retryExecutorFactory); + } + + Options map(Options options) { + if (deleteOnClose) { + return options.copyWithDefaultValue(StandardOption.TEMP_ROOT, path); + } else { + return options; + } } Path path() { @@ -62,11 +79,107 @@ final class TempDirectory implements Closeable { @Override public void close() throws IOException { if (deleteOnClose) { - FileUtils.deleteRecursive(path); + retryExecutorFactory.retryExecutor(IOException.class) + .setMaxAttemptsCount(5) + .setAttemptTimeout(2, TimeUnit.SECONDS) + .setExecutable(context -> { + try { + FileUtils.deleteRecursive(path); + } catch (IOException ex) { + if (!context.isLastAttempt()) { + throw ex; + } else { + // Collect the list of leftover files. Collect at most the first 100 files. + var remainingFiles = DirectoryListing.listFilesAndEmptyDirectories( + path, MAX_REPORTED_UNDELETED_FILE_COUNT).paths(); + + if (remainingFiles.equals(List.of(path))) { + Log.info(I18N.format("warning.tempdir.cleanup-failed", path)); + } else { + remainingFiles.forEach(file -> { + Log.info(I18N.format("warning.tempdir.cleanup-file-failed", file)); + }); + } + + Log.verbose(ex); + } + } + return null; + }).execute(); + } + } + + record DirectoryListing(List paths, boolean complete) { + DirectoryListing { + Objects.requireNonNull(paths); + } + + static DirectoryListing listFilesAndEmptyDirectories(Path path, int limit) { + Objects.requireNonNull(path); + if (limit < 0) { + throw new IllegalArgumentException(); + } else if (limit == 0) { + return new DirectoryListing(List.of(), !Files.exists(path)); + } + + var paths = new ArrayList(); + var stopped = Slot.createEmpty(); + + stopped.set(false); + + try { + Files.walkFileTree(path, new FileVisitor<>() { + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + try (var walk = Files.walk(dir)) { + if (walk.skip(1).findAny().isEmpty()) { + // This is an empty directory, add it to the list. + return addPath(dir, FileVisitResult.SKIP_SUBTREE); + } + } catch (IOException ex) { + Log.verbose(ex); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + return addPath(file, FileVisitResult.CONTINUE); + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + return addPath(file, FileVisitResult.CONTINUE); + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + return FileVisitResult.CONTINUE; + } + + private FileVisitResult addPath(Path v, FileVisitResult result) { + if (paths.size() < limit) { + paths.add(v); + return result; + } else { + stopped.set(true); + } + return FileVisitResult.TERMINATE; + } + + }); + } catch (IOException ex) { + Log.verbose(ex); + } + + return new DirectoryListing(Collections.unmodifiableList(paths), !stopped.get()); } } private final Path path; - private final Options options; private final boolean deleteOnClose; + private final RetryExecutorFactory retryExecutorFactory; + + private final static int MAX_REPORTED_UNDELETED_FILE_COUNT = 100; } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties index 6e5de3d9729..233067d6457 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/resources/MainResources.properties @@ -109,6 +109,9 @@ error.tool-not-found.advice=Please install "{0}" error.tool-old-version=Can not find "{0}" {1} or newer error.tool-old-version.advice=Please install "{0}" {1} or newer +warning.tempdir.cleanup-failed=Warning: Failed to clean-up temporary directory {0} +warning.tempdir.cleanup-file-failed=Warning: Failed to delete "{0}" file in the temporary directory + error.output-bundle-cannot-be-overwritten=Output package file "{0}" exists and can not be removed. error.blocked.option=jlink option [{0}] is not permitted in --jlink-options diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PathDeletionPreventer.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PathDeletionPreventer.java new file mode 100644 index 00000000000..d16b63d9c69 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PathDeletionPreventer.java @@ -0,0 +1,173 @@ +/* + * 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 jdk.jpackage.test; + +import java.io.Closeable; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileLock; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.util.SetBuilder; + +/** + * Path deletion preventer. Encapsulates platform-specifics of how to make a + * file or a directory non-deletable. + *

+ * Implementation should be sufficient to make {@code Files#delete(Path)} + * applied to the path protected from deletion throw. + */ +public sealed interface PathDeletionPreventer { + + enum Implementation { + /** + * Uses Java file lock to prevent deletion of a file. + * Works on Windows. Doesn't work on Linux and macOS. + */ + FILE_CHANNEL_LOCK, + + /** + * Removes write permission from a non-empty directory to prevent its deletion. + * Works on Linux and macOS. Doesn't work on Windows. + */ + READ_ONLY_NON_EMPTY_DIRECTORY, + ; + } + + Implementation implementation(); + + Closeable preventPathDeletion(Path path) throws IOException; + + enum FileChannelLockPathDeletionPreventer implements PathDeletionPreventer { + INSTANCE; + + @Override + public Implementation implementation() { + return Implementation.FILE_CHANNEL_LOCK; + } + + @Override + public Closeable preventPathDeletion(Path path) throws IOException { + return new UndeletablePath(path); + } + + private static final class UndeletablePath implements Closeable { + + UndeletablePath(Path file) throws IOException { + var fos = new FileOutputStream(Objects.requireNonNull(file).toFile()); + boolean lockCreated = false; + try { + this.lock = fos.getChannel().lock(); + this.fos = fos; + lockCreated = true; + } finally { + if (!lockCreated) { + fos.close(); + } + } + } + + @Override + public void close() throws IOException { + try { + lock.close(); + } finally { + fos.close(); + } + } + + private final FileOutputStream fos; + private final FileLock lock; + } + } + + enum ReadOnlyDirectoryPathDeletionPreventer implements PathDeletionPreventer { + INSTANCE; + + @Override + public Implementation implementation() { + return Implementation.READ_ONLY_NON_EMPTY_DIRECTORY; + } + + @Override + public Closeable preventPathDeletion(Path path) throws IOException { + return new UndeletablePath(path); + } + + private static final class UndeletablePath implements Closeable { + + UndeletablePath(Path dir) throws IOException { + this.dir = Objects.requireNonNull(dir); + + // Deliberately don't use Files#createDirectories() as don't want to create missing directories. + try { + Files.createDirectory(dir); + Files.createFile(dir.resolve("empty")); + } catch (FileAlreadyExistsException ex) { + } + + perms = Files.getPosixFilePermissions(dir); + if (perms.contains(PosixFilePermission.OWNER_WRITE)) { + Files.setPosixFilePermissions(dir, SetBuilder.build() + .add(perms) + .remove(PosixFilePermission.OWNER_WRITE) + .emptyAllowed(true) + .create()); + } + } + + @Override + public void close() throws IOException { + if (perms.contains(PosixFilePermission.OWNER_WRITE)) { + Files.setPosixFilePermissions(dir, perms); + } + } + + private final Path dir; + private final Set perms; + } + } + + static final PathDeletionPreventer DEFAULT = new Supplier() { + + @Override + public PathDeletionPreventer get() { + switch (OperatingSystem.current()) { + case WINDOWS -> { + return FileChannelLockPathDeletionPreventer.INSTANCE; + } + default -> { + return ReadOnlyDirectoryPathDeletionPreventer.INSTANCE; + } + } + } + + }.get(); +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/TempDirectoryTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/TempDirectoryTest.java new file mode 100644 index 00000000000..221e7d9f433 --- /dev/null +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/TempDirectoryTest.java @@ -0,0 +1,570 @@ +/* + * 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 jdk.jpackage.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Stream; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.cli.Options; +import jdk.jpackage.internal.cli.StandardOption; +import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.RetryExecutor; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingSupplier; +import jdk.jpackage.test.PathDeletionPreventer; +import jdk.jpackage.test.PathDeletionPreventer.ReadOnlyDirectoryPathDeletionPreventer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; + +public class TempDirectoryTest { + + @Test + void test_directory_use(@TempDir Path tempDirPath) throws IOException { + try (var tempDir = new TempDirectory(Optional.of(tempDirPath), RetryExecutorFactory.DEFAULT)) { + assertEquals(tempDir.path(), tempDirPath); + assertFalse(tempDir.deleteOnClose()); + + var cmdline = Options.of(Map.of()); + assertSame(cmdline, tempDir.map(cmdline)); + } + + assertTrue(Files.isDirectory(tempDirPath)); + } + + @Test + void test_directory_new() throws IOException { + var tempDir = new TempDirectory(Optional.empty(), RetryExecutorFactory.DEFAULT); + try (tempDir) { + assertTrue(Files.isDirectory(tempDir.path())); + assertTrue(tempDir.deleteOnClose()); + + var cmdline = Options.of(Map.of()); + var mappedCmdline = tempDir.map(cmdline); + assertEquals(tempDir.path(), StandardOption.TEMP_ROOT.getFrom(mappedCmdline)); + } + + assertFalse(Files.isDirectory(tempDir.path())); + } + + @SuppressWarnings("try") + @ParameterizedTest + @MethodSource + void test_close(CloseType closeType, @TempDir Path root) { + Globals.main(ThrowingSupplier.toSupplier(() -> { + test_close_impl(closeType, root); + return 0; + })); + } + + @ParameterizedTest + @MethodSource + void test_DirectoryListing_listFilesAndEmptyDirectories( + ListFilesAndEmptyDirectoriesTestSpec test, @TempDir Path root) throws IOException { + test.run(root); + } + + @Test + void test_DirectoryListing_listFilesAndEmptyDirectories_negative(@TempDir Path root) throws IOException { + assertThrowsExactly(IllegalArgumentException.class, () -> { + TempDirectory.DirectoryListing.listFilesAndEmptyDirectories(root, -1); + }); + } + + @ParameterizedTest + @CsvSource({"100", "101", "1", "0"}) + void test_DirectoryListing_listFilesAndEmptyDirectories_nonexistent(int limit, @TempDir Path root) throws IOException { + + var path = root.resolve("foo"); + + var listing = TempDirectory.DirectoryListing.listFilesAndEmptyDirectories(path, limit); + assertTrue(listing.complete()); + + List expected; + if (limit == 0) { + expected = List.of(); + } else { + expected = List.of(path); + } + assertEquals(expected, listing.paths()); + } + + private static Stream test_close() { + switch (PathDeletionPreventer.DEFAULT.implementation()) { + case READ_ONLY_NON_EMPTY_DIRECTORY -> { + return Stream.of(CloseType.values()); + } + default -> { + return Stream.of(CloseType.values()) + .filter(Predicate.not(Set.of( + CloseType.FAIL_NO_LEFTOVER_FILES, + CloseType.FAIL_NO_LEFTOVER_FILES_VERBOSE)::contains)); + } + } + } + + @SuppressWarnings({ "try" }) + private void test_close_impl(CloseType closeType, Path root) throws IOException { + var logSink = new StringWriter(); + var logPrintWriter = new PrintWriter(logSink, true); + Globals.instance().loggerOutputStreams(logPrintWriter, logPrintWriter); + if (closeType.isVerbose()) { + Globals.instance().loggerVerbose(); + } + + final var workDir = root.resolve("workdir"); + Files.createDirectories(workDir); + + final Path leftoverPath; + final TempDirectory tempDir; + + switch (closeType) { + case FAIL_NO_LEFTOVER_FILES_VERBOSE, FAIL_NO_LEFTOVER_FILES -> { + leftoverPath = workDir; + tempDir = new TempDirectory(workDir, true, new RetryExecutorFactory() { + @Override + public RetryExecutor retryExecutor(Class exceptionType) { + return new RetryExecutor(exceptionType).setSleepFunction(_ -> {}); + } + }); + + // Lock the parent directory of the work directory and don't create any files in the work directory. + // This should trigger the error message about the failure to delete the empty work directory. + try (var lockWorkDir = ReadOnlyDirectoryPathDeletionPreventer.INSTANCE.preventPathDeletion(workDir.getParent())) { + tempDir.close(); + } + } + default -> { + Files.createFile(workDir.resolve("b")); + + final var lockedPath = workDir.resolve("a"); + switch (PathDeletionPreventer.DEFAULT.implementation()) { + case FILE_CHANNEL_LOCK -> { + Files.createFile(lockedPath); + leftoverPath = lockedPath; + } + case READ_ONLY_NON_EMPTY_DIRECTORY -> { + Files.createDirectories(lockedPath); + leftoverPath = lockedPath.resolve("a"); + Files.createFile(leftoverPath); + } + default -> { + throw new AssertionError(); + } + } + + tempDir = new TempDirectory(workDir, true, new RetryExecutorFactory() { + @Override + public RetryExecutor retryExecutor(Class exceptionType) { + var config = new RetryExecutorMock.Config(lockedPath, closeType.isSuccess()); + return new RetryExecutorMock<>(exceptionType, config); + } + }); + + tempDir.close(); + } + } + + logPrintWriter.flush(); + var logMessages = new BufferedReader(new StringReader(logSink.toString())).lines().toList(); + + assertTrue(Files.isDirectory(root)); + + if (closeType.isSuccess()) { + assertFalse(Files.exists(tempDir.path())); + assertEquals(List.of(), logMessages); + } else { + assertTrue(Files.isDirectory(tempDir.path())); + assertTrue(Files.exists(leftoverPath)); + assertFalse(Files.exists(tempDir.path().resolve("b"))); + + String errMessage; + switch (closeType) { + case FAIL_SOME_LEFTOVER_FILES_VERBOSE, FAIL_SOME_LEFTOVER_FILES -> { + errMessage = "warning.tempdir.cleanup-file-failed"; + } + case FAIL_NO_LEFTOVER_FILES_VERBOSE, FAIL_NO_LEFTOVER_FILES -> { + errMessage = "warning.tempdir.cleanup-failed"; + } + default -> { + throw new AssertionError(); + } + } + assertEquals(List.of(I18N.format(errMessage, leftoverPath)), logMessages.subList(0, 1)); + + if (closeType.isVerbose()) { + // Check the log contains a stacktrace + assertNotEquals(1, logMessages.size()); + } + FileUtils.deleteRecursive(tempDir.path()); + } + } + + private static Collection test_DirectoryListing_listFilesAndEmptyDirectories() { + + var testCases = new ArrayList(); + + Supplier builder = ListFilesAndEmptyDirectoriesTestSpec::build; + + Stream.of( + builder.get().dirs("").complete(), + builder.get().dirs("").limit(0), + builder.get().dirs("foo").complete(), + builder.get().dirs("foo").limit(0), + builder.get().dirs("foo").limit(1).complete(), + builder.get().dirs("foo").limit(2).complete(), + builder.get().dirs("a/b/c").files("foo").files("b/b", "b/c").complete(), + builder.get().dirs("a/b/c").files("foo").files("b/b", "b/c").limit(4).complete(), + builder.get().dirs("a/b/c").files("foo").files("b/b", "b/c").limit(3) + ).map(ListFilesAndEmptyDirectoriesTestSpec.Builder::create).forEach(testCases::add); + + if (!OperatingSystem.isWindows()) { + Stream.of( + // A directory with the sibling symlink pointing to this directory + builder.get().dirs("foo").symlink("foo-symlink", "foo").complete(), + // A file with the sibling symlink pointing to this file + builder.get().symlink("foo-symlink", "foo").files("foo").complete(), + // A dangling symlink + builder.get().nonexistent("foo/bar/buz").symlink("dangling-symlink", "foo/bar/buz").complete() + ).map(ListFilesAndEmptyDirectoriesTestSpec.Builder::create).forEach(testCases::add); + } + + return testCases; + } + + enum CloseType { + SUCCEED, + FAIL_SOME_LEFTOVER_FILES, + FAIL_SOME_LEFTOVER_FILES_VERBOSE, + FAIL_NO_LEFTOVER_FILES, + FAIL_NO_LEFTOVER_FILES_VERBOSE, + ; + + boolean isSuccess() { + return this == SUCCEED; + } + + boolean isVerbose() { + return name().endsWith("_VERBOSE"); + } + } + + private static final class RetryExecutorMock extends RetryExecutor { + + RetryExecutorMock(Class exceptionType, Config config) { + super(exceptionType); + setSleepFunction(_ -> {}); + this.config = Objects.requireNonNull(config); + } + + @SuppressWarnings({ "try", "unchecked" }) + @Override + public RetryExecutor setExecutable(ThrowingFunction>, T, E> v) { + return super.setExecutable(context -> { + if (context.isLastAttempt() && config.unlockOnLastAttempt()) { + return v.apply(context); + } else { + try (var lock = PathDeletionPreventer.DEFAULT.preventPathDeletion(config.lockedPath())) { + return v.apply(context); + } catch (IOException ex) { + if (exceptionType().isInstance(ex)) { + throw (E)ex; + } else { + throw new AssertionError(); + } + } + } + }); + }; + + private final Config config; + + record Config(Path lockedPath, boolean unlockOnLastAttempt) { + Config { + Objects.requireNonNull(lockedPath); + } + } + } + + sealed interface FileSpec extends Comparable { + Path path(); + Path create(Path root) throws IOException; + public default int compareTo(FileSpec other) { + return path().compareTo(other.path()); + } + + static File file(Path path) { + return new File(path); + } + + static Directory dir(Path path) { + return new Directory(path); + } + + static Nonexistent nonexistent(Path path) { + return new Nonexistent(path); + } + + static Symlink symlink(Path path, FileSpec target) { + return new Symlink(path, target); + } + }; + + record File(Path path) implements FileSpec { + File { + path = normalizePath(path); + if (path.getNameCount() == 0) { + throw new IllegalArgumentException(); + } + } + + @Override + public Path create(Path root) throws IOException { + var resolvedPath = root.resolve(path); + if (!Files.isRegularFile(resolvedPath)) { + Files.createDirectories(resolvedPath.getParent()); + Files.createFile(resolvedPath); + } + return resolvedPath; + } + + @Override + public String toString() { + return String.format("f:%s", path); + } + } + + record Nonexistent(Path path) implements FileSpec { + Nonexistent { + path = normalizePath(path); + if (path.getNameCount() == 0) { + throw new IllegalArgumentException(); + } + } + + @Override + public Path create(Path root) throws IOException { + return root.resolve(path); + } + + @Override + public String toString() { + return String.format("x:%s", path); + } + } + + record Symlink(Path path, FileSpec target) implements FileSpec { + Symlink { + path = normalizePath(path); + if (path.getNameCount() == 0) { + throw new IllegalArgumentException(); + } + Objects.requireNonNull(target); + } + + @Override + public Path create(Path root) throws IOException { + var resolvedPath = root.resolve(path); + var targetPath = target.create(root); + Files.createDirectories(resolvedPath.getParent()); + return Files.createSymbolicLink(resolvedPath, targetPath); + } + + @Override + public String toString() { + return String.format("s:%s->%s", path, target); + } + } + + record Directory(Path path) implements FileSpec { + Directory { + path = normalizePath(path); + } + + @Override + public Path create(Path root) throws IOException { + return Files.createDirectories(root.resolve(path)); + } + + @Override + public String toString() { + return String.format("d:%s", path); + } + } + + private static Path normalizePath(Path path) { + path = path.normalize(); + if (path.isAbsolute()) { + throw new IllegalArgumentException(); + } + return path; + } + + private record ListFilesAndEmptyDirectoriesTestSpec(Set input, int limit, boolean complete) { + + ListFilesAndEmptyDirectoriesTestSpec { + Objects.requireNonNull(input); + + if (!(input instanceof SortedSet)) { + input = new TreeSet<>(input); + } + } + + static Builder build() { + return new Builder(); + } + + static final class Builder { + + ListFilesAndEmptyDirectoriesTestSpec create() { + return new ListFilesAndEmptyDirectoriesTestSpec(Set.copyOf(input), limit, complete); + } + + Builder files(String... paths) { + Stream.of(paths).map(Path::of).map(FileSpec::file).forEach(input::add); + return this; + } + + Builder dirs(String... paths) { + Stream.of(paths).map(Path::of).map(FileSpec::dir).forEach(input::add); + return this; + } + + Builder nonexistent(String... paths) { + Stream.of(paths).map(Path::of).map(FileSpec::nonexistent).forEach(input::add); + return this; + } + + Builder symlink(String path, String target) { + Objects.requireNonNull(target); + + var targetSpec = input.stream().filter(v -> { + return v.path().equals(Path.of(target)); + }).findFirst(); + + if (targetSpec.isEmpty()) { + var v = FileSpec.file(Path.of(target)); + input.add(v); + targetSpec = Optional.ofNullable(v); + } + + input.add(FileSpec.symlink(Path.of(path), targetSpec.get())); + + return this; + } + + Builder limit(int v) { + limit = v; + return this; + } + + Builder complete(boolean v) { + complete = v; + return this; + } + + Builder complete() { + return complete(true); + } + + private final Set input = new HashSet<>(); + private int limit = Integer.MAX_VALUE; + private boolean complete; + } + + void run(Path root) throws IOException { + for (var v : input) { + v.create(root); + } + + for (var v : input) { + Predicate validator; + switch (v) { + case File _ -> { + validator = Files::isRegularFile; + } + case Directory _ -> { + validator = Files::isDirectory; + } + case Symlink _ -> { + validator = Files::isSymbolicLink; + } + case Nonexistent _ -> { + validator = Predicate.not(Files::exists); + } + } + assertTrue(validator.test(root.resolve(v.path()))); + } + + var listing = TempDirectory.DirectoryListing.listFilesAndEmptyDirectories(root, limit); + assertEquals(complete, listing.complete()); + + if (complete) { + var actual = listing.paths().stream().peek(p -> { + assertTrue(p.startsWith(root)); + }).map(root::relativize).sorted().toList(); + var expected = input.stream() + .filter(Predicate.not(Nonexistent.class::isInstance)) + .map(FileSpec::path) + .sorted() + .toList(); + assertEquals(expected, actual); + } else { + assertEquals(limit, listing.paths().size()); + } + } + + @Override + public String toString() { + return String.format("%s; limit=%d; complete=%s", input, limit, complete); + } + } +} From 36d67ffd0188070d0fb087beffece15fea4ba956 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 25 Feb 2026 20:09:48 +0000 Subject: [PATCH 03/54] 6434110: Color constructor parameter name is misleading Reviewed-by: prr, aivanov --- .../share/classes/java/awt/Color.java | 57 +++++++++------- .../ColorClass/ColorARGBConstructorTest.java | 66 +++++++++++++++++++ 2 files changed, 100 insertions(+), 23 deletions(-) create mode 100644 test/jdk/java/awt/ColorClass/ColorARGBConstructorTest.java diff --git a/src/java.desktop/share/classes/java/awt/Color.java b/src/java.desktop/share/classes/java/awt/Color.java index 923afb91866..e129cbae23a 100644 --- a/src/java.desktop/share/classes/java/awt/Color.java +++ b/src/java.desktop/share/classes/java/awt/Color.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -334,7 +334,7 @@ public class Color implements Paint, java.io.Serializable { * The actual color used in rendering depends * on finding the best match given the color space * available for a given output device. - * Alpha is defaulted to 255. + * Alpha defaults to 255. * * @throws IllegalArgumentException if {@code r}, {@code g} * or {@code b} are outside of the range @@ -378,12 +378,15 @@ public class Color implements Paint, java.io.Serializable { } /** - * Creates an opaque sRGB color with the specified combined RGB value - * consisting of the red component in bits 16-23, the green component - * in bits 8-15, and the blue component in bits 0-7. The actual color - * used in rendering depends on finding the best match given the - * color space available for a particular output device. Alpha is - * defaulted to 255. + * Creates an opaque sRGB color with the specified RGB value consisting of + *

    + *
  • the red component in bits 16-23, + *
  • the green component in bits 8-15, and + *
  • the blue component in bits 0-7. + *
+ * The actual color used in rendering depends on finding the best match + * given the color space available for a particular output device. Alpha + * defaults to 255. * * @param rgb the combined RGB components * @see java.awt.image.ColorModel#getRGBdefault @@ -397,14 +400,17 @@ public class Color implements Paint, java.io.Serializable { } /** - * Creates an sRGB color with the specified combined RGBA value consisting - * of the alpha component in bits 24-31, the red component in bits 16-23, - * the green component in bits 8-15, and the blue component in bits 0-7. - * If the {@code hasalpha} argument is {@code false}, alpha - * is defaulted to 255. + * Creates an sRGB color with the specified ARGB value consisting of + *
    + *
  • the alpha component in bits 24-31, + *
  • the red component in bits 16-23, + *
  • the green component in bits 8-15, and + *
  • the blue component in bits 0-7. + *
+ * If the {@code hasAlpha} argument is {@code false}, alpha defaults to 255. * - * @param rgba the combined RGBA components - * @param hasalpha {@code true} if the alpha bits are valid; + * @param argb the combined ARGB components + * @param hasAlpha {@code true} if the alpha bits are valid; * {@code false} otherwise * @see java.awt.image.ColorModel#getRGBdefault * @see #getRed @@ -413,17 +419,17 @@ public class Color implements Paint, java.io.Serializable { * @see #getAlpha * @see #getRGB */ - public Color(int rgba, boolean hasalpha) { - if (hasalpha) { - value = rgba; + public Color(int argb, boolean hasAlpha) { + if (hasAlpha) { + value = argb; } else { - value = 0xff000000 | rgba; + value = 0xff000000 | argb; } } /** * Creates an opaque sRGB color with the specified red, green, and blue - * values in the range (0.0 - 1.0). Alpha is defaulted to 1.0. The + * values in the range (0.0 - 1.0). Alpha defaults to 1.0. The * actual color used in rendering depends on finding the best * match given the color space available for a particular output * device. @@ -570,9 +576,14 @@ public class Color implements Paint, java.io.Serializable { /** * Returns the RGB value representing the color in the default sRGB - * {@link ColorModel}. - * (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are - * blue). + * {@link ColorModel}, consisting of + *
    + *
  • the alpha component in bits 24-31, + *
  • the red component in bits 16-23, + *
  • the green component in bits 8-15, and + *
  • the blue component in bits 0-7. + *
+ * * @return the RGB value of the color in the default sRGB * {@code ColorModel}. * @see java.awt.image.ColorModel#getRGBdefault diff --git a/test/jdk/java/awt/ColorClass/ColorARGBConstructorTest.java b/test/jdk/java/awt/ColorClass/ColorARGBConstructorTest.java new file mode 100644 index 00000000000..3464e2057b9 --- /dev/null +++ b/test/jdk/java/awt/ColorClass/ColorARGBConstructorTest.java @@ -0,0 +1,66 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * 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.awt.Color; + +/** + * @test + * @bug 6434110 + * @summary Verify Color(int, boolean) constructor uses ARGB bit layout + */ +public final class ColorARGBConstructorTest { + + public static void main(String[] args) { + for (int argb : new int[]{0x00000000, 0x01020304, 0xC0903020, + 0x40302010, 0xD08040C0, 0x80000000, + 0x7FFFFFFF, 0xFFFFFFFF, 0xFF000000, + 0x00FF0000, 0x0000FF00, 0x000000FF}) + { + verify(argb, true); + verify(argb, false); + } + } + + private static void verify(int argb, boolean hasAlpha) { + var c = new Color(argb, hasAlpha); + int expRGB = hasAlpha ? argb : (0xFF000000 | argb); + int expA = hasAlpha ? (argb >>> 24) : 0xFF; + int expR = (argb >> 16) & 0xFF; + int expG = (argb >> 8) & 0xFF; + int expB = argb & 0xFF; + check("RGB", expRGB, c.getRGB(), argb, hasAlpha); + check("Alpha", expA, c.getAlpha(), argb, hasAlpha); + check("Red", expR, c.getRed(), argb, hasAlpha); + check("Green", expG, c.getGreen(), argb, hasAlpha); + check("Blue", expB, c.getBlue(), argb, hasAlpha); + } + + private static void check(String comp, int exp, int got, int argb, + boolean hasAlpha) + { + if (exp != got) { + throw new RuntimeException("0x%08X(%b) %s: 0x%08X != 0x%08X" + .formatted(argb, hasAlpha, comp, exp, got)); + } + } +} From 8ba3de98340dc66fee76a77f2d4721684b618916 Mon Sep 17 00:00:00 2001 From: David Holmes Date: Wed, 25 Feb 2026 20:11:51 +0000 Subject: [PATCH 04/54] 8377948: The ThreadWXEnable use of PerfTraceTime is not safe during VM shutdown Reviewed-by: aph, aartemov, fbredberg --- src/hotspot/share/runtime/perfData.hpp | 27 +++++++++++++++++-- src/hotspot/share/runtime/perfData.inline.hpp | 22 ++++++++++++++- .../share/runtime/threadWXSetters.inline.hpp | 7 +++-- 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/runtime/perfData.hpp b/src/hotspot/share/runtime/perfData.hpp index ca1f1f410ad..d910f8662fe 100644 --- a/src/hotspot/share/runtime/perfData.hpp +++ b/src/hotspot/share/runtime/perfData.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -716,7 +716,7 @@ class PerfDataManager : AllStatic { // Utility Classes /* - * this class will administer a PerfCounter used as a time accumulator + * This class will administer a PerfCounter used as a time accumulator * for a basic block much like the TraceTime class. * * Example: @@ -731,6 +731,9 @@ class PerfDataManager : AllStatic { * Note: use of this class does not need to occur within a guarded * block. The UsePerfData guard is used with the implementation * of this class. + * + * But also note this class does not guard against shutdown races - + * see SafePerfTraceTime below. */ class PerfTraceTime : public StackObj { @@ -756,6 +759,26 @@ class PerfTraceTime : public StackObj { } }; +/* A variant of PerfTraceTime that guards against use during shutdown - + * see PerfDataManager::destroy. + */ +class SafePerfTraceTime : public StackObj { + + protected: + elapsedTimer _t; + PerfLongCounter* _timerp; + + public: + inline SafePerfTraceTime(PerfLongCounter* timerp); + + const char* name() const { + assert(_timerp != nullptr, "sanity"); + return _timerp->name(); + } + + inline ~SafePerfTraceTime(); +}; + /* The PerfTraceTimedEvent class is responsible for counting the * occurrence of some event and measuring the elapsed time of * the event in two separate PerfCounter instances. diff --git a/src/hotspot/share/runtime/perfData.inline.hpp b/src/hotspot/share/runtime/perfData.inline.hpp index 5212691b924..ca0b27e25bc 100644 --- a/src/hotspot/share/runtime/perfData.inline.hpp +++ b/src/hotspot/share/runtime/perfData.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -27,6 +27,7 @@ #include "runtime/perfData.hpp" +#include "utilities/globalCounter.inline.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/growableArray.hpp" @@ -50,4 +51,23 @@ inline bool PerfDataManager::exists(const char* name) { } } +inline SafePerfTraceTime::SafePerfTraceTime(PerfLongCounter* timerp) : _timerp(timerp) { + GlobalCounter::CriticalSection cs(Thread::current()); + if (!UsePerfData || !PerfDataManager::has_PerfData() || timerp == nullptr) { + return; + } + _t.start(); +} + +inline SafePerfTraceTime::~SafePerfTraceTime() { + GlobalCounter::CriticalSection cs(Thread::current()); + if (!UsePerfData || !PerfDataManager::has_PerfData() || !_t.is_active()) { + return; + } + + _t.stop(); + _timerp->inc(_t.ticks()); +} + + #endif // SHARE_RUNTIME_PERFDATA_INLINE_HPP diff --git a/src/hotspot/share/runtime/threadWXSetters.inline.hpp b/src/hotspot/share/runtime/threadWXSetters.inline.hpp index e7e37fcde1b..87f8d38e4dc 100644 --- a/src/hotspot/share/runtime/threadWXSetters.inline.hpp +++ b/src/hotspot/share/runtime/threadWXSetters.inline.hpp @@ -42,7 +42,7 @@ class ThreadWXEnable { public: ThreadWXEnable(WXMode* new_mode, Thread* thread) : _thread(thread), _this_wx_mode(new_mode) { - NOT_PRODUCT(PerfTraceTime ptt(ClassLoader::perf_change_wx_time());) + NOT_PRODUCT(SafePerfTraceTime ptt(ClassLoader::perf_change_wx_time());) JavaThread* javaThread = _thread && _thread->is_Java_thread() ? JavaThread::cast(_thread) : nullptr; @@ -55,7 +55,7 @@ public: } ThreadWXEnable(WXMode new_mode, Thread* thread) : _thread(thread), _this_wx_mode(nullptr) { - NOT_PRODUCT(PerfTraceTime ptt(ClassLoader::perf_change_wx_time());) + NOT_PRODUCT(SafePerfTraceTime ptt(ClassLoader::perf_change_wx_time());) JavaThread* javaThread = _thread && _thread->is_Java_thread() ? JavaThread::cast(_thread) : nullptr; @@ -68,7 +68,7 @@ public: } ~ThreadWXEnable() { - NOT_PRODUCT(PerfTraceTime ptt(ClassLoader::perf_change_wx_time());) + NOT_PRODUCT(SafePerfTraceTime ptt(ClassLoader::perf_change_wx_time());) if (_thread) { _thread->enable_wx(_old_mode); JavaThread* javaThread @@ -86,4 +86,3 @@ public: #endif // MACOS_AARCH64 #endif // SHARE_RUNTIME_THREADWXSETTERS_INLINE_HPP - From 32cc7f1f57aff093841d071b658a09b83f16ef2e Mon Sep 17 00:00:00 2001 From: Yasumasa Suenaga Date: Wed, 25 Feb 2026 23:02:07 +0000 Subject: [PATCH 05/54] 8377947: Test serviceability/sa/TestJhsdbJstackMixedCore.java failed on linux-x64 Reviewed-by: cjplummer, kevinw --- .../linux/native/libsaproc/DwarfParser.cpp | 4 +- .../linux/native/libsaproc/dwarf.cpp | 81 +++++++++++-------- .../linux/native/libsaproc/dwarf.hpp | 37 ++++----- 3 files changed, 64 insertions(+), 58 deletions(-) diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/DwarfParser.cpp b/src/jdk.hotspot.agent/linux/native/libsaproc/DwarfParser.cpp index 6c94992e1e2..62dbc84f88c 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/DwarfParser.cpp +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/DwarfParser.cpp @@ -205,7 +205,7 @@ extern "C" JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_linux_amd64_DwarfParser_getReturnAddressOffsetFromCFA (JNIEnv *env, jobject this_obj) { DwarfParser *parser = reinterpret_cast(get_dwarf_context(env, this_obj)); - return parser->get_ra_cfa_offset(); + return parser->get_offset_from_cfa(RA); } /* @@ -217,5 +217,5 @@ extern "C" JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_linux_amd64_DwarfParser_getBasePointerOffsetFromCFA (JNIEnv *env, jobject this_obj) { DwarfParser *parser = reinterpret_cast(get_dwarf_context(env, this_obj)); - return parser->get_bp_cfa_offset(); + return parser->get_offset_from_cfa(RBP); } diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp b/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp index 2636bdf691a..459e3cc57e9 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp @@ -24,10 +24,32 @@ */ #include +#include #include "dwarf.hpp" #include "libproc_impl.h" +DwarfParser::DwarfParser(lib_info *lib) : _lib(lib), + _buf(NULL), + _encoding(0), + _code_factor(0), + _data_factor(0), + _current_pc(0L) { + init_state(_initial_state); + init_state(_state); +} + +void DwarfParser::init_state(struct DwarfState& st) { + st.cfa_reg = MAX_VALUE; + st.return_address_reg = MAX_VALUE; + st.cfa_offset = 0; + + st.offset_from_cfa.clear(); + for (int reg = 0; reg < MAX_VALUE; reg++) { + st.offset_from_cfa[static_cast(reg)] = INT_MAX; + } +} + /* from read_leb128() in dwarf.c in binutils */ uintptr_t DwarfParser::read_leb(bool sign) { uintptr_t result = 0L; @@ -82,7 +104,7 @@ bool DwarfParser::process_cie(unsigned char *start_of_entry, uint32_t id) { _code_factor = read_leb(false); _data_factor = static_cast(read_leb(true)); - _return_address_reg = static_cast(*_buf++); + enum DWARF_Register initial_ra = static_cast(*_buf++); if (strpbrk(augmentation_string, "LP") != NULL) { // Language personality routine (P) and Language Specific Data Area (LSDA:L) @@ -99,14 +121,12 @@ bool DwarfParser::process_cie(unsigned char *start_of_entry, uint32_t id) { // Clear state _current_pc = 0L; - _cfa_reg = MAX_VALUE; - _return_address_reg = RA; - _cfa_offset = 0; - _ra_cfa_offset = 8; - _bp_cfa_offset = INT_MAX; + init_state(_state); + _state.return_address_reg = initial_ra; parse_dwarf_instructions(0L, static_cast(-1L), end); + _initial_state = _state; _buf = orig_pos; return true; } @@ -114,12 +134,7 @@ bool DwarfParser::process_cie(unsigned char *start_of_entry, uint32_t id) { void DwarfParser::parse_dwarf_instructions(uintptr_t begin, uintptr_t pc, const unsigned char *end) { uintptr_t operand1; _current_pc = begin; - - /* for remember state */ - enum DWARF_Register rem_cfa_reg = MAX_VALUE; - int rem_cfa_offset = 0; - int rem_ra_cfa_offset = 8; - int rem_bp_cfa_offset = INT_MAX; + std::stack remember_state; while ((_buf < end) && (_current_pc < pc)) { unsigned char op = *_buf++; @@ -138,21 +153,17 @@ void DwarfParser::parse_dwarf_instructions(uintptr_t begin, uintptr_t pc, const } break; case 0x0c: // DW_CFA_def_cfa - _cfa_reg = static_cast(read_leb(false)); - _cfa_offset = read_leb(false); + _state.cfa_reg = static_cast(read_leb(false)); + _state.cfa_offset = read_leb(false); break; case 0x80: {// DW_CFA_offset operand1 = read_leb(false); enum DWARF_Register reg = static_cast(opa); - if (reg == RBP) { - _bp_cfa_offset = operand1 * _data_factor; - } else if (reg == RA) { - _ra_cfa_offset = operand1 * _data_factor; - } + _state.offset_from_cfa[reg] = operand1 * _data_factor; break; } case 0xe: // DW_CFA_def_cfa_offset - _cfa_offset = read_leb(false); + _state.cfa_offset = read_leb(false); break; case 0x40: // DW_CFA_advance_loc if (_current_pc != 0L) { @@ -184,28 +195,28 @@ void DwarfParser::parse_dwarf_instructions(uintptr_t begin, uintptr_t pc, const } case 0x07: { // DW_CFA_undefined enum DWARF_Register reg = static_cast(read_leb(false)); - // We are only interested in BP here because CFA and RA should not be undefined. - if (reg == RBP) { - _bp_cfa_offset = INT_MAX; - } + _state.offset_from_cfa[reg] = INT_MAX; break; } - case 0x0d: {// DW_CFA_def_cfa_register - _cfa_reg = static_cast(read_leb(false)); + case 0x0d: // DW_CFA_def_cfa_register + _state.cfa_reg = static_cast(read_leb(false)); break; - } case 0x0a: // DW_CFA_remember_state - rem_cfa_reg = _cfa_reg; - rem_cfa_offset = _cfa_offset; - rem_ra_cfa_offset = _ra_cfa_offset; - rem_bp_cfa_offset = _bp_cfa_offset; + remember_state.push(_state); break; case 0x0b: // DW_CFA_restore_state - _cfa_reg = rem_cfa_reg; - _cfa_offset = rem_cfa_offset; - _ra_cfa_offset = rem_ra_cfa_offset; - _bp_cfa_offset = rem_bp_cfa_offset; + if (remember_state.empty()) { + print_debug("DWARF Error: DW_CFA_restore_state with empty stack.\n"); + return; + } + _state = remember_state.top(); + remember_state.pop(); break; + case 0xc0: {// DW_CFA_restore + enum DWARF_Register reg = static_cast(opa); + _state.offset_from_cfa[reg] = _initial_state.offset_from_cfa[reg]; + break; + } default: print_debug("DWARF: Unknown opcode: 0x%x\n", op); return; diff --git a/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.hpp b/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.hpp index a2692738ce1..0a38c9a0f2e 100644 --- a/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.hpp +++ b/src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.hpp @@ -26,6 +26,8 @@ #ifndef _DWARF_HPP_ #define _DWARF_HPP_ +#include + #include "libproc_impl.h" /* @@ -55,6 +57,13 @@ enum DWARF_Register { MAX_VALUE }; +struct DwarfState { + enum DWARF_Register cfa_reg; + enum DWARF_Register return_address_reg; + int cfa_offset; + std::map offset_from_cfa; +}; + /* * DwarfParser finds out CFA (Canonical Frame Address) from DWARF in ELF binary. * Also Return Address (RA) and Base Pointer (BP) are calculated from CFA. @@ -64,16 +73,14 @@ class DwarfParser { const lib_info *_lib; unsigned char *_buf; unsigned char _encoding; - enum DWARF_Register _cfa_reg; - enum DWARF_Register _return_address_reg; unsigned int _code_factor; int _data_factor; uintptr_t _current_pc; - int _cfa_offset; - int _ra_cfa_offset; - int _bp_cfa_offset; + struct DwarfState _initial_state; + struct DwarfState _state; + void init_state(struct DwarfState& st); uintptr_t read_leb(bool sign); uint64_t get_entry_length(); bool process_cie(unsigned char *start_of_entry, uint32_t id); @@ -82,24 +89,12 @@ class DwarfParser { unsigned int get_pc_range(); public: - DwarfParser(lib_info *lib) : _lib(lib), - _buf(NULL), - _encoding(0), - _cfa_reg(MAX_VALUE), - _return_address_reg(RA), - _code_factor(0), - _data_factor(0), - _current_pc(0L), - _cfa_offset(0), - _ra_cfa_offset(8), - _bp_cfa_offset(INT_MAX) {}; - + DwarfParser(lib_info *lib); ~DwarfParser() {} bool process_dwarf(const uintptr_t pc); - enum DWARF_Register get_cfa_register() { return _cfa_reg; } - int get_cfa_offset() { return _cfa_offset; } - int get_ra_cfa_offset() { return _ra_cfa_offset; } - int get_bp_cfa_offset() { return _bp_cfa_offset; } + enum DWARF_Register get_cfa_register() { return _state.cfa_reg; } + int get_cfa_offset() { return _state.cfa_offset; } + int get_offset_from_cfa(enum DWARF_Register reg) { return _state.offset_from_cfa[reg]; } bool is_in(long pc) { return (_lib->exec_start <= pc) && (pc < _lib->exec_end); From abec2124281bd9ffb3c3126b66b7b45dc4d88a79 Mon Sep 17 00:00:00 2001 From: Xiaolong Peng Date: Thu, 26 Feb 2026 00:24:46 +0000 Subject: [PATCH 06/54] 8377011: Shenandoah: assert_bounds should be only called when boundaries have changed Reviewed-by: wkemper, kdnilsen --- .../share/gc/shenandoah/shenandoahFreeSet.cpp | 32 +++++++++++++++---- .../share/gc/shenandoah/shenandoahFreeSet.hpp | 3 ++ test/hotspot/jtreg/ProblemList.txt | 3 -- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp index c4fe9103fcb..961800f20d9 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.cpp @@ -1194,6 +1194,18 @@ void ShenandoahRegionPartitions::assert_bounds() { assert(_humongous_waste[int(ShenandoahFreeSetPartitionId::Mutator)] == young_humongous_waste, "Mutator humongous waste must match"); } + +inline void ShenandoahRegionPartitions::assert_bounds_sanity() { + for (uint8_t i = 0; i < UIntNumPartitions; i++) { + ShenandoahFreeSetPartitionId partition = static_cast(i); + assert(leftmost(partition) == _max || membership(leftmost(partition)) == partition, "Left most boundry must be sane"); + assert(rightmost(partition) == -1 || membership(rightmost(partition)) == partition, "Right most boundry must be sane"); + + assert(leftmost_empty(partition) == _max || leftmost_empty(partition) >= leftmost(partition), "Left most empty must be sane"); + assert(rightmost_empty(partition) == -1 || rightmost_empty(partition) <= rightmost(partition), "Right most empty must be sane"); + } +} + #endif ShenandoahFreeSet::ShenandoahFreeSet(ShenandoahHeap* heap, size_t max_regions) : @@ -1654,6 +1666,12 @@ HeapWord* ShenandoahFreeSet::try_allocate_in(ShenandoahHeapRegion* r, Shenandoah // Not old collector alloc, so this is a young collector gclab or shared allocation orig_partition = ShenandoahFreeSetPartitionId::Collector; } + DEBUG_ONLY(bool boundary_changed = false;) + if ((result != nullptr) && in_new_region) { + _partitions.one_region_is_no_longer_empty(orig_partition); + DEBUG_ONLY(boundary_changed = true;) + } + if (alloc_capacity(r) < PLAB::min_size() * HeapWordSize) { // Regardless of whether this allocation succeeded, if the remaining memory is less than PLAB:min_size(), retire this region. // Note that retire_from_partition() increases used to account for waste. @@ -1662,15 +1680,11 @@ HeapWord* ShenandoahFreeSet::try_allocate_in(ShenandoahHeapRegion* r, Shenandoah // then retire the region so that subsequent searches can find available memory more quickly. size_t idx = r->index(); - if ((result != nullptr) && in_new_region) { - _partitions.one_region_is_no_longer_empty(orig_partition); - } size_t waste_bytes = _partitions.retire_from_partition(orig_partition, idx, r->used()); + DEBUG_ONLY(boundary_changed = true;) if (req.is_mutator_alloc() && (waste_bytes > 0)) { increase_bytes_allocated(waste_bytes); } - } else if ((result != nullptr) && in_new_region) { - _partitions.one_region_is_no_longer_empty(orig_partition); } switch (orig_partition) { @@ -1711,7 +1725,13 @@ HeapWord* ShenandoahFreeSet::try_allocate_in(ShenandoahHeapRegion* r, Shenandoah default: assert(false, "won't happen"); } - _partitions.assert_bounds(); +#ifdef ASSERT + if (boundary_changed) { + _partitions.assert_bounds(); + } else { + _partitions.assert_bounds_sanity(); + } +#endif return result; } diff --git a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp index 4e0aea80a9b..91c6024d522 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp @@ -402,6 +402,9 @@ public: // idx <= rightmost // } void assert_bounds() NOT_DEBUG_RETURN; + // this checks certain sanity conditions related to the bounds with much less effort than is required to + // more rigorously enforce correctness as is done by assert_bounds() + inline void assert_bounds_sanity() NOT_DEBUG_RETURN; }; // Publicly, ShenandoahFreeSet represents memory that is available to mutator threads. The public capacity(), used(), diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index 09c0244addf..ba63f775223 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -96,9 +96,6 @@ gc/TestAllocHumongousFragment.java#g1 8298781 generic-all gc/TestAllocHumongousFragment.java#static 8298781 generic-all gc/shenandoah/oom/TestAllocOutOfMemory.java#large 8344312 linux-ppc64le gc/shenandoah/TestEvilSyncBug.java#generational 8345501 generic-all -gc/shenandoah/TestRetainObjects.java#no-tlab 8361099 generic-all -gc/shenandoah/TestSieveObjects.java#no-tlab 8361099 generic-all -gc/shenandoah/TestSieveObjects.java#no-tlab-genshen 8361099 generic-all ############################################################################# From d6044d3e280dc8bb988a6dd7ab6c9a65b1735608 Mon Sep 17 00:00:00 2001 From: Serguei Spitsyn Date: Thu, 26 Feb 2026 00:52:37 +0000 Subject: [PATCH 07/54] 8378194: Protect process_pending_interp_only() work with JvmtiThreadState_lock Reviewed-by: amenkov, lmesnik --- src/hotspot/share/prims/jvmtiThreadState.cpp | 5 +++-- src/hotspot/share/prims/jvmtiThreadState.hpp | 11 +++++++---- src/hotspot/share/prims/jvmtiThreadState.inline.hpp | 9 +++++++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/hotspot/share/prims/jvmtiThreadState.cpp b/src/hotspot/share/prims/jvmtiThreadState.cpp index f46feb95002..d7accfd9a0a 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.cpp +++ b/src/hotspot/share/prims/jvmtiThreadState.cpp @@ -51,7 +51,7 @@ static const int UNKNOWN_STACK_DEPTH = -99; // JvmtiThreadState *JvmtiThreadState::_head = nullptr; -bool JvmtiThreadState::_seen_interp_only_mode = false; +Atomic JvmtiThreadState::_seen_interp_only_mode{false}; JvmtiThreadState::JvmtiThreadState(JavaThread* thread, oop thread_oop) : _thread_event_enable() { @@ -321,13 +321,14 @@ void JvmtiThreadState::add_env(JvmtiEnvBase *env) { void JvmtiThreadState::enter_interp_only_mode() { assert(_thread != nullptr, "sanity check"); + assert(JvmtiThreadState_lock->is_locked(), "sanity check"); assert(!is_interp_only_mode(), "entering interp only when in interp only mode"); - _seen_interp_only_mode = true; _thread->set_interp_only_mode(true); invalidate_cur_stack_depth(); } void JvmtiThreadState::leave_interp_only_mode() { + assert(JvmtiThreadState_lock->is_locked(), "sanity check"); assert(is_interp_only_mode(), "leaving interp only when not in interp only mode"); if (_thread == nullptr) { // Unmounted virtual thread updates the saved value. diff --git a/src/hotspot/share/prims/jvmtiThreadState.hpp b/src/hotspot/share/prims/jvmtiThreadState.hpp index 43b568cf1fc..866d8828c4c 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.hpp +++ b/src/hotspot/share/prims/jvmtiThreadState.hpp @@ -181,7 +181,7 @@ class JvmtiThreadState : public CHeapObj { inline JvmtiEnvThreadState* head_env_thread_state(); inline void set_head_env_thread_state(JvmtiEnvThreadState* ets); - static bool _seen_interp_only_mode; // interp_only_mode was requested at least once + static Atomic _seen_interp_only_mode; // interp_only_mode was requested at least once public: ~JvmtiThreadState(); @@ -204,15 +204,18 @@ class JvmtiThreadState : public CHeapObj { // Return true if any thread has entered interp_only_mode at any point during the JVMs execution. static bool seen_interp_only_mode() { - return _seen_interp_only_mode; + return _seen_interp_only_mode.load_acquire(); } void add_env(JvmtiEnvBase *env); // The pending_interp_only_mode is set when the interp_only_mode is triggered. // It is cleared by EnterInterpOnlyModeClosure handshake. - bool is_pending_interp_only_mode() { return _pending_interp_only_mode; } - void set_pending_interp_only_mode(bool val) { _pending_interp_only_mode = val; } + bool is_pending_interp_only_mode() { return _pending_interp_only_mode; } + void set_pending_interp_only_mode(bool val) { + _seen_interp_only_mode.release_store(true); + _pending_interp_only_mode = val; + } // Used by the interpreter for fullspeed debugging support bool is_interp_only_mode() { diff --git a/src/hotspot/share/prims/jvmtiThreadState.inline.hpp b/src/hotspot/share/prims/jvmtiThreadState.inline.hpp index 2b060f1a2e4..831a2369a7e 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.inline.hpp +++ b/src/hotspot/share/prims/jvmtiThreadState.inline.hpp @@ -167,8 +167,13 @@ inline void JvmtiThreadState::bind_to(JvmtiThreadState* state, JavaThread* threa inline void JvmtiThreadState::process_pending_interp_only(JavaThread* current) { JvmtiThreadState* state = current->jvmti_thread_state(); - if (state != nullptr && state->is_pending_interp_only_mode()) { - JvmtiEventController::enter_interp_only_mode(state); + if (state != nullptr && seen_interp_only_mode()) { // avoid MutexLocker if possible + MutexLocker mu(JvmtiThreadState_lock); + if (state->is_pending_interp_only_mode()) { + assert(state->get_thread() == current, "sanity check"); + assert(!state->is_interp_only_mode(), "sanity check"); + JvmtiEventController::enter_interp_only_mode(state); + } } } #endif // SHARE_PRIMS_JVMTITHREADSTATE_INLINE_HPP From fd74232d5dc4c6bfbcddb82e1b2621289aa2f65a Mon Sep 17 00:00:00 2001 From: Jayathirth D V Date: Thu, 26 Feb 2026 03:32:19 +0000 Subject: [PATCH 08/54] 8377526: Update Libpng to 1.6.55 Reviewed-by: azvegint, prr, serb --- src/java.desktop/share/legal/libpng.md | 3 ++- .../share/native/libsplashscreen/libpng/CHANGES | 12 +++++++++--- .../share/native/libsplashscreen/libpng/README | 14 +++++++------- .../share/native/libsplashscreen/libpng/png.c | 4 ++-- .../share/native/libsplashscreen/libpng/png.h | 14 +++++++------- .../share/native/libsplashscreen/libpng/pngconf.h | 2 +- .../native/libsplashscreen/libpng/pnglibconf.h | 2 +- .../share/native/libsplashscreen/libpng/pngrtran.c | 6 +++--- 8 files changed, 32 insertions(+), 25 deletions(-) diff --git a/src/java.desktop/share/legal/libpng.md b/src/java.desktop/share/legal/libpng.md index 80d12248ec4..a2ffcca1974 100644 --- a/src/java.desktop/share/legal/libpng.md +++ b/src/java.desktop/share/legal/libpng.md @@ -1,4 +1,4 @@ -## libpng v1.6.54 +## libpng v1.6.55 ### libpng License
@@ -170,6 +170,7 @@ Authors, for copyright and licensing purposes.
  * Guy Eric Schalnat
  * James Yu
  * John Bowler
+ * Joshua Inscoe
  * Kevin Bracey
  * Lucas Chollet
  * Magnus Holmgren
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/CHANGES b/src/java.desktop/share/native/libsplashscreen/libpng/CHANGES
index 3bb1baecd23..af9fcff6eb3 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/CHANGES
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/CHANGES
@@ -5988,7 +5988,7 @@ Version 1.6.32rc01 [August 18, 2017]
 
 Version 1.6.32rc02 [August 22, 2017]
   Added contrib/oss-fuzz directory which contains files used by the oss-fuzz
-    project (https://github.com/google/oss-fuzz/tree/master/projects/libpng).
+    project .
 
 Version 1.6.32 [August 24, 2017]
   No changes.
@@ -6323,15 +6323,21 @@ Version 1.6.53 [December 5, 2025]
 
 Version 1.6.54 [January 12, 2026]
   Fixed CVE-2026-22695 (medium severity):
-    Heap buffer over-read in `png_image_read_direct_scaled.
+    Heap buffer over-read in `png_image_read_direct_scaled`.
     (Reported and fixed by Petr Simecek.)
   Fixed CVE-2026-22801 (medium severity):
     Integer truncation causing heap buffer over-read in `png_image_write_*`.
   Implemented various improvements in oss-fuzz.
     (Contributed by Philippe Antoine.)
 
+Version 1.6.55 [February 9, 2026]
+  Fixed CVE-2026-25646 (high severity):
+    Heap buffer overflow in `png_set_quantize`.
+    (Reported and fixed by Joshua Inscoe.)
+  Resolved an oss-fuzz build issue involving nalloc.
+    (Contributed by Philippe Antoine.)
 
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net.
 Subscription is required; visit
-https://lists.sourceforge.net/lists/listinfo/png-mng-implement
+
 to subscribe.
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/README b/src/java.desktop/share/native/libsplashscreen/libpng/README
index 63d1376edf7..6e0d1e33137 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/README
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/README
@@ -1,4 +1,4 @@
-README for libpng version 1.6.54
+README for libpng version 1.6.55
 ================================
 
 See the note about version numbers near the top of `png.h`.
@@ -24,14 +24,14 @@ for more things than just PNG files.  You can use zlib as a drop-in
 replacement for `fread()` and `fwrite()`, if you are so inclined.
 
 zlib should be available at the same place that libpng is, or at
-https://zlib.net .
+.
 
 You may also want a copy of the PNG specification.  It is available
 as an RFC, a W3C Recommendation, and an ISO/IEC Standard.  You can find
-these at http://www.libpng.org/pub/png/pngdocs.html .
+these at .
 
-This code is currently being archived at https://libpng.sourceforge.io
-in the download area, and at http://libpng.download/src .
+This code is currently being archived at 
+in the download area, and at .
 
 This release, based in a large way on Glenn's, Guy's and Andreas'
 earlier work, was created and will be supported by myself and the PNG
@@ -39,12 +39,12 @@ development group.
 
 Send comments, corrections and commendations to `png-mng-implement`
 at `lists.sourceforge.net`.  (Subscription is required; visit
-https://lists.sourceforge.net/lists/listinfo/png-mng-implement
+
 to subscribe.)
 
 Send general questions about the PNG specification to `png-mng-misc`
 at `lists.sourceforge.net`.  (Subscription is required; visit
-https://lists.sourceforge.net/lists/listinfo/png-mng-misc
+
 to subscribe.)
 
 Historical notes
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/png.c b/src/java.desktop/share/native/libsplashscreen/libpng/png.c
index 5636b4a754e..955fda8dd7e 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/png.c
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/png.c
@@ -42,7 +42,7 @@
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_6_54 Your_png_h_is_not_version_1_6_54;
+typedef png_libpng_version_1_6_55 Your_png_h_is_not_version_1_6_55;
 
 /* Sanity check the chunks definitions - PNG_KNOWN_CHUNKS from pngpriv.h and the
  * corresponding macro definitions.  This causes a compile time failure if
@@ -849,7 +849,7 @@ png_get_copyright(png_const_structrp png_ptr)
    return PNG_STRING_COPYRIGHT
 #else
    return PNG_STRING_NEWLINE \
-      "libpng version 1.6.54" PNG_STRING_NEWLINE \
+      "libpng version 1.6.55" PNG_STRING_NEWLINE \
       "Copyright (c) 2018-2026 Cosmin Truta" PNG_STRING_NEWLINE \
       "Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \
       PNG_STRING_NEWLINE \
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/png.h b/src/java.desktop/share/native/libsplashscreen/libpng/png.h
index ab8876a9626..e95c0444399 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/png.h
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/png.h
@@ -29,7 +29,7 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.54
+ * libpng version 1.6.55
  *
  * Copyright (c) 2018-2026 Cosmin Truta
  * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
@@ -43,7 +43,7 @@
  *   libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger
  *   libpng versions 0.97, January 1998, through 1.6.35, July 2018:
  *     Glenn Randers-Pehrson
- *   libpng versions 1.6.36, December 2018, through 1.6.54, January 2026:
+ *   libpng versions 1.6.36, December 2018, through 1.6.55, February 2026:
  *     Cosmin Truta
  *   See also "Contributing Authors", below.
  */
@@ -267,7 +267,7 @@
  *    ...
  *    1.5.30                  15    10530  15.so.15.30[.0]
  *    ...
- *    1.6.54                  16    10654  16.so.16.54[.0]
+ *    1.6.55                  16    10655  16.so.16.55[.0]
  *
  *    Henceforth the source version will match the shared-library major and
  *    minor numbers; the shared-library major version number will be used for
@@ -303,7 +303,7 @@
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.6.54"
+#define PNG_LIBPNG_VER_STRING "1.6.55"
 #define PNG_HEADER_VERSION_STRING " libpng version " PNG_LIBPNG_VER_STRING "\n"
 
 /* The versions of shared library builds should stay in sync, going forward */
@@ -314,7 +314,7 @@
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
 #define PNG_LIBPNG_VER_MINOR   6
-#define PNG_LIBPNG_VER_RELEASE 54
+#define PNG_LIBPNG_VER_RELEASE 55
 
 /* This should be zero for a public release, or non-zero for a
  * development version.
@@ -345,7 +345,7 @@
  * From version 1.0.1 it is:
  * XXYYZZ, where XX=major, YY=minor, ZZ=release
  */
-#define PNG_LIBPNG_VER 10654 /* 1.6.54 */
+#define PNG_LIBPNG_VER 10655 /* 1.6.55 */
 
 /* Library configuration: these options cannot be changed after
  * the library has been built.
@@ -455,7 +455,7 @@ extern "C" {
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef char *png_libpng_version_1_6_54;
+typedef char *png_libpng_version_1_6_55;
 
 /* Basic control structions.  Read libpng-manual.txt or libpng.3 for more info.
  *
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/pngconf.h b/src/java.desktop/share/native/libsplashscreen/libpng/pngconf.h
index 959c604edbc..b957f8b5061 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/pngconf.h
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/pngconf.h
@@ -29,7 +29,7 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.54
+ * libpng version 1.6.55
  *
  * Copyright (c) 2018-2026 Cosmin Truta
  * Copyright (c) 1998-2002,2004,2006-2016,2018 Glenn Randers-Pehrson
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/pnglibconf.h b/src/java.desktop/share/native/libsplashscreen/libpng/pnglibconf.h
index b413b510acf..ae1ab462072 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/pnglibconf.h
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/pnglibconf.h
@@ -31,7 +31,7 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  */
-/* libpng version 1.6.54 */
+/* libpng version 1.6.55 */
 
 /* Copyright (c) 2018-2026 Cosmin Truta */
 /* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson */
diff --git a/src/java.desktop/share/native/libsplashscreen/libpng/pngrtran.c b/src/java.desktop/share/native/libsplashscreen/libpng/pngrtran.c
index 7680fe64828..fcce80da1cb 100644
--- a/src/java.desktop/share/native/libsplashscreen/libpng/pngrtran.c
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/pngrtran.c
@@ -29,7 +29,7 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Copyright (c) 2018-2025 Cosmin Truta
+ * Copyright (c) 2018-2026 Cosmin Truta
  * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  * Copyright (c) 1996-1997 Andreas Dilger
  * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
@@ -737,8 +737,8 @@ png_set_quantize(png_structrp png_ptr, png_colorp palette,
                          break;
 
                      t->next = hash[d];
-                     t->left = (png_byte)i;
-                     t->right = (png_byte)j;
+                     t->left = png_ptr->palette_to_index[i];
+                     t->right = png_ptr->palette_to_index[j];
                      hash[d] = t;
                   }
                }

From 074044c2f37e2da5bb05ea2fc74f6d1e42735ab6 Mon Sep 17 00:00:00 2001
From: Jasmine Karthikeyan 
Date: Thu, 26 Feb 2026 05:15:30 +0000
Subject: [PATCH 09/54] 8342095: Add autovectorizer support for subword vector
 casts

Reviewed-by: epeter, qamai
---
 src/hotspot/share/opto/superword.cpp          |  17 +-
 src/hotspot/share/opto/superword.hpp          |   4 +-
 .../share/opto/superwordVTransformBuilder.cpp |  14 +
 src/hotspot/share/opto/vectornode.cpp         |   7 +
 src/hotspot/share/opto/vectornode.hpp         |   1 +
 src/hotspot/share/opto/vtransform.hpp         |   1 +
 .../jtreg/compiler/c2/TestMinMaxSubword.java  |  17 +-
 .../TestCompatibleUseDefTypeSize.java         | 241 ++++++++++++++++-
 .../loopopts/superword/TestReductions.java    | 248 +++++++++++++++---
 .../TestRotateByteAndShortVector.java         |  22 +-
 .../vectorization/TestSubwordTruncation.java  |  28 +-
 .../runner/ArrayShiftOpTest.java              |   5 +-
 .../runner/ArrayTypeConvertTest.java          |  70 +++--
 .../runner/BasicShortOpTest.java              |  12 +-
 .../bench/vm/compiler/VectorSubword.java      | 201 ++++++++++++++
 15 files changed, 782 insertions(+), 106 deletions(-)
 create mode 100644 test/micro/org/openjdk/bench/vm/compiler/VectorSubword.java

diff --git a/src/hotspot/share/opto/superword.cpp b/src/hotspot/share/opto/superword.cpp
index 31cc8fa0460..d878b2b1d3d 100644
--- a/src/hotspot/share/opto/superword.cpp
+++ b/src/hotspot/share/opto/superword.cpp
@@ -2214,7 +2214,7 @@ bool SuperWord::is_vector_use(Node* use, int u_idx) const {
     return true;
   }
 
-  if (!is_velt_basic_type_compatible_use_def(use, def)) {
+  if (!is_velt_basic_type_compatible_use_def(use, def, d_pk->size())) {
     return false;
   }
 
@@ -2280,7 +2280,7 @@ Node_List* PackSet::strided_pack_input_at_index_or_null(const Node_List* pack, c
 
 // Check if the output type of def is compatible with the input type of use, i.e. if the
 // types have the same size.
-bool SuperWord::is_velt_basic_type_compatible_use_def(Node* use, Node* def) const {
+bool SuperWord::is_velt_basic_type_compatible_use_def(Node* use, Node* def, const uint pack_size) const {
   assert(in_bb(def) && in_bb(use), "both use and def are in loop");
 
   // Conversions are trivially compatible.
@@ -2306,8 +2306,17 @@ bool SuperWord::is_velt_basic_type_compatible_use_def(Node* use, Node* def) cons
            type2aelembytes(use_bt) == 4;
   }
 
-  // Default case: input size of use equals output size of def.
-  return type2aelembytes(use_bt) == type2aelembytes(def_bt);
+  // Input size of use equals output size of def
+  if (type2aelembytes(use_bt) == type2aelembytes(def_bt)) {
+    return true;
+  }
+
+  // Subword cast: Element sizes differ, but the platform supports a cast to change the def shape to the use shape.
+  if (VectorCastNode::is_supported_subword_cast(def_bt, use_bt, pack_size)) {
+    return true;
+  }
+
+  return false;
 }
 
 // Return nullptr if success, else failure message
diff --git a/src/hotspot/share/opto/superword.hpp b/src/hotspot/share/opto/superword.hpp
index 9654465220b..4e6fce70e5c 100644
--- a/src/hotspot/share/opto/superword.hpp
+++ b/src/hotspot/share/opto/superword.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 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
@@ -653,7 +653,7 @@ private:
   // Is use->in(u_idx) a vector use?
   bool is_vector_use(Node* use, int u_idx) const;
 
-  bool is_velt_basic_type_compatible_use_def(Node* use, Node* def) const;
+  bool is_velt_basic_type_compatible_use_def(Node* use, Node* def, const uint pack_size) const;
 
   bool do_vtransform() const;
 };
diff --git a/src/hotspot/share/opto/superwordVTransformBuilder.cpp b/src/hotspot/share/opto/superwordVTransformBuilder.cpp
index 832e91603d9..f8b8bfe2ed0 100644
--- a/src/hotspot/share/opto/superwordVTransformBuilder.cpp
+++ b/src/hotspot/share/opto/superwordVTransformBuilder.cpp
@@ -254,6 +254,20 @@ VTransformNode* SuperWordVTransformBuilder::get_or_make_vtnode_vector_input_at_i
 
   Node_List* pack_in = _packset.pack_input_at_index_or_null(pack, index);
   if (pack_in != nullptr) {
+    Node* in_p0 = pack_in->at(0);
+    BasicType def_bt = _vloop_analyzer.types().velt_basic_type(in_p0);
+    BasicType use_bt = _vloop_analyzer.types().velt_basic_type(p0);
+
+    // If the use and def types are different, emit a cast node
+    if (use_bt != def_bt && !p0->is_Convert() && VectorCastNode::is_supported_subword_cast(def_bt, use_bt, pack->size())) {
+      VTransformNode* in = get_vtnode(pack_in->at(0));
+      const VTransformVectorNodeProperties properties = VTransformVectorNodeProperties::make_from_pack(pack, _vloop_analyzer);
+      VTransformNode* cast = new (_vtransform.arena()) VTransformElementWiseVectorNode(_vtransform, 2, properties, VectorCastNode::opcode(-1, def_bt));
+      cast->set_req(1, in);
+
+      return cast;
+    }
+
     // Input is a matching pack -> vtnode already exists.
     assert(index != 2 || !VectorNode::is_shift(p0), "shift's count cannot be vector");
     return get_vtnode(pack_in->at(0));
diff --git a/src/hotspot/share/opto/vectornode.cpp b/src/hotspot/share/opto/vectornode.cpp
index ba88ae9496f..d332bf440f6 100644
--- a/src/hotspot/share/opto/vectornode.cpp
+++ b/src/hotspot/share/opto/vectornode.cpp
@@ -1561,6 +1561,13 @@ bool VectorCastNode::implemented(int opc, uint vlen, BasicType src_type, BasicTy
   return false;
 }
 
+bool VectorCastNode::is_supported_subword_cast(BasicType def_bt, BasicType use_bt, const uint pack_size) {
+  assert(def_bt != use_bt, "use and def types must be different");
+
+  // Opcode is only required to disambiguate half float, so we pass -1 as it can't be encountered here.
+  return (is_subword_type(def_bt) || is_subword_type(use_bt)) && VectorCastNode::implemented(-1, pack_size, def_bt, use_bt);
+}
+
 Node* VectorCastNode::Identity(PhaseGVN* phase) {
   if (!in(1)->is_top()) {
     BasicType  in_bt = in(1)->bottom_type()->is_vect()->element_basic_type();
diff --git a/src/hotspot/share/opto/vectornode.hpp b/src/hotspot/share/opto/vectornode.hpp
index edbceb30635..f0d010ee735 100644
--- a/src/hotspot/share/opto/vectornode.hpp
+++ b/src/hotspot/share/opto/vectornode.hpp
@@ -1846,6 +1846,7 @@ class VectorCastNode : public VectorNode {
   static VectorNode* make(int vopc, Node* n1, BasicType bt, uint vlen);
   static int  opcode(int opc, BasicType bt, bool is_signed = true);
   static bool implemented(int opc, uint vlen, BasicType src_type, BasicType dst_type);
+  static bool is_supported_subword_cast(BasicType def_bt, BasicType use_bt, const uint pack_size);
 
   virtual Node* Identity(PhaseGVN* phase);
 };
diff --git a/src/hotspot/share/opto/vtransform.hpp b/src/hotspot/share/opto/vtransform.hpp
index b60c71945e1..2c535eca6d1 100644
--- a/src/hotspot/share/opto/vtransform.hpp
+++ b/src/hotspot/share/opto/vtransform.hpp
@@ -975,4 +975,5 @@ public:
   virtual VTransformApplyResult apply(VTransformApplyState& apply_state) const override;
   NOT_PRODUCT(virtual const char* name() const override { return "StoreVector"; };)
 };
+
 #endif // SHARE_OPTO_VTRANSFORM_HPP
diff --git a/test/hotspot/jtreg/compiler/c2/TestMinMaxSubword.java b/test/hotspot/jtreg/compiler/c2/TestMinMaxSubword.java
index a7e90353f90..6b93f00cdb1 100644
--- a/test/hotspot/jtreg/compiler/c2/TestMinMaxSubword.java
+++ b/test/hotspot/jtreg/compiler/c2/TestMinMaxSubword.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2022, Arm Limited. All rights reserved.
+ * 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
@@ -30,7 +31,7 @@ import java.util.Random;
 
 /*
  * @test
- * @bug 8294816
+ * @bug 8294816 8342095
  * @key randomness
  * @summary Test Math.min/max vectorization miscompilation for integer subwords
  * @library /test/lib /
@@ -58,11 +59,11 @@ public class TestMinMaxSubword {
         }
     }
 
-    // Ensure vector max/min instructions are not generated for integer subword types
-    // as Java APIs for Math.min/max do not support integer subword types and superword
-    // should not generate vectorized Min/Max nodes for them.
+    // Ensure that casts to/from subword types are emitted, as java APIs for Math.min/max do not support integer subword
+    // types and superword should generate int versions and then cast between them.
+
     @Test
-    @IR(failOn = {IRNode.MIN_VI, IRNode.MIN_VF, IRNode.MIN_VD})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public static void testMinShort() {
         for (int i = 0; i < LENGTH; i++) {
            sb[i] = (short) Math.min(sa[i], val);
@@ -78,7 +79,7 @@ public class TestMinMaxSubword {
     }
 
     @Test
-    @IR(failOn = {IRNode.MAX_VI, IRNode.MAX_VF, IRNode.MAX_VD})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public static void testMaxShort() {
         for (int i = 0; i < LENGTH; i++) {
             sb[i] = (short) Math.max(sa[i], val);
@@ -93,7 +94,7 @@ public class TestMinMaxSubword {
     }
 
     @Test
-    @IR(failOn = {IRNode.MIN_VI, IRNode.MIN_VF, IRNode.MIN_VD})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" })
     public static void testMinByte() {
         for (int i = 0; i < LENGTH; i++) {
            bb[i] = (byte) Math.min(ba[i], val);
@@ -109,7 +110,7 @@ public class TestMinMaxSubword {
     }
 
     @Test
-    @IR(failOn = {IRNode.MAX_VI, IRNode.MAX_VF, IRNode.MAX_VD})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" })
     public static void testMaxByte() {
         for (int i = 0; i < LENGTH; i++) {
             bb[i] = (byte) Math.max(ba[i], val);
diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java
index 0e17489e1c8..7399a1ec411 100644
--- a/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java
+++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2024, 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
@@ -34,7 +34,7 @@ import java.nio.ByteOrder;
 
 /*
  * @test
- * @bug 8325155
+ * @bug 8325155 8342095
  * @key randomness
  * @summary Test some cases that vectorize after the removal of the alignment boundaries code.
  *          Now, we instead check if use-def connections have compatible type size.
@@ -106,6 +106,22 @@ public class TestCompatibleUseDefTypeSize {
         tests.put("test9",       () -> { return test9(aL.clone(), bD.clone()); });
         tests.put("test10",      () -> { return test10(aL.clone(), bD.clone()); });
         tests.put("test11",      () -> { return test11(aC.clone()); });
+        tests.put("testByteToInt",   () -> { return testByteToInt(aB.clone(), bI.clone()); });
+        tests.put("testByteToShort", () -> { return testByteToShort(aB.clone(), bS.clone()); });
+        tests.put("testByteToChar",  () -> { return testByteToChar(aB.clone(), bC.clone()); });
+        tests.put("testByteToLong",  () -> { return testByteToLong(aB.clone(), bL.clone()); });
+        tests.put("testShortToByte", () -> { return testShortToByte(aS.clone(), bB.clone()); });
+        tests.put("testShortToChar", () -> { return testShortToChar(aS.clone(), bC.clone()); });
+        tests.put("testShortToInt",  () -> { return testShortToInt(aS.clone(), bI.clone()); });
+        tests.put("testShortToLong", () -> { return testShortToLong(aS.clone(), bL.clone()); });
+        tests.put("testIntToShort",  () -> { return testIntToShort(aI.clone(), bS.clone()); });
+        tests.put("testIntToChar",   () -> { return testIntToChar(aI.clone(), bC.clone()); });
+        tests.put("testIntToByte",   () -> { return testIntToByte(aI.clone(), bB.clone()); });
+        tests.put("testIntToLong",   () -> { return testIntToLong(aI.clone(), bL.clone()); });
+        tests.put("testLongToByte",  () -> { return testLongToByte(aL.clone(), bB.clone()); });
+        tests.put("testLongToShort", () -> { return testLongToShort(aL.clone(), bS.clone()); });
+        tests.put("testLongToChar",  () -> { return testLongToChar(aL.clone(), bC.clone()); });
+        tests.put("testLongToInt",   () -> { return testLongToInt(aL.clone(), bI.clone()); });
 
         // Compute gold value for all test methods before compilation
         for (Map.Entry entry : tests.entrySet()) {
@@ -128,7 +144,23 @@ public class TestCompatibleUseDefTypeSize {
                  "test8",
                  "test9",
                  "test10",
-                 "test11"})
+                 "test11",
+                 "testByteToInt",
+                 "testByteToShort",
+                 "testByteToChar",
+                 "testByteToLong",
+                 "testShortToByte",
+                 "testShortToChar",
+                 "testShortToInt",
+                 "testShortToLong",
+                 "testIntToShort",
+                 "testIntToChar",
+                 "testIntToByte",
+                 "testIntToLong",
+                 "testLongToByte",
+                 "testLongToShort",
+                 "testLongToChar",
+                 "testLongToInt"})
     public void runTests() {
         for (Map.Entry entry : tests.entrySet()) {
             String name = entry.getKey();
@@ -328,12 +360,12 @@ public class TestCompatibleUseDefTypeSize {
     }
 
     @Test
-    @IR(counts = {IRNode.STORE_VECTOR, "= 0"},
+    @IR(counts = {IRNode.STORE_VECTOR, "> 0"},
         applyIfPlatform = {"64-bit", "true"},
-        applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true", "rvv", "true"})
+        applyIf = {"AlignVector", "false"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"})
     // "inflate"  method: 1 byte -> 2 byte.
     // Java scalar code has no explicit conversion.
-    // Vector code would need a conversion. We may add this in the future.
     static Object[] test1(byte[] src, char[] dst) {
         for (int i = 0; i < src.length; i++) {
             dst[i] = (char)(src[i]);
@@ -478,4 +510,201 @@ public class TestCompatibleUseDefTypeSize {
         }
         return new Object[]{ a, new char[] { m } };
     }
+
+    // Narrowing
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
+    public Object[] testIntToShort(int[] ints, short[] res) {
+        for (int i = 0; i < ints.length; i++) {
+            res[i] = (short) ints[i];
+        }
+
+        return new Object[] { ints, res };
+    }
+
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_char)", ">0" })
+    public Object[] testIntToChar(int[] ints, char[] res) {
+        for (int i = 0; i < ints.length; i++) {
+            res[i] = (char) ints[i];
+        }
+
+        return new Object[] { ints, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" })
+    public Object[] testIntToByte(int[] ints, byte[] res) {
+        for (int i = 0; i < ints.length; i++) {
+            res[i] = (byte) ints[i];
+        }
+
+        return new Object[] { ints, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_S2B, IRNode.VECTOR_SIZE + "min(max_short, max_byte)", ">0" })
+    public Object[] testShortToByte(short[] shorts, byte[] res) {
+        for (int i = 0; i < shorts.length; i++) {
+            res[i] = (byte) shorts[i];
+        }
+
+        return new Object[] { shorts, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx2", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_L2B, IRNode.VECTOR_SIZE + "min(max_long, max_byte)", ">0" })
+    public Object[] testLongToByte(long[] longs, byte[] res) {
+        for (int i = 0; i < longs.length; i++) {
+            res[i] = (byte) longs[i];
+        }
+
+        return new Object[] { longs, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_L2S, IRNode.VECTOR_SIZE + "min(max_long, max_short)", ">0" })
+    public Object[] testLongToShort(long[] longs, short[] res) {
+        for (int i = 0; i < longs.length; i++) {
+            res[i] = (short) longs[i];
+        }
+
+        return new Object[] { longs, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_L2S, IRNode.VECTOR_SIZE + "min(max_long, max_char)", ">0" })
+    public Object[] testLongToChar(long[] longs, char[] res) {
+        for (int i = 0; i < longs.length; i++) {
+            res[i] = (char) longs[i];
+        }
+
+        return new Object[] { longs, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_L2I, IRNode.VECTOR_SIZE + "min(max_long, max_int)", ">0" })
+    public Object[] testLongToInt(long[] longs, int[] res) {
+        for (int i = 0; i < longs.length; i++) {
+            res[i] = (int) longs[i];
+        }
+
+        return new Object[] { longs, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.STORE_VECTOR, ">0" })
+    public Object[] testShortToChar(short[] shorts, char[] res) {
+        for (int i = 0; i < shorts.length; i++) {
+            res[i] = (char) shorts[i];
+        }
+
+        return new Object[] { shorts, res };
+    }
+
+    // Widening
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_S2I, IRNode.VECTOR_SIZE + "min(max_short, max_int)", ">0" })
+    public Object[] testShortToInt(short[] shorts, int[] res) {
+        for (int i = 0; i < shorts.length; i++) {
+            res[i] = shorts[i];
+        }
+
+        return new Object[] { shorts, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2I, IRNode.VECTOR_SIZE + "min(max_byte, max_int)", ">0" })
+    public Object[] testByteToInt(byte[] bytes, int[] res) {
+        for (int i = 0; i < bytes.length; i++) {
+            res[i] = bytes[i];
+        }
+
+        return new Object[] { bytes, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2S, IRNode.VECTOR_SIZE + "min(max_byte, max_short)", ">0" })
+    public Object[] testByteToShort(byte[] bytes, short[] res) {
+        for (int i = 0; i < bytes.length; i++) {
+            res[i] = bytes[i];
+        }
+
+        return new Object[] { bytes, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2S, IRNode.VECTOR_SIZE + "min(max_byte, max_char)", ">0" })
+    public Object[] testByteToChar(byte[] bytes, char[] res) {
+        for (int i = 0; i < bytes.length; i++) {
+            res[i] = (char) bytes[i];
+        }
+
+        return new Object[] { bytes, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx2", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2L, IRNode.VECTOR_SIZE + "min(max_byte, max_long)", ">0" })
+    public Object[] testByteToLong(byte[] bytes, long[] res) {
+        for (int i = 0; i < bytes.length; i++) {
+            res[i] = bytes[i];
+        }
+
+        return new Object[] { bytes, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_S2L, IRNode.VECTOR_SIZE + "min(max_short, max_long)", ">0" })
+    public Object[] testShortToLong(short[] shorts, long[] res) {
+        for (int i = 0; i < shorts.length; i++) {
+            res[i] = shorts[i];
+        }
+
+        return new Object[] { shorts, res };
+    }
+
+    @Test
+    @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2L, IRNode.VECTOR_SIZE + "min(max_int, max_long)", ">0" })
+    public Object[] testIntToLong(int[] ints, long[] res) {
+        for (int i = 0; i < ints.length; i++) {
+            res[i] = ints[i];
+        }
+
+        return new Object[] { ints, res };
+    }
 }
diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java
index 1cd5cfa1e75..e0f44bcdb3b 100644
--- a/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java
+++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2024, 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
@@ -23,7 +23,7 @@
 
 /*
  * @test id=no-vectorization
- * @bug 8340093
+ * @bug 8340093 8342095
  * @summary Test vectorization of reduction loops.
  * @library /test/lib /
  * @run driver compiler.loopopts.superword.TestReductions P0
@@ -31,7 +31,7 @@
 
 /*
  * @test id=vanilla
- * @bug 8340093
+ * @bug 8340093 8342095
  * @summary Test vectorization of reduction loops.
  * @library /test/lib /
  * @run driver compiler.loopopts.superword.TestReductions P1
@@ -39,7 +39,7 @@
 
 /*
  * @test id=force-vectorization
- * @bug 8340093
+ * @bug 8340093 8342095
  * @summary Test vectorization of reduction loops.
  * @library /test/lib /
  * @run driver compiler.loopopts.superword.TestReductions P2
@@ -455,7 +455,13 @@ public class TestReductions {
 
     // ---------byte***Simple ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteAndSimple() {
         byte acc = (byte)0xFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -466,7 +472,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteOrSimple() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -477,7 +489,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteXorSimple() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -510,7 +528,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMinSimple() {
         byte acc = Byte.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -521,7 +545,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMaxSimple() {
         byte acc = Byte.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -533,7 +563,13 @@ public class TestReductions {
 
     // ---------byte***DotProduct ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteAndDotProduct() {
         byte acc = (byte)0xFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -544,7 +580,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteOrDotProduct() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -555,7 +597,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteXorDotProduct() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -588,7 +636,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMinDotProduct() {
         byte acc = Byte.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -599,7 +653,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMaxDotProduct() {
         byte acc = Byte.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -611,7 +671,13 @@ public class TestReductions {
 
     // ---------byte***Big ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteAndBig() {
         byte acc = (byte)0xFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -622,7 +688,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteOrBig() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -633,7 +705,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteXorBig() {
         byte acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -666,7 +744,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMinBig() {
         byte acc = Byte.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -677,7 +761,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_B) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_B,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static byte byteMaxBig() {
         byte acc = Byte.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -923,7 +1013,13 @@ public class TestReductions {
 
     // ---------short***Simple ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortAndSimple() {
         short acc = (short)0xFFFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -934,7 +1030,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortOrSimple() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -945,7 +1047,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortXorSimple() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -978,7 +1086,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMinSimple() {
         short acc = Short.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -989,7 +1103,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMaxSimple() {
         short acc = Short.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1001,7 +1121,13 @@ public class TestReductions {
 
     // ---------short***DotProduct ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortAndDotProduct() {
         short acc = (short)0xFFFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1012,7 +1138,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortOrDotProduct() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1023,7 +1155,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortXorDotProduct() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1056,7 +1194,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMinDotProduct() {
         short acc = Short.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1067,7 +1211,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMaxDotProduct() {
         short acc = Short.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1079,7 +1229,13 @@ public class TestReductions {
 
     // ---------short***Big ------------------------------------------------------------
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.AND_REDUCTION_V, "> 0",
+                  IRNode.AND_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortAndBig() {
         short acc = (short)0xFFFF; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1090,7 +1246,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.OR_REDUCTION_V, "> 0",
+                  IRNode.OR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortOrBig() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1101,7 +1263,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.XOR_REDUCTION_V, "> 0",
+                  IRNode.XOR_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortXorBig() {
         short acc = 0; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1134,7 +1302,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MIN_REDUCTION_V, "> 0",
+                  IRNode.MIN_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMinBig() {
         short acc = Short.MAX_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
@@ -1145,7 +1319,13 @@ public class TestReductions {
     }
 
     @Test
-    @IR(failOn = IRNode.LOAD_VECTOR_S) // does not vectorize for now, might in the future.
+    @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                  IRNode.MAX_REDUCTION_V, "> 0",
+                  IRNode.MAX_VI,          "> 0"},
+        applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"},
+        applyIf = {"AutoVectorizationOverrideProfitability", "> 0"})
+    @IR(failOn = IRNode.LOAD_VECTOR_S,
+        applyIf = {"AutoVectorizationOverrideProfitability", "= 0"})
     private static short shortMaxBig() {
         short acc = Short.MIN_VALUE; // neutral element
         for (int i = 0; i < SIZE; i++) {
diff --git a/test/hotspot/jtreg/compiler/vectorization/TestRotateByteAndShortVector.java b/test/hotspot/jtreg/compiler/vectorization/TestRotateByteAndShortVector.java
index e130fc0ba6c..79cde2f0d26 100644
--- a/test/hotspot/jtreg/compiler/vectorization/TestRotateByteAndShortVector.java
+++ b/test/hotspot/jtreg/compiler/vectorization/TestRotateByteAndShortVector.java
@@ -1,6 +1,7 @@
 /*
  * Copyright (c) 2022, 2025 Loongson Technology Co. Ltd. All rights reserved.
  * Copyright (c) 2025, Rivos Inc. All rights reserved.
+ * 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
@@ -24,7 +25,7 @@
 
 /**
  * @test
- * @bug 8286847 8353600
+ * @bug 8286847 8353600 8342095
  * @key randomness
  * @summary Test vectorization of rotate byte and short
  * @library /test/lib /
@@ -116,11 +117,10 @@ public class TestRotateByteAndShortVector {
         }
     }
 
-    // NOTE: currently, there is no platform supporting RotateLeftV/RotateRightV intrinsic.
-    // If there is some implementation, it could probably in a wrong way which is different
-    // from what java language spec expects.
     @Test
-    @IR(failOn = { IRNode.ROTATE_LEFT_V })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                   IRNode.ROTATE_LEFT_V, "> 0" },
+        applyIfCPUFeature = {"avx512f", "true"})
     @IR(failOn = { IRNode.ROTATE_RIGHT_V })
     static void testRotateLeftByte(byte[] test, byte[] arr, int shift) {
         for (int i = 0; i < ARRLEN; i++) {
@@ -130,7 +130,9 @@ public class TestRotateByteAndShortVector {
 
     @Test
     @IR(failOn = { IRNode.ROTATE_LEFT_V })
-    @IR(failOn = { IRNode.ROTATE_RIGHT_V })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0",
+                   IRNode.ROTATE_RIGHT_V, "> 0" },
+        applyIfCPUFeature = {"avx512f", "true"})
     static void testRotateRightByte(byte[] test, byte[] arr, int shift) {
         for (int i = 0; i < ARRLEN; i++) {
             test[i] = (byte) ((arr[i] >>> shift) | (arr[i] << -shift));
@@ -138,7 +140,9 @@ public class TestRotateByteAndShortVector {
     }
 
     @Test
-    @IR(failOn = { IRNode.ROTATE_LEFT_V })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                   IRNode.ROTATE_LEFT_V, "> 0" },
+        applyIfCPUFeature = {"avx512f", "true"})
     @IR(failOn = { IRNode.ROTATE_RIGHT_V })
     static void testRotateLeftShort(short[] test, short[] arr, int shift) {
         for (int i = 0; i < ARRLEN; i++) {
@@ -148,7 +152,9 @@ public class TestRotateByteAndShortVector {
 
     @Test
     @IR(failOn = { IRNode.ROTATE_LEFT_V })
-    @IR(failOn = { IRNode.ROTATE_RIGHT_V })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0",
+                   IRNode.ROTATE_RIGHT_V, "> 0" },
+        applyIfCPUFeature = {"avx512f", "true"})
     static void testRotateRightShort(short[] test, short[] arr, int shift) {
         for (int i = 0; i < ARRLEN; i++) {
             test[i] = (short) ((arr[i] >>> shift) | (arr[i] << -shift));
diff --git a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
index 53c1b89a203..29331cc1845 100644
--- a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
+++ b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.g
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,7 +29,7 @@ import compiler.lib.generators.*;
 
 /*
  * @test
- * @bug 8350177 8362171 8369881
+ * @bug 8350177 8362171 8369881 8342095
  * @summary Ensure that truncation of subword vectors produces correct results
  * @library /test/lib /
  * @run driver compiler.vectorization.TestSubwordTruncation
@@ -73,7 +73,8 @@ public class TestSubwordTruncation {
     // Shorts
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupShortArray")
     public Object[] testShortLeadingZeros(short[] in) {
         short[] res = new short[SIZE];
@@ -98,7 +99,8 @@ public class TestSubwordTruncation {
     }
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupShortArray")
     public Object[] testShortTrailingZeros(short[] in) {
         short[] res = new short[SIZE];
@@ -123,7 +125,8 @@ public class TestSubwordTruncation {
     }
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupShortArray")
     public Object[] testShortReverse(short[] in) {
         short[] res = new short[SIZE];
@@ -148,7 +151,8 @@ public class TestSubwordTruncation {
     }
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupShortArray")
     public Object[] testShortBitCount(short[] in) {
         short[] res = new short[SIZE];
@@ -277,7 +281,8 @@ public class TestSubwordTruncation {
     // Bytes
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupByteArray")
     public Object[] testByteLeadingZeros(byte[] in) {
         byte[] res = new byte[SIZE];
@@ -302,7 +307,8 @@ public class TestSubwordTruncation {
     }
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupByteArray")
     public Object[] testByteTrailingZeros(byte[] in) {
         byte[] res = new byte[SIZE];
@@ -327,7 +333,8 @@ public class TestSubwordTruncation {
     }
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupByteArray")
     public Object[] testByteReverse(byte[] in) {
         byte[] res = new byte[SIZE];
@@ -403,7 +410,8 @@ public class TestSubwordTruncation {
 
 
     @Test
-    @IR(counts = { IRNode.STORE_VECTOR, "=0" })
+    @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" },
+        applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" })
     @Arguments(setup = "setupByteArray")
     public Object[] testByteBitCount(byte[] in) {
         byte[] res = new byte[SIZE];
diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayShiftOpTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayShiftOpTest.java
index 1f0c8e668b7..a0434411da7 100644
--- a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayShiftOpTest.java
+++ b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayShiftOpTest.java
@@ -247,9 +247,8 @@ public class ArrayShiftOpTest extends VectorizationTestRunner {
     }
 
     @Test
-    // Note that right shift operations on subword expressions cannot be
-    // vectorized since precise type info about signedness is missing.
-    @IR(failOn = {IRNode.STORE_VECTOR})
+    @IR(applyIfCPUFeature = {"avx", "true"},
+            counts = {IRNode.RSHIFT_VI, ">0"})
     public short[] subwordExpressionRightShift() {
         short[] res = new short[SIZE];
         for (int i = 0; i < SIZE; i++) {
diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayTypeConvertTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayTypeConvertTest.java
index d3119a00c37..f9c5f6199f1 100644
--- a/test/hotspot/jtreg/compiler/vectorization/runner/ArrayTypeConvertTest.java
+++ b/test/hotspot/jtreg/compiler/vectorization/runner/ArrayTypeConvertTest.java
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2022, 2023, Arm Limited. All rights reserved.
- * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2024, 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
@@ -24,6 +24,7 @@
 
 /*
  * @test
+ * @bug 8183390 8340010 8342095
  * @summary Vectorization test on array type conversions
  * @library /test/lib /
  *
@@ -108,10 +109,9 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
 
     // ---------------- Integer Extension ----------------
     @Test
-    @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
-    // Assert the vectorization failure so that we are reminded to update
-    // the test when this limitation is addressed in the future.
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_S2I, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public int[] signExtension() {
         int[] res = new int[SIZE];
         for (int i = 0; i < SIZE; i++) {
@@ -122,7 +122,7 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
 
     @Test
     @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
+    // Subword vector casts with char do not work currently, see JDK-8349562.
     // Assert the vectorization failure so that we are reminded to update
     // the test when this limitation is addressed in the future.
     public int[] zeroExtension() {
@@ -134,10 +134,9 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
     }
 
     @Test
-    @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
-    // Assert the vectorization failure so that we are reminded to update
-    // the test when this limitation is addressed in the future.
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2I, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" })
     public int[] signExtensionFromByte() {
         int[] res = new int[SIZE];
         for (int i = 0; i < SIZE; i++) {
@@ -146,12 +145,23 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
         return res;
     }
 
+    @Test
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_B2S, IRNode.VECTOR_SIZE + "min(max_short, max_byte)", ">0" })
+    public short[] signExtensionFromByteToShort() {
+        short[] res = new short[SIZE];
+        for (int i = 0; i < SIZE; i++) {
+            res[i] = bytes[i];
+        }
+        return res;
+    }
+
     // ---------------- Integer Narrow ----------------
     @Test
-    @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
-    // Assert the vectorization failure so that we are reminded to update
-    // the test when this limitation is addressed in the future.
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public short[] narrowToSigned() {
         short[] res = new short[SIZE];
         for (int i = 0; i < SIZE; i++) {
@@ -161,10 +171,9 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
     }
 
     @Test
-    @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
-    // Assert the vectorization failure so that we are reminded to update
-    // the test when this limitation is addressed in the future.
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_char)", ">0" })
     public char[] narrowToUnsigned() {
         char[] res = new char[SIZE];
         for (int i = 0; i < SIZE; i++) {
@@ -174,11 +183,10 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
     }
 
     @Test
-    @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
-    // Assert the vectorization failure so that we are reminded to update
-    // the test when this limitation is addressed in the future.
-    public byte[] NarrowToByte() {
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_I2B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" })
+    public byte[] narrowToByte() {
         byte[] res = new byte[SIZE];
         for (int i = 0; i < SIZE; i++) {
             res[i] = (byte) ints[i];
@@ -186,6 +194,18 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
         return res;
     }
 
+    @Test
+    @IR(applyIfCPUFeature = { "avx", "true" },
+        applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"},
+        counts = { IRNode.VECTOR_CAST_S2B, IRNode.VECTOR_SIZE + "min(max_short, max_byte)", ">0" })
+    public byte[] narrowShortToByte() {
+        byte[] res = new byte[SIZE];
+        for (int i = 0; i < SIZE; i++) {
+            res[i] = (byte) shorts[i];
+        }
+        return res;
+    }
+
     // ---------------- Convert I/L to F/D ----------------
     @Test
     @IR(applyIfCPUFeatureOr = {"asimd", "true", "avx", "true", "rvv", "true"},
@@ -268,7 +288,7 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
 
     @Test
     @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
+    // Subword vector casts with char do not work currently, see JDK-8349562.
     // Assert the vectorization failure so that we are reminded to update
     // the test when this limitation is addressed in the future.
     public float[] convertCharToFloat() {
@@ -281,7 +301,7 @@ public class ArrayTypeConvertTest extends VectorizationTestRunner {
 
     @Test
     @IR(failOn = {IRNode.STORE_VECTOR})
-    // Subword vector casts do not work currently, see JDK-8342095.
+    // Subword vector casts with char do not work currently, see JDK-8349562.
     // Assert the vectorization failure so that we are reminded to update
     // the test when this limitation is addressed in the future.
     public double[] convertCharToDouble() {
diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/BasicShortOpTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/BasicShortOpTest.java
index 63739584558..b957a00278a 100644
--- a/test/hotspot/jtreg/compiler/vectorization/runner/BasicShortOpTest.java
+++ b/test/hotspot/jtreg/compiler/vectorization/runner/BasicShortOpTest.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2022, 2023, Arm Limited. All rights reserved.
+ * 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
@@ -23,6 +24,7 @@
 
 /*
  * @test
+ * @bug 8183390 8342095
  * @summary Vectorization test on basic short operations
  * @library /test/lib /
  *
@@ -210,10 +212,10 @@ public class BasicShortOpTest extends VectorizationTestRunner {
         return res;
     }
 
+    // Min/Max vectorization requires a cast from subword to int and back to subword, to avoid losing the higher order bits.
+
     @Test
-    // Note that min operations on subword types cannot be vectorized
-    // because higher bits will be lost.
-    @IR(failOn = {IRNode.STORE_VECTOR})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public short[] vectorMin() {
         short[] res = new short[SIZE];
         for (int i = 0; i < SIZE; i++) {
@@ -223,9 +225,7 @@ public class BasicShortOpTest extends VectorizationTestRunner {
     }
 
     @Test
-    // Note that max operations on subword types cannot be vectorized
-    // because higher bits will be lost.
-    @IR(failOn = {IRNode.STORE_VECTOR})
+    @IR(applyIfCPUFeature = { "avx", "true" }, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" })
     public short[] vectorMax() {
         short[] res = new short[SIZE];
         for (int i = 0; i < SIZE; i++) {
diff --git a/test/micro/org/openjdk/bench/vm/compiler/VectorSubword.java b/test/micro/org/openjdk/bench/vm/compiler/VectorSubword.java
new file mode 100644
index 00000000000..5ade452b875
--- /dev/null
+++ b/test/micro/org/openjdk/bench/vm/compiler/VectorSubword.java
@@ -0,0 +1,201 @@
+/*
+ * 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 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)
+@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
+@Fork(value = 3)
+public class VectorSubword {
+    @Param({"1024"})
+    public int SIZE;
+
+    private byte[] bytes;
+    private short[] shorts;
+    private char[] chars;
+    private int[] ints;
+    private long[] longs;
+
+    @Setup
+    public void init() {
+        bytes = new byte[SIZE];
+        shorts = new short[SIZE];
+        chars = new char[SIZE];
+        ints = new int[SIZE];
+        longs = new long[SIZE];
+    }
+
+    // Narrowing
+
+    @Benchmark
+    public void shortToByte() {
+        for (int i = 0; i < SIZE; i++) {
+            bytes[i] = (byte) shorts[i];
+        }
+    }
+
+    @Benchmark
+    public void shortToChar() {
+        for (int i = 0; i < SIZE; i++) {
+            chars[i] = (char) shorts[i];
+        }
+    }
+
+    @Benchmark
+    public void charToByte() {
+        for (int i = 0; i < SIZE; i++) {
+            bytes[i] = (byte) chars[i];
+        }
+    }
+
+    @Benchmark
+    public void charToShort() {
+        for (int i = 0; i < SIZE; i++) {
+            shorts[i] = (short) chars[i];
+        }
+    }
+
+    @Benchmark
+    public void intToByte() {
+        for (int i = 0; i < SIZE; i++) {
+            bytes[i] = (byte) ints[i];
+        }
+    }
+
+    @Benchmark
+    public void intToShort() {
+        for (int i = 0; i < SIZE; i++) {
+            shorts[i] = (short) ints[i];
+        }
+    }
+
+    @Benchmark
+    public void intToChar() {
+        for (int i = 0; i < SIZE; i++) {
+            chars[i] = (char) ints[i];
+        }
+    }
+
+    @Benchmark
+    public void longToByte() {
+        for (int i = 0; i < SIZE; i++) {
+            bytes[i] = (byte) longs[i];
+        }
+    }
+
+    @Benchmark
+    public void longToShort() {
+        for (int i = 0; i < SIZE; i++) {
+            shorts[i] = (short) longs[i];
+        }
+    }
+
+    @Benchmark
+    public void longToChar() {
+        for (int i = 0; i < SIZE; i++) {
+            chars[i] = (char) longs[i];
+        }
+    }
+
+    @Benchmark
+    public void longToInt() {
+        for (int i = 0; i < SIZE; i++) {
+            ints[i] = (int) longs[i];
+        }
+    }
+
+    // Widening
+
+    @Benchmark
+    public void byteToShort() {
+        for (int i = 0; i < SIZE; i++) {
+            shorts[i] = bytes[i];
+        }
+    }
+
+    @Benchmark
+    public void byteToChar() {
+        for (int i = 0; i < SIZE; i++) {
+            chars[i] = (char) bytes[i];
+        }
+    }
+
+    @Benchmark
+    public void byteToInt() {
+        for (int i = 0; i < SIZE; i++) {
+            ints[i] = bytes[i];
+        }
+    }
+
+    @Benchmark
+    public void byteToLong() {
+        for (int i = 0; i < SIZE; i++) {
+            longs[i] = bytes[i];
+        }
+    }
+
+    @Benchmark
+    public void shortToInt() {
+        for (int i = 0; i < SIZE; i++) {
+            ints[i] = shorts[i];
+        }
+    }
+
+    @Benchmark
+    public void shortToLong() {
+        for (int i = 0; i < SIZE; i++) {
+            longs[i] = shorts[i];
+        }
+    }
+
+    @Benchmark
+    public void charToInt() {
+        for (int i = 0; i < SIZE; i++) {
+            ints[i] = chars[i];
+        }
+    }
+
+    @Benchmark
+    public void charToLong() {
+        for (int i = 0; i < SIZE; i++) {
+            longs[i] = chars[i];
+        }
+    }
+
+    @Benchmark
+    public void intToLong() {
+        for (int i = 0; i < SIZE; i++) {
+            longs[i] = ints[i];
+        }
+    }
+
+}

From d7c8000a493e58c677fed2e04678bb56e70dffc4 Mon Sep 17 00:00:00 2001
From: Jayathirth D V 
Date: Thu, 26 Feb 2026 05:49:31 +0000
Subject: [PATCH 10/54] 8378623: Use unique font names in FormatCharAdvanceTest

Reviewed-by: psadhukhan
---
 .../TextLayout/FormatCharAdvanceTest.java     | 33 +++++++++++--------
 1 file changed, 19 insertions(+), 14 deletions(-)

diff --git a/test/jdk/java/awt/font/TextLayout/FormatCharAdvanceTest.java b/test/jdk/java/awt/font/TextLayout/FormatCharAdvanceTest.java
index 63cd890f1db..4a3f759c559 100644
--- a/test/jdk/java/awt/font/TextLayout/FormatCharAdvanceTest.java
+++ b/test/jdk/java/awt/font/TextLayout/FormatCharAdvanceTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2025, 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
@@ -67,9 +67,13 @@ public class FormatCharAdvanceTest {
      * font.em = 2048
      * font.ascent = 1638
      * font.descent = 410
-     * font.familyname = 'Test'
-     * font.fontname = 'Test'
-     * font.fullname = 'Test'
+     * font.familyname = 'TTFTest'
+     * font.fontname = 'TTFTest'
+     * font.fullname = 'TTFTest'
+     * #Use below values for Type 1 font
+     * #font.familyname = 'Type1Test'
+     * #font.fontname = 'Type1Test'
+     * #font.fullname = 'Type1Test'
      * font.copyright = ''
      * font.autoWidth(0, 0, 2048)
      *
@@ -107,29 +111,30 @@ public class FormatCharAdvanceTest {
      *
      * ttf = 'test.ttf'     # TrueType
      * t64 = 'test.ttf.txt' # TrueType Base64
-     * pfb = 'test.pfb'     # PostScript Type1
-     * p64 = 'test.pfb.txt' # PostScript Type1 Base64
+     * #Use commented lines to generate Type1 font
+     * #pfb = 'test.pfb'     # PostScript Type1
+     * #p64 = 'test.pfb.txt' # PostScript Type1 Base64
      *
      * font.generate(ttf)
-     * font.generate(pfb)
+     * #font.generate(pfb)
      *
      * with open(ttf, 'rb') as f1:
      *   encoded = base64.b64encode(f1.read())
      *   with open(t64, 'wb') as f2:
      *     f2.write(encoded)
      *
-     * with open(pfb, 'rb') as f3:
-     *   encoded = base64.b64encode(f3.read())
-     *   with open(p64, 'wb') as f4:
-     *     f4.write(encoded)
+     * #with open(pfb, 'rb') as f3:
+     *   #encoded = base64.b64encode(f3.read())
+     *   #with open(p64, 'wb') as f4:
+     *     #f4.write(encoded)
      * 
*/ - private static final String TTF_BYTES = "AAEAAAANAIAAAwBQRkZUTarBS1AAABbcAAAAHE9TLzKD7vqWAAABWAAAAGBjbWFw11zF/AAAAvwAAANSY3Z0IABEBREAAAZQAAAABGdhc3D//wADAAAW1AAAAAhnbHlmgVJ3qAAAB4gAAAnMaGVhZCqFqboAAADcAAAANmhoZWEIcgJiAAABFAAAACRobXR4L1UevAAAAbgAAAFEbG9jYb8EwZoAAAZUAAABNG1heHAA4ABCAAABOAAAACBuYW1lJWcF2wAAEVQAAAGJcG9zdBSfZd0AABLgAAAD8QABAAAAAQAAzMHptF8PPPUACwgAAAAAAORfr7QAAAAA5F+vtABEAAACZAVVAAAACAACAAAAAAAAAAEAAAVVAAAAuAJYAAAAAAJkAAEAAAAAAAAAAAAAAAAAAAAJAAEAAACZAAgAAgAIAAIAAgAAAAEAAQAAAEAALgABAAEABAJXAZAABQAABTMFmQAAAR4FMwWZAAAD1wBmAhIAAAIABQMAAAAAAACAACADAgAAABECAKgAAAAAUGZFZACAAAn//wZm/mYAuAVVAAAAAAABAAAAAADIAMgAAAAgAAEC7ABEAAAAAAJYAGQCWABkAlgAZAJYAGQCWABkAjkAAAJYAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAAAAFAAAAAwAAACwAAAAEAAAA7AABAAAAAAJMAAMAAQAAACwAAwAKAAAA7AAEAMAAAAAoACAABAAIAA0AIAA5AFoAegCFAK0GBQYcBt0HDwiRCOIYDiAPIC8gb/7///v//wAAAAkAIAAwAEEAYQCFAK0GAAYcBt0HDwiQCOIYDiALICggYP7///n//wAA/+f/2P/R/8v/wf+a+kj6Mvly+UH3wfdx6EbgSuAy4AIBcwAAAAEAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAMABAAFAAYAAgBzAHQAdQAMAAAAAAFgAAAAAAAAABwAAAAJAAAADAAAAAMAAAANAAAADQAAAAIAAAAgAAAAIAAAAAcAAAAwAAAAOQAAAAgAAABBAAAAWgAAABIAAABhAAAAegAAACwAAACFAAAAhQAAAEYAAACtAAAArQAAAEcAAAYAAAAGBQAAAEgAAAYcAAAGHAAAAE4AAAbdAAAG3QAAAE8AAAcPAAAHDwAAAFAAAAiQAAAIkQAAAFEAAAjiAAAI4gAAAFMAABgOAAAYDgAAAFQAACALAAAgDwAAAFUAACAoAAAgLwAAAFoAACBgAAAgbwAAAGIAAP7/AAD+/wAAAHIAAP/5AAD/+wAAAHMAARC9AAEQvQAAAHYAARDNAAEQzQAAAHcAATQwAAE0PwAAAHgAAbygAAG8owAAAIgAAdFzAAHRegAAAIwADgABAA4AAQAAAJQADgAgAA4AIQAAAJUADgB+AA4AfwAAAJcAAAEGAAABAAAAAAAAAAEDBAUGAgAAAAAAAAAAAAAAAAAAAAEAAAcAAAAAAAAAAAAAAAAAAAAICQoLDA0ODxARAAAAAAAAABITFBUWFxgZGhscHR4fICEiIyQlJicoKSorAAAAAAAALC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAURAAAALAAsADQAPABEAEwAVABUAFwAZABsAHQAfACEAIwAlACcAKQArAC0ALwAxADMANQA3ADkAOwA9AD8AQQBDAEUARwBJAEsATQBPAFEAUwBVAFcAWQBbAF0AYYBjgGWAZ4BpgGuAbYBvgHGAc4B1gHeAeYB7gH2Af4CBgIOAhYCHgImAi4CNgI+AkYCTgJWAl4CZgJuAnYCfgKGAo4ClgKeAqYCrgK2Ar4CxgLOAtYC3gLmAu4C9gL+AwYDDgMWAx4DJgMuAzYDPgNGA04DVgNeA2YDbgN2A34DhgOOA5YDngOmA64DtgO+A8YDzgPWA94D5gPuA/YD/gQGBA4EFgQeBCYELgQ2BD4ERgROBFYEXgRmBG4EdgR+BIYEjgSWBJ4EpgSuBLYEvgTGBM4E1gTeBOYAAgBEAAACZAVVAAMABwAusQEALzyyBwQA7TKxBgXcPLIDAgDtMgCxAwAvPLIFBADtMrIHBgH8PLIBAgDtMjMRIRElIREhRAIg/iQBmP5oBVX6q0QEzQAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAAAAgBkAGQB9ADIAAMABwAANzUhFSE1IRVkAZD+cAGQZGRkZGT//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAAAAAAOAK4AAQAAAAAAAAAAAAIAAQAAAAAAAQAEAA0AAQAAAAAAAgAHACIAAQAAAAAAAwAgAGwAAQAAAAAABAAEAJcAAQAAAAAABQAPALwAAQAAAAAABgAEANYAAwABBAkAAAAAAAAAAwABBAkAAQAIAAMAAwABBAkAAgAOABIAAwABBAkAAwBAACoAAwABBAkABAAIAI0AAwABBAkABQAeAJwAAwABBAkABgAIAMwAAAAAVABlAHMAdAAAVGVzdAAAUgBlAGcAdQBsAGEAcgAAUmVndWxhcgAARgBvAG4AdABGAG8AcgBnAGUAIAAyAC4AMAAgADoAIABUAGUAcwB0ACAAOgAgADMAMAAtADUALQAyADAAMgA1AABGb250Rm9yZ2UgMi4wIDogVGVzdCA6IDMwLTUtMjAyNQAAVABlAHMAdAAAVGVzdAAAVgBlAHIAcwBpAG8AbgAgADAAMAAxAC4AMAAwADAAAFZlcnNpb24gMDAxLjAwMAAAVABlAHMAdAAAVGVzdAAAAAAAAgAAAAAAAP9nAGYAAAAAAAAAAAAAAAAAAAAAAAAAAACZAAAAAQECAQMBBAEFAQYAAwATABQAFQAWABcAGAAZABoAGwAcACQAJQAmACcAKAApACoAKwAsAC0ALgAvADAAMQAyADMANAA1ADYANwA4ADkAOgA7ADwAPQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0BBwEIAQkBCgELAQwBDQEOAQ8BEAERARIBEwEUARUBFgEXARgBGQEaARsBHAEdAR4BHwEgASEBIgEjASQBJQEmAScBKAEpASoBKwEsAS0BLgEvATABMQEyATMBNAE1ATYBNwE4ATkBOgE7ATwBPQE+AT8BQAFBAUIBQwFEAUUBRgFHAUgBSQFKAUsBTAFNAU4BTwFQAVEBUgFTAVQBVQFWAVcBWAFZB3VuaTAwMEQHdW5pMDAwOQd1bmkwMDBBB3VuaTAwMEIHdW5pMDAwQwd1bmkwMDg1B3VuaTAwQUQHdW5pMDYwMAd1bmkwNjAxB3VuaTA2MDIHdW5pMDYwMwd1bmkwNjA0B3VuaTA2MDUHdW5pMDYxQwd1bmkwNkREB3VuaTA3MEYHdW5pMDg5MAd1bmkwODkxB3VuaTA4RTIHdW5pMTgwRQd1bmkyMDBCB3VuaTIwMEMHdW5pMjAwRAd1bmkyMDBFB3VuaTIwMEYHdW5pMjAyOAd1bmkyMDI5B3VuaTIwMkEHdW5pMjAyQgd1bmkyMDJDB3VuaTIwMkQHdW5pMjAyRQd1bmkyMDJGB3VuaTIwNjAHdW5pMjA2MQd1bmkyMDYyB3VuaTIwNjMHdW5pMjA2NAd1bmkyMDY1B3VuaTIwNjYHdW5pMjA2Nwd1bmkyMDY4B3VuaTIwNjkHdW5pMjA2QQd1bmkyMDZCB3VuaTIwNkMHdW5pMjA2RAd1bmkyMDZFB3VuaTIwNkYHdW5pRkVGRgd1bmlGRkY5B3VuaUZGRkEHdW5pRkZGQgZ1MTEwQkQGdTExMENEBnUxMzQzMAZ1MTM0MzEGdTEzNDMyBnUxMzQzMwZ1MTM0MzQGdTEzNDM1BnUxMzQzNgZ1MTM0MzcGdTEzNDM4BnUxMzQzOQZ1MTM0M0EGdTEzNDNCBnUxMzQzQwZ1MTM0M0QGdTEzNDNFBnUxMzQzRgZ1MUJDQTAGdTFCQ0ExBnUxQkNBMgZ1MUJDQTMGdTFEMTczBnUxRDE3NAZ1MUQxNzUGdTFEMTc2BnUxRDE3NwZ1MUQxNzgGdTFEMTc5BnUxRDE3QQZ1RTAwMDEGdUUwMDIwBnVFMDAyMQZ1RTAwN0UGdUUwMDdGAAAAAAAAAf//AAIAAAABAAAAAOIB6+cAAAAA5F+vtAAAAADkX6+0"; + private static final String TTF_BYTES = "AAEAAAANAIAAAwBQRkZUTbCUBjwAABcAAAAAHE9TLzKD7vqWAAABWAAAAGBjbWFw11zF/AAAAvwAAANSY3Z0IABEBREAAAZQAAAABGdhc3D//wADAAAW+AAAAAhnbHlmgVJ3qAAAB4gAAAnMaGVhZC1MmToAAADcAAAANmhoZWEIcgJiAAABFAAAACRobXR4L1UevAAAAbgAAAFEbG9jYb8EwZoAAAZUAAABNG1heHAA4ABCAAABOAAAACBuYW1lLzI4NgAAEVQAAAGtcG9zdBSfZd0AABMEAAAD8QABAAAAAQAAp/gvll8PPPUACwgAAAAAAOXDJ3QAAAAA5cMndABEAAACZAVVAAAACAACAAAAAAAAAAEAAAVVAAAAuAJYAAAAAAJkAAEAAAAAAAAAAAAAAAAAAAAJAAEAAACZAAgAAgAIAAIAAgAAAAEAAQAAAEAALgABAAEABAJXAZAABQAABTMFmQAAAR4FMwWZAAAD1wBmAhIAAAIABQMAAAAAAACAACADAgAAABECAKgAAAAAUGZFZACAAAn//wZm/mYAuAVVAAAAAAABAAAAAADIAMgAAAAgAAEC7ABEAAAAAAJYAGQCWABkAlgAZAJYAGQCWABkAjkAAAJYAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAZABkAGQAAAAFAAAAAwAAACwAAAAEAAAA7AABAAAAAAJMAAMAAQAAACwAAwAKAAAA7AAEAMAAAAAoACAABAAIAA0AIAA5AFoAegCFAK0GBQYcBt0HDwiRCOIYDiAPIC8gb/7///v//wAAAAkAIAAwAEEAYQCFAK0GAAYcBt0HDwiQCOIYDiALICggYP7///n//wAA/+f/2P/R/8v/wf+a+kj6Mvly+UH3wfdx6EbgSuAy4AIBcwAAAAEAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAMABAAFAAYAAgBzAHQAdQAMAAAAAAFgAAAAAAAAABwAAAAJAAAADAAAAAMAAAANAAAADQAAAAIAAAAgAAAAIAAAAAcAAAAwAAAAOQAAAAgAAABBAAAAWgAAABIAAABhAAAAegAAACwAAACFAAAAhQAAAEYAAACtAAAArQAAAEcAAAYAAAAGBQAAAEgAAAYcAAAGHAAAAE4AAAbdAAAG3QAAAE8AAAcPAAAHDwAAAFAAAAiQAAAIkQAAAFEAAAjiAAAI4gAAAFMAABgOAAAYDgAAAFQAACALAAAgDwAAAFUAACAoAAAgLwAAAFoAACBgAAAgbwAAAGIAAP7/AAD+/wAAAHIAAP/5AAD/+wAAAHMAARC9AAEQvQAAAHYAARDNAAEQzQAAAHcAATQwAAE0PwAAAHgAAbygAAG8owAAAIgAAdFzAAHRegAAAIwADgABAA4AAQAAAJQADgAgAA4AIQAAAJUADgB+AA4AfwAAAJcAAAEGAAABAAAAAAAAAAEDBAUGAgAAAAAAAAAAAAAAAAAAAAEAAAcAAAAAAAAAAAAAAAAAAAAICQoLDA0ODxARAAAAAAAAABITFBUWFxgZGhscHR4fICEiIyQlJicoKSorAAAAAAAALC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAURAAAALAAsADQAPABEAEwAVABUAFwAZABsAHQAfACEAIwAlACcAKQArAC0ALwAxADMANQA3ADkAOwA9AD8AQQBDAEUARwBJAEsATQBPAFEAUwBVAFcAWQBbAF0AYYBjgGWAZ4BpgGuAbYBvgHGAc4B1gHeAeYB7gH2Af4CBgIOAhYCHgImAi4CNgI+AkYCTgJWAl4CZgJuAnYCfgKGAo4ClgKeAqYCrgK2Ar4CxgLOAtYC3gLmAu4C9gL+AwYDDgMWAx4DJgMuAzYDPgNGA04DVgNeA2YDbgN2A34DhgOOA5YDngOmA64DtgO+A8YDzgPWA94D5gPuA/YD/gQGBA4EFgQeBCYELgQ2BD4ERgROBFYEXgRmBG4EdgR+BIYEjgSWBJ4EpgSuBLYEvgTGBM4E1gTeBOYAAgBEAAACZAVVAAMABwAusQEALzyyBwQA7TKxBgXcPLIDAgDtMgCxAwAvPLIFBADtMrIHBgH8PLIBAgDtMjMRIRElIREhRAIg/iQBmP5oBVX6q0QEzQAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAAAAgBkAGQB9ADIAAMABwAANzUhFSE1IRVkAZD+cAGQZGRkZGT//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAD//wBkAGQB9ADIEgYALAAA//8AZABkAfQAyBIGACwAAP//AGQAZAH0AMgSBgAsAAAAAAAOAK4AAQAAAAAAAAAAAAIAAQAAAAAAAQAHABMAAQAAAAAAAgAHACsAAQAAAAAAAwAjAHsAAQAAAAAABAAHAK8AAQAAAAAABQAPANcAAQAAAAAABgAHAPcAAwABBAkAAAAAAAAAAwABBAkAAQAOAAMAAwABBAkAAgAOABsAAwABBAkAAwBGADMAAwABBAkABAAOAJ8AAwABBAkABQAeALcAAwABBAkABgAOAOcAAAAAVABUAEYAVABlAHMAdAAAVFRGVGVzdAAAUgBlAGcAdQBsAGEAcgAAUmVndWxhcgAARgBvAG4AdABGAG8AcgBnAGUAIAAyAC4AMAAgADoAIABUAFQARgBUAGUAcwB0ACAAOgAgADIANAAtADIALQAyADAAMgA2AABGb250Rm9yZ2UgMi4wIDogVFRGVGVzdCA6IDI0LTItMjAyNgAAVABUAEYAVABlAHMAdAAAVFRGVGVzdAAAVgBlAHIAcwBpAG8AbgAgADAAMAAxAC4AMAAwADAAAFZlcnNpb24gMDAxLjAwMAAAVABUAEYAVABlAHMAdAAAVFRGVGVzdAAAAAAAAgAAAAAAAP9nAGYAAAAAAAAAAAAAAAAAAAAAAAAAAACZAAAAAQECAQMBBAEFAQYAAwATABQAFQAWABcAGAAZABoAGwAcACQAJQAmACcAKAApACoAKwAsAC0ALgAvADAAMQAyADMANAA1ADYANwA4ADkAOgA7ADwAPQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0BBwEIAQkBCgELAQwBDQEOAQ8BEAERARIBEwEUARUBFgEXARgBGQEaARsBHAEdAR4BHwEgASEBIgEjASQBJQEmAScBKAEpASoBKwEsAS0BLgEvATABMQEyATMBNAE1ATYBNwE4ATkBOgE7ATwBPQE+AT8BQAFBAUIBQwFEAUUBRgFHAUgBSQFKAUsBTAFNAU4BTwFQAVEBUgFTAVQBVQFWAVcBWAFZB3VuaTAwMEQHdW5pMDAwOQd1bmkwMDBBB3VuaTAwMEIHdW5pMDAwQwd1bmkwMDg1B3VuaTAwQUQHdW5pMDYwMAd1bmkwNjAxB3VuaTA2MDIHdW5pMDYwMwd1bmkwNjA0B3VuaTA2MDUHdW5pMDYxQwd1bmkwNkREB3VuaTA3MEYHdW5pMDg5MAd1bmkwODkxB3VuaTA4RTIHdW5pMTgwRQd1bmkyMDBCB3VuaTIwMEMHdW5pMjAwRAd1bmkyMDBFB3VuaTIwMEYHdW5pMjAyOAd1bmkyMDI5B3VuaTIwMkEHdW5pMjAyQgd1bmkyMDJDB3VuaTIwMkQHdW5pMjAyRQd1bmkyMDJGB3VuaTIwNjAHdW5pMjA2MQd1bmkyMDYyB3VuaTIwNjMHdW5pMjA2NAd1bmkyMDY1B3VuaTIwNjYHdW5pMjA2Nwd1bmkyMDY4B3VuaTIwNjkHdW5pMjA2QQd1bmkyMDZCB3VuaTIwNkMHdW5pMjA2RAd1bmkyMDZFB3VuaTIwNkYHdW5pRkVGRgd1bmlGRkY5B3VuaUZGRkEHdW5pRkZGQgZ1MTEwQkQGdTExMENEBnUxMzQzMAZ1MTM0MzEGdTEzNDMyBnUxMzQzMwZ1MTM0MzQGdTEzNDM1BnUxMzQzNgZ1MTM0MzcGdTEzNDM4BnUxMzQzOQZ1MTM0M0EGdTEzNDNCBnUxMzQzQwZ1MTM0M0QGdTEzNDNFBnUxMzQzRgZ1MUJDQTAGdTFCQ0ExBnUxQkNBMgZ1MUJDQTMGdTFEMTczBnUxRDE3NAZ1MUQxNzUGdTFEMTc2BnUxRDE3NwZ1MUQxNzgGdTFEMTc5BnUxRDE3QQZ1RTAwMDEGdUUwMDIwBnVFMDAyMQZ1RTAwN0UGdUUwMDdGAAAAAAAAAf//AAIAAAABAAAAAOUNt1MAAAAA5cMndAAAAADlwyd0"; /** - * Same font as above, but in PostScript Type1 (PFB) format. + * Same font as above, but in PostScript Type1 (PFB) format with different font name. */ - private static final String TYPE1_BYTES = "gAFSBwAAJSFQUy1BZG9iZUZvbnQtMS4wOiBUZXN0IDAwMS4wMDAKJSVUaXRsZTogVGVzdAolVmVyc2lvbjogMDAxLjAwMAolJUNyZWF0aW9uRGF0ZTogRnJpIE1heSAzMCAyMDo1NTo0OCAyMDI1CiUlQ3JlYXRvcjogRGFuaWVsIEdyZWRsZXIKJSAyMDI1LTUtMzA6IENyZWF0ZWQgd2l0aCBGb250Rm9yZ2UgKGh0dHA6Ly9mb250Zm9yZ2Uub3JnKQolIEdlbmVyYXRlZCBieSBGb250Rm9yZ2UgMjAyMzAxMDEgKGh0dHA6Ly9mb250Zm9yZ2Uuc2YubmV0LykKJSVFbmRDb21tZW50cwoKMTAgZGljdCBiZWdpbgovRm9udFR5cGUgMSBkZWYKL0ZvbnRNYXRyaXggWzAuMDAwNDg4MjgxIDAgMCAwLjAwMDQ4ODI4MSAwIDAgXXJlYWRvbmx5IGRlZgovRm9udE5hbWUgL1Rlc3QgZGVmCi9Gb250QkJveCB7MTAwIDEwMCA1MDAgMjAwIH1yZWFkb25seSBkZWYKL1BhaW50VHlwZSAwIGRlZgovRm9udEluZm8gMTAgZGljdCBkdXAgYmVnaW4KIC92ZXJzaW9uICgwMDEuMDAwKSByZWFkb25seSBkZWYKIC9Ob3RpY2UgKCkgcmVhZG9ubHkgZGVmCiAvRnVsbE5hbWUgKFRlc3QpIHJlYWRvbmx5IGRlZgogL0ZhbWlseU5hbWUgKFRlc3QpIHJlYWRvbmx5IGRlZgogL1dlaWdodCAoUmVndWxhcikgcmVhZG9ubHkgZGVmCiAvRlNUeXBlIDAgZGVmCiAvSXRhbGljQW5nbGUgMCBkZWYKIC9pc0ZpeGVkUGl0Y2ggZmFsc2UgZGVmCiAvVW5kZXJsaW5lUG9zaXRpb24gLTIwNC44IGRlZgogL1VuZGVybGluZVRoaWNrbmVzcyAxMDIuNCBkZWYKZW5kIHJlYWRvbmx5IGRlZgovRW5jb2RpbmcgMjU2IGFycmF5CiAwIDEgMjU1IHsgMSBpbmRleCBleGNoIC8ubm90ZGVmIHB1dH0gZm9yCmR1cCA5L3VuaTAwMDkgcHV0CmR1cCAxMC91bmkwMDBBIHB1dApkdXAgMTEvdW5pMDAwQiBwdXQKZHVwIDEyL3VuaTAwMEMgcHV0CmR1cCAxMy91bmkwMDBEIHB1dApkdXAgMzIvc3BhY2UgcHV0CmR1cCA0OC96ZXJvIHB1dApkdXAgNDkvb25lIHB1dApkdXAgNTAvdHdvIHB1dApkdXAgNTEvdGhyZWUgcHV0CmR1cCA1Mi9mb3VyIHB1dApkdXAgNTMvZml2ZSBwdXQKZHVwIDU0L3NpeCBwdXQKZHVwIDU1L3NldmVuIHB1dApkdXAgNTYvZWlnaHQgcHV0CmR1cCA1Ny9uaW5lIHB1dApkdXAgNjUvQSBwdXQKZHVwIDY2L0IgcHV0CmR1cCA2Ny9DIHB1dApkdXAgNjgvRCBwdXQKZHVwIDY5L0UgcHV0CmR1cCA3MC9GIHB1dApkdXAgNzEvRyBwdXQKZHVwIDcyL0ggcHV0CmR1cCA3My9JIHB1dApkdXAgNzQvSiBwdXQKZHVwIDc1L0sgcHV0CmR1cCA3Ni9MIHB1dApkdXAgNzcvTSBwdXQKZHVwIDc4L04gcHV0CmR1cCA3OS9PIHB1dApkdXAgODAvUCBwdXQKZHVwIDgxL1EgcHV0CmR1cCA4Mi9SIHB1dApkdXAgODMvUyBwdXQKZHVwIDg0L1QgcHV0CmR1cCA4NS9VIHB1dApkdXAgODYvViBwdXQKZHVwIDg3L1cgcHV0CmR1cCA4OC9YIHB1dApkdXAgODkvWSBwdXQKZHVwIDkwL1ogcHV0CmR1cCA5Ny9hIHB1dApkdXAgOTgvYiBwdXQKZHVwIDk5L2MgcHV0CmR1cCAxMDAvZCBwdXQKZHVwIDEwMS9lIHB1dApkdXAgMTAyL2YgcHV0CmR1cCAxMDMvZyBwdXQKZHVwIDEwNC9oIHB1dApkdXAgMTA1L2kgcHV0CmR1cCAxMDYvaiBwdXQKZHVwIDEwNy9rIHB1dApkdXAgMTA4L2wgcHV0CmR1cCAxMDkvbSBwdXQKZHVwIDExMC9uIHB1dApkdXAgMTExL28gcHV0CmR1cCAxMTIvcCBwdXQKZHVwIDExMy9xIHB1dApkdXAgMTE0L3IgcHV0CmR1cCAxMTUvcyBwdXQKZHVwIDExNi90IHB1dApkdXAgMTE3L3UgcHV0CmR1cCAxMTgvdiBwdXQKZHVwIDExOS93IHB1dApkdXAgMTIwL3ggcHV0CmR1cCAxMjEveSBwdXQKZHVwIDEyMi96IHB1dApkdXAgMTMzL3VuaTAwODUgcHV0CmR1cCAxNzMvdW5pMDBBRCBwdXQKcmVhZG9ubHkgZGVmCmN1cnJlbnRkaWN0IGVuZApjdXJyZW50ZmlsZSBlZXhlYwqAAo0WAAB0P4QT82NsqFqf/vtQtLsnMCpcwKtuL5Wb8g0yDDc8ISjQoM5wcrH2cqCqOMPA7OsEtEyxdKHDFhLXH/ogyQlUJWN4Ny95WwvylB9DfwWfQa4FmMAFFf7xhzM1V/Ms4yqe59S6tl2lND+ScH4s/PPozkRuWtrDn8N+zmS2izVs4NcQ9FsefyzXaKvKFDYINmh2GhAJRkFi0FTB9r8sRqMZs8ZkUodjFsE6kmRW02YpWP1WdA1YVnNuYQT4E+0xkVZ3eTTuscVEWua/buWeWxlwi0KH20ubr5iCkavAb953/MMe4XMKlPvGzsx0Slmp9qOOLD0ko2287peB1DvLavHCG/r2rr8MhqsKVoSyFr36sVd9hMSQrwFxpRjVEjtt5HDGcbHwy3ylp8b1oopSl5AQmeoW/oGT0rPr+358A+Qd2/wpQgStXDcDExQWDrdOL7J5Fr7VBDu8NNORXc7c5uKb2iVQq5AOF+Yfa5bH4reIFcWrAItBML9L9b8sOf1QKzGymFzgcDW3EEx07Y07ys95zSLkYtY5lkjm07GFSyM9cuWhRctY6RTcjTAFNdbxOUBXbIGf4Q8nhdXXi3IKhYdqdgKEsWphwKEdQeP7QYqW4bPSB881DjF/e7r6PIkua8MXGI3G1I0C53TIFnHXai5dtVJ4cZhdaTzgoD9K6zYMNsb8Tof6THYx+cRUzPbJmb+VbprjDk96+92jF+P0EwubV0GQMLEdCyPDV1u/vIHPePqSJt2/YjgkXEugRbyqzFwfZJdeAmkzcqs1CU9EiqrwgqbEfdmWWwv9BDxgkWD4omPKAKX1A6asv/UVfH8lebHSbrKddpR8XU/C2I/t7UhI19oTFqIvUL061MrZPiHZaFE9bnvJw+P91hF+MoPs69ddhD4Kj6z6MJYNGlvAZMuUM/RdAUwE3HHhwGiCN3Hqi4V+byVeB95B/8YLQK1CiW/pgfU7TqZ1d5nWGoAXAcAu6UYGvZZ0ChX3AEPlIFJ4x4hXfBo0I/k/TEHus/u5dNm/+ixyBcr/rX/e2yPIBfJkBJDG8x/y7JaxOFAD1NMQ4zWjbzP1uPpiGzRKfCXYLF6YXLfGDKJ1w3IENGwIMXBgqOx6O2v2xkYhcAUkrZ2Nw3xpRrnj2RqGCGwz00AHrl9AU7CNaM8BkSe6d86xT8teVYuOk926Xj4/+Kx6rfu526Ylz91kxebopcMvql6ysRVzzSGsW2ec9ZPJo1Q/WKb+tCvBm8OdUnRi+DldIajpytyl08TmlS+IRUcHZbxoIjxb7ZCvF8hd03yDhs9bsUSO6h7jbhegenLIiQPX7RtsGAg3logZLD0NUjcAm2tKBieMHhMxAD89lVmuMkNj5r6EaixXvkvhgqzhjPExdu30Knife5IEnlCvIlMCh1EXQsY9KRkzeTRTKfnZTJ/idze+cX0nCEGcFrvCCjZRfNuaLRHx73o2KlDHmoYBm1mFEEvfUReQxS987AiVfSF7cs8IrLEqV9qe2mCAv7ATbVUFbnvYxTBYvHL9sc4892rLrjSu/yP5RZmmIMOpTH8CStLw1zGAcXH3W3ZfPjQkEA4jzvo1U5Oi9EkBKqlgqjj2pFLWepwuNG/L3Iyr36frW6NFtqCxyVQYcNwOTnmQjY0LXPAKxyz2l+xyo/gcDY8nqtWms5aqINgemqM0pG2wBt3GawARbEVkkKllyB/WJbRw0GGHktmj73ixkTulD6nHZ+vMd+aS8iKXPa2ASEOPpxp515DZxg+VYZIrM0h4mDdRff4To/8NKs7Kx4IZx2qzlhIKS2zHpLwuY/U2Wt80e9nqMCFEtnS8sKpcy1rrE9FzXsFUNtYE6LdIat4ygQxoq24Y6D3bfDpl3E8wMvECaVCJX8lfBhQcGGU6+Jba1qfQ7jonjQM0zfoOwHrApk/dkPkSdjQy7UM+dZNMtgZf2N46UuWC2YCtcqCN1X+o5SpojTgXNmTjUy3KOy6L4GNYOxutsDhWiah6rJ+FGVL9D51MJvT3l02T1+LpNt8ZeZQSkZpx7NdFFTFA4/SE8zycfBLNm71Q9pjQKa30TnCY9ZkMEH9rnArLV0w2Gi6LoJoWpT7GoAB2Cdvi3x9wGDdt60K6oABWiD5mpAv4KfrJMBn5dRDJVyRPARXxwBUROAc3BxY8St3WuWKqDqqef0t0rlqAXGynPrcAjqFMXc/GBWORQ7W/dTvbu/eZb+apjKEX7szjaY4cSRsNge4gTyCEsfhLrdBkncM7up9jj206tIaqZQILxHAnrVwYplJ5D2EvSSLYvxFEVHSrI19aNJEvDK64tzXCV+P4yOCOuXpBmc15PDlrMQEauqrD+xneCO+CrCbudHXOJsbmvQq56+ovLp5SNBfdEPQpqo5tBgQaNHcEjg/iVt++uLxT3vAEFW5d7WXPMYdy+XqoMmdRDOzey0Mdx5BZ92rNM/LthQa6F54nvzkypM64HdxCYlri8cO3k0G6bp2eWdseP0P4zMc5QikuXc/Dr4NztBYe2yJLbLLesWSB8nOWcl+gd0GMX5PY4P5mn5WJDNStLWPdD9NapzMsyx6lZwR9Tfv/XSmay9LEo9YaaxysWfllDIasUCdvhZVi7LJvPu/0GbuHLOz9mP6prkF8h8KmjBYMlMktouA23G74M+Pkdfbj9KAM8zOYCgQFZUaXx3iZ4m3uBtDPeKjUcdFZSnHdW11eSv5aCz2fMbExV/qnPOSMbkR5rvpR71WwVZP6j3tNWr8jlPQ8d60k8jXPy7d8wjw9obnDEpvKzKreEzjfA0wCovNt7FLH9oxWmO5TF8JMg/U7+ToEv0fPAW475dXTXdue98/k/c+3+LCJNbHzBBx14CzpteKXKqGNA3jwgJUhfDsTISiN4gF222zIi1deY9BspjPl7jergbwh+ZPdfk2BLaPTDeNUycKdeiFoJEd8gKLvjMrnPa9IX4HwR9gJSjsQ0UWhnYuaXdk12zk8sVkGJAJLrphh5tHcd4LwG2rWcVXwM/2zw1YXQR+jffC1uxUEPVaq1fSf9RB6iEb8LgIollE+gDEybc+Dw3Q/gxVe5/Nu0vHHur6B+4YEcxvz3O5cYKUQTxDgG4mXJhqZ6z7etSWINChQyP6PUFFbsUIDXjfuHZ9oF4ce1NNOnn/RIwm/u/+AduDTtqloUooZjqak4VbvmBEZcW75liKm0MggeilL0nl5arItzTwE8OudJDBkJ/xnf1yZIgeFKSODIz5aQrIiSMJX3BGRxHEEQrm1xtwCfjtMPpFhFtG+o5fjMlCnowJ6+/HrG3FdZKn4/gv7qCxF2/3NW2J4OWuXbjEsUlSHu57DFvhrVl/q8jv81OfXhZKutYQWjaDWwOQHR+ym6wvMyQ9YfiiJpBXa+Ig9uGAbERyApc8wsCLcy0d8Msxx9PAfhrDa+Gf2yhYGA57t8iGxEcoI0A4B8zKVqYXKf4AdsrVzE9cUpfRN/HH8OGWyv9mKMTJyGJQql/OH5hYHnvJVKZXIz6l3nL/7gnpYaGtASiV1q+JwO7WSk1pfwT9SE4sFl7uS7f3pu4BwPhcz/wyN82f144yav11mrGqypOMaMDR27/L0sW1c3hWBBa8BMU/EuwF7ldclS9nxmFHOc35RLruyQ26cp1niukcpK42wg3ozqGQLoQRIoin0AWnUwnOmkdBEkILqFCiWgERDZuCB7G3pZJW/32HPgD3byO0lH8JF6OiINsUmM+75Y3qdvuepTHxXwpDa9Isero3x/f+UWGGUO12s+Ou2yQKtLsQaBNSTaGEBVCAtpJ58TgZ+KfVyhgRQdINr7GuGq9iRPQBY00anspxvsrhfffggqOariHO8h0jdEZPJarJJAufQbYgKiACtJ8iG6jlIs3GfWRI0jRYDw+kHPc2/A6fS5XGF360aX1I6iy5J1pZpN+6stJq5MQ8QRHopTJWQ0DW1Pq46BglmHH9av/X4tvLFFyyC4X6OB2jDb9+XwwcuJ2t/352IcJC06IsWKDsr6E6vF3hC3GUBUy9I7JbqlAh7zlYK52MITQzGINZD2p8+TJjmDycEr/UM/JHqBzbJniUzxg8vo2/FjpZggU8NuBsTZ5P/YZSgRsZcVKkhkGYAn+euvrQIiZ2LMwOygD0gW/zy7v+Z1aHfxKig7kkOR1ZuVCFE8FWx1unCnFHtkjFIx9JY4cYHboveIlF2IzNhfnKJncBt7DuZORqfAT3gQDZlIFNx06tSnTe1v5l7u7VSKMXRhc3bbeCqfvO/NSOqfLz1QYlj2b0C5sm0AcUe1RpC7rOu6muPLeJ38DOIhJHzs+wpqBZTHJr9zdnjZl+OyXaAAbgCsxamEQW91iGdRmVHqyT+0+XQxssYOF795eGYpsXy9Bik6Z4apt/AcuZQFu3XthVXvjyVCi0Rj3gXjOkFdT1YaiRe6yPRdBB2GorcxCzQQvjZXTuh5P4a7MD/6W0mJYoh0BzQHYC0O/T9v3d8GepAbQTytL7MWIWk9C2qZ0pPciuIfXNmGRWBUkCCts1BAsW39l4giNBCwDQ6CauWkz8iWaxx2krBQpKl0WyBBSd/SIJUFM4psvYNaGNk+xR18s0OrPqvxQvc3NNgVwpAljSM/wt3IzIcIsJHF/u0T60hXgEv4H0f44/SzROL0iGUZIfRZK6sJRGBQH2ZVrFCJ6ageJX7WTBLVwKAtxgIUK2dXAemsYgGm/CIe3JCmwL/YmEh8I8W4LrWzXq4vNF6/Sq1hQ2r4dndAO+HEZ8nYpPr+9pUCUgSvnN7aVWZpc/xJaj5L4U6W28hVZ2mb+UUKDpq0bSxKdkVr2SC/7Q/8WimMNDYCaExzXQ+RzZyv/4227pn/k3y1avulXGz3ujy+lqdciVVWHmPYyJPhqeoyDEkM6g46KL9kg912jsB1SGP7Yc2l7XENW59mh5RE+fNiW8wWjxW0Oa+xSe2+RTOgRA+Ojq2L8+g9sL7jKw7BPAPjnYTo8gMat4DurAKbJrtaRLZMzXkFyE7heHr9NsLJl/d1JLRwNoGDpnvLjyPNBUjW/2CTEEIyI6yq3oOJivAwe1yiJib7IUTkh5MCBSnEssvxOYJRUaR/ILAHMJpAoEV/VOCfBlh/I55gVYZWa+Y/5/AMs5Po1w9/18Q6V4ichv80Qr+Up7+2s8sV6zM7m78WMmQp3IR6uTJasqI2Vnr99KAY31BJVpBelRq2xjIruSHx/BAr2kSHA+Kuk1I9+Y1dEaSbfUpjcly0WDUh9x1VTkrUu1u6XN/i/SkFeO1k8o2o7s0rVXNI+VipXQt69H+yVDea7AYuvy9Rp2kKuq7o7mgcFCVq1Vbeyv++vDSKdYmKbyQ2N7ubU6u41Td59YNfRldl56ec0bl7hgyMUb/7/ifjdRXOVl1sTTMUiETnT+44vuAiiUeOHRgKmRlLgHp9iMnPPZVF3DqExLV1IPraZO/olA9QIc4bM2g6SPebITaH94rZn80oQzWzBAFUzK/B2vY39XGdPSTAZTFn1yAYcRHIhqWZs9+FtJvBN9f9lUxPFHUs3vyKBC8sFph/yee7KNIKyTinMNAs1+jcnVS4LPqR4L4cn3ancasZ6wBgexKIjjwf8KPkgUcMwZqk+KwDeJbmyGblqsRzSuhrwPq0U+n4n1ktcqI11Y4D/u93UrU04LgZwWPEZPrgjGUgciPrRa3BIJb6oT1s5VSfgiupwHaFYgF5sJ3VD0ZcT1zwdet8tPprxRq00SIZMZKZeVSIWD0ai82pPxH4PYLUGwUbW3ocaYouILRf9sF9DP1gaVfd4SDRUuKUtZRiG6lpSopmFO24N1vWq90caknzY91uUWX2v4+C/JHDd47e4h/g1Lf13euI6csefzsnQDTDsyrh5zSJDo26B81kY5RyKv+AnsvTnTl8uroRsh1KqeIUywpWImmlnnWT8rpNg822BjraGaWc9NHFzkUSmOmD/iJRdfRjno1JaeDVk8KBniY0vnMqdBG1BWRMsnUAhWxHJ4Jn5fXCltO2C5OV+x+jYocNhWw4Mgu3CVZp9erAEPsDEUsY4qaMitjRq6yJPn3nwkQRpFHGbXv187fPU/z8+BQ5/W4Qfg/qEmJKcp1T5VcrwLAlZQTomKAt/7xNlJIxlx9bCMVXnvk3Y8hB7kCTaSQmvjC8IXCHbJyMCFQV7qAKdmaihyV7zmpqWcDqfELQChm2KxmQJ1dPYJ1+jR+aYm3an5bPEoCdbsZauFF8qXHIhx8JKvRGgxPrTGHi8N5FcfuNsCA3xOkoSGX9Sxg6h5KEtoeFdkwf5BKqhJj5pcsBewAHkWng86BzAqt7R+a9TnyvLMWvmpI/0fkpRkbg731aWOnWOvbpz6f+nXSxGgrvs/B6xSgFPDo6Ty3ivL+CGitfK6XwdHA07TV/eK5vd5oyNe/Ay5wMdXiypEUWukN+jiuGmrVMkke/0DmXmtqqY3T45iLrqfgwRhXsT9kEdzcWVqM4OkAEqEzpjI0NHG74cslhQvDPbX/ZRp57/bcOuarHpCDakvzajblF2NXf0Wp0dO0NltExHFoY8myAlBu/SMn3VN6GF5faMq370MevoNi4eNRD8XiGUYh+QzVphqtLIeqyyt6W4MzTjwSLgAB0kITRYcG0KVi89iUgZMQdwIOfMUBmS/q1GpBtTFKqI2TwC3dz9oBnNzwi3Ru9yyNuX1mw1p0Sd8UNY0yVbdb7UrLrd0ldVrx2FWNVCEedkn0npe9xstIJvgMuRLA0DNN7vex3hfvGvV7qCuQi5ssNVYUkoyEjlFR3xCThuVCgwzK77JmvWMpeB0eR0O3SH9KK/1qaAkXK/bhyazFdT+WHrexsFYZuO5I1MiQWJzNDQ9r3act5mt0senky0dQ+Sb233mB+RX2AWxOf9SUcRtkKjiTvfSdcKHmLx7ns2F8MQdwFoKz7j4a7sPsuruL+BMHWuDj/VTfnVmG6nlzIjs92LVWKnZ010UOv156HJYQvhlSV+WzPv8EC/2A2LhBx0g1ZJ3vYQIu2G1AuhcZurtEOfbhcIsS6cq9P2YoRYTYTHeiXHNzKot/25uSAFs85GQhWyMz+2L3HBiszTmSdwtf0ZzHgGEBc90JD6yNfjwqF4FJ7AcuLYw5euNz/VEON3z2C021shibn6LGd4RjflA8XmBGSakJ0nkpplflYaQ9Awcv2eKYR4ebAVjhyErm4zHikUC5Vgtz/0UbghbNcX0RIEESW2GaGtFNYIYNPHJNtj4QMYLK7BrUOnzITF+Kx/FZG6oIeySnU+TJoZIkJBIqGLOYSkw+QuEbCbf1BM5nERddA8z+IFxYz7Goxg4XMpc3+L/Hx29UZzkNSY55Y2Swii1qxBWgBaRGpzI66cKfr6mHES+cbb9vNAdFPuBgJttyT/t3Jf+W5yRYt8M4VyIlEiUjAGqL3bqakDP5IwywMSpYeS1PmqWBsbUcV9bAavsLMnnEHvUue8GboIr+EeBMCk6XPBKFahrRZBTQq802IGDYOi++VjG7805Tleu2pX6H/IY/LDQVLnqVhxDaVonTvQqMffVvSwXp7EFNvR/XKxh+IJxO/W3tQeAi8Jn77E3itRU+tQEl8QQ65psW7FBQXujG6YYWK9XbPUPI/AkdVmaAuQQt7RPni0MhxB0Q8k6BqzhwbpyLMPa/XCkHdJLrO2xGupnrwYvt0OcF7Ia/hN9+HAekLtq8l+HcNGIY/JA2RPYOYGSEgAEVAgAACjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAowMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwCjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAowMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwCjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMApjbGVhcnRvbWFyawqAAw=="; + private static final String TYPE1_BYTES = "gAFfBwAAJSFQUy1BZG9iZUZvbnQtMS4wOiBUeXBlMVRlc3QgMDAxLjAwMAolJVRpdGxlOiBUeXBlMVRlc3QKJVZlcnNpb246IDAwMS4wMDAKJSVDcmVhdGlvbkRhdGU6IFR1ZSBGZWIgMjQgMTU6MzQ6MDUgMjAyNgolJUNyZWF0b3I6IEpheWF0aGlydGggUmFvIEQgVgolIDIwMjYtMi0yNDogQ3JlYXRlZCB3aXRoIEZvbnRGb3JnZSAoaHR0cDovL2ZvbnRmb3JnZS5vcmcpCiUgR2VuZXJhdGVkIGJ5IEZvbnRGb3JnZSAyMDI1MTAwOSAoaHR0cDovL2ZvbnRmb3JnZS5zZi5uZXQvKQolJUVuZENvbW1lbnRzCgoxMCBkaWN0IGJlZ2luCi9Gb250VHlwZSAxIGRlZgovRm9udE1hdHJpeCBbMC4wMDA0ODgyODEgMCAwIDAuMDAwNDg4MjgxIDAgMCBdcmVhZG9ubHkgZGVmCi9Gb250TmFtZSAvVHlwZTFUZXN0IGRlZgovRm9udEJCb3ggezEwMCAxMDAgNTAwIDIwMCB9cmVhZG9ubHkgZGVmCi9QYWludFR5cGUgMCBkZWYKL0ZvbnRJbmZvIDkgZGljdCBkdXAgYmVnaW4KIC92ZXJzaW9uICgwMDEuMDAwKSByZWFkb25seSBkZWYKIC9Ob3RpY2UgKCkgcmVhZG9ubHkgZGVmCiAvRnVsbE5hbWUgKFR5cGUxVGVzdCkgcmVhZG9ubHkgZGVmCiAvRmFtaWx5TmFtZSAoVHlwZTFUZXN0KSByZWFkb25seSBkZWYKIC9XZWlnaHQgKFJlZ3VsYXIpIHJlYWRvbmx5IGRlZgogL0l0YWxpY0FuZ2xlIDAgZGVmCiAvaXNGaXhlZFBpdGNoIGZhbHNlIGRlZgogL1VuZGVybGluZVBvc2l0aW9uIC0yMDQuOCBkZWYKIC9VbmRlcmxpbmVUaGlja25lc3MgMTAyLjQgZGVmCmVuZCByZWFkb25seSBkZWYKL0VuY29kaW5nIDI1NiBhcnJheQogMCAxIDI1NSB7IDEgaW5kZXggZXhjaCAvLm5vdGRlZiBwdXR9IGZvcgpkdXAgOS91bmkwMDA5IHB1dApkdXAgMTAvdW5pMDAwQSBwdXQKZHVwIDExL3VuaTAwMEIgcHV0CmR1cCAxMi91bmkwMDBDIHB1dApkdXAgMTMvdW5pMDAwRCBwdXQKZHVwIDMyL3NwYWNlIHB1dApkdXAgNDgvemVybyBwdXQKZHVwIDQ5L29uZSBwdXQKZHVwIDUwL3R3byBwdXQKZHVwIDUxL3RocmVlIHB1dApkdXAgNTIvZm91ciBwdXQKZHVwIDUzL2ZpdmUgcHV0CmR1cCA1NC9zaXggcHV0CmR1cCA1NS9zZXZlbiBwdXQKZHVwIDU2L2VpZ2h0IHB1dApkdXAgNTcvbmluZSBwdXQKZHVwIDY1L0EgcHV0CmR1cCA2Ni9CIHB1dApkdXAgNjcvQyBwdXQKZHVwIDY4L0QgcHV0CmR1cCA2OS9FIHB1dApkdXAgNzAvRiBwdXQKZHVwIDcxL0cgcHV0CmR1cCA3Mi9IIHB1dApkdXAgNzMvSSBwdXQKZHVwIDc0L0ogcHV0CmR1cCA3NS9LIHB1dApkdXAgNzYvTCBwdXQKZHVwIDc3L00gcHV0CmR1cCA3OC9OIHB1dApkdXAgNzkvTyBwdXQKZHVwIDgwL1AgcHV0CmR1cCA4MS9RIHB1dApkdXAgODIvUiBwdXQKZHVwIDgzL1MgcHV0CmR1cCA4NC9UIHB1dApkdXAgODUvVSBwdXQKZHVwIDg2L1YgcHV0CmR1cCA4Ny9XIHB1dApkdXAgODgvWCBwdXQKZHVwIDg5L1kgcHV0CmR1cCA5MC9aIHB1dApkdXAgOTcvYSBwdXQKZHVwIDk4L2IgcHV0CmR1cCA5OS9jIHB1dApkdXAgMTAwL2QgcHV0CmR1cCAxMDEvZSBwdXQKZHVwIDEwMi9mIHB1dApkdXAgMTAzL2cgcHV0CmR1cCAxMDQvaCBwdXQKZHVwIDEwNS9pIHB1dApkdXAgMTA2L2ogcHV0CmR1cCAxMDcvayBwdXQKZHVwIDEwOC9sIHB1dApkdXAgMTA5L20gcHV0CmR1cCAxMTAvbiBwdXQKZHVwIDExMS9vIHB1dApkdXAgMTEyL3AgcHV0CmR1cCAxMTMvcSBwdXQKZHVwIDExNC9yIHB1dApkdXAgMTE1L3MgcHV0CmR1cCAxMTYvdCBwdXQKZHVwIDExNy91IHB1dApkdXAgMTE4L3YgcHV0CmR1cCAxMTkvdyBwdXQKZHVwIDEyMC94IHB1dApkdXAgMTIxL3kgcHV0CmR1cCAxMjIveiBwdXQKZHVwIDEzMy91bmkwMDg1IHB1dApkdXAgMTczL3VuaTAwQUQgcHV0CnJlYWRvbmx5IGRlZgpjdXJyZW50ZGljdCBlbmQKY3VycmVudGZpbGUgZWV4ZWMKgAKNFgAAdD+EE/NjbKhan/77ULS7JzAqXMCrbi+Vm/INMgw3PCEo0KDOcHKx9nKgqjjDwOzrBLRMsXShwxYS1x/6IMkJVCVjeDcveVsL8pQfQ38Fn0GuBZjABRX+8YczNVfzLOMqnufUurZdpTQ/knB+LPzz6M5Eblraw5/Dfs5ktos1bODXEPRbHn8s12iryhQ2CDZodhoQCUZBYtBUwfa/LEajGbPGZFKHYxbBOpJkVtNmKVj9VnQNWFZzbmEE+BPtMZFWd3k07rHFRFrmv27lnlsZcItCh9tLm6+YgpGrwG/ed/zDHuFzCpT7xs7MdEpZqfajjiw9JKNtvO6XgdQ7y2rxwhv69q6/DIarClaEsha9+rFXfYTEkK8BcaUY1RI7beRwxnGx8Mt8pafG9aKKUpeQEJnqFv6Bk9Kz6/t+fAPkHdv8KUIErVw3AxMUFg63Ti+yeRa+1QQ7vDTTkV3O3Obim9olUKuQDhfmH2uWx+K3iBXFqwCLQTC/S/W/LDn9UCsxsphc4HA1txBMdO2NO8rPec0i5GLWOZZI5tOxhUsjPXLloUXLWOkU3I0wBTXW8TlAV2yBn+EPJ4XV14tyCoWHanYChLFqYcChHUHj+0GKluGz0gfPNQ4xf3u6+jyJLmvDFxiNxtSNAud0yBZx12ouXbVSeHGYXWk84KA/Sus2DDbG/E6H+kx2MfnEVMz2yZm/lW6a4w5Pevvdoxfj9BMLm1dBkDCxHQsjw1dbv7yBz3j6kibdv2I4JFxLoEW8qsxcH2SXXgJpM3KrNQlPRIqq8IKmxH3ZllsL/QQ8YJFg+KJjygCl9QOmrL/1FXx/JXmx0m6ynXaUfF1PwtiP7e1ISNfaExaiL1C9OtTK2T4h2WhRPW57ycPj/dYRfjKD7OvXXYQ+Co+s+jCWDRpbwGTLlDP0XQFMBNxx4cBogjdx6ouFfm8lXgfeQf/GC0CtQolv6YH1O06mdXeZ1hqAFwHALulGBr2WdAoV9wBD5SBSeMeIV3waNCP5P0xB7rP7uXTZv/oscgXK/61/3tsjyAXyZASQxvMf8uyWsThQA9TTEOM1o28z9bj6Yhs0Snwl2CxemFy3xgyidcNyBDRsCDFwYKjsejtr9sZGIXAFJK2djcN8aUa549kahghsM9NAB65fQFOwjWjPAZEnunfOsU/LXlWLjpPdul4+P/iseq37udumJc/dZMXm6KXDL6pesrEVc80hrFtnnPWTyaNUP1im/rQrwZvDnVJ0Yvg5XSGo6crcpdPE5pUviEVHB2W8aCI8W+2QrxfIXdN8g4bPW7FEjuoe424XoHpyyIkD1+0MyVNgCVywIoFjugUfAu5NKoFo+7+WyIvtrHlgEuMjEK70a2RhFp7wVuod4VD0EHJ+MWXUglKomSB7mA07KQiQDck++iAwwPmxKLmUdUItfeOcEji8RBoUkcTu9YuNij22HrsBxawVzE8Yz/ZRKqlbHpuuRHao7z2gIobOg8wHb/+lMC1o4vjwayYLSNfFyvf6XivjCkz2KUQlrLX+8WyTVA6JDHsI1xfhI+kr3NTJ2fZBKweobTge72fpGuiVEjV82l52w9UZBH9P70XJUqd1lYIstqLN+mDdVSJ1axsp9sDufLMEFWX9xUlCOyAdOefz02cniXnJcxIVdH8q01OLa5jxMlJ+CBeXO0D4j+r7qY8ZCTyeRT9eEpAykqEajhOoZPjhjtMlw5jgyZJ9COaM30bC3coKF93YSmRQaIkE9b1kw5dGlFvpGGYL4bAzo0SNSkIO00So24z3TISF9aJ1ssBn2072KoV99O/5QN5cWKdDvaSFkMJp0YFRHXNNHe1Zo0kV5Shq0uEygfikR1XDyuLuiycQSHWnFxVr2xSaMnA5CfKwfQu8hQ5ljap6spe1+Qh6Am4TkDa/CaO1QlQ03mRUcyyxFwGZJljNAkI7mVgG6DUlxxVSK8wJMH7otzpS0L2LYTHTG6LV0iXQBjNB4wuH5LqyqTgsiA8x7UASJFYY0RJGrD9moFp/ON0t+NPT6Rfw3Semq239oYpxMQr/mHkHfExaIA0AX31DjfMqWzj4bypd8B9zZFvOogC2EHPobmhYhjzFcbMdVXwnAENC0EVbEMdLzDQFeSFRpDwF6MJ5CyqFS4wD7PsyF/aVlPwi0rLnr6+xygmhFhtpsOi/zVT8qT0BCWBG4+9UZIh6MfLm+JWkLNQcEGmhTglxzIhntDTZkBO9MkYhs2vOM9pAWS9Pjcba8OR6+aiVMOZVReGm7FH3BixWPTHOeqMGpZYH09MRTScHecT7G/TgiZIcUReqM7OdmyExBR2IJ0tLuaEuHxyn7SC5Gdlcf9mL9Kz15sZFzTkZMjJAtCOTPMaHq/0eQIr/Ln1YMDd6O+ApErFrIGDQd4hBA2H8tIZMIuSct/KMzwj83QiB+wvvF/ec6vJCSEjU7FPayLiPt9ELxOKC0p3+k4wfc4PCX0VLozKllmEQ2+m7gkcI+mvWXGkjziNZtg7HsgEZbRTjH2H8LuaonHwNzpASWjt8e6deQzOglya7sRNKamea3s1oGPx1ZAZmGs5EZGtW0wT7h7WbQkM0Pv0Xcmb2d+0MWyOpvThTQOqog9wOrBZp8WQwFMbimf5h3nqrmgeRcmQL5YGrA0lLaShxIB9fiC8RBJ2ndEs8vW4MJU3u95ZJmQUwTDewI2WhsgV4CG9t74y790nLu/OWuRtm83j6FLEvtmgs0fMoE0WAtqrbzB2BLblT4GN7VXbZSE7K8B+zPTlx2Lw1mH4AwW0RK/6Hl6P8Y2KMsVSnLDDhKXxXSpaQQiiMV6lGAT4JLO9dh4cSAl0KVseZ62jLfcpN3T5UpiNAXr/OMqe0Vki/TLdwUCbfNL606j7Ki8v84s/ob3kaoYzKE5HDhgxKRYkd5NXmT321GSDdGW5OG4J5kwcF7KgJ7lY4HwLAkumbF4oMWMDz3FYRK5BxlYA65pSMxhCYKV5XMg2cPDPpLj8S55CI0Nq8WX8vnIY8JhSA2nbnTwzrSU30sN6BpXPILan6UBbNn91PgLOawA9Qnqebuq3BwqHOYAFecMIf3W/70HZ+iFc87AiEPK7kmn2Fm4az69PV3jVBZlIKAYGUHQvTm3+KYnNEGKSoOLB0bUGhklOy3vnbCuZt7Z2i0OpM2d7J9SqaCF1qrmIItsPKwGI6E1XyOhs1pVMwbWUzwHh4EU/wvU0bmcMinR9PWfvyusq4wUeP/rSQoRd7TfFNHZaCg9HJkgDdtjcTjpPBv/SPMNahf6KdknrkRunKE1+XxvdjKxo+7DXcijK8kPwDB5ZAv//BxZ6NEkippShPuCXnlP6huGWMNaM4Ascw+BU3R5P6SHODlrafn48qAqemBBnoUfmCw2mu+su+agNtVYx5MEacrmpyZGaQizFF/IAygncdllch8YCF6upwv0J8ehKxqIrdB5EpS8NwVmSl9HnL4Xkob5/T/PzCK5wCZYkECwKZEF1atSrcoKBeIHzn7FsCGLNDU7WPEseSYZvRNOUmunflZDysYSLBf7XMKkeaLijeB1qrD4P4fone9c9g1KrdZO597AT3DFfL/fTuKfvzLFS2dFJW3JxBhtIAEbVyd7hhE1ik1QulOOh7ZyPiuu60urRcrGU+fQVbXtdCVCZ+NMn/gvFbipQ+4w4Ry8xfBpyWQrIFTyzQ/hyBgecQnA7iJhrSiV56aCErXrHDhNCXvApKd9+rUB6w8Ltrp2ag/AIn3jA414KjLwvcvh2ztTYW9kGsA9c/TQYKYXrgbaWoSd7Z357cmY9I4UOEVad3Fxk8QZ2zWFdvydAyOrGU+7lo6fvirobuADWo1P6/4BSh7ZdzHxs5s3RvDAYrWwoO/WpmMdWzF5RvAXKXXcYhme5QBalZw270QjmB3VOvaZLQgkBFYV/USdi2Pl5yJRxmeRLHxW+9U3gi/vUxowUiFPaJ4hjgzuogct3zF0oJ3ZrSamVut85DZC88fY5RdC/GR53FR+nt51wzu+PPjh2UtQgZTdTD4tfmZ8MGc2BaHiQ+yhEPpXWi2sfkFwkVlOMnHrJOFwKil0Uy8OoHHiDlSQNX22YinDSmcY8silpqltMmVnibm4mQodIocSfNY+DMA6v5oiFFsXUCEiS5P8975OihDJIokTGt4E/z7VQag2vChKPSEMaK6NIhQjGn1qAVq26MDnXkLe1ScmDDVhdBH7F9OiPdGEoGz0R/EHqAiPC6LaGByJwvKm87QgQ0bP/CIWKAGOmV9b9GV18G8nN4+T1xu4bcatp+0RzLNXxPXBMvFYBDvhBv0JqM1Bzkff5VHc8Cly7qfWJ9GPfghDC1cdFtXf/qNzdrCNvEeT5BloKFZ6s7vkDEfGPLqgMxt5T3ywQPJhdh0J5m7HurwNA+BwBycoPts7h33elU2NlSNe7iRbTViFFLirJdYGSlZaelccnNqAJEWC55V5gxbZiA+nym/7KRlEeUpFmLtFBBPKHOsbhK5uNWw2w2cCCJuwlC8FcLoqsGaykaQimUJNrg4r5lDLwcdIPslHivyRywMP4f/rr509DL/ZsvrEZHXpC1UHiuUnpoYp5uD8Sd5t7TCG1pKC5Wqw6QnE3j5Ra0Zd3WaY9MJkTtmj5zAmPvBWtda/uhdM++vqUD5pm2FkmZjpcxdQ+Dw2ebN3eOKQsDcRrNc07d8qWC2XkqAxyolN21qFg4FBcM68Szc1/50XwOK8QyEBhG24XJbMDfwTGOtzKCExUaTje30HoD3Nzzee39rTe8t3aQJ56VVEdDPBsxqjrYHdbEPJFqwRSExlngpbIWjOiEyWu5YbcX0cQgk/TSlnRGV16o9pg2qBbcvWm5gpPZ0Kj3QrxPpmJIUqq6tYoc2zt2LZUbrTnopjvISz8+fm1jIQJt2vpRgnwLwC9uAsf3vBEoZvnxGQKVsG+1B6uVnlK4hKB0retrDEbdcGGpiACMc8IuXH+vQztfpFYR8aCY79MpHm+oHiIUWsBiosbWoYNOZv1D3T28W+A3xBrKABzqhwvymGnMrec/JzNPObaj4szJYJegxC7SyWuNbA8Je5xNon8SKM9KvtSh6MWDOhOMk4eTOyiuwUpUYRiMpazBdMe0msnhuE2qlRvQC08QaDEUZMN+EWEX63wnjN6CfXw5qIdlAHoG9ZypCQy7G3mYVqYLfywMdFBKE7JY+u31XsYp7UNuRkKAN6VGQux6Qym64jGLBO5M5gvzIHmUluXR+y9D6SzcOtocea4Y9/YXggV1MWSmW2dq7hvV58ZYbix1wWwuv10uG8OIUwiaMet6vVag6bIK1RG+7yPB3caz9gCcqoXnU4zlHNYqu6Zcg3226k91SSDWcvy5fHoKSZOtSwkIEb0m+dJURp7QFJ1AeuWoy6oxD6xAM995YBRyLCX3N9gHGiJZ33BbKq85oGrzQN8SeXs6j8+FrglsRqcjvdk7vgZCLRl7qcWsmkFXCzikZsHPn2stZMJm7bVfILwdMTF4A42iV9wy1idF4qXYzAZHLdEP9BDpdGMKRiICY8avlTv0nYMW1qgBz4cXrdmSrBTPV4Ts5/3yDP44/foH/rju3wLoWprGkQMU1cNj66iCCuKnhExh/bRb40wLE1N6H86Le9WYBUbJEJA5Knx3ELAboZ2xK+e8zK2jPZdcv1AGGfPE7V6G7/7YCOepiP4cv+RTru77QaND/sf+eX1N+pb8WDxgTMPQ5/AJeibBWmEO7zw+L8CBY+rAphiofoUzY9U32dBwf82tdPDwvqrtik+HqZfG74h6We9fRJrfUjR3J/5g7P8IpcJAI7XQ6N7IvujSTMCtDtOd5Pf4mzuvFj/y3A5cLXuFT8wvqtm+BaIMLCe0lgWg4h6vtXEeKGmMsCVnZP16QiuaftHgo71UaXH18Z/rafUcV1TirxHs9ddST6hNPZ31IMPVt6L2Z8p3ucsMRPjlqY4SpYjQClVEiUc6R2FPbGstgmH/OU+uDx7oNhRgFV91/h3p/9klZ1PXOHWzTtPN91bKkITWttjft16yhKkY9Qi2vXG/f8BdyNenjFoUHATcsr4n9UtjNFBIptLX7UQFf4KkNnbyeKV1Cqdl3L+NEz8/gXBeAXJgEEHNRBjz9sQLiyj82rL4wgonrKDtxvVRCBVOc3g2BYdnqsKpe7be5GFrhxyYIufRfj64AVfn9tExQC4y7NoQcMUCXHcDXSQaO4DI5kh4hWftJhYRQciNx7okOXWgQakxRz0BLMquW2zr16Eh+a1wMV+RRRbnOQUrdSuOptLp0HeXxDPBmd23mb+o9EaBZopKJcsZ5uVRnRPG5MpSDZBX/dD+ZcFhNxAkwftTJGxbHU2FvDZxZMau4ORlvRpe0jQqK0KAPjVhxygj+efvJhwqE7SjMk92H8tSlUcJNKTPRWlbzC+nXIfQmrUKWHB9WkJYPkygDNksMh29qtDKBoTrPFKd8TjtqAmPPYOARdnuOZ5GBLvk29+HuyIxm1reGzc0gAVPFM4+a5KuvdXP5RDQsfOYhrjfhryXiSjnafEa4Vr8bQV4tCrvM1wB6GwJNUMUIOLnZMKC1Wpa42CVKIjTsED1U11qk0c/z2pdQSW8bkze+S96EspK6YwFRpG+l2w57H45pXKCM/OtEoUFAsNYp0aUI03VLX0vayOPXwZjxfm0Sbxw8GlVveOcDjxP9PubGwJWB3zThbP3mWiciTTtQYHzJ12nStPUWrHe09we4wUPO5jzfTMVhXA/IGP6+xomVdm6BR6Iffn12RP9G+HUeWBB/vSHCL6FMcBSGEKo8kX9sVT43WPthgSJGxH+5cxSVsRZSpa3WEwJI7W6R30TpkUmhLMOROdMF9Oh6+G+73HC6kdt27xFupu9ZkFRCBxpa/QAQxLUKMekm90PTVMdiWBALcRG/5a+GbCJsEwasen3e8NWD8CDFqPPeDNQEhkDNzaWbvtiNttHV9ESmFC5Ty642U6taS7g3yI/aeMBjh6zebr+UmXv17XeNyO6N6KJBOstv8Ry1f/TmkuuQm3fXu3n99fkb5gLZUHIvUuQ+Q3vTnWrPkCt2Ezbp125iAKvlRyhk1pXLvrr/EA1OhtaGnLqEeq5XqBpwh6StXPQXk9qfZT9wNzhylhcM929FxVeGolbk+68k//XdoJhQg4nxUqYBavhqCEpNTvL+tCJP/DOX4MSAH+3VYuzPQGp03X4exr4V3CKf9vCE6BUiBvHjDic5quOPsKCg8oYqU98UUr7f8aF1IwzW5woFt5CcScIS7mxk93T9ZB3WasKAPuMgV97OniMMOLqV1q6x5g1kHT67a7lQG3t1rPIFzDu/YvRh0ro/ldnLOAG7kgcZgBxG+GUlSMJMFzA51cKCE6zulbDK0U4lGyF+0fQzK5J7JGySCNyspkbL2KoioJJPWZ9kEggqZlKQk9ps0HQbBLNKkad1ZVIyuJHrQTddcr6SB8TnUI+FEH9/dyBpfXAx3XCL9xWWSqzEsQ9h24a+oRnfkm9lEQDrR9YpPyFavVP2QhljRuQJ6TXwqrrBe0LbEL7kn3st3w98B99u4MtdP/mbeSDjk5/8iYKLsilg30/mllHfbIv8kue12+JmZJo01gCc+Dehm0rlMPMxeqqrCKlXj5n5FerqqPfkNs/rKfXFFlgu5cl/cBKqP17G4xLPLOLA7wHfabHXZB0vQDeE9SpIAZPmzR9VjXx/quSDUV8p4ABFQIAAAowMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwCjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAowMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwCjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAowMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwCjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAKY2xlYXJ0b21hcmsKgAM="; public static void main(String[] args) throws Exception { From fd48f68a2cc69a0cccbc2503f29aad2de19ec098 Mon Sep 17 00:00:00 2001 From: Emanuel Peter Date: Thu, 26 Feb 2026 07:29:56 +0000 Subject: [PATCH 11/54] 8378166: C2 VectorAPI: NBody / particle life demo Co-authored-by: Paul Sandoz Reviewed-by: sviswanathan, psandoz, jbhateja --- .../jtreg/compiler/gallery/ParticleLife.java | 812 ++++++++++++++++++ .../compiler/gallery/TestParticleLife.java | 219 +++++ 2 files changed, 1031 insertions(+) create mode 100644 test/hotspot/jtreg/compiler/gallery/ParticleLife.java create mode 100644 test/hotspot/jtreg/compiler/gallery/TestParticleLife.java diff --git a/test/hotspot/jtreg/compiler/gallery/ParticleLife.java b/test/hotspot/jtreg/compiler/gallery/ParticleLife.java new file mode 100644 index 00000000000..b6c393d328b --- /dev/null +++ b/test/hotspot/jtreg/compiler/gallery/ParticleLife.java @@ -0,0 +1,812 @@ +/* + * 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.gallery; + +import java.util.Random; + +import jdk.incubator.vector.*; + +import javax.swing.*; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Color; +import java.awt.Font; +import java.awt.Dimension; +import java.awt.BorderLayout; +import java.awt.RenderingHints; +import java.awt.geom.Ellipse2D; + +/** + * This is a visual demo of the Vector API, presenting an N-Body simulation, + * where every body (particle) interacts with every other body. + * + * This is a stand-alone test that you can run directly with: + * java --add-modules=jdk.incubator.vector ParticleLife.java + * + * On x86, you can also play with the UseAVX flag: + * java --add-modules=jdk.incubator.vector -XX:UseAVX=2 ParticleLife.java + * + * There is a JTREG test that automatically runs this demo, + * see {@link TestParticleLife}. + * + * The motivation for this demo is to present a realistic computation, + * such as a physics simulation, but which is currently not auto + * vectorized. It is thus a good candidate for the use of the Vector API. + * This demo is based on the work of Tom Mohr and others before him: + * https://particle-life.com/ + * https://www.youtube.com/@tom-mohr + * + * If you are interested in understanding the components, then look at these: + * - State.update: one step in the simulation. This consists of two parts: + * - updateForce*: This computes the forces between all the particles, which affects the velocities. + * We have multiple implementations (scalar and Vector API). + * This is the most expensive part of the simulation. + * - updatePositions: The velocities are added to the position. + */ +public class ParticleLife { + public static final Random RANDOM = new Random(123); + + // Increasing this number will make the demo slower. + public static int NUMBER_OF_PARTICLES = 2560; + public static int NUMBER_OF_GROUPS = 50; + + public static float ZOOM = 1500f; + + public static float SCALE1 = 0.02f; + public static float SCALE2 = 0.04f; + public static float SCALE3 = 1f; + public static float FORCE_PARTICLE = 0.0001f; + public static float FORCE_ORIGIN = 0.05f; + + // Dampening factor, applied to the velocity. + // 0: no velocity carried to next update, particles have no momentum + // 1: no dampening, can lead to increase in energy in the system over time. + public static float DAMPENING = 0.3f; + + // Time step size of each update. Larger makes the simulation faster. + // But if it is too large, this can lead to numerical instability. + public static float DT = 1f; + + enum Implementation { + Scalar, VectorAPI_Inner_Gather, VectorAPI_Inner_Rearranged, VectorAPI_Outer + } + + public static Implementation IMPLEMENTATION = Implementation.Scalar; + + enum PoleGen { + Default, Random, Rainbow, Sparse + } + + public static PoleGen POLE_GEN = PoleGen.Default; + + private static final VectorSpecies SPECIES_F = FloatVector.SPECIES_PREFERRED; + + public static State STATE = new State(); + + static void main() { + System.out.println("Welcome to the Particle Life Demo!"); + + // Set up a panel we can draw on, and put it in a window. + JFrame frame = new JFrame("Particle Life Demo (VectorAPI)"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(1400, 1000); + frame.setResizable(false); + frame.setLayout(new BorderLayout()); + + ParticlePanel panel = new ParticlePanel(); + panel.setPreferredSize(new Dimension(1000, 0)); + + JPanel controlPanel = new JPanel(); + controlPanel.setLayout(null); + controlPanel.setPreferredSize(new Dimension(400, 0)); + + int y = 10; + // ---------------------------- Reset Button ------------------------- + JButton button = new JButton("Reset"); + button.setBounds(10, y, 120, 30); + button.setToolTipText("Reset state, with new numbers of particles and groups, and new poles."); + controlPanel.add(button); + + button.addActionListener(_ -> { STATE = new State(); }); + y += 40; + + // ---------------------------- Computation Selector ------------------------- + { + JLabel label = new JLabel("Implementation"); + label.setBounds(10, y, 150, 30); + controlPanel.add(label); + + String[] options = {"Scalar", "VectorAPI Inner Gather", "VectorAPI Inner Rearranged", "VectorAPI Outer"}; + JComboBox comboBox = new JComboBox<>(options); + comboBox.setBounds(160, y, 210, 30); + comboBox.setToolTipText("Choose the implementation of the force computation. Using the VectorAPI should be faster."); + controlPanel.add(comboBox); + + comboBox.addActionListener(_ -> { + String selected = (String) comboBox.getSelectedItem(); + switch (selected) { + case "Scalar" -> IMPLEMENTATION = Implementation.Scalar; + case "VectorAPI Inner Gather" -> IMPLEMENTATION = Implementation.VectorAPI_Inner_Gather; + case "VectorAPI Inner Rearranged" -> IMPLEMENTATION = Implementation.VectorAPI_Inner_Rearranged; + case "VectorAPI Outer" -> IMPLEMENTATION = Implementation.VectorAPI_Outer; + } + }); + } + y += 40; + + // ---------------------------- Zoom Slider ------------------------- + JLabel zoomLabel = new JLabel("Zoom"); + zoomLabel.setBounds(10, y, 80, 30); + controlPanel.add(zoomLabel); + + JSlider zoomSlider = new JSlider(JSlider.HORIZONTAL, 10, 2500, (int)ZOOM); + zoomSlider.setBounds(160, y, 200, 30); + zoomSlider.setMajorTickSpacing(100); + zoomSlider.setPaintTicks(false); + zoomSlider.setPaintLabels(false); + controlPanel.add(zoomSlider); + + zoomSlider.addChangeListener(_ -> { + ZOOM = zoomSlider.getValue(); + }); + zoomSlider.setValue((int)ZOOM); + y += 40; + + // ---------------------------- :Particles Slider ------------------------- + JLabel particlesLabel = new JLabel("Particles"); + particlesLabel.setBounds(10, y, 150, 30); + controlPanel.add(particlesLabel); + + JSlider particlesSlider = new JSlider(JSlider.HORIZONTAL, 64, 10000, 64); + particlesSlider.setBounds(160, y, 200, 30); + particlesSlider.setMajorTickSpacing(100); + particlesSlider.setPaintTicks(false); + particlesSlider.setPaintLabels(false); + particlesSlider.setToolTipText("More particles make the simulation slower. Only applied on Reset."); + controlPanel.add(particlesSlider); + + particlesSlider.addChangeListener(_ -> { + NUMBER_OF_PARTICLES = particlesSlider.getValue() / 64 * 64; + particlesLabel.setText("Particles = " + NUMBER_OF_PARTICLES); + }); + particlesSlider.setValue(NUMBER_OF_PARTICLES); + y += 40; + + // ---------------------------- Groups Slider ------------------------- + JLabel groupsLabel = new JLabel("Groups"); + groupsLabel.setBounds(10, y, 150, 30); + controlPanel.add(groupsLabel); + + JSlider groupsSlider = new JSlider(JSlider.HORIZONTAL, 1, 100, 1); + groupsSlider.setBounds(160, y, 200, 30); + groupsSlider.setMajorTickSpacing(100); + groupsSlider.setPaintTicks(false); + groupsSlider.setPaintLabels(false); + groupsSlider.setToolTipText("More groups lead to more complex behavior. Only applied on Reset."); + controlPanel.add(groupsSlider); + + groupsSlider.addChangeListener(_ -> { + NUMBER_OF_GROUPS = groupsSlider.getValue(); + groupsLabel.setText("Groups = " + NUMBER_OF_GROUPS); + }); + groupsSlider.setValue(NUMBER_OF_GROUPS); + y += 40; + + // ---------------------------- Pole Gen Selector ------------------------- + { + JLabel label = new JLabel("Poles"); + label.setBounds(10, y, 150, 30); + controlPanel.add(label); + + String[] options = {"Default", "Random", "Rainbow", "Sparse"}; + JComboBox comboBox = new JComboBox<>(options); + comboBox.setBounds(160, y, 210, 30); + comboBox.setToolTipText("Poles define attraction/repulsion between groups. Only applied on Reset."); + controlPanel.add(comboBox); + + comboBox.addActionListener(_ -> { + String selected = (String) comboBox.getSelectedItem(); + switch (selected) { + case "Default" -> POLE_GEN = PoleGen.Default; + case "Random" -> POLE_GEN = PoleGen.Random; + case "Rainbow" -> POLE_GEN = PoleGen.Rainbow; + case "Sparse" -> POLE_GEN = PoleGen.Sparse; + } + }); + } + y += 40; + + // ---------------------------- Scale1 Slider ------------------------- + JLabel scale1Label = new JLabel("scale1"); + scale1Label.setBounds(10, y, 150, 30); + controlPanel.add(scale1Label); + + JSlider scale1Slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + scale1Slider.setBounds(160, y, 200, 30); + scale1Slider.setMajorTickSpacing(100); + scale1Slider.setPaintTicks(false); + scale1Slider.setPaintLabels(false); + scale1Slider.setToolTipText("Defines (inner) radius: repulsion between all particles."); + controlPanel.add(scale1Slider); + + scale1Slider.addChangeListener(_ -> { + SCALE1 = scale1Slider.getValue() * 0.002f + 0.001f; + scale1Label.setText("scale1 = " + String.format("%.4f", SCALE1)); + }); + scale1Slider.setValue(10); + y += 40; + + // ---------------------------- Scale2 Slider ------------------------- + JLabel scale2Label = new JLabel("scale2"); + scale2Label.setBounds(10, y, 150, 30); + controlPanel.add(scale2Label); + + JSlider scale2Slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + scale2Slider.setBounds(160, y, 200, 30); + scale2Slider.setMajorTickSpacing(100); + scale2Slider.setPaintTicks(false); + scale2Slider.setPaintLabels(false); + scale2Slider.setToolTipText("Defines (outer) radius: attraction/repulsion depending on poles/groups."); + controlPanel.add(scale2Slider); + + scale2Slider.addChangeListener(_ -> { + SCALE2 = scale2Slider.getValue() * 0.002f + 0.001f; + scale2Label.setText("scale2 = " + String.format("%.4f", SCALE2)); + }); + scale2Slider.setValue(20); + y += 40; + + // ---------------------------- Scale3 Slider ------------------------- + JLabel scale3Label = new JLabel("scale3"); + scale3Label.setBounds(10, y, 150, 30); + controlPanel.add(scale3Label); + + JSlider scale3Slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + scale3Slider.setBounds(160, y, 200, 30); + scale3Slider.setMajorTickSpacing(101); + scale3Slider.setPaintTicks(false); + scale3Slider.setPaintLabels(false); + scale3Slider.setToolTipText("Poles factor: adjust attraction/repulsion strenght."); + controlPanel.add(scale3Slider); + + scale3Slider.addChangeListener(_ -> { + SCALE3 = scale3Slider.getValue() * 0.02f; + scale3Label.setText("scale3 = " + String.format("%.4f", SCALE3)); + }); + scale3Slider.setValue(50); + y += 40; + + // ---------------------------- FORCE_PARTICLE Slider ------------------------- + JLabel forceParticlesLabel = new JLabel("fParticles"); + forceParticlesLabel.setBounds(10, y, 150, 30); + controlPanel.add(forceParticlesLabel); + + JSlider forceParticlesSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + forceParticlesSlider.setBounds(160, y, 200, 30); + forceParticlesSlider.setMajorTickSpacing(100); + forceParticlesSlider.setPaintTicks(false); + forceParticlesSlider.setPaintLabels(false); + forceParticlesSlider.setToolTipText("Particles force factor: adjust force strength between particles."); + controlPanel.add(forceParticlesSlider); + + forceParticlesSlider.addChangeListener(_ -> { + FORCE_PARTICLE = forceParticlesSlider.getValue() * 0.00001f; + forceParticlesLabel.setText("fParticles = " + String.format("%.5f", FORCE_PARTICLE)); + }); + forceParticlesSlider.setValue(10); + y += 40; + + // ---------------------------- FORCE_ORIGIN Slider ------------------------- + JLabel forceOriginLabel = new JLabel("fOrigin"); + forceOriginLabel.setBounds(10, y, 150, 30); + controlPanel.add(forceOriginLabel); + + JSlider forceOriginSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + forceOriginSlider.setBounds(160, y, 200, 30); + forceOriginSlider.setMajorTickSpacing(100); + forceOriginSlider.setPaintTicks(false); + forceOriginSlider.setPaintLabels(false); + forceOriginSlider.setToolTipText("Origin force factor: adjust force attracting all particles to the center/origin."); + controlPanel.add(forceOriginSlider); + + forceOriginSlider.addChangeListener(_ -> { + FORCE_ORIGIN = forceOriginSlider.getValue() * 0.0005f; + forceOriginLabel.setText("fOrigin = " + String.format("%.5f", FORCE_ORIGIN)); + }); + forceOriginSlider.setValue(50); + y += 40; + + // ---------------------------- DAMPENING Slider ------------------------- + JLabel dampeningLabel = new JLabel("dampening"); + dampeningLabel.setBounds(10, y, 150, 30); + controlPanel.add(dampeningLabel); + + JSlider dampeningSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + dampeningSlider.setBounds(160, y, 200, 30); + dampeningSlider.setMajorTickSpacing(100); + dampeningSlider.setPaintTicks(false); + dampeningSlider.setPaintLabels(false); + dampeningSlider.setToolTipText("Dampening removes energy from the system over time. 1 = no dampening."); + controlPanel.add(dampeningSlider); + + dampeningSlider.addChangeListener(_ -> { + DAMPENING = dampeningSlider.getValue() * 0.01f; + dampeningLabel.setText("dampening = " + String.format("%.5f", DAMPENING)); + }); + dampeningSlider.setValue(30); + y += 40; + + // ---------------------------- DT Slider ------------------------- + JLabel dtLabel = new JLabel("dt"); + dtLabel.setBounds(10, y, 150, 30); + controlPanel.add(dtLabel); + + JSlider dtSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); + dtSlider.setBounds(160, y, 200, 30); + dtSlider.setMajorTickSpacing(100); + dtSlider.setPaintTicks(false); + dtSlider.setPaintLabels(false); + dtSlider.setToolTipText("Time delta between simulation steps. Small values lead to slow simulation, large values can lead to simulation instability."); + controlPanel.add(dtSlider); + + dtSlider.addChangeListener(_ -> { + DT = dtSlider.getValue() * 0.04f + 0.001f; + dtLabel.setText("dt = " + String.format("%.3f", DT)); + }); + dtSlider.setValue(25); + y += 40; + + // ---------------------------- Force Panel ------------------------- + ForcePanel forcePanel = new ForcePanel(); + forcePanel.setBounds(10, y, 350, 350); + forcePanel.setToolTipText("Displays the attraction/repulsion between the groups. Only updated on Reset."); + controlPanel.add(forcePanel); + y += 360; + + frame.add(panel, BorderLayout.WEST); + frame.add(controlPanel, BorderLayout.CENTER); + frame.setVisible(true); + + System.out.println("Running Demo..."); + try { + // Tight loop where we redraw the panel as fast as possible. + while (true) { + Thread.sleep(1); + STATE.update(); + panel.repaint(); + forcePanel.repaint(); + } + } catch (InterruptedException e) { + System.out.println("Interrputed, terminating demo."); + } finally { + System.out.println("Shut down demo."); + frame.setVisible(false); + frame.dispose(); + } + } + + /** + * State of the simulation. + */ + public static class State { + public long lastTime; + public float fps; + + // "struct of arrays" approach allows adjacent vector loads. + public float[] x; + public float[] y; + public float[] vx; + public float[] vy; + public int[] group; // group index of the particle + + public Color[] colors; // color of the group + + // Matrix of the poles: defines attraction/repulsion between groups i and j + public float[][] poles; + public float[][] polesT; // transpose of poles + public float[] polesScratch; + + public State() { + int n = NUMBER_OF_PARTICLES; + int g = NUMBER_OF_GROUPS; + x = new float[n]; + y = new float[n]; + vx = new float[n]; + vy = new float[n]; + group = new int[n]; + + for (int i = 0; i < n; i++) { + x[i] = 0.2f * (RANDOM.nextFloat() - 0.5f); + y[i] = 0.2f * (RANDOM.nextFloat() - 0.5f); + group[i] = RANDOM.nextInt(g); + } + + colors = new Color[g]; + for (int i = 0; i < g; i++) { + float h = i / (float)g; + colors[i] = Color.getHSBColor(h, 1f, 1f); + } + + poles = new float[g][g]; + polesT = new float[g][g]; + polesScratch = new float[n]; + for (int i = 0; i < g; i++) { + for (int j = 0; j < g; j++) { + poles[i][j] = poleGen(i, j, g); + polesT[j][i] = poles[i][j]; + } + } + + // Set up the FPS tracker + lastTime = System.nanoTime(); + } + + public static float poleGen(int i, int j, int g) { + int offset = (i - j + g) % g; + return switch (POLE_GEN) { + case PoleGen.Default -> (i == j) ? -1f : RANDOM.nextFloat() * 2f - 1f; + case PoleGen.Random -> RANDOM.nextFloat() * 2f - 1f; + case PoleGen.Rainbow -> (i == j) ? -1f : ((offset == 1) ? -0.5f : 0f); + case PoleGen.Sparse -> (i == j) ? -1f : (RANDOM.nextInt(g) <= 2 ? -0.5f : 0.3f); + }; + } + + public void update() { + long nowTime = System.nanoTime(); + float newFPS = 1e9f / (nowTime - lastTime); + fps = 0.9f * fps + 0.1f * newFPS; + lastTime = nowTime; + + switch (IMPLEMENTATION) { + case Implementation.Scalar -> updateForcesScalar(); + case Implementation.VectorAPI_Inner_Gather -> updateForcesVectorAPI_Inner_Gather(); + case Implementation.VectorAPI_Inner_Rearranged -> updateForcesVectorAPI_Inner_Rearranged(); + case Implementation.VectorAPI_Outer -> updateForcesVectorAPI_Outer(); + default -> throw new RuntimeException("not implemented"); + } + + updatePositions(); + } + + public void updateForcesScalar() { + for (int i = 0; i < x.length; i++) { + float pix = x[i]; + float piy = y[i]; + float pivx = vx[i]; + float pivy = vy[i]; + for (int j = 0; j < x.length; j++) { + float pjx = x[j]; + float pjy = y[j]; + + float dx = pix - pjx; + float dy = piy - pjy; + float d = (float)Math.sqrt(dx * dx + dy * dy); + + // Ignoring d=0 avoids division by zero. + // This would happen for i==j which we want to exclude anyway, + // of if two particles have identical position. + if (d > 0f) { + float pole = poles[group[i]][group[j]]; + // If the distance is very large, the force is zero. + float f = 0; + if (d < SCALE1) { + // Small distance: repell all particles + f = (SCALE1 - d) / SCALE1; + } else if (d < SCALE1 + SCALE2) { + // Medium distance: attract/repell according to pole + f = (d - SCALE1) / SCALE2 * pole * SCALE3; + } else if (d < SCALE1 + 2f * SCALE2) { + // Medium distance: attract/repell according to pole + f = ((SCALE1 + 2f * SCALE2) - d) / SCALE2 * pole * SCALE3; + } + // The force is adjustable by the user via FORCE_PARTICLE. + // Additionally we need to respect the DT factor of the simulation + // time step. Finally, we need to normalize dx and dy by dividing + // by d. + f *= FORCE_PARTICLE * DT / d; + pivx += dx * f; + pivy += dy * f; + } + } + vx[i] = pivx; + vy[i] = pivy; + } + } + + // Inner loop vectorization, the inner loop is vectorized. + public void updateForcesVectorAPI_Inner_Gather() { + // We don't want to deal with tail loops, so we just assert that the number of + // particles is a multiple of the vector length. + if (x.length % SPECIES_F.length() != 0) { + throw new RuntimeException("Number of particles is not a multiple of the vector length."); + } + + for (int i = 0; i < x.length; i++) { + float pix = x[i]; + float piy = y[i]; + + // We consider the force of multiple (j) particles on particle i. + var fx = FloatVector.zero(SPECIES_F); + var fy = FloatVector.zero(SPECIES_F); + + for (int j = 0; j < x.length; j += SPECIES_F.length()) { + var pjx = FloatVector.fromArray(SPECIES_F, x, j); + var pjy = FloatVector.fromArray(SPECIES_F, y, j); + + var dx = pjx.sub(pix).neg(); + var dy = pjy.sub(piy).neg(); + var d2 = ( dx.mul(dx) ).add( dy.mul(dy) ); + var d = d2.lanewise(VectorOperators.SQRT); + + // We directly gather the poles from the matrix. + var pole = FloatVector.fromArray(SPECIES_F, poles[group[i]], 0, group, j); + + // We need to compute all 3 piece-wise liner parts. + var poleDivScale2 = pole.mul(SCALE3 / SCALE2); + var f1 = d.sub(SCALE1).neg().mul(1f / SCALE1); + var f2 = d.sub(SCALE1).mul(poleDivScale2); + var f3 = d.sub(SCALE1 + SCALE2 * 2f).neg().mul(poleDivScale2); + + // And we need to perform all checks, for the boundaries of the piece-wise parts. + var f0Mask = d.compare(VectorOperators.GT, 0); + var f1Mask = d.compare(VectorOperators.LT, SCALE1); + var f2Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2); + var f3Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2 * 2f); + var f03Mask = f0Mask.and(f3Mask); + + // Then, we put together the 3 middle parts. + var f12 = f2.blend(f1, f1Mask); + var f123 = f3.blend(f12, f2Mask); + + f123 = f123.mul(FORCE_PARTICLE * DT).div(d); + + // And we only apply the middle (non-zero) parts if the mask is enabled. + fx = fx.add(dx.mul(f123), f03Mask); + fy = fy.add(dy.mul(f123), f03Mask); + } + // We need to add the force of all the (j) particles onto i's velocity. + vx[i] += fx.reduceLanes(VectorOperators.ADD); + vy[i] += fy.reduceLanes(VectorOperators.ADD); + } + } + + // Inner loop vectorization, the inner loop is vectorized. But instead of gathering the poles + // in the inner loop, we rearrange it in the outer loop, so the inner loop has a linear access. + public void updateForcesVectorAPI_Inner_Rearranged() { + // We don't want to deal with tail loops, so we just assert that the number of + // particles is a multiple of the vector length. + if (x.length % SPECIES_F.length() != 0) { + throw new RuntimeException("Number of particles is not a multiple of the vector length."); + } + + for (int i = 0; i < x.length; i++) { + // Rearrange data to avoid rearrange in the loop. + // We could also use the VectorAPI for this loop, but it is not even necessary for speedups. + float[] polesgi = poles[group[i]]; + for (int j = 0; j < x.length; j++) { + polesScratch[j] = polesgi[group[j]]; + } + + float pix = x[i]; + float piy = y[i]; + + // We consider the force of multiple (j) particles on particle i. + var fx = FloatVector.zero(SPECIES_F); + var fy = FloatVector.zero(SPECIES_F); + + for (int j = 0; j < x.length; j += SPECIES_F.length()) { + var pjx = FloatVector.fromArray(SPECIES_F, x, j); + var pjy = FloatVector.fromArray(SPECIES_F, y, j); + + var dx = pjx.sub(pix).neg(); + var dy = pjy.sub(piy).neg(); + var d2 = ( dx.mul(dx) ).add( dy.mul(dy) ); + var d = d2.lanewise(VectorOperators.SQRT); + + // We can now access the poles from scratch in a linear access, avoiding the + // repeated gather in each inner loop. This helps especially if gather is + // not supported on a platform. But it also improves the access pattern on + // platforms where gather would be supported, but linear access is faster. + var pole = FloatVector.fromArray(SPECIES_F, polesScratch, j); + + // We need to compute all 3 piece-wise liner parts. + var poleDivScale2 = pole.mul(SCALE3 / SCALE2); + var f1 = d.sub(SCALE1).neg().mul(1f / SCALE1); + var f2 = d.sub(SCALE1).mul(poleDivScale2); + var f3 = d.sub(SCALE1 + SCALE2 * 2f).neg().mul(poleDivScale2); + + // And we need to perform all checks, for the boundaries of the piece-wise parts. + var f0Mask = d.compare(VectorOperators.GT, 0); + var f1Mask = d.compare(VectorOperators.LT, SCALE1); + var f2Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2); + var f3Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2 * 2f); + var f03Mask = f0Mask.and(f3Mask); + + // Then, we put together the 3 middle parts. + var f12 = f2.blend(f1, f1Mask); + var f123 = f3.blend(f12, f2Mask); + + f123 = f123.mul(FORCE_PARTICLE * DT).div(d); + + // And we only apply the middle (non-zero) parts if the mask is enabled. + fx = fx.add(dx.mul(f123), f03Mask); + fy = fy.add(dy.mul(f123), f03Mask); + } + // We need to add the force of all the (j) particles onto i's velocity. + vx[i] += fx.reduceLanes(VectorOperators.ADD); + vy[i] += fy.reduceLanes(VectorOperators.ADD); + } + } + + // Instead of vectorizing the inner loop, we can also vectorize the outer loop. + public void updateForcesVectorAPI_Outer() { + // We don't want to deal with tail loops, so we just assert that the number of + // particles is a multiple of the vector length. + if (x.length % SPECIES_F.length() != 0) { + throw new RuntimeException("Number of particles is not a multiple of the vector length."); + } + + for (int i = 0; i < x.length; i += SPECIES_F.length()) { + var pix = FloatVector.fromArray(SPECIES_F, x, i); + var piy = FloatVector.fromArray(SPECIES_F, y, i); + var pivx = FloatVector.fromArray(SPECIES_F, vx, i); + var pivy = FloatVector.fromArray(SPECIES_F, vy, i); + + // Let's consider the force of the j particle on all of the i particles in the vector. + for (int j = 0; j < x.length; j++) { + float pjx = x[j]; + float pjy = y[j]; + + var dx = pix.sub(pjx); + var dy = piy.sub(pjy); + var d2 = ( dx.mul(dx) ).add( dy.mul(dy) ); + var d = d2.lanewise(VectorOperators.SQRT); + + // We need to access transpose of poles, because we need to access adjacent i's + var pole = FloatVector.fromArray(SPECIES_F, polesT[group[j]], 0, group, i); + + var poleDivScale2 = pole.mul(SCALE3 / SCALE2); + var f1 = d.sub(SCALE1).neg().mul(1f / SCALE1); + var f2 = d.sub(SCALE1).mul(poleDivScale2); + var f3 = d.sub(SCALE1 + SCALE2 * 2f).neg().mul(poleDivScale2); + + var f0Mask = d.compare(VectorOperators.GT, 0); + var f1Mask = d.compare(VectorOperators.LT, SCALE1); + var f2Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2); + var f3Mask = d.compare(VectorOperators.LT, SCALE1 + SCALE2 * 2f); + var f03Mask = f0Mask.and(f3Mask); + + var f12 = f2.blend(f1, f1Mask); + var f123 = f3.blend(f12, f2Mask); + + f123 = f123.mul(FORCE_PARTICLE * DT).div(d); + pivx = pivx.add(dx.mul(f123), f03Mask); + pivy = pivy.add(dy.mul(f123), f03Mask); + } + pivx.intoArray(vx, i); + pivy.intoArray(vy, i); + } + } + + // The loop is so simple that it can be auto vectorized + public void updatePositions() { + float effectiveDampening = (float)Math.pow(DAMPENING, DT); + for (int i = 0; i < x.length; i++) { + float px = x[i]; + float py = y[i]; + float pvx = vx[i]; + float pvy = vy[i]; + + // Force that pulls to origin, based on distance. + float d = (float)Math.sqrt(px * px + py * py); + pvx -= px * d * FORCE_ORIGIN * DT; + pvy -= py * d * FORCE_ORIGIN * DT; + + // Update position and put drag on speed + px += pvx * DT; + py += pvy * DT; + pvx *= effectiveDampening; + pvy *= effectiveDampening; + + x[i] = px; + y[i] = py; + vx[i] = pvx; + vy[i] = pvy; + } + } + } + + /** + * This panel displays the simulation. + **/ + public static class ParticlePanel extends JPanel { + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2d = (Graphics2D) g; + + // Rendering settings for smoother circles + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + + g2d.setColor(new Color(0, 0, 0)); + g2d.fillRect(0, 0, 1000, 1000); + + // Draw position of points + for (int i = 0; i < STATE.x.length; i++) { + g2d.setColor(STATE.colors[STATE.group[i]]); + int xx = (int)(STATE.x[i] * ZOOM + 500f); + int yy = (int)(STATE.y[i] * ZOOM + 500f); + //g2d.fillRect(xx - 3, yy - 3, 6, 6); + g2d.fill(new Ellipse2D.Double(xx - 3, yy - 3, 6, 6)); + } + + g2d.setColor(new Color(0, 0, 0)); + g2d.fillRect(0, 0, 150, 35); + g2d.setColor(new Color(255, 255, 255)); + g2d.setFont(new Font("Consolas", Font.PLAIN, 30)); + g2d.drawString("FPS: " + (int)Math.floor(STATE.fps), 0, 30); + + g2d.setColor(new Color(255, 255, 255)); + int r1 = (int)(ZOOM * SCALE1); + int r2 = (int)(ZOOM * (SCALE1 + SCALE2 * 2f)); + g2d.drawOval(900 - r1, 100 - r1, 2 * r1, 2 * r1); + g2d.drawOval(900 - r2, 100 - r2, 2 * r2, 2 * r2); + } + } + + /** + * This panel displays the pole matrix. + **/ + public static class ForcePanel extends JPanel { + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2d = (Graphics2D) g; + + g2d.setColor(new Color(0, 0, 0)); + g2d.fillRect(0, 0, 350, 350); + + int nGroups = STATE.poles.length; + int scale = (int)(300f / nGroups); + for (int i = 0; i < nGroups; i++) { + g2d.setColor(STATE.colors[i]); + g2d.fillRect(scale * (i + 1), 0, scale, scale); + g2d.fillRect(0, scale * (i + 1), scale, scale); + + for (int j = 0; j < nGroups; j++) { + float p = STATE.poles[i][j]; + float cr = Math.max(0, p); + float cg = Math.max(0, -p); + g2d.setColor(new Color(cr, cg, 0)); + g2d.fillRect(scale * (i + 1), scale * (j + 1), scale, scale); + } + } + } + } +} diff --git a/test/hotspot/jtreg/compiler/gallery/TestParticleLife.java b/test/hotspot/jtreg/compiler/gallery/TestParticleLife.java new file mode 100644 index 00000000000..e0fb6164acf --- /dev/null +++ b/test/hotspot/jtreg/compiler/gallery/TestParticleLife.java @@ -0,0 +1,219 @@ +/* + * 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 id=ir + * @bug 8378166 + * @summary Visual example of the Vector API: NBody / Particle Life simulation. + * @library /test/lib / + * @modules jdk.incubator.vector + * @run driver ${test.main.class} ir + */ + +/* + * @test id=visual + * @key headful + * @library /test/lib / + * @modules jdk.incubator.vector + * @run main ${test.main.class} visual + */ + +package compiler.gallery; + +import jdk.test.lib.Utils; + +import compiler.lib.ir_framework.*; + +/** + * This test is the JTREG version for automatic verification of the stand-alone + * {@link ParticleLife}. If you just want to run the demo and play with it, + * go look at the documentation in {@link ParticleLife}. + * Here, we launch both a visual version that just runs for a few seconds, to see + * that there are no crashes, but we don't do any specific verification. + * We also have an IR test, that ensures that we get vectorization. + */ +public class TestParticleLife { + public static void main(String[] args) throws InterruptedException { + String mode = args[0]; + System.out.println("Running JTREG test in mode: " + mode); + + switch (mode) { + case "ir" -> runIR(); + case "visual" -> runVisual(); + default -> throw new RuntimeException("Unknown mode: " + mode); + } + } + + private static void runIR() { + System.out.println("Testing with IR rules..."); + TestFramework.runWithFlags("-XX:CompileCommand=inline,compiler.gallery.ParticleLife$State::update*", + "--add-modules=jdk.incubator.vector"); + } + + private static void runVisual() throws InterruptedException { + System.out.println("Testing with 2d Graphics (visual)..."); + + // We will not do anything special here, just launch the application, + // tell it to run for 10 second, interrupt it and let it shut down. + Thread thread = new Thread() { + public void run() { + ParticleLife.main(); + } + }; + thread.setDaemon(true); + thread.start(); + Thread.sleep(Utils.adjustTimeout(10000)); // let demo run for 10 seconds + thread.interrupt(); + Thread.sleep(Utils.adjustTimeout(1000)); // allow demo 1 second for shutdown + } + + // ---------------------- For the IR testing part only -------------------------------- + ParticleLife.State state = new ParticleLife.State(); + + @Test + @Warmup(100) + @IR(counts = {IRNode.REPLICATE_F, "> 0", + IRNode.LOAD_VECTOR_F, "> 0", + IRNode.SUB_VF, "> 0", + IRNode.MUL_VF, "> 0", + IRNode.ADD_VF, "> 0", + IRNode.SQRT_VF, "> 0", + IRNode.STORE_VECTOR, "> 0"}, + applyIf = {"AlignVector", "false"}, + applyIfPlatform = {"64-bit", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}) + private void testIR_updatePositions() { + // This call should inline given the CompileCommand above. + // We expect auto vectorization of the relatively simple loop. + state.updatePositions(); + } + + @Test + @Warmup(10) + @IR(counts = {IRNode.REPLICATE_F, "= 0", + IRNode.LOAD_VECTOR_F, "= 0", + IRNode.REPLICATE_I, "= 0", + IRNode.LOAD_VECTOR_I, "= 0", + IRNode.ADD_VI, "= 0", + IRNode.LOAD_VECTOR_GATHER, "= 0", + IRNode.SUB_VF, "= 0", + IRNode.MUL_VF, "= 0", + IRNode.ADD_VF, "= 0", + IRNode.NEG_VF, "= 0", + IRNode.SQRT_VF, "= 0", + IRNode.DIV_VF, "= 0", + IRNode.VECTOR_MASK_CMP, "= 0", + IRNode.VECTOR_MASK_CAST, "= 0", + IRNode.AND_V_MASK, "= 0", + IRNode.VECTOR_BLEND_F, "= 0", + IRNode.STORE_VECTOR, "= 0", + IRNode.ADD_REDUCTION_VF, "= 0"}, + applyIfPlatform = {"64-bit", "true"}, + applyIfCPUFeatureOr = {"avx2", "true", "asimd", "true"}) + private void testIR_updateForcesScalar() { + // This call should inline given the CompileCommand above. + // We expect no vectorization, though it may in principle be possible + // to auto vectorize one day. + state.updateForcesScalar(); + } + + @Test + @Warmup(10) + @IR(counts = {IRNode.REPLICATE_F, "> 0", + IRNode.LOAD_VECTOR_F, "> 0", + IRNode.REPLICATE_I, "> 0", + IRNode.LOAD_VECTOR_I, "> 0", + IRNode.ADD_VI, "> 0", + IRNode.LOAD_VECTOR_GATHER, "> 0", + IRNode.SUB_VF, "> 0", + IRNode.MUL_VF, "> 0", + IRNode.ADD_VF, "> 0", + IRNode.NEG_VF, "> 0", + IRNode.SQRT_VF, "> 0", + IRNode.DIV_VF, "> 0", + IRNode.VECTOR_MASK_CMP, "> 0", + IRNode.VECTOR_MASK_CAST, "> 0", + IRNode.VECTOR_BLEND_F, "> 0", + IRNode.ADD_REDUCTION_VF, "> 0"}, // instead we reduce the vector to a scalar + applyIfPlatform = {"64-bit", "true"}, + applyIfCPUFeature = {"avx2", "true"}) + private void testIR_updateForcesVectorAPI_Inner_Gather() { + // This call should inline given the CompileCommand above. + // We expect the VectorAPI calls to intrinsify. + state.updateForcesVectorAPI_Inner_Gather(); + } + + @Test + @Warmup(10) + @IR(counts = {IRNode.REPLICATE_F, "> 0", + IRNode.LOAD_VECTOR_F, "> 0", + IRNode.REPLICATE_I, "= 0", // No gather operation + IRNode.LOAD_VECTOR_I, "= 0", // No gather operation + IRNode.ADD_VI, "= 0", // No gather operation + IRNode.LOAD_VECTOR_GATHER, "= 0", // No gather operation + IRNode.SUB_VF, "> 0", + IRNode.MUL_VF, "> 0", + IRNode.ADD_VF, "> 0", + IRNode.NEG_VF, "> 0", + IRNode.SQRT_VF, "> 0", + IRNode.DIV_VF, "> 0", + IRNode.VECTOR_MASK_CMP, "> 0", + IRNode.VECTOR_MASK_CAST, "> 0", + IRNode.VECTOR_BLEND_F, "> 0", + IRNode.ADD_REDUCTION_VF, "> 0"}, // instead we reduce the vector to a scalar + applyIfPlatform = {"64-bit", "true"}, + applyIfCPUFeatureOr = {"avx2", "true", "asimd", "true"}) + private void testIR_updateForcesVectorAPI_Inner_Rearranged() { + // This call should inline given the CompileCommand above. + // We expect the VectorAPI calls to intrinsify. + state.updateForcesVectorAPI_Inner_Rearranged(); + } + + + @Test + @Warmup(10) + @IR(counts = {IRNode.REPLICATE_F, "> 0", + IRNode.LOAD_VECTOR_F, "> 0", + IRNode.REPLICATE_I, "> 0", + IRNode.LOAD_VECTOR_I, "> 0", + IRNode.ADD_VI, "> 0", + IRNode.LOAD_VECTOR_GATHER, "> 0", + IRNode.SUB_VF, "> 0", + IRNode.MUL_VF, "> 0", + IRNode.ADD_VF, "> 0", + IRNode.NEG_VF, "> 0", + IRNode.SQRT_VF, "> 0", + IRNode.DIV_VF, "> 0", + IRNode.VECTOR_MASK_CMP, "> 0", + IRNode.VECTOR_MASK_CAST, "> 0", + IRNode.VECTOR_BLEND_F, "> 0", + IRNode.STORE_VECTOR, "> 0", // store back a vector + IRNode.ADD_REDUCTION_VF, "= 0"}, // and no reduction operation + applyIfPlatform = {"64-bit", "true"}, + applyIfCPUFeature = {"avx2", "true"}) + private void testIR_updateForcesVectorAPI_Outer() { + // This call should inline given the CompileCommand above. + // We expect the VectorAPI calls to intrinsify. + state.updateForcesVectorAPI_Outer(); + } +} From a39a1f10f75c15b93a709eca7bfae2d808cf7b91 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Thu, 26 Feb 2026 08:10:37 +0000 Subject: [PATCH 12/54] 8268850: AST model for 'var' variables should more closely adhere to the source code Reviewed-by: vromero --- .../classes/com/sun/source/tree/Tree.java | 7 + .../com/sun/source/tree/TreeVisitor.java | 9 + .../com/sun/source/tree/VarTypeTree.java | 36 ++ .../com/sun/source/tree/VariableTree.java | 11 +- .../sun/source/util/SimpleTreeVisitor.java | 15 + .../com/sun/source/util/TreeScanner.java | 15 + .../com/sun/tools/javac/comp/Analyzer.java | 2 - .../com/sun/tools/javac/comp/Attr.java | 60 +-- .../com/sun/tools/javac/comp/AttrRecover.java | 5 - .../com/sun/tools/javac/comp/Lower.java | 5 +- .../com/sun/tools/javac/comp/MemberEnter.java | 12 +- .../com/sun/tools/javac/comp/TreeDiffer.java | 6 + .../sun/tools/javac/parser/JavacParser.java | 39 +- .../com/sun/tools/javac/tree/JCTree.java | 38 +- .../com/sun/tools/javac/tree/Pretty.java | 9 + .../com/sun/tools/javac/tree/TreeCopier.java | 8 +- .../com/sun/tools/javac/tree/TreeInfo.java | 2 - .../com/sun/tools/javac/tree/TreeMaker.java | 10 +- .../com/sun/tools/javac/tree/TreeScanner.java | 3 + .../sun/tools/javac/tree/TreeTranslator.java | 4 + .../share/classes/jdk/jshell/Eval.java | 2 +- .../jdk/jshell/SourceCodeAnalysisImpl.java | 4 +- .../failures/target/VarVariables-old.out | 4 +- .../failures/target/VarVariables.out | 4 +- .../tools/javac/lvti/VarAccessibility.java | 393 ++++++++++++++++++ .../tools/javac/lvti/VarWarnings.java | 193 +++++++++ .../javac/parser/DeclarationEndPositions.java | 8 +- .../tools/javac/parser/JavacParserTest.java | 37 +- .../patterns/BindingPatternVarTypeModel.java | 2 +- .../javac/patterns/InstanceOfModelTest.java | 2 +- test/langtools/tools/javac/tree/VarTree.java | 32 +- .../tools/javac/tree/VarWarnPosition.java | 3 + .../tools/javac/tree/VarWarnPosition.out | 6 +- 33 files changed, 873 insertions(+), 113 deletions(-) create mode 100644 src/jdk.compiler/share/classes/com/sun/source/tree/VarTypeTree.java create mode 100644 test/langtools/tools/javac/lvti/VarAccessibility.java create mode 100644 test/langtools/tools/javac/lvti/VarWarnings.java diff --git a/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java b/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java index 845203c8735..152883b4930 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java +++ b/src/jdk.compiler/share/classes/com/sun/source/tree/Tree.java @@ -266,6 +266,13 @@ public interface Tree { */ PRIMITIVE_TYPE(PrimitiveTypeTree.class), + /** + * Used for instances of {@link VarTypeTree}. + * + * @since 27 + */ + VAR_TYPE(VarTypeTree.class), + /** * Used for instances of {@link ReturnTree}. */ diff --git a/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java b/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java index a2a33ccf8eb..f2a067971d1 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java +++ b/src/jdk.compiler/share/classes/com/sun/source/tree/TreeVisitor.java @@ -498,6 +498,15 @@ public interface TreeVisitor { */ R visitPrimitiveType(PrimitiveTypeTree node, P p); + /** + * Visits a {@code VarTypeTree} node. + * @param node the node being visited + * @param p a parameter value + * @return a result value + * @since 27 + */ + R visitVarType(VarTypeTree node, P p); + /** * Visits a {@code TypeParameterTree} node. * @param node the node being visited diff --git a/src/jdk.compiler/share/classes/com/sun/source/tree/VarTypeTree.java b/src/jdk.compiler/share/classes/com/sun/source/tree/VarTypeTree.java new file mode 100644 index 00000000000..bfe13ebdce1 --- /dev/null +++ b/src/jdk.compiler/share/classes/com/sun/source/tree/VarTypeTree.java @@ -0,0 +1,36 @@ +/* + * 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.source.tree; + +import javax.lang.model.type.TypeKind; + +/** + * A tree node for a {@code var} contextual keyword used as a type. + * + * @since 27 + */ +public interface VarTypeTree extends Tree { +} diff --git a/src/jdk.compiler/share/classes/com/sun/source/tree/VariableTree.java b/src/jdk.compiler/share/classes/com/sun/source/tree/VariableTree.java index a1191b2f8e6..11dc41577be 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/tree/VariableTree.java +++ b/src/jdk.compiler/share/classes/com/sun/source/tree/VariableTree.java @@ -65,10 +65,13 @@ public interface VariableTree extends StatementTree { */ ExpressionTree getNameExpression(); - /** - * Returns the type of the variable being declared. - * @return the type - */ + /// {@return the type of the variable being declared.} + /// + /// @apiNote + /// The type of the variable can be one of the following: + /// - if the variable is declared using {@code var}, then the returned value is a {@link VarTypeTree}, + /// - if the variable is a lambda parameter declared without a type (i.e. relying on type inferrence), then the returned value is {@code null}, + /// - otherwise, the variable is declared with an explicit type, and the returned value is that type. Tree getType(); /** diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java b/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java index 77305d56b1e..917df861b70 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/SimpleTreeVisitor.java @@ -803,6 +803,21 @@ public class SimpleTreeVisitor implements TreeVisitor { return defaultAction(node, p); } + /** + * {@inheritDoc} + * + * @implSpec This implementation calls {@code defaultAction}. + * + * @param node {@inheritDoc} + * @param p {@inheritDoc} + * @return the result of {@code defaultAction} + * @since 27 + */ + @Override + public R visitVarType(VarTypeTree node, P p) { + return defaultAction(node, p); + } + /** * {@inheritDoc} * diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java b/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java index 29e81c206e0..ca8b785d8cb 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java @@ -939,6 +939,21 @@ public class TreeScanner implements TreeVisitor { return null; } + /** + * {@inheritDoc} + * + * @implSpec This implementation returns {@code null}. + * + * @param node {@inheritDoc} + * @param p {@inheritDoc} + * @return the result of scanning + * @since 27 + */ + @Override + public R visitVarType(VarTypeTree node, P p) { + return null; + } + /** * {@inheritDoc} * diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java index f45e8500000..fb5576a82e1 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java @@ -370,7 +370,6 @@ public class Analyzer { */ JCVariableDecl rewriteVarType(JCVariableDecl oldTree) { JCVariableDecl newTree = copier.copy(oldTree); - newTree.vartype = null; return newTree; } @@ -751,7 +750,6 @@ public class Analyzer { if (oldLambda.paramKind == ParameterKind.IMPLICIT) { //reset implicit lambda parameters (whose type might have been set during attr) newLambda.paramKind = ParameterKind.IMPLICIT; - newLambda.params.forEach(p -> p.vartype = null); } return newLambda; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index 48e0238fb07..83b684e1225 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -1263,18 +1263,18 @@ public class Attr extends JCTree.Visitor { // parameters have already been entered env.info.scope.enter(tree.sym); } else { - if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) { + if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0 && tree.type == null) { if (tree.init == null) { //cannot use 'var' without initializer log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit)); - tree.vartype = make.at(tree.pos()).Erroneous(); + tree.type = syms.errType; } else { Fragment msg = canInferLocalVarType(tree); if (msg != null) { //cannot use 'var' with initializer which require an explicit target //(e.g. lambda, method reference, array initializer). log.error(tree, Errors.CantInferLocalVarType(tree.name, msg)); - tree.vartype = make.at(tree.pos()).Erroneous(); + tree.type = syms.errType; } } } @@ -1323,7 +1323,7 @@ public class Attr extends JCTree.Visitor { } } if (tree.isImplicitlyTyped()) { - setSyntheticVariableType(tree, v.type); + setupImplicitlyTypedVariable(tree, v.type); } } result = tree.type = v.type; @@ -1597,7 +1597,8 @@ public class Attr extends JCTree.Visitor { } if (tree.var.isImplicitlyTyped()) { Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name); - setSyntheticVariableType(tree.var, inferredType); + tree.var.type = inferredType; + setupImplicitlyTypedVariable(tree.var, inferredType); } attribStat(tree.var, loopEnv); chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); @@ -3223,8 +3224,10 @@ public class Attr extends JCTree.Visitor { Type argType = arityMismatch ? syms.errType : actuals.head; - if (params.head.isImplicitlyTyped()) { - setSyntheticVariableType(params.head, argType); + if (params.head.type == null && + params.head.isImplicitlyTyped()) { //error recovery + params.head.type = argType; + setupImplicitlyTypedVariable(params.head, argType); } params.head.sym = null; actuals = actuals.isEmpty() ? @@ -3442,7 +3445,7 @@ public class Attr extends JCTree.Visitor { JCLambda lambda = (JCLambda)tree; List argtypes = List.nil(); for (JCVariableDecl param : lambda.params) { - argtypes = param.vartype != null && param.vartype.type != null ? + argtypes = !param.isImplicitlyTyped() && param.vartype.type != null ? argtypes.append(param.vartype.type) : argtypes.append(syms.errType); } @@ -4218,7 +4221,7 @@ public class Attr extends JCTree.Visitor { public void visitBindingPattern(JCBindingPattern tree) { Type type; - if (tree.var.vartype != null) { + if (!tree.var.isImplicitlyTyped()) { type = attribType(tree.var.vartype, env); } else { type = resultInfo.pt; @@ -4231,11 +4234,11 @@ public class Attr extends JCTree.Visitor { if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) { chk.checkTransparentVar(tree.var.pos(), v, env.info.scope); } - chk.validate(tree.var.vartype, env, true); if (tree.var.isImplicitlyTyped()) { - setSyntheticVariableType(tree.var, type == Type.noType ? syms.errType - : type); + setupImplicitlyTypedVariable(tree.var, type == Type.noType ? syms.errType + : type); } + chk.validate(tree.var.vartype, env, true); annotate.annotateLater(tree.var.mods.annotations, env, v); if (!tree.var.isImplicitlyTyped()) { annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v); @@ -4254,7 +4257,7 @@ public class Attr extends JCTree.Visitor { public void visitRecordPattern(JCRecordPattern tree) { Type site; - if (tree.deconstructor == null) { + if (tree.deconstructor.hasTag(VARTYPE)) { log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed); tree.record = syms.errSymbol; site = tree.type = types.createErrorType(tree.record.type); @@ -4270,6 +4273,7 @@ public class Attr extends JCTree.Visitor { } tree.type = tree.deconstructor.type = type; site = types.capture(tree.type); + chk.validate(tree.deconstructor, env, true); } List expectedRecordTypes; @@ -4315,7 +4319,6 @@ public class Attr extends JCTree.Visitor { } finally { localEnv.info.scope.leave(); } - chk.validate(tree.deconstructor, env, true); result = tree.type; matchBindings = new MatchBindings(outBindings.toList(), List.nil()); } @@ -5731,15 +5734,20 @@ public class Attr extends JCTree.Visitor { return types.capture(type); } - private void setSyntheticVariableType(JCVariableDecl tree, Type type) { - if (type.isErroneous()) { - tree.vartype = make.at(tree.pos()).Erroneous(); - } else if (tree.declaredUsingVar()) { - Assert.check(tree.typePos != Position.NOPOS); - tree.vartype = make.at(tree.typePos).Type(type); - } else { - tree.vartype = make.at(tree.pos()).Type(type); + private void setupImplicitlyTypedVariable(JCVariableDecl tree, Type type) { + Assert.check(tree.isImplicitlyTyped()); + + type.complete(); + + if (tree.vartype == null) { + return ; } + + Assert.check(tree.vartype.hasTag(VARTYPE)); + + JCVarType vartype = (JCVarType) tree.vartype; + + vartype.type = type; } public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { @@ -6068,9 +6076,6 @@ public class Attr extends JCTree.Visitor { that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); that.sym.adr = 0; } - if (that.vartype == null) { - that.vartype = make.at(Position.NOPOS).Erroneous(); - } super.visitVarDef(that); } @@ -6145,6 +6150,11 @@ public class Attr extends JCTree.Visitor { syms.noSymbol); } } + + @Override + public void visitVarType(JCVarType that) { + initTypeIfNeeded(that); + } } // diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java index 716345fa077..092035c84dd 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java @@ -117,11 +117,6 @@ public class AttrRecover { ? formals.head : ((ArrayType) formals.head).elemtype; if (arg.hasTag(JCTree.Tag.LAMBDA)) { final JCTree.JCLambda lambda = (JCLambda) arg; - if (lambda.paramKind == JCLambda.ParameterKind.IMPLICIT) { - for (JCVariableDecl var : lambda.params) { - var.vartype = null; //reset type - } - } if (types.isFunctionalInterface(formal)) { Type functionalType = types.findDescriptorType(formal); boolean voidCompatible = functionalType.getReturnType().hasTag(TypeTag.VOID); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java index 69161fd682c..be603ffc9ca 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java @@ -3692,11 +3692,12 @@ public class Lower extends TreeTranslator { if (tree.var.type.isPrimitive()) vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit); else - vardefinit = make.TypeCast(tree.var.type, vardefinit); + vardefinit = transTypes.coerce(attrEnv, vardefinit, tree.var.type); JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods, tree.var.name, tree.var.vartype, - vardefinit).setType(tree.var.type); + vardefinit, + tree.var.declKind).setType(tree.var.type); indexDef.sym = tree.var.sym; JCBlock body = make.Block(0, List.of(indexDef, tree.body)); body.bracePos = TreeInfo.endPos(tree.body); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java index e02fb9849c9..cb0e6d4676b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/MemberEnter.java @@ -114,7 +114,7 @@ public class MemberEnter extends JCTree.Visitor { ListBuffer argbuf = new ListBuffer<>(); for (List l = params; l.nonEmpty(); l = l.tail) { memberEnter(l.head, env); - argbuf.append(l.head.vartype.type); + argbuf.append(l.head.sym.type); } // Attribute result type, if one is given. @@ -276,9 +276,13 @@ public class MemberEnter extends JCTree.Visitor { tree.vartype.type = atype.makeVarargs(); } WriteableScope enclScope = enter.enterScope(env); - Type vartype = tree.isImplicitlyTyped() - ? env.info.scope.owner.kind == MTH ? Type.noType : syms.errType - : tree.vartype.type; + Type vartype = switch (tree.declKind) { + case IMPLICIT -> tree.type; + case EXPLICIT -> tree.vartype.type; + case VAR -> tree.type != null ? tree.type + : env.info.scope.owner.kind == MTH ? Type.noType + : syms.errType; + }; Name name = tree.name; VarSymbol v = new VarSymbol(0, name, vartype, enclScope.owner); v.flags_field = chk.checkFlags(tree.mods.flags | tree.declKind.additionalSymbolFlags, v, tree); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java index bbc12f1fe80..4890b749a90 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TreeDiffer.java @@ -93,6 +93,7 @@ import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCTypeUnion; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCUses; +import com.sun.tools.javac.tree.JCTree.JCVarType; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; @@ -631,6 +632,11 @@ public class TreeDiffer extends TreeScanner { result = tree.typetag == that.typetag; } + @Override + public void visitVarType(JCVarType tree) { + result = true; + } + @Override public void visitTypeIntersection(JCTypeIntersection tree) { JCTypeIntersection that = (JCTypeIntersection) parameter; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index 40f91a004fd..16f26c836f8 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -977,13 +977,11 @@ public class JavacParser implements Parser { pattern = toP(F.at(token.pos).AnyPattern()); } else { - int varTypePos = Position.NOPOS; if (parsedType == null) { boolean var = token.kind == IDENTIFIER && token.name() == names.var; e = unannotatedType(allowVar, TYPE | NOLAMBDA); if (var) { - varTypePos = e.pos; - e = null; + e = replaceTypeWithVar(e); } } else { e = parsedType; @@ -1021,12 +1019,9 @@ public class JavacParser implements Parser { name = names.empty; } JCVariableDecl var = toP(F.at(varPos).VarDef(mods, name, e, null, - varTypePos != Position.NOPOS ? JCVariableDecl.DeclKind.VAR : JCVariableDecl.DeclKind.EXPLICIT, - varTypePos)); - if (e == null) { - if (var.name == names.underscore && !allowVar) { - log.error(DiagnosticFlag.SYNTAX, varPos, Errors.UseOfUnderscoreNotAllowed); - } + e.hasTag(VARTYPE) ? JCVariableDecl.DeclKind.VAR : JCVariableDecl.DeclKind.EXPLICIT)); + if (var.name == names.underscore && !allowVar) { + log.error(DiagnosticFlag.SYNTAX, varPos, Errors.UseOfUnderscoreNotAllowed); } pattern = toP(F.at(pos).BindingPattern(var)); } @@ -2178,8 +2173,7 @@ public class JavacParser implements Parser { && restrictedTypeName(param.vartype, true) != null) { checkSourceLevel(param.pos, Feature.VAR_SYNTAX_IMPLICIT_LAMBDAS); param.declKind = JCVariableDecl.DeclKind.VAR; - param.typePos = TreeInfo.getStartPos(param.vartype); - param.vartype = null; + param.vartype = replaceTypeWithVar(param.vartype); } } } @@ -3792,7 +3786,6 @@ public class JavacParser implements Parser { */ JCVariableDecl variableDeclaratorRest(int pos, JCModifiers mods, JCExpression type, Name name, boolean reqInit, Comment dc, boolean localDecl, boolean compound) { - boolean declaredUsingVar = false; JCExpression init = null; type = bracketsOpt(type); @@ -3818,7 +3811,6 @@ public class JavacParser implements Parser { syntaxError(token.pos, Errors.Expected(EQ)); } - int varTypePos = Position.NOPOS; JCTree elemType = TreeInfo.innermostType(type, true); if (elemType.hasTag(IDENT)) { Name typeName = ((JCIdent) elemType).name; @@ -3829,21 +3821,27 @@ public class JavacParser implements Parser { //error - 'var' and arrays reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedArray(typeName)); } else { - declaredUsingVar = true; - varTypePos = elemType.pos; + type = replaceTypeWithVar(type); + if (compound) //error - 'var' in compound local var decl reportSyntaxError(elemType.pos, Errors.RestrictedTypeNotAllowedCompound(typeName)); - //implicit type - type = null; } } } JCVariableDecl result = toP(F.at(pos).VarDef(mods, name, type, init, - declaredUsingVar ? JCVariableDecl.DeclKind.VAR : JCVariableDecl.DeclKind.EXPLICIT, varTypePos)); + type.hasTag(VARTYPE) ? JCVariableDecl.DeclKind.VAR : JCVariableDecl.DeclKind.EXPLICIT)); return attach(result, dc); } + JCExpression replaceTypeWithVar(JCExpression type) { + JCVarType varType = F.at(type).VarType(); + + varType.endpos = type.endpos; + + return varType; + } + Name restrictedTypeName(JCExpression e, boolean shouldWarn) { switch (e.getTag()) { case IDENT: @@ -3954,11 +3952,10 @@ public class JavacParser implements Parser { name = names.empty; } - boolean declaredUsingVar = type != null && type.hasTag(IDENT) && ((JCIdent)type).name == names.var; + boolean declaredUsingVar = type != null && type.hasTag(VARTYPE); JCVariableDecl.DeclKind declKind = declaredUsingVar ? JCVariableDecl.DeclKind.VAR : type != null ? JCVariableDecl.DeclKind.EXPLICIT : JCVariableDecl.DeclKind.IMPLICIT; - int typePos = type != null ? type.pos : pos; - return toP(F.at(pos).VarDef(mods, name, type, null, declKind, typePos)); + return toP(F.at(pos).VarDef(mods, name, type, null, declKind)); } /** Resources = Resource { ";" Resources } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java index c54507bed3f..f0a8b6034df 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/JCTree.java @@ -277,6 +277,10 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { */ TYPEIDENT, + /** 'var' type. + */ + VARTYPE, + /** Array types, of type TypeArray. */ TYPEARRAY, @@ -1038,15 +1042,13 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { public VarSymbol sym; /** how the variable's type was declared */ public DeclKind declKind; - /** a source code position to use for "vartype" when null (can happen if declKind != EXPLICIT) */ - public int typePos; protected JCVariableDecl(JCModifiers mods, Name name, JCExpression vartype, JCExpression init, VarSymbol sym) { - this(mods, name, vartype, init, sym, DeclKind.EXPLICIT, Position.NOPOS); + this(mods, name, vartype, init, sym, DeclKind.EXPLICIT); } protected JCVariableDecl(JCModifiers mods, @@ -1054,21 +1056,19 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { JCExpression vartype, JCExpression init, VarSymbol sym, - DeclKind declKind, - int typePos) { + DeclKind declKind) { this.mods = mods; this.name = name; this.vartype = vartype; this.init = init; this.sym = sym; this.declKind = declKind; - this.typePos = typePos; } protected JCVariableDecl(JCModifiers mods, JCExpression nameexpr, JCExpression vartype) { - this(mods, null, vartype, null, null, DeclKind.EXPLICIT, Position.NOPOS); + this(mods, null, vartype, null, null, DeclKind.EXPLICIT); this.nameexpr = nameexpr; if (nameexpr.hasTag(Tag.IDENT)) { this.name = ((JCIdent)nameexpr).name; @@ -1078,8 +1078,9 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { } } + @DefinedBy(Api.COMPILER_TREE) public boolean isImplicitlyTyped() { - return vartype == null; + return declKind != DeclKind.EXPLICIT; } public boolean declaredUsingVar() { @@ -2047,7 +2048,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { this.params = params; this.body = body; if (params.isEmpty() || - params.head.vartype != null) { + !params.head.isImplicitlyTyped()) { paramKind = ParameterKind.EXPLICIT; } else { paramKind = ParameterKind.IMPLICIT; @@ -2827,6 +2828,24 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { } } + public static class JCVarType extends JCExpression implements VarTypeTree { + public JCVarType() {} + @Override + public void accept(Visitor v) { v.visitVarType(this); } + + @DefinedBy(Api.COMPILER_TREE) + public Kind getKind() { return Kind.VAR_TYPE; } + + @Override @DefinedBy(Api.COMPILER_TREE) + public R accept(TreeVisitor v, D d) { + return v.visitVarType(this, d); + } + @Override + public Tag getTag() { + return VARTYPE; + } + } + /** * An array type, A[] */ @@ -3604,6 +3623,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition { public void visitIdent(JCIdent that) { visitTree(that); } public void visitLiteral(JCLiteral that) { visitTree(that); } public void visitTypeIdent(JCPrimitiveTypeTree that) { visitTree(that); } + public void visitVarType(JCVarType that) { visitTree(that); } public void visitTypeArray(JCArrayTypeTree that) { visitTree(that); } public void visitTypeApply(JCTypeApply that) { visitTree(that); } public void visitTypeUnion(JCTypeUnion that) { visitTree(that); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java index d953663a6d7..c22dfd61637 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java @@ -1529,6 +1529,15 @@ public class Pretty extends JCTree.Visitor { } } + @Override + public void visitVarType(JCVarType that) { + try { + print("var"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + public void visitTypeArray(JCArrayTypeTree tree) { try { printBaseElementType(tree); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java index 9efc6a9d895..95e2976f14e 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeCopier.java @@ -480,6 +480,12 @@ public class TreeCopier

implements TreeVisitor { return M.at(t.pos).TypeIdent(t.typetag); } + @DefinedBy(Api.COMPILER_TREE) + public JCTree visitVarType(VarTypeTree node, P p) { + JCVarType t = (JCVarType) node; + return M.at(t.pos).VarType(); + } + @DefinedBy(Api.COMPILER_TREE) public JCTree visitTypeParameter(TypeParameterTree node, P p) { JCTypeParameter t = (JCTypeParameter) node; @@ -551,7 +557,7 @@ public class TreeCopier

implements TreeVisitor { JCExpression vartype = copy(t.vartype, p); if (t.nameexpr == null) { JCExpression init = copy(t.init, p); - return M.at(t.pos).VarDef(mods, t.name, vartype, init, t.declKind, t.typePos); + return M.at(t.pos).VarDef(mods, t.name, vartype, init, t.declKind); } else { JCExpression nameexpr = copy(t.nameexpr, p); return M.at(t.pos).ReceiverVarDef(mods, nameexpr, vartype); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java index aa616f3f580..ffb259c6a8b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java @@ -621,8 +621,6 @@ public class TreeInfo { return node.mods.pos; } else if (node.vartype != null) { return getStartPos(node.vartype); - } else if (node.typePos != Position.NOPOS) { - return node.typePos; } break; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java index 0e71df99bdc..77391493ad2 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java @@ -238,8 +238,8 @@ public class TreeMaker implements JCTree.Factory { } public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init, - JCVariableDecl.DeclKind declKind, int typePos) { - JCVariableDecl tree = new JCVariableDecl(mods, name, vartype, init, null, declKind, typePos); + JCVariableDecl.DeclKind declKind) { + JCVariableDecl tree = new JCVariableDecl(mods, name, vartype, init, null, declKind); tree.pos = pos; return tree; } @@ -566,6 +566,12 @@ public class TreeMaker implements JCTree.Factory { return tree; } + public JCVarType VarType() { + JCVarType tree = new JCVarType(); + tree.pos = pos; + return tree; + } + public JCArrayTypeTree TypeArray(JCExpression elemtype) { JCArrayTypeTree tree = new JCArrayTypeTree(elemtype); tree.pos = pos; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java index b9ae35da9df..0d1216217c8 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeScanner.java @@ -361,6 +361,9 @@ public class TreeScanner extends Visitor { public void visitTypeIdent(JCPrimitiveTypeTree tree) { } + public void visitVarType(JCVarType tree) { + } + public void visitTypeArray(JCArrayTypeTree tree) { scan(tree.elemtype); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java index 63778fb42ff..5b06e76bf33 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeTranslator.java @@ -418,6 +418,10 @@ public class TreeTranslator extends JCTree.Visitor { result = tree; } + public void visitVarType(JCVarType tree) { + result = tree; + } + public void visitTypeArray(JCArrayTypeTree tree) { tree.elemtype = translate(tree.elemtype); result = tree; diff --git a/src/jdk.jshell/share/classes/jdk/jshell/Eval.java b/src/jdk.jshell/share/classes/jdk/jshell/Eval.java index bc6f6d30236..70f3b70fd66 100644 --- a/src/jdk.jshell/share/classes/jdk/jshell/Eval.java +++ b/src/jdk.jshell/share/classes/jdk/jshell/Eval.java @@ -337,7 +337,7 @@ class Eval { Set anonymousClasses = Collections.emptySet(); StringBuilder sbBrackets = new StringBuilder(); Tree baseType = vt.getType(); - if (baseType != null) { + if (vt.getType() != null && vt.getType().getKind() != Tree.Kind.VAR_TYPE) { tds.scan(baseType); // Not dependent on initializer fullTypeName = displayType = typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false); while (baseType instanceof ArrayTypeTree) { diff --git a/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysisImpl.java b/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysisImpl.java index 1cf0c85702f..35faab231af 100644 --- a/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysisImpl.java +++ b/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysisImpl.java @@ -816,7 +816,7 @@ class SourceCodeAnalysisImpl extends SourceCodeAnalysis { SourcePositions sp = trees.getSourcePositions(); List tokens = new ArrayList<>(); Context ctx = new Context(); - ctx.put(DiagnosticListener.class, (DiagnosticListener) d -> {}); + ctx.put(DiagnosticListener.class, (DiagnosticListener) d -> {}); Scanner scanner = ScannerFactory.instance(ctx).newScanner(wrappedCode, false); Log.instance(ctx).useSource(cut.getSourceFile()); scanner.nextToken(); @@ -932,7 +932,7 @@ class SourceCodeAnalysisImpl extends SourceCodeAnalysis { @Override public Void visitVariable(VariableTree node, Void p) { int pos = ((JCTree) node).pos; - if (sp.getEndPosition(cut, node.getType()) == (-1)) { + if (node.getType() != null && node.getType().getKind() == Kind.VAR_TYPE) { Token varCandidate = findTokensBefore(pos, TokenKind.IDENTIFIER); if (varCandidate != null && "var".equals(varCandidate.name().toString())) { addKeyword.accept(varCandidate); diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables-old.out b/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables-old.out index 5b16d28d053..2b447e4a842 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables-old.out +++ b/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables-old.out @@ -4,6 +4,4 @@ VarVariables.java:24:14: compiler.err.annotation.type.not.applicable VarVariables.java:27:14: compiler.err.annotation.type.not.applicable VarVariables.java:32:14: compiler.err.annotation.type.not.applicable VarVariables.java:36:37: compiler.err.annotation.type.not.applicable -VarVariables.java:32:18: compiler.err.type.annotation.inadmissible: (compiler.misc.type.annotation.1: @VarVariables.TA), java.lang, @VarVariables.TA java.lang.AutoCloseable -VarVariables.java:36:41: compiler.err.type.annotation.inadmissible: (compiler.misc.type.annotation.1: @VarVariables.TA), java.lang, @VarVariables.TA java.lang.String -8 errors +6 errors diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables.out b/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables.out index 2586e7883d6..7f055040855 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables.out +++ b/test/langtools/tools/javac/annotations/typeAnnotations/failures/target/VarVariables.out @@ -4,6 +4,4 @@ VarVariables.java:24:14: compiler.err.annotation.type.not.applicable VarVariables.java:27:14: compiler.err.annotation.type.not.applicable VarVariables.java:32:14: compiler.err.annotation.type.not.applicable VarVariables.java:36:37: compiler.err.annotation.type.not.applicable -VarVariables.java:32:18: compiler.err.type.annotation.inadmissible: (compiler.misc.type.annotation.1: @VarVariables.TA), java.lang, @VarVariables.TA java.lang.AutoCloseable -VarVariables.java:36:41: compiler.err.type.annotation.inadmissible: (compiler.misc.type.annotation.1: @VarVariables.TA), java.lang, @VarVariables.TA java.lang.String -8 errors +6 errors diff --git a/test/langtools/tools/javac/lvti/VarAccessibility.java b/test/langtools/tools/javac/lvti/VarAccessibility.java new file mode 100644 index 00000000000..d39d706faea --- /dev/null +++ b/test/langtools/tools/javac/lvti/VarAccessibility.java @@ -0,0 +1,393 @@ +/* + * 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 + * @summary Check behavior of var when the inferred type is inaccessible + * @library /tools/lib + * @modules java.logging + * java.sql + * jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.compiler/com.sun.tools.javac.util + * @build toolbox.ToolBox toolbox.JavacTask + * @run junit VarAccessibility + */ + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Objects; + +import org.junit.jupiter.api.Test; + +import toolbox.JavacTask; +import toolbox.JavaTask; +import toolbox.Task; +import toolbox.ToolBox; + +public class VarAccessibility { + + private static final ToolBox tb = new ToolBox(); + + @Test + public void testInaccessibleInferredTypeLocalVariable() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + public class API { + public static PackagePrivate get() { + return new PackagePrivate(); + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + var v = API.get(); + System.out.println(v); + } + } + """); + + Files.createDirectories(classes); + + new JavacTask(tb) + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.SUCCESS) + .writeAll(); + + var out = new JavaTask(tb) + .classpath(classes.toString()) + .className("p2.Test") + .run() + .writeAll() + .getOutputLines(Task.OutputKind.STDOUT); + + var expectedOut = List.of("pass"); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + + @Test + public void testInaccessibleInferredTypeForEachIterable() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + import java.util.List; + public class API { + public static Iterable get() { + return List.of(new PackagePrivate()); + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + for (var v : API.get()) { + System.out.println(v); + } + } + } + """); + + Files.createDirectories(classes); + + var out = new JavacTask(tb) + .options("-XDrawDiagnostics") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of( + "Test.java:5:22: compiler.err.not.def.public.cant.access: p1.PackagePrivate, p1", + "1 error"); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + + @Test + public void testInaccessibleInferredTypeForEachArray() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + import java.util.List; + public class API { + public static PackagePrivate[] get() { + return new PackagePrivate[] {new PackagePrivate()}; + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + for (var v : API.get()) { + System.out.println(v); + } + } + } + """); + + Files.createDirectories(classes); + + new JavacTask(tb) + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.SUCCESS) + .writeAll(); + + var out = new JavaTask(tb) + .classpath(classes.toString()) + .className("p2.Test") + .run() + .writeAll() + .getOutputLines(Task.OutputKind.STDOUT); + + var expectedOut = List.of("pass"); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + + @Test + public void testInaccessibleInferredTypeLambda() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + import java.util.function.Consumer; + public class API { + public static void run(Consumer c) { + c.accept(new PackagePrivate()); + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + API.run(v -> System.out.println(v)); + API.run((var v) -> System.out.println(v)); + } + } + """); + + Files.createDirectories(classes); + + var out = new JavacTask(tb) + .options("-XDrawDiagnostics") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of( + "Test.java:5:17: compiler.err.not.def.public.cant.access: p1.PackagePrivate, p1", + "Test.java:6:17: compiler.err.not.def.public.cant.access: p1.PackagePrivate, p1", + "2 errors"); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + + @Test + public void testInaccessibleInferredTypeCanUse() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + public class API { + public static PackagePrivate get() { + return null; + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + var v = API.get(); + System.out.println(v.toString()); + } + } + """); + + Files.createDirectories(classes); + + List log = new JavacTask(tb) + .options("-XDrawDiagnostics") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of( + "Test.java:6:29: compiler.err.not.def.access.class.intf.cant.access: toString(), p1.PackagePrivate", + "1 error" + ); + + if (!Objects.equals(expectedOut, log)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + log); + + } + } + + @Test + public void testInaccessibleInferredBindingPattern() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + public record API(PackagePrivate p) { + public static API create() { + return new API(new PackagePrivate()); + } + } + """, + """ + package p1; + class PackagePrivate { + public String toString() { + return "pass"; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + Object o = API.create(); + if (o instanceof API(var v)) { + System.out.println(v.toString()); + } + } + } + """); + + Files.createDirectories(classes); + + List log = new JavacTask(tb) + .options("-XDrawDiagnostics") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of( + "Test.java:7:33: compiler.err.not.def.access.class.intf.cant.access: toString(), p1.PackagePrivate", + "1 error" + ); + + if (!Objects.equals(expectedOut, log)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + log); + + } + } +} diff --git a/test/langtools/tools/javac/lvti/VarWarnings.java b/test/langtools/tools/javac/lvti/VarWarnings.java new file mode 100644 index 00000000000..a1fbadc0393 --- /dev/null +++ b/test/langtools/tools/javac/lvti/VarWarnings.java @@ -0,0 +1,193 @@ +/* + * 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 + * @summary Check behavior of warnings related to var + * @library /tools/lib + * @modules java.logging + * java.sql + * jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.compiler/com.sun.tools.javac.util + * @build toolbox.ToolBox toolbox.JavacTask + * @run junit VarWarnings + */ + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Objects; + +import org.junit.jupiter.api.Test; + +import toolbox.JavacTask; +import toolbox.Task; +import toolbox.ToolBox; + +public class VarWarnings { + + private static final ToolBox tb = new ToolBox(); + + @Test + public void testDeprecationWarning() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + import java.util.List; + import java.util.function.Consumer; + @SuppressWarnings("deprecation") + public class API { + public static DeprOutter get() { + return new DeprOutter<>(); + } + public static Iterable> getIterable() { + return null; + } + public static void run(Consumer> task) { + } + } + """, + """ + package p1; + @Deprecated + public class DeprInner { + } + """, + """ + package p1; + @Deprecated + public class DeprOutter { + public T get() { + return null; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + var v1 = API.get(); + API.run(v -> v.get().toString()); + API.run((var v) -> v.get().toString()); + for (var v2 : API.getIterable()) {} + } + } + """); + + Files.createDirectories(classes); + + var out = new JavacTask(tb) + .options("-XDrawDiagnostics", + "-Werror", + "-Xlint:deprecation") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.SUCCESS) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of(""); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + + @Test + public void testRawTypeWarning() throws Exception { + Path base = Paths.get("."); + Path src = base.resolve("src"); + Path classes = base.resolve("classes"); + tb.writeJavaFiles(src, + """ + package p1; + import java.util.List; + import java.util.function.Consumer; + @SuppressWarnings("rawtypes") + public class API { + public static RawOutter get() { + return new RawOutter<>(); + } + public static Iterable> getIterable() { + return null; + } + public static void run(Consumer> task) { + } + } + """, + """ + package p1; + public class RawInner { + } + """, + """ + package p1; + public class RawOutter { + public T get() { + return null; + } + } + """, + """ + package p2; + import p1.API; + public class Test { + public static void main(String... args) { + var v1 = API.get(); + API.run(v -> v.get().toString()); + API.run((var v) -> v.get().toString()); + for (var v2 : API.getIterable()) {} + } + } + """); + + Files.createDirectories(classes); + + var out = new JavacTask(tb) + .options("-XDrawDiagnostics", + "-Werror", + "-Xlint:rawtypes") + .outdir(classes) + .files(tb.findJavaFiles(src)) + .run(Task.Expect.SUCCESS) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + var expectedOut = List.of(""); + + if (!Objects.equals(expectedOut, out)) { + throw new AssertionError("Incorrect Output, expected: " + expectedOut + + ", actual: " + out); + + } + } + +} diff --git a/test/langtools/tools/javac/parser/DeclarationEndPositions.java b/test/langtools/tools/javac/parser/DeclarationEndPositions.java index c61a92e80cd..fe4ca8c1652 100644 --- a/test/langtools/tools/javac/parser/DeclarationEndPositions.java +++ b/test/langtools/tools/javac/parser/DeclarationEndPositions.java @@ -86,10 +86,12 @@ public class DeclarationEndPositions { // For variable declarations using "var", verify the "var" position if (tree instanceof JCVariableDecl varDecl && varDecl.declaredUsingVar()) { - int vpos = varDecl.typePos; - if (!input.substring(vpos).startsWith("var")) { + int varStart = varDecl.vartype.getStartPosition(); + int varEnd = varDecl.vartype.getEndPosition(); + + if (!input.substring(varStart, varEnd).startsWith("var")) { throw new AssertionError(String.format( - "wrong %s pos %d for \"%s\" in \"%s\"", "var", vpos, tree, input)); + "wrong %s start pos %d end pos %d for \"%s\" in \"%s\"", "var", varStart, varEnd, tree, input)); } } } diff --git a/test/langtools/tools/javac/parser/JavacParserTest.java b/test/langtools/tools/javac/parser/JavacParserTest.java index 25aeb19f1bb..0bce1ef017c 100644 --- a/test/langtools/tools/javac/parser/JavacParserTest.java +++ b/test/langtools/tools/javac/parser/JavacParserTest.java @@ -87,7 +87,9 @@ import javax.tools.ToolProvider; import com.sun.source.tree.CaseTree; import com.sun.source.tree.DefaultCaseLabelTree; +import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.ModuleTree; +import com.sun.source.tree.VarTypeTree; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.api.JavacTaskPool; import com.sun.tools.javac.api.JavacTaskPool.Worker; @@ -1070,8 +1072,8 @@ public class JavacParserTest extends TestCase { VariableTree stmt2 = (VariableTree) method.getBody().getStatements().get(1); Tree v1Type = stmt1.getType(); Tree v2Type = stmt2.getType(); - assertEquals("Implicit type for v1 is not correct: ", Kind.PRIMITIVE_TYPE, v1Type.getKind()); - assertEquals("Implicit type for v2 is not correct: ", Kind.PRIMITIVE_TYPE, v2Type.getKind()); + assertEquals("Implicit type for v1 is not correct: ", Kind.VAR_TYPE, v1Type.getKind()); + assertEquals("Implicit type for v2 is not correct: ", Kind.VAR_TYPE, v2Type.getKind()); } @Test @@ -3151,6 +3153,37 @@ public class JavacParserTest extends TestCase { codes); } + @Test + void testVarPositions() throws IOException { + String code = """ + public class Test { + void t() { + var v = + } + } + """; + DiagnosticCollector coll = + new DiagnosticCollector<>(); + JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, + null, + null, Arrays.asList(new MyFileObject(code))); + Trees trees = Trees.instance(ct); + SourcePositions sp = trees.getSourcePositions(); + CompilationUnitTree cut = ct.parse().iterator().next(); + new TreeScanner() { + @Override + public Void visitVarType(VarTypeTree node, Void p) { + long start = sp.getStartPosition(cut, node); + long end = sp.getEndPosition(cut, node); + String text = code.substring((int) start, (int) end); + assertEquals("var start pos", + "var", + text); + return null; + } + }; + } + void run(String[] args) throws Exception { int passed = 0, failed = 0; final Pattern p = (args != null && args.length > 0) diff --git a/test/langtools/tools/javac/patterns/BindingPatternVarTypeModel.java b/test/langtools/tools/javac/patterns/BindingPatternVarTypeModel.java index e63cbeb2008..01d742eb9e3 100644 --- a/test/langtools/tools/javac/patterns/BindingPatternVarTypeModel.java +++ b/test/langtools/tools/javac/patterns/BindingPatternVarTypeModel.java @@ -83,7 +83,7 @@ public class BindingPatternVarTypeModel { new TreeScanner() { @Override public Void visitBindingPattern(BindingPatternTree node, Void p) { - if (node.getVariable().getType().getKind() != Tree.Kind.PRIMITIVE_TYPE) { + if (node.getVariable().getType().getKind() != Tree.Kind.VAR_TYPE) { throw new AssertionError("Unexpected type for var: " + node.getVariable().getType().getKind() + ":" + node.getVariable().getType()); diff --git a/test/langtools/tools/javac/patterns/InstanceOfModelTest.java b/test/langtools/tools/javac/patterns/InstanceOfModelTest.java index b756c9263bd..288abec9659 100644 --- a/test/langtools/tools/javac/patterns/InstanceOfModelTest.java +++ b/test/langtools/tools/javac/patterns/InstanceOfModelTest.java @@ -79,7 +79,7 @@ public class InstanceOfModelTest { List expectedInstanceOf = List.of( "null:R", "R r:R", - "R(int v):null" + "R(var v):null" ); if (!Objects.equals(expectedInstanceOf, instanceOf)) { diff --git a/test/langtools/tools/javac/tree/VarTree.java b/test/langtools/tools/javac/tree/VarTree.java index 6efd080bd4f..70caf66862e 100644 --- a/test/langtools/tools/javac/tree/VarTree.java +++ b/test/langtools/tools/javac/tree/VarTree.java @@ -52,27 +52,27 @@ public class VarTree { public static void main(String... args) throws Exception { VarTree test = new VarTree(); test.run("|var testVar = 0;| ", - "int testVar = 0"); + "var testVar = 0"); test.run("|var testVar = 0;| undef undef;", - "int testVar = 0"); + "var testVar = 0"); test.run("|final var testVar = 0;| ", - "final int testVar = 0"); + "final var testVar = 0"); test.run("for (|var testVar| : java.util.Arrays.asList(0, 1)) {}", - "java.lang.Integer testVar"); + "var testVar"); test.run("for (|final var testVar| : java.util.Arrays.asList(0, 1)) {}", - "final java.lang.Integer testVar"); + "final var testVar"); test.run("java.util.function.Consumer c = |testVar| -> {};", - "java.lang.String testVar"); + "/*missing*/ testVar"); //TODO: is the /*missing*/ here ideal? test.run("java.util.function.Consumer c = (|testVar|) -> {};", - "java.lang.String testVar"); + "/*missing*/ testVar"); //TODO: is the /*missing*/ here ideal? test.run("java.util.function.Consumer c = (|var testVar|) -> {};", - "java.lang.String testVar"); + "var testVar"); test.run("java.util.function.Consumer c = (|final var testVar|) -> {};", - "final java.lang.String testVar"); + "final var testVar"); test.run("record Rec(int x) { }; switch (null) { case Rec(|var testVar|) -> {} default -> {} };", - "int testVar"); + "var testVar"); test.run("record Rec(int x) { }; switch (null) { case Rec(|final var testVar|) -> {} default -> {} };", - "final int testVar"); + "final var testVar"); } void run(String code, String expected) throws IOException { @@ -136,11 +136,13 @@ public class VarTree { throw new AssertionError("Unexpected span: " + snip); } - int typeStart = (int) trees.getSourcePositions().getStartPosition(cut, node.getType()); - int typeEnd = (int) trees.getSourcePositions().getEndPosition(cut, node.getType()); + if (node.getType() != null) { + int typeStart = (int) trees.getSourcePositions().getStartPosition(cut, node.getType()); + int typeEnd = (int) trees.getSourcePositions().getEndPosition(cut, node.getType()); - if (typeStart != (-1) && typeEnd != (-1)) { - throw new AssertionError("Unexpected type position: " + typeStart + ", " + typeEnd); + if (typeStart + 3 != typeEnd) { + throw new AssertionError("Unexpected type position: " + typeStart + ", " + typeEnd); + } } found[0] = true; diff --git a/test/langtools/tools/javac/tree/VarWarnPosition.java b/test/langtools/tools/javac/tree/VarWarnPosition.java index f1d5f4346d0..5cdfa41d6ef 100644 --- a/test/langtools/tools/javac/tree/VarWarnPosition.java +++ b/test/langtools/tools/javac/tree/VarWarnPosition.java @@ -25,6 +25,9 @@ public class VarWarnPosition { // Test 4 Consumer c3 = (final var d) -> { }; + + // Test 5 + var d = deprecatedList.get(0); } } diff --git a/test/langtools/tools/javac/tree/VarWarnPosition.out b/test/langtools/tools/javac/tree/VarWarnPosition.out index 87a4ca3a1fd..0bd92acd035 100644 --- a/test/langtools/tools/javac/tree/VarWarnPosition.out +++ b/test/langtools/tools/javac/tree/VarWarnPosition.out @@ -1,8 +1,4 @@ -VarWarnPosition.java:18:14: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package VarWarnPosition.java:21:18: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package -VarWarnPosition.java:21:28: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package VarWarnPosition.java:24:18: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package -VarWarnPosition.java:24:30: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package VarWarnPosition.java:27:18: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package -VarWarnPosition.java:27:36: compiler.warn.has.been.deprecated: Depr, compiler.misc.unnamed.package -7 warnings +3 warnings \ No newline at end of file From 3d8ffabe5dc6efda10ee7c76cca47e54b5383b48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20H=C3=A4ssig?= Date: Thu, 26 Feb 2026 08:21:48 +0000 Subject: [PATCH 13/54] 8364393: Allow templates to have # character without variable replacement Reviewed-by: epeter, chagedorn --- .../lib/template_framework/Renderer.java | 58 ++++++++--- .../lib/template_framework/Template.java | 6 +- .../examples/TestTutorial.java | 4 +- .../tests/TestTemplate.java | 99 ++++++++++++++----- 4 files changed, 130 insertions(+), 37 deletions(-) diff --git a/test/hotspot/jtreg/compiler/lib/template_framework/Renderer.java b/test/hotspot/jtreg/compiler/lib/template_framework/Renderer.java index 61ab9ab343c..cb83a5ea40c 100644 --- a/test/hotspot/jtreg/compiler/lib/template_framework/Renderer.java +++ b/test/hotspot/jtreg/compiler/lib/template_framework/Renderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -413,8 +413,39 @@ final class Renderer { } } + /** + * Finds the index where the next replacement pattern after {@code start} begins while skipping + * over "$$" and "##". + * + * @param s string to search for replacements + * @param start index from which to start searching + * @return the index of the beginning of the next replacement pattern or the length of {@code s} + */ + private int findNextReplacement(final String s, final int start) { + int next = start; + for (int potentialStart = start; potentialStart < s.length() && s.charAt(next) == s.charAt(potentialStart); potentialStart = next + 1) { + // If this is not the first iteration, we have found a doubled up "$" or "#" and need to skip + // over the second instance. + if (potentialStart != start) { + potentialStart += 1; + } + // Find the next "$" or "#", after the potential start. + int dollar = s.indexOf("$", potentialStart); + int hashtag = s.indexOf("#", potentialStart); + // If the character was not found, we want to have the rest of the + // String s, so instead of "-1" take the end/length of the String. + dollar = (dollar == -1) ? s.length() : dollar; + hashtag = (hashtag == -1) ? s.length() : hashtag; + // Take the first one. + next = Math.min(dollar, hashtag); + } + + return next; + } + /** * We split a {@link String} by "#" and "$", and then look at each part. + * However, we escape "##" to "#" and "$$" to "$". * Example: * * s: "abcdefghijklmnop #name abcdefgh${var_name} 12345#{name2}_con $field_name something" @@ -428,16 +459,19 @@ final class Renderer { int start = 0; boolean startIsAfterDollar = false; do { - // Find the next "$" or "#", after start. - int dollar = s.indexOf("$", start); - int hashtag = s.indexOf("#", start); - // If the character was not found, we want to have the rest of the - // String s, so instead of "-1" take the end/length of the String. - dollar = (dollar == -1) ? s.length() : dollar; - hashtag = (hashtag == -1) ? s.length() : hashtag; - // Take the first one. - int next = Math.min(dollar, hashtag); + int next = findNextReplacement(s, start); + + // Detect most zero sized replacement patterns, i.e. "$#" or "#$", for better error reporting. + if (next < s.length() - 2 && ((s.charAt(next) == '$' && s.charAt(next + 1) == '#') || + (s.charAt(next) == '#' && s.charAt(next + 1) == '$'))) { + String pattern = s.substring(next, next + 2); + throw new RendererException("Found zero sized replacement pattern '" + pattern + "'."); + } + String part = s.substring(start, next); + // Escape doubled up replacement characters. + part = part.replace("##", "#"); + part = part.replace("$$", "$"); if (count == 0) { // First part has no "#" or "$" before it. @@ -452,8 +486,8 @@ final class Renderer { // terminate now. return; } - start = next + 1; // skip over the "#" or "$" - startIsAfterDollar = next == dollar; // remember which character we just split with + start = next + 1; + startIsAfterDollar = s.charAt(next) == '$'; // remember which character we just split with count++; } while (true); } diff --git a/test/hotspot/jtreg/compiler/lib/template_framework/Template.java b/test/hotspot/jtreg/compiler/lib/template_framework/Template.java index f245cda0501..3cd3a9097ff 100644 --- a/test/hotspot/jtreg/compiler/lib/template_framework/Template.java +++ b/test/hotspot/jtreg/compiler/lib/template_framework/Template.java @@ -160,7 +160,8 @@ import compiler.lib.ir_framework.TestFramework; * arguments into the strings. But since string templates are not (yet) available, the Templates provide * hashtag replacements in the {@link String}s: the Template argument names are captured, and * the argument values automatically replace any {@code "#name"} in the {@link String}s. See the different overloads - * of {@link #make} for examples. Additional hashtag replacements can be defined with {@link #let}. + * of {@link #make} for examples. Additional hashtag replacements can be defined with {@link #let}. If a "#" is needed + * in the code, hashtag replacmement can be escaped by writing two hashtags, i.e. "##" will render as "#". * We have decided to keep hashtag replacements constrained to the scope of one Template. They * do not escape to outer or inner Template uses. If one needs to pass values to inner Templates, * this can be done with Template arguments. Keeping hashtag replacements local to Templates @@ -172,7 +173,8 @@ import compiler.lib.ir_framework.TestFramework; * For this, Templates provide dollar replacements, which automatically rename any * {@code "$name"} in the {@link String} with a {@code "name_ID"}, where the {@code "ID"} is unique for every use of * a Template. The dollar replacement can also be captured with {@link #$}, and passed to nested - * Templates, which allows sharing of these identifier names between Templates. + * Templates, which allows sharing of these identifier names between Templates. Similar to hashtag replacements, + * dollars can be escaped by doubling up, i.e. "$$" renders as "$". * *

* The dollar and hashtag names must have at least one character. The first character must be a letter diff --git a/test/hotspot/jtreg/testlibrary_tests/template_framework/examples/TestTutorial.java b/test/hotspot/jtreg/testlibrary_tests/template_framework/examples/TestTutorial.java index ed542180bad..7de32d1bc10 100644 --- a/test/hotspot/jtreg/testlibrary_tests/template_framework/examples/TestTutorial.java +++ b/test/hotspot/jtreg/testlibrary_tests/template_framework/examples/TestTutorial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -226,6 +226,8 @@ public class TestTutorial { // we automatically rename the names that have a $ prepended with // var_1, var_2, etc. """ + // You can escape a hashtag by doubling it up. e.g. ## will render as a + // single hashtag. The same goes for $$. int $var = #con; System.out.println("T1: #x, #con, " + $var); """ diff --git a/test/hotspot/jtreg/testlibrary_tests/template_framework/tests/TestTemplate.java b/test/hotspot/jtreg/testlibrary_tests/template_framework/tests/TestTemplate.java index 9be74d232a7..f56a9d5b231 100644 --- a/test/hotspot/jtreg/testlibrary_tests/template_framework/tests/TestTemplate.java +++ b/test/hotspot/jtreg/testlibrary_tests/template_framework/tests/TestTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 8344942 + * @bug 8344942 8364393 * @summary Test some basic Template instantiations. We do not necessarily generate correct * java code, we just test that the code generation deterministically creates the * expected String. @@ -138,6 +138,7 @@ public class TestTemplate { testHookWithNestedTemplates(); testHookRecursion(); testDollar(); + testEscaping(); testLet1(); testLet2(); testDollarAndHashtagBrackets(); @@ -182,7 +183,6 @@ public class TestTemplate { expectRendererException(() -> testFailingDollarName5(), "Is not a valid '$' replacement pattern: '$' in '$'."); expectRendererException(() -> testFailingDollarName6(), "Is not a valid '$' replacement pattern: '$' in 'asdf$'."); expectRendererException(() -> testFailingDollarName7(), "Is not a valid '$' replacement pattern: '$1' in 'asdf$1'."); - expectRendererException(() -> testFailingDollarName8(), "Is not a valid '$' replacement pattern: '$' in 'abc$$abc'."); expectRendererException(() -> testFailingLetName1(), "A hashtag replacement should not be null."); expectRendererException(() -> testFailingHashtagName1(), "Is not a valid hashtag replacement name: ''."); expectRendererException(() -> testFailingHashtagName2(), "Is not a valid hashtag replacement name: 'abc#abc'."); @@ -191,11 +191,12 @@ public class TestTemplate { expectRendererException(() -> testFailingHashtagName5(), "Is not a valid '#' replacement pattern: '#' in '#'."); expectRendererException(() -> testFailingHashtagName6(), "Is not a valid '#' replacement pattern: '#' in 'asdf#'."); expectRendererException(() -> testFailingHashtagName7(), "Is not a valid '#' replacement pattern: '#1' in 'asdf#1'."); - expectRendererException(() -> testFailingHashtagName8(), "Is not a valid '#' replacement pattern: '#' in 'abc##abc'."); expectRendererException(() -> testFailingDollarHashtagName1(), "Is not a valid '#' replacement pattern: '#' in '#$'."); expectRendererException(() -> testFailingDollarHashtagName2(), "Is not a valid '$' replacement pattern: '$' in '$#'."); - expectRendererException(() -> testFailingDollarHashtagName3(), "Is not a valid '#' replacement pattern: '#' in '#$name'."); - expectRendererException(() -> testFailingDollarHashtagName4(), "Is not a valid '$' replacement pattern: '$' in '$#name'."); + expectRendererException(() -> testFailingDollarHashtagName3(), "Found zero sized replacement pattern '#$'."); + expectRendererException(() -> testFailingDollarHashtagName4(), "Found zero sized replacement pattern '$#'."); + expectRendererException(() -> testFailingDollarHashtagName5(), "Found zero sized replacement pattern '#$'."); + expectRendererException(() -> testFailingDollarHashtagName6(), "Found zero sized replacement pattern '$#'."); expectRendererException(() -> testFailingHook(), "Hook 'Hook1' was referenced but not found!"); expectRendererException(() -> testFailingSample1a(), "No Name found for DataName.FilterdSet(MUTABLE, subtypeOf(int), supertypeOf(int))"); expectRendererException(() -> testFailingSample1b(), "No Name found for StructuralName.FilteredSet( subtypeOf(StructuralA) supertypeOf(StructuralA))"); @@ -822,6 +823,60 @@ public class TestTemplate { checkEQ(code, expected); } + public static void testEscaping() { + var template1 = Template.make(() -> scope( + let("one", 1), + let("two", 2), + let("three", 3), + """ + abc##def + abc$$def + abc####def + abc$$$$def + ##abc + $$abc + abc## + abc$$ + ## + $$ + ###### + $$$$$$ + abc###one + abc$$$dollar + #one ###two #####three + ###{one}## + $dollar $$$dollar $$$$$dollar + $$${dollar}$$ + ##$dollar $$#one $$##$$## + """ + )); + + String code = template1.render(); + String expected = + """ + abc#def + abc$def + abc##def + abc$$def + #abc + $abc + abc# + abc$ + # + $ + ### + $$$ + abc#1 + abc$dollar_1 + 1 #2 ##3 + #1# + dollar_1 $dollar_1 $$dollar_1 + $dollar_1$ + #dollar_1 $1 $#$# + """; + checkEQ(code, expected); + } + public static void testLet1() { var hook1 = new Hook("Hook1"); @@ -3382,13 +3437,6 @@ public class TestTemplate { String code = template1.render(); } - public static void testFailingDollarName8() { - var template1 = Template.make(() -> scope( - "abc$$abc" // empty dollar name - )); - String code = template1.render(); - } - public static void testFailingLetName1() { var template1 = Template.make(() -> scope( let(null, $("abc")) // Null input for hashtag name @@ -3447,13 +3495,6 @@ public class TestTemplate { String code = template1.render(); } - public static void testFailingHashtagName8() { - var template1 = Template.make(() -> scope( - "abc##abc" // empty hashtag name - )); - String code = template1.render(); - } - public static void testFailingDollarHashtagName1() { var template1 = Template.make(() -> scope( "#$" // empty hashtag name @@ -3470,14 +3511,28 @@ public class TestTemplate { public static void testFailingDollarHashtagName3() { var template1 = Template.make(() -> scope( - "#$name" // empty hashtag name + "#$name" // Zero sized replacement )); String code = template1.render(); } public static void testFailingDollarHashtagName4() { var template1 = Template.make(() -> scope( - "$#name" // empty dollar name + "$#name" // Zero sized replacement + )); + String code = template1.render(); + } + + public static void testFailingDollarHashtagName5() { + var template1 = Template.make(() -> scope( + "asdf#$abc" // Zero sized replacement + )); + String code = template1.render(); + } + + public static void testFailingDollarHashtagName6() { + var template1 = Template.make(() -> scope( + "asdf$#abc" // Zero sized replacement )); String code = template1.render(); } From 4a08996147222d0d8f77655798ac4c3bb5471633 Mon Sep 17 00:00:00 2001 From: Andrew Haley Date: Thu, 26 Feb 2026 11:02:59 +0000 Subject: [PATCH 14/54] 8378107: Data cache zeroing is used even when it is prohibited Reviewed-by: shade, adinn --- src/hotspot/cpu/aarch64/vm_version_aarch64.cpp | 4 +++- src/hotspot/cpu/aarch64/vm_version_aarch64.hpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp index b678921dd97..9b85733ed08 100644 --- a/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp @@ -446,7 +446,9 @@ void VM_Version::initialize() { FLAG_SET_DEFAULT(BlockZeroingLowLimit, 4 * VM_Version::zva_length()); } } else if (UseBlockZeroing) { - warning("DC ZVA is not available on this CPU"); + if (!FLAG_IS_DEFAULT(UseBlockZeroing)) { + warning("DC ZVA is not available on this CPU"); + } FLAG_SET_DEFAULT(UseBlockZeroing, false); } diff --git a/src/hotspot/cpu/aarch64/vm_version_aarch64.hpp b/src/hotspot/cpu/aarch64/vm_version_aarch64.hpp index 07f6c09e18f..0213872852b 100644 --- a/src/hotspot/cpu/aarch64/vm_version_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/vm_version_aarch64.hpp @@ -207,7 +207,7 @@ public: return false; } - static bool is_zva_enabled() { return 0 <= _zva_length; } + static bool is_zva_enabled() { return 0 < _zva_length; } static int zva_length() { assert(is_zva_enabled(), "ZVA not available"); return _zva_length; From 00064ee77365129074be73d519ebd3570cc38d3a Mon Sep 17 00:00:00 2001 From: Quan Anh Mai Date: Thu, 26 Feb 2026 11:22:43 +0000 Subject: [PATCH 15/54] 8378239: C2: Incorrect check in StoreNode::Identity Reviewed-by: epeter, rcastanedalo --- src/hotspot/share/opto/memnode.cpp | 7 +++++-- .../vectorapi/TestVectorLoadStoreOptimization.java | 12 ++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/hotspot/share/opto/memnode.cpp b/src/hotspot/share/opto/memnode.cpp index 5af0794f29c..f92d6fcfb6c 100644 --- a/src/hotspot/share/opto/memnode.cpp +++ b/src/hotspot/share/opto/memnode.cpp @@ -3567,8 +3567,11 @@ Node* StoreNode::Identity(PhaseGVN* phase) { val->in(MemNode::Address)->eqv_uncast(adr) && val->in(MemNode::Memory )->eqv_uncast(mem) && val->as_Load()->store_Opcode() == Opcode()) { - // Ensure vector type is the same - if (!is_StoreVector() || (mem->is_LoadVector() && as_StoreVector()->vect_type() == mem->as_LoadVector()->vect_type())) { + if (!is_StoreVector()) { + result = mem; + } else if (Opcode() == Op_StoreVector && val->Opcode() == Op_LoadVector && + as_StoreVector()->vect_type() == val->as_LoadVector()->vect_type()) { + // Ensure both are not masked accesses or gathers/scatters and vector types are the same result = mem; } } diff --git a/test/hotspot/jtreg/compiler/vectorapi/TestVectorLoadStoreOptimization.java b/test/hotspot/jtreg/compiler/vectorapi/TestVectorLoadStoreOptimization.java index c603f450d0c..71507bde7c0 100644 --- a/test/hotspot/jtreg/compiler/vectorapi/TestVectorLoadStoreOptimization.java +++ b/test/hotspot/jtreg/compiler/vectorapi/TestVectorLoadStoreOptimization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * Copyright (c) 2025, 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ import jdk.incubator.vector.*; import jdk.test.lib.Asserts; /** - * @test 8371603 + * @test 8371603 8378239 * @key randomness * @library /test/lib / * @summary Test the missing optimization issues for vector load/store caused by JDK-8286941 @@ -96,6 +96,14 @@ public class TestVectorLoadStoreOptimization { } } + // Test that store a value that is just loaded from the same memory location is elided + @Test + @IR(failOn = IRNode.STORE_VECTOR, + applyIfCPUFeatureOr = {"asimd", "true", "avx", "true", "rvv", "true"}) + public static void testStoreVector2() { + IntVector.fromArray(SPECIES, a, 0).intoArray(a, 0); + } + public static void main(String[] args) { TestFramework testFramework = new TestFramework(); testFramework.setDefaultWarmup(10000) From 7065a24be669b8a6cb319124ac5b3b1667420463 Mon Sep 17 00:00:00 2001 From: Quan Anh Mai Date: Thu, 26 Feb 2026 11:28:39 +0000 Subject: [PATCH 16/54] 8378240: C2: MemNode::can_see_stored_value assumes this can never be a StoreVector Reviewed-by: chagedorn, epeter --- src/hotspot/share/opto/memnode.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/hotspot/share/opto/memnode.cpp b/src/hotspot/share/opto/memnode.cpp index f92d6fcfb6c..21ed15f9ec7 100644 --- a/src/hotspot/share/opto/memnode.cpp +++ b/src/hotspot/share/opto/memnode.cpp @@ -1228,8 +1228,13 @@ Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const { } // LoadVector/StoreVector needs additional check to ensure the types match. if (st->is_StoreVector()) { - const TypeVect* in_vt = st->as_StoreVector()->vect_type(); - const TypeVect* out_vt = as_LoadVector()->vect_type(); + if ((Opcode() != Op_LoadVector && Opcode() != Op_StoreVector) || st->Opcode() != Op_StoreVector) { + // Some kind of masked access or gather/scatter + return nullptr; + } + + const TypeVect* in_vt = st->as_StoreVector()->vect_type(); + const TypeVect* out_vt = is_Load() ? as_LoadVector()->vect_type() : as_StoreVector()->vect_type(); if (in_vt != out_vt) { return nullptr; } From 1674006047ba1e96b7b5a8baa899b7cf03e9c9b1 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Thu, 26 Feb 2026 11:47:10 +0000 Subject: [PATCH 17/54] 8378631: Update Zlib Data Compression Library to Version 1.3.2 Reviewed-by: alanb, erikj, lancea --- make/autoconf/lib-bundled.m4 | 2 +- src/java.base/share/legal/zlib.md | 4 +- .../share/native/libzip/zlib/ChangeLog | 51 +++ src/java.base/share/native/libzip/zlib/README | 28 +- .../share/native/libzip/zlib/compress.c | 46 ++- .../share/native/libzip/zlib/deflate.c | 176 ++++++---- .../share/native/libzip/zlib/deflate.h | 8 +- .../share/native/libzip/zlib/gzguts.h | 64 ++-- .../share/native/libzip/zlib/gzlib.c | 103 +++--- .../share/native/libzip/zlib/gzread.c | 314 +++++++++++------- .../share/native/libzip/zlib/gzwrite.c | 267 +++++++++------ .../share/native/libzip/zlib/infback.c | 87 ++--- .../share/native/libzip/zlib/inffast.c | 13 +- .../share/native/libzip/zlib/inffixed.h | 182 +++++----- .../share/native/libzip/zlib/inflate.c | 189 +++-------- .../share/native/libzip/zlib/inflate.h | 2 +- .../share/native/libzip/zlib/inftrees.c | 143 +++++++- .../share/native/libzip/zlib/inftrees.h | 4 +- .../native/libzip/zlib/patches/ChangeLog_java | 2 +- .../share/native/libzip/zlib/trees.c | 28 +- .../share/native/libzip/zlib/uncompr.c | 62 ++-- .../share/native/libzip/zlib/zconf.h | 46 +-- .../share/native/libzip/zlib/zcrc32.c | 166 +++------ src/java.base/share/native/libzip/zlib/zlib.h | 307 +++++++++++------ .../share/native/libzip/zlib/zutil.c | 84 +++-- .../share/native/libzip/zlib/zutil.h | 99 +++++- 26 files changed, 1452 insertions(+), 1025 deletions(-) diff --git a/make/autoconf/lib-bundled.m4 b/make/autoconf/lib-bundled.m4 index a6266bec014..bc358928af0 100644 --- a/make/autoconf/lib-bundled.m4 +++ b/make/autoconf/lib-bundled.m4 @@ -268,7 +268,7 @@ AC_DEFUN_ONCE([LIB_SETUP_ZLIB], if test "x$USE_EXTERNAL_LIBZ" = "xfalse"; then LIBZ_CFLAGS="$LIBZ_CFLAGS -I$TOPDIR/src/java.base/share/native/libzip/zlib" if test "x$OPENJDK_TARGET_OS" = xmacosx; then - LIBZ_CFLAGS="$LIBZ_CFLAGS -DHAVE_UNISTD_H" + LIBZ_CFLAGS="$LIBZ_CFLAGS -DHAVE_UNISTD_H=1 -DHAVE_STDARG_H=1" fi else LIBZ_LIBS="-lz" diff --git a/src/java.base/share/legal/zlib.md b/src/java.base/share/legal/zlib.md index fcc5457bf5b..c729c4248d4 100644 --- a/src/java.base/share/legal/zlib.md +++ b/src/java.base/share/legal/zlib.md @@ -1,9 +1,9 @@ -## zlib v1.3.1 +## zlib v1.3.2 ### zlib License

 
-Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
+Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
 
 This software is provided 'as-is', without any express or implied
 warranty.  In no event will the authors be held liable for any damages
diff --git a/src/java.base/share/native/libzip/zlib/ChangeLog b/src/java.base/share/native/libzip/zlib/ChangeLog
index b801a1031ec..312753edade 100644
--- a/src/java.base/share/native/libzip/zlib/ChangeLog
+++ b/src/java.base/share/native/libzip/zlib/ChangeLog
@@ -1,6 +1,57 @@
 
                 ChangeLog file for zlib
 
+Changes in 1.3.2 (17 Feb 2026)
+- Continued rewrite of CMake build [Vollstrecker]
+- Various portability improvements
+- Various github workflow additions and improvements
+- Check for negative lengths in crc32_combine functions
+- Copy only the initialized window contents in inflateCopy
+- Prevent the use of insecure functions without an explicit request
+- Add compressBound_z and deflateBound_z functions for large values
+- Use atomics to build inflate fixed tables once
+- Add definition of ZLIB_INSECURE to build tests with c89 and c94
+- Add --undefined option to ./configure for UBSan checker
+- Copy only the initialized deflate state in deflateCopy
+- Zero inflate state on allocation
+- Remove untgz from contrib
+- Add _z versions of the compress and uncompress functions
+- Vectorize the CRC-32 calculation on the s390x
+- Set bit 11 of the zip header flags in minizip if UTF-8
+- Update OS/400 support
+- Add a test to configure to check for a working compiler
+- Check for invalid NULL pointer inputs to zlib operations
+- Add --mandir to ./configure to specify manual directory
+- Add LICENSE.Info-Zip to contrib/minizip
+- Remove vstudio projects in lieu of cmake-generated projects
+- Replace strcpy() with memcpy() in contrib/minizip
+
+Changes in 1.3.1.2 (8 Dec 2025)
+- Improve portability to RISC OS
+- Permit compiling contrib/minizip/unzip.c with decryption
+- Enable build of shared library on AIX
+- Make deflateBound() more conservative and handle Z_STREAM_END
+- Add zipAlreadyThere() to minizip zip.c to help avoid duplicates
+- Make z_off_t 64 bits by default
+- Add deflateUsed() function to get the used bits in the last byte
+- Avoid out-of-bounds pointer arithmetic in inflateCopy()
+- Add Haiku to configure for proper LDSHARED settings
+- Add Bazel targets
+- Complete rewrite of CMake build [Vollstrecker]
+- Clarify the use of errnum in gzerror()
+- Note that gzseek() requests are deferred until the next operation
+- Note the use of gzungetc() to run a deferred seek while reading
+- Fix bug in inflatePrime() for 16-bit ints
+- Add a "G" option to force gzip, disabling transparency in gzread()
+- Improve the discrimination between trailing garbage and bad gzip
+- Allow gzflush() to write empty gzip members
+- Remove redundant frees of point list on error in examples/zran.c
+- Clarify the use of inflateGetHeader()
+- Update links to the RFCs
+- Return all available uncompressed data on error in gzread.c
+- Support non-blocking devices in the gz* routines
+- Various other small improvements
+
 Changes in 1.3.1 (22 Jan 2024)
 - Reject overflows of zip header fields in minizip
 - Fix bug in inflateSync() for data held in bit buffer
diff --git a/src/java.base/share/native/libzip/zlib/README b/src/java.base/share/native/libzip/zlib/README
index c5f917540b6..2b1e6f36fe3 100644
--- a/src/java.base/share/native/libzip/zlib/README
+++ b/src/java.base/share/native/libzip/zlib/README
@@ -1,10 +1,10 @@
 ZLIB DATA COMPRESSION LIBRARY
 
-zlib 1.3.1 is a general purpose data compression library.  All the code is
-thread safe.  The data format used by the zlib library is described by RFCs
-(Request for Comments) 1950 to 1952 in the files
-http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
-rfc1952 (gzip format).
+zlib 1.3.2 is a general purpose data compression library.  All the code is
+thread safe (though see the FAQ for caveats).  The data format used by the zlib
+library is described by RFCs (Request for Comments) 1950 to 1952 at
+https://datatracker.ietf.org/doc/html/rfc1950 (zlib format), rfc1951 (deflate
+format) and rfc1952 (gzip format).
 
 All functions of the compression library are documented in the file zlib.h
 (volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
@@ -21,17 +21,17 @@ make_vms.com.
 
 Questions about zlib should be sent to , or to Gilles Vollant
  for the Windows DLL version.  The zlib home page is
-http://zlib.net/ .  Before reporting a problem, please check this site to
+https://zlib.net/ .  Before reporting a problem, please check this site to
 verify that you have the latest version of zlib; otherwise get the latest
 version and check whether the problem still exists or not.
 
-PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
+PLEASE read the zlib FAQ https://zlib.net/zlib_faq.html before asking for help.
 
 Mark Nelson  wrote an article about zlib for the Jan.  1997
 issue of Dr.  Dobb's Journal; a copy of the article is available at
-https://marknelson.us/posts/1997/01/01/zlib-engine.html .
+https://zlib.net/nelson/ .
 
-The changes made in version 1.3.1 are documented in the file ChangeLog.
+The changes made in version 1.3.2 are documented in the file ChangeLog.
 
 Unsupported third party contributions are provided in directory contrib/ .
 
@@ -43,9 +43,9 @@ can be found at https://github.com/pmqs/IO-Compress .
 
 A Python interface to zlib written by A.M. Kuchling  is
 available in Python 1.5 and later versions, see
-http://docs.python.org/library/zlib.html .
+https://docs.python.org/3/library/zlib.html .
 
-zlib is built into tcl: http://wiki.tcl.tk/4610 .
+zlib is built into tcl: https://wiki.tcl-lang.org/page/zlib .
 
 An experimental package to read and write files in .zip format, written on top
 of zlib by Gilles Vollant , is available in the
@@ -69,9 +69,7 @@ Notes for some targets:
 - zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
   other compilers. Use "make test" to check your compiler.
 
-- gzdopen is not supported on RISCOS or BEOS.
-
-- For PalmOs, see http://palmzlib.sourceforge.net/
+- For PalmOs, see https://palmzlib.sourceforge.net/
 
 
 Acknowledgments:
@@ -83,7 +81,7 @@ Acknowledgments:
 
 Copyright notice:
 
- (C) 1995-2024 Jean-loup Gailly and Mark Adler
+ (C) 1995-2026 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/java.base/share/native/libzip/zlib/compress.c b/src/java.base/share/native/libzip/zlib/compress.c
index d7421379673..54346ad2a2f 100644
--- a/src/java.base/share/native/libzip/zlib/compress.c
+++ b/src/java.base/share/native/libzip/zlib/compress.c
@@ -23,7 +23,7 @@
  */
 
 /* compress.c -- compress a memory buffer
- * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler
+ * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -42,13 +42,19 @@
      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
    Z_STREAM_ERROR if the level parameter is invalid.
+
+     The _z versions of the functions take size_t length arguments.
 */
-int ZEXPORT compress2(Bytef *dest, uLongf *destLen, const Bytef *source,
-                      uLong sourceLen, int level) {
+int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
+                        z_size_t sourceLen, int level) {
     z_stream stream;
     int err;
     const uInt max = (uInt)-1;
-    uLong left;
+    z_size_t left;
+
+    if ((sourceLen > 0 && source == NULL) ||
+        destLen == NULL || (*destLen > 0 && dest == NULL))
+        return Z_STREAM_ERROR;
 
     left = *destLen;
     *destLen = 0;
@@ -67,23 +73,36 @@ int ZEXPORT compress2(Bytef *dest, uLongf *destLen, const Bytef *source,
 
     do {
         if (stream.avail_out == 0) {
-            stream.avail_out = left > (uLong)max ? max : (uInt)left;
+            stream.avail_out = left > (z_size_t)max ? max : (uInt)left;
             left -= stream.avail_out;
         }
         if (stream.avail_in == 0) {
-            stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
+            stream.avail_in = sourceLen > (z_size_t)max ? max :
+                                                          (uInt)sourceLen;
             sourceLen -= stream.avail_in;
         }
         err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
     } while (err == Z_OK);
 
-    *destLen = stream.total_out;
+    *destLen = (z_size_t)(stream.next_out - dest);
     deflateEnd(&stream);
     return err == Z_STREAM_END ? Z_OK : err;
 }
-
+int ZEXPORT compress2(Bytef *dest, uLongf *destLen, const Bytef *source,
+                      uLong sourceLen, int level) {
+    int ret;
+    z_size_t got = *destLen;
+    ret = compress2_z(dest, &got, source, sourceLen, level);
+    *destLen = (uLong)got;
+    return ret;
+}
 /* ===========================================================================
  */
+int ZEXPORT compress_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
+                       z_size_t sourceLen) {
+    return compress2_z(dest, destLen, source, sourceLen,
+                       Z_DEFAULT_COMPRESSION);
+}
 int ZEXPORT compress(Bytef *dest, uLongf *destLen, const Bytef *source,
                      uLong sourceLen) {
     return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
@@ -93,7 +112,12 @@ int ZEXPORT compress(Bytef *dest, uLongf *destLen, const Bytef *source,
      If the default memLevel or windowBits for deflateInit() is changed, then
    this function needs to be updated.
  */
-uLong ZEXPORT compressBound(uLong sourceLen) {
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
-           (sourceLen >> 25) + 13;
+z_size_t ZEXPORT compressBound_z(z_size_t sourceLen) {
+    z_size_t bound = sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+                     (sourceLen >> 25) + 13;
+    return bound < sourceLen ? (z_size_t)-1 : bound;
+}
+uLong ZEXPORT compressBound(uLong sourceLen) {
+    z_size_t bound = compressBound_z(sourceLen);
+    return (uLong)bound != bound ? (uLong)-1 : (uLong)bound;
 }
diff --git a/src/java.base/share/native/libzip/zlib/deflate.c b/src/java.base/share/native/libzip/zlib/deflate.c
index 57fc6802bb8..0ec56ec5691 100644
--- a/src/java.base/share/native/libzip/zlib/deflate.c
+++ b/src/java.base/share/native/libzip/zlib/deflate.c
@@ -23,7 +23,7 @@
  */
 
 /* deflate.c -- compress data using the deflation algorithm
- * Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
+ * Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -61,7 +61,7 @@
  *  REFERENCES
  *
  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
- *      Available in http://tools.ietf.org/html/rfc1951
+ *      Available at https://datatracker.ietf.org/doc/html/rfc1951
  *
  *      A description of the Rabin and Karp algorithm is given in the book
  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
@@ -76,7 +76,7 @@
 #include "deflate.h"
 
 const char deflate_copyright[] =
-   " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler ";
+   " deflate 1.3.2 Copyright 1995-2026 Jean-loup Gailly and Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -194,8 +194,8 @@ local const config configuration_table[10] = {
 #define CLEAR_HASH(s) \
     do { \
         s->head[s->hash_size - 1] = NIL; \
-        zmemzero((Bytef *)s->head, \
-                 (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
+        zmemzero(s->head, (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
+        s->slid = 0; \
     } while (0)
 
 /* ===========================================================================
@@ -219,8 +219,8 @@ local void slide_hash(deflate_state *s) {
         m = *--p;
         *p = (Pos)(m >= wsize ? m - wsize : NIL);
     } while (--n);
-    n = wsize;
 #ifndef FASTEST
+    n = wsize;
     p = &s->prev[n];
     do {
         m = *--p;
@@ -230,6 +230,7 @@ local void slide_hash(deflate_state *s) {
          */
     } while (--n);
 #endif
+    s->slid = 1;
 }
 
 /* ===========================================================================
@@ -283,7 +284,14 @@ local void fill_window(deflate_state *s) {
         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
 
         /* Deal with !@#$% 64K limit: */
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable: 4127)
+#endif
         if (sizeof(int) <= 2) {
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
                 more = wsize;
 
@@ -455,6 +463,7 @@ int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
     if (s == Z_NULL) return Z_MEM_ERROR;
+    zmemzero(s, sizeof(deflate_state));
     strm->state = (struct internal_state FAR *)s;
     s->strm = strm;
     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
@@ -736,10 +745,23 @@ int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) {
 /* ========================================================================= */
 int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) {
     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
-    if (pending != Z_NULL)
-        *pending = strm->state->pending;
     if (bits != Z_NULL)
         *bits = strm->state->bi_valid;
+    if (pending != Z_NULL) {
+        *pending = (unsigned)strm->state->pending;
+        if (*pending != strm->state->pending) {
+            *pending = (unsigned)-1;
+            return Z_BUF_ERROR;
+        }
+    }
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateUsed(z_streamp strm, int *bits) {
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+    if (bits != Z_NULL)
+        *bits = strm->state->bi_used;
     return Z_OK;
 }
 
@@ -855,28 +877,34 @@ int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy,
  *
  * Shifts are used to approximate divisions, for speed.
  */
-uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {
+z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen) {
     deflate_state *s;
-    uLong fixedlen, storelen, wraplen;
+    z_size_t fixedlen, storelen, wraplen, bound;
 
     /* upper bound for fixed blocks with 9-bit literals and length 255
        (memLevel == 2, which is the lowest that may not use stored blocks) --
        ~13% overhead plus a small constant */
     fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +
                (sourceLen >> 9) + 4;
+    if (fixedlen < sourceLen)
+        fixedlen = (z_size_t)-1;
 
     /* upper bound for stored blocks with length 127 (memLevel == 1) --
        ~4% overhead plus a small constant */
     storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +
                (sourceLen >> 11) + 7;
+    if (storelen < sourceLen)
+        storelen = (z_size_t)-1;
 
-    /* if can't get parameters, return larger bound plus a zlib wrapper */
-    if (deflateStateCheck(strm))
-        return (fixedlen > storelen ? fixedlen : storelen) + 6;
+    /* if can't get parameters, return larger bound plus a wrapper */
+    if (deflateStateCheck(strm)) {
+        bound = fixedlen > storelen ? fixedlen : storelen;
+        return bound + 18 < bound ? (z_size_t)-1 : bound + 18;
+    }
 
     /* compute wrapper length */
     s = strm->state;
-    switch (s->wrap) {
+    switch (s->wrap < 0 ? -s->wrap : s->wrap) {
     case 0:                                 /* raw deflate */
         wraplen = 0;
         break;
@@ -906,18 +934,25 @@ uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {
         break;
 #endif
     default:                                /* for compiler happiness */
-        wraplen = 6;
+        wraplen = 18;
     }
 
     /* if not default parameters, return one of the conservative bounds */
-    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
-        return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) +
-               wraplen;
+    if (s->w_bits != 15 || s->hash_bits != 8 + 7) {
+        bound = s->w_bits <= s->hash_bits && s->level ? fixedlen :
+                                                        storelen;
+        return bound + wraplen < bound ? (z_size_t)-1 : bound + wraplen;
+    }
 
     /* default settings: return tight bound for that case -- ~0.03% overhead
        plus a small constant */
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
-           (sourceLen >> 25) + 13 - 6 + wraplen;
+    bound = sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+            (sourceLen >> 25) + 13 - 6 + wraplen;
+    return bound < sourceLen ? (z_size_t)-1 : bound;
+}
+uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {
+    z_size_t bound = deflateBound_z(strm, sourceLen);
+    return (uLong)bound != bound ? (uLong)-1 : (uLong)bound;
 }
 
 /* =========================================================================
@@ -941,8 +976,8 @@ local void flush_pending(z_streamp strm) {
     deflate_state *s = strm->state;
 
     _tr_flush_bits(s);
-    len = s->pending;
-    if (len > strm->avail_out) len = strm->avail_out;
+    len = s->pending > strm->avail_out ? strm->avail_out :
+                                         (unsigned)s->pending;
     if (len == 0) return;
 
     zmemcpy(strm->next_out, s->pending_out, len);
@@ -962,8 +997,8 @@ local void flush_pending(z_streamp strm) {
 #define HCRC_UPDATE(beg) \
     do { \
         if (s->gzhead->hcrc && s->pending > (beg)) \
-            strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
-                                s->pending - (beg)); \
+            strm->adler = crc32_z(strm->adler, s->pending_buf + (beg), \
+                                  s->pending - (beg)); \
     } while (0)
 
 /* ========================================================================= */
@@ -1097,8 +1132,8 @@ int ZEXPORT deflate(z_streamp strm, int flush) {
                 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
             }
             if (s->gzhead->hcrc)
-                strm->adler = crc32(strm->adler, s->pending_buf,
-                                    s->pending);
+                strm->adler = crc32_z(strm->adler, s->pending_buf,
+                                      s->pending);
             s->gzindex = 0;
             s->status = EXTRA_STATE;
         }
@@ -1106,9 +1141,9 @@ int ZEXPORT deflate(z_streamp strm, int flush) {
     if (s->status == EXTRA_STATE) {
         if (s->gzhead->extra != Z_NULL) {
             ulg beg = s->pending;   /* start of bytes to update crc */
-            uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
+            ulg left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
             while (s->pending + left > s->pending_buf_size) {
-                uInt copy = s->pending_buf_size - s->pending;
+                ulg copy = s->pending_buf_size - s->pending;
                 zmemcpy(s->pending_buf + s->pending,
                         s->gzhead->extra + s->gzindex, copy);
                 s->pending = s->pending_buf_size;
@@ -1319,12 +1354,13 @@ int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {
 
     ss = source->state;
 
-    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+    zmemcpy(dest, source, sizeof(z_stream));
 
     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
     if (ds == Z_NULL) return Z_MEM_ERROR;
+    zmemzero(ds, sizeof(deflate_state));
     dest->state = (struct internal_state FAR *) ds;
-    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
+    zmemcpy(ds, ss, sizeof(deflate_state));
     ds->strm = dest;
 
     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
@@ -1337,18 +1373,23 @@ int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {
         deflateEnd (dest);
         return Z_MEM_ERROR;
     }
-    /* following zmemcpy do not work for 16-bit MSDOS */
-    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
-    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
-    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
-    zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);
+    /* following zmemcpy's do not work for 16-bit MSDOS */
+    zmemcpy(ds->window, ss->window, ss->high_water);
+    zmemcpy(ds->prev, ss->prev,
+            (ss->slid || ss->strstart - ss->insert > ds->w_size ? ds->w_size :
+                ss->strstart - ss->insert) * sizeof(Pos));
+    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
 
     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
+    zmemcpy(ds->pending_out, ss->pending_out, ss->pending);
 #ifdef LIT_MEM
     ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1));
     ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);
+    zmemcpy(ds->d_buf, ss->d_buf, ss->sym_next * sizeof(ush));
+    zmemcpy(ds->l_buf, ss->l_buf, ss->sym_next);
 #else
     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
+    zmemcpy(ds->sym_buf, ss->sym_buf, ss->sym_next);
 #endif
 
     ds->l_desc.dyn_tree = ds->dyn_ltree;
@@ -1371,9 +1412,9 @@ int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {
  */
 local uInt longest_match(deflate_state *s, IPos cur_match) {
     unsigned chain_length = s->max_chain_length;/* max hash chain length */
-    register Bytef *scan = s->window + s->strstart; /* current string */
-    register Bytef *match;                      /* matched string */
-    register int len;                           /* length of current match */
+    Bytef *scan = s->window + s->strstart;      /* current string */
+    Bytef *match;                               /* matched string */
+    int len;                                    /* length of current match */
     int best_len = (int)s->prev_length;         /* best match length so far */
     int nice_match = s->nice_match;             /* stop if match long enough */
     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
@@ -1388,13 +1429,13 @@ local uInt longest_match(deflate_state *s, IPos cur_match) {
     /* Compare two bytes at a time. Note: this is not always beneficial.
      * Try with and without -DUNALIGNED_OK to check.
      */
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
-    register ush scan_start = *(ushf*)scan;
-    register ush scan_end   = *(ushf*)(scan + best_len - 1);
+    Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
+    ush scan_start = *(ushf*)scan;
+    ush scan_end   = *(ushf*)(scan + best_len - 1);
 #else
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
-    register Byte scan_end1  = scan[best_len - 1];
-    register Byte scan_end   = scan[best_len];
+    Bytef *strend = s->window + s->strstart + MAX_MATCH;
+    Byte scan_end1  = scan[best_len - 1];
+    Byte scan_end   = scan[best_len];
 #endif
 
     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
@@ -1518,10 +1559,10 @@ local uInt longest_match(deflate_state *s, IPos cur_match) {
  * Optimized version for FASTEST only
  */
 local uInt longest_match(deflate_state *s, IPos cur_match) {
-    register Bytef *scan = s->window + s->strstart; /* current string */
-    register Bytef *match;                       /* matched string */
-    register int len;                           /* length of current match */
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+    Bytef *scan = s->window + s->strstart;      /* current string */
+    Bytef *match;                               /* matched string */
+    int len;                                    /* length of current match */
+    Bytef *strend = s->window + s->strstart + MAX_MATCH;
 
     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
      * It is easy to get rid of this optimization if necessary.
@@ -1581,7 +1622,7 @@ local uInt longest_match(deflate_state *s, IPos cur_match) {
 local void check_match(deflate_state *s, IPos start, IPos match, int length) {
     /* check that the match is indeed a match */
     Bytef *back = s->window + (int)match, *here = s->window + start;
-    IPos len = length;
+    IPos len = (IPos)length;
     if (match == (IPos)-1) {
         /* match starts one byte before the current window -- just compare the
            subsequent length-1 bytes */
@@ -1653,13 +1694,14 @@ local block_state deflate_stored(deflate_state *s, int flush) {
      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
      * large input and output buffers, the stored block size will be larger.
      */
-    unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
+    unsigned min_block = (unsigned)(MIN(s->pending_buf_size - 5, s->w_size));
 
     /* Copy as many min_block or larger stored blocks directly to next_out as
      * possible. If flushing, copy the remaining available input to next_out as
      * stored blocks, if there is enough space.
      */
-    unsigned len, left, have, last = 0;
+    int last = 0;
+    unsigned len, left, have;
     unsigned used = s->strm->avail_in;
     do {
         /* Set len to the maximum size block that we can copy directly with the
@@ -1667,12 +1709,12 @@ local block_state deflate_stored(deflate_state *s, int flush) {
          * would be copied from what's left in the window.
          */
         len = MAX_STORED;       /* maximum deflate stored block length */
-        have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
+        have = ((unsigned)s->bi_valid + 42) >> 3;   /* bytes in header */
         if (s->strm->avail_out < have)          /* need room for header */
             break;
             /* maximum stored block length that will fit in avail_out: */
         have = s->strm->avail_out - have;
-        left = s->strstart - s->block_start;    /* bytes left in window */
+        left = (unsigned)(s->strstart - s->block_start);    /* window bytes */
         if (len > (ulg)left + s->strm->avail_in)
             len = left + s->strm->avail_in;     /* limit len to the input */
         if (len > have)
@@ -1695,10 +1737,10 @@ local block_state deflate_stored(deflate_state *s, int flush) {
         _tr_stored_block(s, (char *)0, 0L, last);
 
         /* Replace the lengths in the dummy stored block with len. */
-        s->pending_buf[s->pending - 4] = len;
-        s->pending_buf[s->pending - 3] = len >> 8;
-        s->pending_buf[s->pending - 2] = ~len;
-        s->pending_buf[s->pending - 1] = ~len >> 8;
+        s->pending_buf[s->pending - 4] = (Bytef)len;
+        s->pending_buf[s->pending - 3] = (Bytef)(len >> 8);
+        s->pending_buf[s->pending - 2] = (Bytef)~len;
+        s->pending_buf[s->pending - 1] = (Bytef)(~len >> 8);
 
         /* Write the stored block header bytes. */
         flush_pending(s->strm);
@@ -1769,8 +1811,10 @@ local block_state deflate_stored(deflate_state *s, int flush) {
         s->high_water = s->strstart;
 
     /* If the last block was written to next_out, then done. */
-    if (last)
+    if (last) {
+        s->bi_used = 8;
         return finish_done;
+    }
 
     /* If flushing and all input has been consumed, then done. */
     if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
@@ -1778,7 +1822,7 @@ local block_state deflate_stored(deflate_state *s, int flush) {
         return block_done;
 
     /* Fill the window with any remaining input. */
-    have = s->window_size - s->strstart;
+    have = (unsigned)(s->window_size - s->strstart);
     if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
         /* Slide the window down. */
         s->block_start -= s->w_size;
@@ -1805,11 +1849,11 @@ local block_state deflate_stored(deflate_state *s, int flush) {
      * have enough input for a worthy block, or if flushing and there is enough
      * room for the remaining input as a stored block in the pending buffer.
      */
-    have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
+    have = ((unsigned)s->bi_valid + 42) >> 3;   /* bytes in header */
         /* maximum stored block length that will fit in pending: */
-    have = MIN(s->pending_buf_size - have, MAX_STORED);
+    have = (unsigned)MIN(s->pending_buf_size - have, MAX_STORED);
     min_block = MIN(have, s->w_size);
-    left = s->strstart - s->block_start;
+    left = (unsigned)(s->strstart - s->block_start);
     if (left >= min_block ||
         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
          s->strm->avail_in == 0 && left <= have)) {
@@ -1822,6 +1866,8 @@ local block_state deflate_stored(deflate_state *s, int flush) {
     }
 
     /* We've done all we can with the available input and output. */
+    if (last)
+        s->bi_used = 8;
     return last ? finish_started : need_more;
 }
 
@@ -1870,7 +1916,7 @@ local block_state deflate_fast(deflate_state *s, int flush) {
             /* longest_match() sets match_start */
         }
         if (s->match_length >= MIN_MATCH) {
-            check_match(s, s->strstart, s->match_start, s->match_length);
+            check_match(s, s->strstart, s->match_start, (int)s->match_length);
 
             _tr_tally_dist(s, s->strstart - s->match_start,
                            s->match_length - MIN_MATCH, bflush);
@@ -1992,7 +2038,7 @@ local block_state deflate_slow(deflate_state *s, int flush) {
             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
             /* Do not insert strings in hash table beyond this. */
 
-            check_match(s, s->strstart - 1, s->prev_match, s->prev_length);
+            check_match(s, s->strstart - 1, s->prev_match, (int)s->prev_length);
 
             _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
                            s->prev_length - MIN_MATCH, bflush);
@@ -2100,7 +2146,7 @@ local block_state deflate_rle(deflate_state *s, int flush) {
 
         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
         if (s->match_length >= MIN_MATCH) {
-            check_match(s, s->strstart, s->strstart - 1, s->match_length);
+            check_match(s, s->strstart, s->strstart - 1, (int)s->match_length);
 
             _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
 
diff --git a/src/java.base/share/native/libzip/zlib/deflate.h b/src/java.base/share/native/libzip/zlib/deflate.h
index 830d46b8894..5b6246ee3c4 100644
--- a/src/java.base/share/native/libzip/zlib/deflate.h
+++ b/src/java.base/share/native/libzip/zlib/deflate.h
@@ -23,7 +23,7 @@
  */
 
 /* deflate.h -- internal compression state
- * Copyright (C) 1995-2024 Jean-loup Gailly
+ * Copyright (C) 1995-2026 Jean-loup Gailly
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -295,6 +295,9 @@ typedef struct internal_state {
     /* Number of valid bits in bi_buf.  All bits above the last valid bit
      * are always zero.
      */
+    int bi_used;
+    /* Last number of used bits when going to a byte boundary.
+     */
 
     ulg high_water;
     /* High water mark offset in window for initialized bytes -- bytes above
@@ -303,6 +306,9 @@ typedef struct internal_state {
      * updated to the new high water mark.
      */
 
+    int slid;
+    /* True if the hash table has been slid since it was cleared. */
+
 } FAR deflate_state;
 
 /* Output a byte on the stream.
diff --git a/src/java.base/share/native/libzip/zlib/gzguts.h b/src/java.base/share/native/libzip/zlib/gzguts.h
index 8cce2c69d24..0be646016ed 100644
--- a/src/java.base/share/native/libzip/zlib/gzguts.h
+++ b/src/java.base/share/native/libzip/zlib/gzguts.h
@@ -23,7 +23,7 @@
  */
 
 /* gzguts.h -- zlib internal header definitions for gz* operations
- * Copyright (C) 2004-2024 Mark Adler
+ * Copyright (C) 2004-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -41,6 +41,18 @@
 #  define ZLIB_INTERNAL
 #endif
 
+#if defined(_WIN32)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
+#  ifndef _CRT_SECURE_NO_WARNINGS
+#    define _CRT_SECURE_NO_WARNINGS
+#  endif
+#  ifndef _CRT_NONSTDC_NO_DEPRECATE
+#    define _CRT_NONSTDC_NO_DEPRECATE
+#  endif
+#endif
+
 #include 
 #include "zlib.h"
 #ifdef STDC
@@ -49,8 +61,8 @@
 #  include 
 #endif
 
-#ifndef _POSIX_SOURCE
-#  define _POSIX_SOURCE
+#ifndef _POSIX_C_SOURCE
+#  define _POSIX_C_SOURCE 200112L
 #endif
 #include 
 
@@ -60,19 +72,13 @@
 
 #if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
 #  include 
+#  include 
 #endif
 
-#if defined(_WIN32)
+#if defined(_WIN32) && !defined(WIDECHAR)
 #  define WIDECHAR
 #endif
 
-#ifdef WINAPI_FAMILY
-#  define open _open
-#  define read _read
-#  define write _write
-#  define close _close
-#endif
-
 #ifdef NO_DEFLATE       /* for compatibility with old definition */
 #  define NO_GZCOMPRESS
 #endif
@@ -96,33 +102,28 @@
 #endif
 
 #ifndef HAVE_VSNPRINTF
-#  ifdef MSDOS
+#  if !defined(NO_vsnprintf) && \
+      (defined(MSDOS) || defined(__TURBOC__) || defined(__SASC) || \
+       defined(VMS) || defined(__OS400) || defined(__MVS__))
 /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
    but for now we just assume it doesn't. */
 #    define NO_vsnprintf
 #  endif
-#  ifdef __TURBOC__
-#    define NO_vsnprintf
-#  endif
 #  ifdef WIN32
 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
-#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
-#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
-#         define vsnprintf _vsnprintf
+#    if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#      ifndef vsnprintf
+#        define vsnprintf _vsnprintf
 #      endif
 #    endif
-#  endif
-#  ifdef __SASC
-#    define NO_vsnprintf
-#  endif
-#  ifdef VMS
-#    define NO_vsnprintf
-#  endif
-#  ifdef __OS400__
-#    define NO_vsnprintf
-#  endif
-#  ifdef __MVS__
-#    define NO_vsnprintf
+#  elif !defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L
+/* Otherwise if C89/90, assume no C99 snprintf() or vsnprintf() */
+#    ifndef NO_snprintf
+#      define NO_snprintf
+#    endif
+#    ifndef NO_vsnprintf
+#      define NO_vsnprintf
+#    endif
 #  endif
 #endif
 
@@ -206,7 +207,9 @@ typedef struct {
     unsigned char *out;     /* output buffer (double-sized when reading) */
     int direct;             /* 0 if processing gzip, 1 if transparent */
         /* just for reading */
+    int junk;               /* -1 = start, 1 = junk candidate, 0 = in gzip */
     int how;                /* 0: get header, 1: copy, 2: decompress */
+    int again;              /* true if EAGAIN or EWOULDBLOCK on last i/o */
     z_off64_t start;        /* where the gzip data started, for rewinding */
     int eof;                /* true if end of input file reached */
     int past;               /* true if read requested past end */
@@ -216,7 +219,6 @@ typedef struct {
     int reset;              /* true if a reset is pending after a Z_FINISH */
         /* seek request */
     z_off64_t skip;         /* amount to skip (already rewound if backwards) */
-    int seek;               /* true if seek request pending */
         /* error information */
     int err;                /* error code */
     char *msg;              /* error message */
diff --git a/src/java.base/share/native/libzip/zlib/gzlib.c b/src/java.base/share/native/libzip/zlib/gzlib.c
index 0f4dfae64a0..9489bcc1f12 100644
--- a/src/java.base/share/native/libzip/zlib/gzlib.c
+++ b/src/java.base/share/native/libzip/zlib/gzlib.c
@@ -23,21 +23,21 @@
  */
 
 /* gzlib.c -- zlib functions common to reading and writing gzip files
- * Copyright (C) 2004-2024 Mark Adler
+ * Copyright (C) 2004-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
 #include "gzguts.h"
 
-#if defined(_WIN32) && !defined(__BORLANDC__)
+#if defined(__DJGPP__)
+#  define LSEEK llseek
+#elif defined(_WIN32) && !defined(__BORLANDC__) && !defined(UNDER_CE)
 #  define LSEEK _lseeki64
-#else
-#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#elif defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
 #  define LSEEK lseek64
 #else
 #  define LSEEK lseek
 #endif
-#endif
 
 #if defined UNDER_CE
 
@@ -76,7 +76,7 @@ char ZLIB_INTERNAL *gz_strwinerror(DWORD error) {
             msgbuf[chars] = 0;
         }
 
-        wcstombs(buf, msgbuf, chars + 1);
+        wcstombs(buf, msgbuf, chars + 1);       /* assumes buf is big enough */
         LocalFree(msgbuf);
     }
     else {
@@ -96,10 +96,12 @@ local void gz_reset(gz_statep state) {
         state->eof = 0;             /* not at end of file */
         state->past = 0;            /* have not read past end yet */
         state->how = LOOK;          /* look for gzip header */
+        state->junk = -1;           /* mark first member */
     }
     else                            /* for writing ... */
         state->reset = 0;           /* no deflateReset pending */
-    state->seek = 0;                /* no seek request pending */
+    state->again = 0;               /* no stalled i/o yet */
+    state->skip = 0;                /* no seek request pending */
     gz_error(state, Z_OK, NULL);    /* clear error */
     state->x.pos = 0;               /* no uncompressed data yet */
     state->strm.avail_in = 0;       /* no input data yet */
@@ -109,16 +111,13 @@ local void gz_reset(gz_statep state) {
 local gzFile gz_open(const void *path, int fd, const char *mode) {
     gz_statep state;
     z_size_t len;
-    int oflag;
-#ifdef O_CLOEXEC
-    int cloexec = 0;
-#endif
+    int oflag = 0;
 #ifdef O_EXCL
     int exclusive = 0;
 #endif
 
     /* check input */
-    if (path == NULL)
+    if (path == NULL || mode == NULL)
         return NULL;
 
     /* allocate gzFile structure to return */
@@ -127,6 +126,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
         return NULL;
     state->size = 0;            /* no buffers allocated yet */
     state->want = GZBUFSIZE;    /* requested buffer size */
+    state->err = Z_OK;          /* no error yet */
     state->msg = NULL;          /* no error message yet */
 
     /* interpret mode */
@@ -157,7 +157,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
                 break;
 #ifdef O_CLOEXEC
             case 'e':
-                cloexec = 1;
+                oflag |= O_CLOEXEC;
                 break;
 #endif
 #ifdef O_EXCL
@@ -177,6 +177,14 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
             case 'F':
                 state->strategy = Z_FIXED;
                 break;
+            case 'G':
+                state->direct = -1;
+                break;
+#ifdef O_NONBLOCK
+            case 'N':
+                oflag |= O_NONBLOCK;
+                break;
+#endif
             case 'T':
                 state->direct = 1;
                 break;
@@ -192,22 +200,30 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
         return NULL;
     }
 
-    /* can't force transparent read */
+    /* direct is 0, 1 if "T", or -1 if "G" (last "G" or "T" wins) */
     if (state->mode == GZ_READ) {
-        if (state->direct) {
+        if (state->direct == 1) {
+            /* can't force a transparent read */
             free(state);
             return NULL;
         }
-        state->direct = 1;      /* for empty file */
+        if (state->direct == 0)
+            /* default when reading is auto-detect of gzip vs. transparent --
+               start with a transparent assumption in case of an empty file */
+            state->direct = 1;
     }
+    else if (state->direct == -1) {
+        /* "G" has no meaning when writing -- disallow it */
+        free(state);
+        return NULL;
+    }
+    /* if reading, direct == 1 for auto-detect, -1 for gzip only; if writing or
+       appending, direct == 0 for gzip, 1 for transparent (copy in to out) */
 
     /* save the path name for error messages */
 #ifdef WIDECHAR
-    if (fd == -2) {
+    if (fd == -2)
         len = wcstombs(NULL, path, 0);
-        if (len == (z_size_t)-1)
-            len = 0;
-    }
     else
 #endif
         len = strlen((const char *)path);
@@ -217,29 +233,29 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
         return NULL;
     }
 #ifdef WIDECHAR
-    if (fd == -2)
+    if (fd == -2) {
         if (len)
             wcstombs(state->path, path, len + 1);
         else
             *(state->path) = 0;
+    }
     else
 #endif
+    {
 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
         (void)snprintf(state->path, len + 1, "%s", (const char *)path);
 #else
         strcpy(state->path, path);
 #endif
+    }
 
     /* compute the flags for open() */
-    oflag =
+    oflag |=
 #ifdef O_LARGEFILE
         O_LARGEFILE |
 #endif
 #ifdef O_BINARY
         O_BINARY |
-#endif
-#ifdef O_CLOEXEC
-        (cloexec ? O_CLOEXEC : 0) |
 #endif
         (state->mode == GZ_READ ?
          O_RDONLY :
@@ -252,11 +268,23 @@ local gzFile gz_open(const void *path, int fd, const char *mode) {
            O_APPEND)));
 
     /* open the file with the appropriate flags (or just use fd) */
-    state->fd = fd > -1 ? fd : (
+    if (fd == -1)
+        state->fd = open((const char *)path, oflag, 0666);
 #ifdef WIDECHAR
-        fd == -2 ? _wopen(path, oflag, 0666) :
+    else if (fd == -2)
+        state->fd = _wopen(path, oflag, _S_IREAD | _S_IWRITE);
 #endif
-        open((const char *)path, oflag, 0666));
+    else {
+#ifdef O_NONBLOCK
+        if (oflag & O_NONBLOCK)
+            fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
+#endif
+#ifdef O_CLOEXEC
+        if (oflag & O_CLOEXEC)
+            fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | O_CLOEXEC);
+#endif
+        state->fd = fd;
+    }
     if (state->fd == -1) {
         free(state->path);
         free(state);
@@ -383,9 +411,10 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
     /* normalize offset to a SEEK_CUR specification */
     if (whence == SEEK_SET)
         offset -= state->x.pos;
-    else if (state->seek)
-        offset += state->skip;
-    state->seek = 0;
+    else {
+        offset += state->past ? 0 : state->skip;
+        state->skip = 0;
+    }
 
     /* if within raw area while reading, just go there */
     if (state->mode == GZ_READ && state->how == COPY &&
@@ -396,7 +425,7 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
         state->x.have = 0;
         state->eof = 0;
         state->past = 0;
-        state->seek = 0;
+        state->skip = 0;
         gz_error(state, Z_OK, NULL);
         state->strm.avail_in = 0;
         state->x.pos += offset;
@@ -425,10 +454,7 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
     }
 
     /* request skip (if not zero) */
-    if (offset) {
-        state->seek = 1;
-        state->skip = offset;
-    }
+    state->skip = offset;
     return state->x.pos + offset;
 }
 
@@ -452,7 +478,7 @@ z_off64_t ZEXPORT gztell64(gzFile file) {
         return -1;
 
     /* return position */
-    return state->x.pos + (state->seek ? state->skip : 0);
+    return state->x.pos + (state->past ? 0 : state->skip);
 }
 
 /* -- see zlib.h -- */
@@ -559,7 +585,7 @@ void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) {
     }
 
     /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
-    if (err != Z_OK && err != Z_BUF_ERROR)
+    if (err != Z_OK && err != Z_BUF_ERROR && !state->again)
         state->x.have = 0;
 
     /* set error code, and if no message, then done */
@@ -596,6 +622,7 @@ unsigned ZLIB_INTERNAL gz_intmax(void) {
     return INT_MAX;
 #else
     unsigned p = 1, q;
+
     do {
         q = p;
         p <<= 1;
diff --git a/src/java.base/share/native/libzip/zlib/gzread.c b/src/java.base/share/native/libzip/zlib/gzread.c
index 7b9c9df5fa1..89144d2e56f 100644
--- a/src/java.base/share/native/libzip/zlib/gzread.c
+++ b/src/java.base/share/native/libzip/zlib/gzread.c
@@ -23,7 +23,7 @@
  */
 
 /* gzread.c -- zlib functions for reading gzip files
- * Copyright (C) 2004-2017 Mark Adler
+ * Copyright (C) 2004-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -32,23 +32,36 @@
 /* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
    state->fd, and update state->eof, state->err, and state->msg as appropriate.
    This function needs to loop on read(), since read() is not guaranteed to
-   read the number of bytes requested, depending on the type of descriptor. */
+   read the number of bytes requested, depending on the type of descriptor. It
+   also needs to loop to manage the fact that read() returns an int. If the
+   descriptor is non-blocking and read() returns with no data in order to avoid
+   blocking, then gz_load() will return 0 if some data has been read, or -1 if
+   no data has been read. Either way, state->again is set true to indicate a
+   non-blocking event. If errno is non-zero on return, then there was an error
+   signaled from read().  *have is set to the number of bytes read. */
 local int gz_load(gz_statep state, unsigned char *buf, unsigned len,
                   unsigned *have) {
     int ret;
     unsigned get, max = ((unsigned)-1 >> 2) + 1;
 
+    state->again = 0;
+    errno = 0;
     *have = 0;
     do {
         get = len - *have;
         if (get > max)
             get = max;
-        ret = read(state->fd, buf + *have, get);
+        ret = (int)read(state->fd, buf + *have, get);
         if (ret <= 0)
             break;
         *have += (unsigned)ret;
     } while (*have < len);
     if (ret < 0) {
+        if (errno == EAGAIN || errno == EWOULDBLOCK) {
+            state->again = 1;
+            if (*have != 0)
+                return 0;
+        }
         gz_error(state, Z_ERRNO, zstrerror());
         return -1;
     }
@@ -74,10 +87,14 @@ local int gz_avail(gz_statep state) {
         if (strm->avail_in) {       /* copy what's there to the start */
             unsigned char *p = state->in;
             unsigned const char *q = strm->next_in;
-            unsigned n = strm->avail_in;
-            do {
-                *p++ = *q++;
-            } while (--n);
+
+            if (q != p) {
+                unsigned n = strm->avail_in;
+
+                do {
+                    *p++ = *q++;
+                } while (--n);
+            }
         }
         if (gz_load(state, state->in + strm->avail_in,
                     state->size - strm->avail_in, &got) == -1)
@@ -128,39 +145,44 @@ local int gz_look(gz_statep state) {
         }
     }
 
-    /* get at least the magic bytes in the input buffer */
-    if (strm->avail_in < 2) {
-        if (gz_avail(state) == -1)
-            return -1;
-        if (strm->avail_in == 0)
-            return 0;
-    }
-
-    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
-       a logical dilemma here when considering the case of a partially written
-       gzip file, to wit, if a single 31 byte is written, then we cannot tell
-       whether this is a single-byte file, or just a partially written gzip
-       file -- for here we assume that if a gzip file is being written, then
-       the header will be written in a single operation, so that reading a
-       single byte is sufficient indication that it is not a gzip file) */
-    if (strm->avail_in > 1 &&
-            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
+    /* if transparent reading is disabled, which would only be at the start, or
+       if we're looking for a gzip member after the first one, which is not at
+       the start, then proceed directly to look for a gzip member next */
+    if (state->direct == -1 || state->junk == 0) {
         inflateReset(strm);
         state->how = GZIP;
+        state->junk = state->junk != -1;
         state->direct = 0;
         return 0;
     }
 
-    /* no gzip header -- if we were decoding gzip before, then this is trailing
-       garbage.  Ignore the trailing garbage and finish. */
-    if (state->direct == 0) {
-        strm->avail_in = 0;
-        state->eof = 1;
-        state->x.have = 0;
+    /* otherwise we're at the start with auto-detect -- we check to see if the
+       first four bytes could be gzip header in order to decide whether or not
+       this will be a transparent read */
+
+    /* load any header bytes into the input buffer -- if the input is empty,
+       then it's not an error as this is a transparent read of zero bytes */
+    if (gz_avail(state) == -1)
+        return -1;
+    if (strm->avail_in == 0 || (state->again && strm->avail_in < 4))
+        /* if non-blocking input stalled before getting four bytes, then
+           return and wait until a later call has accumulated enough */
+        return 0;
+
+    /* see if this is (likely) gzip input -- if the first four bytes are
+       consistent with a gzip header, then go look for the first gzip member,
+       otherwise proceed to copy the input transparently */
+    if (strm->avail_in > 3 &&
+            strm->next_in[0] == 31 && strm->next_in[1] == 139 &&
+            strm->next_in[2] == 8 && strm->next_in[3] < 32) {
+        inflateReset(strm);
+        state->how = GZIP;
+        state->junk = 1;
+        state->direct = 0;
         return 0;
     }
 
-    /* doing raw i/o, copy any leftover input to output -- this assumes that
+    /* doing raw i/o: copy any leftover input to output -- this assumes that
        the output buffer is larger than the input buffer, which also assures
        space for gzungetc() */
     state->x.next = state->out;
@@ -168,15 +190,17 @@ local int gz_look(gz_statep state) {
     state->x.have = strm->avail_in;
     strm->avail_in = 0;
     state->how = COPY;
-    state->direct = 1;
     return 0;
 }
 
 /* Decompress from input to the provided next_out and avail_out in the state.
    On return, state->x.have and state->x.next point to the just decompressed
-   data.  If the gzip stream completes, state->how is reset to LOOK to look for
-   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
-   on success, -1 on failure. */
+   data. If the gzip stream completes, state->how is reset to LOOK to look for
+   the next gzip stream or raw data, once state->x.have is depleted. Returns 0
+   on success, -1 on failure. If EOF is reached when looking for more input to
+   complete the gzip member, then an unexpected end of file error is raised.
+   If there is no more input, but state->again is true, then EOF has not been
+   reached, and no error is raised. */
 local int gz_decomp(gz_statep state) {
     int ret = Z_OK;
     unsigned had;
@@ -186,28 +210,41 @@ local int gz_decomp(gz_statep state) {
     had = strm->avail_out;
     do {
         /* get more input for inflate() */
-        if (strm->avail_in == 0 && gz_avail(state) == -1)
-            return -1;
+        if (strm->avail_in == 0 && gz_avail(state) == -1) {
+            ret = state->err;
+            break;
+        }
         if (strm->avail_in == 0) {
-            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
+            if (!state->again)
+                gz_error(state, Z_BUF_ERROR, "unexpected end of file");
             break;
         }
 
         /* decompress and handle errors */
         ret = inflate(strm, Z_NO_FLUSH);
+        if (strm->avail_out < had)
+            /* any decompressed data marks this as a real gzip stream */
+            state->junk = 0;
         if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
             gz_error(state, Z_STREAM_ERROR,
                      "internal error: inflate stream corrupt");
-            return -1;
+            break;
         }
         if (ret == Z_MEM_ERROR) {
             gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
+            break;
         }
         if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
+            if (state->junk == 1) {             /* trailing garbage is ok */
+                strm->avail_in = 0;
+                state->eof = 1;
+                state->how = LOOK;
+                ret = Z_OK;
+                break;
+            }
             gz_error(state, Z_DATA_ERROR,
                      strm->msg == NULL ? "compressed data error" : strm->msg);
-            return -1;
+            break;
         }
     } while (strm->avail_out && ret != Z_STREAM_END);
 
@@ -216,11 +253,14 @@ local int gz_decomp(gz_statep state) {
     state->x.next = strm->next_out - state->x.have;
 
     /* if the gzip stream completed successfully, look for another */
-    if (ret == Z_STREAM_END)
+    if (ret == Z_STREAM_END) {
+        state->junk = 0;
         state->how = LOOK;
+        return 0;
+    }
 
-    /* good decompression */
-    return 0;
+    /* return decompression status */
+    return ret != Z_OK ? -1 : 0;
 }
 
 /* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
@@ -251,25 +291,31 @@ local int gz_fetch(gz_statep state) {
             strm->next_out = state->out;
             if (gz_decomp(state) == -1)
                 return -1;
+            break;
+        default:
+            gz_error(state, Z_STREAM_ERROR, "state corrupt");
+            return -1;
         }
     } while (state->x.have == 0 && (!state->eof || strm->avail_in));
     return 0;
 }
 
-/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
-local int gz_skip(gz_statep state, z_off64_t len) {
+/* Skip state->skip (> 0) uncompressed bytes of output.  Return -1 on error, 0
+   on success. */
+local int gz_skip(gz_statep state) {
     unsigned n;
 
     /* skip over len bytes or reach end-of-file, whichever comes first */
-    while (len)
+    do {
         /* skip over whatever is in output buffer */
         if (state->x.have) {
-            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
-                (unsigned)len : state->x.have;
+            n = GT_OFF(state->x.have) ||
+                (z_off64_t)state->x.have > state->skip ?
+                (unsigned)state->skip : state->x.have;
             state->x.have -= n;
             state->x.next += n;
             state->x.pos += n;
-            len -= n;
+            state->skip -= n;
         }
 
         /* output buffer empty -- return if we're at the end of the input */
@@ -282,30 +328,32 @@ local int gz_skip(gz_statep state, z_off64_t len) {
             if (gz_fetch(state) == -1)
                 return -1;
         }
+    } while (state->skip);
     return 0;
 }
 
 /* Read len bytes into buf from file, or less than len up to the end of the
-   input.  Return the number of bytes read.  If zero is returned, either the
-   end of file was reached, or there was an error.  state->err must be
-   consulted in that case to determine which. */
+   input. Return the number of bytes read. If zero is returned, either the end
+   of file was reached, or there was an error. state->err must be consulted in
+   that case to determine which. If there was an error, but some uncompressed
+   bytes were read before the error, then that count is returned. The error is
+   still recorded, and so is deferred until the next call. */
 local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
     z_size_t got;
     unsigned n;
+    int err;
 
     /* if len is zero, avoid unnecessary operations */
     if (len == 0)
         return 0;
 
     /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return 0;
-    }
+    if (state->skip && gz_skip(state) == -1)
+        return 0;
 
     /* get len bytes to buf, or less than len if at the end */
     got = 0;
+    err = 0;
     do {
         /* set n to the maximum amount of len that fits in an unsigned int */
         n = (unsigned)-1;
@@ -319,37 +367,36 @@ local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
             memcpy(buf, state->x.next, n);
             state->x.next += n;
             state->x.have -= n;
+            if (state->err != Z_OK)
+                /* caught deferred error from gz_fetch() */
+                err = -1;
         }
 
         /* output buffer empty -- return if we're at the end of the input */
-        else if (state->eof && state->strm.avail_in == 0) {
-            state->past = 1;        /* tried to read past end */
+        else if (state->eof && state->strm.avail_in == 0)
             break;
-        }
 
         /* need output data -- for small len or new stream load up our output
-           buffer */
+           buffer, so that gzgetc() can be fast */
         else if (state->how == LOOK || n < (state->size << 1)) {
             /* get more output, looking for header if required */
-            if (gz_fetch(state) == -1)
-                return 0;
+            if (gz_fetch(state) == -1 && state->x.have == 0)
+                /* if state->x.have != 0, error will be caught after copy */
+                err = -1;
             continue;       /* no progress yet -- go back to copy above */
             /* the copy above assures that we will leave with space in the
                output buffer, allowing at least one gzungetc() to succeed */
         }
 
         /* large len -- read directly into user buffer */
-        else if (state->how == COPY) {      /* read directly */
-            if (gz_load(state, (unsigned char *)buf, n, &n) == -1)
-                return 0;
-        }
+        else if (state->how == COPY)        /* read directly */
+            err = gz_load(state, (unsigned char *)buf, n, &n);
 
         /* large len -- decompress directly into user buffer */
         else {  /* state->how == GZIP */
             state->strm.avail_out = n;
             state->strm.next_out = (unsigned char *)buf;
-            if (gz_decomp(state) == -1)
-                return 0;
+            err = gz_decomp(state);
             n = state->x.have;
             state->x.have = 0;
         }
@@ -359,7 +406,11 @@ local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
         buf = (char *)buf + n;
         got += n;
         state->x.pos += n;
-    } while (len);
+    } while (len && !err);
+
+    /* note read past eof */
+    if (len && state->eof)
+        state->past = 1;
 
     /* return number of bytes read into user buffer */
     return got;
@@ -369,16 +420,18 @@ local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
 int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) {
     gz_statep state;
 
-    /* get internal structure */
+    /* get internal structure and check that it's for reading */
     if (file == NULL)
         return -1;
     state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+    if (state->mode != GZ_READ)
         return -1;
 
+    /* check that there was no (serious) error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return -1;
+    gz_error(state, Z_OK, NULL);
+
     /* since an int is returned, make sure len fits in one, otherwise return
        with an error (this avoids a flaw in the interface) */
     if ((int)len < 0) {
@@ -390,28 +443,40 @@ int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) {
     len = (unsigned)gz_read(state, buf, len);
 
     /* check for an error */
-    if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)
-        return -1;
+    if (len == 0) {
+        if (state->err != Z_OK && state->err != Z_BUF_ERROR)
+            return -1;
+        if (state->again) {
+            /* non-blocking input stalled after some input was read, but no
+               uncompressed bytes were produced -- let the application know
+               this isn't EOF */
+            gz_error(state, Z_ERRNO, zstrerror());
+            return -1;
+        }
+    }
 
-    /* return the number of bytes read (this is assured to fit in an int) */
+    /* return the number of bytes read */
     return (int)len;
 }
 
 /* -- see zlib.h -- */
-z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, gzFile file) {
+z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
+                         gzFile file) {
     z_size_t len;
     gz_statep state;
 
-    /* get internal structure */
+    /* get internal structure and check that it's for reading */
     if (file == NULL)
         return 0;
     state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+    if (state->mode != GZ_READ)
         return 0;
 
+    /* check that there was no (serious) error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return 0;
+    gz_error(state, Z_OK, NULL);
+
     /* compute bytes to read -- error on overflow */
     len = nitems * size;
     if (size && len / size != nitems) {
@@ -433,16 +498,18 @@ int ZEXPORT gzgetc(gzFile file) {
     unsigned char buf[1];
     gz_statep state;
 
-    /* get internal structure */
+    /* get internal structure and check that it's for reading */
     if (file == NULL)
         return -1;
     state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+    if (state->mode != GZ_READ)
         return -1;
 
+    /* check that there was no (serious) error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return -1;
+    gz_error(state, Z_OK, NULL);
+
     /* try output buffer (no need to check for skip request) */
     if (state->x.have) {
         state->x.have--;
@@ -462,26 +529,25 @@ int ZEXPORT gzgetc_(gzFile file) {
 int ZEXPORT gzungetc(int c, gzFile file) {
     gz_statep state;
 
-    /* get internal structure */
+    /* get internal structure and check that it's for reading */
     if (file == NULL)
         return -1;
     state = (gz_statep)file;
-
-    /* in case this was just opened, set up the input buffer */
-    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
-        (void)gz_look(state);
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+    if (state->mode != GZ_READ)
         return -1;
 
+    /* in case this was just opened, set up the input buffer */
+    if (state->how == LOOK && state->x.have == 0)
+        (void)gz_look(state);
+
+    /* check that there was no (serious) error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return -1;
+    gz_error(state, Z_OK, NULL);
+
     /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return -1;
-    }
+    if (state->skip && gz_skip(state) == -1)
+        return -1;
 
     /* can't push EOF */
     if (c < 0)
@@ -507,6 +573,7 @@ int ZEXPORT gzungetc(int c, gzFile file) {
     if (state->x.next == state->out) {
         unsigned char *src = state->out + state->x.have;
         unsigned char *dest = state->out + (state->size << 1);
+
         while (src > state->out)
             *--dest = *--src;
         state->x.next = dest;
@@ -526,32 +593,31 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
     unsigned char *eol;
     gz_statep state;
 
-    /* check parameters and get internal structure */
+    /* check parameters, get internal structure, and check that it's for
+       reading */
     if (file == NULL || buf == NULL || len < 1)
         return NULL;
     state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+    if (state->mode != GZ_READ)
         return NULL;
 
-    /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return NULL;
-    }
+    /* check that there was no (serious) error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again)
+        return NULL;
+    gz_error(state, Z_OK, NULL);
 
-    /* copy output bytes up to new line or len - 1, whichever comes first --
-       append a terminating zero to the string (we don't check for a zero in
-       the contents, let the user worry about that) */
+    /* process a skip request */
+    if (state->skip && gz_skip(state) == -1)
+        return NULL;
+
+    /* copy output up to a new line, len-1 bytes, or there is no more output,
+       whichever comes first */
     str = buf;
     left = (unsigned)len - 1;
     if (left) do {
         /* assure that something is in the output buffer */
         if (state->x.have == 0 && gz_fetch(state) == -1)
-            return NULL;                /* error */
+            break;                      /* error */
         if (state->x.have == 0) {       /* end of file */
             state->past = 1;            /* read past end */
             break;                      /* return what we have */
@@ -572,7 +638,9 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
         buf += n;
     } while (left && eol == NULL);
 
-    /* return terminated string, or if nothing, end of file */
+    /* append a terminating zero to the string (we don't check for a zero in
+       the contents, let the user worry about that) -- return the terminated
+       string, or if nothing was read, NULL */
     if (buf == str)
         return NULL;
     buf[0] = 0;
@@ -594,7 +662,7 @@ int ZEXPORT gzdirect(gzFile file) {
         (void)gz_look(state);
 
     /* return 1 if transparent, 0 if processing a gzip stream */
-    return state->direct;
+    return state->direct == 1;
 }
 
 /* -- see zlib.h -- */
@@ -602,12 +670,10 @@ int ZEXPORT gzclose_r(gzFile file) {
     int ret, err;
     gz_statep state;
 
-    /* get internal structure */
+    /* get internal structure and check that it's for reading */
     if (file == NULL)
         return Z_STREAM_ERROR;
     state = (gz_statep)file;
-
-    /* check that we're reading */
     if (state->mode != GZ_READ)
         return Z_STREAM_ERROR;
 
diff --git a/src/java.base/share/native/libzip/zlib/gzwrite.c b/src/java.base/share/native/libzip/zlib/gzwrite.c
index 008b03e7021..b11c318d543 100644
--- a/src/java.base/share/native/libzip/zlib/gzwrite.c
+++ b/src/java.base/share/native/libzip/zlib/gzwrite.c
@@ -23,7 +23,7 @@
  */
 
 /* gzwrite.c -- zlib functions for writing gzip files
- * Copyright (C) 2004-2019 Mark Adler
+ * Copyright (C) 2004-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -98,9 +98,13 @@ local int gz_comp(gz_statep state, int flush) {
     /* write directly if requested */
     if (state->direct) {
         while (strm->avail_in) {
+            errno = 0;
+            state->again = 0;
             put = strm->avail_in > max ? max : strm->avail_in;
-            writ = write(state->fd, strm->next_in, put);
+            writ = (int)write(state->fd, strm->next_in, put);
             if (writ < 0) {
+                if (errno == EAGAIN || errno == EWOULDBLOCK)
+                    state->again = 1;
                 gz_error(state, Z_ERRNO, zstrerror());
                 return -1;
             }
@@ -112,8 +116,9 @@ local int gz_comp(gz_statep state, int flush) {
 
     /* check for a pending reset */
     if (state->reset) {
-        /* don't start a new gzip member unless there is data to write */
-        if (strm->avail_in == 0)
+        /* don't start a new gzip member unless there is data to write and
+           we're not flushing */
+        if (strm->avail_in == 0 && flush == Z_NO_FLUSH)
             return 0;
         deflateReset(strm);
         state->reset = 0;
@@ -127,10 +132,14 @@ local int gz_comp(gz_statep state, int flush) {
         if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
             (flush != Z_FINISH || ret == Z_STREAM_END))) {
             while (strm->next_out > state->x.next) {
+                errno = 0;
+                state->again = 0;
                 put = strm->next_out - state->x.next > (int)max ? max :
                       (unsigned)(strm->next_out - state->x.next);
-                writ = write(state->fd, state->x.next, put);
+                writ = (int)write(state->fd, state->x.next, put);
                 if (writ < 0) {
+                    if (errno == EAGAIN || errno == EWOULDBLOCK)
+                        state->again = 1;
                     gz_error(state, Z_ERRNO, zstrerror());
                     return -1;
                 }
@@ -162,10 +171,12 @@ local int gz_comp(gz_statep state, int flush) {
     return 0;
 }
 
-/* Compress len zeros to output.  Return -1 on a write error or memory
-   allocation failure by gz_comp(), or 0 on success. */
-local int gz_zero(gz_statep state, z_off64_t len) {
-    int first;
+/* Compress state->skip (> 0) zeros to output.  Return -1 on a write error or
+   memory allocation failure by gz_comp(), or 0 on success. state->skip is
+   updated with the number of successfully written zeros, in case there is a
+   stall on a non-blocking write destination. */
+local int gz_zero(gz_statep state) {
+    int first, ret;
     unsigned n;
     z_streamp strm = &(state->strm);
 
@@ -173,29 +184,34 @@ local int gz_zero(gz_statep state, z_off64_t len) {
     if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
         return -1;
 
-    /* compress len zeros (len guaranteed > 0) */
+    /* compress state->skip zeros */
     first = 1;
-    while (len) {
-        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
-            (unsigned)len : state->size;
+    do {
+        n = GT_OFF(state->size) || (z_off64_t)state->size > state->skip ?
+            (unsigned)state->skip : state->size;
         if (first) {
             memset(state->in, 0, n);
             first = 0;
         }
         strm->avail_in = n;
         strm->next_in = state->in;
+        ret = gz_comp(state, Z_NO_FLUSH);
+        n -= strm->avail_in;
         state->x.pos += n;
-        if (gz_comp(state, Z_NO_FLUSH) == -1)
+        state->skip -= n;
+        if (ret == -1)
             return -1;
-        len -= n;
-    }
+    } while (state->skip);
     return 0;
 }
 
 /* Write len bytes from buf to file.  Return the number of bytes written.  If
-   the returned value is less than len, then there was an error. */
+   the returned value is less than len, then there was an error. If the error
+   was a non-blocking stall, then the number of bytes consumed is returned.
+   For any other error, 0 is returned. */
 local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
     z_size_t put = len;
+    int ret;
 
     /* if len is zero, avoid unnecessary operations */
     if (len == 0)
@@ -206,16 +222,13 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
         return 0;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return 0;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return 0;
 
     /* for small len, copy to input buffer, otherwise compress directly */
     if (len < state->size) {
         /* copy to input buffer, compress when full */
-        do {
+        for (;;) {
             unsigned have, copy;
 
             if (state->strm.avail_in == 0)
@@ -230,9 +243,11 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
             state->x.pos += copy;
             buf = (const char *)buf + copy;
             len -= copy;
-            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
-                return 0;
-        } while (len);
+            if (len == 0)
+                break;
+            if (gz_comp(state, Z_NO_FLUSH) == -1)
+                return state->again ? put - len : 0;
+        }
     }
     else {
         /* consume whatever's left in the input buffer */
@@ -243,13 +258,16 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
         state->strm.next_in = (z_const Bytef *)buf;
         do {
             unsigned n = (unsigned)-1;
+
             if (n > len)
                 n = (unsigned)len;
             state->strm.avail_in = n;
+            ret = gz_comp(state, Z_NO_FLUSH);
+            n -= state->strm.avail_in;
             state->x.pos += n;
-            if (gz_comp(state, Z_NO_FLUSH) == -1)
-                return 0;
             len -= n;
+            if (ret == -1)
+                return state->again ? put - len : 0;
         } while (len);
     }
 
@@ -266,9 +284,10 @@ int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len) {
         return 0;
     state = (gz_statep)file;
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return 0;
+    gz_error(state, Z_OK, NULL);
 
     /* since an int is returned, make sure len fits in one, otherwise return
        with an error (this avoids a flaw in the interface) */
@@ -292,9 +311,10 @@ z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, z_size_t nitems,
         return 0;
     state = (gz_statep)file;
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return 0;
+    gz_error(state, Z_OK, NULL);
 
     /* compute bytes to read -- error on overflow */
     len = nitems * size;
@@ -320,16 +340,14 @@ int ZEXPORT gzputc(gzFile file, int c) {
     state = (gz_statep)file;
     strm = &(state->strm);
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return -1;
+    gz_error(state, Z_OK, NULL);
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return -1;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return -1;
 
     /* try writing to input buffer for speed (state->size == 0 if buffer not
        initialized) */
@@ -362,9 +380,10 @@ int ZEXPORT gzputs(gzFile file, const char *s) {
         return -1;
     state = (gz_statep)file;
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return -1;
+    gz_error(state, Z_OK, NULL);
 
     /* write string */
     len = strlen(s);
@@ -373,16 +392,47 @@ int ZEXPORT gzputs(gzFile file, const char *s) {
         return -1;
     }
     put = gz_write(state, s, len);
-    return put < len ? -1 : (int)len;
+    return len && put == 0 ? -1 : (int)put;
 }
 
+#if (((!defined(STDC) && !defined(Z_HAVE_STDARG_H)) || !defined(NO_vsnprintf)) && \
+     (defined(STDC) || defined(Z_HAVE_STDARG_H) || !defined(NO_snprintf))) || \
+    defined(ZLIB_INSECURE)
+/* If the second half of the input buffer is occupied, write out the contents.
+   If there is any input remaining due to a non-blocking stall on write, move
+   it to the start of the buffer. Return true if this did not open up the
+   second half of the buffer.  state->err should be checked after this to
+   handle a gz_comp() error. */
+local int gz_vacate(gz_statep state) {
+    z_streamp strm;
+
+    strm = &(state->strm);
+    if (strm->next_in + strm->avail_in <= state->in + state->size)
+        return 0;
+    (void)gz_comp(state, Z_NO_FLUSH);
+    if (strm->avail_in == 0) {
+        strm->next_in = state->in;
+        return 0;
+    }
+    memmove(state->in, strm->next_in, strm->avail_in);
+    strm->next_in = state->in;
+    return strm->avail_in > state->size;
+}
+#endif
+
 #if defined(STDC) || defined(Z_HAVE_STDARG_H)
 #include 
 
 /* -- see zlib.h -- */
 int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) {
-    int len;
-    unsigned left;
+#if defined(NO_vsnprintf) && !defined(ZLIB_INSECURE)
+#warning "vsnprintf() not available -- gzprintf() stub returns Z_STREAM_ERROR"
+#warning "you can recompile with ZLIB_INSECURE defined to use vsprintf()"
+    /* prevent use of insecure vsprintf(), unless purposefully requested */
+    (void)file, (void)format, (void)va;
+    return Z_STREAM_ERROR;
+#else
+    int len, ret;
     char *next;
     gz_statep state;
     z_streamp strm;
@@ -393,24 +443,34 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) {
     state = (gz_statep)file;
     strm = &(state->strm);
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return Z_STREAM_ERROR;
+    gz_error(state, Z_OK, NULL);
 
     /* make sure we have some buffer space */
     if (state->size == 0 && gz_init(state) == -1)
         return state->err;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return state->err;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return state->err;
 
     /* do the printf() into the input buffer, put length in len -- the input
-       buffer is double-sized just for this function, so there is guaranteed to
-       be state->size bytes available after the current contents */
+       buffer is double-sized just for this function, so there should be
+       state->size bytes available after the current contents */
+    ret = gz_vacate(state);
+    if (state->err) {
+        if (ret && state->again) {
+            /* There was a non-blocking stall on write, resulting in the part
+               of the second half of the output buffer being occupied.  Return
+               a Z_BUF_ERROR to let the application know that this gzprintf()
+               needs to be retried. */
+            gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf");
+        }
+        if (!state->again)
+            return state->err;
+    }
     if (strm->avail_in == 0)
         strm->next_in = state->in;
     next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in);
@@ -436,19 +496,16 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) {
     if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0)
         return 0;
 
-    /* update buffer and position, compress first half if past that */
+    /* update buffer and position */
     strm->avail_in += (unsigned)len;
     state->x.pos += len;
-    if (strm->avail_in >= state->size) {
-        left = strm->avail_in - state->size;
-        strm->avail_in = state->size;
-        if (gz_comp(state, Z_NO_FLUSH) == -1)
-            return state->err;
-        memmove(state->in, state->in + state->size, left);
-        strm->next_in = state->in;
-        strm->avail_in = left;
-    }
+
+    /* write out buffer if more than half is occupied */
+    ret = gz_vacate(state);
+    if (state->err && !state->again)
+        return state->err;
     return len;
+#endif
 }
 
 int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) {
@@ -468,6 +525,17 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
                        int a4, int a5, int a6, int a7, int a8, int a9, int a10,
                        int a11, int a12, int a13, int a14, int a15, int a16,
                        int a17, int a18, int a19, int a20) {
+#if defined(NO_snprintf) && !defined(ZLIB_INSECURE)
+#warning "snprintf() not available -- gzprintf() stub returns Z_STREAM_ERROR"
+#warning "you can recompile with ZLIB_INSECURE defined to use sprintf()"
+    /* prevent use of insecure sprintf(), unless purposefully requested */
+    (void)file, (void)format, (void)a1, (void)a2, (void)a3, (void)a4, (void)a5,
+    (void)a6, (void)a7, (void)a8, (void)a9, (void)a10, (void)a11, (void)a12,
+    (void)a13, (void)a14, (void)a15, (void)a16, (void)a17, (void)a18,
+    (void)a19, (void)a20;
+    return Z_STREAM_ERROR;
+#else
+    int ret;
     unsigned len, left;
     char *next;
     gz_statep state;
@@ -483,24 +551,34 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
     if (sizeof(int) != sizeof(void *))
         return Z_STREAM_ERROR;
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return Z_STREAM_ERROR;
+    gz_error(state, Z_OK, NULL);
 
     /* make sure we have some buffer space */
     if (state->size == 0 && gz_init(state) == -1)
-        return state->error;
+        return state->err;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return state->error;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return state->err;
 
     /* do the printf() into the input buffer, put length in len -- the input
        buffer is double-sized just for this function, so there is guaranteed to
        be state->size bytes available after the current contents */
+    ret = gz_vacate(state);
+    if (state->err) {
+        if (ret && state->again) {
+            /* There was a non-blocking stall on write, resulting in the part
+               of the second half of the output buffer being occupied.  Return
+               a Z_BUF_ERROR to let the application know that this gzprintf()
+               needs to be retried. */
+            gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf");
+        }
+        if (!state->again)
+            return state->err;
+    }
     if (strm->avail_in == 0)
         strm->next_in = state->in;
     next = (char *)(strm->next_in + strm->avail_in);
@@ -534,16 +612,13 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
     /* update buffer and position, compress first half if past that */
     strm->avail_in += len;
     state->x.pos += len;
-    if (strm->avail_in >= state->size) {
-        left = strm->avail_in - state->size;
-        strm->avail_in = state->size;
-        if (gz_comp(state, Z_NO_FLUSH) == -1)
-            return state->err;
-        memmove(state->in, state->in + state->size, left);
-        strm->next_in = state->in;
-        strm->avail_in = left;
-    }
+
+    /* write out buffer if more than half is occupied */
+    ret = gz_vacate(state);
+    if (state->err && !state->again)
+        return state->err;
     return (int)len;
+#endif
 }
 
 #endif
@@ -557,20 +632,18 @@ int ZEXPORT gzflush(gzFile file, int flush) {
         return Z_STREAM_ERROR;
     state = (gz_statep)file;
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
+    /* check that we're writing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again))
         return Z_STREAM_ERROR;
+    gz_error(state, Z_OK, NULL);
 
     /* check flush parameter */
     if (flush < 0 || flush > Z_FINISH)
         return Z_STREAM_ERROR;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return state->err;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return state->err;
 
     /* compress remaining data with requested flush */
     (void)gz_comp(state, flush);
@@ -588,20 +661,19 @@ int ZEXPORT gzsetparams(gzFile file, int level, int strategy) {
     state = (gz_statep)file;
     strm = &(state->strm);
 
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK || state->direct)
+    /* check that we're compressing and that there's no (serious) error */
+    if (state->mode != GZ_WRITE || (state->err != Z_OK && !state->again) ||
+            state->direct)
         return Z_STREAM_ERROR;
+    gz_error(state, Z_OK, NULL);
 
     /* if no change is requested, then do nothing */
     if (level == state->level && strategy == state->strategy)
         return Z_OK;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return state->err;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        return state->err;
 
     /* change compression parameters for subsequent input */
     if (state->size) {
@@ -630,11 +702,8 @@ int ZEXPORT gzclose_w(gzFile file) {
         return Z_STREAM_ERROR;
 
     /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            ret = state->err;
-    }
+    if (state->skip && gz_zero(state) == -1)
+        ret = state->err;
 
     /* flush, free memory, and close file */
     if (gz_comp(state, Z_FINISH) == -1)
diff --git a/src/java.base/share/native/libzip/zlib/infback.c b/src/java.base/share/native/libzip/zlib/infback.c
index f680e2cdbdc..0becbb9eb4f 100644
--- a/src/java.base/share/native/libzip/zlib/infback.c
+++ b/src/java.base/share/native/libzip/zlib/infback.c
@@ -23,7 +23,7 @@
  */
 
 /* infback.c -- inflate using a call-back interface
- * Copyright (C) 1995-2022 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -70,7 +70,7 @@ int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits,
 #ifdef Z_SOLO
         return Z_STREAM_ERROR;
 #else
-    strm->zfree = zcfree;
+        strm->zfree = zcfree;
 #endif
     state = (struct inflate_state FAR *)ZALLOC(strm, 1,
                                                sizeof(struct inflate_state));
@@ -87,57 +87,6 @@ int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits,
     return Z_OK;
 }
 
-/*
-   Return state with length and distance decoding tables and index sizes set to
-   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
-   If BUILDFIXED is defined, then instead this routine builds the tables the
-   first time it's called, and returns those tables the first time and
-   thereafter.  This reduces the size of the code by about 2K bytes, in
-   exchange for a little execution time.  However, BUILDFIXED should not be
-   used for threaded applications, since the rewriting of the tables and virgin
-   may not be thread-safe.
- */
-local void fixedtables(struct inflate_state FAR *state) {
-#ifdef BUILDFIXED
-    static int virgin = 1;
-    static code *lenfix, *distfix;
-    static code fixed[544];
-
-    /* build fixed huffman tables if first call (may not be thread safe) */
-    if (virgin) {
-        unsigned sym, bits;
-        static code *next;
-
-        /* literal/length table */
-        sym = 0;
-        while (sym < 144) state->lens[sym++] = 8;
-        while (sym < 256) state->lens[sym++] = 9;
-        while (sym < 280) state->lens[sym++] = 7;
-        while (sym < 288) state->lens[sym++] = 8;
-        next = fixed;
-        lenfix = next;
-        bits = 9;
-        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
-
-        /* distance table */
-        sym = 0;
-        while (sym < 32) state->lens[sym++] = 5;
-        distfix = next;
-        bits = 5;
-        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
-
-        /* do this just once */
-        virgin = 0;
-    }
-#else /* !BUILDFIXED */
-#   include "inffixed.h"
-#endif /* BUILDFIXED */
-    state->lencode = lenfix;
-    state->lenbits = 9;
-    state->distcode = distfix;
-    state->distbits = 5;
-}
-
 /* Macros for inflateBack(): */
 
 /* Load returned state from inflate_fast() */
@@ -317,7 +266,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
                 state->mode = STORED;
                 break;
             case 1:                             /* fixed block */
-                fixedtables(state);
+                inflate_fixed(state);
                 Tracev((stderr, "inflate:     fixed codes block%s\n",
                         state->last ? " (last)" : ""));
                 state->mode = LEN;              /* decode codes */
@@ -327,8 +276,8 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
                         state->last ? " (last)" : ""));
                 state->mode = TABLE;
                 break;
-            case 3:
-                strm->msg = (char *)"invalid block type";
+            default:
+                strm->msg = (z_const char *)"invalid block type";
                 state->mode = BAD;
             }
             DROPBITS(2);
@@ -339,7 +288,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             BYTEBITS();                         /* go to byte boundary */
             NEEDBITS(32);
             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
-                strm->msg = (char *)"invalid stored block lengths";
+                strm->msg = (z_const char *)"invalid stored block lengths";
                 state->mode = BAD;
                 break;
             }
@@ -377,7 +326,8 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             DROPBITS(4);
 #ifndef PKZIP_BUG_WORKAROUND
             if (state->nlen > 286 || state->ndist > 30) {
-                strm->msg = (char *)"too many length or distance symbols";
+                strm->msg = (z_const char *)
+                    "too many length or distance symbols";
                 state->mode = BAD;
                 break;
             }
@@ -399,7 +349,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             ret = inflate_table(CODES, state->lens, 19, &(state->next),
                                 &(state->lenbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid code lengths set";
+                strm->msg = (z_const char *)"invalid code lengths set";
                 state->mode = BAD;
                 break;
             }
@@ -422,7 +372,8 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
                         NEEDBITS(here.bits + 2);
                         DROPBITS(here.bits);
                         if (state->have == 0) {
-                            strm->msg = (char *)"invalid bit length repeat";
+                            strm->msg = (z_const char *)
+                                "invalid bit length repeat";
                             state->mode = BAD;
                             break;
                         }
@@ -445,7 +396,8 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
                         DROPBITS(7);
                     }
                     if (state->have + copy > state->nlen + state->ndist) {
-                        strm->msg = (char *)"invalid bit length repeat";
+                        strm->msg = (z_const char *)
+                            "invalid bit length repeat";
                         state->mode = BAD;
                         break;
                     }
@@ -459,7 +411,8 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
 
             /* check for end-of-block code (better have one) */
             if (state->lens[256] == 0) {
-                strm->msg = (char *)"invalid code -- missing end-of-block";
+                strm->msg = (z_const char *)
+                    "invalid code -- missing end-of-block";
                 state->mode = BAD;
                 break;
             }
@@ -473,7 +426,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
                                 &(state->lenbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid literal/lengths set";
+                strm->msg = (z_const char *)"invalid literal/lengths set";
                 state->mode = BAD;
                 break;
             }
@@ -482,7 +435,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
                             &(state->next), &(state->distbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid distances set";
+                strm->msg = (z_const char *)"invalid distances set";
                 state->mode = BAD;
                 break;
             }
@@ -541,7 +494,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
 
             /* invalid code */
             if (here.op & 64) {
-                strm->msg = (char *)"invalid literal/length code";
+                strm->msg = (z_const char *)"invalid literal/length code";
                 state->mode = BAD;
                 break;
             }
@@ -573,7 +526,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             }
             DROPBITS(here.bits);
             if (here.op & 64) {
-                strm->msg = (char *)"invalid distance code";
+                strm->msg = (z_const char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
@@ -588,7 +541,7 @@ int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc,
             }
             if (state->offset > state->wsize - (state->whave < state->wsize ?
                                                 left : 0)) {
-                strm->msg = (char *)"invalid distance too far back";
+                strm->msg = (z_const char *)"invalid distance too far back";
                 state->mode = BAD;
                 break;
             }
diff --git a/src/java.base/share/native/libzip/zlib/inffast.c b/src/java.base/share/native/libzip/zlib/inffast.c
index e86dd78d801..1ce89512ec4 100644
--- a/src/java.base/share/native/libzip/zlib/inffast.c
+++ b/src/java.base/share/native/libzip/zlib/inffast.c
@@ -23,7 +23,7 @@
  */
 
 /* inffast.c -- fast decoding
- * Copyright (C) 1995-2017 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -179,7 +179,8 @@ void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) {
                 dist += (unsigned)hold & ((1U << op) - 1);
 #ifdef INFLATE_STRICT
                 if (dist > dmax) {
-                    strm->msg = (char *)"invalid distance too far back";
+                    strm->msg = (z_const char *)
+                        "invalid distance too far back";
                     state->mode = BAD;
                     break;
                 }
@@ -192,8 +193,8 @@ void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) {
                     op = dist - op;             /* distance back in window */
                     if (op > whave) {
                         if (state->sane) {
-                            strm->msg =
-                                (char *)"invalid distance too far back";
+                            strm->msg = (z_const char *)
+                                "invalid distance too far back";
                             state->mode = BAD;
                             break;
                         }
@@ -289,7 +290,7 @@ void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) {
                 goto dodist;
             }
             else {
-                strm->msg = (char *)"invalid distance code";
+                strm->msg = (z_const char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
@@ -304,7 +305,7 @@ void ZLIB_INTERNAL inflate_fast(z_streamp strm, unsigned start) {
             break;
         }
         else {
-            strm->msg = (char *)"invalid literal/length code";
+            strm->msg = (z_const char *)"invalid literal/length code";
             state->mode = BAD;
             break;
         }
diff --git a/src/java.base/share/native/libzip/zlib/inffixed.h b/src/java.base/share/native/libzip/zlib/inffixed.h
index f0a4ef1c4e8..d234b018c87 100644
--- a/src/java.base/share/native/libzip/zlib/inffixed.h
+++ b/src/java.base/share/native/libzip/zlib/inffixed.h
@@ -22,97 +22,97 @@
  * questions.
  */
 
-    /* inffixed.h -- table for decoding fixed codes
-     * Generated automatically by makefixed().
-     */
+/* inffixed.h -- table for decoding fixed codes
+ * Generated automatically by makefixed().
+ */
 
-    /* WARNING: this file should *not* be used by applications.
-       It is part of the implementation of this library and is
-       subject to change. Applications should only use zlib.h.
-     */
+/* WARNING: this file should *not* be used by applications.
+   It is part of the implementation of this library and is
+   subject to change. Applications should only use zlib.h.
+ */
 
-    static const code lenfix[512] = {
-        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
-        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
-        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
-        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
-        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
-        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
-        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
-        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
-        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
-        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
-        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
-        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
-        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
-        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
-        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
-        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
-        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
-        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
-        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
-        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
-        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
-        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
-        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
-        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
-        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
-        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
-        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
-        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
-        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
-        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
-        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
-        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
-        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
-        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
-        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
-        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
-        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
-        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
-        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
-        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
-        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
-        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
-        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
-        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
-        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
-        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
-        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
-        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
-        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
-        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
-        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
-        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
-        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
-        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
-        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
-        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
-        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
-        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
-        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
-        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
-        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
-        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
-        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
-        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
-        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
-        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
-        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
-        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
-        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
-        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
-        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
-        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
-        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
-        {0,9,255}
-    };
+static const code lenfix[512] = {
+    {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
+    {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
+    {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
+    {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
+    {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
+    {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
+    {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
+    {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
+    {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
+    {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
+    {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
+    {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
+    {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
+    {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
+    {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
+    {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
+    {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
+    {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+    {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
+    {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
+    {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
+    {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
+    {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
+    {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
+    {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
+    {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
+    {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
+    {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
+    {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
+    {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
+    {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
+    {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
+    {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
+    {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
+    {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
+    {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
+    {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
+    {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
+    {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
+    {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
+    {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
+    {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
+    {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
+    {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
+    {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
+    {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
+    {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
+    {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+    {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
+    {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
+    {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
+    {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
+    {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
+    {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
+    {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
+    {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
+    {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
+    {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
+    {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
+    {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
+    {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
+    {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
+    {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
+    {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
+    {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
+    {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+    {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
+    {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
+    {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
+    {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
+    {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
+    {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
+    {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
+    {0,9,255}
+};
 
-    static const code distfix[32] = {
-        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
-        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
-        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
-        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
-        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
-        {22,5,193},{64,5,0}
-    };
+static const code distfix[32] = {
+    {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
+    {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
+    {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
+    {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
+    {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
+    {22,5,193},{64,5,0}
+};
diff --git a/src/java.base/share/native/libzip/zlib/inflate.c b/src/java.base/share/native/libzip/zlib/inflate.c
index 3370cfe9565..c548f98f6de 100644
--- a/src/java.base/share/native/libzip/zlib/inflate.c
+++ b/src/java.base/share/native/libzip/zlib/inflate.c
@@ -23,7 +23,7 @@
  */
 
 /* inflate.c -- zlib decompression
- * Copyright (C) 1995-2022 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -109,12 +109,6 @@
 #include "inflate.h"
 #include "inffast.h"
 
-#ifdef MAKEFIXED
-#  ifndef BUILDFIXED
-#    define BUILDFIXED
-#  endif
-#endif
-
 local int inflateStateCheck(z_streamp strm) {
     struct inflate_state FAR *state;
     if (strm == Z_NULL ||
@@ -134,6 +128,7 @@ int ZEXPORT inflateResetKeep(z_streamp strm) {
     state = (struct inflate_state FAR *)strm->state;
     strm->total_in = strm->total_out = state->total = 0;
     strm->msg = Z_NULL;
+    strm->data_type = 0;
     if (state->wrap)        /* to support ill-conceived Java test suite */
         strm->adler = state->wrap & 1;
     state->mode = HEAD;
@@ -226,6 +221,7 @@ int ZEXPORT inflateInit2_(z_streamp strm, int windowBits,
     state = (struct inflate_state FAR *)
             ZALLOC(strm, 1, sizeof(struct inflate_state));
     if (state == Z_NULL) return Z_MEM_ERROR;
+    zmemzero(state, sizeof(struct inflate_state));
     Tracev((stderr, "inflate: allocated\n"));
     strm->state = (struct internal_state FAR *)state;
     state->strm = strm;
@@ -258,123 +254,11 @@ int ZEXPORT inflatePrime(z_streamp strm, int bits, int value) {
     }
     if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
     value &= (1L << bits) - 1;
-    state->hold += (unsigned)value << state->bits;
+    state->hold += (unsigned long)value << state->bits;
     state->bits += (uInt)bits;
     return Z_OK;
 }
 
-/*
-   Return state with length and distance decoding tables and index sizes set to
-   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
-   If BUILDFIXED is defined, then instead this routine builds the tables the
-   first time it's called, and returns those tables the first time and
-   thereafter.  This reduces the size of the code by about 2K bytes, in
-   exchange for a little execution time.  However, BUILDFIXED should not be
-   used for threaded applications, since the rewriting of the tables and virgin
-   may not be thread-safe.
- */
-local void fixedtables(struct inflate_state FAR *state) {
-#ifdef BUILDFIXED
-    static int virgin = 1;
-    static code *lenfix, *distfix;
-    static code fixed[544];
-
-    /* build fixed huffman tables if first call (may not be thread safe) */
-    if (virgin) {
-        unsigned sym, bits;
-        static code *next;
-
-        /* literal/length table */
-        sym = 0;
-        while (sym < 144) state->lens[sym++] = 8;
-        while (sym < 256) state->lens[sym++] = 9;
-        while (sym < 280) state->lens[sym++] = 7;
-        while (sym < 288) state->lens[sym++] = 8;
-        next = fixed;
-        lenfix = next;
-        bits = 9;
-        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
-
-        /* distance table */
-        sym = 0;
-        while (sym < 32) state->lens[sym++] = 5;
-        distfix = next;
-        bits = 5;
-        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
-
-        /* do this just once */
-        virgin = 0;
-    }
-#else /* !BUILDFIXED */
-#   include "inffixed.h"
-#endif /* BUILDFIXED */
-    state->lencode = lenfix;
-    state->lenbits = 9;
-    state->distcode = distfix;
-    state->distbits = 5;
-}
-
-#ifdef MAKEFIXED
-#include 
-
-/*
-   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
-   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
-   those tables to stdout, which would be piped to inffixed.h.  A small program
-   can simply call makefixed to do this:
-
-    void makefixed(void);
-
-    int main(void)
-    {
-        makefixed();
-        return 0;
-    }
-
-   Then that can be linked with zlib built with MAKEFIXED defined and run:
-
-    a.out > inffixed.h
- */
-void makefixed(void)
-{
-    unsigned low, size;
-    struct inflate_state state;
-
-    fixedtables(&state);
-    puts("    /* inffixed.h -- table for decoding fixed codes");
-    puts("     * Generated automatically by makefixed().");
-    puts("     */");
-    puts("");
-    puts("    /* WARNING: this file should *not* be used by applications.");
-    puts("       It is part of the implementation of this library and is");
-    puts("       subject to change. Applications should only use zlib.h.");
-    puts("     */");
-    puts("");
-    size = 1U << 9;
-    printf("    static const code lenfix[%u] = {", size);
-    low = 0;
-    for (;;) {
-        if ((low % 7) == 0) printf("\n        ");
-        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
-               state.lencode[low].bits, state.lencode[low].val);
-        if (++low == size) break;
-        putchar(',');
-    }
-    puts("\n    };");
-    size = 1U << 5;
-    printf("\n    static const code distfix[%u] = {", size);
-    low = 0;
-    for (;;) {
-        if ((low % 6) == 0) printf("\n        ");
-        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
-               state.distcode[low].val);
-        if (++low == size) break;
-        putchar(',');
-    }
-    puts("\n    };");
-}
-#endif /* MAKEFIXED */
-
 /*
    Update the window with the last wsize (normally 32K) bytes written before
    returning.  If window does not exist yet, create it.  This is only called
@@ -666,12 +550,12 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             if (
 #endif
                 ((BITS(8) << 8) + (hold >> 8)) % 31) {
-                strm->msg = (char *)"incorrect header check";
+                strm->msg = (z_const char *)"incorrect header check";
                 state->mode = BAD;
                 break;
             }
             if (BITS(4) != Z_DEFLATED) {
-                strm->msg = (char *)"unknown compression method";
+                strm->msg = (z_const char *)"unknown compression method";
                 state->mode = BAD;
                 break;
             }
@@ -680,7 +564,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             if (state->wbits == 0)
                 state->wbits = len;
             if (len > 15 || len > state->wbits) {
-                strm->msg = (char *)"invalid window size";
+                strm->msg = (z_const char *)"invalid window size";
                 state->mode = BAD;
                 break;
             }
@@ -696,12 +580,12 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             NEEDBITS(16);
             state->flags = (int)(hold);
             if ((state->flags & 0xff) != Z_DEFLATED) {
-                strm->msg = (char *)"unknown compression method";
+                strm->msg = (z_const char *)"unknown compression method";
                 state->mode = BAD;
                 break;
             }
             if (state->flags & 0xe000) {
-                strm->msg = (char *)"unknown header flags set";
+                strm->msg = (z_const char *)"unknown header flags set";
                 state->mode = BAD;
                 break;
             }
@@ -817,7 +701,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             if (state->flags & 0x0200) {
                 NEEDBITS(16);
                 if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
-                    strm->msg = (char *)"header crc mismatch";
+                    strm->msg = (z_const char *)"header crc mismatch";
                     state->mode = BAD;
                     break;
                 }
@@ -864,7 +748,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                 state->mode = STORED;
                 break;
             case 1:                             /* fixed block */
-                fixedtables(state);
+                inflate_fixed(state);
                 Tracev((stderr, "inflate:     fixed codes block%s\n",
                         state->last ? " (last)" : ""));
                 state->mode = LEN_;             /* decode codes */
@@ -878,8 +762,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                         state->last ? " (last)" : ""));
                 state->mode = TABLE;
                 break;
-            case 3:
-                strm->msg = (char *)"invalid block type";
+            default:
+                strm->msg = (z_const char *)"invalid block type";
                 state->mode = BAD;
             }
             DROPBITS(2);
@@ -888,7 +772,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             BYTEBITS();                         /* go to byte boundary */
             NEEDBITS(32);
             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
-                strm->msg = (char *)"invalid stored block lengths";
+                strm->msg = (z_const char *)"invalid stored block lengths";
                 state->mode = BAD;
                 break;
             }
@@ -929,7 +813,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             DROPBITS(4);
 #ifndef PKZIP_BUG_WORKAROUND
             if (state->nlen > 286 || state->ndist > 30) {
-                strm->msg = (char *)"too many length or distance symbols";
+                strm->msg = (z_const char *)
+                    "too many length or distance symbols";
                 state->mode = BAD;
                 break;
             }
@@ -947,12 +832,12 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             while (state->have < 19)
                 state->lens[order[state->have++]] = 0;
             state->next = state->codes;
-            state->lencode = (const code FAR *)(state->next);
+            state->lencode = state->distcode = (const code FAR *)(state->next);
             state->lenbits = 7;
             ret = inflate_table(CODES, state->lens, 19, &(state->next),
                                 &(state->lenbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid code lengths set";
+                strm->msg = (z_const char *)"invalid code lengths set";
                 state->mode = BAD;
                 break;
             }
@@ -976,7 +861,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                         NEEDBITS(here.bits + 2);
                         DROPBITS(here.bits);
                         if (state->have == 0) {
-                            strm->msg = (char *)"invalid bit length repeat";
+                            strm->msg = (z_const char *)
+                                "invalid bit length repeat";
                             state->mode = BAD;
                             break;
                         }
@@ -999,7 +885,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                         DROPBITS(7);
                     }
                     if (state->have + copy > state->nlen + state->ndist) {
-                        strm->msg = (char *)"invalid bit length repeat";
+                        strm->msg = (z_const char *)
+                            "invalid bit length repeat";
                         state->mode = BAD;
                         break;
                     }
@@ -1013,7 +900,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
 
             /* check for end-of-block code (better have one) */
             if (state->lens[256] == 0) {
-                strm->msg = (char *)"invalid code -- missing end-of-block";
+                strm->msg = (z_const char *)
+                    "invalid code -- missing end-of-block";
                 state->mode = BAD;
                 break;
             }
@@ -1027,7 +915,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
                                 &(state->lenbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid literal/lengths set";
+                strm->msg = (z_const char *)"invalid literal/lengths set";
                 state->mode = BAD;
                 break;
             }
@@ -1036,7 +924,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
                             &(state->next), &(state->distbits), state->work);
             if (ret) {
-                strm->msg = (char *)"invalid distances set";
+                strm->msg = (z_const char *)"invalid distances set";
                 state->mode = BAD;
                 break;
             }
@@ -1090,7 +978,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                 break;
             }
             if (here.op & 64) {
-                strm->msg = (char *)"invalid literal/length code";
+                strm->msg = (z_const char *)"invalid literal/length code";
                 state->mode = BAD;
                 break;
             }
@@ -1128,7 +1016,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             DROPBITS(here.bits);
             state->back += here.bits;
             if (here.op & 64) {
-                strm->msg = (char *)"invalid distance code";
+                strm->msg = (z_const char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
@@ -1145,7 +1033,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             }
 #ifdef INFLATE_STRICT
             if (state->offset > state->dmax) {
-                strm->msg = (char *)"invalid distance too far back";
+                strm->msg = (z_const char *)"invalid distance too far back";
                 state->mode = BAD;
                 break;
             }
@@ -1160,7 +1048,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                 copy = state->offset - copy;
                 if (copy > state->whave) {
                     if (state->sane) {
-                        strm->msg = (char *)"invalid distance too far back";
+                        strm->msg = (z_const char *)
+                            "invalid distance too far back";
                         state->mode = BAD;
                         break;
                     }
@@ -1219,7 +1108,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
                      state->flags ? hold :
 #endif
                      ZSWAP32(hold)) != state->check) {
-                    strm->msg = (char *)"incorrect data check";
+                    strm->msg = (z_const char *)"incorrect data check";
                     state->mode = BAD;
                     break;
                 }
@@ -1233,7 +1122,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) {
             if (state->wrap && state->flags) {
                 NEEDBITS(32);
                 if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
-                    strm->msg = (char *)"incorrect length check";
+                    strm->msg = (z_const char *)"incorrect length check";
                     state->mode = BAD;
                     break;
                 }
@@ -1464,7 +1353,6 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
     struct inflate_state FAR *state;
     struct inflate_state FAR *copy;
     unsigned char FAR *window;
-    unsigned wsize;
 
     /* check input */
     if (inflateStateCheck(source) || dest == Z_NULL)
@@ -1475,6 +1363,7 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
     copy = (struct inflate_state FAR *)
            ZALLOC(source, 1, sizeof(struct inflate_state));
     if (copy == Z_NULL) return Z_MEM_ERROR;
+    zmemzero(copy, sizeof(struct inflate_state));
     window = Z_NULL;
     if (state->window != Z_NULL) {
         window = (unsigned char FAR *)
@@ -1486,8 +1375,8 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
     }
 
     /* copy state */
-    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
-    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
+    zmemcpy(dest, source, sizeof(z_stream));
+    zmemcpy(copy, state, sizeof(struct inflate_state));
     copy->strm = dest;
     if (state->lencode >= state->codes &&
         state->lencode <= state->codes + ENOUGH - 1) {
@@ -1495,10 +1384,8 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {
         copy->distcode = copy->codes + (state->distcode - state->codes);
     }
     copy->next = copy->codes + (state->next - state->codes);
-    if (window != Z_NULL) {
-        wsize = 1U << state->wbits;
-        zmemcpy(window, state->window, wsize);
-    }
+    if (window != Z_NULL)
+        zmemcpy(window, state->window, state->whave);
     copy->window = window;
     dest->state = (struct internal_state FAR *)copy;
     return Z_OK;
diff --git a/src/java.base/share/native/libzip/zlib/inflate.h b/src/java.base/share/native/libzip/zlib/inflate.h
index 2cc56dd7fd4..7828fb5db38 100644
--- a/src/java.base/share/native/libzip/zlib/inflate.h
+++ b/src/java.base/share/native/libzip/zlib/inflate.h
@@ -124,7 +124,7 @@ struct inflate_state {
     unsigned char FAR *window;  /* allocated sliding window, if needed */
         /* bit accumulator */
     unsigned long hold;         /* input bit accumulator */
-    unsigned bits;              /* number of bits in "in" */
+    unsigned bits;              /* number of bits in hold */
         /* for string and stored block copying */
     unsigned length;            /* literal or length of data to copy */
     unsigned offset;            /* distance back to copy string from */
diff --git a/src/java.base/share/native/libzip/zlib/inftrees.c b/src/java.base/share/native/libzip/zlib/inftrees.c
index c4913bc4359..5f5d6b4baef 100644
--- a/src/java.base/share/native/libzip/zlib/inftrees.c
+++ b/src/java.base/share/native/libzip/zlib/inftrees.c
@@ -23,17 +23,31 @@
  */
 
 /* inftrees.c -- generate Huffman trees for efficient decoding
- * Copyright (C) 1995-2024 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
+#ifdef MAKEFIXED
+#  ifndef BUILDFIXED
+#    define BUILDFIXED
+#  endif
+#endif
+#ifdef BUILDFIXED
+#  define Z_ONCE
+#endif
+
 #include "zutil.h"
 #include "inftrees.h"
+#include "inflate.h"
+
+#ifndef NULL
+#  define NULL 0
+#endif
 
 #define MAXBITS 15
 
 const char inflate_copyright[] =
-   " inflate 1.3.1 Copyright 1995-2024 Mark Adler ";
+   " inflate 1.3.2 Copyright 1995-2026 Mark Adler ";
 /*
   If you use the zlib library in a product, an acknowledgment is welcome
   in the documentation of your product. If for some reason you cannot
@@ -71,9 +85,9 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
     unsigned mask;              /* mask for low root bits */
     code here;                  /* table entry for duplication */
     code FAR *next;             /* next available space in table */
-    const unsigned short FAR *base;     /* base value table to use */
-    const unsigned short FAR *extra;    /* extra bits table to use */
-    unsigned match;             /* use base and extra for symbol >= match */
+    const unsigned short FAR *base = NULL;  /* base value table to use */
+    const unsigned short FAR *extra = NULL; /* extra bits table to use */
+    unsigned match = 0;         /* use base and extra for symbol >= match */
     unsigned short count[MAXBITS+1];    /* number of codes of each length */
     unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
     static const unsigned short lbase[31] = { /* Length codes 257..285 base */
@@ -81,7 +95,7 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
     static const unsigned short lext[31] = { /* Length codes 257..285 extra */
         16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
-        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 77};
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 75};
     static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
@@ -199,7 +213,6 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
     /* set up for code type */
     switch (type) {
     case CODES:
-        base = extra = work;    /* dummy value--not used */
         match = 20;
         break;
     case LENS:
@@ -207,10 +220,9 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
         extra = lext;
         match = 257;
         break;
-    default:    /* DISTS */
+    case DISTS:
         base = dbase;
         extra = dext;
-        match = 0;
     }
 
     /* initialize state for loop */
@@ -321,3 +333,116 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
     *bits = root;
     return 0;
 }
+
+#ifdef BUILDFIXED
+/*
+  If this is compiled with BUILDFIXED defined, and if inflate will be used in
+  multiple threads, and if atomics are not available, then inflate() must be
+  called with a fixed block (e.g. 0x03 0x00) to initialize the tables and must
+  return before any other threads are allowed to call inflate.
+ */
+
+static code *lenfix, *distfix;
+static code fixed[544];
+
+/* State for z_once(). */
+local z_once_t built = Z_ONCE_INIT;
+
+local void buildtables(void) {
+    unsigned sym, bits;
+    static code *next;
+    unsigned short lens[288], work[288];
+
+    /* literal/length table */
+    sym = 0;
+    while (sym < 144) lens[sym++] = 8;
+    while (sym < 256) lens[sym++] = 9;
+    while (sym < 280) lens[sym++] = 7;
+    while (sym < 288) lens[sym++] = 8;
+    next = fixed;
+    lenfix = next;
+    bits = 9;
+    inflate_table(LENS, lens, 288, &(next), &(bits), work);
+
+    /* distance table */
+    sym = 0;
+    while (sym < 32) lens[sym++] = 5;
+    distfix = next;
+    bits = 5;
+    inflate_table(DISTS, lens, 32, &(next), &(bits), work);
+}
+#else /* !BUILDFIXED */
+#  include "inffixed.h"
+#endif /* BUILDFIXED */
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications if atomics are not available, as it will
+   not be thread-safe.
+ */
+void inflate_fixed(struct inflate_state FAR *state) {
+#ifdef BUILDFIXED
+    z_once(&built, buildtables);
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+#ifdef MAKEFIXED
+#include 
+
+/*
+   Write out the inffixed.h that will be #include'd above.  Defining MAKEFIXED
+   also defines BUILDFIXED, so the tables are built on the fly.  main() writes
+   those tables to stdout, which would directed to inffixed.h. Compile this
+   along with zutil.c:
+
+       cc -DMAKEFIXED -o fix inftrees.c zutil.c
+       ./fix > inffixed.h
+ */
+int main(void) {
+    unsigned low, size;
+    struct inflate_state state;
+
+    inflate_fixed(&state);
+    puts("/* inffixed.h -- table for decoding fixed codes");
+    puts(" * Generated automatically by makefixed().");
+    puts(" */");
+    puts("");
+    puts("/* WARNING: this file should *not* be used by applications.");
+    puts("   It is part of the implementation of this library and is");
+    puts("   subject to change. Applications should only use zlib.h.");
+    puts(" */");
+    puts("");
+    size = 1U << 9;
+    printf("static const code lenfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 7) == 0) printf("\n    ");
+        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
+               state.lencode[low].bits, state.lencode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n};");
+    size = 1U << 5;
+    printf("\nstatic const code distfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 6) == 0) printf("\n    ");
+        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
+               state.distcode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n};");
+    return 0;
+}
+#endif /* MAKEFIXED */
diff --git a/src/java.base/share/native/libzip/zlib/inftrees.h b/src/java.base/share/native/libzip/zlib/inftrees.h
index 3e2e889301d..b9b4fc2fb2b 100644
--- a/src/java.base/share/native/libzip/zlib/inftrees.h
+++ b/src/java.base/share/native/libzip/zlib/inftrees.h
@@ -23,7 +23,7 @@
  */
 
 /* inftrees.h -- header to use inftrees.c
- * Copyright (C) 1995-2005, 2010 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -84,3 +84,5 @@ typedef enum {
 int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
                                 unsigned codes, code FAR * FAR *table,
                                 unsigned FAR *bits, unsigned short FAR *work);
+struct inflate_state;
+void ZLIB_INTERNAL inflate_fixed(struct inflate_state FAR *state);
diff --git a/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java b/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
index 3296c5f2fad..dfde58f0122 100644
--- a/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
+++ b/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java
@@ -1,4 +1,4 @@
-Changes from zlib 1.3.1
+Changes in JDK's in-tree zlib compared to upstream zlib 1.3.2
 
 (1) renamed adler32.c -> zadler32.c, crc32c -> zcrc32.c
 
diff --git a/src/java.base/share/native/libzip/zlib/trees.c b/src/java.base/share/native/libzip/zlib/trees.c
index bbfa9deee5b..cc7b136bcf6 100644
--- a/src/java.base/share/native/libzip/zlib/trees.c
+++ b/src/java.base/share/native/libzip/zlib/trees.c
@@ -23,7 +23,7 @@
  */
 
 /* trees.c -- output deflated data using Huffman coding
- * Copyright (C) 1995-2024 Jean-loup Gailly
+ * Copyright (C) 1995-2026 Jean-loup Gailly
  * detect_data_type() function provided freely by Cosmin Truta, 2006
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
@@ -136,7 +136,7 @@ local int base_dist[D_CODES];
 
 #else
 #  include "trees.h"
-#endif /* GEN_TREES_H */
+#endif /* defined(GEN_TREES_H) || !defined(STDC) */
 
 struct static_tree_desc_s {
     const ct_data *static_tree;  /* static tree or NULL */
@@ -176,7 +176,7 @@ local TCONST static_tree_desc static_bl_desc =
  * IN assertion: 1 <= len <= 15
  */
 local unsigned bi_reverse(unsigned code, int len) {
-    register unsigned res = 0;
+    unsigned res = 0;
     do {
         res |= code & 1;
         code >>= 1, res <<= 1;
@@ -208,10 +208,11 @@ local void bi_windup(deflate_state *s) {
     } else if (s->bi_valid > 0) {
         put_byte(s, (Byte)s->bi_buf);
     }
+    s->bi_used = ((s->bi_valid - 1) & 7) + 1;
     s->bi_buf = 0;
     s->bi_valid = 0;
 #ifdef ZLIB_DEBUG
-    s->bits_sent = (s->bits_sent + 7) & ~7;
+    s->bits_sent = (s->bits_sent + 7) & ~(ulg)7;
 #endif
 }
 
@@ -490,6 +491,7 @@ void ZLIB_INTERNAL _tr_init(deflate_state *s) {
 
     s->bi_buf = 0;
     s->bi_valid = 0;
+    s->bi_used = 0;
 #ifdef ZLIB_DEBUG
     s->compressed_len = 0L;
     s->bits_sent = 0L;
@@ -748,7 +750,7 @@ local void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
         if (++count < max_count && curlen == nextlen) {
             continue;
         } else if (count < min_count) {
-            s->bl_tree[curlen].Freq += count;
+            s->bl_tree[curlen].Freq += (ush)count;
         } else if (curlen != 0) {
             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
             s->bl_tree[REP_3_6].Freq++;
@@ -841,7 +843,7 @@ local int build_bl_tree(deflate_state *s) {
     }
     /* Update opt_len to include the bit length tree and counts */
     s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4;
-    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
+    Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu",
             s->opt_len, s->static_len));
 
     return max_blindex;
@@ -867,13 +869,13 @@ local void send_all_trees(deflate_state *s, int lcodes, int dcodes,
         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
     }
-    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
+    Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent));
 
     send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1);  /* literal tree */
-    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
+    Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent));
 
     send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1);  /* distance tree */
-    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
+    Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent));
 }
 
 /* ===========================================================================
@@ -956,7 +958,7 @@ local void compress_block(deflate_state *s, const ct_data *ltree,
             extra = extra_dbits[code];
             if (extra != 0) {
                 dist -= (unsigned)base_dist[code];
-                send_bits(s, dist, extra);   /* send the extra distance bits */
+                send_bits(s, (int)dist, extra); /* send the extra bits */
             }
         } /* literal or match pair ? */
 
@@ -1030,11 +1032,11 @@ void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
 
         /* Construct the literal and distance trees */
         build_tree(s, (tree_desc *)(&(s->l_desc)));
-        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
+        Tracev((stderr, "\nlit data: dyn %lu, stat %lu", s->opt_len,
                 s->static_len));
 
         build_tree(s, (tree_desc *)(&(s->d_desc)));
-        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
+        Tracev((stderr, "\ndist data: dyn %lu, stat %lu", s->opt_len,
                 s->static_len));
         /* At this point, opt_len and static_len are the total bit lengths of
          * the compressed block data, excluding the tree representations.
@@ -1107,7 +1109,7 @@ void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
 #endif
     }
     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3,
-           s->compressed_len - 7*last));
+           s->compressed_len - 7*(ulg)last));
 }
 
 /* ===========================================================================
diff --git a/src/java.base/share/native/libzip/zlib/uncompr.c b/src/java.base/share/native/libzip/zlib/uncompr.c
index 219c1d264d5..25da59461c3 100644
--- a/src/java.base/share/native/libzip/zlib/uncompr.c
+++ b/src/java.base/share/native/libzip/zlib/uncompr.c
@@ -23,7 +23,7 @@
  */
 
 /* uncompr.c -- decompress a memory buffer
- * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler
+ * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -47,24 +47,24 @@
    memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
    Z_DATA_ERROR if the input data was corrupted, including if the input data is
    an incomplete zlib stream.
+
+     The _z versions of the functions take size_t length arguments.
 */
-int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
-                        uLong *sourceLen) {
+int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
+                          z_size_t *sourceLen) {
     z_stream stream;
     int err;
     const uInt max = (uInt)-1;
-    uLong len, left;
-    Byte buf[1];    /* for detection of incomplete stream when *destLen == 0 */
+    z_size_t len, left;
+
+    if (sourceLen == NULL || (*sourceLen > 0 && source == NULL) ||
+        destLen == NULL || (*destLen > 0 && dest == NULL))
+        return Z_STREAM_ERROR;
 
     len = *sourceLen;
-    if (*destLen) {
-        left = *destLen;
-        *destLen = 0;
-    }
-    else {
-        left = 1;
-        dest = buf;
-    }
+    left = *destLen;
+    if (left == 0 && dest == Z_NULL)
+        dest = (Bytef *)&stream.reserved;       /* next_out cannot be NULL */
 
     stream.next_in = (z_const Bytef *)source;
     stream.avail_in = 0;
@@ -80,30 +80,46 @@ int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
 
     do {
         if (stream.avail_out == 0) {
-            stream.avail_out = left > (uLong)max ? max : (uInt)left;
+            stream.avail_out = left > (z_size_t)max ? max : (uInt)left;
             left -= stream.avail_out;
         }
         if (stream.avail_in == 0) {
-            stream.avail_in = len > (uLong)max ? max : (uInt)len;
+            stream.avail_in = len > (z_size_t)max ? max : (uInt)len;
             len -= stream.avail_in;
         }
         err = inflate(&stream, Z_NO_FLUSH);
     } while (err == Z_OK);
 
-    *sourceLen -= len + stream.avail_in;
-    if (dest != buf)
-        *destLen = stream.total_out;
-    else if (stream.total_out && err == Z_BUF_ERROR)
-        left = 1;
+    /* Set len and left to the unused input data and unused output space. Set
+       *sourceLen to the amount of input consumed. Set *destLen to the amount
+       of data produced. */
+    len += stream.avail_in;
+    left += stream.avail_out;
+    *sourceLen -= len;
+    *destLen -= left;
 
     inflateEnd(&stream);
     return err == Z_STREAM_END ? Z_OK :
            err == Z_NEED_DICT ? Z_DATA_ERROR  :
-           err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
+           err == Z_BUF_ERROR && len == 0 ? Z_DATA_ERROR :
            err;
 }
-
+int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
+                        uLong *sourceLen) {
+    int ret;
+    z_size_t got = *destLen, used = *sourceLen;
+    ret = uncompress2_z(dest, &got, source, &used);
+    *sourceLen = (uLong)used;
+    *destLen = (uLong)got;
+    return ret;
+}
+int ZEXPORT uncompress_z(Bytef *dest, z_size_t *destLen, const Bytef *source,
+                         z_size_t sourceLen) {
+    z_size_t used = sourceLen;
+    return uncompress2_z(dest, destLen, source, &used);
+}
 int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, const Bytef *source,
                        uLong sourceLen) {
-    return uncompress2(dest, destLen, source, &sourceLen);
+    uLong used = sourceLen;
+    return uncompress2(dest, destLen, source, &used);
 }
diff --git a/src/java.base/share/native/libzip/zlib/zconf.h b/src/java.base/share/native/libzip/zlib/zconf.h
index 46204222f5d..d4589739a0a 100644
--- a/src/java.base/share/native/libzip/zlib/zconf.h
+++ b/src/java.base/share/native/libzip/zlib/zconf.h
@@ -23,7 +23,7 @@
  */
 
 /* zconf.h -- configuration of the zlib compression library
- * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler
+ * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -57,7 +57,10 @@
 #  ifndef Z_SOLO
 #    define compress              z_compress
 #    define compress2             z_compress2
+#    define compress_z            z_compress_z
+#    define compress2_z           z_compress2_z
 #    define compressBound         z_compressBound
+#    define compressBound_z       z_compressBound_z
 #  endif
 #  define crc32                 z_crc32
 #  define crc32_combine         z_crc32_combine
@@ -68,6 +71,7 @@
 #  define crc32_z               z_crc32_z
 #  define deflate               z_deflate
 #  define deflateBound          z_deflateBound
+#  define deflateBound_z        z_deflateBound_z
 #  define deflateCopy           z_deflateCopy
 #  define deflateEnd            z_deflateEnd
 #  define deflateGetDictionary  z_deflateGetDictionary
@@ -83,6 +87,7 @@
 #  define deflateSetDictionary  z_deflateSetDictionary
 #  define deflateSetHeader      z_deflateSetHeader
 #  define deflateTune           z_deflateTune
+#  define deflateUsed           z_deflateUsed
 #  define deflate_copyright     z_deflate_copyright
 #  define get_crc_table         z_get_crc_table
 #  ifndef Z_SOLO
@@ -152,9 +157,12 @@
 #  define inflate_copyright     z_inflate_copyright
 #  define inflate_fast          z_inflate_fast
 #  define inflate_table         z_inflate_table
+#  define inflate_fixed         z_inflate_fixed
 #  ifndef Z_SOLO
 #    define uncompress            z_uncompress
 #    define uncompress2           z_uncompress2
+#    define uncompress_z          z_uncompress_z
+#    define uncompress2_z         z_uncompress2_z
 #  endif
 #  define zError                z_zError
 #  ifndef Z_SOLO
@@ -258,10 +266,12 @@
 #  endif
 #endif
 
-#if defined(ZLIB_CONST) && !defined(z_const)
-#  define z_const const
-#else
-#  define z_const
+#ifndef z_const
+#  ifdef ZLIB_CONST
+#    define z_const const
+#  else
+#    define z_const
+#  endif
 #endif
 
 #ifdef Z_SOLO
@@ -457,11 +467,11 @@ typedef uLong FAR uLongf;
    typedef unsigned long z_crc_t;
 #endif
 
-#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#if HAVE_UNISTD_H-0     /* may be set to #if 1 by ./configure */
 #  define Z_HAVE_UNISTD_H
 #endif
 
-#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#if HAVE_STDARG_H-0     /* may be set to #if 1 by ./configure */
 #  define Z_HAVE_STDARG_H
 #endif
 
@@ -494,12 +504,8 @@ typedef uLong FAR uLongf;
 #endif
 
 #ifndef Z_HAVE_UNISTD_H
-#  ifdef __WATCOMC__
-#    define Z_HAVE_UNISTD_H
-#  endif
-#endif
-#ifndef Z_HAVE_UNISTD_H
-#  if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32)
+#  if defined(__WATCOMC__) || defined(__GO32__) || \
+      (defined(_LARGEFILE64_SOURCE) && !defined(_WIN32))
 #    define Z_HAVE_UNISTD_H
 #  endif
 #endif
@@ -534,17 +540,19 @@ typedef uLong FAR uLongf;
 #endif
 
 #ifndef z_off_t
-#  define z_off_t long
+#  define z_off_t long long
 #endif
 
 #if !defined(_WIN32) && defined(Z_LARGE64)
 #  define z_off64_t off64_t
+#elif defined(__MINGW32__)
+#  define z_off64_t long long
+#elif defined(_WIN32) && !defined(__GNUC__)
+#  define z_off64_t __int64
+#elif defined(__GO32__)
+#  define z_off64_t offset_t
 #else
-#  if defined(_WIN32) && !defined(__GNUC__)
-#    define z_off64_t __int64
-#  else
-#    define z_off64_t z_off_t
-#  endif
+#  define z_off64_t z_off_t
 #endif
 
 /* MVS linker does not support external names larger than 8 bytes */
diff --git a/src/java.base/share/native/libzip/zlib/zcrc32.c b/src/java.base/share/native/libzip/zlib/zcrc32.c
index 3f918f76b7c..133cbe158aa 100644
--- a/src/java.base/share/native/libzip/zlib/zcrc32.c
+++ b/src/java.base/share/native/libzip/zlib/zcrc32.c
@@ -23,7 +23,7 @@
  */
 
 /* crc32.c -- compute the CRC-32 of a data stream
- * Copyright (C) 1995-2022 Mark Adler
+ * Copyright (C) 1995-2026 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  *
  * This interleaved implementation of a CRC makes use of pipelined multiple
@@ -48,11 +48,18 @@
 #  include 
 #  ifndef DYNAMIC_CRC_TABLE
 #    define DYNAMIC_CRC_TABLE
-#  endif /* !DYNAMIC_CRC_TABLE */
-#endif /* MAKECRCH */
+#  endif
+#endif
+#ifdef DYNAMIC_CRC_TABLE
+#  define Z_ONCE
+#endif
 
 #include "zutil.h"      /* for Z_U4, Z_U8, z_crc_t, and FAR definitions */
 
+#ifdef HAVE_S390X_VX
+#  include "contrib/crc32vx/crc32_vx_hooks.h"
+#endif
+
  /*
   A CRC of a message is computed on N braids of words in the message, where
   each word consists of W bytes (4 or 8). If N is 3, for example, then three
@@ -123,7 +130,8 @@
 #endif
 
 /* If available, use the ARM processor CRC32 instruction. */
-#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && W == 8
+#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && \
+    defined(W) && W == 8
 #  define ARMCRC32
 #endif
 
@@ -176,10 +184,10 @@ local z_word_t byte_swap(z_word_t word) {
   Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial,
   reflected. For speed, this requires that a not be zero.
  */
-local z_crc_t multmodp(z_crc_t a, z_crc_t b) {
-    z_crc_t m, p;
+local uLong multmodp(uLong a, uLong b) {
+    uLong m, p;
 
-    m = (z_crc_t)1 << 31;
+    m = (uLong)1 << 31;
     p = 0;
     for (;;) {
         if (a & m) {
@@ -195,12 +203,12 @@ local z_crc_t multmodp(z_crc_t a, z_crc_t b) {
 
 /*
   Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been
-  initialized.
+  initialized. n must not be negative.
  */
-local z_crc_t x2nmodp(z_off64_t n, unsigned k) {
-    z_crc_t p;
+local uLong x2nmodp(z_off64_t n, unsigned k) {
+    uLong p;
 
-    p = (z_crc_t)1 << 31;           /* x^0 == 1 */
+    p = (uLong)1 << 31;             /* x^0 == 1 */
     while (n) {
         if (n & 1)
             p = multmodp(x2n_table[k & 31], p);
@@ -228,83 +236,8 @@ local z_crc_t FAR crc_table[256];
    local void write_table64(FILE *, const z_word_t FAR *, int);
 #endif /* MAKECRCH */
 
-/*
-  Define a once() function depending on the availability of atomics. If this is
-  compiled with DYNAMIC_CRC_TABLE defined, and if CRCs will be computed in
-  multiple threads, and if atomics are not available, then get_crc_table() must
-  be called to initialize the tables and must return before any threads are
-  allowed to compute or combine CRCs.
- */
-
-/* Definition of once functionality. */
-typedef struct once_s once_t;
-
-/* Check for the availability of atomics. */
-#if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \
-    !defined(__STDC_NO_ATOMICS__)
-
-#include 
-
-/* Structure for once(), which must be initialized with ONCE_INIT. */
-struct once_s {
-    atomic_flag begun;
-    atomic_int done;
-};
-#define ONCE_INIT {ATOMIC_FLAG_INIT, 0}
-
-/*
-  Run the provided init() function exactly once, even if multiple threads
-  invoke once() at the same time. The state must be a once_t initialized with
-  ONCE_INIT.
- */
-local void once(once_t *state, void (*init)(void)) {
-    if (!atomic_load(&state->done)) {
-        if (atomic_flag_test_and_set(&state->begun))
-            while (!atomic_load(&state->done))
-                ;
-        else {
-            init();
-            atomic_store(&state->done, 1);
-        }
-    }
-}
-
-#else   /* no atomics */
-
-/* Structure for once(), which must be initialized with ONCE_INIT. */
-struct once_s {
-    volatile int begun;
-    volatile int done;
-};
-#define ONCE_INIT {0, 0}
-
-/* Test and set. Alas, not atomic, but tries to minimize the period of
-   vulnerability. */
-local int test_and_set(int volatile *flag) {
-    int was;
-
-    was = *flag;
-    *flag = 1;
-    return was;
-}
-
-/* Run the provided init() function once. This is not thread-safe. */
-local void once(once_t *state, void (*init)(void)) {
-    if (!state->done) {
-        if (test_and_set(&state->begun))
-            while (!state->done)
-                ;
-        else {
-            init();
-            state->done = 1;
-        }
-    }
-}
-
-#endif
-
 /* State for once(). */
-local once_t made = ONCE_INIT;
+local z_once_t made = Z_ONCE_INIT;
 
 /*
   Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
@@ -350,7 +283,7 @@ local void make_crc_table(void) {
     p = (z_crc_t)1 << 30;         /* x^1 */
     x2n_table[0] = p;
     for (n = 1; n < 32; n++)
-        x2n_table[n] = p = multmodp(p, p);
+        x2n_table[n] = p = (z_crc_t)multmodp(p, p);
 
 #ifdef W
     /* initialize the braiding tables -- needs x2n_table[] */
@@ -553,11 +486,11 @@ local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) {
     int k;
     z_crc_t i, p, q;
     for (k = 0; k < w; k++) {
-        p = x2nmodp((n * w + 3 - k) << 3, 0);
+        p = (z_crc_t)x2nmodp((n * w + 3 - k) << 3, 0);
         ltl[k][0] = 0;
         big[w - 1 - k][0] = 0;
         for (i = 1; i < 256; i++) {
-            ltl[k][i] = q = multmodp(i << 24, p);
+            ltl[k][i] = q = (z_crc_t)multmodp(i << 24, p);
             big[w - 1 - k][i] = byte_swap(q);
         }
     }
@@ -572,7 +505,7 @@ local void braid(z_crc_t ltl[][256], z_word_t big[][256], int n, int w) {
  */
 const z_crc_t FAR * ZEXPORT get_crc_table(void) {
 #ifdef DYNAMIC_CRC_TABLE
-    once(&made, make_crc_table);
+    z_once(&made, make_crc_table);
 #endif /* DYNAMIC_CRC_TABLE */
     return (const z_crc_t FAR *)crc_table;
 }
@@ -596,9 +529,8 @@ const z_crc_t FAR * ZEXPORT get_crc_table(void) {
 #define Z_BATCH_ZEROS 0xa10d3d0c    /* computed from Z_BATCH = 3990 */
 #define Z_BATCH_MIN 800             /* fewest words in a final batch */
 
-unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf,
-                              z_size_t len) {
-    z_crc_t val;
+uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) {
+    uLong val;
     z_word_t crc1, crc2;
     const z_word_t *word;
     z_word_t val0, val1, val2;
@@ -609,7 +541,7 @@ unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf,
     if (buf == Z_NULL) return 0;
 
 #ifdef DYNAMIC_CRC_TABLE
-    once(&made, make_crc_table);
+    z_once(&made, make_crc_table);
 #endif /* DYNAMIC_CRC_TABLE */
 
     /* Pre-condition the CRC */
@@ -664,7 +596,7 @@ unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf,
         }
         word += 3 * last;
         num -= 3 * last;
-        val = x2nmodp(last, 6);
+        val = x2nmodp((int)last, 6);
         crc = multmodp(val, crc) ^ crc1;
         crc = multmodp(val, crc) ^ crc2;
     }
@@ -715,13 +647,12 @@ local z_word_t crc_word_big(z_word_t data) {
 #endif
 
 /* ========================================================================= */
-unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf,
-                              z_size_t len) {
+uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) {
     /* Return initial CRC, if requested. */
     if (buf == Z_NULL) return 0;
 
 #ifdef DYNAMIC_CRC_TABLE
-    once(&made, make_crc_table);
+    z_once(&made, make_crc_table);
 #endif /* DYNAMIC_CRC_TABLE */
 
     /* Pre-condition the CRC */
@@ -1036,28 +967,19 @@ unsigned long ZEXPORT crc32_z(unsigned long crc, const unsigned char FAR *buf,
 #endif
 
 /* ========================================================================= */
-unsigned long ZEXPORT crc32(unsigned long crc, const unsigned char FAR *buf,
-                            uInt len) {
+uLong ZEXPORT crc32(uLong crc, const unsigned char FAR *buf, uInt len) {
+    #ifdef HAVE_S390X_VX
+    return crc32_z_hook(crc, buf, len);
+    #endif
     return crc32_z(crc, buf, len);
 }
 
-/* ========================================================================= */
-uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) {
-#ifdef DYNAMIC_CRC_TABLE
-    once(&made, make_crc_table);
-#endif /* DYNAMIC_CRC_TABLE */
-    return multmodp(x2nmodp(len2, 3), crc1) ^ (crc2 & 0xffffffff);
-}
-
-/* ========================================================================= */
-uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) {
-    return crc32_combine64(crc1, crc2, (z_off64_t)len2);
-}
-
 /* ========================================================================= */
 uLong ZEXPORT crc32_combine_gen64(z_off64_t len2) {
+    if (len2 < 0)
+        return 0;
 #ifdef DYNAMIC_CRC_TABLE
-    once(&made, make_crc_table);
+    z_once(&made, make_crc_table);
 #endif /* DYNAMIC_CRC_TABLE */
     return x2nmodp(len2, 3);
 }
@@ -1069,5 +991,17 @@ uLong ZEXPORT crc32_combine_gen(z_off_t len2) {
 
 /* ========================================================================= */
 uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) {
-    return multmodp(op, crc1) ^ (crc2 & 0xffffffff);
+    if (op == 0)
+        return 0;
+    return multmodp(op, crc1 & 0xffffffff) ^ (crc2 & 0xffffffff);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, z_off64_t len2) {
+    return crc32_combine_op(crc1, crc2, crc32_combine_gen64(len2));
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2) {
+    return crc32_combine64(crc1, crc2, (z_off64_t)len2);
 }
diff --git a/src/java.base/share/native/libzip/zlib/zlib.h b/src/java.base/share/native/libzip/zlib/zlib.h
index 07496b5f981..90230f4f23f 100644
--- a/src/java.base/share/native/libzip/zlib/zlib.h
+++ b/src/java.base/share/native/libzip/zlib/zlib.h
@@ -23,9 +23,9 @@
  */
 
 /* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.3.1, January 22nd, 2024
+  version 1.3.2, February 17th, 2026
 
-  Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
+  Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -48,24 +48,28 @@
 
 
   The data format used by the zlib library is described by RFCs (Request for
-  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
+  Comments) 1950 to 1952 at https://datatracker.ietf.org/doc/html/rfc1950
   (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
 */
 
 #ifndef ZLIB_H
 #define ZLIB_H
 
-#include "zconf.h"
+#ifdef ZLIB_BUILD
+#  include 
+#else
+# include "zconf.h"
+#endif
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#define ZLIB_VERSION "1.3.1"
-#define ZLIB_VERNUM 0x1310
+#define ZLIB_VERSION "1.3.2"
+#define ZLIB_VERNUM 0x1320
 #define ZLIB_VER_MAJOR 1
 #define ZLIB_VER_MINOR 3
-#define ZLIB_VER_REVISION 1
+#define ZLIB_VER_REVISION 2
 #define ZLIB_VER_SUBREVISION 0
 
 /*
@@ -465,7 +469,7 @@ ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush);
 
     The Z_BLOCK option assists in appending to or combining deflate streams.
   To assist in this, on return inflate() always sets strm->data_type to the
-  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  number of unused bits in the input taken from strm->next_in, plus 64 if
   inflate() is currently decoding the last block in the deflate stream, plus
   128 if inflate() returned immediately after decoding an end-of-block code or
   decoding the complete header up to just before the first byte of the deflate
@@ -611,18 +615,21 @@ ZEXTERN int ZEXPORT deflateInit2(z_streamp strm,
 
      The strategy parameter is used to tune the compression algorithm.  Use the
    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
-   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
-   string match), or Z_RLE to limit match distances to one (run-length
-   encoding).  Filtered data consists mostly of small values with a somewhat
-   random distribution.  In this case, the compression algorithm is tuned to
-   compress them better.  The effect of Z_FILTERED is to force more Huffman
-   coding and less string matching; it is somewhat intermediate between
-   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
-   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
-   strategy parameter only affects the compression ratio but not the
-   correctness of the compressed output even if it is not set appropriately.
-   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
-   decoder for special applications.
+   filter (or predictor), Z_RLE to limit match distances to one (run-length
+   encoding), or Z_HUFFMAN_ONLY to force Huffman encoding only (no string
+   matching).  Filtered data consists mostly of small values with a somewhat
+   random distribution, as produced by the PNG filters.  In this case, the
+   compression algorithm is tuned to compress them better.  The effect of
+   Z_FILTERED is to force more Huffman coding and less string matching than the
+   default; it is intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.
+   Z_RLE is almost as fast as Z_HUFFMAN_ONLY, but should give better
+   compression for PNG image data than Huffman only.  The degree of string
+   matching from most to none is: Z_DEFAULT_STRATEGY, Z_FILTERED, Z_RLE, then
+   Z_HUFFMAN_ONLY. The strategy parameter affects the compression ratio but
+   never the correctness of the compressed output, even if it is not set
+   optimally for the given data.  Z_FIXED uses the default string matching, but
+   prevents the use of dynamic Huffman codes, allowing for a simpler decoder
+   for special applications.
 
      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
    memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
@@ -782,8 +789,8 @@ ZEXTERN int ZEXPORT deflateTune(z_streamp strm,
    returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  */
 
-ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm,
-                                   uLong sourceLen);
+ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen);
+ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
 /*
      deflateBound() returns an upper bound on the compressed size after
    deflation of sourceLen bytes.  It must be called after deflateInit() or
@@ -795,6 +802,9 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm,
    to return Z_STREAM_END.  Note that it is possible for the compressed size to
    be larger than the value returned by deflateBound() if flush options other
    than Z_FINISH or Z_NO_FLUSH are used.
+
+     delfateBound_z() is the same, but takes and returns a size_t length.  Note
+   that a long is 32 bits on Windows.
 */
 
 ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
@@ -809,6 +819,21 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
    or bits are Z_NULL, then those values are not set.
 
      deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.  If an int is 16 bits and memLevel is 9, then
+   it is possible for the number of pending bytes to not fit in an unsigned. In
+   that case Z_BUF_ERROR is returned and *pending is set to the maximum value
+   of an unsigned.
+ */
+
+ZEXTERN int ZEXPORT deflateUsed(z_streamp strm,
+                                int *bits);
+/*
+     deflateUsed() returns in *bits the most recent number of deflate bits used
+   in the last byte when flushing to a byte boundary. The result is in 1..8, or
+   0 if there has not yet been a flush. This helps determine the location of
+   the last bit of a deflate stream.
+
+     deflateUsed returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
  */
 
@@ -1011,13 +1036,15 @@ ZEXTERN int ZEXPORT inflatePrime(z_streamp strm,
                                  int bits,
                                  int value);
 /*
-     This function inserts bits in the inflate input stream.  The intent is
-   that this function is used to start inflating at a bit position in the
-   middle of a byte.  The provided bits will be used before any bytes are used
-   from next_in.  This function should only be used with raw inflate, and
-   should be used before the first inflate() call after inflateInit2() or
-   inflateReset().  bits must be less than or equal to 16, and that many of the
-   least significant bits of value will be inserted in the input.
+     This function inserts bits in the inflate input stream.  The intent is to
+   use inflatePrime() to start inflating at a bit position in the middle of a
+   byte.  The provided bits will be used before any bytes are used from
+   next_in.  This function should be used with raw inflate, before the first
+   inflate() call, after inflateInit2() or inflateReset().  It can also be used
+   after an inflate() return indicates the end of a deflate block or header
+   when using Z_BLOCK.  bits must be less than or equal to 16, and that many of
+   the least significant bits of value will be inserted in the input.  The
+   other bits in value can be non-zero, and will be ignored.
 
      If bits is negative, then the input stream bit buffer is emptied.  Then
    inflatePrime() can be called again to put bits in the buffer.  This is used
@@ -1025,7 +1052,15 @@ ZEXTERN int ZEXPORT inflatePrime(z_streamp strm,
    to feeding inflate codes.
 
      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent.
+   stream state was inconsistent, or if bits is out of range.  If inflate was
+   in the middle of processing a header, trailer, or stored block lengths, then
+   it is possible for there to be only eight bits available in the bit buffer.
+   In that case, bits > 8 is considered out of range.  However, when used as
+   outlined above, there will always be 16 bits available in the buffer for
+   insertion.  As noted in its documentation above, inflate records the number
+   of bits in the bit buffer on return in data_type. 32 minus that is the
+   number of bits available for insertion.  inflatePrime does not update
+   data_type with the new number of bits in buffer.
 */
 
 ZEXTERN long ZEXPORT inflateMark(z_streamp strm);
@@ -1071,20 +1106,22 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
 
      The text, time, xflags, and os fields are filled in with the gzip header
    contents.  hcrc is set to true if there is a header CRC.  (The header CRC
-   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
-   contains the maximum number of bytes to write to extra.  Once done is true,
-   extra_len contains the actual extra field length, and extra contains the
-   extra field, or that field truncated if extra_max is less than extra_len.
-   If name is not Z_NULL, then up to name_max characters are written there,
-   terminated with a zero unless the length is greater than name_max.  If
-   comment is not Z_NULL, then up to comm_max characters are written there,
-   terminated with a zero unless the length is greater than comm_max.  When any
-   of extra, name, or comment are not Z_NULL and the respective field is not
-   present in the header, then that field is set to Z_NULL to signal its
-   absence.  This allows the use of deflateSetHeader() with the returned
-   structure to duplicate the header.  However if those fields are set to
-   allocated memory, then the application will need to save those pointers
-   elsewhere so that they can be eventually freed.
+   was valid if done is set to one.)  The extra, name, and comment pointers
+   much each be either Z_NULL or point to space to store that information from
+   the header.  If extra is not Z_NULL, then extra_max contains the maximum
+   number of bytes that can be written to extra.  Once done is true, extra_len
+   contains the actual extra field length, and extra contains the extra field,
+   or that field truncated if extra_max is less than extra_len.  If name is not
+   Z_NULL, then up to name_max characters, including the terminating zero, are
+   written there.  If comment is not Z_NULL, then up to comm_max characters,
+   including the terminating zero, are written there.  The application can tell
+   that the name or comment did not fit in the provided space by the absence of
+   a terminating zero.  If any of extra, name, or comment are not present in
+   the header, then that field's pointer is set to Z_NULL.  This allows the use
+   of deflateSetHeader() with the returned structure to duplicate the header.
+   Note that if those fields initially pointed to allocated memory, then the
+   application will need to save them elsewhere so that they can be eventually
+   freed.
 
      If inflateGetHeader is not used, then the header information is simply
    discarded.  The header is always checked for validity, including the header
@@ -1232,13 +1269,14 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags(void);
      21: FASTEST -- deflate algorithm with only one, lowest compression level
      22,23: 0 (reserved)
 
-    The sprintf variant used by gzprintf (zero is best):
+    The sprintf variant used by gzprintf (all zeros is best):
      24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
-     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() is not secure!
      26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+     27: 0 = gzprintf() present, 1 = not -- 1 means gzprintf() returns an error
 
     Remainder:
-     27-31: 0 (reserved)
+     28-31: 0 (reserved)
  */
 
 #ifndef Z_SOLO
@@ -1250,11 +1288,14 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags(void);
    stream-oriented functions.  To simplify the interface, some default options
    are assumed (compression level and memory usage, standard memory allocation
    functions).  The source code of these utility functions can be modified if
-   you need special options.
+   you need special options.  The _z versions of the functions use the size_t
+   type for lengths.  Note that a long is 32 bits on Windows.
 */
 
-ZEXTERN int ZEXPORT compress(Bytef *dest,   uLongf *destLen,
+ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen,
                              const Bytef *source, uLong sourceLen);
+ZEXTERN int ZEXPORT compress_z(Bytef *dest, z_size_t *destLen,
+                               const Bytef *source, z_size_t sourceLen);
 /*
      Compresses the source buffer into the destination buffer.  sourceLen is
    the byte length of the source buffer.  Upon entry, destLen is the total size
@@ -1268,9 +1309,12 @@ ZEXTERN int ZEXPORT compress(Bytef *dest,   uLongf *destLen,
    buffer.
 */
 
-ZEXTERN int ZEXPORT compress2(Bytef *dest,   uLongf *destLen,
+ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen,
                               const Bytef *source, uLong sourceLen,
                               int level);
+ZEXTERN int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen,
+                                const Bytef *source, z_size_t sourceLen,
+                                int level);
 /*
      Compresses the source buffer into the destination buffer.  The level
    parameter has the same meaning as in deflateInit.  sourceLen is the byte
@@ -1285,21 +1329,24 @@ ZEXTERN int ZEXPORT compress2(Bytef *dest,   uLongf *destLen,
 */
 
 ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen);
+ZEXTERN z_size_t ZEXPORT compressBound_z(z_size_t sourceLen);
 /*
      compressBound() returns an upper bound on the compressed size after
    compress() or compress2() on sourceLen bytes.  It would be used before a
    compress() or compress2() call to allocate the destination buffer.
 */
 
-ZEXTERN int ZEXPORT uncompress(Bytef *dest,   uLongf *destLen,
+ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen,
                                const Bytef *source, uLong sourceLen);
+ZEXTERN int ZEXPORT uncompress_z(Bytef *dest, z_size_t *destLen,
+                                 const Bytef *source, z_size_t sourceLen);
 /*
      Decompresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer.  Upon entry, destLen is the total size
+   the byte length of the source buffer.  On entry, *destLen is the total size
    of the destination buffer, which must be large enough to hold the entire
    uncompressed data.  (The size of the uncompressed data must have been saved
    previously by the compressor and transmitted to the decompressor by some
-   mechanism outside the scope of this compression library.) Upon exit, destLen
+   mechanism outside the scope of this compression library.)  On exit, *destLen
    is the actual size of the uncompressed data.
 
      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
@@ -1309,8 +1356,10 @@ ZEXTERN int ZEXPORT uncompress(Bytef *dest,   uLongf *destLen,
    buffer with the uncompressed data up to that point.
 */
 
-ZEXTERN int ZEXPORT uncompress2(Bytef *dest,   uLongf *destLen,
+ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen,
                                 const Bytef *source, uLong *sourceLen);
+ZEXTERN int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen,
+                                  const Bytef *source, z_size_t *sourceLen);
 /*
      Same as uncompress, except that sourceLen is a pointer, where the
    length of the source is *sourceLen.  On return, *sourceLen is the number of
@@ -1338,13 +1387,17 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
    'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression
    as in "wb9F".  (See the description of deflateInit2 for more information
    about the strategy parameter.)  'T' will request transparent writing or
-   appending with no compression and not using the gzip format.
+   appending with no compression and not using the gzip format. 'T' cannot be
+   used to force transparent reading. Transparent reading is automatically
+   performed if there is no gzip header at the start. Transparent reading can
+   be disabled with the 'G' option, which will instead return an error if there
+   is no gzip header. 'N' will open the file in non-blocking mode.
 
-     "a" can be used instead of "w" to request that the gzip stream that will
-   be written be appended to the file.  "+" will result in an error, since
+     'a' can be used instead of 'w' to request that the gzip stream that will
+   be written be appended to the file.  '+' will result in an error, since
    reading and writing to the same gzip file is not supported.  The addition of
-   "x" when writing will create the file exclusively, which fails if the file
-   already exists.  On systems that support it, the addition of "e" when
+   'x' when writing will create the file exclusively, which fails if the file
+   already exists.  On systems that support it, the addition of 'e' when
    reading or writing will set the flag to close the file on an execve() call.
 
      These functions, as well as gzip, will read and decode a sequence of gzip
@@ -1363,14 +1416,22 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
    insufficient memory to allocate the gzFile state, or if an invalid mode was
    specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
    errno can be checked to determine if the reason gzopen failed was that the
-   file could not be opened.
+   file could not be opened. Note that if 'N' is in mode for non-blocking, the
+   open() itself can fail in order to not block. In that case gzopen() will
+   return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can
+   then be re-tried. If the application would like to block on opening the
+   file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
+   resulting file descriptor and 'N' in the mode, which will set it to non-
+   blocking.
 */
 
 ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode);
 /*
      Associate a gzFile with the file descriptor fd.  File descriptors are
    obtained from calls like open, dup, creat, pipe or fileno (if the file has
-   been previously opened with fopen).  The mode parameter is as in gzopen.
+   been previously opened with fopen).  The mode parameter is as in gzopen. An
+   'e' in mode will set fd's flag to close the file on an execve() call. An 'N'
+   in mode will set fd's non-blocking flag.
 
      The next call of gzclose on the returned gzFile will also close the file
    descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
@@ -1440,10 +1501,16 @@ ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len);
    stream.  Alternatively, gzerror can be used before gzclose to detect this
    case.
 
+     gzread can be used to read a gzip file on a non-blocking device. If the
+   input stalls and there is no uncompressed data to return, then gzread() will
+   return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be
+   called again.
+
      gzread returns the number of uncompressed bytes actually read, less than
    len for end of file, or -1 for error.  If len is too large to fit in an int,
    then nothing is read, -1 is returned, and the error state is set to
-   Z_STREAM_ERROR.
+   Z_STREAM_ERROR. If some data was read before an error, then that data is
+   returned until exhausted, after which the next call will signal the error.
 */
 
 ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
@@ -1467,15 +1534,20 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
    multiple of size, then the final partial item is nevertheless read into buf
    and the end-of-file flag is set.  The length of the partial item read is not
    provided, but could be inferred from the result of gztell().  This behavior
-   is the same as the behavior of fread() implementations in common libraries,
-   but it prevents the direct use of gzfread() to read a concurrently written
-   file, resetting and retrying on end-of-file, when size is not 1.
+   is the same as that of fread() implementations in common libraries. This
+   could result in data loss if used with size != 1 when reading a concurrently
+   written file or a non-blocking file. In that case, use size == 1 or gzread()
+   instead.
 */
 
 ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len);
 /*
      Compress and write the len uncompressed bytes at buf to file. gzwrite
-   returns the number of uncompressed bytes written or 0 in case of error.
+   returns the number of uncompressed bytes written, or 0 in case of error or
+   if len is 0.  If the write destination is non-blocking, then gzwrite() may
+   return a number of bytes written that is not 0 and less than len.
+
+     If len does not fit in an int, then 0 is returned and nothing is written.
 */
 
 ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size,
@@ -1490,9 +1562,18 @@ ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size,
    if there was an error.  If the multiplication of size and nitems overflows,
    i.e. the product does not fit in a z_size_t, then nothing is written, zero
    is returned, and the error state is set to Z_STREAM_ERROR.
+
+     If writing a concurrently read file or a non-blocking file with size != 1,
+   a partial item could be written, with no way of knowing how much of it was
+   not written, resulting in data loss.  In that case, use size == 1 or
+   gzwrite() instead.
 */
 
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
 ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...);
+#else
+ZEXTERN int ZEXPORTVA gzprintf();
+#endif
 /*
      Convert, format, compress, and write the arguments (...) to file under
    control of the string format, as in fprintf.  gzprintf returns the number of
@@ -1500,11 +1581,19 @@ ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...);
    of error.  The number of uncompressed bytes written is limited to 8191, or
    one less than the buffer size given to gzbuffer().  The caller should assure
    that this limit is not exceeded.  If it is exceeded, then gzprintf() will
-   return an error (0) with nothing written.  In this case, there may also be a
-   buffer overflow with unpredictable consequences, which is possible only if
-   zlib was compiled with the insecure functions sprintf() or vsprintf(),
-   because the secure snprintf() or vsnprintf() functions were not available.
-   This can be determined using zlibCompileFlags().
+   return an error (0) with nothing written.
+
+     In that last case, there may also be a buffer overflow with unpredictable
+   consequences, which is possible only if zlib was compiled with the insecure
+   functions sprintf() or vsprintf(), because the secure snprintf() and
+   vsnprintf() functions were not available. That would only be the case for
+   a non-ANSI C compiler. zlib may have been built without gzprintf() because
+   secure functions were not available and having gzprintf() be insecure was
+   not an option, in which case, gzprintf() returns Z_STREAM_ERROR. All of
+   these possibilities can be determined using zlibCompileFlags().
+
+     If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
+   the non-blocking write destination.
 */
 
 ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
@@ -1513,6 +1602,11 @@ ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
    the terminating null character.
 
      gzputs returns the number of characters written, or -1 in case of error.
+   The number of characters written may be less than the length of the string
+   if the write destination is non-blocking.
+
+     If the length of the string does not fit in an int, then -1 is returned
+   and nothing is written.
 */
 
 ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len);
@@ -1525,8 +1619,13 @@ ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len);
    left untouched.
 
      gzgets returns buf which is a null-terminated string, or it returns NULL
-   for end-of-file or in case of error.  If there was an error, the contents at
-   buf are indeterminate.
+   for end-of-file or in case of error. If some data was read before an error,
+   then that data is returned until exhausted, after which the next call will
+   return NULL to signal the error.
+
+     gzgets can be used on a file being concurrently written, and on a non-
+   blocking device, both as for gzread(). However lines may be broken in the
+   middle, leaving it up to the application to reassemble them as needed.
 */
 
 ZEXTERN int ZEXPORT gzputc(gzFile file, int c);
@@ -1537,11 +1636,19 @@ ZEXTERN int ZEXPORT gzputc(gzFile file, int c);
 
 ZEXTERN int ZEXPORT gzgetc(gzFile file);
 /*
-     Read and decompress one byte from file.  gzgetc returns this byte or -1
-   in case of end of file or error.  This is implemented as a macro for speed.
-   As such, it does not do all of the checking the other functions do.  I.e.
-   it does not check to see if file is NULL, nor whether the structure file
-   points to has been clobbered or not.
+     Read and decompress one byte from file. gzgetc returns this byte or -1 in
+   case of end of file or error. If some data was read before an error, then
+   that data is returned until exhausted, after which the next call will return
+   -1 to signal the error.
+
+     This is implemented as a macro for speed. As such, it does not do all of
+   the checking the other functions do. I.e. it does not check to see if file
+   is NULL, nor whether the structure file points to has been clobbered or not.
+
+     gzgetc can be used to read a gzip file on a non-blocking device. If the
+   input stalls and there is no uncompressed data to return, then gzgetc() will
+   return -1, and errno will be EAGAIN or EWOULDBLOCK. gzread() can then be
+   called again.
 */
 
 ZEXTERN int ZEXPORT gzungetc(int c, gzFile file);
@@ -1554,6 +1661,11 @@ ZEXTERN int ZEXPORT gzungetc(int c, gzFile file);
    output buffer size of pushed characters is allowed.  (See gzbuffer above.)
    The pushed character will be discarded if the stream is repositioned with
    gzseek() or gzrewind().
+
+     gzungetc(-1, file) will force any pending seek to execute. Then gztell()
+   will report the position, even if the requested seek reached end of file.
+   This can be used to determine the number of uncompressed bytes in a gzip
+   file without having to read it into a buffer.
 */
 
 ZEXTERN int ZEXPORT gzflush(gzFile file, int flush);
@@ -1583,7 +1695,8 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
      If the file is opened for reading, this function is emulated but can be
    extremely slow.  If the file is opened for writing, only forward seeks are
    supported; gzseek then compresses a sequence of zeroes up to the new
-   starting position.
+   starting position. For reading or writing, any actual seeking is deferred
+   until the next read or write operation, or close operation when writing.
 
      gzseek returns the resulting offset location as measured in bytes from
    the beginning of the uncompressed stream, or -1 in case of error, in
@@ -1591,7 +1704,7 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
    would be before the current position.
 */
 
-ZEXTERN int ZEXPORT    gzrewind(gzFile file);
+ZEXTERN int ZEXPORT gzrewind(gzFile file);
 /*
      Rewind file. This function is supported only for reading.
 
@@ -1599,7 +1712,7 @@ ZEXTERN int ZEXPORT    gzrewind(gzFile file);
 */
 
 /*
-ZEXTERN z_off_t ZEXPORT    gztell(gzFile file);
+ZEXTERN z_off_t ZEXPORT gztell(gzFile file);
 
      Return the starting position for the next gzread or gzwrite on file.
    This position represents a number of bytes in the uncompressed data stream,
@@ -1644,8 +1757,11 @@ ZEXTERN int ZEXPORT gzdirect(gzFile file);
 
      If gzdirect() is used immediately after gzopen() or gzdopen() it will
    cause buffers to be allocated to allow reading the file to determine if it
-   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
-   gzdirect().
+   is a gzip file. Therefore if gzbuffer() is used, it should be called before
+   gzdirect(). If the input is being written concurrently or the device is non-
+   blocking, then gzdirect() may give a different answer once four bytes of
+   input have been accumulated, which is what is needed to confirm or deny a
+   gzip header. Before this, gzdirect() will return true (1).
 
      When writing, gzdirect() returns true (1) if transparent writing was
    requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
@@ -1655,7 +1771,7 @@ ZEXTERN int ZEXPORT gzdirect(gzFile file);
    gzip file reading and decompression, which may not be desired.)
 */
 
-ZEXTERN int ZEXPORT    gzclose(gzFile file);
+ZEXTERN int ZEXPORT gzclose(gzFile file);
 /*
      Flush all pending output for file, if necessary, close file and
    deallocate the (de)compression state.  Note that once file is closed, you
@@ -1683,9 +1799,10 @@ ZEXTERN int ZEXPORT gzclose_w(gzFile file);
 ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
 /*
      Return the error message for the last error which occurred on file.
-   errnum is set to zlib error number.  If an error occurred in the file system
-   and not in the compression library, errnum is set to Z_ERRNO and the
-   application may consult errno to get the exact error code.
+   If errnum is not NULL, *errnum is set to zlib error number.  If an error
+   occurred in the file system and not in the compression library, *errnum is
+   set to Z_ERRNO and the application may consult errno to get the exact error
+   code.
 
      The application must not modify the returned string.  Future calls to
    this function may invalidate the previously returned string.  If file is
@@ -1736,7 +1853,8 @@ ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len);
 ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf,
                                 z_size_t len);
 /*
-     Same as adler32(), but with a size_t length.
+     Same as adler32(), but with a size_t length.  Note that a long is 32 bits
+   on Windows.
 */
 
 /*
@@ -1772,7 +1890,8 @@ ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len);
 ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf,
                               z_size_t len);
 /*
-     Same as crc32(), but with a size_t length.
+     Same as crc32(), but with a size_t length.  Note that a long is 32 bits on
+   Windows.
 */
 
 /*
@@ -1782,14 +1901,14 @@ ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2);
    seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
    calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
    check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
-   len2. len2 must be non-negative.
+   len2. len2 must be non-negative, otherwise zero is returned.
 */
 
 /*
 ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2);
 
      Return the operator corresponding to length len2, to be used with
-   crc32_combine_op(). len2 must be non-negative.
+   crc32_combine_op(). len2 must be non-negative, otherwise zero is returned.
 */
 
 ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op);
@@ -1912,9 +2031,9 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file);       /* backward compatibility */
      ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int);
      ZEXTERN z_off_t ZEXPORT gztell64(gzFile);
      ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile);
-     ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t);
-     ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t);
-     ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t);
+     ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t);
+     ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t);
+     ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t);
 #  endif
 #else
    ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *);
diff --git a/src/java.base/share/native/libzip/zlib/zutil.c b/src/java.base/share/native/libzip/zlib/zutil.c
index 92dda78497b..c57c162ffde 100644
--- a/src/java.base/share/native/libzip/zlib/zutil.c
+++ b/src/java.base/share/native/libzip/zlib/zutil.c
@@ -23,7 +23,7 @@
  */
 
 /* zutil.c -- target dependent utility functions for the compression library
- * Copyright (C) 1995-2017 Jean-loup Gailly
+ * Copyright (C) 1995-2026 Jean-loup Gailly
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -110,28 +110,36 @@ uLong ZEXPORT zlibCompileFlags(void) {
     flags += 1L << 21;
 #endif
 #if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#  ifdef NO_vsnprintf
-    flags += 1L << 25;
-#    ifdef HAS_vsprintf_void
-    flags += 1L << 26;
-#    endif
-#  else
-#    ifdef HAS_vsnprintf_void
-    flags += 1L << 26;
-#    endif
-#  endif
+#   ifdef NO_vsnprintf
+#       ifdef ZLIB_INSECURE
+            flags += 1L << 25;
+#       else
+            flags += 1L << 27;
+#       endif
+#       ifdef HAS_vsprintf_void
+            flags += 1L << 26;
+#       endif
+#   else
+#       ifdef HAS_vsnprintf_void
+            flags += 1L << 26;
+#       endif
+#   endif
 #else
     flags += 1L << 24;
-#  ifdef NO_snprintf
-    flags += 1L << 25;
-#    ifdef HAS_sprintf_void
-    flags += 1L << 26;
-#    endif
-#  else
-#    ifdef HAS_snprintf_void
-    flags += 1L << 26;
-#    endif
-#  endif
+#   ifdef NO_snprintf
+#       ifdef ZLIB_INSECURE
+            flags += 1L << 25;
+#       else
+            flags += 1L << 27;
+#       endif
+#       ifdef HAS_sprintf_void
+            flags += 1L << 26;
+#       endif
+#   else
+#       ifdef HAS_snprintf_void
+            flags += 1L << 26;
+#       endif
+#   endif
 #endif
     return flags;
 }
@@ -166,28 +174,34 @@ const char * ZEXPORT zError(int err) {
 
 #ifndef HAVE_MEMCPY
 
-void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len) {
-    if (len == 0) return;
-    do {
-        *dest++ = *source++; /* ??? to be unrolled */
-    } while (--len != 0);
+void ZLIB_INTERNAL zmemcpy(void FAR *dst, const void FAR *src, z_size_t n) {
+    uchf *p = dst;
+    const uchf *q = src;
+    while (n) {
+        *p++ = *q++;
+        n--;
+    }
 }
 
-int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len) {
-    uInt j;
-
-    for (j = 0; j < len; j++) {
-        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
+int ZLIB_INTERNAL zmemcmp(const void FAR *s1, const void FAR *s2, z_size_t n) {
+    const uchf *p = s1, *q = s2;
+    while (n) {
+        if (*p++ != *q++)
+            return (int)p[-1] - (int)q[-1];
+        n--;
     }
     return 0;
 }
 
-void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len) {
+void ZLIB_INTERNAL zmemzero(void FAR *b, z_size_t len) {
+    uchf *p = b;
     if (len == 0) return;
-    do {
-        *dest++ = 0;  /* ??? to be unrolled */
-    } while (--len != 0);
+    while (len) {
+        *p++ = 0;
+        len--;
+    }
 }
+
 #endif
 
 #ifndef Z_SOLO
diff --git a/src/java.base/share/native/libzip/zlib/zutil.h b/src/java.base/share/native/libzip/zlib/zutil.h
index 2b7e697bef9..b337065875d 100644
--- a/src/java.base/share/native/libzip/zlib/zutil.h
+++ b/src/java.base/share/native/libzip/zlib/zutil.h
@@ -23,7 +23,7 @@
  */
 
 /* zutil.h -- internal interface and configuration of the compression library
- * Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler
+ * Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -60,6 +60,10 @@
    define "local" for the non-static meaning of "static", for readability
    (compile with -Dlocal if your debugger can't find static symbols) */
 
+extern const char deflate_copyright[];
+extern const char inflate_copyright[];
+extern const char inflate9_copyright[];
+
 typedef unsigned char  uch;
 typedef uch FAR uchf;
 typedef unsigned short ush;
@@ -72,6 +76,8 @@ typedef unsigned long  ulg;
 #    define Z_U8 unsigned long
 #  elif (ULLONG_MAX == 0xffffffffffffffff)
 #    define Z_U8 unsigned long long
+#  elif (ULONG_LONG_MAX == 0xffffffffffffffff)
+#    define Z_U8 unsigned long long
 #  elif (UINT_MAX == 0xffffffffffffffff)
 #    define Z_U8 unsigned
 #  endif
@@ -87,7 +93,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 /* To be used only when the state is known to be valid */
 
         /* common constants */
-
+#if MAX_WBITS < 9 || MAX_WBITS > 15
+#  error MAX_WBITS must be in 9..15
+#endif
 #ifndef DEF_WBITS
 #  define DEF_WBITS MAX_WBITS
 #endif
@@ -165,7 +173,7 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 #  define OS_CODE  7
 #endif
 
-#ifdef __acorn
+#if defined(__acorn) || defined(__riscos)
 #  define OS_CODE 13
 #endif
 
@@ -192,11 +200,10 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 #endif
 
 /* provide prototypes for these when building zlib without LFS */
-#if !defined(_WIN32) && \
-    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
-    ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t);
-    ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t);
-    ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t);
+#ifndef Z_LARGE64
+   ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t);
+   ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t);
+   ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t);
 #endif
 
         /* common defaults */
@@ -235,9 +242,9 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 #    define zmemzero(dest, len) memset(dest, 0, len)
 #  endif
 #else
-   void ZLIB_INTERNAL zmemcpy(Bytef* dest, const Bytef* source, uInt len);
-   int ZLIB_INTERNAL zmemcmp(const Bytef* s1, const Bytef* s2, uInt len);
-   void ZLIB_INTERNAL zmemzero(Bytef* dest, uInt len);
+   void ZLIB_INTERNAL zmemcpy(void FAR *, const void FAR *, z_size_t);
+   int ZLIB_INTERNAL zmemcmp(const void FAR *, const void FAR *, z_size_t);
+   void ZLIB_INTERNAL zmemzero(void FAR *, z_size_t);
 #endif
 
 /* Diagnostic functions */
@@ -275,4 +282,74 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
 #define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
                     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
 
+#ifdef Z_ONCE
+/*
+  Create a local z_once() function depending on the availability of atomics.
+ */
+
+/* Check for the availability of atomics. */
+#if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \
+    !defined(__STDC_NO_ATOMICS__)
+
+#include 
+typedef struct {
+    atomic_flag begun;
+    atomic_int done;
+} z_once_t;
+#define Z_ONCE_INIT {ATOMIC_FLAG_INIT, 0}
+
+/*
+  Run the provided init() function exactly once, even if multiple threads
+  invoke once() at the same time. The state must be a once_t initialized with
+  Z_ONCE_INIT.
+ */
+local void z_once(z_once_t *state, void (*init)(void)) {
+    if (!atomic_load(&state->done)) {
+        if (atomic_flag_test_and_set(&state->begun))
+            while (!atomic_load(&state->done))
+                ;
+        else {
+            init();
+            atomic_store(&state->done, 1);
+        }
+    }
+}
+
+#else   /* no atomics */
+
+#warning zlib not thread-safe
+
+typedef struct z_once_s {
+    volatile int begun;
+    volatile int done;
+} z_once_t;
+#define Z_ONCE_INIT {0, 0}
+
+/* Test and set. Alas, not atomic, but tries to limit the period of
+   vulnerability. */
+local int test_and_set(int volatile *flag) {
+    int was;
+
+    was = *flag;
+    *flag = 1;
+    return was;
+}
+
+/* Run the provided init() function once. This is not thread-safe. */
+local void z_once(z_once_t *state, void (*init)(void)) {
+    if (!state->done) {
+        if (test_and_set(&state->begun))
+            while (!state->done)
+                ;
+        else {
+            init();
+            state->done = 1;
+        }
+    }
+}
+
+#endif /* ?atomics */
+
+#endif /* Z_ONCE */
+
 #endif /* ZUTIL_H */

From 173153e1b25c5081d6e6886fe9588847f5a564b6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Eirik=20Bj=C3=B8rsn=C3=B8s?= 
Date: Thu, 26 Feb 2026 12:03:16 +0000
Subject: [PATCH 18/54] 8376403: Avoid loading ArrayDeque in
 java.util.zip.ZipFile

Reviewed-by: lancea, jpai
---
 .../share/classes/java/util/zip/ZipFile.java  | 40 +++++++++----------
 1 file changed, 19 insertions(+), 21 deletions(-)

diff --git a/src/java.base/share/classes/java/util/zip/ZipFile.java b/src/java.base/share/classes/java/util/zip/ZipFile.java
index a198c35c366..43a3b37b7d0 100644
--- a/src/java.base/share/classes/java/util/zip/ZipFile.java
+++ b/src/java.base/share/classes/java/util/zip/ZipFile.java
@@ -692,7 +692,7 @@ public class ZipFile implements ZipConstants, Closeable {
         final Set istreams;
 
         // List of cached Inflater objects for decompression
-        Deque inflaterCache;
+        List inflaterCache;
 
         final Cleanable cleanable;
 
@@ -702,7 +702,7 @@ public class ZipFile implements ZipConstants, Closeable {
             assert zipCoder != null : "null ZipCoder";
             this.cleanable = CleanerFactory.cleaner().register(zf, this);
             this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
-            this.inflaterCache = new ArrayDeque<>();
+            this.inflaterCache = new ArrayList<>();
             this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0, zipCoder);
         }
 
@@ -715,10 +715,10 @@ public class ZipFile implements ZipConstants, Closeable {
          * a new one.
          */
         Inflater getInflater() {
-            Inflater inf;
             synchronized (inflaterCache) {
-                if ((inf = inflaterCache.poll()) != null) {
-                    return inf;
+                if (!inflaterCache.isEmpty()) {
+                    // return the most recently used Inflater from the cache of not-in-use Inflaters
+                    return inflaterCache.removeLast();
                 }
             }
             return new Inflater(true);
@@ -728,7 +728,7 @@ public class ZipFile implements ZipConstants, Closeable {
          * Releases the specified inflater to the list of available inflaters.
          */
         void releaseInflater(Inflater inf) {
-            Deque inflaters = this.inflaterCache;
+            List inflaters = this.inflaterCache;
             if (inflaters != null) {
                 synchronized (inflaters) {
                     // double checked!
@@ -747,13 +747,12 @@ public class ZipFile implements ZipConstants, Closeable {
             IOException ioe = null;
 
             // Release cached inflaters and close the cache first
-            Deque inflaters = this.inflaterCache;
+            List inflaters = this.inflaterCache;
             if (inflaters != null) {
                 synchronized (inflaters) {
                     // no need to double-check as only one thread gets a
                     // chance to execute run() (Cleaner guarantee)...
-                    Inflater inf;
-                    while ((inf = inflaters.poll()) != null) {
+                    for (Inflater inf : inflaters) {
                         inf.end();
                     }
                     // close inflaters cache
@@ -762,23 +761,22 @@ public class ZipFile implements ZipConstants, Closeable {
             }
 
             // Close streams, release their inflaters
-            if (istreams != null) {
-                synchronized (istreams) {
-                    if (!istreams.isEmpty()) {
-                        InputStream[] copy = istreams.toArray(new InputStream[0]);
-                        istreams.clear();
-                        for (InputStream is : copy) {
-                            try {
-                                is.close();
-                            } catch (IOException e) {
-                                if (ioe == null) ioe = e;
-                                else ioe.addSuppressed(e);
-                            }
+            synchronized (istreams) {
+                if (!istreams.isEmpty()) {
+                    InputStream[] copy = istreams.toArray(new InputStream[0]);
+                    istreams.clear();
+                    for (InputStream is : copy) {
+                        try {
+                            is.close();
+                        } catch (IOException e) {
+                            if (ioe == null) ioe = e;
+                            else ioe.addSuppressed(e);
                         }
                     }
                 }
             }
 
+
             // Release ZIP src
             if (zsrc != null) {
                 synchronized (zsrc) {

From b13a291667535fdea30936ea5dc87f405e637069 Mon Sep 17 00:00:00 2001
From: Alan Bateman 
Date: Thu, 26 Feb 2026 13:38:14 +0000
Subject: [PATCH 19/54] 8378268: Thread.join can wait on Thread, allows
 joinNanos to be removed

Reviewed-by: jpai, vklang
---
 .../share/classes/java/lang/Thread.java       | 33 +++------
 .../classes/java/lang/VirtualThread.java      | 67 ++++---------------
 2 files changed, 23 insertions(+), 77 deletions(-)

diff --git a/src/java.base/share/classes/java/lang/Thread.java b/src/java.base/share/classes/java/lang/Thread.java
index 57d28aca5f4..4890c1af45b 100644
--- a/src/java.base/share/classes/java/lang/Thread.java
+++ b/src/java.base/share/classes/java/lang/Thread.java
@@ -1881,8 +1881,8 @@ public class Thread implements Runnable {
      * been {@link #start() started}.
      *
      * @implNote
-     * For platform threads, the implementation uses a loop of {@code this.wait}
-     * calls conditioned on {@code this.isAlive}. As a thread terminates the
+     * This implementation uses a loop of {@code this.wait} calls
+     * conditioned on {@code this.isAlive}. As a thread terminates the
      * {@code this.notifyAll} method is invoked. It is recommended that
      * applications not use {@code wait}, {@code notify}, or
      * {@code notifyAll} on {@code Thread} instances.
@@ -1901,13 +1901,12 @@ public class Thread implements Runnable {
     public final void join(long millis) throws InterruptedException {
         if (millis < 0)
             throw new IllegalArgumentException("timeout value is negative");
-
-        if (this instanceof VirtualThread vthread) {
-            if (isAlive()) {
-                long nanos = MILLISECONDS.toNanos(millis);
-                vthread.joinNanos(nanos);
-            }
+        if (!isAlive())
             return;
+
+        // ensure there is a notifyAll to wake up waiters when this thread terminates
+        if (this instanceof VirtualThread vthread) {
+            vthread.beforeJoin();
         }
 
         synchronized (this) {
@@ -1936,8 +1935,8 @@ public class Thread implements Runnable {
      * been {@link #start() started}.
      *
      * @implNote
-     * For platform threads, the implementation uses a loop of {@code this.wait}
-     * calls conditioned on {@code this.isAlive}. As a thread terminates the
+     * This implementation uses a loop of {@code this.wait} calls
+     * conditioned on {@code this.isAlive}. As a thread terminates the
      * {@code this.notifyAll} method is invoked. It is recommended that
      * applications not use {@code wait}, {@code notify}, or
      * {@code notifyAll} on {@code Thread} instances.
@@ -1966,16 +1965,6 @@ public class Thread implements Runnable {
             throw new IllegalArgumentException("nanosecond timeout value out of range");
         }
 
-        if (this instanceof VirtualThread vthread) {
-            if (isAlive()) {
-                // convert arguments to a total in nanoseconds
-                long totalNanos = MILLISECONDS.toNanos(millis);
-                totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
-                vthread.joinNanos(totalNanos);
-            }
-            return;
-        }
-
         if (nanos > 0 && millis < Long.MAX_VALUE) {
             millis++;
         }
@@ -2035,10 +2024,6 @@ public class Thread implements Runnable {
         if (nanos <= 0)
             return false;
 
-        if (this instanceof VirtualThread vthread) {
-            return vthread.joinNanos(nanos);
-        }
-
         // convert to milliseconds
         long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
         if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
diff --git a/src/java.base/share/classes/java/lang/VirtualThread.java b/src/java.base/share/classes/java/lang/VirtualThread.java
index 6cd7ccbbba1..f058f967b91 100644
--- a/src/java.base/share/classes/java/lang/VirtualThread.java
+++ b/src/java.base/share/classes/java/lang/VirtualThread.java
@@ -26,7 +26,6 @@ package java.lang;
 
 import java.util.Locale;
 import java.util.Objects;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ForkJoinPool;
@@ -68,7 +67,6 @@ final class VirtualThread extends BaseVirtualThread {
     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
-    private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
     private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
 
     // scheduler and continuation
@@ -184,8 +182,8 @@ final class VirtualThread extends BaseVirtualThread {
     // carrier thread when mounted, accessed by VM
     private volatile Thread carrierThread;
 
-    // termination object when joining, created lazily if needed
-    private volatile CountDownLatch termination;
+    // true to notifyAll after this virtual thread terminates
+    private volatile boolean notifyAllAfterTerminate;
 
     /**
      * Returns the default scheduler.
@@ -677,11 +675,11 @@ final class VirtualThread extends BaseVirtualThread {
         assert carrierThread == null;
         setState(TERMINATED);
 
-        // notify anyone waiting for this virtual thread to terminate
-        CountDownLatch termination = this.termination;
-        if (termination != null) {
-            assert termination.getCount() == 1;
-            termination.countDown();
+        // notifyAll to wakeup any threads waiting for this thread to terminate
+        if (notifyAllAfterTerminate) {
+            synchronized (this) {
+                notifyAll();
+            }
         }
 
         // notify container
@@ -740,6 +738,13 @@ final class VirtualThread extends BaseVirtualThread {
         // do nothing
     }
 
+    /**
+     * Invoked by Thread.join before a thread waits for this virtual thread to terminate.
+     */
+    void beforeJoin() {
+        notifyAllAfterTerminate = true;
+    }
+
     /**
      * Parks until unparked or interrupted. If already unparked then the parking
      * permit is consumed and this method completes immediately (meaning it doesn't
@@ -999,36 +1004,6 @@ final class VirtualThread extends BaseVirtualThread {
         }
     }
 
-    /**
-     * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate.
-     * A timeout of {@code 0} means to wait forever.
-     *
-     * @throws InterruptedException if interrupted while waiting
-     * @return true if the thread has terminated
-     */
-    boolean joinNanos(long nanos) throws InterruptedException {
-        if (state() == TERMINATED)
-            return true;
-
-        // ensure termination object exists, then re-check state
-        CountDownLatch termination = getTermination();
-        if (state() == TERMINATED)
-            return true;
-
-        // wait for virtual thread to terminate
-        if (nanos == 0) {
-            termination.await();
-        } else {
-            boolean terminated = termination.await(nanos, NANOSECONDS);
-            if (!terminated) {
-                // waiting time elapsed
-                return false;
-            }
-        }
-        assert state() == TERMINATED;
-        return true;
-    }
-
     @Override
     void blockedOn(Interruptible b) {
         disableSuspendAndPreempt();
@@ -1239,20 +1214,6 @@ final class VirtualThread extends BaseVirtualThread {
         return obj == this;
     }
 
-    /**
-     * Returns the termination object, creating it if needed.
-     */
-    private CountDownLatch getTermination() {
-        CountDownLatch termination = this.termination;
-        if (termination == null) {
-            termination = new CountDownLatch(1);
-            if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
-                termination = this.termination;
-            }
-        }
-        return termination;
-    }
-
     /**
      * Returns the lock object to synchronize on when accessing carrierThread.
      * The lock prevents carrierThread from being reset to null during unmount.

From 82ff0255c59645ec115ac7a5fa055667770bf0cf Mon Sep 17 00:00:00 2001
From: Vicente Romero 
Date: Thu, 26 Feb 2026 14:12:50 +0000
Subject: [PATCH 20/54] 8374910: Use of containsTypeEquivalent in array type
 equality test seems bogus

Reviewed-by: liach
---
 .../share/classes/com/sun/tools/javac/code/Types.java           | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
index 539b1470a75..9ffab9fd961 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
@@ -1436,7 +1436,7 @@ public class Types {
                     return visit(s, t);
 
                 return s.hasTag(ARRAY)
-                    && containsTypeEquivalent(t.elemtype, elemtype(s));
+                    && visit(t.elemtype, elemtype(s));
             }
 
             @Override

From 3b8abd459ffc195957a8cb6a45d4e72e100099cc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Eirik=20Bj=C3=B8rsn=C3=B8s?= 
Date: Thu, 26 Feb 2026 15:12:21 +0000
Subject: [PATCH 21/54] 8378398: Modernize
 test/jdk/java/net/URLClassLoader/HttpTest.java

Reviewed-by: dfuchs
---
 .../jdk/java/net/URLClassLoader/HttpTest.java | 459 ++++++++++--------
 1 file changed, 262 insertions(+), 197 deletions(-)

diff --git a/test/jdk/java/net/URLClassLoader/HttpTest.java b/test/jdk/java/net/URLClassLoader/HttpTest.java
index 620eb34dbaa..09ee6dcfa85 100644
--- a/test/jdk/java/net/URLClassLoader/HttpTest.java
+++ b/test/jdk/java/net/URLClassLoader/HttpTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 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
@@ -24,233 +24,298 @@
 /**
  * @test
  * @bug 4636331
+ * @modules jdk.httpserver
  * @library /test/lib
- * @summary Check that URLClassLoader doesn't create excessive http
- *          connections
+ * @summary Check that URLClassLoader with HTTP paths lookups produce the expected http requests
+ * @run junit HttpTest
  */
 import java.net.*;
 import java.io.*;
+import java.nio.charset.StandardCharsets;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
 
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
 import jdk.test.lib.net.URIBuilder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class HttpTest {
 
-    /*
-     * Simple http server to service http requests. Auto shutdown
-     * if "idle" (no requests) for 10 seconds. Forks worker thread
-     * to service persistent connections. Work threads shutdown if
-     * "idle" for 5 seconds.
-     */
-    static class HttpServer implements Runnable {
+    // HTTP server used to track requests
+    static HttpServer server;
 
-        private static HttpServer svr = null;
-        private static Counters cnts = null;
-        private static ServerSocket ss;
+    // RequestLog for capturing requests
+    static class RequestLog {
+        List log = new ArrayList<>();
 
-        private static Object counterLock = new Object();
-        private static int getCount = 0;
-        private static int headCount = 0;
-
-        class Worker extends Thread {
-            Socket s;
-            Worker(Socket s) {
-                this.s = s;
-            }
-
-            public void run() {
-                InputStream in = null;
-                try {
-                    in = s.getInputStream();
-                    for (;;) {
-
-                        // read entire request from client
-                        byte b[] = new byte[1024];
-                        int n, total=0;
-
-                        // max 5 seconds to wait for new request
-                        s.setSoTimeout(5000);
-                        try {
-                            do {
-                                n = in.read(b, total, b.length-total);
-                                // max 0.5 seconds between each segment
-                                // of request.
-                                s.setSoTimeout(500);
-                                if (n > 0) total += n;
-                            } while (n > 0);
-                        } catch (SocketTimeoutException e) { }
-
-                        if (total == 0) {
-                            s.close();
-                            return;
-                        }
-
-                        boolean getRequest = false;
-                        if (b[0] == 'G' && b[1] == 'E' && b[2] == 'T')
-                            getRequest = true;
-
-                        synchronized (counterLock) {
-                            if (getRequest)
-                                getCount++;
-                            else
-                                headCount++;
-                        }
-
-                        // response to client
-                        PrintStream out = new PrintStream(
-                                new BufferedOutputStream(
-                                        s.getOutputStream() ));
-                        out.print("HTTP/1.1 200 OK\r\n");
-
-                        out.print("Content-Length: 75000\r\n");
-                        out.print("\r\n");
-                        if (getRequest) {
-                            for (int i=0; i<75*1000; i++) {
-                                out.write( (byte)'.' );
-                            }
-                        }
-                        out.flush();
-
-                    } // for
-
-                } catch (Exception e) {
-                    unexpected(e);
-                } finally {
-                    if (in != null) { try {in.close(); } catch(IOException e) {unexpected(e);} }
-                }
-            }
+        // Add a request to the log
+        public synchronized void capture(String method, URI uri) {
+            log.add(new Request(method, uri));
         }
 
-        HttpServer() throws Exception {
-            ss = new ServerSocket();
-            ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
+        // Clear requests
+        public synchronized void clear() {
+            log.clear();
         }
 
-        public void run() {
-            try {
-                // shutdown if no request in 10 seconds.
-                ss.setSoTimeout(10000);
-                for (;;) {
-                    Socket s = ss.accept();
-                    (new Worker(s)).start();
-                }
-            } catch (Exception e) {
-            }
+        public synchronized List requests() {
+            return List.copyOf(log);
         }
-
-        void unexpected(Exception e) {
-            System.out.println(e);
-            e.printStackTrace();
-        }
-
-        public static HttpServer create() throws Exception {
-            if (svr != null)
-                return svr;
-            cnts = new Counters();
-            svr = new HttpServer();
-            (new Thread(svr)).start();
-            return svr;
-        }
-
-        public static void shutdown() throws Exception {
-            if (svr != null) {
-                ss.close();
-                svr = null;
-            }
-        }
-
-        public int port() {
-            return ss.getLocalPort();
-        }
-
-        public static class Counters {
-            public void reset() {
-                synchronized (counterLock) {
-                    getCount = 0;
-                    headCount = 0;
-                }
-            }
-
-            public int getCount() {
-                synchronized (counterLock) {
-                    return getCount;
-                }
-            }
-
-            public int headCount() {
-                synchronized (counterLock) {
-                    return headCount;
-                }
-            }
-
-            public String toString() {
-                synchronized (counterLock) {
-                    return "GET count: " + getCount + "; " +
-                       "HEAD count: " + headCount;
-                }
-            }
-        }
-
-        public Counters counters() {
-            return cnts;
-        }
-
     }
 
-    public static void main(String args[]) throws Exception {
-        boolean failed = false;
+    // Represents a single request
+    record Request(String method, URI path) {}
 
-        // create http server
-        HttpServer svr = HttpServer.create();
+    // Request log for this test
+    static RequestLog log = new RequestLog();
 
-        // create class loader
-        URL urls[] = {
-                URIBuilder.newBuilder().scheme("http").loopback().port(svr.port())
-                        .path("/dir1/").toURL(),
-                URIBuilder.newBuilder().scheme("http").loopback().port(svr.port())
-                        .path("/dir2/").toURL(),
+    // Handlers specific to tests
+    static Map handlers = new ConcurrentHashMap<>();
+
+    // URLClassLoader with HTTP URL class path
+    private static URLClassLoader loader;
+
+    @BeforeAll
+    static void setup() throws Exception {
+        server = HttpServer.create();
+        server.bind(new InetSocketAddress(
+                InetAddress.getLoopbackAddress(), 0), 0);
+        server.createContext("/", e -> {
+            // Capture request in the log
+            log.capture(e.getRequestMethod(), e.getRequestURI());
+            // Check for custom handler
+            HttpHandler custom = handlers.get(e.getRequestURI());
+            if (custom != null) {
+                custom.handle(e);
+            } else {
+                // Successful responses echo the request path in the body
+                byte[] response = e.getRequestURI().getPath()
+                        .getBytes(StandardCharsets.UTF_8);
+                e.sendResponseHeaders(200, response.length);
+                try (var out = e.getResponseBody()) {
+                    out.write(response);
+                }
+            }
+            e.close();
+        });
+        server.start();
+        int port = server.getAddress().getPort();
+
+        // Create class loader with two HTTP URLs
+        URL[] searchPath = new URL[] {
+                getHttpUri("/dir1/", port),
+                getHttpUri("/dir2/", port)
         };
-        URLClassLoader cl = new URLClassLoader(urls);
+        loader = new URLClassLoader(searchPath);
+    }
 
-        // Test 1 - check that getResource does single HEAD request
-        svr.counters().reset();
-        URL url = cl.getResource("foo.gif");
-        System.out.println(svr.counters());
+    // Create an HTTP URL for the given path and port using the loopback address
+    private static URL getHttpUri(String path, int port) throws Exception {
+        return URIBuilder.newBuilder()
+                .scheme("http")
+                .loopback()
+                .port(port)
+                .path(path).toURL();
+    }
 
-        if (svr.counters().getCount() > 0 ||
-            svr.counters().headCount() > 1) {
-            failed = true;
+    // Add redirect handler for a given path
+    private static void redirect(String path, String target) {
+        handlers.put(URI.create(path), e -> {
+            e.getResponseHeaders().set("Location", target);
+            e.sendResponseHeaders(301, 0);
+        });
+    }
+
+    // Return 404 not found for a given path
+    private static void notFound(String path) {
+        handlers.put(URI.create(path),  e ->
+                e.sendResponseHeaders(404, 0));
+    }
+
+    @AfterAll
+    static void shutdown() {
+        server.stop(2000);
+    }
+
+    @BeforeEach
+    void reset() {
+        synchronized (log) {
+            log.clear();
+        }
+        handlers.clear();
+    }
+
+    // Check that getResource does single HEAD request
+    @Test
+    void getResourceSingleHead() {
+        URL url = loader.getResource("foo.gif");
+        // Expect one HEAD
+        assertRequests(e -> e
+                .request("HEAD", "/dir1/foo.gif")
+        );
+    }
+
+    // Check that getResource follows redirects
+    @Test
+    void getResourceShouldFollowRedirect() {
+        redirect("/dir1/foo.gif", "/dir1/target.gif");
+        URL url = loader.getResource("foo.gif");
+        // Expect extra HEAD for redirect target
+        assertRequests(e -> e
+                .request("HEAD", "/dir1/foo.gif")
+                .request("HEAD", "/dir1/target.gif")
+        );
+
+        /*
+         * Note: Long-standing behavior is that URLClassLoader:getResource
+         * returns a URL for the requested resource, not the location redirected to
+         */
+        assertEquals("/dir1/foo.gif", url.getPath());
+
+    }
+
+    // Check that getResource treats a redirect to a not-found resource as a not-found resource
+    @Test
+    void getResourceRedirectTargetNotFound() {
+        redirect("/dir1/foo.gif", "/dir1/target.gif");
+        notFound("/dir1/target.gif");
+        URL url = loader.getResource("foo.gif");
+        // Expect extra HEAD for redirect target and next URL in search path
+        assertRequests(e -> e
+                .request("HEAD", "/dir1/foo.gif")
+                .request("HEAD", "/dir1/target.gif")
+                .request("HEAD", "/dir2/foo.gif")
+
+        );
+        // Should find URL for /dir2
+        assertEquals("/dir2/foo.gif", url.getPath());
+    }
+
+    // Check that getResourceAsStream does one HEAD and one GET request
+    @Test
+    void getResourceAsStreamSingleGet() throws IOException {
+        // Expect content from the first path
+        try (var in = loader.getResourceAsStream("foo2.gif")) {
+            assertEquals("/dir1/foo2.gif",
+                    new String(in.readAllBytes(), StandardCharsets.UTF_8));
+        }
+        // Expect one HEAD, one GET
+        assertRequests( e -> e
+                .request("HEAD", "/dir1/foo2.gif")
+                .request("GET",  "/dir1/foo2.gif")
+        );
+    }
+
+    // Check that getResourceAsStream follows redirects
+    @Test
+    void getResourceAsStreamFollowRedirect() throws IOException {
+        redirect("/dir1/foo.gif", "/dir1/target.gif");
+        // Expect content from the redirected location
+        try (var in = loader.getResourceAsStream("foo.gif")) {
+            assertEquals("/dir1/target.gif",
+                    new String(in.readAllBytes(), StandardCharsets.UTF_8));
         }
 
-        // Test 2 - check that getResourceAsStream does at most
-        //          one GET request
-        svr.counters().reset();
-        InputStream in = cl.getResourceAsStream("foo2.gif");
-        in.close();
-        System.out.println(svr.counters());
-        if (svr.counters().getCount() > 1) {
-            failed = true;
+        /*
+         * Note: Long standing behavior of URLClassLoader::getResourceAsStream
+         * is to use HEAD during the findResource resource discovery and to not
+         * "remember" the HEAD redirect location when performing the GET. This
+         * explains why we observe two redirects here, one for HEAD, one for GET.
+         */
+        assertRequests( e -> e
+                .request("HEAD", "/dir1/foo.gif")
+                .request("HEAD", "/dir1/target.gif")
+                .request("GET",  "/dir1/foo.gif")
+                .request("GET",  "/dir1/target.gif")
+        );
+    }
+
+    // getResourceAsStream on a 404 should try next path
+    @Test
+    void getResourceTryNextPath() throws IOException {
+        // Make the first path return 404
+        notFound("/dir1/foo.gif");
+        // Expect content from the second path
+        try (var in = loader.getResourceAsStream("foo.gif")) {
+            assertEquals("/dir2/foo.gif",
+                    new String(in.readAllBytes(), StandardCharsets.UTF_8));
         }
+        // Expect two HEADs, one GET
+        assertRequests(e -> e
+                .request("HEAD", "/dir1/foo.gif")
+                .request("HEAD", "/dir2/foo.gif")
+                .request("GET",  "/dir2/foo.gif")
+        );
+    }
 
-        // Test 3 - check that getResources only does HEAD requests
-        svr.counters().reset();
-        Enumeration e = cl.getResources("foos.gif");
-        try {
-            for (;;) {
-                e.nextElement();
-            }
-        } catch (NoSuchElementException exc) { }
-        System.out.println(svr.counters());
-        if (svr.counters().getCount() > 1) {
-            failed = true;
-        }
+    // Check that getResources only does HEAD requests
+    @Test
+    void getResourcesOnlyHead() throws IOException {
+        Collections.list(loader.getResources("foos.gif"));
+        // Expect one HEAD for each path
+        assertRequests(e ->  e
+                .request("HEAD", "/dir1/foos.gif")
+                .request("HEAD", "/dir2/foos.gif")
+        );
+    }
 
-        // shutdown http server
-        svr.shutdown();
+    // Check that getResources skips 404 URL
+    @Test
+    void getResourcesShouldSkipFailedHead() throws IOException {
+        // Make first path fail with 404
+        notFound("/dir1/foos.gif");
+        List resources = Collections.list(loader.getResources("foos.gif"));
+        // Expect one HEAD for each path
+        assertRequests(e ->  e
+                .request("HEAD", "/dir1/foos.gif")
+                .request("HEAD", "/dir2/foos.gif")
+        );
 
-        if (failed) {
-            throw new Exception("Excessive http connections established - Test failed");
+        // Expect a single URL to be returned
+        assertEquals(1, resources.size());
+    }
+
+    // Utils for asserting requests
+    static class Expect {
+        List requests = new ArrayList<>();
+
+        Expect request(String method, String path) {
+            requests.add(new Request(method, URI.create(path)));
+            return this;
         }
     }
 
+    static void assertRequests(Consumer e) {
+        // Collect expected requests
+        Expect exp = new Expect();
+        e.accept(exp);
+        List expected = exp.requests;
+
+        // Actual requests
+        List requests = log.requests();
+
+        // Verify expected number of requests
+        assertEquals(expected.size(), requests.size(), "Unexpected request count");
+
+        // Verify expected requests in order
+        for (int i = 0; i < expected.size(); i++) {
+            Request ex = expected.get(i);
+            Request req = requests.get(i);
+            // Verify method
+            assertEquals(ex.method, req.method,
+                    String.format("Request %s has unexpected method %s", i, ex.method)
+            );
+            // Verify path
+            assertEquals(ex.path, req.path,
+                    String.format("Request %s has unexpected request URI %s", i, ex.path)
+            );
+        }
+    }
 }

From 4f83d211d16bf7aab8b3d7128df6764e017166ef Mon Sep 17 00:00:00 2001
From: Vicente Romero 
Date: Thu, 26 Feb 2026 15:18:54 +0000
Subject: [PATCH 22/54] 8368864: Confusing error message (or wrong error) when
 record component has @deprecated Javadoc tag

Reviewed-by: jlahoda
---
 .../sun/tools/javac/parser/JavacParser.java   |  6 +++
 .../javac/records/RecordCompilationTests.java | 52 +++++++++++++++++++
 2 files changed, 58 insertions(+)

diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
index 16f26c836f8..d32b892eb54 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
@@ -5406,6 +5406,12 @@ public class JavacParser implements Parser {
 
         if (recordComponent) {
             mods = modifiersOpt();
+            /* it could be that the user added a javadoc with the @deprecated tag, when analyzing this
+             * javadoc, javac will set the DEPRECATED flag. This is correct in most cases but not for
+             * record components and thus should be removed in that case. Any javadoc applied to
+             * record components is ignored
+             */
+            mods.flags &= ~Flags.DEPRECATED;
         } else {
             mods = optFinal(Flags.PARAMETER | (lambdaParameter ? Flags.LAMBDA_PARAMETER : 0));
         }
diff --git a/test/langtools/tools/javac/records/RecordCompilationTests.java b/test/langtools/tools/javac/records/RecordCompilationTests.java
index a8384ba4692..48b5cdd8588 100644
--- a/test/langtools/tools/javac/records/RecordCompilationTests.java
+++ b/test/langtools/tools/javac/records/RecordCompilationTests.java
@@ -2169,4 +2169,56 @@ class RecordCompilationTests extends CompilationTestCase {
                 """
         );
     }
+
+    @Test
+    void testDeprecatedJavadoc() {
+        String[] previousOptions = getCompileOptions();
+        try {
+            setCompileOptions(new String[] {"-Xlint:deprecation"});
+            assertOKWithWarning("compiler.warn.has.been.deprecated",
+                """
+                record R(
+                    /**
+                     * @deprecated
+                     */
+                    @Deprecated
+                    int i
+                ) {}
+                class Client {
+                    R r;
+                    int j = r.i();
+                }
+                """
+            );
+            assertOKWithWarning("compiler.warn.has.been.deprecated",
+                """
+                record R(
+                    @Deprecated
+                    int i
+                ) {}
+                class Client {
+                    R r;
+                    int j = r.i();
+                }
+                """
+            );
+            // javadoc tag only has no effect
+            assertOK(
+                    """
+                    record R(
+                        /**
+                         * @deprecated
+                         */
+                        int i
+                    ) {}
+                    class Client {
+                        R r;
+                        int j = r.i();
+                    }
+                    """
+            );
+        } finally {
+            setCompileOptions(previousOptions);
+        }
+    }
 }

From 94de8982f99ff7fd5d955246a56a12bf2bf69785 Mon Sep 17 00:00:00 2001
From: Vicente Romero 
Date: Thu, 26 Feb 2026 15:21:31 +0000
Subject: [PATCH 23/54] 8372382: Invalid RuntimeVisibleTypeAnnotations for
 compact record constructor

Reviewed-by: liach
---
 .../com/sun/tools/javac/parser/JavacParser.java    |  5 +++--
 .../TypeAnnotationsPositionsOnRecords.java         | 14 ++++++++++++++
 2 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
index d32b892eb54..df5da5cb954 100644
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
@@ -4421,12 +4421,13 @@ public class JavacParser implements Parser {
                 JCMethodDecl methDef = (JCMethodDecl) def;
                 if (methDef.name == names.init && methDef.params.isEmpty() && (methDef.mods.flags & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0) {
                     ListBuffer tmpParams = new ListBuffer<>();
+                    TreeCopier copier = new TreeCopier<>(F);
                     for (JCVariableDecl param : headerFields) {
                         tmpParams.add(F.at(param)
                                 // we will get flags plus annotations from the record component
                                 .VarDef(F.Modifiers(Flags.PARAMETER | Flags.GENERATED_MEMBER | Flags.MANDATED | param.mods.flags & Flags.VARARGS,
-                                        param.mods.annotations),
-                                param.name, param.vartype, null));
+                                        copier.copy(param.mods.annotations)),
+                                param.name, copier.copy(param.vartype), null));
                     }
                     methDef.params = tmpParams.toList();
                 }
diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java
index dfa266ef035..b8ee32fcacd 100644
--- a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java
+++ b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java
@@ -78,6 +78,17 @@ public class TypeAnnotationsPositionsOnRecords {
             record Record6(String t1, @Nullable String t2) {
                 public Record6 {}
             }
+
+            class Test2 {
+                @Target(ElementType.TYPE_USE)
+                @Retention(RetentionPolicy.RUNTIME)
+                public @interface Anno {}
+
+                class Foo {}
+                record Record7(Test2.@Anno Foo foo) {
+                    public Record7 {} // compact constructor
+                }
+            }
             """;
 
     public static void main(String... args) throws Exception {
@@ -100,6 +111,8 @@ public class TypeAnnotationsPositionsOnRecords {
                 "Record5.class").toUri()), 1);
         checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
                 "Record6.class").toUri()), 1);
+        checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
+                "Test2$Record7.class").toUri()), 0);
     }
 
     void compileTestClass() throws Exception {
@@ -110,6 +123,7 @@ public class TypeAnnotationsPositionsOnRecords {
 
     void checkClassFile(final File cfile, int... taPositions) throws Exception {
         ClassModel classFile = ClassFile.of().parse(cfile.toPath());
+        System.err.println("-----------loading " + cfile.getPath());
         int accessorPos = 0;
         int checkedAccessors = 0;
         for (MethodModel method : classFile.methods()) {

From 71a1af7d0b4723c8ed740fc40ede75091ecf8c07 Mon Sep 17 00:00:00 2001
From: Phil Race 
Date: Thu, 26 Feb 2026 16:23:24 +0000
Subject: [PATCH 24/54] 8378377: Remove use of AppContext from JEditorPane

Reviewed-by: serb, dnguyen, psadhukhan
---
 .../classes/javax/swing/JEditorPane.java      | 95 +++++--------------
 1 file changed, 23 insertions(+), 72 deletions(-)

diff --git a/src/java.desktop/share/classes/javax/swing/JEditorPane.java b/src/java.desktop/share/classes/javax/swing/JEditorPane.java
index 2f8f0f30722..3134b8bace2 100644
--- a/src/java.desktop/share/classes/javax/swing/JEditorPane.java
+++ b/src/java.desktop/share/classes/javax/swing/JEditorPane.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -1227,12 +1227,11 @@ public class JEditorPane extends JTextComponent {
      */
     @SuppressWarnings("deprecation")
     public static EditorKit createEditorKitForContentType(String type) {
-        Hashtable kitRegistry = getKitRegistry();
         EditorKit k = kitRegistry.get(type);
         if (k == null) {
             // try to dynamically load the support
-            String classname = getKitTypeRegistry().get(type);
-            ClassLoader loader = getKitLoaderRegistry().get(type);
+            String classname = kitTypeRegistry.get(type);
+            ClassLoader loader = kitLoaderRegistry.get(type);
             try {
                 Class c;
                 if (loader != null) {
@@ -1287,13 +1286,13 @@ public class JEditorPane extends JTextComponent {
      * @param loader the ClassLoader to use to load the name
      */
     public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
-        getKitTypeRegistry().put(type, classname);
+        kitTypeRegistry.put(type, classname);
         if (loader != null) {
-            getKitLoaderRegistry().put(type, loader);
+            kitLoaderRegistry.put(type, loader);
         } else {
-            getKitLoaderRegistry().remove(type);
+            kitLoaderRegistry.remove(type);
         }
-        getKitRegistry().remove(type);
+        kitRegistry.remove(type);
     }
 
     /**
@@ -1306,63 +1305,27 @@ public class JEditorPane extends JTextComponent {
      * @since 1.3
      */
     public static String getEditorKitClassNameForContentType(String type) {
-        return getKitTypeRegistry().get(type);
+        return kitTypeRegistry.get(type);
     }
 
-    private static Hashtable getKitTypeRegistry() {
-        loadDefaultKitsIfNecessary();
-        @SuppressWarnings("unchecked")
-        Hashtable tmp =
-            (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
-        return tmp;
-    }
+    private static final Hashtable kitTypeRegistry = new Hashtable<>();
+    private static final Hashtable kitLoaderRegistry = new Hashtable<>();
 
-    private static Hashtable getKitLoaderRegistry() {
-        loadDefaultKitsIfNecessary();
-        @SuppressWarnings("unchecked")
-        Hashtable tmp =
-            (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
-        return tmp;
-    }
+    private static final Hashtable kitRegistry = new Hashtable<>(3);
 
-    private static Hashtable getKitRegistry() {
-        @SuppressWarnings("unchecked")
-        Hashtable ht =
-            (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
-        if (ht == null) {
-            ht = new Hashtable<>(3);
-            SwingUtilities.appContextPut(kitRegistryKey, ht);
-        }
-        return ht;
-    }
-
-    /**
-     * This is invoked every time the registries are accessed. Loading
-     * is done this way instead of via a static as the static is only
-     * called once when running in an AppContext.
-     */
-    private static void loadDefaultKitsIfNecessary() {
-        if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) {
-            synchronized(defaultEditorKitMap) {
-                if (defaultEditorKitMap.size() == 0) {
-                    defaultEditorKitMap.put("text/plain",
-                                            "javax.swing.JEditorPane$PlainEditorKit");
-                    defaultEditorKitMap.put("text/html",
-                                            "javax.swing.text.html.HTMLEditorKit");
-                    defaultEditorKitMap.put("text/rtf",
-                                            "javax.swing.text.rtf.RTFEditorKit");
-                    defaultEditorKitMap.put("application/rtf",
-                                            "javax.swing.text.rtf.RTFEditorKit");
-                }
-            }
-            Hashtable ht = new Hashtable<>();
-            SwingUtilities.appContextPut(kitTypeRegistryKey, ht);
-            ht = new Hashtable<>();
-            SwingUtilities.appContextPut(kitLoaderRegistryKey, ht);
-            for (String key : defaultEditorKitMap.keySet()) {
-                registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
-            }
+    static final Map defaultEditorKitMap = new HashMap(0);
 
+    static {
+        defaultEditorKitMap.put("text/plain",
+                                "javax.swing.JEditorPane$PlainEditorKit");
+        defaultEditorKitMap.put("text/html",
+                                "javax.swing.text.html.HTMLEditorKit");
+        defaultEditorKitMap.put("text/rtf",
+                                "javax.swing.text.rtf.RTFEditorKit");
+        defaultEditorKitMap.put("application/rtf",
+                                "javax.swing.text.rtf.RTFEditorKit");
+        for (String key : defaultEditorKitMap.keySet()) {
+            registerEditorKitForContentType(key,defaultEditorKitMap.get(key));
         }
     }
 
@@ -1587,16 +1550,6 @@ public class JEditorPane extends JTextComponent {
      */
     private Hashtable typeHandlers;
 
-    /*
-     * Private AppContext keys for this class's static variables.
-     */
-    private static final Object kitRegistryKey =
-        new StringBuffer("JEditorPane.kitRegistry");
-    private static final Object kitTypeRegistryKey =
-        new StringBuffer("JEditorPane.kitTypeRegistry");
-    private static final Object kitLoaderRegistryKey =
-        new StringBuffer("JEditorPane.kitLoaderRegistry");
-
     /**
      * @see #getUIClassID
      * @see #readObject
@@ -1633,8 +1586,6 @@ public class JEditorPane extends JTextComponent {
      */
     public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
 
-    static final Map defaultEditorKitMap = new HashMap(0);
-
     /**
      * Returns a string representation of this JEditorPane.
      * This method

From fcc2a2922fe0312758a9eef5f1ea371e5803bc8b Mon Sep 17 00:00:00 2001
From: Phil Race 
Date: Thu, 26 Feb 2026 16:23:49 +0000
Subject: [PATCH 25/54] 8378297: Remove AppContext from several Swing component
 and related classes

Reviewed-by: azvegint, psadhukhan, dnguyen
---
 .../classes/javax/swing/DebugGraphics.java    | 16 ++--
 .../share/classes/javax/swing/JDialog.java    | 24 ++----
 .../share/classes/javax/swing/JFrame.java     | 24 ++----
 .../share/classes/javax/swing/JPopupMenu.java | 20 +----
 .../classes/javax/swing/PopupFactory.java     | 63 ++++++----------
 .../classes/javax/swing/SwingUtilities.java   | 20 ++---
 .../classes/javax/swing/ToolTipManager.java   | 13 ++--
 .../swing/ToolTipManager/Test6657026.java     | 75 -------------------
 8 files changed, 57 insertions(+), 198 deletions(-)
 delete mode 100644 test/jdk/javax/swing/ToolTipManager/Test6657026.java

diff --git a/src/java.desktop/share/classes/javax/swing/DebugGraphics.java b/src/java.desktop/share/classes/javax/swing/DebugGraphics.java
index 83b44716c04..512b56ee28a 100644
--- a/src/java.desktop/share/classes/javax/swing/DebugGraphics.java
+++ b/src/java.desktop/share/classes/javax/swing/DebugGraphics.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -1492,14 +1492,12 @@ public class DebugGraphics extends Graphics {
     /** Returns DebugGraphicsInfo, or creates one if none exists.
       */
     static DebugGraphicsInfo info() {
-        DebugGraphicsInfo debugGraphicsInfo = (DebugGraphicsInfo)
-            SwingUtilities.appContextGet(debugGraphicsInfoKey);
-        if (debugGraphicsInfo == null) {
-            debugGraphicsInfo = new DebugGraphicsInfo();
-            SwingUtilities.appContextPut(debugGraphicsInfoKey,
-                                         debugGraphicsInfo);
+        synchronized (DebugGraphicsInfo.class) {
+            if (debugGraphicsInfo == null) {
+                debugGraphicsInfo = new DebugGraphicsInfo();
+            }
+            return debugGraphicsInfo;
         }
-        return debugGraphicsInfo;
     }
-    private static final Class debugGraphicsInfoKey = DebugGraphicsInfo.class;
+    private static DebugGraphicsInfo debugGraphicsInfo;
 }
diff --git a/src/java.desktop/share/classes/javax/swing/JDialog.java b/src/java.desktop/share/classes/javax/swing/JDialog.java
index 99d6385cd7c..a7d8791c72c 100644
--- a/src/java.desktop/share/classes/javax/swing/JDialog.java
+++ b/src/java.desktop/share/classes/javax/swing/JDialog.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -101,13 +101,6 @@ public class JDialog extends Dialog implements WindowConstants,
                                                RootPaneContainer,
                                TransferHandler.HasGetTransferHandler
 {
-    /**
-     * Key into the AppContext, used to check if should provide decorations
-     * by default.
-     */
-    private static final Object defaultLookAndFeelDecoratedKey =
-            new StringBuffer("JDialog.defaultLookAndFeelDecorated");
-
     private int defaultCloseOperation = HIDE_ON_CLOSE;
 
     /**
@@ -1119,6 +1112,8 @@ public class JDialog extends Dialog implements WindowConstants,
         }
     }
 
+    private static boolean defaultLAFDecorated;
+
     /**
      * Provides a hint as to whether or not newly created {@code JDialog}s
      * should have their Window decorations (such as borders, widgets to
@@ -1144,11 +1139,7 @@ public class JDialog extends Dialog implements WindowConstants,
      * @since 1.4
      */
     public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) {
-        if (defaultLookAndFeelDecorated) {
-            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE);
-        } else {
-            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE);
-        }
+        defaultLAFDecorated = defaultLookAndFeelDecorated;
     }
 
     /**
@@ -1160,12 +1151,7 @@ public class JDialog extends Dialog implements WindowConstants,
      * @since 1.4
      */
     public static boolean isDefaultLookAndFeelDecorated() {
-        Boolean defaultLookAndFeelDecorated =
-            (Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey);
-        if (defaultLookAndFeelDecorated == null) {
-            defaultLookAndFeelDecorated = Boolean.FALSE;
-        }
-        return defaultLookAndFeelDecorated.booleanValue();
+        return defaultLAFDecorated;
     }
 
     /**
diff --git a/src/java.desktop/share/classes/javax/swing/JFrame.java b/src/java.desktop/share/classes/javax/swing/JFrame.java
index 8bde7e18f03..bab215625b9 100644
--- a/src/java.desktop/share/classes/javax/swing/JFrame.java
+++ b/src/java.desktop/share/classes/javax/swing/JFrame.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -126,13 +126,6 @@ public class JFrame  extends Frame implements WindowConstants,
                                               RootPaneContainer,
                               TransferHandler.HasGetTransferHandler
 {
-    /**
-     * Key into the AppContext, used to check if should provide decorations
-     * by default.
-     */
-    private static final Object defaultLookAndFeelDecoratedKey =
-            new StringBuffer("JFrame.defaultLookAndFeelDecorated");
-
     private int defaultCloseOperation = HIDE_ON_CLOSE;
 
     /**
@@ -755,6 +748,8 @@ public class JFrame  extends Frame implements WindowConstants,
         }
     }
 
+    private static boolean defaultLAFDecorated;
+
     /**
      * Provides a hint as to whether or not newly created JFrames
      * should have their Window decorations (such as borders, widgets to
@@ -780,11 +775,7 @@ public class JFrame  extends Frame implements WindowConstants,
      * @since 1.4
      */
     public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) {
-        if (defaultLookAndFeelDecorated) {
-            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE);
-        } else {
-            SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE);
-        }
+        defaultLAFDecorated = defaultLookAndFeelDecorated;
     }
 
 
@@ -797,12 +788,7 @@ public class JFrame  extends Frame implements WindowConstants,
      * @since 1.4
      */
     public static boolean isDefaultLookAndFeelDecorated() {
-        Boolean defaultLookAndFeelDecorated =
-            (Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey);
-        if (defaultLookAndFeelDecorated == null) {
-            defaultLookAndFeelDecorated = Boolean.FALSE;
-        }
-        return defaultLookAndFeelDecorated.booleanValue();
+        return defaultLAFDecorated;
     }
 
     /**
diff --git a/src/java.desktop/share/classes/javax/swing/JPopupMenu.java b/src/java.desktop/share/classes/javax/swing/JPopupMenu.java
index 1b04e8c6169..2ecc7cf3b1e 100644
--- a/src/java.desktop/share/classes/javax/swing/JPopupMenu.java
+++ b/src/java.desktop/share/classes/javax/swing/JPopupMenu.java
@@ -112,12 +112,6 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement {
      */
     private static final String uiClassID = "PopupMenuUI";
 
-    /**
-     * Key used in AppContext to determine if light way popups are the default.
-     */
-    private static final Object defaultLWPopupEnabledKey =
-        new StringBuffer("JPopupMenu.defaultLWPopupEnabledKey");
-
     /** Bug#4425878-Property javax.swing.adjustPopupLocationToFit introduced */
     static boolean popupPositionFixDisabled =
          System.getProperty("javax.swing.adjustPopupLocationToFit","").equals("false");
@@ -153,6 +147,8 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement {
     private static final boolean VERBOSE = false; // show reuse hits/misses
     private static final boolean DEBUG =   false;  // show bad params, misc.
 
+    private static boolean defaultLWPopupEnabled = true;
+
     /**
      *  Sets the default value of the lightWeightPopupEnabled
      *  property.
@@ -163,8 +159,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement {
      *  @see #setLightWeightPopupEnabled
      */
     public static void setDefaultLightWeightPopupEnabled(boolean aFlag) {
-        SwingUtilities.appContextPut(defaultLWPopupEnabledKey,
-                                     Boolean.valueOf(aFlag));
+        defaultLWPopupEnabled = aFlag;
     }
 
     /**
@@ -177,14 +172,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement {
      *  @see #setDefaultLightWeightPopupEnabled
      */
     public static boolean getDefaultLightWeightPopupEnabled() {
-        Boolean b = (Boolean)
-            SwingUtilities.appContextGet(defaultLWPopupEnabledKey);
-        if (b == null) {
-            SwingUtilities.appContextPut(defaultLWPopupEnabledKey,
-                                         Boolean.TRUE);
-            return true;
-        }
-        return b.booleanValue();
+        return defaultLWPopupEnabled;
     }
 
     /**
diff --git a/src/java.desktop/share/classes/javax/swing/PopupFactory.java b/src/java.desktop/share/classes/javax/swing/PopupFactory.java
index 2b274c816b1..208177fc55e 100644
--- a/src/java.desktop/share/classes/javax/swing/PopupFactory.java
+++ b/src/java.desktop/share/classes/javax/swing/PopupFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -80,13 +80,6 @@ public class PopupFactory {
             }
         });
     }
-    /**
-     * The shared instanceof PopupFactory is per
-     * AppContext. This is the key used in the
-     * AppContext to locate the PopupFactory.
-     */
-    private static final Object SharedInstanceKey =
-        new StringBuffer("PopupFactory.SharedInstanceKey");
 
     /**
      * Max number of items to store in any one particular cache.
@@ -118,6 +111,7 @@ public class PopupFactory {
      */
     public PopupFactory() {}
 
+    static PopupFactory sharedFactory;
     /**
      * Sets the PopupFactory that will be used to obtain
      * Popups.
@@ -132,7 +126,9 @@ public class PopupFactory {
         if (factory == null) {
             throw new IllegalArgumentException("PopupFactory can not be null");
         }
-        SwingUtilities.appContextPut(SharedInstanceKey, factory);
+        synchronized (PopupFactory.class) {
+            sharedFactory = factory;
+        }
     }
 
     /**
@@ -142,14 +138,12 @@ public class PopupFactory {
      * @return Shared PopupFactory
      */
     public static PopupFactory getSharedInstance() {
-        PopupFactory factory = (PopupFactory)SwingUtilities.appContextGet(
-                         SharedInstanceKey);
-
-        if (factory == null) {
-            factory = new PopupFactory();
-            setSharedInstance(factory);
+        synchronized (PopupFactory.class) {
+            if (sharedFactory == null) {
+                sharedFactory = new PopupFactory();
+            }
+            return sharedFactory;
         }
-        return factory;
     }
 
 
@@ -351,8 +345,6 @@ public class PopupFactory {
      * Popup implementation that uses a Window as the popup.
      */
     private static class HeavyWeightPopup extends Popup {
-        private static final Object heavyWeightPopupCacheKey =
-                 new StringBuffer("PopupFactory.heavyWeightPopupCache");
 
         private volatile boolean isCacheEnabled = true;
 
@@ -434,21 +426,16 @@ public class PopupFactory {
             }
         }
 
+        private static Map> cache;
         /**
          * Returns the cache to use for heavy weight popups. Maps from
          * Window to a List of
          * HeavyWeightPopups.
          */
-        @SuppressWarnings("unchecked")
         private static Map> getHeavyWeightPopupCache() {
             synchronized (HeavyWeightPopup.class) {
-                Map> cache = (Map>)SwingUtilities.appContextGet(
-                                  heavyWeightPopupCacheKey);
-
                 if (cache == null) {
                     cache = new HashMap<>(2);
-                    SwingUtilities.appContextPut(heavyWeightPopupCacheKey,
-                                                 cache);
                 }
                 return cache;
             }
@@ -728,18 +715,17 @@ public class PopupFactory {
             return popup;
         }
 
+        private static List cache;
         /**
          * Returns the cache to use for heavy weight popups.
          */
-        @SuppressWarnings("unchecked")
         private static List getLightWeightPopupCache() {
-            List cache = (List)SwingUtilities.appContextGet(
-                                   lightWeightPopupCacheKey);
-            if (cache == null) {
-                cache = new ArrayList<>();
-                SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache);
+            synchronized (LightWeightPopup.class) {
+                if (cache == null) {
+                    cache = new ArrayList<>();
+                }
+                return cache;
             }
-            return cache;
         }
 
         /**
@@ -849,8 +835,6 @@ public class PopupFactory {
      * Popup implementation that uses a Panel as the popup.
      */
     private static class MediumWeightPopup extends ContainerPopup {
-        private static final Object mediumWeightPopupCacheKey =
-                             new StringBuffer("PopupFactory.mediumPopupCache");
 
         /** Child of the panel. The contents are added to this. */
         private JRootPane rootPane;
@@ -877,19 +861,18 @@ public class PopupFactory {
             return popup;
         }
 
+        private static List cache;
         /**
          * Returns the cache to use for medium weight popups.
          */
         @SuppressWarnings("unchecked")
         private static List getMediumWeightPopupCache() {
-            List cache = (List)SwingUtilities.appContextGet(
-                                    mediumWeightPopupCacheKey);
-
-            if (cache == null) {
-                cache = new ArrayList<>();
-                SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache);
+            synchronized (MediumWeightPopup.class) {
+                if (cache == null) {
+                    cache = new ArrayList<>();
+                }
+                return cache;
             }
-            return cache;
         }
 
         /**
diff --git a/src/java.desktop/share/classes/javax/swing/SwingUtilities.java b/src/java.desktop/share/classes/javax/swing/SwingUtilities.java
index bc6441212de..afe1c444c31 100644
--- a/src/java.desktop/share/classes/javax/swing/SwingUtilities.java
+++ b/src/java.desktop/share/classes/javax/swing/SwingUtilities.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -1899,11 +1899,6 @@ public class SwingUtilities implements SwingConstants
         return null;
     }
 
-
-    // Don't use String, as it's not guaranteed to be unique in a Hashtable.
-    private static final Object sharedOwnerFrameKey =
-       new StringBuffer("SwingUtilities.sharedOwnerFrame");
-
     @SuppressWarnings("serial") // JDK-implementation class
     static class SharedOwnerFrame extends Frame implements WindowListener {
         public void addNotify() {
@@ -1961,6 +1956,7 @@ public class SwingUtilities implements SwingConstants
         }
     }
 
+    private static Frame sharedOwnerFrame;
     /**
      * Returns a toolkit-private, shared, invisible Frame
      * to be the owner for JDialogs and JWindows created with
@@ -1970,14 +1966,12 @@ public class SwingUtilities implements SwingConstants
      * @see java.awt.GraphicsEnvironment#isHeadless
      */
     static Frame getSharedOwnerFrame() throws HeadlessException {
-        Frame sharedOwnerFrame =
-            (Frame)SwingUtilities.appContextGet(sharedOwnerFrameKey);
-        if (sharedOwnerFrame == null) {
-            sharedOwnerFrame = new SharedOwnerFrame();
-            SwingUtilities.appContextPut(sharedOwnerFrameKey,
-                                         sharedOwnerFrame);
+        synchronized (SharedOwnerFrame.class) {
+            if (sharedOwnerFrame == null) {
+                sharedOwnerFrame = new SharedOwnerFrame();
+            }
+            return sharedOwnerFrame;
         }
-        return sharedOwnerFrame;
     }
 
     /**
diff --git a/src/java.desktop/share/classes/javax/swing/ToolTipManager.java b/src/java.desktop/share/classes/javax/swing/ToolTipManager.java
index a9e2c6e69bb..4c3d0209823 100644
--- a/src/java.desktop/share/classes/javax/swing/ToolTipManager.java
+++ b/src/java.desktop/share/classes/javax/swing/ToolTipManager.java
@@ -61,7 +61,6 @@ public final class ToolTipManager extends MouseAdapter implements MouseMotionLis
     JComponent insideComponent;
     MouseEvent mouseEvent;
     boolean showImmediately;
-    private static final Object TOOL_TIP_MANAGER_KEY = new Object();
     transient Popup tipWindow;
     /** The Window tip is being displayed in. This will be non-null if
      * the Window tip is in differs from that of insideComponent's Window.
@@ -394,19 +393,19 @@ public final class ToolTipManager extends MouseAdapter implements MouseMotionLis
         }
     }
 
+    private static ToolTipManager manager;
     /**
      * Returns a shared ToolTipManager instance.
      *
      * @return a shared ToolTipManager object
      */
     public static ToolTipManager sharedInstance() {
-        Object value = SwingUtilities.appContextGet(TOOL_TIP_MANAGER_KEY);
-        if (value instanceof ToolTipManager) {
-            return (ToolTipManager) value;
+        synchronized(ToolTipManager.class) {
+            if (manager == null) {
+                manager = new ToolTipManager();
+            }
+            return manager;
         }
-        ToolTipManager manager = new ToolTipManager();
-        SwingUtilities.appContextPut(TOOL_TIP_MANAGER_KEY, manager);
-        return manager;
     }
 
     // add keylistener here to trigger tip for access
diff --git a/test/jdk/javax/swing/ToolTipManager/Test6657026.java b/test/jdk/javax/swing/ToolTipManager/Test6657026.java
deleted file mode 100644
index 0678d57f768..00000000000
--- a/test/jdk/javax/swing/ToolTipManager/Test6657026.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2009, 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 6657026
- * @summary Tests shared ToolTipManager in different application contexts
- * @author Sergey Malenkov
- * @modules java.desktop/sun.awt
- */
-
-import sun.awt.SunToolkit;
-import javax.swing.ToolTipManager;
-
-public class Test6657026 implements Runnable {
-
-    private static final int DISMISS = 4000;
-    private static final int INITIAL = 750;
-    private static final int RESHOW = 500;
-
-    public static void main(String[] args) throws InterruptedException {
-        ToolTipManager manager = ToolTipManager.sharedInstance();
-        if (DISMISS != manager.getDismissDelay()) {
-            throw new Error("unexpected dismiss delay");
-        }
-        if (INITIAL != manager.getInitialDelay()) {
-            throw new Error("unexpected initial delay");
-        }
-        if (RESHOW != manager.getReshowDelay()) {
-            throw new Error("unexpected reshow delay");
-        }
-        manager.setDismissDelay(DISMISS + 1);
-        manager.setInitialDelay(INITIAL + 1);
-        manager.setReshowDelay(RESHOW + 1);
-
-        ThreadGroup group = new ThreadGroup("$$$");
-        Thread thread = new Thread(group, new Test6657026());
-        thread.start();
-        thread.join();
-    }
-
-    public void run() {
-        SunToolkit.createNewAppContext();
-        ToolTipManager manager = ToolTipManager.sharedInstance();
-        if (DISMISS != manager.getDismissDelay()) {
-            throw new Error("shared dismiss delay");
-        }
-        if (INITIAL != manager.getInitialDelay()) {
-            throw new Error("shared initial delay");
-        }
-        if (RESHOW != manager.getReshowDelay()) {
-            throw new Error("shared reshow delay");
-        }
-    }
-}

From 8b805630b4c54a8e9e489cff08f0260cd42dc362 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Eirik=20Bj=C3=B8rsn=C3=B8s?= 
Date: Thu, 26 Feb 2026 16:33:51 +0000
Subject: [PATCH 26/54] 8376477: Avoid loading empty Lock classes in Shutdown
 and ReferenceQueue

Reviewed-by: rriggs, shade
---
 src/java.base/share/classes/java/lang/Shutdown.java        | 7 +++----
 .../share/classes/java/lang/ref/ReferenceQueue.java        | 5 ++---
 2 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/src/java.base/share/classes/java/lang/Shutdown.java b/src/java.base/share/classes/java/lang/Shutdown.java
index 87c4732a5ce..a9d4d6a28a9 100644
--- a/src/java.base/share/classes/java/lang/Shutdown.java
+++ b/src/java.base/share/classes/java/lang/Shutdown.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -55,11 +55,10 @@ class Shutdown {
     private static int currentRunningHook = -1;
 
     /* The preceding static fields are protected by this lock */
-    private static class Lock { };
-    private static Object lock = new Lock();
+    private static final Object lock = new Object();
 
     /* Lock object for the native halt method */
-    private static Object haltLock = new Lock();
+    private static final Object haltLock = new Object();
 
     /**
      * Add a new system shutdown hook.  Checks the shutdown state and
diff --git a/src/java.base/share/classes/java/lang/ref/ReferenceQueue.java b/src/java.base/share/classes/java/lang/ref/ReferenceQueue.java
index d3879d4a8fc..ee1892e8878 100644
--- a/src/java.base/share/classes/java/lang/ref/ReferenceQueue.java
+++ b/src/java.base/share/classes/java/lang/ref/ReferenceQueue.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -60,8 +60,7 @@ public class ReferenceQueue<@jdk.internal.RequiresIdentity T> {
     private volatile Reference head;
     private long queueLength = 0;
 
-    private static class Lock { };
-    private final Lock lock = new Lock();
+    private final Object lock = new Object();
 
     /**
      * Constructs a new reference-object queue.

From aa6c06e1665cd44ae880824aedb3c861f0951cb1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= 
Date: Thu, 26 Feb 2026 18:50:45 +0000
Subject: [PATCH 27/54] 8309748: Improve host selection in `External
 Specifications` page

Reviewed-by: nbenalla
---
 .../share/classes/java/lang/Character.java    | 14 ++---
 .../formats/html/ExternalSpecsWriter.java     | 62 +++++++++++++++++--
 .../html/resources/standard.properties        |  5 +-
 .../formats/html/resources/stylesheet.css     |  4 +-
 .../doclet/testSpecTag/TestSpecTag.java       | 43 +++++++++----
 5 files changed, 98 insertions(+), 30 deletions(-)

diff --git a/src/java.base/share/classes/java/lang/Character.java b/src/java.base/share/classes/java/lang/Character.java
index ffda729a45a..33284d86e2d 100644
--- a/src/java.base/share/classes/java/lang/Character.java
+++ b/src/java.base/share/classes/java/lang/Character.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 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
@@ -11233,7 +11233,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character is an Emoji;
      *          {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isEmoji(int codePoint) {
@@ -11252,7 +11252,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character has the Emoji Presentation
      *          property; {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isEmojiPresentation(int codePoint) {
@@ -11271,7 +11271,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character is an Emoji Modifier;
      *          {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isEmojiModifier(int codePoint) {
@@ -11290,7 +11290,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character is an Emoji Modifier Base;
      *          {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isEmojiModifierBase(int codePoint) {
@@ -11309,7 +11309,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character is an Emoji Component;
      *          {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isEmojiComponent(int codePoint) {
@@ -11328,7 +11328,7 @@ class Character implements java.io.Serializable, Comparable, Constabl
      * @param   codePoint the character (Unicode code point) to be tested.
      * @return  {@code true} if the character is an Extended Pictographic;
      *          {@code false} otherwise.
-     * @spec https://unicode.org/reports/tr51/ Unicode Emoji
+     * @spec https://www.unicode.org/reports/tr51/ Unicode Emoji
      * @since   21
      */
     public static boolean isExtendedPictographic(int codePoint) {
diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ExternalSpecsWriter.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ExternalSpecsWriter.java
index 0115de5558f..b8767dd9913 100644
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ExternalSpecsWriter.java
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ExternalSpecsWriter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2019, 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
@@ -57,7 +57,11 @@ import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;
 import jdk.javadoc.internal.doclets.toolkit.util.IndexItem;
 import jdk.javadoc.internal.html.Content;
 import jdk.javadoc.internal.html.ContentBuilder;
+import jdk.javadoc.internal.html.HtmlAttr;
+import jdk.javadoc.internal.html.HtmlId;
+import jdk.javadoc.internal.html.HtmlTag;
 import jdk.javadoc.internal.html.HtmlTree;
+import jdk.javadoc.internal.html.Script;
 import jdk.javadoc.internal.html.Text;
 
 import static java.util.stream.Collectors.groupingBy;
@@ -108,6 +112,24 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
                         HtmlTree.HEADING(Headings.PAGE_TITLE_HEADING,
                                 contents.getContent("doclet.External_Specifications"))))
                 .addMainContent(mainContent)
+                .addMainContent(new Script("""
+                        let select = document.getElementById('specs-by-domain');
+                        select.addEventListener("change", selectHost);
+                        addEventListener("pageshow", selectHost);
+                        function selectHost() {
+                            const selectedClass = select.value ? "external-specs-tab" + select.value : "external-specs";
+                            let tabPanel = document.getElementById("external-specs.tabpanel");
+                            let count = 0;
+                            tabPanel.querySelectorAll("div.external-specs").forEach(function(elem) {
+                                elem.style.display = elem.classList.contains(selectedClass) ? "" : "none";
+                                if (elem.style.display === "") {
+                                    let isEvenRow = count++ % 4 < 2;
+                                    toggleStyle(elem.classList, isEvenRow, evenRowColor, oddRowColor);
+                                }
+                            });
+                        }
+                        selectHost();
+                        """).asContent())
                 .setFooter(getFooter()));
         printHtmlDocument(null, "external specifications", body);
 
@@ -180,7 +202,7 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
         boolean noHost = false;
         for (var searchIndexItems : searchIndexMap.values()) {
             try {
-                URI uri = getSpecURI(searchIndexItems.get(0));
+                URI uri = getSpecURI(searchIndexItems.getFirst());
                 String host = uri.getHost();
                 if (host != null) {
                     hostNamesSet.add(host);
@@ -191,14 +213,19 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
                 // ignore
             }
         }
-        var hostNamesList = new ArrayList<>(hostNamesSet);
 
         var table = new Table(HtmlStyles.summaryTable)
                 .setCaption(contents.externalSpecifications)
                 .setHeader(new TableHeader(contents.specificationLabel, contents.referencedIn))
                 .setColumnStyles(HtmlStyles.colFirst, HtmlStyles.colLast)
-                .setId(HtmlIds.EXTERNAL_SPECS);
+                .setId(HtmlIds.EXTERNAL_SPECS)
+                .setDefaultTab(contents.externalSpecifications)
+                .setRenderTabs(false);
+
+        var hostNamesList = new ArrayList<>(hostNamesSet);
+        Content selector = Text.EMPTY;
         if ((hostNamesList.size() + (noHost ? 1 : 0)) > 1) {
+            selector = createHostSelect(hostNamesList, noHost);
             for (var host : hostNamesList) {
                 table.addTab(Text.of(host), u -> host.equals(u.getHost()));
             }
@@ -207,10 +234,9 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
                         u -> u.getHost() == null);
             }
         }
-        table.setDefaultTab(Text.of(resources.getText("doclet.External_Specifications.All_Specifications")));
 
         for (List searchIndexItems : searchIndexMap.values()) {
-            IndexItem ii = searchIndexItems.get(0);
+            IndexItem ii = searchIndexItems.getFirst();
             Content specName = createSpecLink(ii);
             Content referencesList = HtmlTree.UL(HtmlStyles.refList, searchIndexItems,
                     item -> HtmlTree.LI(createLink(item)));
@@ -227,6 +253,7 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
                 table.addRow(specName, references);
             }
         }
+        content.add(selector);
         content.add(table);
     }
 
@@ -235,6 +262,29 @@ public class ExternalSpecsWriter extends HtmlDocletWriter {
                 .collect(groupingBy(IndexItem::getLabel, () -> new TreeMap<>(getTitleComparator()), toList()));
     }
 
+    private Content createHostSelect(List hosts, boolean hasLocal) {
+        var index = 1;
+        var id = HtmlId.of("specs-by-domain");
+        var specsByHost = resources.getText("doclet.External_Specifications.by-host");
+        var select = HtmlTree.of(HtmlTag.SELECT)
+                .setId(id)
+                .add(HtmlTree.of(HtmlTag.OPTION)
+                        .put(HtmlAttr.VALUE, "")
+                        .add(Text.of(resources.getText("doclet.External_Specifications.all-hosts"))));
+
+        for (var host : hosts) {
+            select.add(HtmlTree.of(HtmlTag.OPTION)
+                    .put(HtmlAttr.VALUE, Integer.toString(index++))
+                    .add(Text.of(host)));
+        }
+        if (hasLocal) {
+            select.add(HtmlTree.of(HtmlTag.OPTION)
+                    .put(HtmlAttr.VALUE, Integer.toString(index))
+                    .add(Text.of("Local")));
+        }
+        return new ContentBuilder(HtmlTree.LABEL(id.name(), Text.of(specsByHost)), Text.of(" "), select);
+    }
+
     Comparator getTitleComparator() {
         Collator collator = Collator.getInstance();
         return (s1, s2) -> {
diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties
index 4366295477b..1aba5c9862b 100644
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/standard.properties
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2010, 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
@@ -180,7 +180,8 @@ doclet.Inheritance_Tree=Inheritance Tree
 doclet.DefinedIn=Defined In
 doclet.ReferencedIn=Referenced In
 doclet.External_Specifications=External Specifications
-doclet.External_Specifications.All_Specifications=All Specifications
+doclet.External_Specifications.by-host=Show specifications by host name:
+doclet.External_Specifications.all-hosts=All host names
 doclet.External_Specifications.no-host=Local
 doclet.Specification=Specification
 doclet.Summary_Page=Summary Page
diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/stylesheet.css b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/stylesheet.css
index 6198df5c2f3..5bd14f7cf33 100644
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/stylesheet.css
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/stylesheet.css
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2026, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
@@ -1228,7 +1228,7 @@ input::placeholder {
 input:focus::placeholder {
     color: transparent;
 }
-select#search-modules {
+select {
     margin: 0 10px 10px 2px;
     font-size: var(--nav-font-size);
     padding: 3px 5px;
diff --git a/test/langtools/jdk/javadoc/doclet/testSpecTag/TestSpecTag.java b/test/langtools/jdk/javadoc/doclet/testSpecTag/TestSpecTag.java
index e914f8022fd..1c3e8306d7b 100644
--- a/test/langtools/jdk/javadoc/doclet/testSpecTag/TestSpecTag.java
+++ b/test/langtools/jdk/javadoc/doclet/testSpecTag/TestSpecTag.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
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 6251738 8226279 8297802 8305407
+ * @bug 6251738 8226279 8297802 8305407 8309748
  * @summary JDK-8226279 javadoc should support a new at-spec tag
  * @library /tools/lib ../../lib
  * @modules jdk.javadoc/jdk.javadoc.internal.tool
@@ -343,16 +343,15 @@ public class TestSpecTag extends JavadocTester {
 
         checkOutput("external-specs.html", true,
                 """
-                    
\ - \ - \ -
+ +
+
+
External Specifications
+
Specification
@@ -369,7 +368,25 @@ public class TestSpecTag extends JavadocTester { -
"""); +
""", + """ + """); } @Test From 5e85d99c360fa12042a42fb3ed8ceb50c733d7a0 Mon Sep 17 00:00:00 2001 From: Chen Liang Date: Thu, 26 Feb 2026 20:17:08 +0000 Subject: [PATCH 28/54] 8378715: Use early field initialization for java.lang.invoke generated code Reviewed-by: jvernee --- .../java/lang/invoke/ClassSpecializer.java | 16 +++++++--------- .../lang/invoke/InnerClassLambdaMetafactory.java | 8 ++++---- .../java/lang/invoke/MethodHandleProxies.java | 12 ++++++------ 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java b/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java index 4b6d74b1b2e..be3805cf5b1 100644 --- a/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java +++ b/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 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 @@ -746,15 +746,7 @@ abstract class ClassSpecializer.SpeciesDat new Consumer<>() { @Override public void accept(CodeBuilder cob) { - cob.aload(0); // this - final List ctorArgs = AFTER_THIS.fromTypes(superCtorType.parameterList()); - for (Var ca : ctorArgs) { - ca.emitLoadInstruction(cob); - } - - // super(ca...) - cob.invokespecial(superClassDesc, INIT_NAME, methodDesc(superCtorType)); // store down fields Var lastFV = AFTER_THIS.lastOf(ctorArgs); @@ -766,6 +758,12 @@ abstract class ClassSpecializer.SpeciesDat cob.putfield(classDesc, f.name, f.desc); } + // super(ca...) + cob.aload(0); // this + for (Var ca : ctorArgs) { + ca.emitLoadInstruction(cob); + } + cob.invokespecial(superClassDesc, INIT_NAME, methodDesc(superCtorType)); cob.return_(); } }); diff --git a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 4dac59771e8..d5cfc6f11a2 100644 --- a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -391,15 +391,15 @@ import sun.invoke.util.Wrapper; new Consumer<>() { @Override public void accept(CodeBuilder cob) { - cob.aload(0) - .invokespecial(CD_Object, INIT_NAME, MTD_void); int parameterCount = factoryType.parameterCount(); for (int i = 0; i < parameterCount; i++) { cob.aload(0) .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i)) .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i]))); } - cob.return_(); + cob.aload(0) + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .return_(); } }); } diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java b/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java index 70592351827..16f5c7e59b8 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -362,10 +362,8 @@ public final class MethodHandleProxies { // (Lookup, MethodHandle target, MethodHandle callerBoundTarget) clb.withMethodBody(INIT_NAME, MTD_void_Lookup_MethodHandle_MethodHandle, 0, cob -> { - cob.aload(0) - .invokespecial(CD_Object, INIT_NAME, MTD_void) - // call ensureOriginalLookup to verify the given Lookup has access - .aload(1) + // call ensureOriginalLookup to verify the given Lookup has access + cob.aload(1) .invokestatic(proxyDesc, ENSURE_ORIGINAL_LOOKUP, MTD_void_Lookup) // this.target = target; .aload(0) @@ -383,7 +381,9 @@ public final class MethodHandleProxies { } // complete - cob.return_(); + cob.aload(0) + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .return_(); }); // private static void ensureOriginalLookup(Lookup) checks if the given Lookup From cd462a88c62fd07fe213f442fc3989c78313a274 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 26 Feb 2026 20:29:51 +0000 Subject: [PATCH 29/54] 8378385: Remove AppContext from AWT Windows implementation classes Reviewed-by: dnguyen, serb --- .../sun/awt/windows/WComponentPeer.java | 4 +-- .../sun/awt/windows/WEmbeddedFrame.java | 5 ++-- .../classes/sun/awt/windows/WInputMethod.java | 7 ++--- .../sun/awt/windows/WMenuItemPeer.java | 4 +-- .../classes/sun/awt/windows/WToolkit.java | 30 ++----------------- .../sun/awt/windows/WTrayIconPeer.java | 4 +-- 6 files changed, 14 insertions(+), 40 deletions(-) diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WComponentPeer.java b/src/java.desktop/windows/classes/sun/awt/windows/WComponentPeer.java index 1b3fb9a85e9..00ad60c8bb3 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WComponentPeer.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WComponentPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -902,7 +902,7 @@ public abstract class WComponentPeer extends WObjectPeer */ void postEvent(AWTEvent event) { preprocessPostEvent(event); - WToolkit.postEvent(WToolkit.targetToAppContext(target), event); + WToolkit.postEvent(event); } void preprocessPostEvent(AWTEvent event) {} diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WEmbeddedFrame.java b/src/java.desktop/windows/classes/sun/awt/windows/WEmbeddedFrame.java index 9a74a1c25f7..0bd44d8ca85 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WEmbeddedFrame.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WEmbeddedFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -238,8 +238,7 @@ public final class WEmbeddedFrame extends EmbeddedFrame { peer.emulateActivation(true); } }; - WToolkit.postEvent(WToolkit.targetToAppContext(this), - new InvocationEvent(this, r)); + WToolkit.postEvent(new InvocationEvent(this, r)); } } diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java b/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java index a9237e21ff6..50ad23fabcd 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -602,7 +602,7 @@ final class WInputMethod extends InputMethodAdapter commitedTextLength, TextHitInfo.leading(caretPos), TextHitInfo.leading(visiblePos)); - WToolkit.postEvent(WToolkit.targetToAppContext(source), event); + WToolkit.postEvent(event); } public void inquireCandidatePosition() @@ -641,8 +641,7 @@ final class WInputMethod extends InputMethodAdapter openCandidateWindow(awtFocussedComponentPeer, x, y); } }; - WToolkit.postEvent(WToolkit.targetToAppContext(source), - new InvocationEvent(source, r)); + WToolkit.postEvent(new InvocationEvent(source, r)); } // java.awt.Toolkit#getNativeContainer() is not available diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WMenuItemPeer.java b/src/java.desktop/windows/classes/sun/awt/windows/WMenuItemPeer.java index 4abb9fa84ae..2594bd38a7d 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WMenuItemPeer.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WMenuItemPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -123,7 +123,7 @@ class WMenuItemPeer extends WObjectPeer implements MenuItemPeer { * Post an event. Queue it for execution by the callback thread. */ void postEvent(AWTEvent event) { - WToolkit.postEvent(WToolkit.targetToAppContext(target), event); + WToolkit.postEvent(event); } native void create(WMenuPeer parent); diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java b/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java index 0fdc4c6005b..4ed3e6b7e68 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -123,7 +123,6 @@ import javax.swing.text.JTextComponent; import sun.awt.AWTAccessor; import sun.awt.AWTAutoShutdown; -import sun.awt.AppContext; import sun.awt.DisplayChangedListener; import sun.awt.LightweightFrame; import sun.awt.SunToolkit; @@ -777,20 +776,7 @@ public final class WToolkit extends SunToolkit implements Runnable { ((DisplayChangedListener) lge).displayChanged(); } }; - if (AppContext.getAppContext() != null) { - // Common case, standalone application - EventQueue.invokeLater(runnable); - } else { - if (displayChangeExecutor == null) { - // No synchronization, called on the Toolkit thread only - displayChangeExecutor = Executors.newFixedThreadPool(1, r -> { - Thread t = Executors.defaultThreadFactory().newThread(r); - t.setDaemon(true); - return t; - }); - } - displayChangeExecutor.submit(runnable); - } + EventQueue.invokeLater(runnable); } /** @@ -910,17 +896,7 @@ public final class WToolkit extends SunToolkit implements Runnable { } updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE)); - - if (AppContext.getAppContext() == null) { - // We cannot post the update to any EventQueue. Listeners will - // be called on EDTs by DesktopPropertyChangeSupport - updateProperties(props); - } else { - // Cannot update on Toolkit thread. - // DesktopPropertyChangeSupport will call listeners on Toolkit - // thread if it has AppContext (standalone mode) - EventQueue.invokeLater(() -> updateProperties(props)); - } + EventQueue.invokeLater(() -> updateProperties(props)); } private synchronized void updateProperties(final Map props) { diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WTrayIconPeer.java b/src/java.desktop/windows/classes/sun/awt/windows/WTrayIconPeer.java index 7cf92292a32..5c04803669d 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WTrayIconPeer.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WTrayIconPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -181,7 +181,7 @@ final class WTrayIconPeer extends WObjectPeer implements TrayIconPeer { } void postEvent(AWTEvent event) { - WToolkit.postEvent(WToolkit.targetToAppContext(target), event); + WToolkit.postEvent(event); } native void create(); From 871730aa9b2c799e8a5ff9e6c1d3b507d16c0c6b Mon Sep 17 00:00:00 2001 From: Kirill Shirokov Date: Thu, 26 Feb 2026 21:43:46 +0000 Subject: [PATCH 30/54] 8377862: Jtreg is unable to detect SkippedException because it is wrapped by CompileFramework Reviewed-by: mhaessig, epeter --- .../compile_framework/CompileFramework.java | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/compiler/lib/compile_framework/CompileFramework.java b/test/hotspot/jtreg/compiler/lib/compile_framework/CompileFramework.java index d9a98582aec..3612f5ab3d3 100644 --- a/test/hotspot/jtreg/compiler/lib/compile_framework/CompileFramework.java +++ b/test/hotspot/jtreg/compiler/lib/compile_framework/CompileFramework.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 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 @@ -28,6 +28,8 @@ import java.lang.reflect.Method; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Optional; +import jtreg.SkippedException; /** * This is the entry-point for the Compile Framework. Its purpose it to allow @@ -132,10 +134,31 @@ public class CompileFramework { } catch (IllegalAccessException e) { throw new CompileFrameworkException("Illegal access:", e); } catch (InvocationTargetException e) { + // Rethrow jtreg.SkippedException so the tests are properly skipped. + // If we wrapped the SkippedException instead, it would get buried + // in the exception causes and cause a failed test instead. + findJtregSkippedExceptionInCauses(e).ifPresent(ex -> { throw ex; }); throw new CompileFrameworkException("Invocation target:", e); } } + private static Optional findJtregSkippedExceptionInCauses(Throwable ex) { + while (ex != null) { + // jtreg.SkippedException can be from a different classloader, comparing by name + if (ex.getClass().getName().equals(SkippedException.class.getName())) { + return Optional.of((RuntimeException) ex); + } + + if (ex.getCause() == ex) { + break; + } + + ex = ex.getCause(); + } + + return Optional.empty(); + } + private Method findMethod(String className, String methodName) { Class c = getClass(className); Method[] methods = c.getDeclaredMethods(); From 526228ca3f785263ed03995df3da09ef737ba4ca Mon Sep 17 00:00:00 2001 From: Kelvin Nilsen Date: Thu, 26 Feb 2026 22:23:21 +0000 Subject: [PATCH 31/54] 8377142: Jtreg test gc/shenandoah/oom/TestThreadFailure.java triggers assert(young_reserve + reserve_for_mixed + reserve_for_promo <= old_available + young_available) failed Reviewed-by: wkemper --- .../shenandoah/shenandoahGenerationalHeap.cpp | 203 +++++++++++------- 1 file changed, 122 insertions(+), 81 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahGenerationalHeap.cpp b/src/hotspot/share/gc/shenandoah/shenandoahGenerationalHeap.cpp index 98d30a3481f..2c2e5533c01 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahGenerationalHeap.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahGenerationalHeap.cpp @@ -605,7 +605,8 @@ void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t mutator_x ShenandoahOldGeneration* old_gen = old_generation(); size_t old_capacity = old_gen->max_capacity(); size_t old_usage = old_gen->used(); // includes humongous waste - size_t old_available = ((old_capacity >= old_usage)? old_capacity - old_usage: 0) + old_trashed_regions * region_size_bytes; + size_t old_currently_available = + ((old_capacity >= old_usage)? old_capacity - old_usage: 0) + old_trashed_regions * region_size_bytes; ShenandoahYoungGeneration* young_gen = young_generation(); size_t young_capacity = young_gen->max_capacity(); @@ -621,7 +622,8 @@ void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t mutator_x size_t young_reserve = (young_generation()->max_capacity() * ShenandoahEvacReserve) / 100; // If ShenandoahOldEvacPercent equals 100, max_old_reserve is limited only by mutator_xfer_limit and young_reserve - const size_t bound_on_old_reserve = ((old_available + mutator_xfer_limit + young_reserve) * ShenandoahOldEvacPercent) / 100; + const size_t bound_on_old_reserve = + ((old_currently_available + mutator_xfer_limit + young_reserve) * ShenandoahOldEvacPercent) / 100; size_t proposed_max_old = ((ShenandoahOldEvacPercent == 100)? bound_on_old_reserve: MIN2((young_reserve * ShenandoahOldEvacPercent) / (100 - ShenandoahOldEvacPercent), @@ -631,68 +633,105 @@ void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t mutator_x } // Decide how much old space we should reserve for a mixed collection - size_t reserve_for_mixed = 0; + size_t proposed_reserve_for_mixed = 0; const size_t old_fragmented_available = - old_available - (old_generation()->free_unaffiliated_regions() + old_trashed_regions) * region_size_bytes; + old_currently_available - (old_generation()->free_unaffiliated_regions() + old_trashed_regions) * region_size_bytes; if (old_fragmented_available > proposed_max_old) { - // After we've promoted regions in place, there may be an abundance of old-fragmented available memory, - // even more than the desired percentage for old reserve. We cannot transfer these fragmented regions back - // to young. Instead we make the best of the situation by using this fragmented memory for both promotions - // and evacuations. + // In this case, the old_fragmented_available is greater than the desired amount of evacuation to old. + // We'll use all of this memory to hold results of old evacuation, and we'll give back to the young generation + // any old regions that are not fragmented. + // + // This scenario may happen after we have promoted many regions in place, and each of these regions had non-zero + // unused memory, so there is now an abundance of old-fragmented available memory, even more than the desired + // percentage for old reserve. We cannot transfer these fragmented regions back to young. Instead we make the + // best of the situation by using this fragmented memory for both promotions and evacuations. + proposed_max_old = old_fragmented_available; } - size_t reserve_for_promo = old_fragmented_available; + // Otherwise: old_fragmented_available <= proposed_max_old. Do not shrink proposed_max_old from the original computation. + + // Though we initially set proposed_reserve_for_promo to equal the entirety of old fragmented available, we have the + // opportunity below to shift some of this memory into the proposed_reserve_for_mixed. + size_t proposed_reserve_for_promo = old_fragmented_available; const size_t max_old_reserve = proposed_max_old; + const size_t mixed_candidate_live_memory = old_generation()->unprocessed_collection_candidates_live_memory(); const bool doing_mixed = (mixed_candidate_live_memory > 0); if (doing_mixed) { - // We want this much memory to be unfragmented in order to reliably evacuate old. This is conservative because we - // may not evacuate the entirety of unprocessed candidates in a single mixed evacuation. + // In the ideal, all of the memory reserved for mixed evacuation would be unfragmented, but we don't enforce + // this. Note that the initial value of max_evac_need is conservative because we may not evacuate all of the + // remaining mixed evacuation candidates in a single cycle. const size_t max_evac_need = (size_t) (mixed_candidate_live_memory * ShenandoahOldEvacWaste); - assert(old_available >= old_generation()->free_unaffiliated_regions() * region_size_bytes, + assert(old_currently_available >= old_generation()->free_unaffiliated_regions() * region_size_bytes, "Unaffiliated available must be less than total available"); // We prefer to evacuate all of mixed into unfragmented memory, and will expand old in order to do so, unless // we already have too much fragmented available memory in old. - reserve_for_mixed = max_evac_need; - if (reserve_for_mixed + reserve_for_promo > max_old_reserve) { - // In this case, we'll allow old-evac to target some of the fragmented old memory. - size_t excess_reserves = (reserve_for_mixed + reserve_for_promo) - max_old_reserve; - if (reserve_for_promo > excess_reserves) { - reserve_for_promo -= excess_reserves; + proposed_reserve_for_mixed = max_evac_need; + if (proposed_reserve_for_mixed + proposed_reserve_for_promo > max_old_reserve) { + // We're trying to reserve more memory than is available. So we need to shrink our reserves. + size_t excess_reserves = (proposed_reserve_for_mixed + proposed_reserve_for_promo) - max_old_reserve; + // We need to shrink reserves by excess_reserves. We prefer to shrink by reducing promotion, giving priority to mixed + // evacuation. If the promotion reserve is larger than the amount we need to shrink by, do all the shrinkage there. + if (proposed_reserve_for_promo > excess_reserves) { + proposed_reserve_for_promo -= excess_reserves; } else { - excess_reserves -= reserve_for_promo; - reserve_for_promo = 0; - reserve_for_mixed -= excess_reserves; + // Otherwise, we'll shrink promotion reserve to zero and we'll shrink the mixed-evac reserve by the remaining excess. + excess_reserves -= proposed_reserve_for_promo; + proposed_reserve_for_promo = 0; + proposed_reserve_for_mixed -= excess_reserves; } } } + assert(proposed_reserve_for_mixed + proposed_reserve_for_promo <= max_old_reserve, + "Reserve for mixed (%zu) plus reserve for promotions (%zu) must be less than maximum old reserve (%zu)", + proposed_reserve_for_mixed, proposed_reserve_for_promo, max_old_reserve); // Decide how much additional space we should reserve for promotions from young. We give priority to mixed evacations // over promotions. const size_t promo_load = old_generation()->get_promotion_potential(); const bool doing_promotions = promo_load > 0; - if (doing_promotions) { - // We've already set aside all of the fragmented available memory within old-gen to represent old objects - // to be promoted from young generation. promo_load represents the memory that we anticipate to be promoted - // from regions that have reached tenure age. In the ideal, we will always use fragmented old-gen memory - // to hold individually promoted objects and will use unfragmented old-gen memory to represent the old-gen - // evacuation workloa. - // We're promoting and have an estimate of memory to be promoted from aged regions - assert(max_old_reserve >= (reserve_for_mixed + reserve_for_promo), "Sanity"); - const size_t available_for_additional_promotions = max_old_reserve - (reserve_for_mixed + reserve_for_promo); - size_t promo_need = (size_t)(promo_load * ShenandoahPromoEvacWaste); - if (promo_need > reserve_for_promo) { - reserve_for_promo += MIN2(promo_need - reserve_for_promo, available_for_additional_promotions); + // promo_load represents the combined total of live memory within regions that have reached tenure age. The true + // promotion potential is larger than this, because individual objects within regions that have not yet reached tenure + // age may be promotable. On the other hand, some of the objects that we intend to promote in the next GC cycle may + // die before they are next marked. In the future, the promo_load will include the total size of tenurable objects + // residing in regions that have not yet reached tenure age. + + if (doing_promotions) { + // We are always doing promotions, even when old_generation->get_promotion_potential() returns 0. As currently implemented, + // get_promotion_potential() only knows the total live memory contained within young-generation regions whose age is + // tenurable. It does not know whether that memory will still be live at the end of the next mark cycle, and it doesn't + // know how much memory is contained within objects whose individual ages are tenurable, which reside in regions with + // non-tenurable age. We use this, as adjusted by ShenandoahPromoEvacWaste, as an approximation of the total amount of + // memory to be promoted. In the near future, we expect to implement a change that will allow get_promotion_potential() + // to account also for the total memory contained within individual objects that are tenure-ready even when they do + // not reside in aged regions. This will represent a conservative over approximation of promotable memory because + // some of these objects may die before the next GC cycle executes. + + // Be careful not to ask for too much promotion reserves. We have observed jtreg test failures under which a greedy + // promotion reserve causes a humongous allocation which is awaiting a full GC to fail (specifically + // gc/TestAllocHumongousFragment.java). This happens if too much of the memory reclaimed by the full GC + // is immediately reserved so that it cannot be allocated by the waiting mutator. It's not clear that this + // particular test is representative of the needs of typical GenShen users. It is really a test of high frequency + // Full GCs under heap fragmentation stress. + + size_t promo_need = (size_t) (promo_load * ShenandoahPromoEvacWaste); + if (promo_need > proposed_reserve_for_promo) { + const size_t available_for_additional_promotions = + max_old_reserve - (proposed_reserve_for_mixed + proposed_reserve_for_promo); + if (proposed_reserve_for_promo + available_for_additional_promotions >= promo_need) { + proposed_reserve_for_promo = promo_need; + } else { + proposed_reserve_for_promo += available_for_additional_promotions; + } } - // We've already reserved all the memory required for the promo_load, and possibly more. The excess - // can be consumed by objects promoted from regions that have not yet reached tenure age. } + // else, leave proposed_reserve_for_promo as is. By default, it is initialized to represent old_fragmented_available. // This is the total old we want to reserve (initialized to the ideal reserve) - size_t old_reserve = reserve_for_mixed + reserve_for_promo; + size_t proposed_old_reserve = proposed_reserve_for_mixed + proposed_reserve_for_promo; // We now check if the old generation is running a surplus or a deficit. size_t old_region_deficit = 0; @@ -702,68 +741,70 @@ void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t mutator_x // align the mutator_xfer_limit on region size mutator_xfer_limit = mutator_region_xfer_limit * region_size_bytes; - if (old_available >= old_reserve) { + if (old_currently_available >= proposed_old_reserve) { // We are running a surplus, so the old region surplus can go to young - const size_t old_surplus = old_available - old_reserve; + const size_t old_surplus = old_currently_available - proposed_old_reserve; old_region_surplus = old_surplus / region_size_bytes; const size_t unaffiliated_old_regions = old_generation()->free_unaffiliated_regions() + old_trashed_regions; old_region_surplus = MIN2(old_region_surplus, unaffiliated_old_regions); old_generation()->set_region_balance(checked_cast(old_region_surplus)); - } else if (old_available + mutator_xfer_limit >= old_reserve) { - // Mutator's xfer limit is sufficient to satisfy our need: transfer all memory from there - size_t old_deficit = old_reserve - old_available; + old_currently_available -= old_region_surplus * region_size_bytes; + young_available += old_region_surplus * region_size_bytes; + } else if (old_currently_available + mutator_xfer_limit >= proposed_old_reserve) { + // We know that old_currently_available < proposed_old_reserve because above test failed. Expand old_currently_available. + // Mutator's xfer limit is sufficient to satisfy our need: transfer all memory from there. + size_t old_deficit = proposed_old_reserve - old_currently_available; old_region_deficit = (old_deficit + region_size_bytes - 1) / region_size_bytes; old_generation()->set_region_balance(0 - checked_cast(old_region_deficit)); + old_currently_available += old_region_deficit * region_size_bytes; + young_available -= old_region_deficit * region_size_bytes; } else { - // We'll try to xfer from both mutator excess and from young collector reserve - size_t available_reserves = old_available + young_reserve + mutator_xfer_limit; - size_t old_entitlement = (available_reserves * ShenandoahOldEvacPercent) / 100; + // We know that (old_currently_available < proposed_old_reserve) and + // (old_currently_available + mutator_xfer_limit < proposed_old_reserve) because above tests failed. + // We need to shrink proposed_old_reserves. - // Round old_entitlement down to nearest multiple of regions to be transferred to old - size_t entitled_xfer = old_entitlement - old_available; - entitled_xfer = region_size_bytes * (entitled_xfer / region_size_bytes); - size_t unaffiliated_young_regions = young_generation()->free_unaffiliated_regions(); - size_t unaffiliated_young_memory = unaffiliated_young_regions * region_size_bytes; - if (entitled_xfer > unaffiliated_young_memory) { - entitled_xfer = unaffiliated_young_memory; - } - old_entitlement = old_available + entitled_xfer; - if (old_entitlement < old_reserve) { - // There's not enough memory to satisfy our desire. Scale back our old-gen intentions. - size_t budget_overrun = old_reserve - old_entitlement;; - if (reserve_for_promo > budget_overrun) { - reserve_for_promo -= budget_overrun; - old_reserve -= budget_overrun; - } else { - budget_overrun -= reserve_for_promo; - reserve_for_promo = 0; - reserve_for_mixed = (reserve_for_mixed > budget_overrun)? reserve_for_mixed - budget_overrun: 0; - old_reserve = reserve_for_promo + reserve_for_mixed; - } - } + // We could potentially shrink young_reserves in order to further expand proposed_old_reserves. Let's not bother. The + // important thing is that we keep a total amount of memory in reserve in preparation for the next GC cycle. At + // the time we choose the next collection set, we'll have an opportunity to shift some of these young reserves + // into old reserves if that makes sense. - // Because of adjustments above, old_reserve may be smaller now than it was when we tested the branch - // condition above: "(old_available + mutator_xfer_limit >= old_reserve) - // Therefore, we do NOT know that: mutator_xfer_limit < old_reserve - old_available - - size_t old_deficit = old_reserve - old_available; - old_region_deficit = (old_deficit + region_size_bytes - 1) / region_size_bytes; - - // Shrink young_reserve to account for loan to old reserve - const size_t reserve_xfer_regions = old_region_deficit - mutator_region_xfer_limit; - young_reserve -= reserve_xfer_regions * region_size_bytes; + // Start by taking all of mutator_xfer_limit into old_currently_available. + size_t old_region_deficit = mutator_region_xfer_limit; old_generation()->set_region_balance(0 - checked_cast(old_region_deficit)); + old_currently_available += old_region_deficit * region_size_bytes; + young_available -= old_region_deficit * region_size_bytes; + + assert(old_currently_available < proposed_old_reserve, + "Old currently available (%zu) must be less than old reserve (%zu)", old_currently_available, proposed_old_reserve); + + // There's not enough memory to satisfy our desire. Scale back our old-gen intentions. We prefer to satisfy + // the budget_overrun entirely from the promotion reserve, if that is large enough. Otherwise, we'll satisfy + // the overrun from a combination of promotion and mixed-evacuation reserves. + size_t budget_overrun = proposed_old_reserve - old_currently_available; + if (proposed_reserve_for_promo > budget_overrun) { + proposed_reserve_for_promo -= budget_overrun; + // Dead code: + // proposed_old_reserve -= budget_overrun; + } else { + budget_overrun -= proposed_reserve_for_promo; + proposed_reserve_for_promo = 0; + proposed_reserve_for_mixed = (proposed_reserve_for_mixed > budget_overrun)? proposed_reserve_for_mixed - budget_overrun: 0; + // Dead code: + // Note: proposed_reserve_for_promo is 0 and proposed_reserve_for_mixed may equal 0. + // proposed_old_reserve = proposed_reserve_for_mixed; + } } - assert(old_region_deficit == 0 || old_region_surplus == 0, "Only surplus or deficit, never both"); - assert(young_reserve + reserve_for_mixed + reserve_for_promo <= old_available + young_available, + assert(old_region_deficit == 0 || old_region_surplus == 0, + "Only surplus (%zu) or deficit (%zu), never both", old_region_surplus, old_region_deficit); + assert(young_reserve + proposed_reserve_for_mixed + proposed_reserve_for_promo <= old_currently_available + young_available, "Cannot reserve more memory than is available: %zu + %zu + %zu <= %zu + %zu", - young_reserve, reserve_for_mixed, reserve_for_promo, old_available, young_available); + young_reserve, proposed_reserve_for_mixed, proposed_reserve_for_promo, old_currently_available, young_available); // deficit/surplus adjustments to generation sizes will precede rebuild young_generation()->set_evacuation_reserve(young_reserve); - old_generation()->set_evacuation_reserve(reserve_for_mixed); - old_generation()->set_promoted_reserve(reserve_for_promo); + old_generation()->set_evacuation_reserve(proposed_reserve_for_mixed); + old_generation()->set_promoted_reserve(proposed_reserve_for_promo); } void ShenandoahGenerationalHeap::coalesce_and_fill_old_regions(bool concurrent) { From 4a6de12b3a356b4aec9049ec3ee1ee26cd4517bf Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Thu, 26 Feb 2026 23:59:09 +0000 Subject: [PATCH 32/54] 8371438: jpackage should handle the case when "--mac-sign" is specified without signing identity options Reviewed-by: almatvee --- .../jdk/jpackage/internal/MacFromOptions.java | 98 ++++-- .../jdk/jpackage/internal/OptionUtils.java | 7 +- .../jpackage/internal/cli/StandardOption.java | 2 +- test/jdk/tools/jpackage/TEST.properties | 4 +- .../jdk/jpackage/test/MacHelperTest.java | 144 ++++++++- .../jdk/jpackage/test/JPackageCommand.java | 11 +- .../helpers/jdk/jpackage/test/MacHelper.java | 182 +++++++++-- .../helpers/jdk/jpackage/test/MacSign.java | 128 ++++++-- .../jdk/jpackage/test/mock/CommandAction.java | 30 ++ .../test/mock/MockIllegalStateException.java | 4 +- .../test/stdmock/MacSecurityMock.java | 176 +++++++++++ .../test/stdmock/MacSignMockUtils.java | 284 +++++++++++++++++ .../cli/OptionsValidationFailTest.excludes | 10 + .../jpackage/macosx/SigningAppImageTest.java | 15 +- .../macosx/SigningAppImageTwoStepsTest.java | 33 +- .../tools/jpackage/macosx/SigningBase.java | 20 +- .../jpackage/macosx/SigningPackageTest.java | 89 +++++- .../macosx/SigningPackageTwoStepTest.java | 2 +- .../SigningRuntimeImagePackageTest.java | 2 +- test/jdk/tools/jpackage/share/ErrorTest.java | 293 +++++++++++++++++- 20 files changed, 1397 insertions(+), 137 deletions(-) create mode 100644 test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSecurityMock.java create mode 100644 test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSignMockUtils.java diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacFromOptions.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacFromOptions.java index 0598e6bc2a9..4cd4f386ad8 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacFromOptions.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacFromOptions.java @@ -29,6 +29,8 @@ import static jdk.jpackage.internal.FromOptions.createPackageBuilder; import static jdk.jpackage.internal.MacPackagingPipeline.APPLICATION_LAYOUT; import static jdk.jpackage.internal.MacRuntimeValidator.validateRuntimeHasJliLib; import static jdk.jpackage.internal.MacRuntimeValidator.validateRuntimeHasNoBinDir; +import static jdk.jpackage.internal.OptionUtils.isBundlingOperation; +import static jdk.jpackage.internal.cli.StandardBundlingOperation.CREATE_MAC_PKG; import static jdk.jpackage.internal.cli.StandardBundlingOperation.SIGN_MAC_APP_IMAGE; import static jdk.jpackage.internal.cli.StandardOption.APPCLASS; import static jdk.jpackage.internal.cli.StandardOption.ICON; @@ -120,23 +122,39 @@ final class MacFromOptions { final Optional pkgSigningIdentityBuilder; - if (sign && (MAC_INSTALLER_SIGN_IDENTITY.containsIn(options) || MAC_SIGNING_KEY_NAME.containsIn(options))) { + if (!sign) { + pkgSigningIdentityBuilder = Optional.empty(); + } else if (hasAppImageSignIdentity(options) && !hasPkgInstallerSignIdentity(options)) { + // They explicitly request to sign the app image, + // but don't specify signing identity for signing the PKG package. + // They want signed app image inside of unsigned PKG. + pkgSigningIdentityBuilder = Optional.empty(); + } else { final var signingIdentityBuilder = createSigningIdentityBuilder(options); - MAC_INSTALLER_SIGN_IDENTITY.ifPresentIn(options, signingIdentityBuilder::signingIdentity); - MAC_SIGNING_KEY_NAME.findIn(options).ifPresent(userName -> { - final StandardCertificateSelector domain; - if (appStore) { - domain = StandardCertificateSelector.APP_STORE_PKG_INSTALLER; - } else { - domain = StandardCertificateSelector.PKG_INSTALLER; - } - signingIdentityBuilder.certificateSelector(StandardCertificateSelector.create(userName, domain)); - }); + MAC_INSTALLER_SIGN_IDENTITY.findIn(options).ifPresentOrElse( + signingIdentityBuilder::signingIdentity, + () -> { + MAC_SIGNING_KEY_NAME.findIn(options).or(() -> { + if (MAC_APP_IMAGE_SIGN_IDENTITY.findIn(options).isPresent()) { + return Optional.empty(); + } else { + return Optional.of(""); + } + }).ifPresent(userName -> { + final StandardCertificateSelector domain; + if (appStore) { + domain = StandardCertificateSelector.APP_STORE_PKG_INSTALLER; + } else { + domain = StandardCertificateSelector.PKG_INSTALLER; + } + + signingIdentityBuilder.certificateSelector(StandardCertificateSelector.create(userName, domain)); + }); + } + ); pkgSigningIdentityBuilder = Optional.of(signingIdentityBuilder); - } else { - pkgSigningIdentityBuilder = Optional.empty(); } ApplicationWithDetails app = null; @@ -230,33 +248,47 @@ final class MacFromOptions { MAC_BUNDLE_IDENTIFIER.ifPresentIn(options, appBuilder::bundleIdentifier); MAC_APP_CATEGORY.ifPresentIn(options, appBuilder::category); - final boolean sign; + final boolean sign = MAC_SIGN.getFrom(options); final boolean appStore; - if (PREDEFINED_APP_IMAGE.containsIn(options) && OptionUtils.bundlingOperation(options) != SIGN_MAC_APP_IMAGE) { + if (PREDEFINED_APP_IMAGE.containsIn(options)) { final var appImageFileOptions = superAppBuilder.externalApplication().orElseThrow().extra(); - sign = MAC_SIGN.getFrom(appImageFileOptions); appStore = MAC_APP_STORE.getFrom(appImageFileOptions); } else { - sign = MAC_SIGN.getFrom(options); appStore = MAC_APP_STORE.getFrom(options); } appBuilder.appStore(appStore); - if (sign && (MAC_APP_IMAGE_SIGN_IDENTITY.containsIn(options) || MAC_SIGNING_KEY_NAME.containsIn(options))) { - final var signingIdentityBuilder = createSigningIdentityBuilder(options); - MAC_APP_IMAGE_SIGN_IDENTITY.ifPresentIn(options, signingIdentityBuilder::signingIdentity); - MAC_SIGNING_KEY_NAME.findIn(options).ifPresent(userName -> { - final StandardCertificateSelector domain; - if (appStore) { - domain = StandardCertificateSelector.APP_STORE_APP_IMAGE; - } else { - domain = StandardCertificateSelector.APP_IMAGE; - } + final var signOnlyPkgInstaller = sign && ( + isBundlingOperation(options, CREATE_MAC_PKG) + && !hasAppImageSignIdentity(options) + && hasPkgInstallerSignIdentity(options)); - signingIdentityBuilder.certificateSelector(StandardCertificateSelector.create(userName, domain)); - }); + if (sign && !signOnlyPkgInstaller) { + final var signingIdentityBuilder = createSigningIdentityBuilder(options); + + MAC_APP_IMAGE_SIGN_IDENTITY.findIn(options).ifPresentOrElse( + signingIdentityBuilder::signingIdentity, + () -> { + MAC_SIGNING_KEY_NAME.findIn(options).or(() -> { + if (MAC_INSTALLER_SIGN_IDENTITY.containsIn(options)) { + return Optional.empty(); + } else { + return Optional.of(""); + } + }).ifPresent(userName -> { + final StandardCertificateSelector domain; + if (appStore) { + domain = StandardCertificateSelector.APP_STORE_APP_IMAGE; + } else { + domain = StandardCertificateSelector.APP_IMAGE; + } + + signingIdentityBuilder.certificateSelector(StandardCertificateSelector.create(userName, domain)); + }); + } + ); final var signingBuilder = new AppImageSigningConfigBuilder(signingIdentityBuilder); if (appStore) { @@ -331,4 +363,12 @@ final class MacFromOptions { return builder.create(fa); } + + private static boolean hasAppImageSignIdentity(Options options) { + return options.contains(MAC_SIGNING_KEY_NAME) || options.contains(MAC_APP_IMAGE_SIGN_IDENTITY); + } + + private static boolean hasPkgInstallerSignIdentity(Options options) { + return options.contains(MAC_SIGNING_KEY_NAME) || options.contains(MAC_INSTALLER_SIGN_IDENTITY); + } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/OptionUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/OptionUtils.java index 97e1274f078..b39e67a9eb7 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/OptionUtils.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/OptionUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -32,6 +32,7 @@ import static jdk.jpackage.internal.cli.StandardOption.PREDEFINED_APP_IMAGE; import static jdk.jpackage.internal.cli.StandardOption.PREDEFINED_RUNTIME_IMAGE; import java.nio.file.Path; +import java.util.Objects; import jdk.jpackage.internal.cli.Options; import jdk.jpackage.internal.cli.StandardBundlingOperation; @@ -51,4 +52,8 @@ final class OptionUtils { static StandardBundlingOperation bundlingOperation(Options options) { return StandardBundlingOperation.valueOf(BUNDLING_OPERATION_DESCRIPTOR.getFrom(options)).orElseThrow(); } + + static boolean isBundlingOperation(Options options, StandardBundlingOperation op) { + return bundlingOperation(options).equals(Objects.requireNonNull(op)); + } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java index 4450a6168e2..eca82da99aa 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/cli/StandardOption.java @@ -109,7 +109,7 @@ public final class StandardOption { public static final OptionValue VERBOSE = auxilaryOption("verbose").create(); - public static final OptionValue TYPE = option("type", BundleType.class).addAliases("t") + static final OptionValue TYPE = option("type", BundleType.class).addAliases("t") .scope(StandardBundlingOperation.values()).inScope(NOT_BUILDING_APP_IMAGE) .converterExceptionFactory(ERROR_WITH_VALUE).converterExceptionFormatString("ERR_InvalidInstallerType") .converter(str -> { diff --git a/test/jdk/tools/jpackage/TEST.properties b/test/jdk/tools/jpackage/TEST.properties index 19eda305364..5cc4aa7a1b9 100644 --- a/test/jdk/tools/jpackage/TEST.properties +++ b/test/jdk/tools/jpackage/TEST.properties @@ -13,7 +13,7 @@ maxOutputSize = 2000000 # Run jpackage tests on windows platform sequentially. # Having "share" directory in the list affects tests on other platforms. # The better option would be: -# if (platfrom == windowws) { +# if (platfrom == windows) { # exclusiveAccess.dirs=share windows # } # but conditionals are not supported by jtreg configuration files. @@ -29,4 +29,6 @@ modules = \ jdk.jpackage/jdk.jpackage.internal.util.function \ jdk.jpackage/jdk.jpackage.internal.resources:+open \ java.base/jdk.internal.util \ + java.base/sun.security.util \ + java.base/sun.security.x509 \ jdk.jlink/jdk.tools.jlink.internal diff --git a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/MacHelperTest.java b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/MacHelperTest.java index 5d14f021eaf..b8f7bfd456e 100644 --- a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/MacHelperTest.java +++ b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/MacHelperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -31,14 +31,20 @@ import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Stream; import jdk.jpackage.internal.util.PListReader; import jdk.jpackage.internal.util.XmlUtils; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -public class MacHelperTest { +public class MacHelperTest extends JUnitAdapter { @Test public void test_flatMapPList() { @@ -105,6 +111,18 @@ public class MacHelperTest { ), props); } + @ParameterizedTest + @MethodSource + public void test_appImageSigned(SignedTestSpec spec) { + spec.test(MacHelper::appImageSigned); + } + + @ParameterizedTest + @MethodSource + public void test_nativePackageSigned(SignedTestSpec spec) { + spec.test(MacHelper::nativePackageSigned); + } + private static String createPListXml(String ...xml) { final List content = new ArrayList<>(); content.add(""); @@ -125,4 +143,126 @@ public class MacHelperTest { throw new RuntimeException(ex); } } + + private static Stream test_appImageSigned() { + + List data = new ArrayList<>(); + + for (var signingIdentityOption : List.of( + List.of(), + List.of("--mac-signing-key-user-name", "foo"), + List.of("--mac-app-image-sign-identity", "foo"), + List.of("--mac-installer-sign-identity", "foo"), + List.of("--mac-installer-sign-identity", "foo", "--mac-app-image-sign-identity", "bar") + )) { + for (var type : List.of(PackageType.IMAGE, PackageType.MAC_DMG, PackageType.MAC_PKG)) { + for (var withMacSign : List.of(true, false)) { + if (signingIdentityOption.contains("--mac-installer-sign-identity") && type != PackageType.MAC_PKG) { + continue; + } + + var builder = SignedTestSpec.build().type(type).cmdline(signingIdentityOption); + if (withMacSign) { + builder.cmdline("--mac-sign"); + if (Stream.of( + "--mac-signing-key-user-name", + "--mac-app-image-sign-identity" + ).anyMatch(signingIdentityOption::contains) || signingIdentityOption.isEmpty()) { + builder.signed(); + } + } + + data.add(builder); + } + } + } + + return data.stream().map(SignedTestSpec.Builder::create); + } + + private static Stream test_nativePackageSigned() { + + List data = new ArrayList<>(); + + for (var signingIdentityOption : List.of( + List.of(), + List.of("--mac-signing-key-user-name", "foo"), + List.of("--mac-app-image-sign-identity", "foo"), + List.of("--mac-installer-sign-identity", "foo"), + List.of("--mac-installer-sign-identity", "foo", "--mac-app-image-sign-identity", "bar") + )) { + for (var type : List.of(PackageType.MAC_DMG, PackageType.MAC_PKG)) { + for (var withMacSign : List.of(true, false)) { + if (signingIdentityOption.contains("--mac-installer-sign-identity") && type != PackageType.MAC_PKG) { + continue; + } + + var builder = SignedTestSpec.build().type(type).cmdline(signingIdentityOption); + if (withMacSign) { + builder.cmdline("--mac-sign"); + if (type == PackageType.MAC_PKG && (Stream.of( + "--mac-signing-key-user-name", + "--mac-installer-sign-identity" + ).anyMatch(signingIdentityOption::contains) || signingIdentityOption.isEmpty())) { + builder.signed(); + } + } + + data.add(builder); + } + } + } + + return data.stream().map(SignedTestSpec.Builder::create); + } + + private record SignedTestSpec(boolean expectedSigned, PackageType type, List cmdline) { + + SignedTestSpec { + Objects.requireNonNull(type); + cmdline.forEach(Objects::requireNonNull); + } + + void test(Function func) { + var actualSigned = func.apply((new JPackageCommand().addArguments(cmdline).setPackageType(type))); + assertEquals(expectedSigned, actualSigned); + } + + static Builder build() { + return new Builder(); + } + + static final class Builder { + + SignedTestSpec create() { + return new SignedTestSpec( + expectedSigned, + Optional.ofNullable(type).orElse(PackageType.IMAGE), + cmdline); + } + + Builder signed() { + expectedSigned = true; + return this; + } + + Builder type(PackageType v) { + type = v; + return this; + } + + Builder cmdline(String... args) { + return cmdline(List.of(args)); + } + + Builder cmdline(List v) { + cmdline.addAll(v); + return this; + } + + private boolean expectedSigned; + private PackageType type; + private List cmdline = new ArrayList<>(); + } + } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java index da6af4bed33..251d95a1089 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java @@ -1292,7 +1292,7 @@ public class JPackageCommand extends CommandArguments { } }), MAC_BUNDLE_UNSIGNED_SIGNATURE(cmd -> { - if (TKit.isOSX() && !MacHelper.appImageSigned(cmd)) { + if (TKit.isOSX()) { MacHelper.verifyUnsignedBundleSignature(cmd); } }), @@ -1316,7 +1316,14 @@ public class JPackageCommand extends CommandArguments { }), PREDEFINED_APP_IMAGE_COPY(cmd -> { Optional.ofNullable(cmd.getArgumentValue("--app-image")).filter(_ -> { - return !TKit.isOSX() || !MacHelper.signPredefinedAppImage(cmd); + if (!TKit.isOSX() || !cmd.hasArgument("--mac-sign")) { + return true; + } else { + var signAppImage = MacHelper.signPredefinedAppImage(cmd) + || MacHelper.hasAppImageSignIdentity(cmd) + || MacHelper.isSignWithoutSignIdentity(cmd); + return !signAppImage; + } }).filter(_ -> { // Don't examine the contents of the output app image if this is Linux package installing in the "/usr" subtree. return Optional.ofNullable(cmd.onLinuxPackageInstallDir(null, _ -> false)).orElse(true); diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java index 1191cd02221..1372058d440 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java @@ -76,6 +76,7 @@ import jdk.jpackage.internal.util.RetryExecutor; import jdk.jpackage.internal.util.XmlUtils; import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.internal.util.function.ThrowingSupplier; +import jdk.jpackage.test.MacSign.CertificateHash; import jdk.jpackage.test.MacSign.CertificateRequest; import jdk.jpackage.test.MacSign.CertificateType; import jdk.jpackage.test.MacSign.ResolvedKeychain; @@ -259,10 +260,7 @@ public final class MacHelper { * predefined app image in place and {@code false} otherwise. */ public static boolean signPredefinedAppImage(JPackageCommand cmd) { - Objects.requireNonNull(cmd); - if (!TKit.isOSX()) { - throw new UnsupportedOperationException(); - } + cmd.verifyIsOfType(PackageType.MAC_DMG, PackageType.MAC_PKG, PackageType.IMAGE); return cmd.hasArgument("--mac-sign") && cmd.hasArgument("--app-image") && cmd.isImagePackageType(); } @@ -279,10 +277,7 @@ public final class MacHelper { * otherwise. */ public static boolean appImageSigned(JPackageCommand cmd) { - Objects.requireNonNull(cmd); - if (!TKit.isOSX()) { - throw new UnsupportedOperationException(); - } + cmd.verifyIsOfType(PackageType.MAC_DMG, PackageType.MAC_PKG, PackageType.IMAGE); var runtimeImageBundle = Optional.ofNullable(cmd.getArgumentValue("--runtime-image")).map(Path::of).flatMap(MacBundle::fromPath); var appImage = Optional.ofNullable(cmd.getArgumentValue("--app-image")).map(Path::of); @@ -291,23 +286,102 @@ public final class MacHelper { // If the predefined runtime is a signed bundle, bundled image should be signed too. return true; } else if (appImage.map(MacHelper::isBundleSigned).orElse(false)) { - // The external app image is signed, so the app image is signed too. + // The predefined app image is signed, so the app image is signed too. return true; } - if (!cmd.isImagePackageType() && appImage.isPresent()) { - // Building a ".pkg" or a ".dmg" bundle from the predefined app image. - // The predefined app image is unsigned, so the app image bundled - // in the output native package will be unsigned too - // (even if the ".pkg" file may be signed itself, and we never sign ".dmg" files). - return false; - } - if (!cmd.hasArgument("--mac-sign")) { return false; + } else { + return isSignWithoutSignIdentity(cmd) || hasAppImageSignIdentity(cmd); } + } - return (cmd.hasArgument("--mac-signing-key-user-name") || cmd.hasArgument("--mac-app-image-sign-identity")); + /** + * Returns {@code true} if the given jpackage command line is configured such + * that the native package it will produce will be signed. + * + * @param cmd the jpackage command to examine + * @return {@code true} if the given jpackage command line is configured such + * the native package it will produce will be signed and {@code false} + * otherwise. + */ + public static boolean nativePackageSigned(JPackageCommand cmd) { + cmd.verifyIsOfType(PackageType.MAC); + + switch (cmd.packageType()) { + case MAC_DMG -> { + return false; + } + case MAC_PKG -> { + if (!cmd.hasArgument("--mac-sign")) { + return false; + } else { + return isSignWithoutSignIdentity(cmd) || hasPkgInstallerSignIdentity(cmd); + } + } + default -> { + throw new IllegalStateException(); + } + } + } + + /** + * Returns {@code true} if the given jpackage command line has app image signing + * identity option. The command line must have "--mac-sign" option. + * + * @param cmd the jpackage command to examine + * @return {@code true} if the given jpackage command line has app image signing + * identity option and {@code false} otherwise. + */ + public static boolean hasAppImageSignIdentity(JPackageCommand cmd) { + cmd.verifyIsOfType(PackageType.MAC_DMG, PackageType.MAC_PKG, PackageType.IMAGE); + if (!cmd.hasArgument("--mac-sign")) { + throw new IllegalArgumentException(); + } + return Stream.of( + "--mac-signing-key-user-name", + "--mac-app-image-sign-identity" + ).anyMatch(cmd::hasArgument); + } + + /** + * Returns {@code true} if the given jpackage command line has PKG installer signing + * identity option. The command line must have "--mac-sign" option. + * + * @param cmd the jpackage command to examine + * @return {@code true} if the given jpackage command line has PKG installer signing + * identity option and {@code false} otherwise. + */ + public static boolean hasPkgInstallerSignIdentity(JPackageCommand cmd) { + cmd.verifyIsOfType(PackageType.MAC_PKG); + if (!cmd.hasArgument("--mac-sign")) { + throw new IllegalArgumentException(); + } + return Stream.of( + "--mac-signing-key-user-name", + "--mac-installer-sign-identity" + ).anyMatch(cmd::hasArgument); + } + + /** + * Returns {@code true} if the given jpackage command line doesn't have signing + * identity options. The command line must have "--mac-sign" option. + * + * @param cmd the jpackage command to examine + * @return {@code true} if the given jpackage command line doesn't have signing + * identity options and {@code false} otherwise. + */ + public static boolean isSignWithoutSignIdentity(JPackageCommand cmd) { + cmd.verifyIsOfType(PackageType.MAC_DMG, PackageType.MAC_PKG, PackageType.IMAGE); + if (!cmd.hasArgument("--mac-sign")) { + throw new IllegalArgumentException(); + } + return Stream.of( + "--mac-signing-key-user-name", + "--mac-app-image-sign-identity", + "--mac-installer-sign-identity" + ).noneMatch(cmd::hasArgument); } public static void writeFaPListFragment(JPackageCommand cmd, XMLStreamWriter xml) { @@ -702,6 +776,14 @@ public final class MacHelper { MacSign.CertificateType.CODE_SIGN, Name.KEY_IDENTITY_APP_IMAGE, MacSign.CertificateType.INSTALLER, Name.KEY_IDENTITY_INSTALLER)), + /** + * "--mac-installer-sign-identity" or "--mac-app-image-sign-identity" option + * with the SHA1 of a signing certificate + */ + SIGN_KEY_IDENTITY_SHA1(Map.of( + MacSign.CertificateType.CODE_SIGN, Name.KEY_IDENTITY_APP_IMAGE, + MacSign.CertificateType.INSTALLER, Name.KEY_IDENTITY_INSTALLER)), + /** * "--mac-app-image-sign-identity" regardless of the type of signing identity * (for signing app image or .pkg installer). @@ -714,6 +796,12 @@ public final class MacHelper { */ SIGN_KEY_IDENTITY_INSTALLER(Name.KEY_IDENTITY_INSTALLER), + /** + * No explicit option specifying signing identity. jpackage will pick one from + * the specified keychain. + */ + SIGN_KEY_IMPLICIT, + ; Type(Map optionNameMap) { @@ -736,11 +824,24 @@ public final class MacHelper { return optionNameMapper.apply(Objects.requireNonNull(certType)); } + public boolean passThrough() { + return Stream.of(MacSign.CertificateType.values()) + .map(this::mapOptionName) + .flatMap(Optional::stream) + .map(Name::passThrough) + .distinct() + .reduce((_, _) -> { + throw new IllegalStateException(); + }).orElse(false); + } + public static Type[] defaultValues() { return new Type[] { SIGN_KEY_USER_SHORT_NAME, SIGN_KEY_USER_FULL_NAME, - SIGN_KEY_IDENTITY + SIGN_KEY_IDENTITY, + SIGN_KEY_IDENTITY_SHA1, + SIGN_KEY_IMPLICIT }; } @@ -751,7 +852,7 @@ public final class MacHelper { public String toString() { var sb = new StringBuilder(); sb.append('{'); - applyTo((optionName, _) -> { + type.mapOptionName(certRequest.type()).ifPresent(optionName -> { sb.append(optionName); switch (type) { case SIGN_KEY_USER_FULL_NAME -> { @@ -762,6 +863,9 @@ public final class MacHelper { sb.append("=").append(ENQUOTER.applyTo(optionValue)); }); } + case SIGN_KEY_IDENTITY_SHA1 -> { + sb.append("/sha1"); + } default -> { // NOP } @@ -787,12 +891,16 @@ public final class MacHelper { } public List asCmdlineArgs() { - String[] args = new String[2]; - applyTo((optionName, optionValue) -> { - args[0] = optionName; - args[1] = optionValue; - }); - return List.of(args); + if (type == Type.SIGN_KEY_IMPLICIT) { + return List.of(); + } else { + String[] args = new String[2]; + applyTo((optionName, optionValue) -> { + args[0] = optionName; + args[1] = optionValue; + }); + return List.of(args); + } } public Optional passThrough() { @@ -817,6 +925,9 @@ public final class MacHelper { case SIGN_KEY_USER_SHORT_NAME -> { return certRequest.shortName(); } + case SIGN_KEY_IDENTITY_SHA1 -> { + return CertificateHash.of(certRequest.cert()).toString(); + } default -> { throw new IllegalStateException(); } @@ -960,18 +1071,21 @@ public final class MacHelper { } static void verifyUnsignedBundleSignature(JPackageCommand cmd) { - if (!cmd.isImagePackageType()) { + + if (!cmd.isImagePackageType() && !nativePackageSigned(cmd)) { MacSignVerify.assertUnsigned(cmd.outputBundle()); } - final Path bundleRoot; - if (cmd.isImagePackageType()) { - bundleRoot = cmd.outputBundle(); - } else { - bundleRoot = cmd.pathToUnpackedPackageFile(cmd.appInstallationDirectory()); - } + if (!appImageSigned(cmd)) { + final Path bundleRoot; + if (cmd.isImagePackageType()) { + bundleRoot = cmd.outputBundle(); + } else { + bundleRoot = cmd.pathToUnpackedPackageFile(cmd.appInstallationDirectory()); + } - MacSignVerify.assertAdhocSigned(bundleRoot); + MacSignVerify.assertAdhocSigned(bundleRoot); + } } static PackageHandlers createDmgPackageHandlers() { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java index 4dbb2bc1e18..20f7ac41eef 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacSign.java @@ -63,9 +63,11 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.stream.Stream; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; +import jdk.jpackage.internal.util.MemoizingSupplier; import jdk.jpackage.internal.util.function.ExceptionBox; import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.internal.util.function.ThrowingSupplier; @@ -280,8 +282,15 @@ public final class MacSign { return sb.toString(); } + public static Builder build() { + return new Builder(); + } + public static final class Builder { + private Builder() { + } + public Builder name(String v) { keychainBuilder.name(v); return this; @@ -306,8 +315,8 @@ public final class MacSign { return new KeychainWithCertsSpec(keychain, List.copyOf(certs)); } - private Keychain.Builder keychainBuilder = new Keychain.Builder(); - private List certs = new ArrayList<>(); + private final Keychain.Builder keychainBuilder = Keychain.build(); + private final List certs = new ArrayList<>(); } } @@ -326,8 +335,15 @@ public final class MacSign { } } + public static Builder build() { + return new Builder(); + } + public static final class Builder { + private Builder() { + } + public Builder name(String v) { name = v; return this; @@ -599,12 +615,7 @@ public final class MacSign { @Override public String toString() { - final var sb = new StringBuilder(); - sb.append(frame("BEGIN " + label)); - sb.append(ENCODER.encodeToString(data)); - sb.append("\n"); - sb.append(frame("END " + label)); - return sb.toString(); + return PemDataFormatter.format(label, data); } static PemData of(X509Certificate cert) { @@ -619,6 +630,21 @@ public final class MacSign { throw new UncheckedIOException(ex); } } + } + + private final class PemDataFormatter { + + static String format(String label, byte[] data) { + Objects.requireNonNull(label); + Objects.requireNonNull(data); + + final var sb = new StringBuilder(); + sb.append(frame("BEGIN " + label)); + sb.append(ENCODER.encodeToString(data)); + sb.append("\n"); + sb.append(frame("END " + label)); + return sb.toString(); + } private static String frame(String str) { return String.format("-----%s-----\n", Objects.requireNonNull(str)); @@ -627,6 +653,11 @@ public final class MacSign { private static final Base64.Encoder ENCODER = Base64.getMimeEncoder(64, "\n".getBytes()); } + public static String formatX509Certificate(X509Certificate cert) { + Objects.requireNonNull(cert); + return PemDataFormatter.format("CERTIFICATE", toSupplier(cert::getEncoded).get()); + } + public enum DigestAlgorithm { SHA1(20, () -> MessageDigest.getInstance("SHA-1")), SHA256(32, () -> MessageDigest.getInstance("SHA-256")); @@ -773,8 +804,15 @@ public final class MacSign { return COMPARATOR.compare(this, o); } + public static Builder build() { + return new Builder(); + } + public static final class Builder { + private Builder() { + } + public Builder userName(String v) { userName = v; return this; @@ -1068,6 +1106,15 @@ public final class MacSign { return !missingKeychain && !missingCertificates && !invalidCertificates; } + /** + * Creates an empty keychain with unique name in the work directory of the current test. + */ + public static Keychain createEmptyKeychain() { + return Keychain.build() + .name(TKit.createUniquePath(TKit.workDir().resolve("empty.keychain")).toAbsolutePath().toString()) + .create().create(); + } + public static Keychain.UsageBuilder withKeychains(KeychainWithCertsSpec... keychains) { return withKeychains(Stream.of(keychains).map(KeychainWithCertsSpec::keychain).toArray(Keychain[]::new)); } @@ -1100,9 +1147,14 @@ public final class MacSign { public static void withKeychain(Consumer consumer, Consumer mutator, ResolvedKeychain keychain) { Objects.requireNonNull(consumer); - withKeychains(() -> { + Objects.requireNonNull(mutator); + if (keychain.isMock()) { consumer.accept(keychain); - }, mutator, keychain.spec().keychain()); + } else { + withKeychains(() -> { + consumer.accept(keychain); + }, mutator, keychain.spec().keychain()); + } } public static void withKeychain(Consumer consumer, ResolvedKeychain keychain) { @@ -1111,7 +1163,15 @@ public final class MacSign { public static final class ResolvedKeychain { public ResolvedKeychain(KeychainWithCertsSpec spec) { + isMock = false; this.spec = Objects.requireNonNull(spec); + certMapSupplier = MemoizingSupplier.runOnce(() -> { + return MacSign.mapCertificateRequests(spec); + }); + } + + public static ResolvedKeychain createMock(String name, Map certs) { + return new ResolvedKeychain(name, certs); } public KeychainWithCertsSpec spec() { @@ -1122,15 +1182,30 @@ public final class MacSign { return spec.keychain().name(); } - public Map mapCertificateRequests() { - if (certMap == null) { - synchronized (this) { - if (certMap == null) { - certMap = MacSign.mapCertificateRequests(spec); - } - } + public boolean isMock() { + return isMock; + } + + public ResolvedKeychain toMock(Map signEnv) { + if (isMock) { + throw new UnsupportedOperationException("Already a mock"); } - return certMap; + + var comm = Comm.compare(Set.copyOf(spec.certificateRequests()), signEnv.keySet()); + if (!comm.unique1().isEmpty()) { + throw new IllegalArgumentException(String.format( + "Signing environment missing %s certificate request mappings in [%s] keychain", + comm.unique1(), name())); + } + + var certs = new HashMap<>(signEnv); + certs.keySet().retainAll(comm.common()); + + return createMock(name(), certs); + } + + public Map mapCertificateRequests() { + return certMapSupplier.get(); } public Function asCertificateResolver() { @@ -1145,8 +1220,23 @@ public final class MacSign { }; } + private ResolvedKeychain(String name, Map certs) { + + var keychainBuilder = KeychainWithCertsSpec.build().name(Objects.requireNonNull(name)); + certs.keySet().forEach(keychainBuilder::addCert); + + var certsCopy = Map.copyOf(Objects.requireNonNull(certs)); + + isMock = true; + spec = keychainBuilder.create(); + certMapSupplier = MemoizingSupplier.runOnce(() -> { + return certsCopy; + }); + } + + private final boolean isMock; private final KeychainWithCertsSpec spec; - private volatile Map certMap; + private final Supplier> certMapSupplier; } private static Map mapCertificateRequests(KeychainWithCertsSpec spec) { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java index d9ab38e006a..c4899a5376f 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/CommandAction.java @@ -60,6 +60,36 @@ public interface CommandAction { public MockIllegalStateException unexpectedArguments() { return new MockIllegalStateException(String.format("Unexpected arguments: %s", args)); } + + public Context shift(int count) { + if (count < 0) { + throw new IllegalArgumentException(); + } else if (count == 0) { + return this; + } else { + return new Context(out, err, args.subList(Integer.min(count, args.size()), args.size())); + } + } + + public Context shift() { + return shift(1); + } + + public void printlnOut(Object obj) { + out.println(obj); + } + + public void printlnOut(String str) { + out.println(str); + } + + public void printlnErr(Object obj) { + err.println(obj); + } + + public void printlnErr(String str) { + err.println(str); + } } /** diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java index 1817587364a..4656e1d4f7b 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/mock/MockIllegalStateException.java @@ -22,13 +22,15 @@ */ package jdk.jpackage.test.mock; +import java.util.Objects; + /** * Indicates command mock internal error. */ public final class MockIllegalStateException extends IllegalStateException { public MockIllegalStateException(String msg) { - super(msg); + super(Objects.requireNonNull(msg)); } private static final long serialVersionUID = 1L; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSecurityMock.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSecurityMock.java new file mode 100644 index 00000000000..fe9a67f1889 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSecurityMock.java @@ -0,0 +1,176 @@ +/* + * 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 jdk.jpackage.test.stdmock; + +import java.nio.file.Path; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import jdk.jpackage.test.MacSign; +import jdk.jpackage.test.MacSign.CertificateRequest; +import jdk.jpackage.test.MacSign.ResolvedKeychain; +import jdk.jpackage.test.mock.CommandAction; +import jdk.jpackage.test.mock.MockIllegalStateException; + +/** + * Mocks /usr/bin/security command. + */ +final class MacSecurityMock implements CommandAction { + + MacSecurityMock(MacSignMockUtils.SignEnv signEnv) { + Objects.requireNonNull(signEnv); + + var keychains = signEnv.keychains(); + + var stdUserKeychains = Stream.of(StandardKeychain.values()).map(StandardKeychain::keychainName).filter(name -> { + // Add standard keychain unless it is defined in the signing environment. + return keychains.stream().noneMatch(keychain -> { + return keychain.name().equals(name); + }); + }).map(name -> { + // Assume the standard keychain is empty. + return ResolvedKeychain.createMock(name, Map.of()); + }); + + allKnownKeychains = Stream.of( + stdUserKeychains, + keychains.stream() + ).flatMap(x -> x).collect(Collectors.toUnmodifiableMap(ResolvedKeychain::name, x -> x)); + + currentKeychains.addAll(Stream.of(StandardKeychain.values()) + .map(StandardKeychain::keychainName) + .map(allKnownKeychains::get) + .map(Objects::requireNonNull).toList()); + } + + @Override + public Optional run(Context context) { + switch (context.args().getFirst()) { + case "list-keychains" -> { + listKeychains(context.shift()); + return Optional.of(0); + } + case "find-certificate" -> { + findCertificate(context.shift()); + return Optional.of(0); + } + default -> { + throw context.unexpectedArguments(); + } + } + } + + private void listKeychains(Context context) { + if (context.args().getFirst().equals("-s")) { + currentKeychains.clear(); + currentKeychains.addAll(context.shift().args().stream().map(name -> { + return Optional.ofNullable(allKnownKeychains.get(name)).orElseThrow(() -> { + throw new MockIllegalStateException(String.format("Unknown keychain name: %s", name)); + }); + }).toList()); + } else if (context.args().isEmpty()) { + currentKeychains.stream().map(keychain -> { + return String.format(" \"%s\"", keychain.name()); + }).forEach(context::printlnOut); + } else { + throw context.unexpectedArguments(); + } + } + + private void findCertificate(Context context) { + + var args = new ArrayList<>(context.args()); + for (var mandatoryArg : List.of("-p", "-a")) { + if (!args.remove(mandatoryArg)) { + throw context.unexpectedArguments(); + } + } + + var certNameFilter = context.findOptionValue("-c").map(certNameSubstr -> { + + // Remove option name and its value. + var idx = args.indexOf("-c"); + args.remove(idx); + args.remove(idx); + + Predicate> pred = e -> { + return e.getKey().name().contains(certNameSubstr); + }; + return pred; + }); + + Stream keychains; + if (args.isEmpty()) { + keychains = currentKeychains.stream(); + } else { + // Remaining arguments must be keychain names. + keychains = args.stream().map(keychainName -> { + return Optional.ofNullable(allKnownKeychains.get(keychainName)).orElseThrow(() -> { + throw new MockIllegalStateException(String.format("Unknown keychain name: %s", keychainName)); + }); + }); + } + + var certStream = keychains.flatMap(keychain -> { + return keychain.mapCertificateRequests().entrySet().stream(); + }); + + if (certNameFilter.isPresent()) { + certStream = certStream.filter(certNameFilter.get()); + } + + certStream.map(Map.Entry::getValue).map(MacSign::formatX509Certificate).forEach(formattedCert -> { + context.out().print(formattedCert); + }); + } + + // Keep the order of the items as the corresponding keychains appear + // in the output of the "/usr/bin/security list-keychains" command. + private enum StandardKeychain { + USER_KEYCHAIN { + @Override + String keychainName() { + return Path.of(System.getProperty("user.home")).resolve("Library/Keychains/login.keychain-db").toString(); + } + }, + SYSTEM_KEYCHAIN { + @Override + String keychainName() { + return "/Library/Keychains/System.keychain"; + } + }, + ; + + abstract String keychainName(); + } + + private final List currentKeychains = new ArrayList(); + private final Map allKnownKeychains; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSignMockUtils.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSignMockUtils.java new file mode 100644 index 00000000000..164261a6000 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/stdmock/MacSignMockUtils.java @@ -0,0 +1,284 @@ +/* + * 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 jdk.jpackage.test.stdmock; + +import static jdk.jpackage.internal.util.function.ExceptionBox.toUnchecked; +import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; +import static jdk.jpackage.internal.util.function.ThrowingRunnable.toRunnable; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.test.MacSign.CertificateRequest; +import jdk.jpackage.test.MacSign.KeychainWithCertsSpec; +import jdk.jpackage.test.MacSign.ResolvedKeychain; +import jdk.jpackage.test.mock.CommandActionSpec; +import jdk.jpackage.test.mock.CommandActionSpecs; +import jdk.jpackage.test.mock.CommandMockSpec; + + +/** + * Utilities to create macOS signing tool mocks. + */ +public final class MacSignMockUtils { + + private MacSignMockUtils() { + } + + public static Map resolveCertificateRequests( + Collection certificateRequests) { + Objects.requireNonNull(certificateRequests); + + var caKeys = createKeyPair(); + + Function resolver = toFunction(certRequest -> { + var builder = new CertificateBuilder() + .setSubjectName("CN=" + certRequest.name()) + .setPublicKey(caKeys.getPublic()) + .setSerialNumber(BigInteger.ONE) + .addSubjectKeyIdExt(caKeys.getPublic()) + .addAuthorityKeyIdExt(caKeys.getPublic()); + + Instant from; + Instant to; + if (certRequest.expired()) { + from = LocalDate.now().minusDays(10).atStartOfDay(ZoneId.systemDefault()).toInstant(); + to = from.plus(Duration.ofDays(1)); + } else { + from = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant(); + to = from.plus(Duration.ofDays(certRequest.days())); + } + builder.setValidity(Date.from(from), Date.from(to)); + + return builder.build(null, caKeys.getPrivate()); + }); + + return certificateRequests.stream() + .distinct() + .collect(Collectors.toUnmodifiableMap(x -> x, resolver)); + } + + public static Map resolveCertificateRequests( + CertificateRequest... certificateRequests) { + return resolveCertificateRequests(List.of(certificateRequests)); + } + + public static final class SignEnv { + + public SignEnv(List spec) { + Objects.requireNonNull(spec); + + spec.stream().map(keychain -> { + return keychain.keychain().name(); + }).collect(Collectors.toMap(x -> x, x -> x, (a, b) -> { + throw new IllegalArgumentException(String.format("Multiple keychains with the same name: %s", a)); + })); + + this.spec = List.copyOf(spec); + this.env = resolveCertificateRequests( + spec.stream().map(KeychainWithCertsSpec::certificateRequests).flatMap(Collection::stream).toList()); + } + + public SignEnv(KeychainWithCertsSpec... spec) { + this(List.of(spec)); + } + + public List keychains() { + return spec.stream().map(ResolvedKeychain::new).map(keychain -> { + return keychain.toMock(env); + }).toList(); + } + + public Map env() { + return env; + } + + private final Map env; + private final List spec; + } + + public static CommandMockSpec securityMock(SignEnv signEnv) { + var action = CommandActionSpec.create("/usr/bin/security", new MacSecurityMock(signEnv)); + return new CommandMockSpec(action.description(), CommandActionSpecs.build().action(action).create()); + } + + private static KeyPair createKeyPair() { + try { + var kpg = KeyPairGenerator.getInstance("RSA"); + return kpg.generateKeyPair(); + } catch (NoSuchAlgorithmException ex) { + throw ExceptionBox.toUnchecked(ex); + } + } + + // + // Reflection proxy for jdk.test.lib.security.CertificateBuilder class. + // + // Can't use it directly because it is impossible to cherry-pick this class from the JDK test lib in JUnit tests due to limitations of jtreg. + // + // Shared jpackage JUnit tests don't require "jdk.jpackage.test.stdmock", but they depend on "jdk.jpackage.test" package. + // Source code for these two packages resides in the same directory tree, so jtreg will pull in classes from both packages for the jpackage JUnit tests. + // Static dependency on jdk.test.lib.security.CertificateBuilder class will force pulling in the entire JDK test lib, because of jtreg limitations. + // + // Use dynamic dependency as a workaround. Tests that require jdk.test.lib.security.CertificateBuilder class, should have + // + // /* + // * ... + // * @library /test/lib + // * @build jdk.test.lib.security.CertificateBuilder + // */ + // + // in their declarations. They also should have + // + // --add-exports java.base/sun.security.x509=ALL-UNNAMED + // --add-exports java.base/sun.security.util=ALL-UNNAMED + // + // on javac and java command lines. + // + private static final class CertificateBuilder { + + CertificateBuilder() { + instance = toSupplier(ctor::newInstance).get(); + } + + CertificateBuilder setSubjectName(String v) { + toRunnable(() -> { + setSubjectName.invoke(instance, v); + }).run(); + return this; + } + + CertificateBuilder setPublicKey(PublicKey v) { + toRunnable(() -> { + setPublicKey.invoke(instance, v); + }).run(); + return this; + } + + CertificateBuilder setSerialNumber(BigInteger v) { + toRunnable(() -> { + setSerialNumber.invoke(instance, v); + }).run(); + return this; + } + + CertificateBuilder addSubjectKeyIdExt(PublicKey v) { + toRunnable(() -> { + addSubjectKeyIdExt.invoke(instance, v); + }).run(); + return this; + } + + CertificateBuilder addAuthorityKeyIdExt(PublicKey v) { + toRunnable(() -> { + addAuthorityKeyIdExt.invoke(instance, v); + }).run(); + return this; + } + + CertificateBuilder setValidity(Date from, Date to) { + toRunnable(() -> { + setValidity.invoke(instance, from, to); + }).run(); + return this; + } + + X509Certificate build(X509Certificate issuerCert, PrivateKey issuerKey) throws IOException, CertificateException { + try { + return (X509Certificate)toSupplier(() -> { + return build.invoke(instance, issuerCert, issuerKey); + }).get(); + } catch (ExceptionBox box) { + switch (ExceptionBox.unbox(box)) { + case IOException ex -> { + throw ex; + } + case CertificateException ex -> { + throw ex; + } + default -> { + throw box; + } + } + } + } + + private final Object instance; + + private static final Constructor ctor; + private static final Method setSubjectName; + private static final Method setPublicKey; + private static final Method setSerialNumber; + private static final Method addSubjectKeyIdExt; + private static final Method addAuthorityKeyIdExt; + private static final Method setValidity; + private static final Method build; + + static { + try { + var certificateBuilderClass = Class.forName("jdk.test.lib.security.CertificateBuilder"); + + ctor = certificateBuilderClass.getConstructor(); + + setSubjectName = certificateBuilderClass.getMethod("setSubjectName", String.class); + + setPublicKey = certificateBuilderClass.getMethod("setPublicKey", PublicKey.class); + + setSerialNumber = certificateBuilderClass.getMethod("setSerialNumber", BigInteger.class); + + addSubjectKeyIdExt = certificateBuilderClass.getMethod("addSubjectKeyIdExt", PublicKey.class); + + addAuthorityKeyIdExt = certificateBuilderClass.getMethod("addAuthorityKeyIdExt", PublicKey.class); + + setValidity = certificateBuilderClass.getMethod("setValidity", Date.class, Date.class); + + build = certificateBuilderClass.getMethod("build", X509Certificate.class, PrivateKey.class); + + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException ex) { + throw toUnchecked(ex); + } + } + } +} diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes index 40f73e624b6..0b98c051238 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/cli/OptionsValidationFailTest.excludes @@ -39,6 +39,16 @@ ErrorTest.test(WIN_MSI; app-desc=Hello; args-add=[--app-version, 1234]; errors=[ ErrorTest.test(WIN_MSI; app-desc=Hello; args-add=[--app-version, 256.1]; errors=[message.error-header+[error.msi-product-version-major-out-of-range, 256.1], message.advice-header+[error.version-string-wrong-format.advice]]) ErrorTest.test(WIN_MSI; app-desc=Hello; args-add=[--launcher-as-service]; errors=[message.error-header+[error.missing-service-installer], message.advice-header+[error.missing-service-installer.advice]]) ErrorTest.test(args-add=[@foo]; errors=[message.error-header+[ERR_CannotParseOptions, foo]]) +ErrorTest.testMacSignWithoutIdentity(IMAGE; app-desc=Hello; args-add=[--mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(IMAGE; args-add=[--app-image, @@APP_IMAGE_WITH_SHORT_NAME@@, --mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(MAC_DMG; app-desc=Hello; args-add=[--mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(MAC_DMG; args-add=[--app-image, @@APP_IMAGE_WITH_SHORT_NAME@@, --mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; app-desc=Hello; args-add=[--mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN], message.error-header+[error.cert.not.found, INSTALLER, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; app-desc=Hello; args-add=[--mac-sign, --mac-signing-keychain, @@KEYCHAIN_WITH_APP_IMAGE_CERT@@]; args-del=[--name]; errors=[message.error-header+[error.cert.not.found, INSTALLER, KEYCHAIN_WITH_APP_IMAGE_CERT]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; app-desc=Hello; args-add=[--mac-sign, --mac-signing-keychain, @@KEYCHAIN_WITH_PKG_CERT@@]; args-del=[--name]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, KEYCHAIN_WITH_PKG_CERT]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; args-add=[--app-image, @@APP_IMAGE_WITH_SHORT_NAME@@, --mac-sign, --mac-signing-keychain, @@EMPTY_KEYCHAIN@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, EMPTY_KEYCHAIN], message.error-header+[error.cert.not.found, INSTALLER, EMPTY_KEYCHAIN]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; args-add=[--mac-sign, --mac-signing-keychain, @@KEYCHAIN_WITH_APP_IMAGE_CERT@@, --app-image, @@APP_IMAGE_WITH_SHORT_NAME@@]; errors=[message.error-header+[error.cert.not.found, INSTALLER, KEYCHAIN_WITH_APP_IMAGE_CERT]]) +ErrorTest.testMacSignWithoutIdentity(MAC_PKG; args-add=[--mac-sign, --mac-signing-keychain, @@KEYCHAIN_WITH_PKG_CERT@@, --app-image, @@APP_IMAGE_WITH_SHORT_NAME@@]; errors=[message.error-header+[error.cert.not.found, CODE_SIGN, KEYCHAIN_WITH_PKG_CERT]]) ErrorTest.testMacSigningIdentityValidation(IMAGE, --mac-app-image-sign-identity, true) ErrorTest.testMacSigningIdentityValidation(IMAGE, --mac-signing-key-user-name, false) ErrorTest.testMacSigningIdentityValidation(MAC_DMG, --mac-app-image-sign-identity, true) diff --git a/test/jdk/tools/jpackage/macosx/SigningAppImageTest.java b/test/jdk/tools/jpackage/macosx/SigningAppImageTest.java index 0f299cb5a24..3a257a425b6 100644 --- a/test/jdk/tools/jpackage/macosx/SigningAppImageTest.java +++ b/test/jdk/tools/jpackage/macosx/SigningAppImageTest.java @@ -82,10 +82,17 @@ public class SigningAppImageTest { SigningBase.StandardCertificateRequest.CODESIGN_UNICODE )) { for (var signIdentityType : SignKeyOption.Type.defaultValues()) { - data.add(new SignKeyOptionWithKeychain( - signIdentityType, - certRequest, - SigningBase.StandardKeychain.MAIN.keychain())); + SigningBase.StandardKeychain keychain; + if (signIdentityType == SignKeyOption.Type.SIGN_KEY_IMPLICIT) { + keychain = SigningBase.StandardKeychain.SINGLE; + if (!keychain.contains(certRequest)) { + continue; + } + } else { + keychain = SigningBase.StandardKeychain.MAIN; + } + + data.add(new SignKeyOptionWithKeychain(signIdentityType, certRequest, keychain.keychain())); } } diff --git a/test/jdk/tools/jpackage/macosx/SigningAppImageTwoStepsTest.java b/test/jdk/tools/jpackage/macosx/SigningAppImageTwoStepsTest.java index 2c7ae205e69..a6d94b59bd9 100644 --- a/test/jdk/tools/jpackage/macosx/SigningAppImageTwoStepsTest.java +++ b/test/jdk/tools/jpackage/macosx/SigningAppImageTwoStepsTest.java @@ -93,6 +93,11 @@ public class SigningAppImageTwoStepsTest { return new TestSpec(Optional.ofNullable(signAppImage), sign); } + Builder keychain(SigningBase.StandardKeychain v) { + keychain = Objects.requireNonNull(v); + return this; + } + Builder certRequest(SigningBase.StandardCertificateRequest v) { certRequest = Objects.requireNonNull(v); return this; @@ -117,9 +122,10 @@ public class SigningAppImageTwoStepsTest { return new SignKeyOptionWithKeychain( signIdentityType, certRequest, - SigningBase.StandardKeychain.MAIN.keychain()); + keychain.keychain()); } + private SigningBase.StandardKeychain keychain = SigningBase.StandardKeychain.MAIN; private SigningBase.StandardCertificateRequest certRequest = SigningBase.StandardCertificateRequest.CODESIGN; private SignKeyOption.Type signIdentityType = SignKeyOption.Type.SIGN_KEY_IDENTITY; @@ -144,18 +150,26 @@ public class SigningAppImageTwoStepsTest { }, signOption.keychain()); }, appImageCmd::execute); - var cmd = new JPackageCommand() - .setPackageType(PackageType.IMAGE) - .addArguments("--app-image", appImageCmd.outputBundle()) - .mutate(sign::addTo); + MacSign.withKeychain(keychain -> { + var cmd = new JPackageCommand() + .setPackageType(PackageType.IMAGE) + .addArguments("--app-image", appImageCmd.outputBundle()) + .mutate(sign::addTo); - cmd.executeAndAssertHelloAppImageCreated(); - MacSignVerify.verifyAppImageSigned(cmd, sign.certRequest()); + cmd.executeAndAssertHelloAppImageCreated(); + MacSignVerify.verifyAppImageSigned(cmd, sign.certRequest()); + }, sign.keychain()); } } public static Collection test() { + var signIdentityTypes = List.of( + SignKeyOption.Type.SIGN_KEY_USER_SHORT_NAME, + SignKeyOption.Type.SIGN_KEY_IDENTITY_APP_IMAGE, + SignKeyOption.Type.SIGN_KEY_IMPLICIT + ); + List data = new ArrayList<>(); for (var appImageSign : withAndWithout(SignKeyOption.Type.SIGN_KEY_IDENTITY)) { @@ -167,9 +181,12 @@ public class SigningAppImageTwoStepsTest { .certRequest(SigningBase.StandardCertificateRequest.CODESIGN_ACME_TECH_LTD) .signAppImage(); }); - for (var signIdentityType : SignKeyOption.Type.defaultValues()) { + for (var signIdentityType : signIdentityTypes) { builder.signIdentityType(signIdentityType) .certRequest(SigningBase.StandardCertificateRequest.CODESIGN); + if (signIdentityType == SignKeyOption.Type.SIGN_KEY_IMPLICIT) { + builder.keychain(SigningBase.StandardKeychain.SINGLE); + } data.add(builder.sign().create()); } } diff --git a/test/jdk/tools/jpackage/macosx/SigningBase.java b/test/jdk/tools/jpackage/macosx/SigningBase.java index 5f4367e6096..e7e2d7e44cf 100644 --- a/test/jdk/tools/jpackage/macosx/SigningBase.java +++ b/test/jdk/tools/jpackage/macosx/SigningBase.java @@ -38,7 +38,7 @@ import jdk.jpackage.test.TKit; * @test * @summary Setup the environment for jpackage macos signing tests. * Creates required keychains and signing identities. - * Does NOT run any jpackag tests. + * Does NOT run any jpackage tests. * @library /test/jdk/tools/jpackage/helpers * @build jdk.jpackage.test.* * @compile -Xlint:all -Werror SigningBase.java @@ -51,7 +51,7 @@ import jdk.jpackage.test.TKit; * @test * @summary Tear down the environment for jpackage macos signing tests. * Deletes required keychains and signing identities. - * Does NOT run any jpackag tests. + * Does NOT run any jpackage tests. * @library /test/jdk/tools/jpackage/helpers * @build jdk.jpackage.test.* * @compile -Xlint:all -Werror SigningBase.java @@ -83,7 +83,7 @@ public class SigningBase { } private static CertificateRequest.Builder cert() { - return new CertificateRequest.Builder(); + return CertificateRequest.build(); } private final CertificateRequest spec; @@ -118,6 +118,12 @@ public class SigningBase { StandardCertificateRequest.PKG, StandardCertificateRequest.CODESIGN_COPY, StandardCertificateRequest.PKG_COPY), + /** + * A keychain with a single certificate for each role. + */ + SINGLE("jpackagerTest-single.keychain", + StandardCertificateRequest.CODESIGN, + StandardCertificateRequest.PKG), ; StandardKeychain(String keychainName, StandardCertificateRequest... certs) { @@ -145,7 +151,7 @@ public class SigningBase { } private static KeychainWithCertsSpec.Builder keychain(String name) { - return new KeychainWithCertsSpec.Builder().name(name); + return KeychainWithCertsSpec.build().name(name); } private static List signingEnv() { @@ -164,13 +170,13 @@ public class SigningBase { } public static void verifySignTestEnvReady() { - if (!Inner.SIGN_ENV_READY) { + if (!SignEnvReady.VALUE) { TKit.throwSkippedException(new IllegalStateException("Misconfigured signing test environment")); } } - private final class Inner { - private static final boolean SIGN_ENV_READY = MacSign.isDeployed(StandardKeychain.signingEnv()); + private final class SignEnvReady { + static final boolean VALUE = MacSign.isDeployed(StandardKeychain.signingEnv()); } private static final String NAME_ASCII = "jpackage.openjdk.java.net"; diff --git a/test/jdk/tools/jpackage/macosx/SigningPackageTest.java b/test/jdk/tools/jpackage/macosx/SigningPackageTest.java index 8a93ce5f749..d1c17fb61cd 100644 --- a/test/jdk/tools/jpackage/macosx/SigningPackageTest.java +++ b/test/jdk/tools/jpackage/macosx/SigningPackageTest.java @@ -94,7 +94,7 @@ public class SigningPackageTest { } public static Collection test() { - return TestSpec.testCases(true).stream().map(v -> { + return TestSpec.testCases().stream().map(v -> { return new Object[] {v}; }).toList(); } @@ -126,7 +126,10 @@ public class SigningPackageTest { } if (appImageSignOption.isEmpty()) { - if (packageSignOption.get().type() != SignKeyOption.Type.SIGN_KEY_IDENTITY) { + if (!List.of( + SignKeyOption.Type.SIGN_KEY_IDENTITY, + SignKeyOption.Type.SIGN_KEY_IDENTITY_SHA1 + ).contains(packageSignOption.get().type())) { // They request to sign the .pkg installer without // the "--mac-installer-sign-identity" option, // but didn't specify a signing option for the packaged app image. @@ -204,15 +207,61 @@ public class SigningPackageTest { } MacSign.ResolvedKeychain keychain() { - return SigningBase.StandardKeychain.MAIN.keychain(); + return chooseKeychain(Stream.of( + appImageSignOption.stream(), + packageSignOption.stream() + ).flatMap(x -> x).map(SignKeyOption::type).findFirst().orElseThrow()).keychain(); } - static List testCases(boolean withUnicode) { + /** + * Types of test cases to skip. + */ + enum SkipTestCases { + /** + * Skip test cases with signing identities/key names with symbols outside of the + * ASCII codepage. + */ + SKIP_UNICODE, + /** + * Skip test cases in which the value of the "--mac-signing-key-user-name" + * option is the full signing identity name. + */ + SKIP_SIGN_KEY_USER_FULL_NAME, + /** + * Skip test cases in which the value of the "--mac-installer-sign-identity" or + * "--mac-app-image-sign-identity" option is the SHA1 digest of the signing + * certificate. + */ + SKIP_SIGN_KEY_IDENTITY_SHA1, + ; + } + + static List minimalTestCases() { + return testCases(SkipTestCases.values()); + } + + static List testCases(SkipTestCases... skipTestCases) { + + final var skipTestCasesAsSet = Set.of(skipTestCases); + + final var signIdentityTypes = Stream.of(SignKeyOption.Type.defaultValues()).filter(v -> { + switch (v) { + case SIGN_KEY_USER_FULL_NAME -> { + return !skipTestCasesAsSet.contains(SkipTestCases.SKIP_SIGN_KEY_USER_FULL_NAME); + } + case SIGN_KEY_IDENTITY_SHA1 -> { + return !skipTestCasesAsSet.contains(SkipTestCases.SKIP_SIGN_KEY_IDENTITY_SHA1); + } + default -> { + return true; + } + } + }).toList(); List data = new ArrayList<>(); List> certRequestGroups; - if (withUnicode) { + if (!skipTestCasesAsSet.contains(SkipTestCases.SKIP_UNICODE)) { certRequestGroups = List.of( List.of(SigningBase.StandardCertificateRequest.CODESIGN, SigningBase.StandardCertificateRequest.PKG), List.of(SigningBase.StandardCertificateRequest.CODESIGN_UNICODE, SigningBase.StandardCertificateRequest.PKG_UNICODE) @@ -224,19 +273,33 @@ public class SigningPackageTest { } for (var certRequests : certRequestGroups) { - for (var signIdentityType : SignKeyOption.Type.defaultValues()) { - var keychain = SigningBase.StandardKeychain.MAIN.keychain(); + for (var signIdentityType : signIdentityTypes) { + if (signIdentityType == SignKeyOption.Type.SIGN_KEY_IMPLICIT + && !SigningBase.StandardKeychain.SINGLE.contains(certRequests.getFirst())) { + // Skip invalid test case: the keychain for testing signing without + // an explicitly specified signing key option doesn't have this signing key. + break; + } + + if (signIdentityType.passThrough() && !certRequests.contains(SigningBase.StandardCertificateRequest.CODESIGN)) { + // Using a pass-through signing option. + // Doesn't make sense to waste time on testing it with multiple certificates. + // Skip the test cases using non "default" certificate. + break; + } + + var keychain = chooseKeychain(signIdentityType).keychain(); var appImageSignKeyOption = new SignKeyOption(signIdentityType, certRequests.getFirst(), keychain); var pkgSignKeyOption = new SignKeyOption(signIdentityType, certRequests.getLast(), keychain); switch (signIdentityType) { - case SIGN_KEY_IDENTITY -> { + case SIGN_KEY_IDENTITY, SIGN_KEY_IDENTITY_SHA1 -> { // Use "--mac-installer-sign-identity" and "--mac-app-image-sign-identity" signing options. // They allows to sign the packaged app image and the installer (.pkg) separately. data.add(new TestSpec(Optional.of(appImageSignKeyOption), Optional.empty(), PackageType.MAC)); data.add(new TestSpec(Optional.empty(), Optional.of(pkgSignKeyOption), PackageType.MAC_PKG)); } - case SIGN_KEY_USER_SHORT_NAME -> { + case SIGN_KEY_USER_SHORT_NAME, SIGN_KEY_IMPLICIT -> { // Use "--mac-signing-key-user-name" signing option with short user name or implicit signing option. // It signs both the packaged app image and the installer (.pkg). // Thus, if the installer is not signed, it can be used only with .dmg packaging. @@ -263,5 +326,13 @@ public class SigningPackageTest { return data; } + + private static SigningBase.StandardKeychain chooseKeychain(SignKeyOption.Type signIdentityType) { + if (signIdentityType == SignKeyOption.Type.SIGN_KEY_IMPLICIT) { + return SigningBase.StandardKeychain.SINGLE; + } else { + return SigningBase.StandardKeychain.MAIN; + } + } } } diff --git a/test/jdk/tools/jpackage/macosx/SigningPackageTwoStepTest.java b/test/jdk/tools/jpackage/macosx/SigningPackageTwoStepTest.java index 23195c9a856..d0de9c8c704 100644 --- a/test/jdk/tools/jpackage/macosx/SigningPackageTwoStepTest.java +++ b/test/jdk/tools/jpackage/macosx/SigningPackageTwoStepTest.java @@ -108,7 +108,7 @@ public class SigningPackageTwoStepTest { appImageSignOption = Optional.empty(); } - for (var signPackage : SigningPackageTest.TestSpec.testCases(false)) { + for (var signPackage : SigningPackageTest.TestSpec.minimalTestCases()) { data.add(new TwoStepsTestSpec(appImageSignOption, signPackage)); } } diff --git a/test/jdk/tools/jpackage/macosx/SigningRuntimeImagePackageTest.java b/test/jdk/tools/jpackage/macosx/SigningRuntimeImagePackageTest.java index 604399ebd7a..54021aa2a0b 100644 --- a/test/jdk/tools/jpackage/macosx/SigningRuntimeImagePackageTest.java +++ b/test/jdk/tools/jpackage/macosx/SigningRuntimeImagePackageTest.java @@ -125,7 +125,7 @@ public class SigningRuntimeImagePackageTest { runtimeSignOption = Optional.empty(); } - for (var signPackage : SigningPackageTest.TestSpec.testCases(false)) { + for (var signPackage : SigningPackageTest.TestSpec.minimalTestCases()) { data.add(new RuntimeTestSpec(runtimeSignOption, runtimeType, signPackage)); } } diff --git a/test/jdk/tools/jpackage/share/ErrorTest.java b/test/jdk/tools/jpackage/share/ErrorTest.java index 86390a85068..2133823381c 100644 --- a/test/jdk/tools/jpackage/share/ErrorTest.java +++ b/test/jdk/tools/jpackage/share/ErrorTest.java @@ -26,7 +26,7 @@ import static java.util.stream.Collectors.toMap; import static jdk.internal.util.OperatingSystem.LINUX; import static jdk.internal.util.OperatingSystem.MACOS; import static jdk.internal.util.OperatingSystem.WINDOWS; -import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; import static jdk.jpackage.test.JPackageCommand.makeAdvice; import static jdk.jpackage.test.JPackageCommand.makeError; @@ -45,6 +45,7 @@ import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.stream.Stream; +import jdk.internal.util.OperatingSystem; import jdk.jpackage.internal.util.TokenReplace; import jdk.jpackage.test.Annotations.Parameter; import jdk.jpackage.test.Annotations.ParameterSupplier; @@ -53,14 +54,27 @@ import jdk.jpackage.test.CannedArgument; import jdk.jpackage.test.CannedFormattedString; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.JPackageOutputValidator; +import jdk.jpackage.test.MacSign; +import jdk.jpackage.test.MacSign.CertificateRequest; +import jdk.jpackage.test.MacSign.CertificateType; +import jdk.jpackage.test.MacSign.KeychainWithCertsSpec; +import jdk.jpackage.test.MacSign.ResolvedKeychain; +import jdk.jpackage.test.MacSign.StandardCertificateNamePrefix; import jdk.jpackage.test.PackageType; import jdk.jpackage.test.TKit; +import jdk.jpackage.test.mock.Script; +import jdk.jpackage.test.mock.VerbatimCommandMock; +import jdk.jpackage.test.stdmock.JPackageMockUtils; +import jdk.jpackage.test.stdmock.MacSignMockUtils; /* * @test * @summary Test jpackage output for erroneous input * @library /test/jdk/tools/jpackage/helpers + * @library /test/lib * @build jdk.jpackage.test.* + * @build jdk.jpackage.test.stdmock.* + * @build jdk.test.lib.security.CertificateBuilder * @compile -Xlint:all -Werror ErrorTest.java * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main * --jpt-run=ErrorTest @@ -71,7 +85,10 @@ import jdk.jpackage.test.TKit; * @test * @summary Test jpackage output for erroneous input * @library /test/jdk/tools/jpackage/helpers + * @library /test/lib * @build jdk.jpackage.test.* + * @build jdk.jpackage.test.stdmock.* + * @build jdk.test.lib.security.CertificateBuilder * @compile -Xlint:all -Werror ErrorTest.java * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main * --jpt-run=ErrorTest @@ -81,10 +98,10 @@ import jdk.jpackage.test.TKit; public final class ErrorTest { enum Token { - JAVA_HOME(cmd -> { + JAVA_HOME(() -> { return System.getProperty("java.home"); }), - APP_IMAGE(cmd -> { + APP_IMAGE(() -> { final var appImageRoot = TKit.createTempDirectory("appimage"); final var appImageCmd = JPackageCommand.helloAppImage() @@ -92,28 +109,44 @@ public final class ErrorTest { appImageCmd.execute(); - return appImageCmd.outputBundle().toString(); + return appImageCmd.outputBundle(); }), - INVALID_MAC_RUNTIME_BUNDLE(toFunction(cmd -> { + APP_IMAGE_WITH_SHORT_NAME(() -> { + final var appImageRoot = TKit.createTempDirectory("appimage"); + + final var appImageCmd = JPackageCommand.helloAppImage() + .setFakeRuntime().setArgumentValue("--dest", appImageRoot); + + // Let jpackage pick the name from the main class (Hello). It qualifies as the "short" name. + appImageCmd.removeArgumentWithValue("--name"); + + appImageCmd.execute(); + + return appImageCmd.outputBundle(); + }), + INVALID_MAC_RUNTIME_BUNDLE(toSupplier(() -> { // Has "Contents/MacOS/libjli.dylib", but missing "Contents/Home/lib/libjli.dylib". final Path root = TKit.createTempDirectory("mac-invalid-runtime-bundle"); Files.createDirectories(root.resolve("Contents/Home")); Files.createFile(root.resolve("Contents/Info.plist")); Files.createDirectories(root.resolve("Contents/MacOS")); Files.createFile(root.resolve("Contents/MacOS/libjli.dylib")); - return root.toString(); + return root; })), - INVALID_MAC_RUNTIME_IMAGE(toFunction(cmd -> { + INVALID_MAC_RUNTIME_IMAGE(toSupplier(() -> { // Has some files in the "lib" subdirectory, but doesn't have the "lib/libjli.dylib" file. final Path root = TKit.createTempDirectory("mac-invalid-runtime-image"); Files.createDirectories(root.resolve("lib")); Files.createFile(root.resolve("lib/foo")); - return root.toString(); + return root; })), - EMPTY_DIR(toFunction(cmd -> { + EMPTY_DIR(() -> { return TKit.createTempDirectory("empty-dir"); - })), + }), ADD_LAUNCHER_PROPERTY_FILE, + EMPTY_KEYCHAIN, + KEYCHAIN_WITH_APP_IMAGE_CERT, + KEYCHAIN_WITH_PKG_CERT, ; private Token() { @@ -124,6 +157,12 @@ public final class ErrorTest { this.valueSupplier = Optional.of(valueSupplier); } + private Token(Supplier valueSupplier) { + this(_ -> { + return valueSupplier.get(); + }); + } + String token() { return makeToken(name()); } @@ -558,7 +597,7 @@ public final class ErrorTest { } public static Collection invalidAppVersion() { - return fromTestSpecBuilders(Stream.of( + return toTestArgs(Stream.of( // Invalid app version. Just cover all different error messages. // Extensive testing of invalid version strings is done in DottedVersionTest unit test. testSpec().addArgs("--app-version", "").error("error.version-string-empty"), @@ -601,7 +640,7 @@ public final class ErrorTest { argsStream = Stream.concat(argsStream, Stream.of(List.of("--win-console"))); } - return fromTestSpecBuilders(argsStream.map(args -> { + return toTestArgs(argsStream.map(args -> { var builder = testSpec().noAppDesc().nativeType() .addArgs("--runtime-image", Token.JAVA_HOME.token()) .addArgs(args); @@ -629,7 +668,7 @@ public final class ErrorTest { } public static Collection testAdditionLaunchers() { - return fromTestSpecBuilders(Stream.of( + return toTestArgs(Stream.of( testSpec().addArgs("--add-launcher", Token.ADD_LAUNCHER_PROPERTY_FILE.token()) .error("error.parameter-add-launcher-malformed", Token.ADD_LAUNCHER_PROPERTY_FILE, "--add-launcher"), testSpec().removeArgs("--name").addArgs("--name", "foo", "--add-launcher", "foo=" + Token.ADD_LAUNCHER_PROPERTY_FILE.token()) @@ -637,6 +676,184 @@ public final class ErrorTest { )); } + @Test(ifOS = MACOS) + @ParameterSupplier + @ParameterSupplier("testMacPkgSignWithoutIdentity") + public static void testMacSignWithoutIdentity(TestSpec spec) { + // The test called JPackage Command.useToolProviderBy Default(), + // which alters global variables in the test library, + // so run the test case with a new global state to isolate the alteration of the globals. + TKit.withNewState(() -> { + testMacSignWithoutIdentityWithNewTKitState(spec); + }); + } + + private static void testMacSignWithoutIdentityWithNewTKitState(TestSpec spec) { + final Token keychainToken = spec.expectedMessages().stream().flatMap(cannedStr -> { + return Stream.of(cannedStr.args()).filter(Token.class::isInstance).map(Token.class::cast).filter(token -> { + switch (token) { + case EMPTY_KEYCHAIN, KEYCHAIN_WITH_APP_IMAGE_CERT, KEYCHAIN_WITH_PKG_CERT -> { + return true; + } + default -> { + return false; + } + } + }); + }).distinct().reduce((a, b) -> { + throw new IllegalStateException(String.format( + "Error messages %s reference multiple keychains: %s and %s", spec.expectedMessages(), a, b)); + }).orElseThrow(); + + final ResolvedKeychain keychain; + + switch (keychainToken) { + case EMPTY_KEYCHAIN -> { + keychain = new ResolvedKeychain(new KeychainWithCertsSpec(MacSign.createEmptyKeychain(), List.of())); + } + case KEYCHAIN_WITH_APP_IMAGE_CERT, KEYCHAIN_WITH_PKG_CERT -> { + CertificateType existingCertType; + switch (keychainToken) { + case KEYCHAIN_WITH_APP_IMAGE_CERT -> { + existingCertType = CertificateType.CODE_SIGN; + } + case KEYCHAIN_WITH_PKG_CERT -> { + existingCertType = CertificateType.INSTALLER; + } + default -> { + throw new AssertionError(); + } + } + + keychain = Stream.of(SignEnvMock.SingleCertificateKeychain.values()).filter(k -> { + return k.certificateType() == existingCertType; + }).findFirst().orElseThrow().keychain(); + + var script = Script.build() + // Disable the mutation making mocks "run once". + .commandMockBuilderMutator(null) + // Replace "/usr/bin/security" with the mock bound to the keychain mock. + .map(MacSignMockUtils.securityMock(SignEnvMock.VALUE)) + // Don't mock other external commands. + .use(VerbatimCommandMock.INSTANCE) + .createLoop(); + + // Create jpackage tool provider using the /usr/bin/security mock. + var jpackage = JPackageMockUtils.createJPackageToolProvider(OperatingSystem.MACOS, script); + + // Override the default jpackage tool provider with the one using the /usr/bin/security mock. + JPackageCommand.useToolProviderByDefault(jpackage); + } + default -> { + throw new AssertionError(); + } + } + + MacSign.withKeychain(_ -> { + spec.mapExpectedMessages(cannedStr -> { + return cannedStr.mapArgs(arg -> { + switch (arg) { + case StandardCertificateNamePrefix certPrefix -> { + return certPrefix.value(); + } + case Token _ -> { + return keychain.name(); + } + default -> { + return arg; + } + } + }); + }).test(Map.of(keychainToken, _ -> keychain.name())); + }, keychain); + } + + public static Collection testMacSignWithoutIdentity() { + final List testCases = new ArrayList<>(); + + final var signArgs = List.of("--mac-sign", "--mac-signing-keychain", Token.EMPTY_KEYCHAIN.token()); + final var appImageArgs = List.of("--app-image", Token.APP_IMAGE_WITH_SHORT_NAME.token()); + + for (var withAppImage : List.of(true, false)) { + var builder = testSpec(); + if (withAppImage) { + builder.noAppDesc().addArgs(appImageArgs); + } + builder.addArgs(signArgs); + + for (var type: List.of(PackageType.IMAGE, PackageType.MAC_PKG, PackageType.MAC_DMG)) { + builder.setMessages().error("error.cert.not.found", + MacSign.StandardCertificateNamePrefix.CODE_SIGN, Token.EMPTY_KEYCHAIN); + switch (type) { + case MAC_PKG -> { + // jpackage must report two errors: + // 1. It can't find signing identity to sign the app image + // 2. It can't find signing identity to sign the PKG installer + builder.error("error.cert.not.found", + MacSign.StandardCertificateNamePrefix.INSTALLER, Token.EMPTY_KEYCHAIN); + } + default -> { + // NOP + } + } + var testSpec = builder.type(type).create(); + testCases.add(testSpec); + } + } + + return toTestArgs(testCases); + } + + public static Collection testMacPkgSignWithoutIdentity() { + final List testCases = new ArrayList<>(); + + final var appImageArgs = List.of("--app-image", Token.APP_IMAGE_WITH_SHORT_NAME.token()); + + for (var withAppImage : List.of(true, false)) { + for (var existingCertType : CertificateType.values()) { + Token keychain; + StandardCertificateNamePrefix missingCertificateNamePrefix; + switch (existingCertType) { + case INSTALLER -> { + keychain = Token.KEYCHAIN_WITH_PKG_CERT; + missingCertificateNamePrefix = StandardCertificateNamePrefix.CODE_SIGN; + } + case CODE_SIGN -> { + keychain = Token.KEYCHAIN_WITH_APP_IMAGE_CERT; + missingCertificateNamePrefix = StandardCertificateNamePrefix.INSTALLER; + } + default -> { + throw new AssertionError(); + } + } + + var builder = testSpec() + .type(PackageType.MAC_PKG) + .addArgs("--mac-sign", "--mac-signing-keychain", keychain.token()) + .error("error.cert.not.found", missingCertificateNamePrefix, keychain); + + if (withAppImage) { + builder.noAppDesc().addArgs(appImageArgs); + } else { + /* + * Use shorter name to avoid + * + * [03:08:55.623] --mac-package-name is set to 'MacSignWithoutIdentityErrorTest', which is longer than 16 characters. For a better Mac experience consider shortening it. + * + * in the output. + * The same idea is behind using the "APP_IMAGE_WITH_SHORT_NAME" token + * instead of the "APP_IMAGE" for the predefined app image. + */ + builder.removeArgs("--name"); + } + + testCases.add(builder); + } + } + + return toTestArgs(testCases); + } + @Test @ParameterSupplier("invalidNames") public static void testInvalidAppName(InvalidName name) { @@ -1007,8 +1224,14 @@ public final class ErrorTest { ); } - private static Collection toTestArgs(Stream stream) { - return stream.filter(v -> { + private static Collection toTestArgs(Stream stream) { + return stream.map(v -> { + if (v instanceof TestSpec.Builder builder) { + return builder.create(); + } else { + return v; + } + }).filter(v -> { if (v instanceof TestSpec ts) { return ts.isSupported(); } else { @@ -1019,8 +1242,8 @@ public final class ErrorTest { }).toList(); } - private static Collection fromTestSpecBuilders(Stream stream) { - return toTestArgs(stream.map(TestSpec.Builder::create)); + private static Collection toTestArgs(Collection col) { + return toTestArgs(col.stream()); } private static String adjustTextStreamVerifierArg(String str) { @@ -1028,4 +1251,40 @@ public final class ErrorTest { } private static final Pattern LINE_SEP_REGEXP = Pattern.compile("\\R"); + + private final class SignEnvMock { + + enum SingleCertificateKeychain { + FOO(CertificateType.CODE_SIGN), + BAR(CertificateType.INSTALLER), + ; + + SingleCertificateKeychain(CertificateType certificateType) { + this.keychain = KeychainWithCertsSpec.build() + .name(name().toLowerCase() + ".keychain") + .addCert(CertificateRequest.build() + .userName(name().toLowerCase()) + .type(Objects.requireNonNull(certificateType))) + .create(); + } + + static List signingEnv() { + return Stream.of(values()).map(v -> { + return v.keychain; + }).toList(); + } + + CertificateType certificateType() { + return keychain.certificateRequests().getFirst().type(); + } + + ResolvedKeychain keychain() { + return new ResolvedKeychain(keychain).toMock(VALUE.env()); + } + + private final KeychainWithCertsSpec keychain; + } + + static final MacSignMockUtils.SignEnv VALUE = new MacSignMockUtils.SignEnv(SingleCertificateKeychain.signingEnv()); + } } From d887e2e6fdcb0070a5f881098120074d972ee3df Mon Sep 17 00:00:00 2001 From: Ben Taylor Date: Fri, 27 Feb 2026 00:37:13 +0000 Subject: [PATCH 33/54] 8377713: Shenandoah: Convert ShenandoahReferenceProcessor to use Atomic Reviewed-by: shade, wkemper --- .../shenandoahReferenceProcessor.cpp | 22 +++++++++---------- .../shenandoahReferenceProcessor.hpp | 5 +++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.cpp b/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.cpp index 7187431c8f8..37e9729b7ff 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.cpp @@ -504,7 +504,7 @@ void ShenandoahReferenceProcessor::process_references(ShenandoahRefProcThreadLoc if (!CompressedOops::is_null(*list)) { oop head = lrb(CompressedOops::decode_not_null(*list)); shenandoah_assert_not_in_cset_except(&head, head, ShenandoahHeap::heap()->cancelled_gc() || !ShenandoahLoadRefBarrier); - oop prev = AtomicAccess::xchg(&_pending_list, head); + oop prev = _pending_list.exchange(head); set_oop_field(p, prev); if (prev == nullptr) { // First to prepend to list, record tail @@ -519,14 +519,14 @@ void ShenandoahReferenceProcessor::process_references(ShenandoahRefProcThreadLoc void ShenandoahReferenceProcessor::work() { // Process discovered references uint max_workers = ShenandoahHeap::heap()->max_workers(); - uint worker_id = AtomicAccess::add(&_iterate_discovered_list_id, 1U, memory_order_relaxed) - 1; + uint worker_id = _iterate_discovered_list_id.fetch_then_add(1U, memory_order_relaxed); while (worker_id < max_workers) { if (UseCompressedOops) { process_references(_ref_proc_thread_locals[worker_id], worker_id); } else { process_references(_ref_proc_thread_locals[worker_id], worker_id); } - worker_id = AtomicAccess::add(&_iterate_discovered_list_id, 1U, memory_order_relaxed) - 1; + worker_id = _iterate_discovered_list_id.fetch_then_add(1U, memory_order_relaxed); } } @@ -559,7 +559,7 @@ public: void ShenandoahReferenceProcessor::process_references(ShenandoahPhaseTimings::Phase phase, WorkerThreads* workers, bool concurrent) { - AtomicAccess::release_store_fence(&_iterate_discovered_list_id, 0U); + _iterate_discovered_list_id.release_store_fence(0U); // Process discovered lists ShenandoahReferenceProcessorTask task(phase, concurrent, this); @@ -576,7 +576,7 @@ void ShenandoahReferenceProcessor::process_references(ShenandoahPhaseTimings::Ph void ShenandoahReferenceProcessor::enqueue_references_locked() { // Prepend internal pending list to external pending list - shenandoah_assert_not_in_cset_except(&_pending_list, _pending_list, ShenandoahHeap::heap()->cancelled_gc() || !ShenandoahLoadRefBarrier); + shenandoah_assert_not_in_cset_except(&_pending_list, _pending_list.load_relaxed(), ShenandoahHeap::heap()->cancelled_gc() || !ShenandoahLoadRefBarrier); // During reference processing, we maintain a local list of references that are identified by // _pending_list and _pending_list_tail. _pending_list_tail points to the next field of the last Reference object on @@ -589,7 +589,7 @@ void ShenandoahReferenceProcessor::enqueue_references_locked() { // 2. Overwriting the next field of the last Reference on my local list to point at the previous head of the // global Universe::_reference_pending_list - oop former_head_of_global_list = Universe::swap_reference_pending_list(_pending_list); + oop former_head_of_global_list = Universe::swap_reference_pending_list(_pending_list.load_relaxed()); if (UseCompressedOops) { set_oop_field(reinterpret_cast(_pending_list_tail), former_head_of_global_list); } else { @@ -598,7 +598,7 @@ void ShenandoahReferenceProcessor::enqueue_references_locked() { } void ShenandoahReferenceProcessor::enqueue_references(bool concurrent) { - if (_pending_list == nullptr) { + if (_pending_list.load_relaxed() == nullptr) { // Nothing to enqueue return; } @@ -616,7 +616,7 @@ void ShenandoahReferenceProcessor::enqueue_references(bool concurrent) { } // Reset internal pending list - _pending_list = nullptr; + _pending_list.store_relaxed(nullptr); _pending_list_tail = &_pending_list; } @@ -640,9 +640,9 @@ void ShenandoahReferenceProcessor::abandon_partial_discovery() { clean_discovered_list(_ref_proc_thread_locals[index].discovered_list_addr()); } } - if (_pending_list != nullptr) { - oop pending = _pending_list; - _pending_list = nullptr; + if (_pending_list.load_relaxed() != nullptr) { + oop pending = _pending_list.load_relaxed(); + _pending_list.store_relaxed(nullptr); if (UseCompressedOops) { narrowOop* list = reference_discovered_addr(pending); clean_discovered_list(list); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.hpp b/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.hpp index 14adb924585..01c79029132 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahReferenceProcessor.hpp @@ -31,6 +31,7 @@ #include "gc/shared/referenceProcessorStats.hpp" #include "gc/shenandoah/shenandoahPhaseTimings.hpp" #include "memory/allocation.hpp" +#include "runtime/atomic.hpp" class ShenandoahMarkRefsSuperClosure; class WorkerThreads; @@ -133,10 +134,10 @@ private: ShenandoahRefProcThreadLocal* _ref_proc_thread_locals; - oop _pending_list; + Atomic _pending_list; void* _pending_list_tail; // T* - volatile uint _iterate_discovered_list_id; + Atomic _iterate_discovered_list_id; ReferenceProcessorStats _stats; From 538bebf76e812058145f7a3f5591cbf1c2f756c7 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Fri, 27 Feb 2026 00:52:18 +0000 Subject: [PATCH 34/54] 8376253: [macOS] FileSystemView may not report system icons when -Xcheck:jni is enabled Reviewed-by: prr, dnguyen --- .../macosx/native/libawt_lwawt/awt/CImage.m | 4 +- .../SystemIconPixelDataTest.java | 93 +++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 test/jdk/javax/swing/JFileChooser/FileSystemView/SystemIconPixelDataTest.java diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/CImage.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/CImage.m index 051588f95bf..fa534fff275 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/CImage.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/CImage.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -270,7 +270,7 @@ JNI_COCOA_ENTER(env); NSRect fromRect = NSMakeRect(0, 0, sw, sh); NSRect toRect = NSMakeRect(0, 0, dw, dh); CImage_CopyNSImageIntoArray(img, dst, fromRect, toRect); - (*env)->ReleasePrimitiveArrayCritical(env, buffer, dst, JNI_ABORT); + (*env)->ReleasePrimitiveArrayCritical(env, buffer, dst, 0); } JNI_COCOA_EXIT(env); diff --git a/test/jdk/javax/swing/JFileChooser/FileSystemView/SystemIconPixelDataTest.java b/test/jdk/javax/swing/JFileChooser/FileSystemView/SystemIconPixelDataTest.java new file mode 100644 index 00000000000..c71c7a3e6a9 --- /dev/null +++ b/test/jdk/javax/swing/JFileChooser/FileSystemView/SystemIconPixelDataTest.java @@ -0,0 +1,93 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * 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.awt.EventQueue; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.swing.Icon; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.filechooser.FileSystemView; + +/** + * @test + * @bug 8376253 + * @summary FileSystemView may not report system icons when -Xcheck:jni enabled + * @key headful + * @run main SystemIconPixelDataTest + * @run main/othervm -Xcheck:jni SystemIconPixelDataTest + */ +public final class SystemIconPixelDataTest { + + public static void main(String[] args) throws Exception { + for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) { + AtomicBoolean ok = new AtomicBoolean(); + EventQueue.invokeAndWait(() -> ok.set(setLookAndFeel(laf))); + if (ok.get()) { + EventQueue.invokeAndWait(SystemIconPixelDataTest::test); + } + } + } + + private static boolean setLookAndFeel(LookAndFeelInfo laf) { + try { + UIManager.setLookAndFeel(laf.getClassName()); + System.out.println("LookAndFeel: " + laf.getClassName()); + return true; + } catch (UnsupportedLookAndFeelException ignored) { + return false; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static void test() { + FileSystemView fsv = FileSystemView.getFileSystemView(); + File home = fsv.getHomeDirectory(); + Icon icon = fsv.getSystemIcon(home); + if (icon == null) { + return; + } + int w = icon.getIconWidth(); + int h = icon.getIconHeight(); + if (w <= 0 || h <= 0) { + throw new RuntimeException("Invalid icon size: " + w + "x" + h); + } + var img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = img.createGraphics(); + icon.paintIcon(null, g, 0, 0); + g.dispose(); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + if (img.getRGB(x, y) != 0) { + return; + } + } + } + throw new RuntimeException("All pixels are zero"); + } +} From 1c6e7ffee4f136d769a050c28ab2aeaa30643eac Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Fri, 27 Feb 2026 01:56:03 +0000 Subject: [PATCH 35/54] 8377845: Restore regtest for JDK-8324881 with DiagnoseSyncOnValueBasedClasses=2 Reviewed-by: sspitsyn, lmesnik --- test/jdk/com/sun/jdi/EATests.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/jdk/com/sun/jdi/EATests.java b/test/jdk/com/sun/jdi/EATests.java index cb51e91021b..3a936f288cc 100644 --- a/test/jdk/com/sun/jdi/EATests.java +++ b/test/jdk/com/sun/jdi/EATests.java @@ -84,6 +84,15 @@ * @comment Regression test for using the wrong thread when logging during re-locking from deoptimization. * * @comment DiagnoseSyncOnValueBasedClasses=2 will cause logging when locking on \@ValueBased objects. + * @run driver EATests + * -XX:+UnlockDiagnosticVMOptions + * -Xms256m -Xmx256m + * -Xbootclasspath/a:. + * -XX:CompileCommand=dontinline,*::dontinline_* + * -XX:+WhiteBoxAPI + * -Xbatch + * -XX:+DoEscapeAnalysis -XX:+EliminateAllocations -XX:+EliminateLocks -XX:+EliminateNestedLocks + * -XX:DiagnoseSyncOnValueBasedClasses=2 * * @comment Re-lock may inflate monitors when re-locking, which cause monitorinflation trace logging. * @run driver EATests From d7f4365b296d120521e16666e2ce2177a8d2c44d Mon Sep 17 00:00:00 2001 From: SendaoYan Date: Fri, 27 Feb 2026 02:33:54 +0000 Subject: [PATCH 36/54] 8378561: Mark gc/shenandoah/compiler/TestLinkToNativeRBP.java as /native Reviewed-by: shade, wkemper --- .../jtreg/gc/shenandoah/compiler/TestLinkToNativeRBP.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/gc/shenandoah/compiler/TestLinkToNativeRBP.java b/test/hotspot/jtreg/gc/shenandoah/compiler/TestLinkToNativeRBP.java index 96440ba15ae..2877e8a4a85 100644 --- a/test/hotspot/jtreg/gc/shenandoah/compiler/TestLinkToNativeRBP.java +++ b/test/hotspot/jtreg/gc/shenandoah/compiler/TestLinkToNativeRBP.java @@ -30,7 +30,7 @@ * @requires ((os.arch == "amd64" | os.arch == "x86_64") & sun.arch.data.model == "64") | os.arch == "aarch64" | os.arch == "ppc64" | os.arch == "ppc64le" * @requires vm.gc.Shenandoah * - * @run main/othervm --enable-native-access=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions + * @run main/native/othervm --enable-native-access=ALL-UNNAMED -XX:+UnlockDiagnosticVMOptions * -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=aggressive TestLinkToNativeRBP * */ From 6daca7ef99b5333be9dd074ff848783807080884 Mon Sep 17 00:00:00 2001 From: Renjith Kannath Pariyangad Date: Fri, 27 Feb 2026 03:15:27 +0000 Subject: [PATCH 37/54] 8268675: RTE from "Printable.print" propagates through "PrinterJob.print" Reviewed-by: psadhukhan, prr --- .../classes/sun/print/RasterPrinterJob.java | 7 ++++- .../ExceptionFromPrintableIsIgnoredTest.java | 29 +++++++------------ 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java index 754af87b94e..32728efde6c 100644 --- a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java +++ b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -1610,6 +1610,11 @@ public abstract class RasterPrinterJob extends PrinterJob { cancelDoc(); } + } catch (PrinterException pe) { + throw pe; + } catch (Throwable printError) { + throw (PrinterException) + new PrinterException().initCause(printError.getCause()); } finally { // reset previousPaper in case this job is invoked again. previousPaper = null; diff --git a/test/jdk/java/awt/print/PrinterJob/ExceptionFromPrintableIsIgnoredTest.java b/test/jdk/java/awt/print/PrinterJob/ExceptionFromPrintableIsIgnoredTest.java index a62ae536e1b..4c2ff370cb8 100644 --- a/test/jdk/java/awt/print/PrinterJob/ExceptionFromPrintableIsIgnoredTest.java +++ b/test/jdk/java/awt/print/PrinterJob/ExceptionFromPrintableIsIgnoredTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 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 @@ -21,15 +21,16 @@ * questions. */ -/* @test - @bug 8262731 - @key headful printer - @summary Verify that "PrinterJob.print" throws the expected exception, - if "Printable.print" throws an exception. - @run main ExceptionFromPrintableIsIgnoredTest MAIN PE - @run main ExceptionFromPrintableIsIgnoredTest MAIN RE - @run main ExceptionFromPrintableIsIgnoredTest EDT PE - @run main ExceptionFromPrintableIsIgnoredTest EDT RE +/* + * @test + * @bug 8262731 8268675 + * @key printer + * @summary Verify that "PrinterJob.print" throws the expected exception, + * if "Printable.print" throws an exception. + * @run main ExceptionFromPrintableIsIgnoredTest MAIN PE + * @run main ExceptionFromPrintableIsIgnoredTest MAIN RE + * @run main ExceptionFromPrintableIsIgnoredTest EDT PE + * @run main ExceptionFromPrintableIsIgnoredTest EDT RE */ import java.awt.Graphics; @@ -64,14 +65,6 @@ public class ExceptionFromPrintableIsIgnoredTest { "Test started. threadType='%s', exceptionType='%s'", threadType, exceptionType)); - String osName = System.getProperty("os.name"); - boolean isOSX = osName.toLowerCase().startsWith("mac"); - if ((exceptionType == TestExceptionType.RE) && !isOSX) { - System.out.println( - "Currently this test scenario can be verified only on macOS."); - return; - } - printError = null; if (threadType == TestThreadType.MAIN) { From dc06fede2af2f10011695b0539b6f4d2cb1f07df Mon Sep 17 00:00:00 2001 From: Serguei Spitsyn Date: Fri, 27 Feb 2026 04:47:48 +0000 Subject: [PATCH 38/54] 8373367: interp-only mechanism fails to work for carrier threads in a corner case Reviewed-by: amenkov, lmesnik --- src/hotspot/share/prims/jvmtiEnvBase.cpp | 4 +-- .../share/prims/jvmtiEnvThreadState.cpp | 9 ++---- .../share/prims/jvmtiEnvThreadState.hpp | 4 +-- .../share/prims/jvmtiEventController.cpp | 31 +++++++++++++------ src/hotspot/share/prims/jvmtiThreadState.cpp | 29 ++++++++--------- src/hotspot/share/prims/jvmtiThreadState.hpp | 15 ++++++--- .../share/prims/jvmtiThreadState.inline.hpp | 21 ++++++------- 7 files changed, 61 insertions(+), 52 deletions(-) diff --git a/src/hotspot/share/prims/jvmtiEnvBase.cpp b/src/hotspot/share/prims/jvmtiEnvBase.cpp index 4894a4dd21a..401bb4dfdb8 100644 --- a/src/hotspot/share/prims/jvmtiEnvBase.cpp +++ b/src/hotspot/share/prims/jvmtiEnvBase.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -2491,7 +2491,7 @@ SetOrClearFramePopClosure::do_thread(Thread *target) { _result = JVMTI_ERROR_NO_MORE_FRAMES; return; } - assert(_state->get_thread_or_saved() == java_thread, "Must be"); + assert(_state->get_thread() == java_thread, "Must be"); RegisterMap reg_map(java_thread, RegisterMap::UpdateMap::include, diff --git a/src/hotspot/share/prims/jvmtiEnvThreadState.cpp b/src/hotspot/share/prims/jvmtiEnvThreadState.cpp index 571c4ca5528..303923076b1 100644 --- a/src/hotspot/share/prims/jvmtiEnvThreadState.cpp +++ b/src/hotspot/share/prims/jvmtiEnvThreadState.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -151,11 +151,6 @@ bool JvmtiEnvThreadState::is_virtual() { return _state->is_virtual(); } -// Use _thread_saved if cthread is detached from JavaThread (_thread == nullptr). -JavaThread* JvmtiEnvThreadState::get_thread_or_saved() { - return _state->get_thread_or_saved(); -} - JavaThread* JvmtiEnvThreadState::get_thread() { return _state->get_thread(); } @@ -344,7 +339,7 @@ void JvmtiEnvThreadState::reset_current_location(jvmtiEvent event_type, bool ena if (enabled) { // If enabling breakpoint, no need to reset. // Can't do anything if empty stack. - JavaThread* thread = get_thread_or_saved(); + JavaThread* thread = get_thread(); if (event_type == JVMTI_EVENT_SINGLE_STEP && ((thread == nullptr && is_virtual()) || thread->has_last_Java_frame())) { diff --git a/src/hotspot/share/prims/jvmtiEnvThreadState.hpp b/src/hotspot/share/prims/jvmtiEnvThreadState.hpp index a2ab25a59dd..16b369e0857 100644 --- a/src/hotspot/share/prims/jvmtiEnvThreadState.hpp +++ b/src/hotspot/share/prims/jvmtiEnvThreadState.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -170,8 +170,6 @@ public: inline JvmtiThreadState* jvmti_thread_state() { return _state; } - // use _thread_saved if cthread is detached from JavaThread - JavaThread *get_thread_or_saved(); JavaThread *get_thread(); inline JvmtiEnv *get_env() { return _env; } diff --git a/src/hotspot/share/prims/jvmtiEventController.cpp b/src/hotspot/share/prims/jvmtiEventController.cpp index 9df3bbb4b3e..cb44b833c48 100644 --- a/src/hotspot/share/prims/jvmtiEventController.cpp +++ b/src/hotspot/share/prims/jvmtiEventController.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -217,6 +217,10 @@ class EnterInterpOnlyModeClosure : public HandshakeClosure { assert(state != nullptr, "sanity check"); assert(state->get_thread() == jt, "handshake unsafe conditions"); + assert(jt->jvmti_thread_state() == state, "sanity check"); + assert(!jt->is_interp_only_mode(), "sanity check"); + assert(!state->is_interp_only_mode(), "sanity check"); + if (!state->is_pending_interp_only_mode()) { _completed = true; return; // The pending flag has been already cleared, so bail out. @@ -361,7 +365,8 @@ void VM_ChangeSingleStep::doit() { void JvmtiEventControllerPrivate::enter_interp_only_mode(JvmtiThreadState *state) { EC_TRACE(("[%s] # Entering interpreter only mode", - JvmtiTrace::safe_get_thread_name(state->get_thread_or_saved()))); + JvmtiTrace::safe_get_thread_name(state->get_thread()))); + JavaThread *target = state->get_thread(); Thread *current = Thread::current(); @@ -371,8 +376,13 @@ void JvmtiEventControllerPrivate::enter_interp_only_mode(JvmtiThreadState *state } // This flag will be cleared in EnterInterpOnlyModeClosure handshake. state->set_pending_interp_only_mode(true); - if (target == nullptr) { // an unmounted virtual thread - return; // EnterInterpOnlyModeClosure will be executed right after mount. + + // There are two cases when entering interp_only_mode is postponed: + // 1. Unmounted virtual thread - EnterInterpOnlyModeClosure::do_thread will be executed at mount; + // 2. Carrier thread with mounted virtual thread - EnterInterpOnlyModeClosure::do_thread will be executed at unmount. + if (target == nullptr || // an unmounted virtual thread + JvmtiEnvBase::is_thread_carrying_vthread(target, state->get_thread_oop())) { // a vthread carrying thread + return; // EnterInterpOnlyModeClosure will be executed right after mount or unmount. } EnterInterpOnlyModeClosure hs(state); if (target->is_handshake_safe_for(current)) { @@ -388,7 +398,8 @@ void JvmtiEventControllerPrivate::enter_interp_only_mode(JvmtiThreadState *state void JvmtiEventControllerPrivate::leave_interp_only_mode(JvmtiThreadState *state) { EC_TRACE(("[%s] # Leaving interpreter only mode", - JvmtiTrace::safe_get_thread_name(state->get_thread_or_saved()))); + JvmtiTrace::safe_get_thread_name(state->get_thread()))); + if (state->is_pending_interp_only_mode()) { state->set_pending_interp_only_mode(false); // Just clear the pending flag. assert(!state->is_interp_only_mode(), "sanity check"); @@ -409,7 +420,7 @@ JvmtiEventControllerPrivate::trace_changed(JvmtiThreadState *state, jlong now_en if (changed & bit) { // it changed, print it log_trace(jvmti)("[%s] # %s event %s", - JvmtiTrace::safe_get_thread_name(state->get_thread_or_saved()), + JvmtiTrace::safe_get_thread_name(state->get_thread()), (now_enabled & bit)? "Enabling" : "Disabling", JvmtiTrace::event_name((jvmtiEvent)ei)); } } @@ -932,7 +943,7 @@ JvmtiEventControllerPrivate::set_user_enabled(JvmtiEnvBase *env, JavaThread *thr void JvmtiEventControllerPrivate::set_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) { EC_TRACE(("[%s] # set frame pop - frame=%d", - JvmtiTrace::safe_get_thread_name(ets->get_thread_or_saved()), + JvmtiTrace::safe_get_thread_name(ets->get_thread()), fpop.frame_number() )); ets->get_frame_pops()->set(fpop); @@ -943,7 +954,7 @@ JvmtiEventControllerPrivate::set_frame_pop(JvmtiEnvThreadState *ets, JvmtiFrameP void JvmtiEventControllerPrivate::clear_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) { EC_TRACE(("[%s] # clear frame pop - frame=%d", - JvmtiTrace::safe_get_thread_name(ets->get_thread_or_saved()), + JvmtiTrace::safe_get_thread_name(ets->get_thread()), fpop.frame_number() )); ets->get_frame_pops()->clear(fpop); @@ -953,7 +964,7 @@ JvmtiEventControllerPrivate::clear_frame_pop(JvmtiEnvThreadState *ets, JvmtiFram void JvmtiEventControllerPrivate::clear_all_frame_pops(JvmtiEnvThreadState *ets) { EC_TRACE(("[%s] # clear all frame pops", - JvmtiTrace::safe_get_thread_name(ets->get_thread_or_saved()) + JvmtiTrace::safe_get_thread_name(ets->get_thread()) )); ets->get_frame_pops()->clear_all(); @@ -965,7 +976,7 @@ JvmtiEventControllerPrivate::clear_to_frame_pop(JvmtiEnvThreadState *ets, JvmtiF int cleared_cnt = ets->get_frame_pops()->clear_to(fpop); EC_TRACE(("[%s] # clear to frame pop - frame=%d, count=%d", - JvmtiTrace::safe_get_thread_name(ets->get_thread_or_saved()), + JvmtiTrace::safe_get_thread_name(ets->get_thread()), fpop.frame_number(), cleared_cnt )); diff --git a/src/hotspot/share/prims/jvmtiThreadState.cpp b/src/hotspot/share/prims/jvmtiThreadState.cpp index d7accfd9a0a..32bf2c4e98e 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.cpp +++ b/src/hotspot/share/prims/jvmtiThreadState.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -57,7 +57,6 @@ JvmtiThreadState::JvmtiThreadState(JavaThread* thread, oop thread_oop) : _thread_event_enable() { assert(JvmtiThreadState_lock->is_locked(), "sanity check"); _thread = thread; - _thread_saved = nullptr; _exception_state = ES_CLEARED; _hide_single_stepping = false; _pending_interp_only_mode = false; @@ -118,11 +117,11 @@ JvmtiThreadState::JvmtiThreadState(JavaThread* thread, oop thread_oop) if (thread != nullptr) { if (thread_oop == nullptr || thread->jvmti_vthread() == nullptr || thread->jvmti_vthread() == thread_oop) { - // The JavaThread for carrier or mounted virtual thread case. + // The JavaThread for an active carrier or a mounted virtual thread case. // Set this only if thread_oop is current thread->jvmti_vthread(). thread->set_jvmti_thread_state(this); + assert(!thread->is_interp_only_mode(), "sanity check"); } - thread->set_interp_only_mode(false); } } @@ -135,7 +134,10 @@ JvmtiThreadState::~JvmtiThreadState() { } // clear this as the state for the thread + assert(get_thread() != nullptr, "sanity check"); + assert(get_thread()->jvmti_thread_state() == this, "sanity check"); get_thread()->set_jvmti_thread_state(nullptr); + get_thread()->set_interp_only_mode(false); // zap our env thread states { @@ -323,6 +325,9 @@ void JvmtiThreadState::enter_interp_only_mode() { assert(_thread != nullptr, "sanity check"); assert(JvmtiThreadState_lock->is_locked(), "sanity check"); assert(!is_interp_only_mode(), "entering interp only when in interp only mode"); + assert(_thread->jvmti_vthread() == nullptr || _thread->jvmti_vthread() == get_thread_oop(), "sanity check"); + assert(_thread->jvmti_thread_state() == this, "sanity check"); + _saved_interp_only_mode = true; _thread->set_interp_only_mode(true); invalidate_cur_stack_depth(); } @@ -330,10 +335,9 @@ void JvmtiThreadState::enter_interp_only_mode() { void JvmtiThreadState::leave_interp_only_mode() { assert(JvmtiThreadState_lock->is_locked(), "sanity check"); assert(is_interp_only_mode(), "leaving interp only when not in interp only mode"); - if (_thread == nullptr) { - // Unmounted virtual thread updates the saved value. - _saved_interp_only_mode = false; - } else { + _saved_interp_only_mode = false; + if (_thread != nullptr && _thread->jvmti_thread_state() == this) { + assert(_thread->jvmti_vthread() == nullptr || _thread->jvmti_vthread() == get_thread_oop(), "sanity check"); _thread->set_interp_only_mode(false); } } @@ -341,7 +345,7 @@ void JvmtiThreadState::leave_interp_only_mode() { // Helper routine used in several places int JvmtiThreadState::count_frames() { - JavaThread* thread = get_thread_or_saved(); + JavaThread* thread = get_thread(); javaVFrame *jvf; ResourceMark rm; if (thread == nullptr) { @@ -578,11 +582,8 @@ void JvmtiThreadState::update_thread_oop_during_vm_start() { } } +// For virtual threads only. void JvmtiThreadState::set_thread(JavaThread* thread) { - _thread_saved = nullptr; // Common case. - if (!_is_virtual && thread == nullptr) { - // Save JavaThread* if carrier thread is being detached. - _thread_saved = _thread; - } + assert(is_virtual(), "sanity check"); _thread = thread; } diff --git a/src/hotspot/share/prims/jvmtiThreadState.hpp b/src/hotspot/share/prims/jvmtiThreadState.hpp index 866d8828c4c..fa77518a8b6 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.hpp +++ b/src/hotspot/share/prims/jvmtiThreadState.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -123,8 +123,11 @@ class JvmtiVTSuspender : AllStatic { class JvmtiThreadState : public CHeapObj { private: friend class JvmtiEnv; + // The _thread field is a link to the JavaThread associated with JvmtiThreadState. + // A platform (including carrier) thread should always have a stable link to its JavaThread. + // The _thread field of a virtual thread should point to the JavaThread when + // virtual thread is mounted. It should be set to null when it is unmounted. JavaThread *_thread; - JavaThread *_thread_saved; OopHandle _thread_oop_h; // Jvmti Events that cannot be posted in their current context. JvmtiDeferredEventQueue* _jvmti_event_queue; @@ -219,7 +222,7 @@ class JvmtiThreadState : public CHeapObj { // Used by the interpreter for fullspeed debugging support bool is_interp_only_mode() { - return _thread == nullptr ? _saved_interp_only_mode : _thread->is_interp_only_mode(); + return _saved_interp_only_mode; } void enter_interp_only_mode(); void leave_interp_only_mode(); @@ -248,8 +251,10 @@ class JvmtiThreadState : public CHeapObj { int count_frames(); - inline JavaThread *get_thread() { return _thread; } - inline JavaThread *get_thread_or_saved(); // return _thread_saved if _thread is null + inline JavaThread *get_thread() { + assert(is_virtual() || _thread != nullptr, "sanity check"); + return _thread; + } // Needed for virtual threads as they can migrate to different JavaThread's. // Also used for carrier threads to clear/restore _thread. diff --git a/src/hotspot/share/prims/jvmtiThreadState.inline.hpp b/src/hotspot/share/prims/jvmtiThreadState.inline.hpp index 831a2369a7e..aa81463a696 100644 --- a/src/hotspot/share/prims/jvmtiThreadState.inline.hpp +++ b/src/hotspot/share/prims/jvmtiThreadState.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -130,22 +130,21 @@ inline JvmtiThreadState* JvmtiThreadState::state_for(JavaThread *thread, Handle return state; } -inline JavaThread* JvmtiThreadState::get_thread_or_saved() { - // Use _thread_saved if cthread is detached from JavaThread (_thread == null). - return (_thread == nullptr && !is_virtual()) ? _thread_saved : _thread; -} - inline void JvmtiThreadState::set_should_post_on_exceptions(bool val) { - get_thread_or_saved()->set_should_post_on_exceptions_flag(val ? JNI_TRUE : JNI_FALSE); + get_thread()->set_should_post_on_exceptions_flag(val ? JNI_TRUE : JNI_FALSE); } inline void JvmtiThreadState::unbind_from(JvmtiThreadState* state, JavaThread* thread) { if (state == nullptr) { + assert(!thread->is_interp_only_mode(), "sanity check"); return; } - // Save thread's interp_only_mode. - state->_saved_interp_only_mode = thread->is_interp_only_mode(); - state->set_thread(nullptr); // Make sure stale _thread value is never used. + assert(thread->jvmti_thread_state() == state, "sanity check"); + assert(state->get_thread() == thread, "sanity check"); + assert(thread->is_interp_only_mode() == state->_saved_interp_only_mode, "sanity check"); + if (state->is_virtual()) { // clean _thread link for virtual threads only + state->set_thread(nullptr); // make sure stale _thread value is never used + } } inline void JvmtiThreadState::bind_to(JvmtiThreadState* state, JavaThread* thread) { @@ -158,7 +157,7 @@ inline void JvmtiThreadState::bind_to(JvmtiThreadState* state, JavaThread* threa // Bind JavaThread to JvmtiThreadState. thread->set_jvmti_thread_state(state); - if (state != nullptr) { + if (state != nullptr && state->is_virtual()) { // Bind to JavaThread. state->set_thread(thread); } From 463b9e00ce9e348164d8a6eebe27808bb1e93162 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Fri, 27 Feb 2026 06:06:29 +0000 Subject: [PATCH 39/54] 8078744: Right half of system menu icon on title bar does not activate when clicked in Metal L&F Reviewed-by: tr, dnguyen --- .../swing/plaf/metal/MetalTitlePane.java | 3 +- .../swing/plaf/metal/MetalTitlePaneBug.java | 65 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 test/jdk/javax/swing/plaf/metal/MetalTitlePaneBug.java diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTitlePane.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTitlePane.java index ae8b379a579..4ed6734df1f 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTitlePane.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTitlePane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -437,6 +437,7 @@ class MetalTitlePane extends JComponent { */ private JMenu createMenu() { JMenu menu = new JMenu(""); + menu.setPreferredSize(new Dimension(IMAGE_WIDTH, IMAGE_HEIGHT)); if (getWindowDecorationStyle() == JRootPane.FRAME) { addMenuItems(menu); } diff --git a/test/jdk/javax/swing/plaf/metal/MetalTitlePaneBug.java b/test/jdk/javax/swing/plaf/metal/MetalTitlePaneBug.java new file mode 100644 index 00000000000..dde6249752d --- /dev/null +++ b/test/jdk/javax/swing/plaf/metal/MetalTitlePaneBug.java @@ -0,0 +1,65 @@ +/* + * 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 8078744 + * @summary Verifies right half of system menu icon on title bar + * activates when clicked + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MetalTitlePaneBug + */ + +import javax.swing.JFrame; +import javax.swing.UIManager; + +public class MetalTitlePaneBug { + + static final String INSTRUCTIONS = """ + A Frame is shown with a titlepane. + Click on the left edge of the system menu icon on the title pane. + It should show "Restore", "Minimize", "Maximize", "Close" menu. + Click on the right edge of the system menu icon. + It should also show "Restore", "Minimize", "Maximize", "Close" menu. + If it shows, press Pass else press Fail. + """; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(MetalTitlePaneBug::createUI) + .build() + .awaitAndCheck(); + } + + static JFrame createUI() { + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(200, 100); + return frame; + } +} From f6c69cadc7c622028fb02cef1b419f54ac05c85e Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Fri, 27 Feb 2026 06:44:51 +0000 Subject: [PATCH 40/54] 8378379: Remove reference to obsolete jdk.net.usePlainSocketImpl property from SSLSocketReset test Reviewed-by: coffeys --- .../sun/security/ssl/SSLSocketImpl/SSLSocketReset.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketReset.java b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketReset.java index 6b0f365edc7..64779facd26 100644 --- a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketReset.java +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketReset.java @@ -21,16 +21,14 @@ * questions. */ -// -// Please run in othervm mode. SunJSSE does not support dynamic system -// properties, no way to re-use system properties in samevm/agentvm mode. -// - /* * @test * @bug 8268965 * @summary Socket reset issue for TLS socket close - * @run main/othervm -Djdk.net.usePlainSocketImpl=true SSLSocketReset + * @comment The test uses SSLContext.getDefault(), so we use othervm to prevent + * usage of unexpected default SSLContext that might be set by some + * other test + * @run main/othervm SSLSocketReset */ import javax.net.ssl.*; From 94a34a32aa723e4620f4ef4700b3e20d6ab9bf62 Mon Sep 17 00:00:00 2001 From: Leo Korinth Date: Fri, 27 Feb 2026 09:51:40 +0000 Subject: [PATCH 41/54] 8377895: Create sizeof_auto to reduce narrowing conversions Reviewed-by: kbarrett, jsjolen, dlong, aboldtch, stefank, ayang --- src/hotspot/share/oops/cpCache.hpp | 2 +- .../share/utilities/globalDefinitions.hpp | 23 ++++++++++++ .../utilities/test_globalDefinitions.cpp | 35 +++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/hotspot/share/oops/cpCache.hpp b/src/hotspot/share/oops/cpCache.hpp index e9e4f9a40e5..14202f226d1 100644 --- a/src/hotspot/share/oops/cpCache.hpp +++ b/src/hotspot/share/oops/cpCache.hpp @@ -196,7 +196,7 @@ class ConstantPoolCache: public MetaspaceObj { #endif public: - static int size() { return align_metadata_size(sizeof(ConstantPoolCache) / wordSize); } + static int size() { return align_metadata_size(sizeof_auto(ConstantPoolCache) / wordSize); } private: // Helpers diff --git a/src/hotspot/share/utilities/globalDefinitions.hpp b/src/hotspot/share/utilities/globalDefinitions.hpp index ea4f6f99ae6..9560d863a2c 100644 --- a/src/hotspot/share/utilities/globalDefinitions.hpp +++ b/src/hotspot/share/utilities/globalDefinitions.hpp @@ -168,6 +168,29 @@ class oopDesc; #define SIZE_FORMAT_X_0 "0x%08" PRIxPTR #endif // _LP64 + +template +constexpr auto sizeof_auto_impl() { + if constexpr (N <= std::numeric_limits::max()) return uint8_t(N); + else if constexpr (N <= std::numeric_limits::max()) return uint16_t(N); + else if constexpr (N <= std::numeric_limits::max()) return uint32_t(N); + else return uint64_t(N); +} + +// Yields the size (in bytes) of the operand, using the smallest +// unsigned type that can represent the size value. The operand may be +// an expression, which is an unevaluated operand, or it may be a +// type. All of the restrictions for sizeof operands apply to the +// operand. The result is a constant expression. +// +// Example of correct usage of sizeof/sizeof_auto: +// // this will wrap using sizeof_auto, use sizeof to ensure computation using size_t +// size_t size = std::numeric_limits::max() * sizeof(uint16_t); +// // implicit narrowing conversion or compiler warning/error using stricter compiler flags when using sizeof +// int count = 42 / sizeof_auto(uint16_t); + +#define sizeof_auto(...) sizeof_auto_impl() + // Convert pointer to intptr_t, for use in printing pointers. inline intptr_t p2i(const volatile void* p) { return (intptr_t) p; diff --git a/test/hotspot/gtest/utilities/test_globalDefinitions.cpp b/test/hotspot/gtest/utilities/test_globalDefinitions.cpp index f24d74ea529..6636efbba8e 100644 --- a/test/hotspot/gtest/utilities/test_globalDefinitions.cpp +++ b/test/hotspot/gtest/utilities/test_globalDefinitions.cpp @@ -321,3 +321,38 @@ TEST(globalDefinitions, jlong_from) { val = jlong_from(0xABCD, 0xEFEF); EXPECT_EQ(val, CONST64(0x0000ABCD0000EFEF)); } + +struct NoCopy { + int x; + NONCOPYABLE(NoCopy); +}; + +TEST(globalDefinitions, sizeof_auto) { + char x = 5; + char& y = x; + char* z = &x; + EXPECT_EQ(sizeof_auto(x), sizeof(x)); + EXPECT_EQ(sizeof_auto(y), sizeof(y)); + EXPECT_EQ(sizeof_auto(z), sizeof(z)); + + NoCopy nc{0}; + sizeof_auto(nc); + + static_assert(sizeof_auto(char[1LL]) == 1); + static_assert(sizeof_auto(char[std::numeric_limits::max() + 1LL]) == std::numeric_limits::max() + 1LL); + static_assert(sizeof_auto(char[std::numeric_limits::max() + 1LL]) == std::numeric_limits::max() + 1LL); +#if defined(_LP64) && !defined(_WINDOWS) + // char array sometimes limited to 2 gig length on 32 bit platforms (signed), disabled for Windows because of compiler error C2148. + static_assert(sizeof_auto(char[std::numeric_limits::max() + 1LL]) == std::numeric_limits::max() + 1LL); +#endif + + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max()])) == sizeof(uint8_t)); + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max() + 1LL])) == sizeof(uint16_t)); + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max()])) == sizeof(uint16_t)); + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max() + 1LL])) == sizeof(uint32_t)); +#if defined(_LP64) && !defined(_WINDOWS) + // char array sometimes limited to 2 gig length on 32 bit platforms (signed), disabled for Windows because of compiler error C2148. + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max()])) == sizeof(uint32_t)); + static_assert(sizeof(sizeof_auto(char[std::numeric_limits::max() + 1LL])) == sizeof(uint64_t)); +#endif +} From 4e15a4adfc50e37e2be01e90a67fde4b12126abd Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Fri, 27 Feb 2026 11:36:54 +0000 Subject: [PATCH 42/54] 8378823: AIX build fails after zlib updated by JDK-8378631 Reviewed-by: mdoerr, jpai, stuefe --- make/autoconf/lib-bundled.m4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/autoconf/lib-bundled.m4 b/make/autoconf/lib-bundled.m4 index bc358928af0..7aa5fdf2589 100644 --- a/make/autoconf/lib-bundled.m4 +++ b/make/autoconf/lib-bundled.m4 @@ -267,7 +267,7 @@ AC_DEFUN_ONCE([LIB_SETUP_ZLIB], LIBZ_LIBS="" if test "x$USE_EXTERNAL_LIBZ" = "xfalse"; then LIBZ_CFLAGS="$LIBZ_CFLAGS -I$TOPDIR/src/java.base/share/native/libzip/zlib" - if test "x$OPENJDK_TARGET_OS" = xmacosx; then + if test "x$OPENJDK_TARGET_OS" = xmacosx -o "x$OPENJDK_TARGET_OS" = xaix -o "x$OPENJDK_TARGET_OS" = xlinux; then LIBZ_CFLAGS="$LIBZ_CFLAGS -DHAVE_UNISTD_H=1 -DHAVE_STDARG_H=1" fi else From 5606036793a8819da463bfd12446372276b4effa Mon Sep 17 00:00:00 2001 From: Christoph Langer Date: Fri, 27 Feb 2026 12:35:28 +0000 Subject: [PATCH 43/54] 8378563: ConnectionRefusedMessage::testFinishConnect fails when jdk.includeInExceptions contains hostInfo Reviewed-by: mdoerr, mbaesken, dfuchs --- .../ConnectionRefusedMessage.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) rename test/jdk/java/nio/channels/{Selector => SocketChannel}/ConnectionRefusedMessage.java (92%) diff --git a/test/jdk/java/nio/channels/Selector/ConnectionRefusedMessage.java b/test/jdk/java/nio/channels/SocketChannel/ConnectionRefusedMessage.java similarity index 92% rename from test/jdk/java/nio/channels/Selector/ConnectionRefusedMessage.java rename to test/jdk/java/nio/channels/SocketChannel/ConnectionRefusedMessage.java index 04490f63efe..d71bc6569cb 100644 --- a/test/jdk/java/nio/channels/Selector/ConnectionRefusedMessage.java +++ b/test/jdk/java/nio/channels/SocketChannel/ConnectionRefusedMessage.java @@ -42,7 +42,8 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; * @summary Verify that when a SocketChannel is registered with a Selector * with an interest in CONNECT operation, then SocketChannel.finishConnect() * throws the correct exception message, if the connect() fails - * @run junit ${test.main.class} + * @run junit/othervm -Djdk.includeInExceptions=hostInfoExclSocket ${test.main.class} + * @run junit/othervm -Djdk.includeInExceptions=hostInfo -Dcheck.relaxed=true ${test.main.class} */ class ConnectionRefusedMessage { @@ -108,10 +109,14 @@ class ConnectionRefusedMessage { } private static void assertExceptionMessage(final ConnectException ce) { - if (!"Connection refused".equals(ce.getMessage())) { - // propagate the original exception - fail("unexpected exception message: " + ce.getMessage(), ce); + if ("Connection refused".equals(ce.getMessage())) { + return; } + if (Boolean.getBoolean("check.relaxed") && ce.getMessage() != null && ce.getMessage().startsWith("Connection refused")) { + return; + } + // propagate the original exception + fail("unexpected exception message: " + ce.getMessage(), ce); } // Try to find a suitable port to provoke a "Connection Refused" error. From 1fb608e1bcbbc3fd68205ea168f10584cc5c2a62 Mon Sep 17 00:00:00 2001 From: Chen Liang Date: Fri, 27 Feb 2026 17:52:24 +0000 Subject: [PATCH 44/54] 8378792: ObjectMethods.bootstrap missing getter validation Reviewed-by: rriggs, jvernee --- .../java/lang/runtime/ObjectMethods.java | 23 +++--- .../java/lang/runtime/ObjectMethodsTest.java | 71 ++++++++++++++----- 2 files changed, 68 insertions(+), 26 deletions(-) diff --git a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java index 18aa6f29f1f..e4b2886404f 100644 --- a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java +++ b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 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 @@ -363,9 +363,9 @@ public final class ObjectMethods { * @return the method handle */ private static MethodHandle makeToString(MethodHandles.Lookup lookup, - Class receiverClass, - MethodHandle[] getters, - List names) { + Class receiverClass, + MethodHandle[] getters, + List names) { assert getters.length == names.size(); if (getters.length == 0) { // special case @@ -516,8 +516,8 @@ public final class ObjectMethods { requireNonNull(type); requireNonNull(recordClass); requireNonNull(names); - requireNonNull(getters); - Arrays.stream(getters).forEach(Objects::requireNonNull); + List getterList = List.of(getters); // deep null check + MethodType methodType; if (type instanceof MethodType mt) methodType = mt; @@ -526,7 +526,14 @@ public final class ObjectMethods { if (!MethodHandle.class.equals(type)) throw new IllegalArgumentException(type.toString()); } - List getterList = List.of(getters); + + for (MethodHandle getter : getterList) { + var getterType = getter.type(); + if (getterType.parameterCount() != 1 || getterType.returnType() == void.class || getterType.parameterType(0) != recordClass) { + throw new IllegalArgumentException("Illegal getter type %s for recordClass %s".formatted(getterType, recordClass.getTypeName())); + } + } + MethodHandle handle = switch (methodName) { case "equals" -> { if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class))) @@ -541,7 +548,7 @@ public final class ObjectMethods { case "toString" -> { if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass))) throw new IllegalArgumentException("Bad method type: " + methodType); - List nameList = "".equals(names) ? List.of() : List.of(names.split(";")); + List nameList = names.isEmpty() ? List.of() : List.of(names.split(";")); if (nameList.size() != getterList.size()) throw new IllegalArgumentException("Name list and accessor list do not match"); yield makeToString(lookup, recordClass, getters, nameList); diff --git a/test/jdk/java/lang/runtime/ObjectMethodsTest.java b/test/jdk/java/lang/runtime/ObjectMethodsTest.java index 951d3b68383..d7ca5912273 100644 --- a/test/jdk/java/lang/runtime/ObjectMethodsTest.java +++ b/test/jdk/java/lang/runtime/ObjectMethodsTest.java @@ -36,11 +36,11 @@ import java.lang.invoke.MethodType; import java.lang.runtime.ObjectMethods; import static java.lang.invoke.MethodType.methodType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.*; public class ObjectMethodsTest { @@ -144,8 +144,8 @@ public class ObjectMethodsTest { assertEquals("Empty[]", (String)handle.invokeExact(new Empty())); } - Class NPE = NullPointerException.class; - Class IAE = IllegalArgumentException.class; + private static final Class NPE = NullPointerException.class; + private static final Class IAE = IllegalArgumentException.class; @Test public void exceptions() { @@ -157,25 +157,60 @@ public class ObjectMethodsTest { assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, "toString", C.EQUALS_DESC, C.class, "x;y", C.ACCESSORS)); assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, "hashCode", C.TO_STRING_DESC, C.class, "x;y", C.ACCESSORS)); assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, "equals", C.HASHCODE_DESC, C.class, "x;y", C.ACCESSORS)); + } - record NamePlusType(String mn, MethodType mt) {} - List namePlusTypeList = List.of( + record NamePlusType(String name, MethodType type) {} + + static List namePlusTypeList() { + return List.of( new NamePlusType("toString", C.TO_STRING_DESC), new NamePlusType("equals", C.EQUALS_DESC), new NamePlusType("hashCode", C.HASHCODE_DESC) ); - - for (NamePlusType npt : namePlusTypeList) { - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, npt.mn(), npt.mt(), C.class, "x;y", null)); - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, npt.mn(), npt.mt(), C.class, "x;y", new MethodHandle[]{null})); - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, npt.mn(), npt.mt(), C.class, null, C.ACCESSORS)); - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, npt.mn(), npt.mt(), null, "x;y", C.ACCESSORS)); - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, npt.mn(), null, C.class, "x;y", C.ACCESSORS)); - assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, null, npt.mt(), C.class, "x;y", C.ACCESSORS)); - assertThrows(NPE, () -> ObjectMethods.bootstrap(null, npt.mn(), npt.mt(), C.class, "x;y", C.ACCESSORS)); - } } + @MethodSource("namePlusTypeList") + @ParameterizedTest + void commonExceptions(NamePlusType npt) { + String name = npt.name(); + MethodType type = npt.type(); + + // Null checks + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, "x;y", null)); + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, "x;y", new MethodHandle[]{null})); + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, null, C.ACCESSORS)); + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, null, "x;y", C.ACCESSORS)); + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, name, null, C.class, "x;y", C.ACCESSORS)); + assertThrows(NPE, () -> ObjectMethods.bootstrap(LOOKUP, null, type, C.class, "x;y", C.ACCESSORS)); + assertThrows(NPE, () -> ObjectMethods.bootstrap(null, name, type, C.class, "x;y", C.ACCESSORS)); + + // Bad indy call receiver type - change C to this test class + assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, name, type.changeParameterType(0, this.getClass()), C.class, "x;y", C.ACCESSORS)); + + // Bad getter types + var wrongReceiverGetter = assertDoesNotThrow(() -> MethodHandles.lookup().findGetter(this.getClass(), "y", int.class)); + assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, "x;y", + new MethodHandle[]{ + C.ACCESSORS[0], + wrongReceiverGetter, + })); + var extraArgGetter = MethodHandles.dropArguments(C.ACCESSORS[1], 1, int.class); + assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, "x;y", + new MethodHandle[]{ + C.ACCESSORS[0], + extraArgGetter, + })); + var voidReturnGetter = MethodHandles.empty(MethodType.methodType(void.class, C.class)); + assertThrows(IAE, () -> ObjectMethods.bootstrap(LOOKUP, name, type, C.class, "x;y", + new MethodHandle[]{ + C.ACCESSORS[0], + voidReturnGetter, + })); + } + + // same field name and type as C::y, for wrongReceiverGetter + private int y; + // Based on the ObjectMethods internal implementation private static int hashCombiner(int x, int y) { return x*31 + y; From a436287c139c88af1b570cc2738e3f33b8ec7fe6 Mon Sep 17 00:00:00 2001 From: Xiaolong Peng Date: Fri, 27 Feb 2026 18:12:05 +0000 Subject: [PATCH 45/54] 8377048: Shenandoah: shenandoahLock related improvments Reviewed-by: kdnilsen, wkemper --- .../shenandoahBarrierSetNMethod.cpp | 4 +- .../gc/shenandoah/shenandoahCodeRoots.cpp | 6 +- .../gc/shenandoah/shenandoahConcurrentGC.cpp | 2 +- .../share/gc/shenandoah/shenandoahFreeSet.hpp | 4 +- .../share/gc/shenandoah/shenandoahHeap.cpp | 10 ++++ .../share/gc/shenandoah/shenandoahHeap.hpp | 20 ++++++- .../share/gc/shenandoah/shenandoahLock.cpp | 28 +++++---- .../share/gc/shenandoah/shenandoahLock.hpp | 58 ++++++------------- .../share/gc/shenandoah/shenandoahNMethod.cpp | 2 +- .../share/gc/shenandoah/shenandoahNMethod.hpp | 16 +++-- .../shenandoah/shenandoahNMethod.inline.hpp | 8 +-- .../share/gc/shenandoah/shenandoahUnload.cpp | 8 +-- 12 files changed, 91 insertions(+), 75 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp index c6e6108fda8..2be5722f7f9 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahBarrierSetNMethod.cpp @@ -41,9 +41,9 @@ bool ShenandoahBarrierSetNMethod::nmethod_entry_barrier(nmethod* nm) { return true; } - ShenandoahReentrantLock* lock = ShenandoahNMethod::lock_for_nmethod(nm); + ShenandoahNMethodLock* lock = ShenandoahNMethod::lock_for_nmethod(nm); assert(lock != nullptr, "Must be"); - ShenandoahReentrantLocker locker(lock); + ShenandoahNMethodLocker locker(lock); if (!is_armed(nm)) { // Some other thread managed to complete while we were diff --git a/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.cpp b/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.cpp index 07d339eb32e..64e135e9a4e 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahCodeRoots.cpp @@ -136,13 +136,13 @@ public: assert(!nm_data->is_unregistered(), "Should not see unregistered entry"); if (nm->is_unloading()) { - ShenandoahReentrantLocker locker(nm_data->lock()); + ShenandoahNMethodLocker locker(nm_data->lock()); nm->unlink(); return; } { - ShenandoahReentrantLocker locker(nm_data->lock()); + ShenandoahNMethodLocker locker(nm_data->lock()); // Heal oops if (_bs->is_armed(nm)) { @@ -154,7 +154,7 @@ public: } // Clear compiled ICs and exception caches - ShenandoahReentrantLocker locker(nm_data->ic_lock()); + ShenandoahNMethodLocker locker(nm_data->ic_lock()); nm->unload_nmethod_caches(_unloading_occurred); } }; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahConcurrentGC.cpp b/src/hotspot/share/gc/shenandoah/shenandoahConcurrentGC.cpp index 364279deafe..5206a0558e8 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahConcurrentGC.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahConcurrentGC.cpp @@ -1023,7 +1023,7 @@ public: void do_nmethod(nmethod* n) { ShenandoahNMethod* data = ShenandoahNMethod::gc_data(n); - ShenandoahReentrantLocker locker(data->lock()); + ShenandoahNMethodLocker locker(data->lock()); // Setup EvacOOM scope below reentrant lock to avoid deadlock with // nmethod_entry_barrier ShenandoahEvacOOMScope oom; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp index 91c6024d522..d55a06d5713 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahFreeSet.hpp @@ -32,8 +32,8 @@ #include "gc/shenandoah/shenandoahSimpleBitMap.hpp" #include "logging/logStream.hpp" -typedef ShenandoahLock ShenandoahRebuildLock; -typedef ShenandoahLocker ShenandoahRebuildLocker; +typedef ShenandoahLock ShenandoahRebuildLock; +typedef ShenandoahLocker ShenandoahRebuildLocker; // Each ShenandoahHeapRegion is associated with a ShenandoahFreeSetPartitionId. enum class ShenandoahFreeSetPartitionId : uint8_t { diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp b/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp index 9dd837b90d2..d78bdae6a51 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp @@ -2834,3 +2834,13 @@ void ShenandoahHeap::log_heap_status(const char* msg) const { global_generation()->log_status(msg); } } + +ShenandoahHeapLocker::ShenandoahHeapLocker(ShenandoahHeapLock* lock, bool allow_block_for_safepoint) : _lock(lock) { +#ifdef ASSERT + ShenandoahFreeSet* free_set = ShenandoahHeap::heap()->free_set(); + // free_set is nullptr only at pre-initialized state + assert(free_set == nullptr || !free_set->rebuild_lock()->owned_by_self(), "Dead lock, can't acquire heap lock while holding free-set rebuild lock"); + assert(_lock != nullptr, "Must not"); +#endif + _lock->lock(allow_block_for_safepoint); +} diff --git a/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp b/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp index 4a4499667ff..85ad339469d 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahHeap.hpp @@ -117,9 +117,23 @@ public: virtual bool is_thread_safe() { return false; } }; -typedef ShenandoahLock ShenandoahHeapLock; -typedef ShenandoahLocker ShenandoahHeapLocker; -typedef Stack ShenandoahScanObjectStack; +typedef ShenandoahLock ShenandoahHeapLock; +// ShenandoahHeapLocker implements locker to assure mutually exclusive access to the global heap data structures. +// Asserts in the implementation detect potential deadlock usage with regards the rebuild lock that is present +// in ShenandoahFreeSet. Whenever both locks are acquired, this lock should be acquired before the +// ShenandoahFreeSet rebuild lock. +class ShenandoahHeapLocker : public StackObj { +private: + ShenandoahHeapLock* _lock; +public: + ShenandoahHeapLocker(ShenandoahHeapLock* lock, bool allow_block_for_safepoint = false); + + ~ShenandoahHeapLocker() { + _lock->unlock(); + } +}; + +typedef Stack ShenandoahScanObjectStack; // Shenandoah GC is low-pause concurrent GC that uses a load reference barrier // for concurent evacuation and a snapshot-at-the-beginning write barrier for diff --git a/src/hotspot/share/gc/shenandoah/shenandoahLock.cpp b/src/hotspot/share/gc/shenandoah/shenandoahLock.cpp index 7eec0b9af64..7e317f53424 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahLock.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahLock.cpp @@ -93,7 +93,7 @@ ShenandoahSimpleLock::ShenandoahSimpleLock() { assert(os::mutex_init_done(), "Too early!"); } -void ShenandoahSimpleLock::lock() { +void ShenandoahSimpleLock::lock(bool allow_block_for_safepoint) { _lock.lock(); } @@ -101,28 +101,31 @@ void ShenandoahSimpleLock::unlock() { _lock.unlock(); } -ShenandoahReentrantLock::ShenandoahReentrantLock() : - ShenandoahSimpleLock(), _owner(nullptr), _count(0) { - assert(os::mutex_init_done(), "Too early!"); +template +ShenandoahReentrantLock::ShenandoahReentrantLock() : + Lock(), _owner(nullptr), _count(0) { } -ShenandoahReentrantLock::~ShenandoahReentrantLock() { +template +ShenandoahReentrantLock::~ShenandoahReentrantLock() { assert(_count == 0, "Unbalance"); } -void ShenandoahReentrantLock::lock() { +template +void ShenandoahReentrantLock::lock(bool allow_block_for_safepoint) { Thread* const thread = Thread::current(); Thread* const owner = _owner.load_relaxed(); if (owner != thread) { - ShenandoahSimpleLock::lock(); + Lock::lock(allow_block_for_safepoint); _owner.store_relaxed(thread); } _count++; } -void ShenandoahReentrantLock::unlock() { +template +void ShenandoahReentrantLock::unlock() { assert(owned_by_self(), "Invalid owner"); assert(_count > 0, "Invalid count"); @@ -130,12 +133,17 @@ void ShenandoahReentrantLock::unlock() { if (_count == 0) { _owner.store_relaxed((Thread*)nullptr); - ShenandoahSimpleLock::unlock(); + Lock::unlock(); } } -bool ShenandoahReentrantLock::owned_by_self() const { +template +bool ShenandoahReentrantLock::owned_by_self() const { Thread* const thread = Thread::current(); Thread* const owner = _owner.load_relaxed(); return owner == thread; } + +// Explicit template instantiation +template class ShenandoahReentrantLock; +template class ShenandoahReentrantLock; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahLock.hpp b/src/hotspot/share/gc/shenandoah/shenandoahLock.hpp index 2e44810cd5d..7c91df191e5 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahLock.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahLock.hpp @@ -31,7 +31,7 @@ #include "runtime/javaThread.hpp" #include "runtime/safepoint.hpp" -class ShenandoahLock { +class ShenandoahLock { private: enum LockState { unlocked = 0, locked = 1 }; @@ -48,7 +48,7 @@ private: public: ShenandoahLock() : _state(unlocked), _owner(nullptr) {}; - void lock(bool allow_block_for_safepoint) { + void lock(bool allow_block_for_safepoint = false) { assert(_owner.load_relaxed() != Thread::current(), "reentrant locking attempt, would deadlock"); if ((allow_block_for_safepoint && SafepointSynchronize::is_synchronizing()) || @@ -83,34 +83,19 @@ public: } }; -class ShenandoahLocker : public StackObj { -private: - ShenandoahLock* const _lock; -public: - ShenandoahLocker(ShenandoahLock* lock, bool allow_block_for_safepoint = false) : _lock(lock) { - if (_lock != nullptr) { - _lock->lock(allow_block_for_safepoint); - } - } - - ~ShenandoahLocker() { - if (_lock != nullptr) { - _lock->unlock(); - } - } -}; - +// Simple lock using PlatformMonitor class ShenandoahSimpleLock { private: PlatformMonitor _lock; // native lock public: ShenandoahSimpleLock(); - - virtual void lock(); - virtual void unlock(); + void lock(bool allow_block_for_safepoint = false); + void unlock(); }; -class ShenandoahReentrantLock : public ShenandoahSimpleLock { +// templated reentrant lock +template +class ShenandoahReentrantLock : public Lock { private: Atomic _owner; uint64_t _count; @@ -119,30 +104,25 @@ public: ShenandoahReentrantLock(); ~ShenandoahReentrantLock(); - virtual void lock(); - virtual void unlock(); + void lock(bool allow_block_for_safepoint = false); + void unlock(); // If the lock already owned by this thread bool owned_by_self() const ; }; -class ShenandoahReentrantLocker : public StackObj { -private: - ShenandoahReentrantLock* const _lock; - +// template based ShenandoahLocker +template +class ShenandoahLocker : public StackObj { + Lock* const _lock; public: - ShenandoahReentrantLocker(ShenandoahReentrantLock* lock) : - _lock(lock) { - if (_lock != nullptr) { - _lock->lock(); - } + ShenandoahLocker(Lock* lock, bool allow_block_for_safepoint = false) : _lock(lock) { + assert(_lock != nullptr, "Must not"); + _lock->lock(allow_block_for_safepoint); } - ~ShenandoahReentrantLocker() { - if (_lock != nullptr) { - assert(_lock->owned_by_self(), "Must be owner"); - _lock->unlock(); - } + ~ShenandoahLocker() { + _lock->unlock(); } }; diff --git a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.cpp b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.cpp index facaefd4b62..594ad614d90 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.cpp @@ -241,7 +241,7 @@ void ShenandoahNMethodTable::register_nmethod(nmethod* nm) { assert(nm == data->nm(), "Must be same nmethod"); // Prevent updating a nmethod while concurrent iteration is in progress. wait_until_concurrent_iteration_done(); - ShenandoahReentrantLocker data_locker(data->lock()); + ShenandoahNMethodLocker data_locker(data->lock()); data->update(); } else { // For a new nmethod, we can safely append it to the list, because diff --git a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.hpp b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.hpp index 77faf6c0dcb..2686b4f4985 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.hpp @@ -33,6 +33,10 @@ #include "runtime/atomic.hpp" #include "utilities/growableArray.hpp" +// Use ShenandoahReentrantLock as ShenandoahNMethodLock +typedef ShenandoahReentrantLock ShenandoahNMethodLock; +typedef ShenandoahLocker ShenandoahNMethodLocker; + // ShenandoahNMethod tuple records the internal locations of oop slots within reclocation stream in // the nmethod. This allows us to quickly scan the oops without doing the nmethod-internal scans, // that sometimes involves parsing the machine code. Note it does not record the oops themselves, @@ -44,16 +48,16 @@ private: int _oops_count; bool _has_non_immed_oops; bool _unregistered; - ShenandoahReentrantLock _lock; - ShenandoahReentrantLock _ic_lock; + ShenandoahNMethodLock _lock; + ShenandoahNMethodLock _ic_lock; public: ShenandoahNMethod(nmethod *nm, GrowableArray& oops, bool has_non_immed_oops); ~ShenandoahNMethod(); inline nmethod* nm() const; - inline ShenandoahReentrantLock* lock(); - inline ShenandoahReentrantLock* ic_lock(); + inline ShenandoahNMethodLock* lock(); + inline ShenandoahNMethodLock* ic_lock(); inline void oops_do(OopClosure* oops, bool fix_relocations = false); // Update oops when the nmethod is re-registered void update(); @@ -61,8 +65,8 @@ public: inline bool is_unregistered() const; static ShenandoahNMethod* for_nmethod(nmethod* nm); - static inline ShenandoahReentrantLock* lock_for_nmethod(nmethod* nm); - static inline ShenandoahReentrantLock* ic_lock_for_nmethod(nmethod* nm); + static inline ShenandoahNMethodLock* lock_for_nmethod(nmethod* nm); + static inline ShenandoahNMethodLock* ic_lock_for_nmethod(nmethod* nm); static void heal_nmethod(nmethod* nm); static inline void heal_nmethod_metadata(ShenandoahNMethod* nmethod_data); diff --git a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.inline.hpp b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.inline.hpp index 6758298675b..ef9e347b821 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahNMethod.inline.hpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahNMethod.inline.hpp @@ -35,11 +35,11 @@ nmethod* ShenandoahNMethod::nm() const { return _nm; } -ShenandoahReentrantLock* ShenandoahNMethod::lock() { +ShenandoahNMethodLock* ShenandoahNMethod::lock() { return &_lock; } -ShenandoahReentrantLock* ShenandoahNMethod::ic_lock() { +ShenandoahNMethodLock* ShenandoahNMethod::ic_lock() { return &_ic_lock; } @@ -85,11 +85,11 @@ void ShenandoahNMethod::attach_gc_data(nmethod* nm, ShenandoahNMethod* gc_data) nm->set_gc_data(gc_data); } -ShenandoahReentrantLock* ShenandoahNMethod::lock_for_nmethod(nmethod* nm) { +ShenandoahNMethodLock* ShenandoahNMethod::lock_for_nmethod(nmethod* nm) { return gc_data(nm)->lock(); } -ShenandoahReentrantLock* ShenandoahNMethod::ic_lock_for_nmethod(nmethod* nm) { +ShenandoahNMethodLock* ShenandoahNMethod::ic_lock_for_nmethod(nmethod* nm) { return gc_data(nm)->ic_lock(); } diff --git a/src/hotspot/share/gc/shenandoah/shenandoahUnload.cpp b/src/hotspot/share/gc/shenandoah/shenandoahUnload.cpp index b248fab7958..ac7fe1f9a3a 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahUnload.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahUnload.cpp @@ -80,7 +80,7 @@ public: virtual bool has_dead_oop(nmethod* nm) const { assert(ShenandoahHeap::heap()->is_concurrent_weak_root_in_progress(), "Only for this phase"); ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm); - ShenandoahReentrantLocker locker(data->lock()); + ShenandoahNMethodLocker locker(data->lock()); ShenandoahIsUnloadingOopClosure cl; data->oops_do(&cl); return cl.is_unloading(); @@ -90,14 +90,14 @@ public: class ShenandoahCompiledICProtectionBehaviour : public CompiledICProtectionBehaviour { public: virtual bool lock(nmethod* nm) { - ShenandoahReentrantLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); + ShenandoahNMethodLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); assert(lock != nullptr, "Not yet registered?"); lock->lock(); return true; } virtual void unlock(nmethod* nm) { - ShenandoahReentrantLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); + ShenandoahNMethodLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); assert(lock != nullptr, "Not yet registered?"); lock->unlock(); } @@ -107,7 +107,7 @@ public: return true; } - ShenandoahReentrantLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); + ShenandoahNMethodLock* const lock = ShenandoahNMethod::ic_lock_for_nmethod(nm); assert(lock != nullptr, "Not yet registered?"); return lock->owned_by_self(); } From 3144b572d33713cd3311352f0bbaac8b69408fe4 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Fri, 27 Feb 2026 19:52:06 +0000 Subject: [PATCH 46/54] 8378388: Add missing @Override annotations in "javax.print.attribute.standard" package part 1 Reviewed-by: prr, azvegint --- .../javax/print/attribute/standard/Chromaticity.java | 6 +++++- .../javax/print/attribute/standard/ColorSupported.java | 6 +++++- .../javax/print/attribute/standard/Compression.java | 6 +++++- .../classes/javax/print/attribute/standard/Copies.java | 5 ++++- .../javax/print/attribute/standard/CopiesSupported.java | 5 ++++- .../print/attribute/standard/DateTimeAtCompleted.java | 5 ++++- .../javax/print/attribute/standard/DateTimeAtCreation.java | 5 ++++- .../print/attribute/standard/DateTimeAtProcessing.java | 5 ++++- .../javax/print/attribute/standard/Destination.java | 5 ++++- .../javax/print/attribute/standard/DialogOwner.java | 5 ++++- .../print/attribute/standard/DialogTypeSelection.java | 6 +++++- .../javax/print/attribute/standard/DocumentName.java | 5 ++++- .../classes/javax/print/attribute/standard/Fidelity.java | 6 +++++- .../classes/javax/print/attribute/standard/Finishings.java | 7 ++++++- .../javax/print/attribute/standard/JobHoldUntil.java | 5 ++++- .../javax/print/attribute/standard/JobImpressions.java | 5 ++++- .../print/attribute/standard/JobImpressionsCompleted.java | 5 ++++- .../print/attribute/standard/JobImpressionsSupported.java | 5 ++++- .../classes/javax/print/attribute/standard/JobKOctets.java | 5 ++++- .../print/attribute/standard/JobKOctetsProcessed.java | 5 ++++- .../print/attribute/standard/JobKOctetsSupported.java | 5 ++++- .../javax/print/attribute/standard/JobMediaSheets.java | 5 ++++- .../print/attribute/standard/JobMediaSheetsCompleted.java | 5 ++++- .../print/attribute/standard/JobMediaSheetsSupported.java | 5 ++++- .../print/attribute/standard/JobMessageFromOperator.java | 5 ++++- .../classes/javax/print/attribute/standard/JobName.java | 5 ++++- .../print/attribute/standard/JobOriginatingUserName.java | 5 ++++- .../javax/print/attribute/standard/JobPriority.java | 5 ++++- .../print/attribute/standard/JobPrioritySupported.java | 5 ++++- .../classes/javax/print/attribute/standard/JobSheets.java | 6 +++++- .../classes/javax/print/attribute/standard/JobState.java | 6 +++++- .../javax/print/attribute/standard/JobStateReason.java | 6 +++++- .../javax/print/attribute/standard/JobStateReasons.java | 5 ++++- 33 files changed, 142 insertions(+), 33 deletions(-) diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Chromaticity.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Chromaticity.java index 0481060f73f..25dbb7ddaca 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Chromaticity.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Chromaticity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -114,6 +114,7 @@ public final class Chromaticity extends EnumSyntax /** * Returns the string table for class {@code Chromaticity}. */ + @Override protected String[] getStringTable() { return myStringTable; } @@ -121,6 +122,7 @@ public final class Chromaticity extends EnumSyntax /** * Returns the enumeration value table for class {@code Chromaticity}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return myEnumValueTable; } @@ -135,6 +137,7 @@ public final class Chromaticity extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Chromaticity.class; } @@ -148,6 +151,7 @@ public final class Chromaticity extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "chromaticity"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/ColorSupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/ColorSupported.java index 6affb3e28dc..8ce2c5eef7c 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/ColorSupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/ColorSupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -104,6 +104,7 @@ public final class ColorSupported extends EnumSyntax /** * Returns the string table for class {@code ColorSupported}. */ + @Override protected String[] getStringTable() { return myStringTable; } @@ -111,6 +112,7 @@ public final class ColorSupported extends EnumSyntax /** * Returns the enumeration value table for class {@code ColorSupported}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return myEnumValueTable; } @@ -125,6 +127,7 @@ public final class ColorSupported extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return ColorSupported.class; } @@ -138,6 +141,7 @@ public final class ColorSupported extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "color-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Compression.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Compression.java index b1e7f1e89fc..9eeab5d9688 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Compression.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Compression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -106,6 +106,7 @@ public class Compression extends EnumSyntax implements DocAttribute { /** * Returns the string table for class {@code Compression}. */ + @Override protected String[] getStringTable() { return myStringTable.clone(); } @@ -113,6 +114,7 @@ public class Compression extends EnumSyntax implements DocAttribute { /** * Returns the enumeration value table for class {@code Compression}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return (EnumSyntax[])myEnumValueTable.clone(); } @@ -127,6 +129,7 @@ public class Compression extends EnumSyntax implements DocAttribute { * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Compression.class; } @@ -140,6 +143,7 @@ public class Compression extends EnumSyntax implements DocAttribute { * * @return attribute category name */ + @Override public final String getName() { return "compression"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Copies.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Copies.java index 33a98c035be..6292cc4c8c2 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Copies.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Copies.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -97,6 +97,7 @@ public final class Copies extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this copies * attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return super.equals (object) && object instanceof Copies; } @@ -110,6 +111,7 @@ public final class Copies extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Copies.class; } @@ -122,6 +124,7 @@ public final class Copies extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "copies"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/CopiesSupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/CopiesSupported.java index e7b411d8e55..3c2cf4bb550 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/CopiesSupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/CopiesSupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -105,6 +105,7 @@ public final class CopiesSupported extends SetOfIntegerSyntax * @return {@code true} if {@code object} is equivalent to this copies * supported attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return super.equals (object) && object instanceof CopiesSupported; } @@ -119,6 +120,7 @@ public final class CopiesSupported extends SetOfIntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return CopiesSupported.class; } @@ -132,6 +134,7 @@ public final class CopiesSupported extends SetOfIntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "copies-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCompleted.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCompleted.java index 4e0a3b27259..a7a31dacd8d 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCompleted.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCompleted.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -88,6 +88,7 @@ public final class DateTimeAtCompleted extends DateTimeSyntax * @return {@code true} if {@code object} is equivalent to this date-time at * completed attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return(super.equals (object) && object instanceof DateTimeAtCompleted); @@ -105,6 +106,7 @@ public final class DateTimeAtCompleted extends DateTimeSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DateTimeAtCompleted.class; } @@ -118,6 +120,7 @@ public final class DateTimeAtCompleted extends DateTimeSyntax * * @return attribute category name */ + @Override public final String getName() { return "date-time-at-completed"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCreation.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCreation.java index fc09f0672c2..53b85b7cf5c 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCreation.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtCreation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -88,6 +88,7 @@ public final class DateTimeAtCreation extends DateTimeSyntax * @return {@code true} if {@code object} is equivalent to this date-time at * creation attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return(super.equals (object) && object instanceof DateTimeAtCreation); @@ -103,6 +104,7 @@ public final class DateTimeAtCreation extends DateTimeSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DateTimeAtCreation.class; } @@ -116,6 +118,7 @@ public final class DateTimeAtCreation extends DateTimeSyntax * * @return attribute category name */ + @Override public final String getName() { return "date-time-at-creation"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtProcessing.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtProcessing.java index 8b1f3efdc0f..310f3f756c7 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtProcessing.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DateTimeAtProcessing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -89,6 +89,7 @@ public final class DateTimeAtProcessing extends DateTimeSyntax * @return {@code true} if {@code object} is equivalent to this date-time at * processing attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return(super.equals (object) && object instanceof DateTimeAtProcessing); @@ -104,6 +105,7 @@ public final class DateTimeAtProcessing extends DateTimeSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DateTimeAtProcessing.class; } @@ -117,6 +119,7 @@ public final class DateTimeAtProcessing extends DateTimeSyntax * * @return attribute category name */ + @Override public final String getName() { return "date-time-at-processing"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Destination.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Destination.java index bc1d240c9c1..655a314b136 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Destination.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Destination.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -89,6 +89,7 @@ public final class Destination extends URISyntax * @return {@code true} if {@code object} is equivalent to this destination * attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals(object) && object instanceof Destination); @@ -104,6 +105,7 @@ public final class Destination extends URISyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Destination.class; } @@ -117,6 +119,7 @@ public final class Destination extends URISyntax * * @return attribute category name */ + @Override public final String getName() { return "spool-data-destination"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DialogOwner.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DialogOwner.java index 593e656cf6b..01a410d075b 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DialogOwner.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DialogOwner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2025, 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 @@ -50,6 +50,7 @@ public final class DialogOwner implements PrintRequestAttribute { private static class Accessor extends DialogOwnerAccessor { + @Override public long getOwnerID(DialogOwner owner) { return owner.getID(); } @@ -133,6 +134,7 @@ public final class DialogOwner implements PrintRequestAttribute { * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DialogOwner.class; } @@ -145,6 +147,7 @@ public final class DialogOwner implements PrintRequestAttribute { * {@code "dialog-owner"}. * */ + @Override public final String getName() { return "dialog-owner"; diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DialogTypeSelection.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DialogTypeSelection.java index ae3195d0280..2cf003060b1 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DialogTypeSelection.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DialogTypeSelection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -98,6 +98,7 @@ public final class DialogTypeSelection extends EnumSyntax /** * Returns the string table for class {@code DialogTypeSelection}. */ + @Override protected String[] getStringTable() { return myStringTable; } @@ -106,6 +107,7 @@ public final class DialogTypeSelection extends EnumSyntax * Returns the enumeration value table for class * {@code DialogTypeSelection}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return myEnumValueTable; } @@ -120,6 +122,7 @@ public final class DialogTypeSelection extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DialogTypeSelection.class; } @@ -133,6 +136,7 @@ public final class DialogTypeSelection extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "dialog-type-selection"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/DocumentName.java b/src/java.desktop/share/classes/javax/print/attribute/standard/DocumentName.java index eb2bd7a870d..bd1f574e4ba 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/DocumentName.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/DocumentName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -86,6 +86,7 @@ public final class DocumentName extends TextSyntax implements DocAttribute { * @return {@code true} if {@code object} is equivalent to this document * name attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof DocumentName); } @@ -100,6 +101,7 @@ public final class DocumentName extends TextSyntax implements DocAttribute { * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return DocumentName.class; } @@ -113,6 +115,7 @@ public final class DocumentName extends TextSyntax implements DocAttribute { * * @return attribute category name */ + @Override public final String getName() { return "document-name"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Fidelity.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Fidelity.java index b0e4b70c87c..8c8941c76c4 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Fidelity.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Fidelity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -101,6 +101,7 @@ public final class Fidelity extends EnumSyntax /** * Returns the string table for class {@code Fidelity}. */ + @Override protected String[] getStringTable() { return myStringTable; } @@ -108,6 +109,7 @@ public final class Fidelity extends EnumSyntax /** * Returns the enumeration value table for class {@code Fidelity}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return myEnumValueTable; } @@ -122,6 +124,7 @@ public final class Fidelity extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Fidelity.class; } @@ -135,6 +138,7 @@ public final class Fidelity extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "ipp-attribute-fidelity"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Finishings.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Finishings.java index 46d520ecb48..7d9d042b3e7 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Finishings.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Finishings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -344,6 +344,7 @@ public class Finishings extends EnumSyntax /** * Returns the string table for class {@code Finishings}. */ + @Override protected String[] getStringTable() { return myStringTable.clone(); } @@ -351,6 +352,7 @@ public class Finishings extends EnumSyntax /** * Returns the enumeration value table for class {@code Finishings}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return (EnumSyntax[])myEnumValueTable.clone(); } @@ -358,6 +360,7 @@ public class Finishings extends EnumSyntax /** * Returns the lowest integer value used by class {@code Finishings}. */ + @Override protected int getOffset() { return 3; } @@ -372,6 +375,7 @@ public class Finishings extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return Finishings.class; } @@ -385,6 +389,7 @@ public class Finishings extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "finishings"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobHoldUntil.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobHoldUntil.java index d4e2c2625df..2b9ede6940f 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobHoldUntil.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobHoldUntil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -123,6 +123,7 @@ public final class JobHoldUntil extends DateTimeSyntax * @return {@code true} if {@code object} is equivalent to this job hold * until attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals(object) && object instanceof JobHoldUntil); } @@ -137,6 +138,7 @@ public final class JobHoldUntil extends DateTimeSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobHoldUntil.class; } @@ -150,6 +152,7 @@ public final class JobHoldUntil extends DateTimeSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-hold-until"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressions.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressions.java index ed9600838be..70d7c7e5e46 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressions.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -110,6 +110,7 @@ public final class JobImpressions extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job * impressions attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return super.equals (object) && object instanceof JobImpressions; } @@ -124,6 +125,7 @@ public final class JobImpressions extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobImpressions.class; } @@ -137,6 +139,7 @@ public final class JobImpressions extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-impressions"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsCompleted.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsCompleted.java index 4974f9e13c9..e6fdeb93d05 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsCompleted.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsCompleted.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobImpressionsCompleted extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job * impressions completed attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return(super.equals (object) && object instanceof JobImpressionsCompleted); @@ -109,6 +110,7 @@ public final class JobImpressionsCompleted extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobImpressionsCompleted.class; } @@ -122,6 +124,7 @@ public final class JobImpressionsCompleted extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-impressions-completed"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsSupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsSupported.java index 131b19f5ad2..82b3049b8bd 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsSupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobImpressionsSupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobImpressionsSupported extends SetOfIntegerSyntax * @return {@code true} if {@code object} is equivalent to this job * impressions supported attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobImpressionsSupported); @@ -109,6 +110,7 @@ public final class JobImpressionsSupported extends SetOfIntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobImpressionsSupported.class; } @@ -122,6 +124,7 @@ public final class JobImpressionsSupported extends SetOfIntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-impressions-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctets.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctets.java index 454a30a3a28..acd04fab21d 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctets.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctets.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -159,6 +159,7 @@ public final class JobKOctets extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job K octets * attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return super.equals(object) && object instanceof JobKOctets; } @@ -173,6 +174,7 @@ public final class JobKOctets extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobKOctets.class; } @@ -186,6 +188,7 @@ public final class JobKOctets extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-k-octets"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsProcessed.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsProcessed.java index 9acc44f5777..efd9cac2441 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsProcessed.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsProcessed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -104,6 +104,7 @@ public final class JobKOctetsProcessed extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job K octets * processed attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return(super.equals (object) && object instanceof JobKOctetsProcessed); @@ -119,6 +120,7 @@ public final class JobKOctetsProcessed extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobKOctetsProcessed.class; } @@ -132,6 +134,7 @@ public final class JobKOctetsProcessed extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-k-octets-processed"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsSupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsSupported.java index 032d172d6e2..221328caeb8 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsSupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobKOctetsSupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -93,6 +93,7 @@ public final class JobKOctetsSupported extends SetOfIntegerSyntax * @return {@code true} if {@code object} is equivalent to this job K octets * supported attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobKOctetsSupported); @@ -108,6 +109,7 @@ public final class JobKOctetsSupported extends SetOfIntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobKOctetsSupported.class; } @@ -121,6 +123,7 @@ public final class JobKOctetsSupported extends SetOfIntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-k-octets-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheets.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheets.java index a3720748f68..181bda79826 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheets.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheets.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -101,6 +101,7 @@ public class JobMediaSheets extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job media * sheets attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return super.equals(object) && object instanceof JobMediaSheets; } @@ -115,6 +116,7 @@ public class JobMediaSheets extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobMediaSheets.class; } @@ -128,6 +130,7 @@ public class JobMediaSheets extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-media-sheets"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsCompleted.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsCompleted.java index e6f1eb9b4d8..fea87dc8ebd 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsCompleted.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsCompleted.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobMediaSheetsCompleted extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job media * sheets completed attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobMediaSheetsCompleted); @@ -109,6 +110,7 @@ public final class JobMediaSheetsCompleted extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobMediaSheetsCompleted.class; } @@ -122,6 +124,7 @@ public final class JobMediaSheetsCompleted extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-media-sheets-completed"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsSupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsSupported.java index a942f277175..8feeafef18a 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsSupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMediaSheetsSupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobMediaSheetsSupported extends SetOfIntegerSyntax * @return {@code true} if {@code object} is equivalent to this job media * sheets supported attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobMediaSheetsSupported); @@ -109,6 +110,7 @@ public final class JobMediaSheetsSupported extends SetOfIntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobMediaSheetsSupported.class; } @@ -122,6 +124,7 @@ public final class JobMediaSheetsSupported extends SetOfIntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-media-sheets-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMessageFromOperator.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMessageFromOperator.java index cd944103d23..796fe37774c 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobMessageFromOperator.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobMessageFromOperator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobMessageFromOperator extends TextSyntax * @return {@code true} if {@code object} is equivalent to this job message * from operator attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobMessageFromOperator); @@ -109,6 +110,7 @@ public final class JobMessageFromOperator extends TextSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobMessageFromOperator.class; } @@ -122,6 +124,7 @@ public final class JobMessageFromOperator extends TextSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-message-from-operator"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobName.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobName.java index cceabd8b8f0..4fa9eaee6fd 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobName.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -92,6 +92,7 @@ public final class JobName extends TextSyntax * @return {@code true} if {@code object} is equivalent to this job name * attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals(object) && object instanceof JobName); } @@ -105,6 +106,7 @@ public final class JobName extends TextSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobName.class; } @@ -117,6 +119,7 @@ public final class JobName extends TextSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-name"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobOriginatingUserName.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobOriginatingUserName.java index d8dfd56a920..eda27d142f9 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobOriginatingUserName.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobOriginatingUserName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -91,6 +91,7 @@ public final class JobOriginatingUserName extends TextSyntax * @return {@code true} if {@code object} is equivalent to this job * originating user name attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobOriginatingUserName); @@ -106,6 +107,7 @@ public final class JobOriginatingUserName extends TextSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobOriginatingUserName.class; } @@ -119,6 +121,7 @@ public final class JobOriginatingUserName extends TextSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-originating-user-name"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobPriority.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobPriority.java index 7c77a504673..5ca9990ec13 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobPriority.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobPriority.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -94,6 +94,7 @@ public final class JobPriority extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job priority * attribute, {@code false} otherwise */ + @Override public boolean equals(Object object) { return (super.equals (object) && object instanceof JobPriority); } @@ -108,6 +109,7 @@ public final class JobPriority extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobPriority.class; } @@ -121,6 +123,7 @@ public final class JobPriority extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-priority"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobPrioritySupported.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobPrioritySupported.java index 6df729a9813..422d823bff7 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobPrioritySupported.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobPrioritySupported.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -86,6 +86,7 @@ public final class JobPrioritySupported extends IntegerSyntax * @return {@code true} if {@code object} is equivalent to this job priority * supported attribute, {@code false} otherwise */ + @Override public boolean equals (Object object) { return (super.equals(object) && @@ -102,6 +103,7 @@ public final class JobPrioritySupported extends IntegerSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobPrioritySupported.class; } @@ -115,6 +117,7 @@ public final class JobPrioritySupported extends IntegerSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-priority-supported"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobSheets.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobSheets.java index 130b8eb27a3..59a31096d2a 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobSheets.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobSheets.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -101,6 +101,7 @@ public class JobSheets extends EnumSyntax /** * Returns the string table for class {@code JobSheets}. */ + @Override protected String[] getStringTable() { return myStringTable.clone(); } @@ -108,6 +109,7 @@ public class JobSheets extends EnumSyntax /** * Returns the enumeration value table for class {@code JobSheets}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return (EnumSyntax[])myEnumValueTable.clone(); } @@ -122,6 +124,7 @@ public class JobSheets extends EnumSyntax * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobSheets.class; } @@ -135,6 +138,7 @@ public class JobSheets extends EnumSyntax * * @return attribute category name */ + @Override public final String getName() { return "job-sheets"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobState.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobState.java index 13499a9b2a7..0b0ba9d3276 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobState.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobState.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -206,6 +206,7 @@ public class JobState extends EnumSyntax implements PrintJobAttribute { /** * Returns the string table for class {@code JobState}. */ + @Override protected String[] getStringTable() { return myStringTable; } @@ -213,6 +214,7 @@ public class JobState extends EnumSyntax implements PrintJobAttribute { /** * Returns the enumeration value table for class {@code JobState}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return myEnumValueTable; } @@ -227,6 +229,7 @@ public class JobState extends EnumSyntax implements PrintJobAttribute { * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobState.class; } @@ -240,6 +243,7 @@ public class JobState extends EnumSyntax implements PrintJobAttribute { * * @return attribute category name */ + @Override public final String getName() { return "job-state"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReason.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReason.java index 2f8526cb7b1..aba72ec9c1a 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReason.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReason.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -436,6 +436,7 @@ public class JobStateReason extends EnumSyntax implements Attribute { /** * Returns the string table for class {@code JobStateReason}. */ + @Override protected String[] getStringTable() { return myStringTable.clone(); } @@ -443,6 +444,7 @@ public class JobStateReason extends EnumSyntax implements Attribute { /** * Returns the enumeration value table for class {@code JobStateReason}. */ + @Override protected EnumSyntax[] getEnumValueTable() { return (EnumSyntax[])myEnumValueTable.clone(); } @@ -457,6 +459,7 @@ public class JobStateReason extends EnumSyntax implements Attribute { * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobStateReason.class; } @@ -470,6 +473,7 @@ public class JobStateReason extends EnumSyntax implements Attribute { * * @return attribute category name */ + @Override public final String getName() { return "job-state-reason"; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReasons.java b/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReasons.java index 22b438c02eb..4e3e66d0ea8 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReasons.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/JobStateReasons.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -140,6 +140,7 @@ public final class JobStateReasons * class {@link JobStateReason JobStateReason} * @since 1.5 */ + @Override public boolean add(JobStateReason o) { if (o == null) { throw new NullPointerException(); @@ -157,6 +158,7 @@ public final class JobStateReasons * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ + @Override public final Class getCategory() { return JobStateReasons.class; } @@ -170,6 +172,7 @@ public final class JobStateReasons * * @return attribute category name */ + @Override public final String getName() { return "job-state-reasons"; } From e0b040a6c6713827033e9ba51c9ded920dd0203b Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Fri, 27 Feb 2026 20:34:16 +0000 Subject: [PATCH 47/54] 8331994: Adapt MAKEFLAGS check for GNU Make 4.4.1 Reviewed-by: jpai, dholmes --- make/PreInit.gmk | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/make/PreInit.gmk b/make/PreInit.gmk index 3df44308dd9..8152587781c 100644 --- a/make/PreInit.gmk +++ b/make/PreInit.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2012, 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 @@ -66,7 +66,8 @@ CALLED_SPEC_TARGETS := $(filter-out $(ALL_GLOBAL_TARGETS), $(CALLED_TARGETS)) ifeq ($(CALLED_SPEC_TARGETS), ) SKIP_SPEC := true endif -ifeq ($(findstring p, $(MAKEFLAGS))$(findstring q, $(MAKEFLAGS)), pq) +MFLAGS_SINGLE := $(filter-out --%, $(MFLAGS)) +ifeq ($(findstring p, $(MFLAGS_SINGLE))$(findstring q, $(MFLAGS_SINGLE)), pq) SKIP_SPEC := true endif From 4bee207d0ad948734e04516dd8d7c9504cb83665 Mon Sep 17 00:00:00 2001 From: Andrew Dinn Date: Fri, 27 Feb 2026 21:49:55 +0000 Subject: [PATCH 48/54] 8377554: Load card table base and other values via AOTRuntimeConstants in AOT code Reviewed-by: kvn, asmehra --- src/hotspot/cpu/aarch64/aarch64.ad | 30 +++++++++- .../cpu/aarch64/c1_LIRAssembler_aarch64.cpp | 10 ++++ .../gc/g1/g1BarrierSetAssembler_aarch64.cpp | 23 +++++++- .../cpu/aarch64/macroAssembler_aarch64.cpp | 22 ++++++++ .../cpu/aarch64/macroAssembler_aarch64.hpp | 3 + src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp | 10 ++++ .../x86/gc/g1/g1BarrierSetAssembler_x86.cpp | 41 ++++++++++++-- .../cardTableBarrierSetAssembler_x86.cpp | 24 ++++++-- .../cardTableBarrierSetAssembler_x86.hpp | 2 +- src/hotspot/cpu/x86/macroAssembler_x86.cpp | 14 +++++ src/hotspot/cpu/x86/macroAssembler_x86.hpp | 1 + src/hotspot/cpu/x86/x86.ad | 25 +++++++++ src/hotspot/share/adlc/main.cpp | 2 + src/hotspot/share/code/aotCodeCache.cpp | 55 +++++++++++++++++++ src/hotspot/share/code/aotCodeCache.hpp | 33 +++++++++++ src/hotspot/share/gc/g1/g1BarrierSet.hpp | 3 + .../gc/shared/c1/cardTableBarrierSetC1.cpp | 13 +++++ .../gc/shared/c2/cardTableBarrierSetC2.cpp | 14 ++++- .../gc/shared/c2/cardTableBarrierSetC2.hpp | 2 +- .../share/gc/shared/cardTableBarrierSet.hpp | 4 ++ src/hotspot/share/opto/idealKit.cpp | 11 ++++ src/hotspot/share/opto/idealKit.hpp | 3 + src/hotspot/share/opto/type.cpp | 2 +- 23 files changed, 329 insertions(+), 18 deletions(-) diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index a9ca91d9309..9734c6845ea 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -3403,11 +3403,13 @@ encode %{ } else if (rtype == relocInfo::metadata_type) { __ mov_metadata(dst_reg, (Metadata*)con); } else { - assert(rtype == relocInfo::none, "unexpected reloc type"); + assert(rtype == relocInfo::none || rtype == relocInfo::external_word_type, "unexpected reloc type"); + // load fake address constants using a normal move if (! __ is_valid_AArch64_address(con) || con < (address)(uintptr_t)os::vm_page_size()) { __ mov(dst_reg, con); } else { + // no reloc so just use adrp and add uint64_t offset; __ adrp(dst_reg, con, offset); __ add(dst_reg, dst_reg, offset); @@ -4535,6 +4537,18 @@ operand immP_1() interface(CONST_INTER); %} +// AOT Runtime Constants Address +operand immAOTRuntimeConstantsAddress() +%{ + // Check if the address is in the range of AOT Runtime Constants + predicate(AOTRuntimeConstants::contains((address)(n->get_ptr()))); + match(ConP); + + op_cost(0); + format %{ %} + interface(CONST_INTER); +%} + // Float and Double operands // Double Immediate operand immD() @@ -6898,6 +6912,20 @@ instruct loadConP1(iRegPNoSp dst, immP_1 con) ins_pipe(ialu_imm); %} +instruct loadAOTRCAddress(iRegPNoSp dst, immAOTRuntimeConstantsAddress con) +%{ + match(Set dst con); + + ins_cost(INSN_COST); + format %{ "adr $dst, $con\t# AOT Runtime Constants Address" %} + + ins_encode %{ + __ load_aotrc_address($dst$$Register, (address)$con$$constant); + %} + + ins_pipe(ialu_imm); +%} + // Load Narrow Pointer Constant instruct loadConN(iRegNNoSp dst, immN con) diff --git a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp index c0621cbd5c2..30048a2079d 100644 --- a/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/c1_LIRAssembler_aarch64.cpp @@ -33,6 +33,7 @@ #include "c1/c1_ValueStack.hpp" #include "ci/ciArrayKlass.hpp" #include "ci/ciInstance.hpp" +#include "code/aotCodeCache.hpp" #include "code/compiledIC.hpp" #include "gc/shared/collectedHeap.hpp" #include "gc/shared/gc_globals.hpp" @@ -532,6 +533,15 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + address b = c->as_pointer(); + if (AOTRuntimeConstants::contains(b)) { + __ load_aotrc_address(dest->as_register_lo(), b); + break; + } + } +#endif __ mov(dest->as_register_lo(), (intptr_t)c->as_jlong()); break; } diff --git a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp index d7884c27a2c..68291720208 100644 --- a/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/gc/g1/g1BarrierSetAssembler_aarch64.cpp @@ -23,6 +23,7 @@ */ #include "asm/macroAssembler.inline.hpp" +#include "code/aotCodeCache.hpp" #include "gc/g1/g1BarrierSet.hpp" #include "gc/g1/g1BarrierSetAssembler.hpp" #include "gc/g1/g1BarrierSetRuntime.hpp" @@ -243,9 +244,25 @@ static void generate_post_barrier(MacroAssembler* masm, assert_different_registers(store_addr, new_val, thread, tmp1, tmp2, noreg, rscratch1); // Does store cross heap regions? - __ eor(tmp1, store_addr, new_val); // tmp1 := store address ^ new value - __ lsr(tmp1, tmp1, G1HeapRegion::LogOfHRGrainBytes); // tmp1 := ((store address ^ new value) >> LogOfHRGrainBytes) - __ cbz(tmp1, done); + #if INCLUDE_CDS + // AOT code needs to load the barrier grain shift from the aot + // runtime constants area in the code cache otherwise we can compile + // it as an immediate operand + if (AOTCodeCache::is_on_for_dump()) { + address grain_shift_address = (address)AOTRuntimeConstants::grain_shift_address(); + __ eor(tmp1, store_addr, new_val); + __ lea(tmp2, ExternalAddress(grain_shift_address)); + __ ldrb(tmp2, tmp2); + __ lsrv(tmp1, tmp1, tmp2); + __ cbz(tmp1, done); + } else +#endif + { + __ eor(tmp1, store_addr, new_val); // tmp1 := store address ^ new value + __ lsr(tmp1, tmp1, G1HeapRegion::LogOfHRGrainBytes); // tmp1 := ((store address ^ new value) >> LogOfHRGrainBytes) + __ cbz(tmp1, done); + } + // Crosses regions, storing null? if (new_val_may_be_null) { __ cbz(new_val, done); diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp index 35e90d296c9..3e3e95be07e 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.cpp @@ -5754,6 +5754,14 @@ void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_off } void MacroAssembler::load_byte_map_base(Register reg) { +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address(); + lea(reg, ExternalAddress(byte_map_base_adr)); + ldr(reg, Address(reg)); + return; + } +#endif CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set(); // Strictly speaking the card table base isn't an address at all, and it might @@ -5761,6 +5769,20 @@ void MacroAssembler::load_byte_map_base(Register reg) { mov(reg, (uint64_t)ctbs->card_table_base_const()); } +void MacroAssembler::load_aotrc_address(Register reg, address a) { +#if INCLUDE_CDS + assert(AOTRuntimeConstants::contains(a), "address out of range for data area"); + if (AOTCodeCache::is_on_for_dump()) { + // all aotrc field addresses should be registered in the AOTCodeCache address table + lea(reg, ExternalAddress(a)); + } else { + mov(reg, (uint64_t)a); + } +#else + ShouldNotReachHere(); +#endif +} + void MacroAssembler::build_frame(int framesize) { assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR"); assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment"); diff --git a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp index 7b5af532ca1..fa32f3055b9 100644 --- a/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/macroAssembler_aarch64.hpp @@ -1476,6 +1476,9 @@ public: // Load the base of the cardtable byte map into reg. void load_byte_map_base(Register reg); + // Load a constant address in the AOT Runtime Constants area + void load_aotrc_address(Register reg, address a); + // Prolog generator routines to support switch between x86 code and // generated ARM code diff --git a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp index 37ee9451405..d9be0fdcc8d 100644 --- a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp @@ -32,6 +32,7 @@ #include "c1/c1_ValueStack.hpp" #include "ci/ciArrayKlass.hpp" #include "ci/ciInstance.hpp" +#include "code/aotCodeCache.hpp" #include "compiler/oopMap.hpp" #include "gc/shared/collectedHeap.hpp" #include "gc/shared/gc_globals.hpp" @@ -535,6 +536,15 @@ void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_cod case T_LONG: { assert(patch_code == lir_patch_none, "no patching handled here"); +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + address b = c->as_pointer(); + if (AOTRuntimeConstants::contains(b)) { + __ load_aotrc_address(dest->as_register_lo(), b); + break; + } + } +#endif __ movptr(dest->as_register_lo(), (intptr_t)c->as_jlong()); break; } diff --git a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp index 34de9403ccf..b20d7b5cd07 100644 --- a/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/g1/g1BarrierSetAssembler_x86.cpp @@ -23,6 +23,7 @@ */ #include "asm/macroAssembler.inline.hpp" +#include "code/aotCodeCache.hpp" #include "gc/g1/g1BarrierSet.hpp" #include "gc/g1/g1BarrierSetAssembler.hpp" #include "gc/g1/g1BarrierSetRuntime.hpp" @@ -268,6 +269,16 @@ void G1BarrierSetAssembler::g1_write_barrier_pre(MacroAssembler* masm, __ bind(done); } +#if INCLUDE_CDS +// return a register that differs from reg1, reg2, reg3 and reg4 + +static Register pick_different_reg(Register reg1, Register reg2 = noreg, Register reg3= noreg, Register reg4 = noreg) { + RegSet available = (RegSet::of(rscratch1, rscratch2, rax, rbx) + rdx - + RegSet::of(reg1, reg2, reg3, reg4)); + return *(available.begin()); +} +#endif // INCLUDE_CDS + static void generate_post_barrier(MacroAssembler* masm, const Register store_addr, const Register new_val, @@ -280,10 +291,32 @@ static void generate_post_barrier(MacroAssembler* masm, Label L_done; // Does store cross heap regions? - __ movptr(tmp1, store_addr); // tmp1 := store address - __ xorptr(tmp1, new_val); // tmp1 := store address ^ new value - __ shrptr(tmp1, G1HeapRegion::LogOfHRGrainBytes); // ((store address ^ new value) >> LogOfHRGrainBytes) == 0? - __ jccb(Assembler::equal, L_done); +#if INCLUDE_CDS + // AOT code needs to load the barrier grain shift from the aot + // runtime constants area in the code cache otherwise we can compile + // it as an immediate operand + + if (AOTCodeCache::is_on_for_dump()) { + address grain_shift_addr = AOTRuntimeConstants::grain_shift_address(); + Register save = pick_different_reg(rcx, tmp1, new_val, store_addr); + __ push(save); + __ movptr(save, store_addr); + __ xorptr(save, new_val); + __ push(rcx); + __ lea(rcx, ExternalAddress(grain_shift_addr)); + __ movl(rcx, Address(rcx, 0)); + __ shrptr(save); + __ pop(rcx); + __ pop(save); + __ jcc(Assembler::equal, L_done); + } else +#endif // INCLUDE_CDS + { + __ movptr(tmp1, store_addr); // tmp1 := store address + __ xorptr(tmp1, new_val); // tmp1 := store address ^ new value + __ shrptr(tmp1, G1HeapRegion::LogOfHRGrainBytes); // ((store address ^ new value) >> LogOfHRGrainBytes) == 0? + __ jccb(Assembler::equal, L_done); + } // Crosses regions, storing null? if (new_val_may_be_null) { diff --git a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp index 65e6b4e01fc..0ea769dd488 100644 --- a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.cpp @@ -23,6 +23,7 @@ */ #include "asm/macroAssembler.inline.hpp" +#include "code/aotCodeCache.hpp" #include "gc/shared/barrierSet.hpp" #include "gc/shared/cardTable.hpp" #include "gc/shared/cardTableBarrierSet.hpp" @@ -111,7 +112,15 @@ void CardTableBarrierSetAssembler::gen_write_ref_array_post_barrier(MacroAssembl __ shrptr(end, CardTable::card_shift()); __ subptr(end, addr); // end --> cards count - __ mov64(tmp, (intptr_t)ctbs->card_table_base_const()); +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + __ lea(tmp, ExternalAddress(AOTRuntimeConstants::card_table_base_address())); + __ movq(tmp, Address(tmp, 0)); + } else +#endif + { + __ mov64(tmp, (intptr_t)ctbs->card_table_base_const()); + } __ addptr(addr, tmp); __ BIND(L_loop); __ movb(Address(addr, count, Address::times_1), 0); @@ -121,7 +130,7 @@ __ BIND(L_loop); __ BIND(L_done); } -void CardTableBarrierSetAssembler::store_check(MacroAssembler* masm, Register obj, Address dst) { +void CardTableBarrierSetAssembler::store_check(MacroAssembler* masm, Register obj, Address dst, Register rscratch) { // Does a store check for the oop in register obj. The content of // register obj is destroyed afterwards. CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set(); @@ -136,6 +145,13 @@ void CardTableBarrierSetAssembler::store_check(MacroAssembler* masm, Register ob // never need to be relocated. On 64bit however the value may be too // large for a 32bit displacement. intptr_t byte_map_base = (intptr_t)ctbs->card_table_base_const(); +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + __ lea(rscratch, ExternalAddress(AOTRuntimeConstants::card_table_base_address())); + __ movq(rscratch, Address(rscratch, 0)); + card_addr = Address(rscratch, obj, Address::times_1, 0); + } else +#endif if (__ is_simm32(byte_map_base)) { card_addr = Address(noreg, obj, Address::times_1, byte_map_base); } else { @@ -174,10 +190,10 @@ void CardTableBarrierSetAssembler::oop_store_at(MacroAssembler* masm, DecoratorS if (needs_post_barrier) { // flatten object address if needed if (!precise || (dst.index() == noreg && dst.disp() == 0)) { - store_check(masm, dst.base(), dst); + store_check(masm, dst.base(), dst, tmp2); } else { __ lea(tmp1, dst); - store_check(masm, tmp1, dst); + store_check(masm, tmp1, dst, tmp2); } } } diff --git a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.hpp b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.hpp index 0a36571c757..201c11062f2 100644 --- a/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/gc/shared/cardTableBarrierSetAssembler_x86.hpp @@ -33,7 +33,7 @@ protected: virtual void gen_write_ref_array_pre_barrier(MacroAssembler* masm, DecoratorSet decorators, Register addr, Register count) {} - void store_check(MacroAssembler* masm, Register obj, Address dst); + void store_check(MacroAssembler* masm, Register obj, Address dst, Register rscratch); virtual void gen_write_ref_array_post_barrier(MacroAssembler* masm, DecoratorSet decorators, Register addr, Register count, Register tmp); diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.cpp b/src/hotspot/cpu/x86/macroAssembler_x86.cpp index 83169df3456..b54f6adc263 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp @@ -10034,6 +10034,20 @@ void MacroAssembler::restore_legacy_gprs() { addq(rsp, 16 * wordSize); } +void MacroAssembler::load_aotrc_address(Register reg, address a) { +#if INCLUDE_CDS + assert(AOTRuntimeConstants::contains(a), "address out of range for data area"); + if (AOTCodeCache::is_on_for_dump()) { + // all aotrc field addresses should be registered in the AOTCodeCache address table + lea(reg, ExternalAddress(a)); + } else { + mov64(reg, (uint64_t)a); + } +#else + ShouldNotReachHere(); +#endif +} + void MacroAssembler::setcc(Assembler::Condition comparison, Register dst) { if (VM_Version::supports_apx_f()) { esetzucc(comparison, dst); diff --git a/src/hotspot/cpu/x86/macroAssembler_x86.hpp b/src/hotspot/cpu/x86/macroAssembler_x86.hpp index eb23199ca63..5c049f710e2 100644 --- a/src/hotspot/cpu/x86/macroAssembler_x86.hpp +++ b/src/hotspot/cpu/x86/macroAssembler_x86.hpp @@ -2070,6 +2070,7 @@ public: void save_legacy_gprs(); void restore_legacy_gprs(); + void load_aotrc_address(Register reg, address a); void setcc(Assembler::Condition comparison, Register dst); }; diff --git a/src/hotspot/cpu/x86/x86.ad b/src/hotspot/cpu/x86/x86.ad index aed54fe93d4..0ffa4c2031c 100644 --- a/src/hotspot/cpu/x86/x86.ad +++ b/src/hotspot/cpu/x86/x86.ad @@ -5187,6 +5187,18 @@ operand immL_65535() interface(CONST_INTER); %} +// AOT Runtime Constants Address +operand immAOTRuntimeConstantsAddress() +%{ + // Check if the address is in the range of AOT Runtime Constants + predicate(AOTRuntimeConstants::contains((address)(n->get_ptr()))); + match(ConP); + + op_cost(0); + format %{ %} + interface(CONST_INTER); +%} + operand kReg() %{ constraint(ALLOC_IN_RC(vectmask_reg)); @@ -7332,6 +7344,19 @@ instruct loadD(regD dst, memory mem) ins_pipe(pipe_slow); // XXX %} +instruct loadAOTRCAddress(rRegP dst, immAOTRuntimeConstantsAddress con) +%{ + match(Set dst con); + + format %{ "leaq $dst, $con\t# AOT Runtime Constants Address" %} + + ins_encode %{ + __ load_aotrc_address($dst$$Register, (address)$con$$constant); + %} + + ins_pipe(ialu_reg_fat); +%} + // max = java.lang.Math.max(float a, float b) instruct maxF_reg_avx10_2(regF dst, regF a, regF b) %{ predicate(VM_Version::supports_avx10_2()); diff --git a/src/hotspot/share/adlc/main.cpp b/src/hotspot/share/adlc/main.cpp index 4e8a96617e8..8e6ea5bbec9 100644 --- a/src/hotspot/share/adlc/main.cpp +++ b/src/hotspot/share/adlc/main.cpp @@ -213,6 +213,7 @@ int main(int argc, char *argv[]) AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._VM_file._name)); AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._HPP_file._name)); AD.addInclude(AD._CPP_file, "memory/allocation.inline.hpp"); + AD.addInclude(AD._CPP_file, "code/aotCodeCache.hpp"); AD.addInclude(AD._CPP_file, "code/codeCache.hpp"); AD.addInclude(AD._CPP_file, "code/compiledIC.hpp"); AD.addInclude(AD._CPP_file, "code/nativeInst.hpp"); @@ -257,6 +258,7 @@ int main(int argc, char *argv[]) AD.addInclude(AD._CPP_PEEPHOLE_file, "adfiles", get_basename(AD._HPP_file._name)); AD.addInclude(AD._CPP_PIPELINE_file, "adfiles", get_basename(AD._HPP_file._name)); AD.addInclude(AD._DFA_file, "adfiles", get_basename(AD._HPP_file._name)); + AD.addInclude(AD._DFA_file, "code/aotCodeCache.hpp"); AD.addInclude(AD._DFA_file, "oops/compressedOops.hpp"); AD.addInclude(AD._DFA_file, "opto/cfgnode.hpp"); // Use PROB_MAX in predicate. AD.addInclude(AD._DFA_file, "opto/intrinsicnode.hpp"); diff --git a/src/hotspot/share/code/aotCodeCache.cpp b/src/hotspot/share/code/aotCodeCache.cpp index 32a53691f3f..e5f68afc51d 100644 --- a/src/hotspot/share/code/aotCodeCache.cpp +++ b/src/hotspot/share/code/aotCodeCache.cpp @@ -29,9 +29,11 @@ #include "cds/cds_globals.hpp" #include "cds/cdsConfig.hpp" #include "cds/heapShared.hpp" +#include "ci/ciUtilities.hpp" #include "classfile/javaAssertions.hpp" #include "code/aotCodeCache.hpp" #include "code/codeCache.hpp" +#include "gc/shared/cardTableBarrierSet.hpp" #include "gc/shared/gcConfig.hpp" #include "logging/logStream.hpp" #include "memory/memoryReserver.hpp" @@ -53,6 +55,7 @@ #endif #if INCLUDE_G1GC #include "gc/g1/g1BarrierSetRuntime.hpp" +#include "gc/g1/g1HeapRegion.hpp" #endif #if INCLUDE_SHENANDOAHGC #include "gc/shenandoah/shenandoahRuntime.hpp" @@ -258,6 +261,9 @@ void AOTCodeCache::init2() { return; } + // initialize aot runtime constants as appropriate to this runtime + AOTRuntimeConstants::initialize_from_runtime(); + // initialize the table of external routines so we can save // generated code blobs that reference them AOTCodeAddressTable* table = opened_cache->_table; @@ -1447,6 +1453,12 @@ void AOTCodeAddressTable::init_extrs() { #endif #endif // ZERO + // addresses of fields in AOT runtime constants area + address* p = AOTRuntimeConstants::field_addresses_list(); + while (*p != nullptr) { + SET_ADDRESS(_extrs, *p++); + } + _extrs_complete = true; log_debug(aot, codecache, init)("External addresses recorded"); } @@ -1729,6 +1741,11 @@ int AOTCodeAddressTable::id_for_address(address addr, RelocIterator reloc, CodeB if (addr == (address)-1) { // Static call stub has jump to itself return id; } + // Check card_table_base address first since it can point to any address + BarrierSet* bs = BarrierSet::barrier_set(); + bool is_const_card_table_base = !UseG1GC && !UseShenandoahGC && bs->is_a(BarrierSet::CardTableBarrierSet); + guarantee(!is_const_card_table_base || addr != ci_card_table_address_const(), "sanity"); + // Seach for C string id = id_for_C_string(addr); if (id >= 0) { @@ -1798,6 +1815,44 @@ int AOTCodeAddressTable::id_for_address(address addr, RelocIterator reloc, CodeB return id; } +AOTRuntimeConstants AOTRuntimeConstants::_aot_runtime_constants; + +void AOTRuntimeConstants::initialize_from_runtime() { + BarrierSet* bs = BarrierSet::barrier_set(); + address card_table_base = nullptr; + uint grain_shift = 0; +#if INCLUDE_G1GC + if (bs->is_a(BarrierSet::G1BarrierSet)) { + grain_shift = G1HeapRegion::LogOfHRGrainBytes; + } else +#endif +#if INCLUDE_SHENANDOAHGC + if (bs->is_a(BarrierSet::ShenandoahBarrierSet)) { + grain_shift = 0; + } else +#endif + if (bs->is_a(BarrierSet::CardTableBarrierSet)) { + CardTable::CardValue* base = ci_card_table_address_const(); + assert(base != nullptr, "unexpected byte_map_base"); + card_table_base = base; + CardTableBarrierSet* ctbs = barrier_set_cast(bs); + grain_shift = ctbs->grain_shift(); + } + _aot_runtime_constants._card_table_base = card_table_base; + _aot_runtime_constants._grain_shift = grain_shift; +} + +address AOTRuntimeConstants::_field_addresses_list[] = { + ((address)&_aot_runtime_constants._card_table_base), + ((address)&_aot_runtime_constants._grain_shift), + nullptr +}; + +address AOTRuntimeConstants::card_table_base_address() { + assert(UseSerialGC || UseParallelGC, "Only these GCs have constant card table base"); + return (address)&_aot_runtime_constants._card_table_base; +} + // This is called after initialize() but before init2() // and _cache is not set yet. void AOTCodeCache::print_on(outputStream* st) { diff --git a/src/hotspot/share/code/aotCodeCache.hpp b/src/hotspot/share/code/aotCodeCache.hpp index 45b4a15510d..85f8b47920f 100644 --- a/src/hotspot/share/code/aotCodeCache.hpp +++ b/src/hotspot/share/code/aotCodeCache.hpp @@ -25,6 +25,7 @@ #ifndef SHARE_CODE_AOTCODECACHE_HPP #define SHARE_CODE_AOTCODECACHE_HPP +#include "gc/shared/gc_globals.hpp" #include "runtime/stubInfo.hpp" /* @@ -422,4 +423,36 @@ public: #endif // PRODUCT }; +// code cache internal runtime constants area used by AOT code +class AOTRuntimeConstants { + friend class AOTCodeCache; + private: + address _card_table_base; + uint _grain_shift; + static address _field_addresses_list[]; + static AOTRuntimeConstants _aot_runtime_constants; + // private constructor for unique singleton + AOTRuntimeConstants() { } + // private for use by friend class AOTCodeCache + static void initialize_from_runtime(); + public: +#if INCLUDE_CDS + static bool contains(address adr) { + address base = (address)&_aot_runtime_constants; + address hi = base + sizeof(AOTRuntimeConstants); + return (base <= adr && adr < hi); + } + static address card_table_base_address(); + static address grain_shift_address() { return (address)&_aot_runtime_constants._grain_shift; } + static address* field_addresses_list() { + return _field_addresses_list; + } +#else + static bool contains(address adr) { return false; } + static address card_table_base_address() { return nullptr; } + static address grain_shift_address() { return nullptr; } + static address* field_addresses_list() { return nullptr; } +#endif +}; + #endif // SHARE_CODE_AOTCODECACHE_HPP diff --git a/src/hotspot/share/gc/g1/g1BarrierSet.hpp b/src/hotspot/share/gc/g1/g1BarrierSet.hpp index 406096acf10..c5c7058471c 100644 --- a/src/hotspot/share/gc/g1/g1BarrierSet.hpp +++ b/src/hotspot/share/gc/g1/g1BarrierSet.hpp @@ -25,6 +25,7 @@ #ifndef SHARE_GC_G1_G1BARRIERSET_HPP #define SHARE_GC_G1_G1BARRIERSET_HPP +#include "gc/g1/g1HeapRegion.hpp" #include "gc/g1/g1SATBMarkQueueSet.hpp" #include "gc/shared/bufferNode.hpp" #include "gc/shared/cardTable.hpp" @@ -116,6 +117,8 @@ class G1BarrierSet: public CardTableBarrierSet { virtual void print_on(outputStream* st) const; + virtual uint grain_shift() { return G1HeapRegion::LogOfHRGrainBytes; } + // Callbacks for runtime accesses. template class AccessBarrier: public CardTableBarrierSet::AccessBarrier { diff --git a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp index 914358760aa..86b74aa5736 100644 --- a/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp +++ b/src/hotspot/share/gc/shared/c1/cardTableBarrierSetC1.cpp @@ -22,6 +22,7 @@ * */ +#include "code/aotCodeCache.hpp" #include "gc/shared/c1/cardTableBarrierSetC1.hpp" #include "gc/shared/cardTable.hpp" #include "gc/shared/cardTableBarrierSet.hpp" @@ -123,6 +124,7 @@ void CardTableBarrierSetC1::post_barrier(LIRAccess& access, LIR_Opr addr, LIR_Op assert(addr->is_register(), "must be a register at this point"); #ifdef CARDTABLEBARRIERSET_POST_BARRIER_HELPER + assert(!AOTCodeCache::is_on(), "this path is not implemented"); gen->CardTableBarrierSet_post_barrier_helper(addr, card_table_base); #else LIR_Opr tmp = gen->new_pointer_register(); @@ -135,6 +137,17 @@ void CardTableBarrierSetC1::post_barrier(LIRAccess& access, LIR_Opr addr, LIR_Op } LIR_Address* card_addr; +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + // load the card table address from the AOT Runtime Constants area + LIR_Opr byte_map_base_adr = LIR_OprFact::intptrConst(AOTRuntimeConstants::card_table_base_address()); + LIR_Opr byte_map_base_reg = gen->new_pointer_register(); + __ move(byte_map_base_adr, byte_map_base_reg); + LIR_Address* byte_map_base_indirect = new LIR_Address(byte_map_base_reg, 0, T_LONG); + __ move(byte_map_base_indirect, byte_map_base_reg); + card_addr = new LIR_Address(tmp, byte_map_base_reg, T_BYTE); + } else +#endif if (gen->can_inline_as_constant(card_table_base)) { card_addr = new LIR_Address(tmp, card_table_base->as_jint(), T_BYTE); } else { diff --git a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp index 42af77ebdf4..f7445ff254f 100644 --- a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp +++ b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.cpp @@ -23,6 +23,7 @@ */ #include "ci/ciUtilities.hpp" +#include "code/aotCodeCache.hpp" #include "gc/shared/c2/cardTableBarrierSetC2.hpp" #include "gc/shared/cardTable.hpp" #include "gc/shared/cardTableBarrierSet.hpp" @@ -114,13 +115,20 @@ Node* CardTableBarrierSetC2::atomic_xchg_at_resolved(C2AtomicParseAccess& access return result; } -Node* CardTableBarrierSetC2::byte_map_base_node(GraphKit* kit) const { +Node* CardTableBarrierSetC2::byte_map_base_node(IdealKit* kit) const { // Get base of card map +#if INCLUDE_CDS + if (AOTCodeCache::is_on_for_dump()) { + // load the card table address from the AOT Runtime Constants area + Node* byte_map_base_adr = kit->makecon(TypeRawPtr::make(AOTRuntimeConstants::card_table_base_address())); + return kit->load_aot_const(byte_map_base_adr, TypeRawPtr::NOTNULL); + } +#endif CardTable::CardValue* card_table_base = ci_card_table_address_const(); if (card_table_base != nullptr) { return kit->makecon(TypeRawPtr::make((address)card_table_base)); } else { - return kit->null(); + return kit->makecon(Type::get_zero_type(T_ADDRESS)); } } @@ -168,7 +176,7 @@ void CardTableBarrierSetC2::post_barrier(GraphKit* kit, Node* card_offset = __ URShiftX(cast, __ ConI(CardTable::card_shift())); // Combine card table base and card offset - Node* card_adr = __ AddP(__ top(), byte_map_base_node(kit), card_offset); + Node* card_adr = __ AddP(__ top(), byte_map_base_node(&ideal), card_offset); // Get the alias_index for raw card-mark memory int adr_type = Compile::AliasIdxRaw; diff --git a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.hpp b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.hpp index 84876808f0d..8f5bae8c6dd 100644 --- a/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.hpp +++ b/src/hotspot/share/gc/shared/c2/cardTableBarrierSetC2.hpp @@ -43,7 +43,7 @@ protected: Node* new_val, const Type* value_type) const; virtual Node* atomic_xchg_at_resolved(C2AtomicParseAccess& access, Node* new_val, const Type* value_type) const; - Node* byte_map_base_node(GraphKit* kit) const; + Node* byte_map_base_node(IdealKit* kit) const; public: virtual void eliminate_gc_barrier(PhaseMacroExpand* macro, Node* node) const; diff --git a/src/hotspot/share/gc/shared/cardTableBarrierSet.hpp b/src/hotspot/share/gc/shared/cardTableBarrierSet.hpp index 3a9b46d9df8..5d355318b21 100644 --- a/src/hotspot/share/gc/shared/cardTableBarrierSet.hpp +++ b/src/hotspot/share/gc/shared/cardTableBarrierSet.hpp @@ -103,6 +103,10 @@ public: virtual void print_on(outputStream* st) const; + // The AOT code cache manager needs to know the region grain size + // shift for some barrier sets. + virtual uint grain_shift() { return 0; } + template class AccessBarrier: public BarrierSet::AccessBarrier { typedef BarrierSet::AccessBarrier Raw; diff --git a/src/hotspot/share/opto/idealKit.cpp b/src/hotspot/share/opto/idealKit.cpp index dd7e9ae52b7..fbb61bfdf72 100644 --- a/src/hotspot/share/opto/idealKit.cpp +++ b/src/hotspot/share/opto/idealKit.cpp @@ -360,6 +360,17 @@ Node* IdealKit::load(Node* ctl, return transform(ld); } +// Load AOT runtime constant +Node* IdealKit::load_aot_const(Node* adr, const Type* t) { + BasicType bt = t->basic_type(); + const TypePtr* adr_type = nullptr; // debug-mode-only argument + DEBUG_ONLY(adr_type = C->get_adr_type(Compile::AliasIdxRaw)); + Node* ctl = (Node*)C->root(); // Raw memory access needs control + Node* ld = LoadNode::make(_gvn, ctl, C->immutable_memory(), adr, adr_type, t, bt, MemNode::unordered, + LoadNode::DependsOnlyOnTest, false, false, false, false, 0); + return transform(ld); +} + Node* IdealKit::store(Node* ctl, Node* adr, Node *val, BasicType bt, int adr_idx, MemNode::MemOrd mo, bool require_atomic_access, diff --git a/src/hotspot/share/opto/idealKit.hpp b/src/hotspot/share/opto/idealKit.hpp index 280f61fd9a9..518c3b92136 100644 --- a/src/hotspot/share/opto/idealKit.hpp +++ b/src/hotspot/share/opto/idealKit.hpp @@ -224,6 +224,9 @@ class IdealKit: public StackObj { MemNode::MemOrd mo = MemNode::unordered, LoadNode::ControlDependency control_dependency = LoadNode::DependsOnlyOnTest); + // Load AOT runtime constant + Node* load_aot_const(Node* adr, const Type* t); + // Return the new StoreXNode Node* store(Node* ctl, Node* adr, diff --git a/src/hotspot/share/opto/type.cpp b/src/hotspot/share/opto/type.cpp index c637737eef9..1a0872ee0e6 100644 --- a/src/hotspot/share/opto/type.cpp +++ b/src/hotspot/share/opto/type.cpp @@ -97,7 +97,7 @@ const Type::TypeInfo Type::_type_info[Type::lastype] = { { Bad, T_ILLEGAL, "vectorz:", false, Op_VecZ, relocInfo::none }, // VectorZ #endif { Bad, T_ADDRESS, "anyptr:", false, Op_RegP, relocInfo::none }, // AnyPtr - { Bad, T_ADDRESS, "rawptr:", false, Op_RegP, relocInfo::none }, // RawPtr + { Bad, T_ADDRESS, "rawptr:", false, Op_RegP, relocInfo::external_word_type }, // RawPtr { Bad, T_OBJECT, "oop:", true, Op_RegP, relocInfo::oop_type }, // OopPtr { Bad, T_OBJECT, "inst:", true, Op_RegP, relocInfo::oop_type }, // InstPtr { Bad, T_OBJECT, "ary:", true, Op_RegP, relocInfo::oop_type }, // AryPtr From b0318fee71926b424e770ff1c85add0d96cc85c0 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Fri, 27 Feb 2026 22:24:02 +0000 Subject: [PATCH 49/54] 8378865: After fix for JDK-8378385 two tests are failing on windows Reviewed-by: kizune --- .../Dialog/CloseDialog/CloseDialogTest.java | 119 ---------------- .../DisplayChangesException.java | 133 ------------------ 2 files changed, 252 deletions(-) delete mode 100644 test/jdk/java/awt/Dialog/CloseDialog/CloseDialogTest.java delete mode 100644 test/jdk/java/awt/Toolkit/DisplayChangesException/DisplayChangesException.java diff --git a/test/jdk/java/awt/Dialog/CloseDialog/CloseDialogTest.java b/test/jdk/java/awt/Dialog/CloseDialog/CloseDialogTest.java deleted file mode 100644 index 1201e5c835c..00000000000 --- a/test/jdk/java/awt/Dialog/CloseDialog/CloseDialogTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. - * 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.awt.Dialog; -import java.awt.Frame; -import java.io.*; -import javax.swing.*; -import sun.awt.SunToolkit; -import java.util.concurrent.atomic.AtomicReference; - -/** - * @test - * @key headful - * @bug 8043705 - * @summary Can't exit color chooser dialog when running in non-default AppContext - * @modules java.desktop/sun.awt - * @run main CloseDialogTest - */ - -public class CloseDialogTest { - - private static volatile Frame frame; - private static volatile Dialog dialog; - private static volatile InputStream testErrorStream; - private static final PrintStream systemErrStream = System.err; - private static final AtomicReference caughtException - = new AtomicReference<>(); - - public static void main(String[] args) throws Exception { - - // redirect System err - PipedOutputStream errorOutputStream = new PipedOutputStream(); - testErrorStream = new PipedInputStream(errorOutputStream); - System.setErr(new PrintStream(errorOutputStream)); - - ThreadGroup swingTG = new ThreadGroup(getRootThreadGroup(), "SwingTG"); - try { - new Thread(swingTG, () -> { - SunToolkit.createNewAppContext(); - SwingUtilities.invokeLater(() -> { - frame = new Frame(); - frame.setSize(300, 300); - frame.setVisible(true); - - dialog = new Dialog(frame); - dialog.setSize(200, 200); - dialog.setModal(true); - dialog.setVisible(true); - }); - }).start(); - - Thread.sleep(400); - - Thread disposeThread = new Thread(swingTG, () -> - SwingUtilities.invokeLater(() -> { - try { - while (dialog == null || !dialog.isVisible()) { - Thread.sleep(100); - } - dialog.setVisible(false); - dialog.dispose(); - frame.dispose(); - } catch (Exception e) { - caughtException.set(e); - } - })); - disposeThread.start(); - disposeThread.join(); - Thread.sleep(500); - - // read System err - final char[] buffer = new char[2048]; - System.err.print("END"); - System.setErr(systemErrStream); - try (Reader in = new InputStreamReader(testErrorStream, "UTF-8")) { - int size = in.read(buffer, 0, buffer.length); - String errorString = new String(buffer, 0, size); - if (!errorString.startsWith("END")) { - System.err.println(errorString. - substring(0, errorString.length() - 4)); - throw new RuntimeException("Error output is not empty!"); - } - } - } finally { - if (caughtException.get() != null) { - throw new RuntimeException("Failed. Caught exception!", - caughtException.get()); - } - } - } - - private static ThreadGroup getRootThreadGroup() { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - while (threadGroup.getParent() != null) { - threadGroup = threadGroup.getParent(); - } - return threadGroup; - } -} diff --git a/test/jdk/java/awt/Toolkit/DisplayChangesException/DisplayChangesException.java b/test/jdk/java/awt/Toolkit/DisplayChangesException/DisplayChangesException.java deleted file mode 100644 index 0f13265ac58..00000000000 --- a/test/jdk/java/awt/Toolkit/DisplayChangesException/DisplayChangesException.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.awt.EventQueue; -import java.awt.GraphicsEnvironment; -import java.awt.Toolkit; -import java.lang.reflect.Method; -import java.util.concurrent.CountDownLatch; - -import javax.swing.JButton; -import javax.swing.JFrame; - -import sun.awt.DisplayChangedListener; -import sun.awt.SunToolkit; - -/** - * @test - * @key headful - * @bug 8207070 - * @modules java.desktop/sun.java2d - * java.desktop/sun.awt - * java.desktop/sun.awt.windows:open - */ -public final class DisplayChangesException { - - private static boolean fail; - private static CountDownLatch go = new CountDownLatch(1); - - static final class TestThread extends Thread { - - private JFrame frame; - - private TestThread(ThreadGroup tg, String threadName) { - super(tg, threadName); - } - - public void run() { - try { - test(); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - private void test() throws Exception { - SunToolkit.createNewAppContext(); - EventQueue.invokeAndWait(() -> { - frame = new JFrame(); - final JButton b = new JButton(); - b.addPropertyChangeListener(evt -> { - if (!SunToolkit.isDispatchThreadForAppContext(b)) { - System.err.println("Wrong thread:" + currentThread()); - fail = true; - } - }); - frame.add(b); - frame.setSize(100, 100); - frame.setLocationRelativeTo(null); - frame.pack(); - }); - go.await(); - EventQueue.invokeAndWait(() -> { - frame.dispose(); - }); - } - } - - public static void main(final String[] args) throws Exception { - ThreadGroup tg0 = new ThreadGroup("ThreadGroup0"); - ThreadGroup tg1 = new ThreadGroup("ThreadGroup1"); - - TestThread t0 = new TestThread(tg0, "TestThread 0"); - TestThread t1 = new TestThread(tg1, "TestThread 1"); - - t0.start(); - t1.start(); - Thread.sleep(1500); // Cannot use Robot.waitForIdle - testToolkit(); - Thread.sleep(1500); - testGE(); - Thread.sleep(1500); - go.countDown(); - - if (fail) { - throw new RuntimeException(); - } - } - - private static void testGE() { - Object ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - if (!(ge instanceof DisplayChangedListener)) { - return; - } - ((DisplayChangedListener) ge).displayChanged(); - } - - private static void testToolkit() { - final Class toolkit; - try { - toolkit = Class.forName("sun.awt.windows.WToolkit"); - } catch (final ClassNotFoundException ignored) { - return; - } - try { - final Method displayChanged = toolkit.getMethod("displayChanged"); - displayChanged.invoke(Toolkit.getDefaultToolkit()); - } catch (final Exception e) { - e.printStackTrace(); - fail = true; - } - } -} - From 58a7ccfca41bf06f6da98ff8b8d58c4ff0f16551 Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Fri, 27 Feb 2026 23:13:19 +0000 Subject: [PATCH 50/54] 8378798: Test tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java failed: missing IOException Reviewed-by: almatvee --- .../jdk/jpackage/internal/util/CommandOutputControlTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java index d71cf7c4d41..b179f32447f 100644 --- a/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java +++ b/test/jdk/tools/jpackage/junit/share/jdk.jpackage/jdk/jpackage/internal/util/CommandOutputControlTest.java @@ -458,7 +458,7 @@ public class CommandOutputControlTest { processDestroyer.get().join(); } - @DisabledOnOs(value = OS.MAC, disabledReason = "Closing a stream doesn't consistently cause a trouble as it should") + @DisabledOnOs(value = {OS.MAC, OS.LINUX}, disabledReason = "Closing a stream doesn't consistently cause a trouble as expected") @ParameterizedTest @EnumSource(OutputStreams.class) public void test_close_streams(OutputStreams action) throws InterruptedException, IOException { From e5aac0961d53611fee57333c0a959e3d5b42ede8 Mon Sep 17 00:00:00 2001 From: Dingli Zhang Date: Sat, 28 Feb 2026 00:33:11 +0000 Subject: [PATCH 51/54] 8378752: Enable some subword vector casts IR matching tests for RISC-V Reviewed-by: fyang, jkarthikeyan --- .../TestCompatibleUseDefTypeSize.java | 28 ++++----- .../loopopts/superword/TestReductions.java | 60 +++++++++---------- .../vectorization/TestSubwordTruncation.java | 16 ++--- 3 files changed, 52 insertions(+), 52 deletions(-) diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java index 7399a1ec411..873533aaba8 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestCompatibleUseDefTypeSize.java @@ -514,7 +514,7 @@ public class TestCompatibleUseDefTypeSize { // Narrowing @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", ">0" }) public Object[] testIntToShort(int[] ints, short[] res) { @@ -527,7 +527,7 @@ public class TestCompatibleUseDefTypeSize { @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_I2S, IRNode.VECTOR_SIZE + "min(max_int, max_char)", ">0" }) public Object[] testIntToChar(int[] ints, char[] res) { @@ -539,7 +539,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_I2B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", ">0" }) public Object[] testIntToByte(int[] ints, byte[] res) { @@ -551,7 +551,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_S2B, IRNode.VECTOR_SIZE + "min(max_short, max_byte)", ">0" }) public Object[] testShortToByte(short[] shorts, byte[] res) { @@ -575,7 +575,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_L2S, IRNode.VECTOR_SIZE + "min(max_long, max_short)", ">0" }) public Object[] testLongToShort(long[] longs, short[] res) { @@ -587,7 +587,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_L2S, IRNode.VECTOR_SIZE + "min(max_long, max_char)", ">0" }) public Object[] testLongToChar(long[] longs, char[] res) { @@ -599,7 +599,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_L2I, IRNode.VECTOR_SIZE + "min(max_long, max_int)", ">0" }) public Object[] testLongToInt(long[] longs, int[] res) { @@ -611,7 +611,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.STORE_VECTOR, ">0" }) public Object[] testShortToChar(short[] shorts, char[] res) { @@ -625,7 +625,7 @@ public class TestCompatibleUseDefTypeSize { // Widening @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_S2I, IRNode.VECTOR_SIZE + "min(max_short, max_int)", ">0" }) public Object[] testShortToInt(short[] shorts, int[] res) { @@ -637,7 +637,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_B2I, IRNode.VECTOR_SIZE + "min(max_byte, max_int)", ">0" }) public Object[] testByteToInt(byte[] bytes, int[] res) { @@ -649,7 +649,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_B2S, IRNode.VECTOR_SIZE + "min(max_byte, max_short)", ">0" }) public Object[] testByteToShort(byte[] bytes, short[] res) { @@ -661,7 +661,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_B2S, IRNode.VECTOR_SIZE + "min(max_byte, max_char)", ">0" }) public Object[] testByteToChar(byte[] bytes, char[] res) { @@ -685,7 +685,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_S2L, IRNode.VECTOR_SIZE + "min(max_short, max_long)", ">0" }) public Object[] testShortToLong(short[] shorts, long[] res) { @@ -697,7 +697,7 @@ public class TestCompatibleUseDefTypeSize { } @Test - @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true" }, + @IR(applyIfCPUFeatureOr = { "avx", "true", "asimd", "true", "rvv", "true" }, applyIfOr = {"AlignVector", "false", "UseCompactObjectHeaders", "false"}, counts = { IRNode.VECTOR_CAST_I2L, IRNode.VECTOR_SIZE + "min(max_int, max_long)", ">0" }) public Object[] testIntToLong(int[] ints, long[] res) { diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java index e0f44bcdb3b..9d674950499 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestReductions.java @@ -458,7 +458,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -475,7 +475,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -492,7 +492,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -531,7 +531,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -548,7 +548,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -566,7 +566,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -583,7 +583,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -600,7 +600,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -639,7 +639,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -656,7 +656,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -674,7 +674,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -691,7 +691,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -708,7 +708,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -747,7 +747,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -764,7 +764,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_B, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1016,7 +1016,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1033,7 +1033,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1050,7 +1050,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1089,7 +1089,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1106,7 +1106,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1124,7 +1124,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1141,7 +1141,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1158,7 +1158,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1197,7 +1197,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1214,7 +1214,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1232,7 +1232,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.AND_REDUCTION_V, "> 0", IRNode.AND_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1249,7 +1249,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.OR_REDUCTION_V, "> 0", IRNode.OR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1266,7 +1266,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.XOR_REDUCTION_V, "> 0", IRNode.XOR_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1305,7 +1305,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MIN_REDUCTION_V, "> 0", IRNode.MIN_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) @@ -1322,7 +1322,7 @@ public class TestReductions { @IR(counts = {IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0", IRNode.MAX_REDUCTION_V, "> 0", IRNode.MAX_VI, "> 0"}, - applyIfCPUFeatureOr = {"avx", "true", "asimd", "true"}, + applyIfCPUFeatureOr = {"avx", "true", "asimd", "true", "rvv", "true"}, applyIf = {"AutoVectorizationOverrideProfitability", "> 0"}) @IR(failOn = IRNode.LOAD_VECTOR_S, applyIf = {"AutoVectorizationOverrideProfitability", "= 0"}) diff --git a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java index 29331cc1845..2f6296e41d2 100644 --- a/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java +++ b/test/hotspot/jtreg/compiler/vectorization/TestSubwordTruncation.java @@ -74,7 +74,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupShortArray") public Object[] testShortLeadingZeros(short[] in) { short[] res = new short[SIZE]; @@ -100,7 +100,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupShortArray") public Object[] testShortTrailingZeros(short[] in) { short[] res = new short[SIZE]; @@ -126,7 +126,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupShortArray") public Object[] testShortReverse(short[] in) { short[] res = new short[SIZE]; @@ -152,7 +152,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_S, IRNode.VECTOR_SIZE + "min(max_int, max_short)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupShortArray") public Object[] testShortBitCount(short[] in) { short[] res = new short[SIZE]; @@ -282,7 +282,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupByteArray") public Object[] testByteLeadingZeros(byte[] in) { byte[] res = new byte[SIZE]; @@ -308,7 +308,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupByteArray") public Object[] testByteTrailingZeros(byte[] in) { byte[] res = new byte[SIZE]; @@ -334,7 +334,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupByteArray") public Object[] testByteReverse(byte[] in) { byte[] res = new byte[SIZE]; @@ -411,7 +411,7 @@ public class TestSubwordTruncation { @Test @IR(counts = { IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_int, max_byte)", "> 0" }, - applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true" }) + applyIfCPUFeatureOr = { "avx2", "true", "asimd", "true", "zvbb", "true" }) @Arguments(setup = "setupByteArray") public Object[] testByteBitCount(byte[] in) { byte[] res = new byte[SIZE]; From 357f29dc864552a2c41e61b18ea73d9dda1c9825 Mon Sep 17 00:00:00 2001 From: Yasumasa Suenaga Date: Sat, 28 Feb 2026 03:28:47 +0000 Subject: [PATCH 52/54] 8378312: [VectorAPI] libraryUnaryOp/libraryBinaryOp failed to intrinsify Reviewed-by: psandoz, sherman --- src/hotspot/share/classfile/vmIntrinsics.hpp | 4 +- .../jdk/internal/vm/vector/VectorSupport.java | 4 +- .../jdk/incubator/vector/DoubleVector.java | 4 +- .../jdk/incubator/vector/FloatVector.java | 4 +- .../incubator/vector/VectorMathLibrary.java | 10 +-- .../compiler/lib/ir_framework/IRNode.java | 6 ++ .../TestVectorLibraryUnaryOpAndBinaryOp.java | 62 +++++++++++++++++++ 7 files changed, 81 insertions(+), 13 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/vectorapi/TestVectorLibraryUnaryOpAndBinaryOp.java diff --git a/src/hotspot/share/classfile/vmIntrinsics.hpp b/src/hotspot/share/classfile/vmIntrinsics.hpp index 29cb5d737d8..67817682ced 100644 --- a/src/hotspot/share/classfile/vmIntrinsics.hpp +++ b/src/hotspot/share/classfile/vmIntrinsics.hpp @@ -1029,7 +1029,7 @@ class methodHandle; do_intrinsic(_VectorUnaryLibOp, jdk_internal_vm_vector_VectorSupport, vector_unary_lib_op_name, vector_unary_lib_op_sig, F_S) \ do_signature(vector_unary_lib_op_sig,"(J" \ "Ljava/lang/Class;" \ - "Ljava/lang/Class;" \ + "I" \ "I" \ "Ljava/lang/String;" \ "Ljdk/internal/vm/vector/VectorSupport$Vector;" \ @@ -1040,7 +1040,7 @@ class methodHandle; do_intrinsic(_VectorBinaryLibOp, jdk_internal_vm_vector_VectorSupport, vector_binary_lib_op_name, vector_binary_lib_op_sig, F_S) \ do_signature(vector_binary_lib_op_sig,"(J" \ "Ljava/lang/Class;" \ - "Ljava/lang/Class;" \ + "I" \ "I" \ "Ljava/lang/String;" \ "Ljdk/internal/vm/vector/VectorSupport$VectorPayload;" \ diff --git a/src/java.base/share/classes/jdk/internal/vm/vector/VectorSupport.java b/src/java.base/share/classes/jdk/internal/vm/vector/VectorSupport.java index 03f95222a52..23a787971c0 100644 --- a/src/java.base/share/classes/jdk/internal/vm/vector/VectorSupport.java +++ b/src/java.base/share/classes/jdk/internal/vm/vector/VectorSupport.java @@ -336,7 +336,7 @@ public class VectorSupport { @IntrinsicCandidate public static , E> - V libraryUnaryOp(long addr, Class vClass, Class eClass, int length, String debugName, + V libraryUnaryOp(long addr, Class vClass, int laneType, int length, String debugName, V v, UnaryOperation defaultImpl) { assert isNonCapturingLambda(defaultImpl) : defaultImpl; @@ -374,7 +374,7 @@ public class VectorSupport { @IntrinsicCandidate public static - V libraryBinaryOp(long addr, Class vClass, Class eClass, int length, String debugName, + V libraryBinaryOp(long addr, Class vClass, int laneType, int length, String debugName, V v1, V v2, BinaryOperation defaultImpl) { assert isNonCapturingLambda(defaultImpl) : defaultImpl; diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/DoubleVector.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/DoubleVector.java index 519122b4d28..5e7c97dc56d 100644 --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/DoubleVector.java +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/DoubleVector.java @@ -724,7 +724,7 @@ public abstract class DoubleVector extends AbstractVector { @ForceInline final DoubleVector unaryMathOp(VectorOperators.Unary op) { - return VectorMathLibrary.unaryMathOp(op, opCode(op), species(), DoubleVector::unaryOperations, + return VectorMathLibrary.unaryMathOp(op, opCode(op), vspecies(), DoubleVector::unaryOperations, this); } @@ -851,7 +851,7 @@ public abstract class DoubleVector extends AbstractVector { @ForceInline final DoubleVector binaryMathOp(VectorOperators.Binary op, DoubleVector that) { - return VectorMathLibrary.binaryMathOp(op, opCode(op), species(), DoubleVector::binaryOperations, + return VectorMathLibrary.binaryMathOp(op, opCode(op), vspecies(), DoubleVector::binaryOperations, this, that); } diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/FloatVector.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/FloatVector.java index 9950abf696d..5862a295fa3 100644 --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/FloatVector.java +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/FloatVector.java @@ -724,7 +724,7 @@ public abstract class FloatVector extends AbstractVector { @ForceInline final FloatVector unaryMathOp(VectorOperators.Unary op) { - return VectorMathLibrary.unaryMathOp(op, opCode(op), species(), FloatVector::unaryOperations, + return VectorMathLibrary.unaryMathOp(op, opCode(op), vspecies(), FloatVector::unaryOperations, this); } @@ -851,7 +851,7 @@ public abstract class FloatVector extends AbstractVector { @ForceInline final FloatVector binaryMathOp(VectorOperators.Binary op, FloatVector that) { - return VectorMathLibrary.binaryMathOp(op, opCode(op), species(), FloatVector::binaryOperations, + return VectorMathLibrary.binaryMathOp(op, opCode(op), vspecies(), FloatVector::binaryOperations, this, that); } diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorMathLibrary.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorMathLibrary.java index 4898cb70884..1c1cfcc78c7 100644 --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorMathLibrary.java +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorMathLibrary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 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 @@ -283,7 +283,7 @@ import static jdk.internal.vm.vector.Utils.debug; @ForceInline /*package-private*/ static > - V unaryMathOp(Unary op, int opc, VectorSpecies vspecies, + V unaryMathOp(Unary op, int opc, AbstractSpecies vspecies, IntFunction> implSupplier, V v) { var entry = lookup(op, opc, vspecies, implSupplier); @@ -293,7 +293,7 @@ import static jdk.internal.vm.vector.Utils.debug; @SuppressWarnings({"unchecked"}) Class vt = (Class)vspecies.vectorType(); return VectorSupport.libraryUnaryOp( - entry.entry.address(), vt, vspecies.elementType(), vspecies.length(), entry.name, + entry.entry.address(), vt, vspecies.laneTypeOrdinal(), vspecies.length(), entry.name, v, entry.impl); } else { @@ -304,7 +304,7 @@ import static jdk.internal.vm.vector.Utils.debug; @ForceInline /*package-private*/ static > - V binaryMathOp(Binary op, int opc, VectorSpecies vspecies, + V binaryMathOp(Binary op, int opc, AbstractSpecies vspecies, IntFunction> implSupplier, V v1, V v2) { var entry = lookup(op, opc, vspecies, implSupplier); @@ -314,7 +314,7 @@ import static jdk.internal.vm.vector.Utils.debug; @SuppressWarnings({"unchecked"}) Class vt = (Class)vspecies.vectorType(); return VectorSupport.libraryBinaryOp( - entry.entry.address(), vt, vspecies.elementType(), vspecies.length(), entry.name, + entry.entry.address(), vt, vspecies.laneTypeOrdinal(), vspecies.length(), entry.name, v1, v2, entry.impl); } else { diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java index c31ce198644..3508c06ad0a 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java @@ -1488,6 +1488,12 @@ public class IRNode { beforeMatchingNameRegex(VECTOR_MASK_FIRST_TRUE, "VectorMaskFirstTrue"); } + // Can only be used if libjsvml or libsleef is available + public static final String CALL_LEAF_VECTOR = PREFIX + "CALL_LEAF_VECTOR" + POSTFIX; + static { + beforeMatchingNameRegex(CALL_LEAF_VECTOR, "CallLeafVector"); + } + // Can only be used if avx512_vnni is available. public static final String MUL_ADD_VS2VI_VNNI = PREFIX + "MUL_ADD_VS2VI_VNNI" + POSTFIX; static { diff --git a/test/hotspot/jtreg/compiler/vectorapi/TestVectorLibraryUnaryOpAndBinaryOp.java b/test/hotspot/jtreg/compiler/vectorapi/TestVectorLibraryUnaryOpAndBinaryOp.java new file mode 100644 index 00000000000..f7837e1abfa --- /dev/null +++ b/test/hotspot/jtreg/compiler/vectorapi/TestVectorLibraryUnaryOpAndBinaryOp.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2026, NTT DATA + * 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.vectorapi; + +import compiler.lib.ir_framework.*; +import jdk.incubator.vector.*; + +/** + * @test + * @bug 8378312 + * @library /test/lib / + * @summary VectorAPI: libraryUnaryOp and libraryBinaryOp should be intrinsified. + * @modules jdk.incubator.vector + * + * @run driver compiler.vectorapi.TestVectorLibraryUnaryOpAndBinaryOp + */ + +public class TestVectorLibraryUnaryOpAndBinaryOp { + + @Test + @IR(counts = { IRNode.CALL_LEAF_VECTOR, "= 1" }, applyIfCPUFeatureOr = { "asimd", "true", "avx", "true" }) + public static void testUnary() { + var vec = FloatVector.broadcast(FloatVector.SPECIES_128, 3.14f); + vec.lanewise(VectorOperators.COS); + } + + @Test + @IR(counts = { IRNode.CALL_LEAF_VECTOR, "= 1" }, applyIfCPUFeatureOr = { "asimd", "true", "avx", "true" }) + public static void testBinary() { + var vec = FloatVector.broadcast(FloatVector.SPECIES_128, 2.0f); + vec.lanewise(VectorOperators.HYPOT, 1.0f); + } + + public static void main(String[] args) { + TestFramework testFramework = new TestFramework(); + testFramework.addFlags("--add-modules=jdk.incubator.vector") + .start(); + } + +} From 20ac1b182eef2af02d017f9e7724fabd60724a33 Mon Sep 17 00:00:00 2001 From: Ashutosh Mehra Date: Sat, 28 Feb 2026 04:33:20 +0000 Subject: [PATCH 53/54] 8378871: CPU feature flags are not properly set in vm_version_windows_aarch64.cpp Reviewed-by: kvn --- .../vm_version_windows_aarch64.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/hotspot/os_cpu/windows_aarch64/vm_version_windows_aarch64.cpp b/src/hotspot/os_cpu/windows_aarch64/vm_version_windows_aarch64.cpp index a20feadcba4..93beb549366 100644 --- a/src/hotspot/os_cpu/windows_aarch64/vm_version_windows_aarch64.cpp +++ b/src/hotspot/os_cpu/windows_aarch64/vm_version_windows_aarch64.cpp @@ -27,22 +27,30 @@ #include "runtime/vm_version.hpp" int VM_Version::get_current_sve_vector_length() { - assert(_features & CPU_SVE, "should not call this"); + assert(VM_Version::supports_sve(), "should not call this"); ShouldNotReachHere(); return 0; } int VM_Version::set_and_get_current_sve_vector_length(int length) { - assert(_features & CPU_SVE, "should not call this"); + assert(VM_Version::supports_sve(), "should not call this"); ShouldNotReachHere(); return 0; } void VM_Version::get_os_cpu_info() { - if (IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE)) _features |= CPU_CRC32; - if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) _features |= CPU_AES | CPU_SHA1 | CPU_SHA2; - if (IsProcessorFeaturePresent(PF_ARM_VFP_32_REGISTERS_AVAILABLE)) _features |= CPU_ASIMD; + if (IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE)) { + set_feature(CPU_CRC32); + } + if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) { + set_feature(CPU_AES); + set_feature(CPU_SHA1); + set_feature(CPU_SHA2); + } + if (IsProcessorFeaturePresent(PF_ARM_VFP_32_REGISTERS_AVAILABLE)) { + set_feature(CPU_ASIMD); + } // No check for CPU_PMULL, CPU_SVE, CPU_SVE2 __int64 dczid_el0 = _ReadStatusReg(0x5807 /* ARM64_DCZID_EL0 */); From d62b9f78ca4a35bb6c5f665172c7abce4dac56ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eirik=20Bj=C3=B8rsn=C3=B8s?= Date: Sat, 28 Feb 2026 05:41:32 +0000 Subject: [PATCH 54/54] 8377992: (zipfs) Align ZipFileSystem END header validation with the ZipFile implementation Reviewed-by: lancea --- .../share/classes/java/util/zip/ZipFile.java | 16 +- .../classes/jdk/nio/zipfs/ZipFileSystem.java | 40 ++- .../util/zip/ZipFile/EndOfCenValidation.java | 279 ++---------------- .../jdk/jdk/nio/zipfs/EndOfCenValidation.java | 150 ++++++++++ test/lib/jdk/test/lib/util/ZipUtils.java | 247 ++++++++++++++++ 5 files changed, 464 insertions(+), 268 deletions(-) create mode 100644 test/jdk/jdk/nio/zipfs/EndOfCenValidation.java create mode 100644 test/lib/jdk/test/lib/util/ZipUtils.java diff --git a/src/java.base/share/classes/java/util/zip/ZipFile.java b/src/java.base/share/classes/java/util/zip/ZipFile.java index 43a3b37b7d0..140d76c8c91 100644 --- a/src/java.base/share/classes/java/util/zip/ZipFile.java +++ b/src/java.base/share/classes/java/util/zip/ZipFile.java @@ -1719,8 +1719,10 @@ public class ZipFile implements ZipConstants, Closeable { this.cen = null; return; // only END header present } - if (end.cenlen > end.endpos) + // Validate END header + if (end.cenlen > end.endpos) { zerror("invalid END header (bad central directory size)"); + } long cenpos = end.endpos - end.cenlen; // position of CEN table // Get position of first local file (LOC) header, taking into // account that there may be a stub prefixed to the ZIP file. @@ -1728,18 +1730,22 @@ public class ZipFile implements ZipConstants, Closeable { if (locpos < 0) { zerror("invalid END header (bad central directory offset)"); } - // read in the CEN if (end.cenlen > MAX_CEN_SIZE) { zerror("invalid END header (central directory size too large)"); } if (end.centot < 0 || end.centot > end.cenlen / CENHDR) { zerror("invalid END header (total entries count too large)"); } - cen = this.cen = new byte[(int)end.cenlen]; - if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen) { + // Validation ensures these are <= Integer.MAX_VALUE + int cenlen = Math.toIntExact(end.cenlen); + int centot = Math.toIntExact(end.centot); + + // read in the CEN + cen = this.cen = new byte[cenlen]; + if (readFullyAt(cen, 0, cen.length, cenpos) != cenlen) { zerror("read CEN tables failed"); } - this.total = Math.toIntExact(end.centot); + this.total = centot; } else { cen = this.cen; this.total = knownTotal; diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java index b3db11eb1fe..3223ff9dccd 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -105,6 +105,9 @@ class ZipFileSystem extends FileSystem { private static final String COMPRESSION_METHOD_DEFLATED = "DEFLATED"; // Value specified for compressionMethod property to not compress Zip entries private static final String COMPRESSION_METHOD_STORED = "STORED"; + // CEN size is limited to the maximum array size in the JDK + // See ArraysSupport.SOFT_MAX_ARRAY_LENGTH; + private static final int MAX_CEN_SIZE = Integer.MAX_VALUE - 8; private final ZipFileSystemProvider provider; private final Path zfpath; @@ -1353,7 +1356,7 @@ class ZipFileSystem extends FileSystem { // to use the end64 values end.cenlen = cenlen64; end.cenoff = cenoff64; - end.centot = (int)centot64; // assume total < 2g + end.centot = centot64; end.endpos = end64pos; return end; } @@ -1575,23 +1578,34 @@ class ZipFileSystem extends FileSystem { buildNodeTree(); return null; // only END header present } - if (end.cenlen > end.endpos) - throw new ZipException("invalid END header (bad central directory size)"); + // Validate END header + if (end.cenlen > end.endpos) { + zerror("invalid END header (bad central directory size)"); + } long cenpos = end.endpos - end.cenlen; // position of CEN table - // Get position of first local file (LOC) header, taking into - // account that there may be a stub prefixed to the zip file. + // account that there may be a stub prefixed to the ZIP file. locpos = cenpos - end.cenoff; - if (locpos < 0) - throw new ZipException("invalid END header (bad central directory offset)"); + if (locpos < 0) { + zerror("invalid END header (bad central directory offset)"); + } + if (end.cenlen > MAX_CEN_SIZE) { + zerror("invalid END header (central directory size too large)"); + } + if (end.centot < 0 || end.centot > end.cenlen / CENHDR) { + zerror("invalid END header (total entries count too large)"); + } + // Validation ensures these are <= Integer.MAX_VALUE + int cenlen = Math.toIntExact(end.cenlen); + int centot = Math.toIntExact(end.centot); // read in the CEN - byte[] cen = new byte[(int)(end.cenlen)]; - if (readNBytesAt(cen, 0, cen.length, cenpos) != end.cenlen) { - throw new ZipException("read CEN tables failed"); + byte[] cen = new byte[cenlen]; + if (readNBytesAt(cen, 0, cen.length, cenpos) != cenlen) { + zerror("read CEN tables failed"); } // Iterate through the entries in the central directory - inodes = LinkedHashMap.newLinkedHashMap(end.centot + 1); + inodes = LinkedHashMap.newLinkedHashMap(centot + 1); int pos = 0; int limit = cen.length; while (pos < limit) { @@ -2666,7 +2680,7 @@ class ZipFileSystem extends FileSystem { // int disknum; // int sdisknum; // int endsub; - int centot; // 4 bytes + long centot; // 4 bytes long cenlen; // 4 bytes long cenoff; // 4 bytes // int comlen; // comment length @@ -2689,7 +2703,7 @@ class ZipFileSystem extends FileSystem { xoff = ZIP64_MINVAL; hasZip64 = true; } - int count = centot; + int count = Math.toIntExact(centot); if (count >= ZIP64_MINVAL32) { count = ZIP64_MINVAL32; hasZip64 = true; diff --git a/test/jdk/java/util/zip/ZipFile/EndOfCenValidation.java b/test/jdk/java/util/zip/ZipFile/EndOfCenValidation.java index 7adcfb9c128..7ca71c9890a 100644 --- a/test/jdk/java/util/zip/ZipFile/EndOfCenValidation.java +++ b/test/jdk/java/util/zip/ZipFile/EndOfCenValidation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 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 @@ -25,33 +25,26 @@ * @bug 8272746 * @modules java.base/jdk.internal.util * @summary Verify that ZipFile rejects files with CEN sizes exceeding the implementation limit + * @library /test/lib + * @build jdk.test.lib.util.ZipUtils * @run junit/othervm EndOfCenValidation */ import jdk.internal.util.ArraysSupport; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.io.*; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.FileChannel; -import java.nio.charset.StandardCharsets; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.HexFormat; -import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; -import static org.junit.jupiter.api.Assertions.*; +import static jdk.test.lib.util.ZipUtils.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * This test augments {@link TestTooManyEntries}. It creates sparse ZIPs where @@ -65,36 +58,13 @@ import static org.junit.jupiter.api.Assertions.*; public class EndOfCenValidation { // Zip files produced by this test - public static final Path CEN_TOO_LARGE_ZIP = Path.of("cen-size-too-large.zip"); - public static final Path INVALID_CEN_SIZE = Path.of("invalid-zen-size.zip"); - public static final Path BAD_CEN_OFFSET_ZIP = Path.of("bad-cen-offset.zip"); - // Some ZipFile constants for manipulating the 'End of central directory record' (END header) - private static final int ENDHDR = ZipFile.ENDHDR; // End of central directory record size - private static final int ENDSIZ = ZipFile.ENDSIZ; // Offset of CEN size field within ENDHDR - private static final int ENDOFF = ZipFile.ENDOFF; // Offset of CEN offset field within ENDHDR + static final Path CEN_TOO_LARGE_ZIP = Path.of("cen-size-too-large.zip"); + static final Path INVALID_CEN_SIZE = Path.of("invalid-zen-size.zip"); + static final Path BAD_CEN_OFFSET_ZIP = Path.of("bad-cen-offset.zip"); + static final Path BAD_ENTRY_COUNT_ZIP = Path.of("bad-entry-count.zip"); + // Maximum allowed CEN size allowed by ZipFile - private static final int MAX_CEN_SIZE = ArraysSupport.SOFT_MAX_ARRAY_LENGTH; - - // Expected message when CEN size does not match file size - private static final String INVALID_CEN_BAD_SIZE = "invalid END header (bad central directory size)"; - // Expected message when CEN offset is too large - private static final String INVALID_CEN_BAD_OFFSET = "invalid END header (bad central directory offset)"; - // Expected message when CEN size is too large - private static final String INVALID_CEN_SIZE_TOO_LARGE = "invalid END header (central directory size too large)"; - // Expected message when total entry count is too large - private static final String INVALID_BAD_ENTRY_COUNT = "invalid END header (total entries count too large)"; - - // A valid ZIP file, used as a template - private byte[] zipBytes; - - /** - * Create a valid ZIP file, used as a template - * @throws IOException if an error occurs - */ - @BeforeEach - public void setup() throws IOException { - zipBytes = templateZip(); - } + static final int MAX_CEN_SIZE = ArraysSupport.SOFT_MAX_ARRAY_LENGTH; /** * Delete big files after test, in case the file system did not support sparse files. @@ -105,6 +75,7 @@ public class EndOfCenValidation { Files.deleteIfExists(CEN_TOO_LARGE_ZIP); Files.deleteIfExists(INVALID_CEN_SIZE); Files.deleteIfExists(BAD_CEN_OFFSET_ZIP); + Files.deleteIfExists(BAD_ENTRY_COUNT_ZIP); } /** @@ -115,14 +86,8 @@ public class EndOfCenValidation { @Test public void shouldRejectTooLargeCenSize() throws IOException { int size = MAX_CEN_SIZE + 1; - Path zip = zipWithModifiedEndRecord(size, true, 0, CEN_TOO_LARGE_ZIP); - - ZipException ex = assertThrows(ZipException.class, () -> { - new ZipFile(zip.toFile()); - }); - - assertEquals(INVALID_CEN_SIZE_TOO_LARGE, ex.getMessage()); + verifyRejection(zip, INVALID_CEN_SIZE_TOO_LARGE); } /** @@ -133,16 +98,9 @@ public class EndOfCenValidation { */ @Test public void shouldRejectInvalidCenSize() throws IOException { - int size = MAX_CEN_SIZE; - Path zip = zipWithModifiedEndRecord(size, false, 0, INVALID_CEN_SIZE); - - ZipException ex = assertThrows(ZipException.class, () -> { - new ZipFile(zip.toFile()); - }); - - assertEquals(INVALID_CEN_BAD_SIZE, ex.getMessage()); + verifyRejection(zip, INVALID_CEN_BAD_SIZE); } /** @@ -153,16 +111,9 @@ public class EndOfCenValidation { */ @Test public void shouldRejectInvalidCenOffset() throws IOException { - int size = MAX_CEN_SIZE; - Path zip = zipWithModifiedEndRecord(size, true, 100, BAD_CEN_OFFSET_ZIP); - - ZipException ex = assertThrows(ZipException.class, () -> { - new ZipFile(zip.toFile()); - }); - - assertEquals(INVALID_CEN_BAD_OFFSET, ex.getMessage()); + verifyRejection(zip, INVALID_CEN_BAD_OFFSET); } /** @@ -181,192 +132,20 @@ public class EndOfCenValidation { Long.MAX_VALUE // Unreasonably large }) public void shouldRejectBadTotalEntries(long totalEntries) throws IOException { - /** - * A small ZIP using the ZIP64 format. - * - * ZIP created using: "echo -n hello | zip zip64.zip -" - * Hex encoded using: "cat zip64.zip | xxd -ps" - * - * The file has the following structure: - * - * 0000 LOCAL HEADER #1 04034B50 - * 0004 Extract Zip Spec 2D '4.5' - * 0005 Extract OS 00 'MS-DOS' - * 0006 General Purpose Flag 0000 - * 0008 Compression Method 0000 'Stored' - * 000A Last Mod Time 5947AB78 'Mon Oct 7 21:27:48 2024' - * 000E CRC 363A3020 - * 0012 Compressed Length FFFFFFFF - * 0016 Uncompressed Length FFFFFFFF - * 001A Filename Length 0001 - * 001C Extra Length 0014 - * 001E Filename '-' - * 001F Extra ID #0001 0001 'ZIP64' - * 0021 Length 0010 - * 0023 Uncompressed Size 0000000000000006 - * 002B Compressed Size 0000000000000006 - * 0033 PAYLOAD hello. - * - * 0039 CENTRAL HEADER #1 02014B50 - * 003D Created Zip Spec 1E '3.0' - * 003E Created OS 03 'Unix' - * 003F Extract Zip Spec 2D '4.5' - * 0040 Extract OS 00 'MS-DOS' - * 0041 General Purpose Flag 0000 - * 0043 Compression Method 0000 'Stored' - * 0045 Last Mod Time 5947AB78 'Mon Oct 7 21:27:48 2024' - * 0049 CRC 363A3020 - * 004D Compressed Length 00000006 - * 0051 Uncompressed Length FFFFFFFF - * 0055 Filename Length 0001 - * 0057 Extra Length 000C - * 0059 Comment Length 0000 - * 005B Disk Start 0000 - * 005D Int File Attributes 0001 - * [Bit 0] 1 Text Data - * 005F Ext File Attributes 11B00000 - * 0063 Local Header Offset 00000000 - * 0067 Filename '-' - * 0068 Extra ID #0001 0001 'ZIP64' - * 006A Length 0008 - * 006C Uncompressed Size 0000000000000006 - * - * 0074 ZIP64 END CENTRAL DIR 06064B50 - * RECORD - * 0078 Size of record 000000000000002C - * 0080 Created Zip Spec 1E '3.0' - * 0081 Created OS 03 'Unix' - * 0082 Extract Zip Spec 2D '4.5' - * 0083 Extract OS 00 'MS-DOS' - * 0084 Number of this disk 00000000 - * 0088 Central Dir Disk no 00000000 - * 008C Entries in this disk 0000000000000001 - * 0094 Total Entries 0000000000000001 - * 009C Size of Central Dir 000000000000003B - * 00A4 Offset to Central dir 0000000000000039 - * - * 00AC ZIP64 END CENTRAL DIR 07064B50 - * LOCATOR - * 00B0 Central Dir Disk no 00000000 - * 00B4 Offset to Central dir 0000000000000074 - * 00BC Total no of Disks 00000001 - * - * 00C0 END CENTRAL HEADER 06054B50 - * 00C4 Number of this disk 0000 - * 00C6 Central Dir Disk no 0000 - * 00C8 Entries in this disk 0001 - * 00CA Total Entries 0001 - * 00CC Size of Central Dir 0000003B - * 00D0 Offset to Central Dir FFFFFFFF - * 00D4 Comment Length 0000 - */ + Path zip = zip64WithModifiedTotalEntries(BAD_ENTRY_COUNT_ZIP, totalEntries); + verifyRejection(zip, INVALID_BAD_ENTRY_COUNT); + } - byte[] zipBytes = HexFormat.of().parseHex(""" - 504b03042d000000000078ab475920303a36ffffffffffffffff01001400 - 2d010010000600000000000000060000000000000068656c6c6f0a504b01 - 021e032d000000000078ab475920303a3606000000ffffffff01000c0000 - 00000001000000b011000000002d010008000600000000000000504b0606 - 2c000000000000001e032d00000000000000000001000000000000000100 - 0000000000003b000000000000003900000000000000504b060700000000 - 740000000000000001000000504b050600000000010001003b000000ffff - ffff0000 - """.replaceAll("\n","")); - - // Buffer to manipulate the above ZIP - ByteBuffer buf = ByteBuffer.wrap(zipBytes).order(ByteOrder.LITTLE_ENDIAN); - // Offset of the 'total entries' in the 'ZIP64 END CENTRAL DIR' record - // Update ZIP64 entry count to a value which cannot possibly fit in the small CEN - buf.putLong(0x94, totalEntries); - // The corresponding END field needs the ZIP64 magic value - buf.putShort(0xCA, (short) 0xFFFF); - // Write the ZIP to disk - Path zipFile = Path.of("bad-entry-count.zip"); - Files.write(zipFile, zipBytes); - - // Verify that the END header is rejected + /** + * Verify that ZipFile rejects the ZIP file with a ZipException + * with the given message + * @param zip ZIP file to open + * @param msg exception message to expect + */ + private static void verifyRejection(Path zip, String msg) { ZipException ex = assertThrows(ZipException.class, () -> { - try (var zf = new ZipFile(zipFile.toFile())) { - } + new ZipFile(zip.toFile()); }); - - assertEquals(INVALID_BAD_ENTRY_COUNT, ex.getMessage()); - } - - /** - * Create an ZIP file with a single entry, then modify the CEN size - * in the 'End of central directory record' (END header) to the given size. - * - * The CEN is optionally "inflated" with trailing zero bytes such that - * its actual size matches the one stated in the END header. - * - * The CEN offset is optiontially adjusted by the given amount - * - * The resulting ZIP is technically not valid, but it does allow us - * to test that large or invalid CEN sizes are rejected - * @param cenSize the CEN size to put in the END record - * @param inflateCen if true, zero-pad the CEN to the desired size - * @param cenOffAdjust Adjust the CEN offset field of the END record with this amount - * @throws IOException if an error occurs - */ - private Path zipWithModifiedEndRecord(int cenSize, - boolean inflateCen, - int cenOffAdjust, - Path zip) throws IOException { - - // A byte buffer for reading the END - ByteBuffer buffer = ByteBuffer.wrap(zipBytes.clone()).order(ByteOrder.LITTLE_ENDIAN); - - // Offset of the END header - int endOffset = buffer.limit() - ENDHDR; - - // Modify the CEN size - int sizeOffset = endOffset + ENDSIZ; - int currentCenSize = buffer.getInt(sizeOffset); - buffer.putInt(sizeOffset, cenSize); - - // Optionally modify the CEN offset - if (cenOffAdjust != 0) { - int offOffset = endOffset + ENDOFF; - int currentCenOff = buffer.getInt(offOffset); - buffer.putInt(offOffset, currentCenOff + cenOffAdjust); - } - - // When creating a sparse file, the file must not already exit - Files.deleteIfExists(zip); - - // Open a FileChannel for writing a sparse file - EnumSet options = EnumSet.of(StandardOpenOption.CREATE_NEW, - StandardOpenOption.WRITE, - StandardOpenOption.SPARSE); - - try (FileChannel channel = FileChannel.open(zip, options)) { - - // Write everything up to END - channel.write(buffer.slice(0, buffer.limit() - ENDHDR)); - - if (inflateCen) { - // Inject "empty bytes" to make the actual CEN size match the END - int injectBytes = cenSize - currentCenSize; - channel.position(channel.position() + injectBytes); - } - // Write the modified END - channel.write(buffer.slice(buffer.limit() - ENDHDR, ENDHDR)); - } - return zip; - } - - /** - * Produce a byte array of a ZIP with a single entry - * - * @throws IOException if an error occurs - */ - private byte[] templateZip() throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - try (ZipOutputStream zo = new ZipOutputStream(bout)) { - ZipEntry entry = new ZipEntry("duke.txt"); - zo.putNextEntry(entry); - zo.write("duke".getBytes(StandardCharsets.UTF_8)); - } - return bout.toByteArray(); + assertEquals(msg, ex.getMessage()); } } diff --git a/test/jdk/jdk/nio/zipfs/EndOfCenValidation.java b/test/jdk/jdk/nio/zipfs/EndOfCenValidation.java new file mode 100644 index 00000000000..ed0bdbb52ea --- /dev/null +++ b/test/jdk/jdk/nio/zipfs/EndOfCenValidation.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2023, 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 + * @modules java.base/jdk.internal.util + * @summary Verify that ZipFileSystem rejects files with CEN sizes exceeding the implementation limit + * @library /test/lib + * @build jdk.test.lib.util.ZipUtils + * @run junit/othervm EndOfCenValidation + */ + +import jdk.internal.util.ArraysSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipException; + +import static jdk.test.lib.util.ZipUtils.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * This test augments {@link TestTooManyEntries}. It creates sparse ZIPs where + * the CEN size is inflated to the desired value. This helps this test run + * fast with much less resources. + * + * While the CEN in these files are zero-filled and the produced ZIPs are technically + * invalid, the CEN is never actually read by ZipFileSystem since it does + * 'End of central directory record' (END header) validation before reading the CEN. + */ +public class EndOfCenValidation { + + // Zip files produced by this test + static final Path CEN_TOO_LARGE_ZIP = Path.of("cen-size-too-large.zip"); + static final Path INVALID_CEN_SIZE = Path.of("invalid-zen-size.zip"); + static final Path BAD_CEN_OFFSET_ZIP = Path.of("bad-cen-offset.zip"); + static final Path BAD_ENTRY_COUNT_ZIP = Path.of("bad-entry-count.zip"); + + // Maximum allowed CEN size allowed by ZipFileSystem + static final int MAX_CEN_SIZE = ArraysSupport.SOFT_MAX_ARRAY_LENGTH; + + /** + * Delete big files after test, in case the file system did not support sparse files. + * @throws IOException if an error occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(CEN_TOO_LARGE_ZIP); + Files.deleteIfExists(INVALID_CEN_SIZE); + Files.deleteIfExists(BAD_CEN_OFFSET_ZIP); + Files.deleteIfExists(BAD_ENTRY_COUNT_ZIP); + } + + /** + * Validates that an 'End of central directory record' (END header) with a CEN + * length exceeding {@link #MAX_CEN_SIZE} limit is rejected + * @throws IOException if an error occurs + */ + @Test + public void shouldRejectTooLargeCenSize() throws IOException { + int size = MAX_CEN_SIZE + 1; + Path zip = zipWithModifiedEndRecord(size, true, 0, CEN_TOO_LARGE_ZIP); + verifyRejection(zip, INVALID_CEN_SIZE_TOO_LARGE); + } + + /** + * Validate that an 'End of central directory record' (END header) + * where the value of the CEN size field exceeds the position of + * the END header is rejected. + * @throws IOException if an error occurs + */ + @Test + public void shouldRejectInvalidCenSize() throws IOException { + int size = MAX_CEN_SIZE; + Path zip = zipWithModifiedEndRecord(size, false, 0, INVALID_CEN_SIZE); + verifyRejection(zip, INVALID_CEN_BAD_SIZE); + } + + /** + * Validate that an 'End of central directory record' (the END header) + * where the value of the CEN offset field is larger than the position + * of the END header minus the CEN size is rejected + * @throws IOException if an error occurs + */ + @Test + public void shouldRejectInvalidCenOffset() throws IOException { + int size = MAX_CEN_SIZE; + Path zip = zipWithModifiedEndRecord(size, true, 100, BAD_CEN_OFFSET_ZIP); + verifyRejection(zip, INVALID_CEN_BAD_OFFSET); + } + + /** + * Validate that a 'Zip64 End of Central Directory' record (the END header) + * where the value of the 'total entries' field is larger than what fits + * in the CEN size is rejected. + * + * @throws IOException if an error occurs + */ + @ParameterizedTest + @ValueSource(longs = { + -1, // Negative + Long.MIN_VALUE, // Very negative + 0x3B / 3L - 1, // Cannot fit in test ZIP's CEN + MAX_CEN_SIZE / 3 + 1, // Too large to allocate int[] entries array + Long.MAX_VALUE // Unreasonably large + }) + public void shouldRejectBadTotalEntries(long totalEntries) throws IOException { + Path zip = zip64WithModifiedTotalEntries(BAD_ENTRY_COUNT_ZIP, totalEntries); + verifyRejection(zip, INVALID_BAD_ENTRY_COUNT); + } + + /** + * Verify that ZipFileSystem.newFileSystem rejects the ZIP file with a ZipException + * with the given message + * @param zip ZIP file to open + * @param msg exception message to expect + */ + private static void verifyRejection(Path zip, String msg) { + ZipException ex = assertThrows(ZipException.class, () -> { + FileSystems.newFileSystem(zip); + }); + assertEquals(msg, ex.getMessage()); + } +} diff --git a/test/lib/jdk/test/lib/util/ZipUtils.java b/test/lib/jdk/test/lib/util/ZipUtils.java new file mode 100644 index 00000000000..a1568e51cc1 --- /dev/null +++ b/test/lib/jdk/test/lib/util/ZipUtils.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2023, 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 jdk.test.lib.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +/** + * This class consists exclusively of static utility methods that are useful + * for creating and manipulating ZIP files. + */ +public final class ZipUtils { + // Some ZipFile constants for manipulating the 'End of central directory record' (END header) + private static final int ENDHDR = ZipFile.ENDHDR; // End of central directory record size + private static final int ENDSIZ = ZipFile.ENDSIZ; // Offset of CEN size field within ENDHDR + private static final int ENDOFF = ZipFile.ENDOFF; // Offset of CEN offset field within ENDHDR + // Expected message when CEN size does not match file size + public static final String INVALID_CEN_BAD_SIZE = "invalid END header (bad central directory size)"; + // Expected message when CEN offset is too large + public static final String INVALID_CEN_BAD_OFFSET = "invalid END header (bad central directory offset)"; + // Expected message when CEN size is too large + public static final String INVALID_CEN_SIZE_TOO_LARGE = "invalid END header (central directory size too large)"; + // Expected message when total entry count is too large + public static final String INVALID_BAD_ENTRY_COUNT = "invalid END header (total entries count too large)"; + + private ZipUtils() { } + + /** + * Create an ZIP file with a single entry, then modify the CEN size + * in the 'End of central directory record' (END header) to the given size. + * + * The CEN is optionally "inflated" with trailing zero bytes such that + * its actual size matches the one stated in the END header. + * + * The CEN offset is optiontially adjusted by the given amount + * + * The resulting ZIP is technically not valid, but it does allow us + * to test that large or invalid CEN sizes are rejected + * @param cenSize the CEN size to put in the END record + * @param inflateCen if true, zero-pad the CEN to the desired size + * @param cenOffAdjust Adjust the CEN offset field of the END record with this amount + * @throws IOException if an error occurs + */ + public static Path zipWithModifiedEndRecord(int cenSize, + boolean inflateCen, + int cenOffAdjust, + Path zip) throws IOException { + // A byte buffer for reading the END + ByteBuffer buffer = ByteBuffer.wrap(templateZip()).order(ByteOrder.LITTLE_ENDIAN); + + // Offset of the END header + int endOffset = buffer.limit() - ENDHDR; + + // Modify the CEN size + int sizeOffset = endOffset + ENDSIZ; + int currentCenSize = buffer.getInt(sizeOffset); + buffer.putInt(sizeOffset, cenSize); + + // Optionally modify the CEN offset + if (cenOffAdjust != 0) { + int offOffset = endOffset + ENDOFF; + int currentCenOff = buffer.getInt(offOffset); + buffer.putInt(offOffset, currentCenOff + cenOffAdjust); + } + // When creating a sparse file, the file must not already exit + Files.deleteIfExists(zip); + + // Open a FileChannel for writing a sparse file + EnumSet options = EnumSet.of(StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, + StandardOpenOption.SPARSE); + + try (FileChannel channel = FileChannel.open(zip, options)) { + // Write everything up to END + channel.write(buffer.slice(0, buffer.limit() - ENDHDR)); + if (inflateCen) { + // Inject "empty bytes" to make the actual CEN size match the END + int injectBytes = cenSize - currentCenSize; + channel.position(channel.position() + injectBytes); + } + // Write the modified END + channel.write(buffer.slice(buffer.limit() - ENDHDR, ENDHDR)); + } + return zip; + } + + /** + * Create a small Zip64 ZIP file, then modify the Zip64 END header + * with a possibly very large total entry count + * + * @param zip file to write to + * @param totalEntries the number of entries wanted in the Zip64 END header + * @return the modified ZIP file + * @throws IOException if an unexpeced IO error occurs + */ + public static Path zip64WithModifiedTotalEntries(Path zip, long totalEntries) throws IOException { + /** + * A small ZIP using the ZIP64 format. + * + * ZIP created using: "echo -n hello | zip zip64.zip -" + * Hex encoded using: "cat zip64.zip | xxd -ps" + * + * The file has the following structure: + * + * 0000 LOCAL HEADER #1 04034B50 + * 0004 Extract Zip Spec 2D '4.5' + * 0005 Extract OS 00 'MS-DOS' + * 0006 General Purpose Flag 0000 + * 0008 Compression Method 0000 'Stored' + * 000A Last Mod Time 5947AB78 'Mon Oct 7 21:27:48 2024' + * 000E CRC 363A3020 + * 0012 Compressed Length FFFFFFFF + * 0016 Uncompressed Length FFFFFFFF + * 001A Filename Length 0001 + * 001C Extra Length 0014 + * 001E Filename '-' + * 001F Extra ID #0001 0001 'ZIP64' + * 0021 Length 0010 + * 0023 Uncompressed Size 0000000000000006 + * 002B Compressed Size 0000000000000006 + * 0033 PAYLOAD hello. + * + * 0039 CENTRAL HEADER #1 02014B50 + * 003D Created Zip Spec 1E '3.0' + * 003E Created OS 03 'Unix' + * 003F Extract Zip Spec 2D '4.5' + * 0040 Extract OS 00 'MS-DOS' + * 0041 General Purpose Flag 0000 + * 0043 Compression Method 0000 'Stored' + * 0045 Last Mod Time 5947AB78 'Mon Oct 7 21:27:48 2024' + * 0049 CRC 363A3020 + * 004D Compressed Length 00000006 + * 0051 Uncompressed Length FFFFFFFF + * 0055 Filename Length 0001 + * 0057 Extra Length 000C + * 0059 Comment Length 0000 + * 005B Disk Start 0000 + * 005D Int File Attributes 0001 + * [Bit 0] 1 Text Data + * 005F Ext File Attributes 11B00000 + * 0063 Local Header Offset 00000000 + * 0067 Filename '-' + * 0068 Extra ID #0001 0001 'ZIP64' + * 006A Length 0008 + * 006C Uncompressed Size 0000000000000006 + * + * 0074 ZIP64 END CENTRAL DIR 06064B50 + * RECORD + * 0078 Size of record 000000000000002C + * 0080 Created Zip Spec 1E '3.0' + * 0081 Created OS 03 'Unix' + * 0082 Extract Zip Spec 2D '4.5' + * 0083 Extract OS 00 'MS-DOS' + * 0084 Number of this disk 00000000 + * 0088 Central Dir Disk no 00000000 + * 008C Entries in this disk 0000000000000001 + * 0094 Total Entries 0000000000000001 + * 009C Size of Central Dir 000000000000003B + * 00A4 Offset to Central dir 0000000000000039 + * + * 00AC ZIP64 END CENTRAL DIR 07064B50 + * LOCATOR + * 00B0 Central Dir Disk no 00000000 + * 00B4 Offset to Central dir 0000000000000074 + * 00BC Total no of Disks 00000001 + * + * 00C0 END CENTRAL HEADER 06054B50 + * 00C4 Number of this disk 0000 + * 00C6 Central Dir Disk no 0000 + * 00C8 Entries in this disk 0001 + * 00CA Total Entries 0001 + * 00CC Size of Central Dir 0000003B + * 00D0 Offset to Central Dir FFFFFFFF + * 00D4 Comment Length 0000 + */ + + byte[] zipBytes = HexFormat.of().parseHex(""" + 504b03042d000000000078ab475920303a36ffffffffffffffff01001400 + 2d010010000600000000000000060000000000000068656c6c6f0a504b01 + 021e032d000000000078ab475920303a3606000000ffffffff01000c0000 + 00000001000000b011000000002d010008000600000000000000504b0606 + 2c000000000000001e032d00000000000000000001000000000000000100 + 0000000000003b000000000000003900000000000000504b060700000000 + 740000000000000001000000504b050600000000010001003b000000ffff + ffff0000 + """.replaceAll("\n","")); + + // Buffer to manipulate the above ZIP + ByteBuffer buf = ByteBuffer.wrap(zipBytes).order(ByteOrder.LITTLE_ENDIAN); + // Offset of the 'total entries' in the 'ZIP64 END CENTRAL DIR' record + // Update ZIP64 entry count to a value which cannot possibly fit in the small CEN + buf.putLong(0x94, totalEntries); + // The corresponding END field needs the ZIP64 magic value + buf.putShort(0xCA, (short) 0xFFFF); + // Write the ZIP to disk + Files.write(zip, zipBytes); + return zip; + } + + /** + * Produce a byte array of a ZIP with a single entry + * + * @throws IOException if an error occurs + */ + private static byte[] templateZip() throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try (ZipOutputStream zo = new ZipOutputStream(bout)) { + ZipEntry entry = new ZipEntry("duke.txt"); + zo.putNextEntry(entry); + zo.write("duke".getBytes(StandardCharsets.UTF_8)); + } + return bout.toByteArray(); + } +}